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