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