RecipientEditTextView.java revision c16fb2a3bcc168fb69a92f43aebf6cfa4bf3a007
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.ClipDescription;
22import android.content.ClipboardManager;
23import android.content.Context;
24import android.content.DialogInterface;
25import android.content.DialogInterface.OnDismissListener;
26import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.Bitmap;
29import android.graphics.BitmapFactory;
30import android.graphics.Canvas;
31import android.graphics.Matrix;
32import android.graphics.Point;
33import android.graphics.Rect;
34import android.graphics.RectF;
35import android.graphics.drawable.BitmapDrawable;
36import android.graphics.drawable.Drawable;
37import android.os.AsyncTask;
38import android.os.Handler;
39import android.os.Message;
40import android.os.Parcelable;
41import android.text.Editable;
42import android.text.InputType;
43import android.text.Layout;
44import android.text.Spannable;
45import android.text.SpannableString;
46import android.text.SpannableStringBuilder;
47import android.text.Spanned;
48import android.text.TextPaint;
49import android.text.TextUtils;
50import android.text.TextWatcher;
51import android.text.method.QwertyKeyListener;
52import android.text.style.ImageSpan;
53import android.text.util.Rfc822Token;
54import android.text.util.Rfc822Tokenizer;
55import android.util.AttributeSet;
56import android.util.Log;
57import android.util.Patterns;
58import android.view.ActionMode;
59import android.view.ActionMode.Callback;
60import android.view.DragEvent;
61import android.view.GestureDetector;
62import android.view.KeyEvent;
63import android.view.LayoutInflater;
64import android.view.Menu;
65import android.view.MenuItem;
66import android.view.MotionEvent;
67import android.view.View;
68import android.view.View.OnClickListener;
69import android.view.ViewParent;
70import android.view.inputmethod.EditorInfo;
71import android.view.inputmethod.InputConnection;
72import android.widget.AdapterView;
73import android.widget.AdapterView.OnItemClickListener;
74import android.widget.Button;
75import android.widget.ListAdapter;
76import android.widget.ListPopupWindow;
77import android.widget.ListView;
78import android.widget.MultiAutoCompleteTextView;
79import android.widget.ScrollView;
80import android.widget.TextView;
81
82import java.util.ArrayList;
83import java.util.Arrays;
84import java.util.Collection;
85import java.util.Collections;
86import java.util.Comparator;
87import java.util.HashMap;
88import java.util.HashSet;
89import java.util.Set;
90import java.util.regex.Matcher;
91
92/**
93 * RecipientEditTextView is an auto complete text view for use with applications
94 * that use the new Chips UI for addressing a message to recipients.
95 */
96public class RecipientEditTextView extends MultiAutoCompleteTextView implements
97        OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
98        GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
99        TextView.OnEditorActionListener {
100
101    private static final char COMMIT_CHAR_COMMA = ',';
102
103    private static final char NAME_WRAPPER_CHAR = '"';
104
105    private static final char COMMIT_CHAR_SEMICOLON = ';';
106
107    private static final char COMMIT_CHAR_SPACE = ' ';
108
109    private static final String TAG = "RecipientEditTextView";
110
111    private static int DISMISS = "dismiss".hashCode();
112
113    private static final long DISMISS_DELAY = 300;
114
115    // TODO: get correct number/ algorithm from with UX.
116    // Visible for testing.
117    /*package*/ static final int CHIP_LIMIT = 2;
118
119    private static final int MAX_CHIPS_PARSED = 50;
120
121    private static int sSelectedTextColor = -1;
122
123    // Resources for displaying chips.
124    private Drawable mChipBackground = null;
125
126    private Drawable mChipDelete = null;
127
128    private Drawable mInvalidChipBackground;
129
130    private Drawable mChipBackgroundPressed;
131
132    private float mChipHeight;
133
134    private float mChipFontSize;
135
136    private float mLineSpacingExtra;
137
138    private int mChipPadding;
139
140    private Tokenizer mTokenizer;
141
142    private Validator mValidator;
143
144    private RecipientChip mSelectedChip;
145
146    private int mAlternatesLayout;
147
148    private Bitmap mDefaultContactPhoto;
149
150    private ImageSpan mMoreChip;
151
152    private TextView mMoreItem;
153
154    private final ArrayList<String> mPendingChips = new ArrayList<String>();
155
156    private Handler mHandler;
157
158    private int mPendingChipsCount = 0;
159
160    private boolean mNoChips = false;
161
162    private ListPopupWindow mAlternatesPopup;
163
164    private ListPopupWindow mAddressPopup;
165
166    private ArrayList<RecipientChip> mTemporaryRecipients;
167
168    private ArrayList<RecipientChip> mRemovedSpans;
169
170    private boolean mShouldShrink = true;
171
172    // Chip copy fields.
173    private GestureDetector mGestureDetector;
174
175    private Dialog mCopyDialog;
176
177    private String mCopyAddress;
178
179    /**
180     * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a
181     * selected chip.
182     */
183    private OnItemClickListener mAlternatesListener;
184
185    private int mCheckedItem;
186
187    private TextWatcher mTextWatcher;
188
189    // Obtain the enclosing scroll view, if it exists, so that the view can be
190    // scrolled to show the last line of chips content.
191    private ScrollView mScrollView;
192
193    private boolean mTriedGettingScrollView;
194
195    private boolean mDragEnabled = false;
196
197    private final Runnable mAddTextWatcher = new Runnable() {
198        @Override
199        public void run() {
200            if (mTextWatcher == null) {
201                mTextWatcher = new RecipientTextWatcher();
202                addTextChangedListener(mTextWatcher);
203            }
204        }
205    };
206
207    private IndividualReplacementTask mIndividualReplacements;
208
209    private Runnable mHandlePendingChips = new Runnable() {
210
211        @Override
212        public void run() {
213            handlePendingChips();
214        }
215
216    };
217
218    private Runnable mDelayedShrink = new Runnable() {
219
220        @Override
221        public void run() {
222            shrink();
223        }
224
225    };
226
227    public RecipientEditTextView(Context context, AttributeSet attrs) {
228        super(context, attrs);
229        setChipDimensions(context, attrs);
230        if (sSelectedTextColor == -1) {
231            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
232        }
233        mAlternatesPopup = new ListPopupWindow(context);
234        mAddressPopup = new ListPopupWindow(context);
235        mCopyDialog = new Dialog(context);
236        mAlternatesListener = new OnItemClickListener() {
237            @Override
238            public void onItemClick(AdapterView<?> adapterView,View view, int position,
239                    long rowId) {
240                mAlternatesPopup.setOnItemClickListener(null);
241                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
242                        .getRecipientEntry(position));
243                Message delayed = Message.obtain(mHandler, DISMISS);
244                delayed.obj = mAlternatesPopup;
245                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
246                clearComposingText();
247            }
248        };
249        setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
250        setOnItemClickListener(this);
251        setCustomSelectionActionModeCallback(this);
252        mHandler = new Handler() {
253            @Override
254            public void handleMessage(Message msg) {
255                if (msg.what == DISMISS) {
256                    ((ListPopupWindow) msg.obj).dismiss();
257                    return;
258                }
259                super.handleMessage(msg);
260            }
261        };
262        mTextWatcher = new RecipientTextWatcher();
263        addTextChangedListener(mTextWatcher);
264        mGestureDetector = new GestureDetector(context, this);
265        setOnEditorActionListener(this);
266    }
267
268    @Override
269    public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
270        if (action == EditorInfo.IME_ACTION_DONE) {
271            if (commitDefault()) {
272                return true;
273            }
274            if (mSelectedChip != null) {
275                clearSelectedChip();
276                return true;
277            } else if (focusNext()) {
278                return true;
279            }
280        }
281        return false;
282    }
283
284    @Override
285    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
286        InputConnection connection = super.onCreateInputConnection(outAttrs);
287        int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
288        if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
289            // clear the existing action
290            outAttrs.imeOptions ^= imeActions;
291            // set the DONE action
292            outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
293        }
294        if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
295            outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
296        }
297        outAttrs.actionLabel = getContext().getString(R.string.done);
298        return connection;
299    }
300
301    /*package*/ RecipientChip getLastChip() {
302        RecipientChip last = null;
303        RecipientChip[] chips = getSortedRecipients();
304        if (chips != null && chips.length > 0) {
305            last = chips[chips.length - 1];
306        }
307        return last;
308    }
309
310    @Override
311    public void onSelectionChanged(int start, int end) {
312        // When selection changes, see if it is inside the chips area.
313        // If so, move the cursor back after the chips again.
314        RecipientChip last = getLastChip();
315        if (last != null && start < getSpannable().getSpanEnd(last)) {
316            // Grab the last chip and set the cursor to after it.
317            setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length()));
318        }
319        super.onSelectionChanged(start, end);
320    }
321
322    @Override
323    public void onRestoreInstanceState(Parcelable state) {
324        if (!TextUtils.isEmpty(getText())) {
325            super.onRestoreInstanceState(null);
326        } else {
327            super.onRestoreInstanceState(state);
328        }
329    }
330
331    @Override
332    public Parcelable onSaveInstanceState() {
333        // If the user changes orientation while they are editing, just roll back the selection.
334        clearSelectedChip();
335        return super.onSaveInstanceState();
336    }
337
338    /**
339     * Convenience method: Append the specified text slice to the TextView's
340     * display buffer, upgrading it to BufferType.EDITABLE if it was
341     * not already editable. Commas are excluded as they are added automatically
342     * by the view.
343     */
344    @Override
345    public void append(CharSequence text, int start, int end) {
346        // We don't care about watching text changes while appending.
347        if (mTextWatcher != null) {
348            removeTextChangedListener(mTextWatcher);
349        }
350        super.append(text, start, end);
351        if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
352            String displayString = text.toString();
353            int separatorPos = displayString.lastIndexOf(COMMIT_CHAR_COMMA);
354            // Verify that the separator pos is not within ""; if it is, look
355            // past the closing quote. If there is no comma past ", this string
356            // will resolve to an error chip.
357            if (separatorPos > -1) {
358                String parseDisplayString = displayString.substring(separatorPos);
359                int endQuotedTextPos = parseDisplayString.indexOf(NAME_WRAPPER_CHAR);
360                if (endQuotedTextPos > separatorPos) {
361                    separatorPos = parseDisplayString.lastIndexOf(COMMIT_CHAR_COMMA,
362                            endQuotedTextPos);
363                }
364            }
365            if (!TextUtils.isEmpty(displayString)
366                    && TextUtils.getTrimmedLength(displayString) > 0) {
367                mPendingChipsCount++;
368                mPendingChips.add(text.toString());
369            }
370        }
371        // Put a message on the queue to make sure we ALWAYS handle pending
372        // chips.
373        if (mPendingChipsCount > 0) {
374            postHandlePendingChips();
375        }
376        mHandler.post(mAddTextWatcher);
377    }
378
379    @Override
380    public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
381        super.onFocusChanged(hasFocus, direction, previous);
382        if (!hasFocus) {
383            shrink();
384        } else {
385            expand();
386        }
387    }
388
389    @Override
390    public void performValidation() {
391        // Do nothing. Chips handles its own validation.
392    }
393
394    private void shrink() {
395        if (mTokenizer == null) {
396            return;
397        }
398        if (mSelectedChip != null
399                && mSelectedChip.getEntry().getContactId() != RecipientEntry.INVALID_CONTACT) {
400            clearSelectedChip();
401        } else {
402            if (getWidth() <= 0) {
403                // We don't have the width yet which means the view hasn't been drawn yet
404                // and there is no reason to attempt to commit chips yet.
405                // This focus lost must be the result of an orientation change
406                // or an initial rendering.
407                // Re-post the shrink for later.
408                mHandler.removeCallbacks(mDelayedShrink);
409                mHandler.post(mDelayedShrink);
410                return;
411            }
412            // Reset any pending chips as they would have been handled
413            // when the field lost focus.
414            if (mPendingChipsCount > 0) {
415                postHandlePendingChips();
416            } else {
417                Editable editable = getText();
418                int end = getSelectionEnd();
419                int start = mTokenizer.findTokenStart(editable, end);
420                RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
421                if ((chips == null || chips.length == 0)) {
422                    Editable text = getText();
423                    int whatEnd = mTokenizer.findTokenEnd(text, start);
424                    // This token was already tokenized, so skip past the ending token.
425                    if (whatEnd < text.length() && text.charAt(whatEnd) == ',') {
426                        whatEnd++;
427                    }
428                    // In the middle of chip; treat this as an edit
429                    // and commit the whole token.
430                    int selEnd = getSelectionEnd();
431                    if (whatEnd != selEnd) {
432                        handleEdit(start, whatEnd);
433                    } else {
434                        commitChip(start, end, editable);
435                    }
436                }
437            }
438            mHandler.post(mAddTextWatcher);
439        }
440        createMoreChip();
441    }
442
443    private void expand() {
444        removeMoreChip();
445        setCursorVisible(true);
446        Editable text = getText();
447        setSelection(text != null && text.length() > 0 ? text.length() : 0);
448        // If there are any temporary chips, try replacing them now that the user
449        // has expanded the field.
450        if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
451            new RecipientReplacementTask().execute();
452            mTemporaryRecipients = null;
453        }
454    }
455
456    private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
457        paint.setTextSize(mChipFontSize);
458        if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
459            Log.d(TAG, "Max width is negative: " + maxWidth);
460        }
461        return TextUtils.ellipsize(text, paint, maxWidth,
462                TextUtils.TruncateAt.END);
463    }
464
465    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
466        // Ellipsize the text so that it takes AT MOST the entire width of the
467        // autocomplete text entry area. Make sure to leave space for padding
468        // on the sides.
469        int height = (int) mChipHeight;
470        int deleteWidth = height;
471        float[] widths = new float[1];
472        paint.getTextWidths(" ", widths);
473        CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
474                calculateAvailableWidth(true) - deleteWidth - widths[0]);
475
476        // Make sure there is a minimum chip width so the user can ALWAYS
477        // tap a chip without difficulty.
478        int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
479                ellipsizedText.length()))
480                + (mChipPadding * 2) + deleteWidth);
481
482        // Create the background of the chip.
483        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
484        Canvas canvas = new Canvas(tmpBitmap);
485        if (mChipBackgroundPressed != null) {
486            mChipBackgroundPressed.setBounds(0, 0, width, height);
487            mChipBackgroundPressed.draw(canvas);
488            paint.setColor(sSelectedTextColor);
489            // Vertically center the text in the chip.
490            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
491                    getTextYOffset((String) ellipsizedText, paint, height), paint);
492            // Make the delete a square.
493            Rect backgroundPadding = new Rect();
494            mChipBackgroundPressed.getPadding(backgroundPadding);
495            mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left,
496                    0 + backgroundPadding.top,
497                    width - backgroundPadding.right,
498                    height - backgroundPadding.bottom);
499            mChipDelete.draw(canvas);
500        } else {
501            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
502        }
503        return tmpBitmap;
504    }
505
506
507    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
508        // Ellipsize the text so that it takes AT MOST the entire width of the
509        // autocomplete text entry area. Make sure to leave space for padding
510        // on the sides.
511        int height = (int) mChipHeight;
512        int iconWidth = height;
513        float[] widths = new float[1];
514        paint.getTextWidths(" ", widths);
515        CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
516                calculateAvailableWidth(false) - iconWidth - widths[0]);
517        // Make sure there is a minimum chip width so the user can ALWAYS
518        // tap a chip without difficulty.
519        int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
520                ellipsizedText.length()))
521                + (mChipPadding * 2) + iconWidth);
522
523        // Create the background of the chip.
524        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
525        Canvas canvas = new Canvas(tmpBitmap);
526        Drawable background = getChipBackground(contact);
527        if (background != null) {
528            background.setBounds(0, 0, width, height);
529            background.draw(canvas);
530
531            // Don't draw photos for recipients that have been typed in.
532            if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) {
533                byte[] photoBytes = contact.getPhotoBytes();
534                // There may not be a photo yet if anything but the first contact address
535                // was selected.
536                if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
537                    // TODO: cache this in the recipient entry?
538                    ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
539                            .getPhotoThumbnailUri());
540                    photoBytes = contact.getPhotoBytes();
541                }
542
543                Bitmap photo;
544                if (photoBytes != null) {
545                    photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
546                } else {
547                    // TODO: can the scaled down default photo be cached?
548                    photo = mDefaultContactPhoto;
549                }
550                // Draw the photo on the left side.
551                if (photo != null) {
552                    RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
553                    Rect backgroundPadding = new Rect();
554                    mChipBackground.getPadding(backgroundPadding);
555                    RectF dst = new RectF(width - iconWidth + backgroundPadding.left,
556                            0 + backgroundPadding.top,
557                            width - backgroundPadding.right,
558                            height - backgroundPadding.bottom);
559                    Matrix matrix = new Matrix();
560                    matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
561                    canvas.drawBitmap(photo, matrix, paint);
562                }
563            } else {
564                // Don't leave any space for the icon. It isn't being drawn.
565                iconWidth = 0;
566            }
567            paint.setColor(getContext().getResources().getColor(android.R.color.black));
568            // Vertically center the text in the chip.
569            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
570                    getTextYOffset((String)ellipsizedText, paint, height), paint);
571        } else {
572            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
573        }
574        return tmpBitmap;
575    }
576
577    /**
578     * Get the background drawable for a RecipientChip.
579     */
580    // Visible for testing.
581    /*package*/ Drawable getChipBackground(RecipientEntry contact) {
582        return (mValidator != null && mValidator.isValid(contact.getDestination())) ?
583                mChipBackground : mInvalidChipBackground;
584    }
585
586    private float getTextYOffset(String text, TextPaint paint, int height) {
587        Rect bounds = new Rect();
588        paint.getTextBounds(text, 0, text.length(), bounds);
589        int textHeight = bounds.bottom - bounds.top ;
590        return height - ((height - textHeight) / 2) - (int)paint.descent();
591    }
592
593    private RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
594            throws NullPointerException {
595        if (mChipBackground == null) {
596            throw new NullPointerException(
597                    "Unable to render any chips as setChipDimensions was not called.");
598        }
599        Layout layout = getLayout();
600
601        TextPaint paint = getPaint();
602        float defaultSize = paint.getTextSize();
603        int defaultColor = paint.getColor();
604
605        Bitmap tmpBitmap;
606        if (pressed) {
607            tmpBitmap = createSelectedChip(contact, paint, layout);
608
609        } else {
610            tmpBitmap = createUnselectedChip(contact, paint, layout);
611        }
612
613        // Pass the full text, un-ellipsized, to the chip.
614        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
615        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
616        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
617        // Return text to the original size.
618        paint.setTextSize(defaultSize);
619        paint.setColor(defaultColor);
620        return recipientChip;
621    }
622
623    /**
624     * Calculate the bottom of the line the chip will be located on using:
625     * 1) which line the chip appears on
626     * 2) the height of a chip
627     * 3) padding built into the edit text view
628     */
629    private int calculateOffsetFromBottom(int line) {
630        // Line offsets start at zero.
631        int actualLine = getLineCount() - (line + 1);
632        return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
633                + getDropDownVerticalOffset();
634    }
635
636    /**
637     * Get the max amount of space a chip can take up. The formula takes into
638     * account the width of the EditTextView, any view padding, and padding
639     * that will be added to the chip.
640     */
641    private float calculateAvailableWidth(boolean pressed) {
642        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
643    }
644
645
646    private void setChipDimensions(Context context, AttributeSet attrs) {
647        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
648                0);
649        Resources r = getContext().getResources();
650        mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
651        if (mChipBackground == null) {
652            mChipBackground = r.getDrawable(R.drawable.chip_background);
653        }
654        mChipBackgroundPressed = a
655                .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed);
656        if (mChipBackgroundPressed == null) {
657            mChipBackgroundPressed = r.getDrawable(R.drawable.chip_background_selected);
658        }
659        mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
660        if (mChipDelete == null) {
661            mChipDelete = r.getDrawable(R.drawable.chip_delete);
662        }
663        mChipPadding = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
664        if (mChipPadding == -1) {
665            mChipPadding = (int) r.getDimension(R.dimen.chip_padding);
666        }
667        mAlternatesLayout = a.getResourceId(R.styleable.RecipientEditTextView_chipAlternatesLayout,
668                -1);
669        if (mAlternatesLayout == -1) {
670            mAlternatesLayout = R.layout.chips_alternate_item;
671        }
672
673        mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
674
675        mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
676
677        mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
678        if (mChipHeight == -1) {
679            mChipHeight = r.getDimension(R.dimen.chip_height);
680        }
681        mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
682        if (mChipFontSize == -1) {
683            mChipFontSize = r.getDimension(R.dimen.chip_text_size);
684        }
685        mInvalidChipBackground = a
686                .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
687        if (mInvalidChipBackground == null) {
688            mInvalidChipBackground = r.getDrawable(R.drawable.chip_background_invalid);
689        }
690        mLineSpacingExtra =  context.getResources().getDimension(R.dimen.line_spacing_extra);
691        a.recycle();
692    }
693
694    // Visible for testing.
695    /* package */ void setMoreItem(TextView moreItem) {
696        mMoreItem = moreItem;
697    }
698
699
700    // Visible for testing.
701    /* package */ void setChipBackground(Drawable chipBackground) {
702        mChipBackground = chipBackground;
703    }
704
705    // Visible for testing.
706    /* package */ void setChipHeight(int height) {
707        mChipHeight = height;
708    }
709
710    /**
711     * Set whether to shrink the recipients field such that at most
712     * one line of recipients chips are shown when the field loses
713     * focus. By default, the number of displayed recipients will be
714     * limited and a "more" chip will be shown when focus is lost.
715     * @param shrink
716     */
717    public void setOnFocusListShrinkRecipients(boolean shrink) {
718        mShouldShrink = shrink;
719    }
720
721    @Override
722    public void onSizeChanged(int width, int height, int oldw, int oldh) {
723        super.onSizeChanged(width, height, oldw, oldh);
724        if (width != 0 && height != 0) {
725            if (mPendingChipsCount > 0) {
726                postHandlePendingChips();
727            } else {
728                checkChipWidths();
729            }
730        }
731        // Try to find the scroll view parent, if it exists.
732        if (mScrollView == null && !mTriedGettingScrollView) {
733            ViewParent parent = getParent();
734            while (parent != null && !(parent instanceof ScrollView)) {
735                parent = parent.getParent();
736            }
737            if (parent != null) {
738                mScrollView = (ScrollView) parent;
739            }
740            mTriedGettingScrollView = true;
741        }
742    }
743
744    private void postHandlePendingChips() {
745        mHandler.removeCallbacks(mHandlePendingChips);
746        mHandler.post(mHandlePendingChips);
747    }
748
749    private void checkChipWidths() {
750        // Check the widths of the associated chips.
751        RecipientChip[] chips = getSortedRecipients();
752        if (chips != null) {
753            Rect bounds;
754            for (RecipientChip chip : chips) {
755                bounds = chip.getDrawable().getBounds();
756                if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) {
757                    // Need to redraw that chip.
758                    replaceChip(chip, chip.getEntry());
759                }
760            }
761        }
762    }
763
764    // Visible for testing.
765    /*package*/ void handlePendingChips() {
766        if (getViewWidth() <= 0) {
767            // The widget has not been sized yet.
768            // This will be called as a result of onSizeChanged
769            // at a later point.
770            return;
771        }
772        if (mPendingChipsCount <= 0) {
773            return;
774        }
775
776        synchronized (mPendingChips) {
777            Editable editable = getText();
778            // Tokenize!
779            if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
780                for (int i = 0; i < mPendingChips.size(); i++) {
781                    String current = mPendingChips.get(i);
782                    int tokenStart = editable.toString().indexOf(current);
783                    int tokenEnd = tokenStart + current.length();
784                    if (tokenStart >= 0) {
785                        // When we have a valid token, include it with the token
786                        // to the left.
787                        if (tokenEnd < editable.length() - 2
788                                && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
789                            tokenEnd++;
790                        }
791                        createReplacementChip(tokenStart, tokenEnd, editable);
792                    }
793                    mPendingChipsCount--;
794                }
795                sanitizeEnd();
796            } else {
797                mNoChips = true;
798            }
799
800            if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
801                    && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
802                if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
803                    new RecipientReplacementTask().execute();
804                    mTemporaryRecipients = null;
805                } else {
806                    // Create the "more" chip
807                    mIndividualReplacements = new IndividualReplacementTask();
808                    mIndividualReplacements.execute(new ArrayList<RecipientChip>(
809                            mTemporaryRecipients.subList(0, CHIP_LIMIT)));
810
811                    createMoreChip();
812                }
813            } else {
814                // There are too many recipients to look up, so just fall back
815                // to showing addresses for all of them.
816                mTemporaryRecipients = null;
817                createMoreChip();
818            }
819            mPendingChipsCount = 0;
820            mPendingChips.clear();
821        }
822    }
823
824    // Visible for testing.
825    /*package*/ int getViewWidth() {
826        return getWidth();
827    }
828
829    /**
830     * Remove any characters after the last valid chip.
831     */
832    // Visible for testing.
833    /*package*/ void sanitizeEnd() {
834        // Don't sanitize while we are waiting for pending chips to complete.
835        if (mPendingChipsCount > 0) {
836            return;
837        }
838        // Find the last chip; eliminate any commit characters after it.
839        RecipientChip[] chips = getSortedRecipients();
840        if (chips != null && chips.length > 0) {
841            int end;
842            ImageSpan lastSpan;
843            mMoreChip = getMoreChip();
844            if (mMoreChip != null) {
845                lastSpan = mMoreChip;
846            } else {
847                lastSpan = getLastChip();
848            }
849            end = getSpannable().getSpanEnd(lastSpan);
850            Editable editable = getText();
851            int length = editable.length();
852            if (length > end) {
853                // See what characters occur after that and eliminate them.
854                if (Log.isLoggable(TAG, Log.DEBUG)) {
855                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
856                            + editable);
857                }
858                editable.delete(end + 1, length);
859            }
860        }
861    }
862
863    /**
864     * Create a chip that represents just the email address of a recipient. At some later
865     * point, this chip will be attached to a real contact entry, if one exists.
866     */
867    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
868        if (alreadyHasChip(tokenStart, tokenEnd)) {
869            // There is already a chip present at this location.
870            // Don't recreate it.
871            return;
872        }
873        String token = editable.toString().substring(tokenStart, tokenEnd);
874        int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
875        if (commitCharIndex == token.length() - 1) {
876            token = token.substring(0, token.length() - 1);
877        }
878        RecipientEntry entry = createTokenizedEntry(token);
879        if (entry != null) {
880            String destText = createAddressText(entry);
881            // Always leave a blank space at the end of a chip.
882            int textLength = destText.length() - 1;
883            SpannableString chipText = new SpannableString(destText);
884            int end = getSelectionEnd();
885            int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0;
886            RecipientChip chip = null;
887            try {
888                if (!mNoChips) {
889                    chip = constructChipSpan(entry, start, false);
890                    chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
891                }
892            } catch (NullPointerException e) {
893                Log.e(TAG, e.getMessage(), e);
894            }
895            editable.replace(tokenStart, tokenEnd, chipText);
896            // Add this chip to the list of entries "to replace"
897            if (chip != null) {
898                if (mTemporaryRecipients == null) {
899                    mTemporaryRecipients = new ArrayList<RecipientChip>();
900                }
901                chip.setOriginalText(chipText.toString());
902                mTemporaryRecipients.add(chip);
903            }
904        }
905    }
906
907    private static boolean isPhoneNumber(String number) {
908        // TODO: replace this function with libphonenumber's isPossibleNumber (see
909        // PhoneNumberUtil). One complication is that it requires the sender's region which
910        // comes from the CurrentCountryIso. For now, let's just do this simple match.
911        if (TextUtils.isEmpty(number)) {
912            return false;
913        }
914
915        Matcher match = Patterns.PHONE.matcher(number);
916        return match.matches();
917    }
918
919    private RecipientEntry createTokenizedEntry(String token) {
920        if (TextUtils.isEmpty(token)) {
921            return null;
922        }
923        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
924        String display = null;
925        if (isPhoneQuery()) {
926            // The number often arrives as "(800) 123-1231, ".
927            // Trim the space and trailing comma if necessary.
928            token = token.trim();
929            char charAt = token.charAt(token.length() - 1);
930            if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
931                token = token.substring(0, token.length() - 1);
932            }
933
934            // look for something that looks like a phone number. At this point, the original
935            // token might have looked like this: "Fred Flinstone <(800) 425-2323>"
936            if (!isPhoneNumber(token) && isValid(token) && tokens != null && tokens.length > 0) {
937                for (int i = 0; i < tokens.length; i++) {
938                    // If we can get a phone number from tokenizing, then generate an entry from
939                    // this.
940                    display = tokens[i].getName();
941                    if (!TextUtils.isEmpty(display) && isPhoneNumber(display)) {
942                        return RecipientEntry.constructGeneratedEntry(display, display);
943                    } else {
944                        display = tokens[i].getAddress();
945                        if (!TextUtils.isEmpty(display) && isPhoneNumber(display)) {
946                            return RecipientEntry.constructFakeEntry(display);
947                        }
948                    }
949                }
950            }
951            // If the original token is a phone number to start with or as a last resort, use the
952            // original token.
953            return RecipientEntry.constructFakeEntry(token);
954        }
955        if (isValid(token) && tokens != null && tokens.length > 0) {
956            // If we can get a name from tokenizing, then generate an entry from
957            // this.
958            display = tokens[0].getName();
959            if (!TextUtils.isEmpty(display)) {
960                return RecipientEntry.constructGeneratedEntry(display, token);
961            } else {
962                display = tokens[0].getAddress();
963                if (!TextUtils.isEmpty(display)) {
964                    return RecipientEntry.constructFakeEntry(display);
965                }
966            }
967        }
968        // Unable to validate the token or to create a valid token from it.
969        // Just create a chip the user can edit.
970        String validatedToken = null;
971        if (mValidator != null && !mValidator.isValid(token)) {
972            // Try fixing up the entry using the validator.
973            validatedToken = mValidator.fixText(token).toString();
974            if (!TextUtils.isEmpty(validatedToken)) {
975                if (validatedToken.contains(token)) {
976                    // protect against the case of a validator with a null domain,
977                    // which doesn't add a domain to the token
978                    Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
979                    if (tokenized.length > 0) {
980                        validatedToken = tokenized[0].getAddress();
981                    }
982                } else {
983                    // We ran into a case where the token was invalid and removed
984                    // by the validator. In this case, just use the original token
985                    // and let the user sort out the error chip.
986                    validatedToken = null;
987                }
988            }
989        }
990        // Otherwise, fallback to just creating an editable email address chip.
991        return RecipientEntry
992                .constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token);
993    }
994
995    private boolean isValid(String text) {
996        return mValidator == null ? true : mValidator.isValid(text);
997    }
998
999    private String tokenizeAddress(String destination) {
1000        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
1001        if (tokens != null && tokens.length > 0) {
1002            return tokens[0].getAddress();
1003        }
1004        return destination;
1005    }
1006
1007    @Override
1008    public void setTokenizer(Tokenizer tokenizer) {
1009        mTokenizer = tokenizer;
1010        super.setTokenizer(mTokenizer);
1011    }
1012
1013    @Override
1014    public void setValidator(Validator validator) {
1015        mValidator = validator;
1016        super.setValidator(validator);
1017    }
1018
1019    /**
1020     * We cannot use the default mechanism for replaceText. Instead,
1021     * we override onItemClickListener so we can get all the associated
1022     * contact information including display text, address, and id.
1023     */
1024    @Override
1025    protected void replaceText(CharSequence text) {
1026        return;
1027    }
1028
1029    /**
1030     * Dismiss any selected chips when the back key is pressed.
1031     */
1032    @Override
1033    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
1034        if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) {
1035            clearSelectedChip();
1036            return true;
1037        }
1038        return super.onKeyPreIme(keyCode, event);
1039    }
1040
1041    /**
1042     * Monitor key presses in this view to see if the user types
1043     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
1044     * If the user has entered text that has contact matches and types
1045     * a commit key, create a chip from the topmost matching contact.
1046     * If the user has entered text that has no contact matches and types
1047     * a commit key, then create a chip from the text they have entered.
1048     */
1049    @Override
1050    public boolean onKeyUp(int keyCode, KeyEvent event) {
1051        switch (keyCode) {
1052            case KeyEvent.KEYCODE_ENTER:
1053            case KeyEvent.KEYCODE_DPAD_CENTER:
1054                if (event.hasNoModifiers()) {
1055                    if (commitDefault()) {
1056                        return true;
1057                    }
1058                    if (mSelectedChip != null) {
1059                        clearSelectedChip();
1060                        return true;
1061                    } else if (focusNext()) {
1062                        return true;
1063                    }
1064                }
1065                break;
1066            case KeyEvent.KEYCODE_TAB:
1067                if (event.hasNoModifiers()) {
1068                    if (mSelectedChip != null) {
1069                        clearSelectedChip();
1070                    } else {
1071                        commitDefault();
1072                    }
1073                    if (focusNext()) {
1074                        return true;
1075                    }
1076                }
1077                break;
1078        }
1079        return super.onKeyUp(keyCode, event);
1080    }
1081
1082    private boolean focusNext() {
1083        View next = focusSearch(View.FOCUS_DOWN);
1084        if (next != null) {
1085            next.requestFocus();
1086            return true;
1087        }
1088        return false;
1089    }
1090
1091    /**
1092     * Create a chip from the default selection. If the popup is showing, the
1093     * default is the first item in the popup suggestions list. Otherwise, it is
1094     * whatever the user had typed in. End represents where the the tokenizer
1095     * should search for a token to turn into a chip.
1096     * @return If a chip was created from a real contact.
1097     */
1098    private boolean commitDefault() {
1099        // If there is no tokenizer, don't try to commit.
1100        if (mTokenizer == null) {
1101            return false;
1102        }
1103        Editable editable = getText();
1104        int end = getSelectionEnd();
1105        int start = mTokenizer.findTokenStart(editable, end);
1106
1107        if (shouldCreateChip(start, end)) {
1108            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1109            // In the middle of chip; treat this as an edit
1110            // and commit the whole token.
1111            if (whatEnd != getSelectionEnd()) {
1112                handleEdit(start, whatEnd);
1113                return true;
1114            }
1115            return commitChip(start, end , editable);
1116        }
1117        return false;
1118    }
1119
1120    private void commitByCharacter() {
1121        // We can't possibly commit by character if we can't tokenize.
1122        if (mTokenizer == null) {
1123            return;
1124        }
1125        Editable editable = getText();
1126        int end = getSelectionEnd();
1127        int start = mTokenizer.findTokenStart(editable, end);
1128        if (shouldCreateChip(start, end)) {
1129            commitChip(start, end, editable);
1130        }
1131        setSelection(getText().length());
1132    }
1133
1134    private boolean commitChip(int start, int end, Editable editable) {
1135        ListAdapter adapter = getAdapter();
1136        if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
1137                && end == getSelectionEnd() && !isPhoneQuery()) {
1138            // choose the first entry.
1139            submitItemAtPosition(0);
1140            dismissDropDown();
1141            return true;
1142        } else {
1143            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
1144            if (editable.length() > tokenEnd + 1) {
1145                char charAt = editable.charAt(tokenEnd + 1);
1146                if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1147                    tokenEnd++;
1148                }
1149            }
1150            String text = editable.toString().substring(start, tokenEnd).trim();
1151            clearComposingText();
1152            if (text != null && text.length() > 0 && !text.equals(" ")) {
1153                RecipientEntry entry = createTokenizedEntry(text);
1154                if (entry != null) {
1155                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
1156                    CharSequence chipText = createChip(entry, false);
1157                    if (chipText != null && start > -1 && end > -1) {
1158                        editable.replace(start, end, chipText);
1159                    }
1160                }
1161                // Only dismiss the dropdown if it is related to the text we
1162                // just committed.
1163                // For paste, it may not be as there are possibly multiple
1164                // tokens being added.
1165                if (end == getSelectionEnd()) {
1166                    dismissDropDown();
1167                }
1168                sanitizeBetween();
1169                return true;
1170            }
1171        }
1172        return false;
1173    }
1174
1175    // Visible for testing.
1176    /* package */ void sanitizeBetween() {
1177        // Don't sanitize while we are waiting for content to chipify.
1178        if (mPendingChipsCount > 0) {
1179            return;
1180        }
1181        // Find the last chip.
1182        RecipientChip[] recips = getSortedRecipients();
1183        if (recips != null && recips.length > 0) {
1184            RecipientChip last = recips[recips.length - 1];
1185            RecipientChip beforeLast = null;
1186            if (recips.length > 1) {
1187                beforeLast = recips[recips.length - 2];
1188            }
1189            int startLooking = 0;
1190            int end = getSpannable().getSpanStart(last);
1191            if (beforeLast != null) {
1192                startLooking = getSpannable().getSpanEnd(beforeLast);
1193                Editable text = getText();
1194                if (startLooking == -1 || startLooking > text.length() - 1) {
1195                    // There is nothing after this chip.
1196                    return;
1197                }
1198                if (text.charAt(startLooking) == ' ') {
1199                    startLooking++;
1200                }
1201            }
1202            if (startLooking >= 0 && end >= 0 && startLooking < end) {
1203                getText().delete(startLooking, end);
1204            }
1205        }
1206    }
1207
1208    private boolean shouldCreateChip(int start, int end) {
1209        return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
1210    }
1211
1212    private boolean alreadyHasChip(int start, int end) {
1213        if (mNoChips) {
1214            return true;
1215        }
1216        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
1217        if ((chips == null || chips.length == 0)) {
1218            return false;
1219        }
1220        return true;
1221    }
1222
1223    private void handleEdit(int start, int end) {
1224        if (start == -1 || end == -1) {
1225            // This chip no longer exists in the field.
1226            dismissDropDown();
1227            return;
1228        }
1229        // This is in the middle of a chip, so select out the whole chip
1230        // and commit it.
1231        Editable editable = getText();
1232        setSelection(end);
1233        String text = getText().toString().substring(start, end);
1234        if (!TextUtils.isEmpty(text)) {
1235            RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
1236            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1237            CharSequence chipText = createChip(entry, false);
1238            int selEnd = getSelectionEnd();
1239            if (chipText != null && start > -1 && selEnd > -1) {
1240                editable.replace(start, selEnd, chipText);
1241            }
1242        }
1243        dismissDropDown();
1244    }
1245
1246    /**
1247     * If there is a selected chip, delegate the key events
1248     * to the selected chip.
1249     */
1250    @Override
1251    public boolean onKeyDown(int keyCode, KeyEvent event) {
1252        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1253            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1254                mAlternatesPopup.dismiss();
1255            }
1256            removeChip(mSelectedChip);
1257        }
1258
1259        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
1260            return true;
1261        }
1262
1263        return super.onKeyDown(keyCode, event);
1264    }
1265
1266    // Visible for testing.
1267    /* package */ Spannable getSpannable() {
1268        return getText();
1269    }
1270
1271    private int getChipStart(RecipientChip chip) {
1272        return getSpannable().getSpanStart(chip);
1273    }
1274
1275    private int getChipEnd(RecipientChip chip) {
1276        return getSpannable().getSpanEnd(chip);
1277    }
1278
1279    /**
1280     * Instead of filtering on the entire contents of the edit box,
1281     * this subclass method filters on the range from
1282     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1283     * if the length of that range meets or exceeds {@link #getThreshold}
1284     * and makes sure that the range is not already a Chip.
1285     */
1286    @Override
1287    protected void performFiltering(CharSequence text, int keyCode) {
1288        if (enoughToFilter() && !isCompletedToken(text)) {
1289            int end = getSelectionEnd();
1290            int start = mTokenizer.findTokenStart(text, end);
1291            // If this is a RecipientChip, don't filter
1292            // on its contents.
1293            Spannable span = getSpannable();
1294            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
1295            if (chips != null && chips.length > 0) {
1296                return;
1297            }
1298        }
1299        super.performFiltering(text, keyCode);
1300    }
1301
1302    // Visible for testing.
1303    /*package*/ boolean isCompletedToken(CharSequence text) {
1304        if (TextUtils.isEmpty(text)) {
1305            return false;
1306        }
1307        // Check to see if this is a completed token before filtering.
1308        int end = text.length();
1309        int start = mTokenizer.findTokenStart(text, end);
1310        String token = text.toString().substring(start, end).trim();
1311        if (!TextUtils.isEmpty(token)) {
1312            char atEnd = token.charAt(token.length() - 1);
1313            return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1314        }
1315        return false;
1316    }
1317
1318    private void clearSelectedChip() {
1319        if (mSelectedChip != null) {
1320            unselectChip(mSelectedChip);
1321            mSelectedChip = null;
1322        }
1323        setCursorVisible(true);
1324    }
1325
1326    /**
1327     * Monitor touch events in the RecipientEditTextView.
1328     * If the view does not have focus, any tap on the view
1329     * will just focus the view. If the view has focus, determine
1330     * if the touch target is a recipient chip. If it is and the chip
1331     * is not selected, select it and clear any other selected chips.
1332     * If it isn't, then select that chip.
1333     */
1334    @Override
1335    public boolean onTouchEvent(MotionEvent event) {
1336        if (!isFocused()) {
1337            // Ignore any chip taps until this view is focused.
1338            return super.onTouchEvent(event);
1339        }
1340        boolean handled = super.onTouchEvent(event);
1341        int action = event.getAction();
1342        boolean chipWasSelected = false;
1343        if (mSelectedChip == null) {
1344            mGestureDetector.onTouchEvent(event);
1345        }
1346        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1347            float x = event.getX();
1348            float y = event.getY();
1349            int offset = putOffsetInRange(getOffsetForPosition(x, y));
1350            RecipientChip currentChip = findChip(offset);
1351            if (currentChip != null) {
1352                if (action == MotionEvent.ACTION_UP) {
1353                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1354                        clearSelectedChip();
1355                        mSelectedChip = selectChip(currentChip);
1356                    } else if (mSelectedChip == null) {
1357                        setSelection(getText().length());
1358                        commitDefault();
1359                        mSelectedChip = selectChip(currentChip);
1360                    } else {
1361                        onClick(mSelectedChip, offset, x, y);
1362                    }
1363                }
1364                chipWasSelected = true;
1365                handled = true;
1366            } else if (mSelectedChip != null
1367                    && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1368                chipWasSelected = true;
1369            }
1370        }
1371        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1372            clearSelectedChip();
1373        }
1374        return handled;
1375    }
1376
1377    private void scrollLineIntoView(int line) {
1378        if (mScrollView != null) {
1379            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1380        }
1381    }
1382
1383    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1384            int width, Context context) {
1385        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1386        int bottom;
1387        if (line == getLineCount() -1) {
1388            bottom = 0;
1389        } else {
1390            bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math.abs(getLineCount() - 1
1391                    - line)));
1392        }
1393        // Align the alternates popup with the left side of the View,
1394        // regardless of the position of the chip tapped.
1395        alternatesPopup.setWidth(width);
1396        alternatesPopup.setAnchorView(this);
1397        alternatesPopup.setVerticalOffset(bottom);
1398        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1399        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1400        // Clear the checked item.
1401        mCheckedItem = -1;
1402        alternatesPopup.show();
1403        ListView listView = alternatesPopup.getListView();
1404        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1405        // Checked item would be -1 if the adapter has not
1406        // loaded the view that should be checked yet. The
1407        // variable will be set correctly when onCheckedItemChanged
1408        // is called in a separate thread.
1409        if (mCheckedItem != -1) {
1410            listView.setItemChecked(mCheckedItem, true);
1411            mCheckedItem = -1;
1412        }
1413    }
1414
1415    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1416        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1417                mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this);
1418    }
1419
1420    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1421        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1422                .getEntry());
1423    }
1424
1425    @Override
1426    public void onCheckedItemChanged(int position) {
1427        ListView listView = mAlternatesPopup.getListView();
1428        if (listView != null && listView.getCheckedItemCount() == 0) {
1429            listView.setItemChecked(position, true);
1430        }
1431        mCheckedItem = position;
1432    }
1433
1434    // TODO: This algorithm will need a lot of tweaking after more people have used
1435    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1436    // what comes before the finger.
1437    private int putOffsetInRange(int o) {
1438        int offset = o;
1439        Editable text = getText();
1440        int length = text.length();
1441        // Remove whitespace from end to find "real end"
1442        int realLength = length;
1443        for (int i = length - 1; i >= 0; i--) {
1444            if (text.charAt(i) == ' ') {
1445                realLength--;
1446            } else {
1447                break;
1448            }
1449        }
1450
1451        // If the offset is beyond or at the end of the text,
1452        // leave it alone.
1453        if (offset >= realLength) {
1454            return offset;
1455        }
1456        Editable editable = getText();
1457        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1458            // Keep walking backward!
1459            offset--;
1460        }
1461        return offset;
1462    }
1463
1464    private int findText(Editable text, int offset) {
1465        if (text.charAt(offset) != ' ') {
1466            return offset;
1467        }
1468        return -1;
1469    }
1470
1471    private RecipientChip findChip(int offset) {
1472        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1473        // Find the chip that contains this offset.
1474        for (int i = 0; i < chips.length; i++) {
1475            RecipientChip chip = chips[i];
1476            int start = getChipStart(chip);
1477            int end = getChipEnd(chip);
1478            if (offset >= start && offset <= end) {
1479                return chip;
1480            }
1481        }
1482        return null;
1483    }
1484
1485    // Visible for testing.
1486    // Use this method to generate text to add to the list of addresses.
1487    /* package */String createAddressText(RecipientEntry entry) {
1488        String display = entry.getDisplayName();
1489        String address = entry.getDestination();
1490        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1491            display = null;
1492        }
1493        String trimmedDisplayText;
1494        if (isPhoneQuery() && isPhoneNumber(address)) {
1495            trimmedDisplayText = address.trim();
1496        } else {
1497            if (address != null) {
1498                // Tokenize out the address in case the address already
1499                // contained the username as well.
1500                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1501                if (tokenized != null && tokenized.length > 0) {
1502                    address = tokenized[0].getAddress();
1503                }
1504            }
1505            Rfc822Token token = new Rfc822Token(display, address, null);
1506            trimmedDisplayText = token.toString().trim();
1507        }
1508        int index = trimmedDisplayText.indexOf(",");
1509        return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1510                && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1511                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1512    }
1513
1514    // Visible for testing.
1515    // Use this method to generate text to display in a chip.
1516    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1517        String display = entry.getDisplayName();
1518        String address = entry.getDestination();
1519        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1520            display = null;
1521        }
1522        if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) {
1523            // Tokenize out the address in case the address already
1524            // contained the username as well.
1525            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1526            if (tokenized != null && tokenized.length > 0) {
1527                address = tokenized[0].getAddress();
1528            }
1529        }
1530        if (!TextUtils.isEmpty(display)) {
1531            return display;
1532        } else if (!TextUtils.isEmpty(address)){
1533            return address;
1534        } else {
1535            return new Rfc822Token(display, address, null).toString();
1536        }
1537    }
1538
1539    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1540        String displayText = createAddressText(entry);
1541        if (TextUtils.isEmpty(displayText)) {
1542            return null;
1543        }
1544        SpannableString chipText = null;
1545        // Always leave a blank space at the end of a chip.
1546        int end = getSelectionEnd();
1547        int start = mTokenizer.findTokenStart(getText(), end);
1548        int textLength = displayText.length()-1;
1549        chipText = new SpannableString(displayText);
1550        if (!mNoChips) {
1551            try {
1552                RecipientChip chip = constructChipSpan(entry, start, pressed);
1553                chipText.setSpan(chip, 0, textLength,
1554                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1555                chip.setOriginalText(chipText.toString());
1556            } catch (NullPointerException e) {
1557                Log.e(TAG, e.getMessage(), e);
1558                return null;
1559            }
1560        }
1561        return chipText;
1562    }
1563
1564    /**
1565     * When an item in the suggestions list has been clicked, create a chip from the
1566     * contact information of the selected item.
1567     */
1568    @Override
1569    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1570        submitItemAtPosition(position);
1571    }
1572
1573    private void submitItemAtPosition(int position) {
1574        RecipientEntry entry = createValidatedEntry(
1575                (RecipientEntry)getAdapter().getItem(position));
1576        if (entry == null) {
1577            return;
1578        }
1579        clearComposingText();
1580
1581        int end = getSelectionEnd();
1582        int start = mTokenizer.findTokenStart(getText(), end);
1583
1584        Editable editable = getText();
1585        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1586        CharSequence chip = createChip(entry, false);
1587        if (chip != null && start >= 0 && end >= 0) {
1588            editable.replace(start, end, chip);
1589        }
1590        sanitizeBetween();
1591    }
1592
1593    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1594        if (item == null) {
1595            return null;
1596        }
1597        final RecipientEntry entry;
1598        // If the display name and the address are the same, or if this is a
1599        // valid contact, but the destination is invalid, then make this a fake
1600        // recipient that is editable.
1601        String destination = item.getDestination();
1602        if (RecipientEntry.isCreatedRecipient(item.getContactId())
1603                && (TextUtils.isEmpty(item.getDisplayName())
1604                        || TextUtils.equals(item.getDisplayName(), destination)
1605                        || (mValidator != null && !mValidator.isValid(destination)))) {
1606            entry = RecipientEntry.constructFakeEntry(destination);
1607        } else {
1608            entry = item;
1609        }
1610        return entry;
1611    }
1612
1613    /** Returns a collection of contact Id for each chip inside this View. */
1614    /* package */ Collection<Long> getContactIds() {
1615        final Set<Long> result = new HashSet<Long>();
1616        RecipientChip[] chips = getSortedRecipients();
1617        if (chips != null) {
1618            for (RecipientChip chip : chips) {
1619                result.add(chip.getContactId());
1620            }
1621        }
1622        return result;
1623    }
1624
1625
1626    /** Returns a collection of data Id for each chip inside this View. May be null. */
1627    /* package */ Collection<Long> getDataIds() {
1628        final Set<Long> result = new HashSet<Long>();
1629        RecipientChip [] chips = getSortedRecipients();
1630        if (chips != null) {
1631            for (RecipientChip chip : chips) {
1632                result.add(chip.getDataId());
1633            }
1634        }
1635        return result;
1636    }
1637
1638    // Visible for testing.
1639    /* package */RecipientChip[] getSortedRecipients() {
1640        RecipientChip[] recips = getSpannable()
1641                .getSpans(0, getText().length(), RecipientChip.class);
1642        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1643                .asList(recips));
1644        final Spannable spannable = getSpannable();
1645        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1646
1647            @Override
1648            public int compare(RecipientChip first, RecipientChip second) {
1649                int firstStart = spannable.getSpanStart(first);
1650                int secondStart = spannable.getSpanStart(second);
1651                if (firstStart < secondStart) {
1652                    return -1;
1653                } else if (firstStart > secondStart) {
1654                    return 1;
1655                } else {
1656                    return 0;
1657                }
1658            }
1659        });
1660        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1661    }
1662
1663    @Override
1664    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1665        return false;
1666    }
1667
1668    @Override
1669    public void onDestroyActionMode(ActionMode mode) {
1670    }
1671
1672    @Override
1673    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1674        return false;
1675    }
1676
1677    /**
1678     * No chips are selectable.
1679     */
1680    @Override
1681    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1682        return false;
1683    }
1684
1685    // Visible for testing.
1686    /* package */ImageSpan getMoreChip() {
1687        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1688                MoreImageSpan.class);
1689        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1690    }
1691
1692    private MoreImageSpan createMoreSpan(int count) {
1693        String moreText = String.format(mMoreItem.getText().toString(), count);
1694        TextPaint morePaint = new TextPaint(getPaint());
1695        morePaint.setTextSize(mMoreItem.getTextSize());
1696        morePaint.setColor(mMoreItem.getCurrentTextColor());
1697        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1698                + mMoreItem.getPaddingRight();
1699        int height = getLineHeight();
1700        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1701        Canvas canvas = new Canvas(drawable);
1702        int adjustedHeight = height;
1703        Layout layout = getLayout();
1704        if (layout != null) {
1705            adjustedHeight -= layout.getLineDescent(0);
1706        }
1707        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1708
1709        Drawable result = new BitmapDrawable(getResources(), drawable);
1710        result.setBounds(0, 0, width, height);
1711        return new MoreImageSpan(result);
1712    }
1713
1714    // Visible for testing.
1715    /*package*/ void createMoreChipPlainText() {
1716        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
1717        Editable text = getText();
1718        int start = 0;
1719        int end = start;
1720        for (int i = 0; i < CHIP_LIMIT; i++) {
1721            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1722            start = end; // move to the next token and get its end.
1723        }
1724        // Now, count total addresses.
1725        start = 0;
1726        int tokenCount = countTokens(text);
1727        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
1728        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
1729        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1730        text.replace(end, text.length(), chipText);
1731        mMoreChip = moreSpan;
1732    }
1733
1734    // Visible for testing.
1735    /* package */int countTokens(Editable text) {
1736        int tokenCount = 0;
1737        int start = 0;
1738        while (start < text.length()) {
1739            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1740            tokenCount++;
1741            if (start >= text.length()) {
1742                break;
1743            }
1744        }
1745        return tokenCount;
1746    }
1747
1748    /**
1749     * Create the more chip. The more chip is text that replaces any chips that
1750     * do not fit in the pre-defined available space when the
1751     * RecipientEditTextView loses focus.
1752     */
1753    // Visible for testing.
1754    /* package */ void createMoreChip() {
1755        if (mNoChips) {
1756            createMoreChipPlainText();
1757            return;
1758        }
1759
1760        if (!mShouldShrink) {
1761            return;
1762        }
1763
1764        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1765        if (tempMore.length > 0) {
1766            getSpannable().removeSpan(tempMore[0]);
1767        }
1768        RecipientChip[] recipients = getSortedRecipients();
1769
1770        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1771            mMoreChip = null;
1772            return;
1773        }
1774        Spannable spannable = getSpannable();
1775        int numRecipients = recipients.length;
1776        int overage = numRecipients - CHIP_LIMIT;
1777        MoreImageSpan moreSpan = createMoreSpan(overage);
1778        mRemovedSpans = new ArrayList<RecipientChip>();
1779        int totalReplaceStart = 0;
1780        int totalReplaceEnd = 0;
1781        Editable text = getText();
1782        for (int i = numRecipients - overage; i < recipients.length; i++) {
1783            mRemovedSpans.add(recipients[i]);
1784            if (i == numRecipients - overage) {
1785                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1786            }
1787            if (i == recipients.length - 1) {
1788                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1789            }
1790            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1791                int spanStart = spannable.getSpanStart(recipients[i]);
1792                int spanEnd = spannable.getSpanEnd(recipients[i]);
1793                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1794            }
1795            spannable.removeSpan(recipients[i]);
1796        }
1797        if (totalReplaceEnd < text.length()) {
1798            totalReplaceEnd = text.length();
1799        }
1800        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1801        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1802        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1803        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1804        text.replace(start, end, chipText);
1805        mMoreChip = moreSpan;
1806    }
1807
1808    /**
1809     * Replace the more chip, if it exists, with all of the recipient chips it had
1810     * replaced when the RecipientEditTextView gains focus.
1811     */
1812    // Visible for testing.
1813    /*package*/ void removeMoreChip() {
1814        if (mMoreChip != null) {
1815            Spannable span = getSpannable();
1816            span.removeSpan(mMoreChip);
1817            mMoreChip = null;
1818            // Re-add the spans that were removed.
1819            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1820                // Recreate each removed span.
1821                RecipientChip[] recipients = getSortedRecipients();
1822                // Start the search for tokens after the last currently visible
1823                // chip.
1824                if (recipients == null || recipients.length == 0) {
1825                    return;
1826                }
1827                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1828                Editable editable = getText();
1829                for (RecipientChip chip : mRemovedSpans) {
1830                    int chipStart;
1831                    int chipEnd;
1832                    String token;
1833                    // Need to find the location of the chip, again.
1834                    token = (String) chip.getOriginalText();
1835                    // As we find the matching recipient for the remove spans,
1836                    // reduce the size of the string we need to search.
1837                    // That way, if there are duplicates, we always find the correct
1838                    // recipient.
1839                    chipStart = editable.toString().indexOf(token, end);
1840                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1841                    // Only set the span if we found a matching token.
1842                    if (chipStart != -1) {
1843                        editable.setSpan(chip, chipStart, chipEnd,
1844                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1845                    }
1846                }
1847                mRemovedSpans.clear();
1848            }
1849        }
1850    }
1851
1852    /**
1853     * Show specified chip as selected. If the RecipientChip is just an email address,
1854     * selecting the chip will take the contents of the chip and place it at
1855     * the end of the RecipientEditTextView for inline editing. If the
1856     * RecipientChip is a complete contact, then selecting the chip
1857     * will change the background color of the chip, show the delete icon,
1858     * and a popup window with the address in use highlighted and any other
1859     * alternate addresses for the contact.
1860     * @param currentChip Chip to select.
1861     * @return A RecipientChip in the selected state or null if the chip
1862     * just contained an email address.
1863     */
1864    private RecipientChip selectChip(RecipientChip currentChip) {
1865        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1866            CharSequence text = currentChip.getValue();
1867            Editable editable = getText();
1868            removeChip(currentChip);
1869            editable.append(text);
1870            setCursorVisible(true);
1871            setSelection(editable.length());
1872            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1873        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1874            int start = getChipStart(currentChip);
1875            int end = getChipEnd(currentChip);
1876            getSpannable().removeSpan(currentChip);
1877            RecipientChip newChip;
1878            try {
1879                if (mNoChips) {
1880                    return null;
1881                }
1882                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1883            } catch (NullPointerException e) {
1884                Log.e(TAG, e.getMessage(), e);
1885                return null;
1886            }
1887            Editable editable = getText();
1888            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1889            if (start == -1 || end == -1) {
1890                Log.d(TAG, "The chip being selected no longer exists but should.");
1891            } else {
1892                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1893            }
1894            newChip.setSelected(true);
1895            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1896                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1897            }
1898            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1899            setCursorVisible(false);
1900            return newChip;
1901        } else {
1902            int start = getChipStart(currentChip);
1903            int end = getChipEnd(currentChip);
1904            getSpannable().removeSpan(currentChip);
1905            RecipientChip newChip;
1906            try {
1907                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1908            } catch (NullPointerException e) {
1909                Log.e(TAG, e.getMessage(), e);
1910                return null;
1911            }
1912            Editable editable = getText();
1913            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1914            if (start == -1 || end == -1) {
1915                Log.d(TAG, "The chip being selected no longer exists but should.");
1916            } else {
1917                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1918            }
1919            newChip.setSelected(true);
1920            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1921                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1922            }
1923            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1924            setCursorVisible(false);
1925            return newChip;
1926        }
1927    }
1928
1929
1930    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1931            int width, Context context) {
1932        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1933        int bottom = calculateOffsetFromBottom(line);
1934        // Align the alternates popup with the left side of the View,
1935        // regardless of the position of the chip tapped.
1936        popup.setWidth(width);
1937        popup.setAnchorView(this);
1938        popup.setVerticalOffset(bottom);
1939        popup.setAdapter(createSingleAddressAdapter(currentChip));
1940        popup.setOnItemClickListener(new OnItemClickListener() {
1941            @Override
1942            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1943                unselectChip(currentChip);
1944                popup.dismiss();
1945            }
1946        });
1947        popup.show();
1948        ListView listView = popup.getListView();
1949        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1950        listView.setItemChecked(0, true);
1951    }
1952
1953    /**
1954     * Remove selection from this chip. Unselecting a RecipientChip will render
1955     * the chip without a delete icon and with an unfocused background. This is
1956     * called when the RecipientChip no longer has focus.
1957     */
1958    private void unselectChip(RecipientChip chip) {
1959        int start = getChipStart(chip);
1960        int end = getChipEnd(chip);
1961        Editable editable = getText();
1962        mSelectedChip = null;
1963        if (start == -1 || end == -1) {
1964            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
1965            setSelection(editable.length());
1966            commitDefault();
1967        } else {
1968            getSpannable().removeSpan(chip);
1969            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1970            editable.removeSpan(chip);
1971            try {
1972                if (!mNoChips) {
1973                    editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1974                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1975                }
1976            } catch (NullPointerException e) {
1977                Log.e(TAG, e.getMessage(), e);
1978            }
1979        }
1980        setCursorVisible(true);
1981        setSelection(editable.length());
1982        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1983            mAlternatesPopup.dismiss();
1984        }
1985    }
1986
1987    /**
1988     * Return whether a touch event was inside the delete target of
1989     * a selected chip. It is in the delete target if:
1990     * 1) the x and y points of the event are within the
1991     * delete assset.
1992     * 2) the point tapped would have caused a cursor to appear
1993     * right after the selected chip.
1994     * @return boolean
1995     */
1996    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1997        // Figure out the bounds of this chip and whether or not
1998        // the user clicked in the X portion.
1999        return chip.isSelected() && offset == getChipEnd(chip);
2000    }
2001
2002    /**
2003     * Remove the chip and any text associated with it from the RecipientEditTextView.
2004     */
2005    // Visible for testing.
2006    /*pacakge*/ void removeChip(RecipientChip chip) {
2007        Spannable spannable = getSpannable();
2008        int spanStart = spannable.getSpanStart(chip);
2009        int spanEnd = spannable.getSpanEnd(chip);
2010        Editable text = getText();
2011        int toDelete = spanEnd;
2012        boolean wasSelected = chip == mSelectedChip;
2013        // Clear that there is a selected chip before updating any text.
2014        if (wasSelected) {
2015            mSelectedChip = null;
2016        }
2017        // Always remove trailing spaces when removing a chip.
2018        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2019            toDelete++;
2020        }
2021        spannable.removeSpan(chip);
2022        if (spanStart >= 0 && toDelete > 0) {
2023            text.delete(spanStart, toDelete);
2024        }
2025        if (wasSelected) {
2026            clearSelectedChip();
2027        }
2028    }
2029
2030    /**
2031     * Replace this currently selected chip with a new chip
2032     * that uses the contact data provided.
2033     */
2034    // Visible for testing.
2035    /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) {
2036        boolean wasSelected = chip == mSelectedChip;
2037        if (wasSelected) {
2038            mSelectedChip = null;
2039        }
2040        int start = getChipStart(chip);
2041        int end = getChipEnd(chip);
2042        getSpannable().removeSpan(chip);
2043        Editable editable = getText();
2044        CharSequence chipText = createChip(entry, false);
2045        if (chipText != null) {
2046            if (start == -1 || end == -1) {
2047                Log.e(TAG, "The chip to replace does not exist but should.");
2048                editable.insert(0, chipText);
2049            } else {
2050                if (!TextUtils.isEmpty(chipText)) {
2051                    // There may be a space to replace with this chip's new
2052                    // associated space. Check for it
2053                    int toReplace = end;
2054                    while (toReplace >= 0 && toReplace < editable.length()
2055                            && editable.charAt(toReplace) == ' ') {
2056                        toReplace++;
2057                    }
2058                    editable.replace(start, toReplace, chipText);
2059                }
2060            }
2061        }
2062        setCursorVisible(true);
2063        if (wasSelected) {
2064            clearSelectedChip();
2065        }
2066    }
2067
2068    /**
2069     * Handle click events for a chip. When a selected chip receives a click
2070     * event, see if that event was in the delete icon. If so, delete it.
2071     * Otherwise, unselect the chip.
2072     */
2073    public void onClick(RecipientChip chip, int offset, float x, float y) {
2074        if (chip.isSelected()) {
2075            if (isInDelete(chip, offset, x, y)) {
2076                removeChip(chip);
2077            } else {
2078                clearSelectedChip();
2079            }
2080        }
2081    }
2082
2083    private boolean chipsPending() {
2084        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2085    }
2086
2087    @Override
2088    public void removeTextChangedListener(TextWatcher watcher) {
2089        mTextWatcher = null;
2090        super.removeTextChangedListener(watcher);
2091    }
2092
2093    private class RecipientTextWatcher implements TextWatcher {
2094
2095        @Override
2096        public void afterTextChanged(Editable s) {
2097            // If the text has been set to null or empty, make sure we remove
2098            // all the spans we applied.
2099            if (TextUtils.isEmpty(s)) {
2100                // Remove all the chips spans.
2101                Spannable spannable = getSpannable();
2102                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
2103                        RecipientChip.class);
2104                for (RecipientChip chip : chips) {
2105                    spannable.removeSpan(chip);
2106                }
2107                if (mMoreChip != null) {
2108                    spannable.removeSpan(mMoreChip);
2109                }
2110                return;
2111            }
2112            // Get whether there are any recipients pending addition to the
2113            // view. If there are, don't do anything in the text watcher.
2114            if (chipsPending()) {
2115                return;
2116            }
2117            // If the user is editing a chip, don't clear it.
2118            if (mSelectedChip != null
2119                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
2120                setCursorVisible(true);
2121                setSelection(getText().length());
2122                clearSelectedChip();
2123            }
2124            int length = s.length();
2125            // Make sure there is content there to parse and that it is
2126            // not just the commit character.
2127            if (length > 1) {
2128                char last;
2129                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2130                int len = length() - 1;
2131                if (end != len) {
2132                    last = s.charAt(end);
2133                } else {
2134                    last = s.charAt(len);
2135                }
2136                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
2137                    commitByCharacter();
2138                } else if (last == COMMIT_CHAR_SPACE) {
2139                    if (!isPhoneQuery()) {
2140                        // Check if this is a valid email address. If it is,
2141                        // commit it.
2142                        String text = getText().toString();
2143                        int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2144                        String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2145                                tokenStart));
2146                        if (!TextUtils.isEmpty(sub) && mValidator != null &&
2147                                mValidator.isValid(sub)) {
2148                            commitByCharacter();
2149                        }
2150                    }
2151                }
2152            }
2153        }
2154
2155        @Override
2156        public void onTextChanged(CharSequence s, int start, int before, int count) {
2157            // This is a delete; check to see if the insertion point is on a space
2158            // following a chip.
2159            if (before > count) {
2160                // If the item deleted is a space, and the thing before the
2161                // space is a chip, delete the entire span.
2162                int selStart = getSelectionStart();
2163                RecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2164                        RecipientChip.class);
2165                if (repl.length > 0) {
2166                    // There is a chip there! Just remove it.
2167                    Editable editable = getText();
2168                    // Add the separator token.
2169                    int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2170                    int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
2171                    tokenEnd = tokenEnd + 1;
2172                    if (tokenEnd > editable.length()) {
2173                        tokenEnd = editable.length();
2174                    }
2175                    editable.delete(tokenStart, tokenEnd);
2176                    getSpannable().removeSpan(repl[0]);
2177                }
2178            } else if (count > before) {
2179                // Only scroll when the user is adding text, not clearing text.
2180                scrollBottomIntoView();
2181            }
2182        }
2183
2184        @Override
2185        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2186            // Do nothing.
2187        }
2188    }
2189
2190    private void scrollBottomIntoView() {
2191        if (mScrollView != null) {
2192            mScrollView.scrollBy(0, (int)(getLineCount() * mChipHeight));
2193        }
2194    }
2195
2196    /**
2197     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2198     */
2199    private void handlePasteClip(ClipData clip) {
2200        removeTextChangedListener(mTextWatcher);
2201
2202        if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
2203            for (int i = 0; i < clip.getItemCount(); i++) {
2204                CharSequence paste = clip.getItemAt(i).getText();
2205                if (paste != null) {
2206                    int start = getSelectionStart();
2207                    int end = getSelectionEnd();
2208                    Editable editable = getText();
2209                    if (start >= 0 && end >= 0 && start != end) {
2210                        editable.append(paste, start, end);
2211                    } else {
2212                        editable.insert(end, paste);
2213                    }
2214                    handlePasteAndReplace();
2215                }
2216            }
2217        }
2218
2219        mHandler.post(mAddTextWatcher);
2220    }
2221
2222    @Override
2223    public boolean onTextContextMenuItem(int id) {
2224        if (id == android.R.id.paste) {
2225            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2226                    Context.CLIPBOARD_SERVICE);
2227            handlePasteClip(clipboard.getPrimaryClip());
2228            return true;
2229        }
2230        return super.onTextContextMenuItem(id);
2231    }
2232
2233    private void handlePasteAndReplace() {
2234        ArrayList<RecipientChip> created = handlePaste();
2235        if (created != null && created.size() > 0) {
2236            // Perform reverse lookups on the pasted contacts.
2237            IndividualReplacementTask replace = new IndividualReplacementTask();
2238            replace.execute(created);
2239        }
2240    }
2241
2242    // Visible for testing.
2243    /* package */ArrayList<RecipientChip> handlePaste() {
2244        String text = getText().toString();
2245        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2246        String lastAddress = text.substring(originalTokenStart);
2247        int tokenStart = originalTokenStart;
2248        int prevTokenStart = tokenStart;
2249        RecipientChip findChip = null;
2250        ArrayList<RecipientChip> created = new ArrayList<RecipientChip>();
2251        if (tokenStart != 0) {
2252            // There are things before this!
2253            while (tokenStart != 0 && findChip == null) {
2254                prevTokenStart = tokenStart;
2255                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2256                findChip = findChip(tokenStart);
2257            }
2258            if (tokenStart != originalTokenStart) {
2259                if (findChip != null) {
2260                    tokenStart = prevTokenStart;
2261                }
2262                int tokenEnd;
2263                RecipientChip createdChip;
2264                while (tokenStart < originalTokenStart) {
2265                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2266                            tokenStart));
2267                    commitChip(tokenStart, tokenEnd, getText());
2268                    createdChip = findChip(tokenStart);
2269                    if (createdChip == null) {
2270                        break;
2271                    }
2272                    // +1 for the space at the end.
2273                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2274                    created.add(createdChip);
2275                }
2276            }
2277        }
2278        // Take a look at the last token. If the token has been completed with a
2279        // commit character, create a chip.
2280        if (isCompletedToken(lastAddress)) {
2281            Editable editable = getText();
2282            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2283            commitChip(tokenStart, editable.length(), editable);
2284            created.add(findChip(tokenStart));
2285        }
2286        return created;
2287    }
2288
2289    // Visible for testing.
2290    /* package */int movePastTerminators(int tokenEnd) {
2291        if (tokenEnd >= length()) {
2292            return tokenEnd;
2293        }
2294        char atEnd = getText().toString().charAt(tokenEnd);
2295        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2296            tokenEnd++;
2297        }
2298        // This token had not only an end token character, but also a space
2299        // separating it from the next token.
2300        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2301            tokenEnd++;
2302        }
2303        return tokenEnd;
2304    }
2305
2306    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2307        private RecipientChip createFreeChip(RecipientEntry entry) {
2308            try {
2309                if (mNoChips) {
2310                    return null;
2311                }
2312                return constructChipSpan(entry, -1, false);
2313            } catch (NullPointerException e) {
2314                Log.e(TAG, e.getMessage(), e);
2315                return null;
2316            }
2317        }
2318
2319        @Override
2320        protected Void doInBackground(Void... params) {
2321            if (mIndividualReplacements != null) {
2322                mIndividualReplacements.cancel(true);
2323            }
2324            // For each chip in the list, look up the matching contact.
2325            // If there is a match, replace that chip with the matching
2326            // chip.
2327            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
2328            RecipientChip[] existingChips = getSortedRecipients();
2329            for (int i = 0; i < existingChips.length; i++) {
2330                originalRecipients.add(existingChips[i]);
2331            }
2332            if (mRemovedSpans != null) {
2333                originalRecipients.addAll(mRemovedSpans);
2334            }
2335            ArrayList<String> addresses = new ArrayList<String>();
2336            RecipientChip chip;
2337            for (int i = 0; i < originalRecipients.size(); i++) {
2338                chip = originalRecipients.get(i);
2339                if (chip != null) {
2340                    addresses.add(createAddressText(chip.getEntry()));
2341                }
2342            }
2343            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2344                    .getMatchingRecipients(getContext(), addresses);
2345            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
2346            for (final RecipientChip temp : originalRecipients) {
2347                RecipientEntry entry = null;
2348                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2349                        && getSpannable().getSpanStart(temp) != -1) {
2350                    // Replace this.
2351                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
2352                            .getDestination())));
2353                }
2354                if (entry != null) {
2355                    replacements.add(createFreeChip(entry));
2356                } else {
2357                    replacements.add(temp);
2358                }
2359            }
2360            if (replacements != null && replacements.size() > 0) {
2361                mHandler.post(new Runnable() {
2362                    @Override
2363                    public void run() {
2364                        Editable oldText = getText();
2365                        int start, end;
2366                        int i = 0;
2367                        for (RecipientChip chip : originalRecipients) {
2368                            // Find the location of the chip in the text currently shown.
2369                            start = oldText.getSpanStart(chip);
2370                            if (start != -1) {
2371                                end = oldText.getSpanEnd(chip);
2372                                oldText.removeSpan(chip);
2373                                RecipientChip replacement = replacements.get(i);
2374                                // Trim any whitespace, as we will already have
2375                                // it added if these are replacement chips.
2376                                SpannableString displayText = new SpannableString(
2377                                        createAddressText(replacement.getEntry()).trim());
2378                                displayText.setSpan(replacement, 0, displayText.length(),
2379                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2380                                // Replace the old text we found with with the new display text,
2381                                // which now may also contain the display name of the recipient.
2382                                oldText.replace(start, end, displayText);
2383                                replacement.setOriginalText(displayText.toString());
2384                            }
2385                            i++;
2386                        }
2387                        originalRecipients.clear();
2388                    }
2389                });
2390            }
2391            return null;
2392        }
2393    }
2394
2395    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
2396        @SuppressWarnings("unchecked")
2397        @Override
2398        protected Void doInBackground(Object... params) {
2399            // For each chip in the list, look up the matching contact.
2400            // If there is a match, replace that chip with the matching
2401            // chip.
2402            final ArrayList<RecipientChip> originalRecipients =
2403                (ArrayList<RecipientChip>) params[0];
2404            ArrayList<String> addresses = new ArrayList<String>();
2405            RecipientChip chip;
2406            for (int i = 0; i < originalRecipients.size(); i++) {
2407                chip = originalRecipients.get(i);
2408                if (chip != null) {
2409                    addresses.add(createAddressText(chip.getEntry()));
2410                }
2411            }
2412            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2413                    .getMatchingRecipients(getContext(), addresses);
2414            for (final RecipientChip temp : originalRecipients) {
2415                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2416                        && getSpannable().getSpanStart(temp) != -1) {
2417                    // Replace this.
2418                    final RecipientEntry entry = createValidatedEntry(entries.get(tokenizeAddress(
2419                            temp.getEntry().getDestination()).toLowerCase()));
2420                    if (entry != null) {
2421                        mHandler.post(new Runnable() {
2422                            @Override
2423                            public void run() {
2424                                replaceChip(temp, entry);
2425                            }
2426                        });
2427                    }
2428                }
2429            }
2430            return null;
2431        }
2432    }
2433
2434
2435    /**
2436     * MoreImageSpan is a simple class created for tracking the existence of a
2437     * more chip across activity restarts/
2438     */
2439    private class MoreImageSpan extends ImageSpan {
2440        public MoreImageSpan(Drawable b) {
2441            super(b);
2442        }
2443    }
2444
2445    @Override
2446    public boolean onDown(MotionEvent e) {
2447        return false;
2448    }
2449
2450    @Override
2451    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2452        // Do nothing.
2453        return false;
2454    }
2455
2456    @Override
2457    public void onLongPress(MotionEvent event) {
2458        if (mSelectedChip != null) {
2459            return;
2460        }
2461        float x = event.getX();
2462        float y = event.getY();
2463        int offset = putOffsetInRange(getOffsetForPosition(x, y));
2464        RecipientChip currentChip = findChip(offset);
2465        if (currentChip != null) {
2466            if (mDragEnabled) {
2467                // Start drag-and-drop for the selected chip.
2468                startDrag(currentChip);
2469            } else {
2470                // Copy the selected chip email address.
2471                showCopyDialog(currentChip.getEntry().getDestination());
2472            }
2473        }
2474    }
2475
2476    /**
2477     * Enables drag-and-drop for chips.
2478     */
2479    public void enableDrag() {
2480        mDragEnabled = true;
2481    }
2482
2483    /**
2484     * Starts drag-and-drop for the selected chip.
2485     */
2486    private void startDrag(RecipientChip currentChip) {
2487        String address = currentChip.getEntry().getDestination();
2488        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2489
2490        // Start drag mode.
2491        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2492
2493        // Remove the current chip, so drag-and-drop will result in a move.
2494        // TODO (phamm): consider readd this chip if it's dropped outside a target.
2495        removeChip(currentChip);
2496    }
2497
2498    /**
2499     * Handles drag event.
2500     */
2501    @Override
2502    public boolean onDragEvent(DragEvent event) {
2503        switch (event.getAction()) {
2504            case DragEvent.ACTION_DRAG_STARTED:
2505                // Only handle plain text drag and drop.
2506                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2507            case DragEvent.ACTION_DRAG_ENTERED:
2508                requestFocus();
2509                return true;
2510            case DragEvent.ACTION_DROP:
2511                handlePasteClip(event.getClipData());
2512                return true;
2513        }
2514        return false;
2515    }
2516
2517    /**
2518     * Drag shadow for a {@link RecipientChip}.
2519     */
2520    private final class RecipientChipShadow extends DragShadowBuilder {
2521        private final RecipientChip mChip;
2522
2523        public RecipientChipShadow(RecipientChip chip) {
2524            mChip = chip;
2525        }
2526
2527        @Override
2528        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
2529            Rect rect = mChip.getDrawable().getBounds();
2530            shadowSize.set(rect.width(), rect.height());
2531            shadowTouchPoint.set(rect.centerX(), rect.centerY());
2532        }
2533
2534        @Override
2535        public void onDrawShadow(Canvas canvas) {
2536            mChip.getDrawable().draw(canvas);
2537        }
2538    }
2539
2540    private void showCopyDialog(final String address) {
2541        mCopyAddress = address;
2542        mCopyDialog.setTitle(address);
2543        mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
2544        mCopyDialog.setCancelable(true);
2545        mCopyDialog.setCanceledOnTouchOutside(true);
2546        Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
2547        button.setOnClickListener(this);
2548        int btnTitleId;
2549        if (isPhoneQuery()) {
2550            btnTitleId = R.string.copy_number;
2551        } else {
2552            btnTitleId = R.string.copy_email;
2553        }
2554        String buttonTitle = getContext().getResources().getString(btnTitleId);
2555        button.setText(buttonTitle);
2556        mCopyDialog.setOnDismissListener(this);
2557        mCopyDialog.show();
2558    }
2559
2560    @Override
2561    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
2562        // Do nothing.
2563        return false;
2564    }
2565
2566    @Override
2567    public void onShowPress(MotionEvent e) {
2568        // Do nothing.
2569    }
2570
2571    @Override
2572    public boolean onSingleTapUp(MotionEvent e) {
2573        // Do nothing.
2574        return false;
2575    }
2576
2577    @Override
2578    public void onDismiss(DialogInterface dialog) {
2579        mCopyAddress = null;
2580    }
2581
2582    @Override
2583    public void onClick(View v) {
2584        // Copy this to the clipboard.
2585        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2586                Context.CLIPBOARD_SERVICE);
2587        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
2588        mCopyDialog.dismiss();
2589    }
2590
2591    protected boolean isPhoneQuery() {
2592        return getAdapter() != null
2593                && ((BaseRecipientAdapter) getAdapter()).getQueryType()
2594                    == BaseRecipientAdapter.QUERY_TYPE_PHONE;
2595    }
2596}
2597