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