RecipientEditTextView.java revision c0a34aba4889151d822dd1ac0ae8b722cf5edebb
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            } else if (mSelectedChip != null
1049                    && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1050                chipWasSelected = true;
1051            }
1052        }
1053        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1054            clearSelectedChip();
1055        }
1056        return handled;
1057    }
1058
1059    private void scrollLineIntoView(int line) {
1060        if (mScrollView != null) {
1061            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1062        }
1063    }
1064
1065    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1066            int width, Context context) {
1067        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1068        int bottom = calculateOffsetFromBottom(line);
1069        // Align the alternates popup with the left side of the View,
1070        // regardless of the position of the chip tapped.
1071        alternatesPopup.setWidth(width);
1072        setEnabled(false);
1073        alternatesPopup.setAnchorView(this);
1074        alternatesPopup.setVerticalOffset(bottom);
1075        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1076        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1077        // Clear the checked item.
1078        mCheckedItem = -1;
1079        alternatesPopup.show();
1080        ListView listView = alternatesPopup.getListView();
1081        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1082        // Checked item would be -1 if the adapter has not
1083        // loaded the view that should be checked yet. The
1084        // variable will be set correctly when onCheckedItemChanged
1085        // is called in a separate thread.
1086        if (mCheckedItem != -1) {
1087            listView.setItemChecked(mCheckedItem, true);
1088            mCheckedItem = -1;
1089        }
1090    }
1091
1092    // Dismiss listener for alterns and single address popup.
1093    @Override
1094    public void onDismiss() {
1095        setEnabled(true);
1096    }
1097
1098    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1099        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1100                mAlternatesLayout, this);
1101    }
1102
1103    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1104        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1105                .getEntry());
1106    }
1107
1108    @Override
1109    public void onCheckedItemChanged(int position) {
1110        ListView listView = mAlternatesPopup.getListView();
1111        if (listView != null && listView.getCheckedItemCount() == 0) {
1112            listView.setItemChecked(position, true);
1113        }
1114        mCheckedItem = position;
1115    }
1116
1117    // TODO: This algorithm will need a lot of tweaking after more people have used
1118    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1119    // what comes before the finger.
1120    private int putOffsetInRange(int o) {
1121        int offset = o;
1122        Editable text = getText();
1123        int length = text.length();
1124        // Remove whitespace from end to find "real end"
1125        int realLength = length;
1126        for (int i = length - 1; i >= 0; i--) {
1127            if (text.charAt(i) == ' ') {
1128                realLength--;
1129            } else {
1130                break;
1131            }
1132        }
1133
1134        // If the offset is beyond or at the end of the text,
1135        // leave it alone.
1136        if (offset >= realLength) {
1137            return offset;
1138        }
1139        Editable editable = getText();
1140        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1141            // Keep walking backward!
1142            offset--;
1143        }
1144        return offset;
1145    }
1146
1147    private int findText(Editable text, int offset) {
1148        if (text.charAt(offset) != ' ') {
1149            return offset;
1150        }
1151        return -1;
1152    }
1153
1154    private RecipientChip findChip(int offset) {
1155        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1156        // Find the chip that contains this offset.
1157        for (int i = 0; i < chips.length; i++) {
1158            RecipientChip chip = chips[i];
1159            int start = getChipStart(chip);
1160            int end = getChipEnd(chip);
1161            if (offset >= start && offset <= end) {
1162                return chip;
1163            }
1164        }
1165        return null;
1166    }
1167
1168    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1169        String displayText = entry.getDestination();
1170        displayText = (String) mTokenizer.terminateToken(displayText);
1171        // Always leave a blank space at the end of a chip.
1172        int textLength = displayText.length()-1;
1173        SpannableString chipText = new SpannableString(displayText);
1174        int end = getSelectionEnd();
1175        int start = mTokenizer.findTokenStart(getText(), end);
1176        try {
1177            RecipientChip chip = constructChipSpan(entry, start, pressed);
1178            chipText.setSpan(chip, 0, textLength,
1179                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1180            chip.setOriginalText(chipText.toString());
1181        } catch (NullPointerException e) {
1182            Log.e(TAG, e.getMessage(), e);
1183            return null;
1184        }
1185
1186        return chipText;
1187    }
1188
1189    /**
1190     * When an item in the suggestions list has been clicked, create a chip from the
1191     * contact information of the selected item.
1192     */
1193    @Override
1194    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1195        submitItemAtPosition(position);
1196    }
1197
1198    private void submitItemAtPosition(int position) {
1199        RecipientEntry entry = createValidatedEntry(
1200                (RecipientEntry)getAdapter().getItem(position));
1201        if (entry == null) {
1202            return;
1203        }
1204        clearComposingText();
1205
1206        int end = getSelectionEnd();
1207        int start = mTokenizer.findTokenStart(getText(), end);
1208
1209        Editable editable = getText();
1210        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1211        CharSequence chip = createChip(entry, false);
1212        if (chip != null) {
1213            editable.replace(start, end, chip);
1214        }
1215    }
1216
1217    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1218        if (item == null) {
1219            return null;
1220        }
1221        final RecipientEntry entry;
1222        // If the display name and the address are the same, or if this is a
1223        // valid contact, but the destination is invalid, then make this a fake
1224        // recipient that is editable.
1225        String destination = item.getDestination();
1226        if (TextUtils.isEmpty(item.getDisplayName())
1227                || TextUtils.equals(item.getDisplayName(), destination)
1228                || (mValidator != null && !mValidator.isValid(destination))) {
1229            entry = RecipientEntry.constructFakeEntry(destination);
1230        } else {
1231            entry = item;
1232        }
1233        return entry;
1234    }
1235
1236    /** Returns a collection of contact Id for each chip inside this View. */
1237    /* package */ Collection<Long> getContactIds() {
1238        final Set<Long> result = new HashSet<Long>();
1239        RecipientChip[] chips = getRecipients();
1240        if (chips != null) {
1241            for (RecipientChip chip : chips) {
1242                result.add(chip.getContactId());
1243            }
1244        }
1245        return result;
1246    }
1247
1248    private RecipientChip[] getRecipients() {
1249        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1250    }
1251
1252    private RecipientChip[] getSortedRecipients() {
1253        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1254                .asList(getRecipients()));
1255        final Spannable spannable = getSpannable();
1256        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1257
1258            @Override
1259            public int compare(RecipientChip first, RecipientChip second) {
1260                int firstStart = spannable.getSpanStart(first);
1261                int secondStart = spannable.getSpanStart(second);
1262                if (firstStart < secondStart) {
1263                    return -1;
1264                } else if (firstStart > secondStart) {
1265                    return 1;
1266                } else {
1267                    return 0;
1268                }
1269            }
1270        });
1271        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1272    }
1273
1274    /** Returns a collection of data Id for each chip inside this View. May be null. */
1275    /* package */ Collection<Long> getDataIds() {
1276        final Set<Long> result = new HashSet<Long>();
1277        RecipientChip [] chips = getRecipients();
1278        if (chips != null) {
1279            for (RecipientChip chip : chips) {
1280                result.add(chip.getDataId());
1281            }
1282        }
1283        return result;
1284    }
1285
1286
1287    @Override
1288    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1289        return false;
1290    }
1291
1292    @Override
1293    public void onDestroyActionMode(ActionMode mode) {
1294    }
1295
1296    @Override
1297    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1298        return false;
1299    }
1300
1301    /**
1302     * No chips are selectable.
1303     */
1304    @Override
1305    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1306        return false;
1307    }
1308
1309    /**
1310     * Create the more chip. The more chip is text that replaces any chips that
1311     * do not fit in the pre-defined available space when the
1312     * RecipientEditTextView loses focus.
1313     */
1314    private void createMoreChip() {
1315        if (!mShouldShrink) {
1316            return;
1317        }
1318
1319        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1320        if (tempMore.length > 0) {
1321            getSpannable().removeSpan(tempMore[0]);
1322        }
1323        RecipientChip[] recipients = getSortedRecipients();
1324        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1325            mMoreChip = null;
1326            return;
1327        }
1328        Spannable spannable = getSpannable();
1329        int numRecipients = recipients.length;
1330        int overage = numRecipients - CHIP_LIMIT;
1331        String moreText = String.format(mMoreItem.getText().toString(), overage);
1332        TextPaint morePaint = new TextPaint(getPaint());
1333        morePaint.setTextSize(mMoreItem.getTextSize());
1334        morePaint.setColor(mMoreItem.getCurrentTextColor());
1335        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1336                + mMoreItem.getPaddingRight();
1337        int height = getLineHeight();
1338        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1339        Canvas canvas = new Canvas(drawable);
1340        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
1341                morePaint);
1342
1343        Drawable result = new BitmapDrawable(getResources(), drawable);
1344        result.setBounds(0, 0, width, height);
1345        MoreImageSpan moreSpan = new MoreImageSpan(result);
1346        // Remove the overage chips.
1347        if (recipients == null || recipients.length == 0) {
1348            Log.w(TAG,
1349                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1350            mMoreChip = null;
1351            return;
1352        }
1353        mRemovedSpans = new ArrayList<RecipientChip>();
1354        int totalReplaceStart = 0;
1355        int totalReplaceEnd = 0;
1356        Editable text = getText();
1357        for (int i = numRecipients - overage; i < recipients.length; i++) {
1358            mRemovedSpans.add(recipients[i]);
1359            if (i == numRecipients - overage) {
1360                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1361            }
1362            if (i == recipients.length - 1) {
1363                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1364            }
1365            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1366                int spanStart = spannable.getSpanStart(recipients[i]);
1367                int spanEnd = spannable.getSpanEnd(recipients[i]);
1368                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1369            }
1370            spannable.removeSpan(recipients[i]);
1371        }
1372        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1373        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1374        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1375        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1376        text.replace(start, end, chipText);
1377        mMoreChip = moreSpan;
1378    }
1379
1380    /**
1381     * Replace the more chip, if it exists, with all of the recipient chips it had
1382     * replaced when the RecipientEditTextView gains focus.
1383     */
1384    private void removeMoreChip() {
1385        if (mMoreChip != null) {
1386            Spannable span = getSpannable();
1387            span.removeSpan(mMoreChip);
1388            mMoreChip = null;
1389            // Re-add the spans that were removed.
1390            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1391                // Recreate each removed span.
1392                RecipientChip[] recipients = getRecipients();
1393                // Start the search for tokens after the last currently visible
1394                // chip.
1395                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1396                Editable editable = getText();
1397                for (RecipientChip chip : mRemovedSpans) {
1398                    int chipStart;
1399                    int chipEnd;
1400                    String token;
1401                    // Need to find the location of the chip, again.
1402                    token = (String) chip.getOriginalText();
1403                    // As we find the matching recipient for the remove spans,
1404                    // reduce the size of the string we need to search.
1405                    // That way, if there are duplicates, we always find the correct
1406                    // recipient.
1407                    chipStart = editable.toString().indexOf(token, end);
1408                    // -1 for the space!
1409                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1410                    // Only set the span if we found a matching token.
1411                    if (chipStart != -1) {
1412                        editable.setSpan(chip, chipStart, chipEnd,
1413                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1414                    }
1415                }
1416                mRemovedSpans.clear();
1417            }
1418        }
1419    }
1420
1421    /**
1422     * Show specified chip as selected. If the RecipientChip is just an email address,
1423     * selecting the chip will take the contents of the chip and place it at
1424     * the end of the RecipientEditTextView for inline editing. If the
1425     * RecipientChip is a complete contact, then selecting the chip
1426     * will change the background color of the chip, show the delete icon,
1427     * and a popup window with the address in use highlighted and any other
1428     * alternate addresses for the contact.
1429     * @param currentChip Chip to select.
1430     * @return A RecipientChip in the selected state or null if the chip
1431     * just contained an email address.
1432     */
1433    public RecipientChip selectChip(RecipientChip currentChip) {
1434        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1435            CharSequence text = currentChip.getValue();
1436            Editable editable = getText();
1437            removeChip(currentChip);
1438            editable.append(text);
1439            setCursorVisible(true);
1440            setSelection(editable.length());
1441            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1442        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1443            int start = getChipStart(currentChip);
1444            int end = getChipEnd(currentChip);
1445            getSpannable().removeSpan(currentChip);
1446            RecipientChip newChip;
1447            try {
1448                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1449            } catch (NullPointerException e) {
1450                Log.e(TAG, e.getMessage(), e);
1451                return null;
1452            }
1453            Editable editable = getText();
1454            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1455            if (start == -1 || end == -1) {
1456                Log.d(TAG, "The chip being selected no longer exists but should.");
1457            } else {
1458                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1459            }
1460            newChip.setSelected(true);
1461            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1462                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1463            }
1464            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1465            setCursorVisible(false);
1466            return newChip;
1467        } else {
1468            int start = getChipStart(currentChip);
1469            int end = getChipEnd(currentChip);
1470            getSpannable().removeSpan(currentChip);
1471            RecipientChip newChip;
1472            try {
1473                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1474            } catch (NullPointerException e) {
1475                Log.e(TAG, e.getMessage(), e);
1476                return null;
1477            }
1478            Editable editable = getText();
1479            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1480            if (start == -1 || end == -1) {
1481                Log.d(TAG, "The chip being selected no longer exists but should.");
1482            } else {
1483                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1484            }
1485            newChip.setSelected(true);
1486            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1487                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1488            }
1489            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1490            setCursorVisible(false);
1491            return newChip;
1492        }
1493    }
1494
1495
1496    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1497            int width, Context context) {
1498        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1499        int bottom = calculateOffsetFromBottom(line);
1500        // Align the alternates popup with the left side of the View,
1501        // regardless of the position of the chip tapped.
1502        setEnabled(false);
1503        popup.setWidth(width);
1504        popup.setAnchorView(this);
1505        popup.setVerticalOffset(bottom);
1506        popup.setAdapter(createSingleAddressAdapter(currentChip));
1507        popup.setOnItemClickListener(new OnItemClickListener() {
1508            @Override
1509            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1510                unselectChip(currentChip);
1511                popup.dismiss();
1512            }
1513        });
1514        popup.show();
1515        ListView listView = popup.getListView();
1516        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1517        listView.setItemChecked(0, true);
1518    }
1519
1520    /**
1521     * Remove selection from this chip. Unselecting a RecipientChip will render
1522     * the chip without a delete icon and with an unfocused background. This
1523     * is called when the RecipientChip no longer has focus.
1524     */
1525    public void unselectChip(RecipientChip chip) {
1526        int start = getChipStart(chip);
1527        int end = getChipEnd(chip);
1528        Editable editable = getText();
1529        mSelectedChip = null;
1530        if (start == -1 || end == -1) {
1531            Log.w(TAG,
1532                    "The chip doesn't exist or may be a chip a user was editing");
1533            setSelection(editable.length());
1534            commitDefault();
1535        } else {
1536            getSpannable().removeSpan(chip);
1537            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1538            editable.removeSpan(chip);
1539            try {
1540                editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1541                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1542            } catch (NullPointerException e) {
1543                Log.e(TAG, e.getMessage(), e);
1544            }
1545        }
1546        setCursorVisible(true);
1547        setSelection(editable.length());
1548        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1549            mAlternatesPopup.dismiss();
1550        }
1551    }
1552
1553    /**
1554     * Return whether this chip contains the position passed in.
1555     */
1556    public boolean matchesChip(RecipientChip chip, int offset) {
1557        int start = getChipStart(chip);
1558        int end = getChipEnd(chip);
1559        if (start == -1 || end == -1) {
1560            return false;
1561        }
1562        return (offset >= start && offset <= end);
1563    }
1564
1565
1566    /**
1567     * Return whether a touch event was inside the delete target of
1568     * a selected chip. It is in the delete target if:
1569     * 1) the x and y points of the event are within the
1570     * delete assset.
1571     * 2) the point tapped would have caused a cursor to appear
1572     * right after the selected chip.
1573     * @return boolean
1574     */
1575    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1576        // Figure out the bounds of this chip and whether or not
1577        // the user clicked in the X portion.
1578        return chip.isSelected() && offset == getChipEnd(chip);
1579    }
1580
1581    /**
1582     * Remove the chip and any text associated with it from the RecipientEditTextView.
1583     */
1584    private void removeChip(RecipientChip chip) {
1585        Spannable spannable = getSpannable();
1586        int spanStart = spannable.getSpanStart(chip);
1587        int spanEnd = spannable.getSpanEnd(chip);
1588        Editable text = getText();
1589        int toDelete = spanEnd;
1590        boolean wasSelected = chip == mSelectedChip;
1591        // Clear that there is a selected chip before updating any text.
1592        if (wasSelected) {
1593            mSelectedChip = null;
1594        }
1595        // Always remove trailing spaces when removing a chip.
1596        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1597            toDelete++;
1598        }
1599        spannable.removeSpan(chip);
1600        text.delete(spanStart, toDelete);
1601        if (wasSelected) {
1602            clearSelectedChip();
1603        }
1604    }
1605
1606    /**
1607     * Replace this currently selected chip with a new chip
1608     * that uses the contact data provided.
1609     */
1610    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1611        boolean wasSelected = chip == mSelectedChip;
1612        if (wasSelected) {
1613            mSelectedChip = null;
1614        }
1615        int start = getChipStart(chip);
1616        int end = getChipEnd(chip);
1617        getSpannable().removeSpan(chip);
1618        Editable editable = getText();
1619        CharSequence chipText = createChip(entry, false);
1620        if (start == -1 || end == -1) {
1621            Log.e(TAG, "The chip to replace does not exist but should.");
1622            editable.insert(0, chipText);
1623        } else {
1624            // There may be a space to replace with this chip's new associated
1625            // space. Check for it.
1626            int toReplace = end;
1627            while (toReplace >= 0 && toReplace < editable.length()
1628                    && editable.charAt(toReplace) == ' ') {
1629                toReplace++;
1630            }
1631            editable.replace(start, toReplace, chipText);
1632        }
1633        setCursorVisible(true);
1634        if (wasSelected) {
1635            clearSelectedChip();
1636        }
1637    }
1638
1639    /**
1640     * Handle click events for a chip. When a selected chip receives a click
1641     * event, see if that event was in the delete icon. If so, delete it.
1642     * Otherwise, unselect the chip.
1643     */
1644    public void onClick(RecipientChip chip, int offset, float x, float y) {
1645        if (chip.isSelected()) {
1646            if (isInDelete(chip, offset, x, y)) {
1647                removeChip(chip);
1648            } else {
1649                clearSelectedChip();
1650            }
1651        }
1652    }
1653
1654    private boolean chipsPending() {
1655        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1656    }
1657
1658    @Override
1659    public void removeTextChangedListener(TextWatcher watcher) {
1660        mTextWatcher = null;
1661        super.removeTextChangedListener(watcher);
1662    }
1663
1664    private class RecipientTextWatcher implements TextWatcher {
1665        @Override
1666        public void afterTextChanged(Editable s) {
1667            // If the text has been set to null or empty, make sure we remove
1668            // all the spans we applied.
1669            if (TextUtils.isEmpty(s)) {
1670                // Remove all the chips spans.
1671                Spannable spannable = getSpannable();
1672                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1673                        RecipientChip.class);
1674                for (RecipientChip chip : chips) {
1675                    spannable.removeSpan(chip);
1676                }
1677                if (mMoreChip != null) {
1678                    spannable.removeSpan(mMoreChip);
1679                }
1680                return;
1681            }
1682            // Get whether there are any recipients pending addition to the
1683            // view. If there are, don't do anything in the text watcher.
1684            if (chipsPending()) {
1685                return;
1686            }
1687            // If the user is editing a chip, don't clear it.
1688            if (mSelectedChip != null
1689                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
1690                setCursorVisible(true);
1691                setSelection(getText().length());
1692                clearSelectedChip();
1693            }
1694            int length = s.length();
1695            // Make sure there is content there to parse and that it is
1696            // not just the commit character.
1697            if (length > 1) {
1698                char last;
1699                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1700                int len = length() - 1;
1701                if (end != len) {
1702                    last = s.charAt(end);
1703                } else {
1704                    last = s.charAt(len);
1705                }
1706                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1707                    commitByCharacter();
1708                } else if (last == COMMIT_CHAR_SPACE) {
1709                    // Check if this is a valid email address. If it is,
1710                    // commit it.
1711                    String text = getText().toString();
1712                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1713                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1714                            tokenStart));
1715                    if (mValidator != null && mValidator.isValid(sub)) {
1716                        commitByCharacter();
1717                    }
1718                }
1719            }
1720        }
1721
1722        @Override
1723        public void onTextChanged(CharSequence s, int start, int before, int count) {
1724            // Do nothing.
1725        }
1726
1727        @Override
1728        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1729        }
1730    }
1731
1732    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1733        private RecipientChip createFreeChip(RecipientEntry entry) {
1734            String displayText = entry.getDestination();
1735            if (displayText.indexOf(",") == -1) {
1736                displayText = (String) mTokenizer.terminateToken(displayText);
1737            }
1738            try {
1739                return constructChipSpan(entry, -1, false);
1740            } catch (NullPointerException e) {
1741                Log.e(TAG, e.getMessage(), e);
1742                return null;
1743            }
1744        }
1745
1746        @Override
1747        protected Void doInBackground(Void... params) {
1748            if (mIndividualReplacements != null) {
1749                mIndividualReplacements.cancel(true);
1750            }
1751            // For each chip in the list, look up the matching contact.
1752            // If there is a match, replace that chip with the matching
1753            // chip.
1754            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1755            RecipientChip[] existingChips = getSortedRecipients();
1756            for (int i = 0; i < existingChips.length; i++) {
1757                originalRecipients.add(existingChips[i]);
1758            }
1759            if (mRemovedSpans != null) {
1760                originalRecipients.addAll(mRemovedSpans);
1761            }
1762            String[] addresses = new String[originalRecipients.size()];
1763            for (int i = 0; i < originalRecipients.size(); i++) {
1764                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1765            }
1766            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1767                    .getMatchingRecipients(getContext(), addresses);
1768            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1769            for (final RecipientChip temp : originalRecipients) {
1770                RecipientEntry entry = null;
1771                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1772                        && getSpannable().getSpanStart(temp) != -1) {
1773                    // Replace this.
1774                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
1775                            .getDestination())));
1776                }
1777                if (entry != null) {
1778                    replacements.add(createFreeChip(entry));
1779                } else {
1780                    replacements.add(temp);
1781                }
1782            }
1783            if (replacements != null && replacements.size() > 0) {
1784                mHandler.post(new Runnable() {
1785                    @Override
1786                    public void run() {
1787                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1788                                .toString());
1789                        Editable oldText = getText();
1790                        int start, end;
1791                        int i = 0;
1792                        for (RecipientChip chip : originalRecipients) {
1793                            start = oldText.getSpanStart(chip);
1794                            if (start != -1) {
1795                                end = oldText.getSpanEnd(chip);
1796                                text.removeSpan(chip);
1797                                // Leave a spot for the space!
1798                                RecipientChip replacement = replacements.get(i);
1799                                text.setSpan(replacement, start, end,
1800                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1801                                replacement.setOriginalText(text.toString().substring(start, end));
1802                            }
1803                            i++;
1804                        }
1805                        Editable editable = getText();
1806                        editable.clear();
1807                        editable.insert(0, text);
1808                        originalRecipients.clear();
1809                    }
1810                });
1811            }
1812            return null;
1813        }
1814    }
1815
1816    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1817        @SuppressWarnings("unchecked")
1818        @Override
1819        protected Void doInBackground(Object... params) {
1820            // For each chip in the list, look up the matching contact.
1821            // If there is a match, replace that chip with the matching
1822            // chip.
1823            final ArrayList<RecipientChip> originalRecipients =
1824                (ArrayList<RecipientChip>) params[0];
1825            String[] addresses = new String[originalRecipients.size()];
1826            for (int i = 0; i < originalRecipients.size(); i++) {
1827                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1828            }
1829            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1830                    .getMatchingRecipients(getContext(), addresses);
1831            for (final RecipientChip temp : originalRecipients) {
1832                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1833                        && getSpannable().getSpanStart(temp) != -1) {
1834                    // Replace this.
1835                    final RecipientEntry entry = createValidatedEntry(entries
1836                            .get(tokenizeAddress(temp.getEntry().getDestination())));
1837                    if (entry != null) {
1838                        mHandler.post(new Runnable() {
1839                            @Override
1840                            public void run() {
1841                                replaceChip(temp, entry);
1842                            }
1843                        });
1844                    }
1845                }
1846            }
1847            return null;
1848        }
1849    }
1850
1851
1852    /**
1853     * MoreImageSpan is a simple class created for tracking the existence of a
1854     * more chip across activity restarts/
1855     */
1856    private class MoreImageSpan extends ImageSpan {
1857        public MoreImageSpan(Drawable b) {
1858            super(b);
1859        }
1860    }
1861
1862    @Override
1863    public boolean onDown(MotionEvent e) {
1864        return false;
1865    }
1866
1867    @Override
1868    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
1869        // Do nothing.
1870        return false;
1871    }
1872
1873    @Override
1874    public void onLongPress(MotionEvent event) {
1875        if (mSelectedChip != null) {
1876            return;
1877        }
1878        float x = event.getX();
1879        float y = event.getY();
1880        int offset = putOffsetInRange(getOffsetForPosition(x, y));
1881        RecipientChip currentChip = findChip(offset);
1882        if (currentChip != null) {
1883            // Copy the selected chip email address.
1884            showCopyDialog(currentChip.getEntry().getDestination());
1885        }
1886    }
1887
1888    private void showCopyDialog(final String address) {
1889        mCopyAddress = address;
1890        mCopyDialog.setTitle(address);
1891        mCopyDialog.setContentView(mCopyViewRes);
1892        mCopyDialog.setCancelable(true);
1893        mCopyDialog.setCanceledOnTouchOutside(true);
1894        mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this);
1895        mCopyDialog.setOnDismissListener(this);
1896        mCopyDialog.show();
1897    }
1898
1899    @Override
1900    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
1901        // Do nothing.
1902        return false;
1903    }
1904
1905    @Override
1906    public void onShowPress(MotionEvent e) {
1907        // Do nothing.
1908    }
1909
1910    @Override
1911    public boolean onSingleTapUp(MotionEvent e) {
1912        // Do nothing.
1913        return false;
1914    }
1915
1916    @Override
1917    public void onDismiss(DialogInterface dialog) {
1918        mCopyAddress = null;
1919    }
1920
1921    @Override
1922    public void onClick(View v) {
1923        // Copy this to the clipboard.
1924        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
1925                Context.CLIPBOARD_SERVICE);
1926        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
1927        mCopyDialog.dismiss();
1928    }
1929}
1930