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