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