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