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