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