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