RecipientEditTextView.java revision 03cfe3eee5635e419ab1d70d463b2b8beac72f00
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 && mSelectedChip != null) {
996            clearSelectedChip();
997            return true;
998        }
999        return super.onKeyPreIme(keyCode, event);
1000    }
1001
1002    /**
1003     * Monitor key presses in this view to see if the user types
1004     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
1005     * If the user has entered text that has contact matches and types
1006     * a commit key, create a chip from the topmost matching contact.
1007     * If the user has entered text that has no contact matches and types
1008     * a commit key, then create a chip from the text they have entered.
1009     */
1010    @Override
1011    public boolean onKeyUp(int keyCode, KeyEvent event) {
1012        switch (keyCode) {
1013            case KeyEvent.KEYCODE_ENTER:
1014            case KeyEvent.KEYCODE_DPAD_CENTER:
1015                if (event.hasNoModifiers()) {
1016                    if (commitDefault()) {
1017                        return true;
1018                    }
1019                    if (mSelectedChip != null) {
1020                        clearSelectedChip();
1021                        return true;
1022                    } else if (focusNext()) {
1023                        return true;
1024                    }
1025                }
1026                break;
1027            case KeyEvent.KEYCODE_TAB:
1028                if (event.hasNoModifiers()) {
1029                    if (mSelectedChip != null) {
1030                        clearSelectedChip();
1031                    } else {
1032                        commitDefault();
1033                    }
1034                    if (focusNext()) {
1035                        return true;
1036                    }
1037                }
1038                break;
1039        }
1040        return super.onKeyUp(keyCode, event);
1041    }
1042
1043    private boolean focusNext() {
1044        View next = focusSearch(View.FOCUS_DOWN);
1045        if (next != null) {
1046            next.requestFocus();
1047            return true;
1048        }
1049        return false;
1050    }
1051
1052    /**
1053     * Create a chip from the default selection. If the popup is showing, the
1054     * default is the first item in the popup suggestions list. Otherwise, it is
1055     * whatever the user had typed in. End represents where the the tokenizer
1056     * should search for a token to turn into a chip.
1057     * @return If a chip was created from a real contact.
1058     */
1059    private boolean commitDefault() {
1060        // If there is no tokenizer, don't try to commit.
1061        if (mTokenizer == null) {
1062            return false;
1063        }
1064        Editable editable = getText();
1065        int end = getSelectionEnd();
1066        int start = mTokenizer.findTokenStart(editable, end);
1067
1068        if (shouldCreateChip(start, end)) {
1069            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1070            // In the middle of chip; treat this as an edit
1071            // and commit the whole token.
1072            if (whatEnd != getSelectionEnd()) {
1073                handleEdit(start, whatEnd);
1074                return true;
1075            }
1076            return commitChip(start, end , editable);
1077        }
1078        return false;
1079    }
1080
1081    private void commitByCharacter() {
1082        // We can't possibly commit by character if we can't tokenize.
1083        if (mTokenizer == null) {
1084            return;
1085        }
1086        Editable editable = getText();
1087        int end = getSelectionEnd();
1088        int start = mTokenizer.findTokenStart(editable, end);
1089        if (shouldCreateChip(start, end)) {
1090            commitChip(start, end, editable);
1091        }
1092        setSelection(getText().length());
1093    }
1094
1095    private boolean commitChip(int start, int end, Editable editable) {
1096        ListAdapter adapter = getAdapter();
1097        if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
1098                && end == getSelectionEnd() && !isPhoneQuery()) {
1099            // choose the first entry.
1100            submitItemAtPosition(0);
1101            dismissDropDown();
1102            return true;
1103        } else {
1104            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
1105            if (editable.length() > tokenEnd + 1) {
1106                char charAt = editable.charAt(tokenEnd + 1);
1107                if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1108                    tokenEnd++;
1109                }
1110            }
1111            String text = editable.toString().substring(start, tokenEnd).trim();
1112            clearComposingText();
1113            if (text != null && text.length() > 0 && !text.equals(" ")) {
1114                RecipientEntry entry = createTokenizedEntry(text);
1115                if (entry != null) {
1116                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
1117                    CharSequence chipText = createChip(entry, false);
1118                    if (chipText != null && start > -1 && end > -1) {
1119                        editable.replace(start, end, chipText);
1120                    }
1121                }
1122                // Only dismiss the dropdown if it is related to the text we
1123                // just committed.
1124                // For paste, it may not be as there are possibly multiple
1125                // tokens being added.
1126                if (end == getSelectionEnd()) {
1127                    dismissDropDown();
1128                }
1129                sanitizeBetween();
1130                return true;
1131            }
1132        }
1133        return false;
1134    }
1135
1136    // Visible for testing.
1137    /* package */ void sanitizeBetween() {
1138        // Don't sanitize while we are waiting for content to chipify.
1139        if (mPendingChipsCount > 0) {
1140            return;
1141        }
1142        // Find the last chip.
1143        RecipientChip[] recips = getSortedRecipients();
1144        if (recips != null && recips.length > 0) {
1145            RecipientChip last = recips[recips.length - 1];
1146            RecipientChip beforeLast = null;
1147            if (recips.length > 1) {
1148                beforeLast = recips[recips.length - 2];
1149            }
1150            int startLooking = 0;
1151            int end = getSpannable().getSpanStart(last);
1152            if (beforeLast != null) {
1153                startLooking = getSpannable().getSpanEnd(beforeLast);
1154                Editable text = getText();
1155                if (startLooking == -1 || startLooking > text.length() - 1) {
1156                    // There is nothing after this chip.
1157                    return;
1158                }
1159                if (text.charAt(startLooking) == ' ') {
1160                    startLooking++;
1161                }
1162            }
1163            if (startLooking >= 0 && end >= 0 && startLooking < end) {
1164                getText().delete(startLooking, end);
1165            }
1166        }
1167    }
1168
1169    private boolean shouldCreateChip(int start, int end) {
1170        return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
1171    }
1172
1173    private boolean alreadyHasChip(int start, int end) {
1174        if (mNoChips) {
1175            return true;
1176        }
1177        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
1178        if ((chips == null || chips.length == 0)) {
1179            return false;
1180        }
1181        return true;
1182    }
1183
1184    private void handleEdit(int start, int end) {
1185        if (start == -1 || end == -1) {
1186            // This chip no longer exists in the field.
1187            dismissDropDown();
1188            return;
1189        }
1190        // This is in the middle of a chip, so select out the whole chip
1191        // and commit it.
1192        Editable editable = getText();
1193        setSelection(end);
1194        String text = getText().toString().substring(start, end);
1195        if (!TextUtils.isEmpty(text)) {
1196            RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
1197            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1198            CharSequence chipText = createChip(entry, false);
1199            int selEnd = getSelectionEnd();
1200            if (chipText != null && start > -1 && selEnd > -1) {
1201                editable.replace(start, selEnd, chipText);
1202            }
1203        }
1204        dismissDropDown();
1205    }
1206
1207    /**
1208     * If there is a selected chip, delegate the key events
1209     * to the selected chip.
1210     */
1211    @Override
1212    public boolean onKeyDown(int keyCode, KeyEvent event) {
1213        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1214            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1215                mAlternatesPopup.dismiss();
1216            }
1217            removeChip(mSelectedChip);
1218        }
1219
1220        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
1221            return true;
1222        }
1223
1224        return super.onKeyDown(keyCode, event);
1225    }
1226
1227    // Visible for testing.
1228    /* package */ Spannable getSpannable() {
1229        return getText();
1230    }
1231
1232    private int getChipStart(RecipientChip chip) {
1233        return getSpannable().getSpanStart(chip);
1234    }
1235
1236    private int getChipEnd(RecipientChip chip) {
1237        return getSpannable().getSpanEnd(chip);
1238    }
1239
1240    /**
1241     * Instead of filtering on the entire contents of the edit box,
1242     * this subclass method filters on the range from
1243     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1244     * if the length of that range meets or exceeds {@link #getThreshold}
1245     * and makes sure that the range is not already a Chip.
1246     */
1247    @Override
1248    protected void performFiltering(CharSequence text, int keyCode) {
1249        if (enoughToFilter() && !isCompletedToken(text)) {
1250            int end = getSelectionEnd();
1251            int start = mTokenizer.findTokenStart(text, end);
1252            // If this is a RecipientChip, don't filter
1253            // on its contents.
1254            Spannable span = getSpannable();
1255            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
1256            if (chips != null && chips.length > 0) {
1257                return;
1258            }
1259        }
1260        super.performFiltering(text, keyCode);
1261    }
1262
1263    // Visible for testing.
1264    /*package*/ boolean isCompletedToken(CharSequence text) {
1265        if (TextUtils.isEmpty(text)) {
1266            return false;
1267        }
1268        // Check to see if this is a completed token before filtering.
1269        int end = text.length();
1270        int start = mTokenizer.findTokenStart(text, end);
1271        String token = text.toString().substring(start, end).trim();
1272        if (!TextUtils.isEmpty(token)) {
1273            char atEnd = token.charAt(token.length() - 1);
1274            return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1275        }
1276        return false;
1277    }
1278
1279    private void clearSelectedChip() {
1280        if (mSelectedChip != null) {
1281            unselectChip(mSelectedChip);
1282            mSelectedChip = null;
1283        }
1284        setCursorVisible(true);
1285    }
1286
1287    /**
1288     * Monitor touch events in the RecipientEditTextView.
1289     * If the view does not have focus, any tap on the view
1290     * will just focus the view. If the view has focus, determine
1291     * if the touch target is a recipient chip. If it is and the chip
1292     * is not selected, select it and clear any other selected chips.
1293     * If it isn't, then select that chip.
1294     */
1295    @Override
1296    public boolean onTouchEvent(MotionEvent event) {
1297        if (!isFocused()) {
1298            // Ignore any chip taps until this view is focused.
1299            return super.onTouchEvent(event);
1300        }
1301        boolean handled = super.onTouchEvent(event);
1302        int action = event.getAction();
1303        boolean chipWasSelected = false;
1304        if (mSelectedChip == null) {
1305            mGestureDetector.onTouchEvent(event);
1306        }
1307        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1308            float x = event.getX();
1309            float y = event.getY();
1310            int offset = putOffsetInRange(getOffsetForPosition(x, y));
1311            RecipientChip currentChip = findChip(offset);
1312            if (currentChip != null) {
1313                if (action == MotionEvent.ACTION_UP) {
1314                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1315                        clearSelectedChip();
1316                        mSelectedChip = selectChip(currentChip);
1317                    } else if (mSelectedChip == null) {
1318                        setSelection(getText().length());
1319                        commitDefault();
1320                        mSelectedChip = selectChip(currentChip);
1321                    } else {
1322                        onClick(mSelectedChip, offset, x, y);
1323                    }
1324                }
1325                chipWasSelected = true;
1326                handled = true;
1327            } else if (mSelectedChip != null
1328                    && mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1329                chipWasSelected = true;
1330            }
1331        }
1332        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1333            clearSelectedChip();
1334        }
1335        return handled;
1336    }
1337
1338    private void scrollLineIntoView(int line) {
1339        if (mScrollView != null) {
1340            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1341        }
1342    }
1343
1344    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1345            int width, Context context) {
1346        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1347        int bottom = calculateOffsetFromBottom(line);
1348        // Align the alternates popup with the left side of the View,
1349        // regardless of the position of the chip tapped.
1350        alternatesPopup.setWidth(width);
1351        setEnabled(false);
1352        alternatesPopup.setAnchorView(this);
1353        alternatesPopup.setVerticalOffset(bottom);
1354        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1355        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1356        // Clear the checked item.
1357        mCheckedItem = -1;
1358        alternatesPopup.show();
1359        ListView listView = alternatesPopup.getListView();
1360        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1361        // Checked item would be -1 if the adapter has not
1362        // loaded the view that should be checked yet. The
1363        // variable will be set correctly when onCheckedItemChanged
1364        // is called in a separate thread.
1365        if (mCheckedItem != -1) {
1366            listView.setItemChecked(mCheckedItem, true);
1367            mCheckedItem = -1;
1368        }
1369    }
1370
1371    // Dismiss listener for alterns and single address popup.
1372    @Override
1373    public void onDismiss() {
1374        setEnabled(true);
1375    }
1376
1377    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1378        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1379                mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this);
1380    }
1381
1382    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1383        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1384                .getEntry());
1385    }
1386
1387    @Override
1388    public void onCheckedItemChanged(int position) {
1389        ListView listView = mAlternatesPopup.getListView();
1390        if (listView != null && listView.getCheckedItemCount() == 0) {
1391            listView.setItemChecked(position, true);
1392        }
1393        mCheckedItem = position;
1394    }
1395
1396    // TODO: This algorithm will need a lot of tweaking after more people have used
1397    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1398    // what comes before the finger.
1399    private int putOffsetInRange(int o) {
1400        int offset = o;
1401        Editable text = getText();
1402        int length = text.length();
1403        // Remove whitespace from end to find "real end"
1404        int realLength = length;
1405        for (int i = length - 1; i >= 0; i--) {
1406            if (text.charAt(i) == ' ') {
1407                realLength--;
1408            } else {
1409                break;
1410            }
1411        }
1412
1413        // If the offset is beyond or at the end of the text,
1414        // leave it alone.
1415        if (offset >= realLength) {
1416            return offset;
1417        }
1418        Editable editable = getText();
1419        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1420            // Keep walking backward!
1421            offset--;
1422        }
1423        return offset;
1424    }
1425
1426    private int findText(Editable text, int offset) {
1427        if (text.charAt(offset) != ' ') {
1428            return offset;
1429        }
1430        return -1;
1431    }
1432
1433    private RecipientChip findChip(int offset) {
1434        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1435        // Find the chip that contains this offset.
1436        for (int i = 0; i < chips.length; i++) {
1437            RecipientChip chip = chips[i];
1438            int start = getChipStart(chip);
1439            int end = getChipEnd(chip);
1440            if (offset >= start && offset <= end) {
1441                return chip;
1442            }
1443        }
1444        return null;
1445    }
1446
1447    // Visible for testing.
1448    // Use this method to generate text to add to the list of addresses.
1449    /* package */String createAddressText(RecipientEntry entry) {
1450        String display = entry.getDisplayName();
1451        String address = entry.getDestination();
1452        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1453            display = null;
1454        }
1455        String trimmedDisplayText;
1456        if (isPhoneQuery() && isPhoneNumber(address)) {
1457            trimmedDisplayText = address.trim();
1458        } else {
1459            if (address != null) {
1460                // Tokenize out the address in case the address already
1461                // contained the username as well.
1462                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1463                if (tokenized != null && tokenized.length > 0) {
1464                    address = tokenized[0].getAddress();
1465                }
1466            }
1467            Rfc822Token token = new Rfc822Token(display, address, null);
1468            trimmedDisplayText = token.toString().trim();
1469        }
1470        int index = trimmedDisplayText.indexOf(",");
1471        return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1472                && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1473                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1474    }
1475
1476    // Visible for testing.
1477    // Use this method to generate text to display in a chip.
1478    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1479        String display = entry.getDisplayName();
1480        String address = entry.getDestination();
1481        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1482            display = null;
1483        }
1484        if (address != null && !(isPhoneQuery() && isPhoneNumber(address))) {
1485            // Tokenize out the address in case the address already
1486            // contained the username as well.
1487            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1488            if (tokenized != null && tokenized.length > 0) {
1489                address = tokenized[0].getAddress();
1490            }
1491        }
1492        if (!TextUtils.isEmpty(display)) {
1493            return display;
1494        } else if (!TextUtils.isEmpty(address)){
1495            return address;
1496        } else {
1497            return new Rfc822Token(display, address, null).toString();
1498        }
1499    }
1500
1501    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1502        String displayText = createAddressText(entry);
1503        if (TextUtils.isEmpty(displayText)) {
1504            return null;
1505        }
1506        SpannableString chipText = null;
1507        // Always leave a blank space at the end of a chip.
1508        int end = getSelectionEnd();
1509        int start = mTokenizer.findTokenStart(getText(), end);
1510        int textLength = displayText.length()-1;
1511        chipText = new SpannableString(displayText);
1512        if (!mNoChips) {
1513            try {
1514                RecipientChip chip = constructChipSpan(entry, start, pressed);
1515                chipText.setSpan(chip, 0, textLength,
1516                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1517                chip.setOriginalText(chipText.toString());
1518            } catch (NullPointerException e) {
1519                Log.e(TAG, e.getMessage(), e);
1520                return null;
1521            }
1522        }
1523        return chipText;
1524    }
1525
1526    /**
1527     * When an item in the suggestions list has been clicked, create a chip from the
1528     * contact information of the selected item.
1529     */
1530    @Override
1531    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1532        submitItemAtPosition(position);
1533    }
1534
1535    private void submitItemAtPosition(int position) {
1536        RecipientEntry entry = createValidatedEntry(
1537                (RecipientEntry)getAdapter().getItem(position));
1538        if (entry == null) {
1539            return;
1540        }
1541        clearComposingText();
1542
1543        int end = getSelectionEnd();
1544        int start = mTokenizer.findTokenStart(getText(), end);
1545
1546        Editable editable = getText();
1547        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1548        CharSequence chip = createChip(entry, false);
1549        if (chip != null && start >= 0 && end >= 0) {
1550            editable.replace(start, end, chip);
1551        }
1552        sanitizeBetween();
1553    }
1554
1555    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1556        if (item == null) {
1557            return null;
1558        }
1559        final RecipientEntry entry;
1560        // If the display name and the address are the same, or if this is a
1561        // valid contact, but the destination is invalid, then make this a fake
1562        // recipient that is editable.
1563        String destination = item.getDestination();
1564        if (RecipientEntry.isCreatedRecipient(item.getContactId())
1565                && (TextUtils.isEmpty(item.getDisplayName())
1566                        || TextUtils.equals(item.getDisplayName(), destination)
1567                        || (mValidator != null && !mValidator.isValid(destination)))) {
1568            entry = RecipientEntry.constructFakeEntry(destination);
1569        } else {
1570            entry = item;
1571        }
1572        return entry;
1573    }
1574
1575    /** Returns a collection of contact Id for each chip inside this View. */
1576    /* package */ Collection<Long> getContactIds() {
1577        final Set<Long> result = new HashSet<Long>();
1578        RecipientChip[] chips = getSortedRecipients();
1579        if (chips != null) {
1580            for (RecipientChip chip : chips) {
1581                result.add(chip.getContactId());
1582            }
1583        }
1584        return result;
1585    }
1586
1587
1588    /** Returns a collection of data Id for each chip inside this View. May be null. */
1589    /* package */ Collection<Long> getDataIds() {
1590        final Set<Long> result = new HashSet<Long>();
1591        RecipientChip [] chips = getSortedRecipients();
1592        if (chips != null) {
1593            for (RecipientChip chip : chips) {
1594                result.add(chip.getDataId());
1595            }
1596        }
1597        return result;
1598    }
1599
1600    // Visible for testing.
1601    /* package */RecipientChip[] getSortedRecipients() {
1602        RecipientChip[] recips = getSpannable()
1603                .getSpans(0, getText().length(), RecipientChip.class);
1604        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1605                .asList(recips));
1606        final Spannable spannable = getSpannable();
1607        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1608
1609            @Override
1610            public int compare(RecipientChip first, RecipientChip second) {
1611                int firstStart = spannable.getSpanStart(first);
1612                int secondStart = spannable.getSpanStart(second);
1613                if (firstStart < secondStart) {
1614                    return -1;
1615                } else if (firstStart > secondStart) {
1616                    return 1;
1617                } else {
1618                    return 0;
1619                }
1620            }
1621        });
1622        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1623    }
1624
1625    @Override
1626    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1627        return false;
1628    }
1629
1630    @Override
1631    public void onDestroyActionMode(ActionMode mode) {
1632    }
1633
1634    @Override
1635    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1636        return false;
1637    }
1638
1639    /**
1640     * No chips are selectable.
1641     */
1642    @Override
1643    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1644        return false;
1645    }
1646
1647    // Visible for testing.
1648    /* package */ImageSpan getMoreChip() {
1649        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1650                MoreImageSpan.class);
1651        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1652    }
1653
1654    private MoreImageSpan createMoreSpan(int count) {
1655        String moreText = String.format(mMoreItem.getText().toString(), count);
1656        TextPaint morePaint = new TextPaint(getPaint());
1657        morePaint.setTextSize(mMoreItem.getTextSize());
1658        morePaint.setColor(mMoreItem.getCurrentTextColor());
1659        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1660                + mMoreItem.getPaddingRight();
1661        int height = getLineHeight();
1662        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1663        Canvas canvas = new Canvas(drawable);
1664        int adjustedHeight = height;
1665        Layout layout = getLayout();
1666        if (layout != null) {
1667            adjustedHeight -= layout.getLineDescent(0);
1668        }
1669        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1670
1671        Drawable result = new BitmapDrawable(getResources(), drawable);
1672        result.setBounds(0, 0, width, height);
1673        return new MoreImageSpan(result);
1674    }
1675
1676    // Visible for testing.
1677    /*package*/ void createMoreChipPlainText() {
1678        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
1679        Editable text = getText();
1680        int start = 0;
1681        int end = start;
1682        for (int i = 0; i < CHIP_LIMIT; i++) {
1683            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1684            start = end; // move to the next token and get its end.
1685        }
1686        // Now, count total addresses.
1687        start = 0;
1688        int tokenCount = countTokens(text);
1689        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
1690        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
1691        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1692        text.replace(end, text.length(), chipText);
1693        mMoreChip = moreSpan;
1694    }
1695
1696    // Visible for testing.
1697    /* package */int countTokens(Editable text) {
1698        int tokenCount = 0;
1699        int start = 0;
1700        while (start < text.length()) {
1701            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1702            tokenCount++;
1703            if (start >= text.length()) {
1704                break;
1705            }
1706        }
1707        return tokenCount;
1708    }
1709
1710    /**
1711     * Create the more chip. The more chip is text that replaces any chips that
1712     * do not fit in the pre-defined available space when the
1713     * RecipientEditTextView loses focus.
1714     */
1715    // Visible for testing.
1716    /* package */ void createMoreChip() {
1717        if (mNoChips) {
1718            createMoreChipPlainText();
1719            return;
1720        }
1721
1722        if (!mShouldShrink) {
1723            return;
1724        }
1725
1726        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1727        if (tempMore.length > 0) {
1728            getSpannable().removeSpan(tempMore[0]);
1729        }
1730        RecipientChip[] recipients = getSortedRecipients();
1731
1732        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1733            mMoreChip = null;
1734            return;
1735        }
1736        Spannable spannable = getSpannable();
1737        int numRecipients = recipients.length;
1738        int overage = numRecipients - CHIP_LIMIT;
1739        MoreImageSpan moreSpan = createMoreSpan(overage);
1740        mRemovedSpans = new ArrayList<RecipientChip>();
1741        int totalReplaceStart = 0;
1742        int totalReplaceEnd = 0;
1743        Editable text = getText();
1744        for (int i = numRecipients - overage; i < recipients.length; i++) {
1745            mRemovedSpans.add(recipients[i]);
1746            if (i == numRecipients - overage) {
1747                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1748            }
1749            if (i == recipients.length - 1) {
1750                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1751            }
1752            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1753                int spanStart = spannable.getSpanStart(recipients[i]);
1754                int spanEnd = spannable.getSpanEnd(recipients[i]);
1755                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1756            }
1757            spannable.removeSpan(recipients[i]);
1758        }
1759        if (totalReplaceEnd < text.length()) {
1760            totalReplaceEnd = text.length();
1761        }
1762        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1763        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1764        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1765        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1766        text.replace(start, end, chipText);
1767        mMoreChip = moreSpan;
1768    }
1769
1770    /**
1771     * Replace the more chip, if it exists, with all of the recipient chips it had
1772     * replaced when the RecipientEditTextView gains focus.
1773     */
1774    // Visible for testing.
1775    /*package*/ void removeMoreChip() {
1776        if (mMoreChip != null) {
1777            Spannable span = getSpannable();
1778            span.removeSpan(mMoreChip);
1779            mMoreChip = null;
1780            // Re-add the spans that were removed.
1781            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1782                // Recreate each removed span.
1783                RecipientChip[] recipients = getSortedRecipients();
1784                // Start the search for tokens after the last currently visible
1785                // chip.
1786                if (recipients == null || recipients.length == 0) {
1787                    return;
1788                }
1789                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1790                Editable editable = getText();
1791                for (RecipientChip chip : mRemovedSpans) {
1792                    int chipStart;
1793                    int chipEnd;
1794                    String token;
1795                    // Need to find the location of the chip, again.
1796                    token = (String) chip.getOriginalText();
1797                    // As we find the matching recipient for the remove spans,
1798                    // reduce the size of the string we need to search.
1799                    // That way, if there are duplicates, we always find the correct
1800                    // recipient.
1801                    chipStart = editable.toString().indexOf(token, end);
1802                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1803                    // Only set the span if we found a matching token.
1804                    if (chipStart != -1) {
1805                        editable.setSpan(chip, chipStart, chipEnd,
1806                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1807                    }
1808                }
1809                mRemovedSpans.clear();
1810            }
1811        }
1812    }
1813
1814    /**
1815     * Show specified chip as selected. If the RecipientChip is just an email address,
1816     * selecting the chip will take the contents of the chip and place it at
1817     * the end of the RecipientEditTextView for inline editing. If the
1818     * RecipientChip is a complete contact, then selecting the chip
1819     * will change the background color of the chip, show the delete icon,
1820     * and a popup window with the address in use highlighted and any other
1821     * alternate addresses for the contact.
1822     * @param currentChip Chip to select.
1823     * @return A RecipientChip in the selected state or null if the chip
1824     * just contained an email address.
1825     */
1826    private RecipientChip selectChip(RecipientChip currentChip) {
1827        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1828            CharSequence text = currentChip.getValue();
1829            Editable editable = getText();
1830            removeChip(currentChip);
1831            editable.append(text);
1832            setCursorVisible(true);
1833            setSelection(editable.length());
1834            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1835        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1836            int start = getChipStart(currentChip);
1837            int end = getChipEnd(currentChip);
1838            getSpannable().removeSpan(currentChip);
1839            RecipientChip newChip;
1840            try {
1841                if (mNoChips) {
1842                    return null;
1843                }
1844                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1845            } catch (NullPointerException e) {
1846                Log.e(TAG, e.getMessage(), e);
1847                return null;
1848            }
1849            Editable editable = getText();
1850            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1851            if (start == -1 || end == -1) {
1852                Log.d(TAG, "The chip being selected no longer exists but should.");
1853            } else {
1854                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1855            }
1856            newChip.setSelected(true);
1857            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1858                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1859            }
1860            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1861            setCursorVisible(false);
1862            return newChip;
1863        } else {
1864            int start = getChipStart(currentChip);
1865            int end = getChipEnd(currentChip);
1866            getSpannable().removeSpan(currentChip);
1867            RecipientChip newChip;
1868            try {
1869                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1870            } catch (NullPointerException e) {
1871                Log.e(TAG, e.getMessage(), e);
1872                return null;
1873            }
1874            Editable editable = getText();
1875            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1876            if (start == -1 || end == -1) {
1877                Log.d(TAG, "The chip being selected no longer exists but should.");
1878            } else {
1879                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1880            }
1881            newChip.setSelected(true);
1882            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1883                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1884            }
1885            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1886            setCursorVisible(false);
1887            return newChip;
1888        }
1889    }
1890
1891
1892    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1893            int width, Context context) {
1894        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1895        int bottom = calculateOffsetFromBottom(line);
1896        // Align the alternates popup with the left side of the View,
1897        // regardless of the position of the chip tapped.
1898        setEnabled(false);
1899        popup.setWidth(width);
1900        popup.setAnchorView(this);
1901        popup.setVerticalOffset(bottom);
1902        popup.setAdapter(createSingleAddressAdapter(currentChip));
1903        popup.setOnItemClickListener(new OnItemClickListener() {
1904            @Override
1905            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1906                unselectChip(currentChip);
1907                popup.dismiss();
1908            }
1909        });
1910        popup.show();
1911        ListView listView = popup.getListView();
1912        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1913        listView.setItemChecked(0, true);
1914    }
1915
1916    /**
1917     * Remove selection from this chip. Unselecting a RecipientChip will render
1918     * the chip without a delete icon and with an unfocused background. This is
1919     * called when the RecipientChip no longer has focus.
1920     */
1921    private void unselectChip(RecipientChip chip) {
1922        int start = getChipStart(chip);
1923        int end = getChipEnd(chip);
1924        Editable editable = getText();
1925        mSelectedChip = null;
1926        if (start == -1 || end == -1) {
1927            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
1928            setSelection(editable.length());
1929            commitDefault();
1930        } else {
1931            getSpannable().removeSpan(chip);
1932            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1933            editable.removeSpan(chip);
1934            try {
1935                if (!mNoChips) {
1936                    editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1937                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1938                }
1939            } catch (NullPointerException e) {
1940                Log.e(TAG, e.getMessage(), e);
1941            }
1942        }
1943        setCursorVisible(true);
1944        setSelection(editable.length());
1945        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1946            mAlternatesPopup.dismiss();
1947        }
1948    }
1949
1950    /**
1951     * Return whether a touch event was inside the delete target of
1952     * a selected chip. It is in the delete target if:
1953     * 1) the x and y points of the event are within the
1954     * delete assset.
1955     * 2) the point tapped would have caused a cursor to appear
1956     * right after the selected chip.
1957     * @return boolean
1958     */
1959    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1960        // Figure out the bounds of this chip and whether or not
1961        // the user clicked in the X portion.
1962        return chip.isSelected() && offset == getChipEnd(chip);
1963    }
1964
1965    /**
1966     * Remove the chip and any text associated with it from the RecipientEditTextView.
1967     */
1968    // Visible for testing.
1969    /*pacakge*/ void removeChip(RecipientChip chip) {
1970        Spannable spannable = getSpannable();
1971        int spanStart = spannable.getSpanStart(chip);
1972        int spanEnd = spannable.getSpanEnd(chip);
1973        Editable text = getText();
1974        int toDelete = spanEnd;
1975        boolean wasSelected = chip == mSelectedChip;
1976        // Clear that there is a selected chip before updating any text.
1977        if (wasSelected) {
1978            mSelectedChip = null;
1979        }
1980        // Always remove trailing spaces when removing a chip.
1981        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1982            toDelete++;
1983        }
1984        spannable.removeSpan(chip);
1985        if (spanStart >= 0 && toDelete > 0) {
1986            text.delete(spanStart, toDelete);
1987        }
1988        if (wasSelected) {
1989            clearSelectedChip();
1990        }
1991    }
1992
1993    /**
1994     * Replace this currently selected chip with a new chip
1995     * that uses the contact data provided.
1996     */
1997    // Visible for testing.
1998    /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) {
1999        boolean wasSelected = chip == mSelectedChip;
2000        if (wasSelected) {
2001            mSelectedChip = null;
2002        }
2003        int start = getChipStart(chip);
2004        int end = getChipEnd(chip);
2005        getSpannable().removeSpan(chip);
2006        Editable editable = getText();
2007        CharSequence chipText = createChip(entry, false);
2008        if (chipText != null) {
2009            if (start == -1 || end == -1) {
2010                Log.e(TAG, "The chip to replace does not exist but should.");
2011                editable.insert(0, chipText);
2012            } else {
2013                if (!TextUtils.isEmpty(chipText)) {
2014                    // There may be a space to replace with this chip's new
2015                    // associated
2016                    // space. Check for it
2017                    int toReplace = end;
2018                    while (toReplace >= 0 && toReplace < editable.length()
2019                            && editable.charAt(toReplace) == ' ') {
2020                        toReplace++;
2021                    }
2022                    editable.replace(start, toReplace, chipText);
2023                }
2024            }
2025        }
2026        setCursorVisible(true);
2027        if (wasSelected) {
2028            clearSelectedChip();
2029        }
2030    }
2031
2032    /**
2033     * Handle click events for a chip. When a selected chip receives a click
2034     * event, see if that event was in the delete icon. If so, delete it.
2035     * Otherwise, unselect the chip.
2036     */
2037    public void onClick(RecipientChip chip, int offset, float x, float y) {
2038        if (chip.isSelected()) {
2039            if (isInDelete(chip, offset, x, y)) {
2040                removeChip(chip);
2041            } else {
2042                clearSelectedChip();
2043            }
2044        }
2045    }
2046
2047    private boolean chipsPending() {
2048        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2049    }
2050
2051    @Override
2052    public void removeTextChangedListener(TextWatcher watcher) {
2053        mTextWatcher = null;
2054        super.removeTextChangedListener(watcher);
2055    }
2056
2057    private class RecipientTextWatcher implements TextWatcher {
2058
2059        @Override
2060        public void afterTextChanged(Editable s) {
2061            // If the text has been set to null or empty, make sure we remove
2062            // all the spans we applied.
2063            if (TextUtils.isEmpty(s)) {
2064                // Remove all the chips spans.
2065                Spannable spannable = getSpannable();
2066                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
2067                        RecipientChip.class);
2068                for (RecipientChip chip : chips) {
2069                    spannable.removeSpan(chip);
2070                }
2071                if (mMoreChip != null) {
2072                    spannable.removeSpan(mMoreChip);
2073                }
2074                return;
2075            }
2076            // Get whether there are any recipients pending addition to the
2077            // view. If there are, don't do anything in the text watcher.
2078            if (chipsPending()) {
2079                return;
2080            }
2081            // If the user is editing a chip, don't clear it.
2082            if (mSelectedChip != null
2083                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
2084                setCursorVisible(true);
2085                setSelection(getText().length());
2086                clearSelectedChip();
2087            }
2088            int length = s.length();
2089            // Make sure there is content there to parse and that it is
2090            // not just the commit character.
2091            if (length > 1) {
2092                char last;
2093                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2094                int len = length() - 1;
2095                if (end != len) {
2096                    last = s.charAt(end);
2097                } else {
2098                    last = s.charAt(len);
2099                }
2100                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
2101                    commitByCharacter();
2102                } else if (last == COMMIT_CHAR_SPACE) {
2103                    if (!isPhoneQuery()) {
2104                        // Check if this is a valid email address. If it is,
2105                        // commit it.
2106                        String text = getText().toString();
2107                        int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2108                        String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2109                                tokenStart));
2110                        if (!TextUtils.isEmpty(sub) && mValidator != null &&
2111                                mValidator.isValid(sub)) {
2112                            commitByCharacter();
2113                        }
2114                    }
2115                }
2116            }
2117        }
2118
2119        @Override
2120        public void onTextChanged(CharSequence s, int start, int before, int count) {
2121            // This is a delete; check to see if the insertion point is on a space
2122            // following a chip.
2123            if (before > count) {
2124                // If the item deleted is a space, and the thing before the
2125                // space is a chip, delete the entire span.
2126                int selStart = getSelectionStart();
2127                RecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2128                        RecipientChip.class);
2129                if (repl.length > 0) {
2130                    // There is a chip there! Just remove it.
2131                    Editable editable = getText();
2132                    // Add the separator token.
2133                    int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2134                    int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
2135                    tokenEnd = tokenEnd + 1;
2136                    if (tokenEnd > editable.length()) {
2137                        tokenEnd = editable.length();
2138                    }
2139                    editable.delete(tokenStart, tokenEnd);
2140                    getSpannable().removeSpan(repl[0]);
2141                }
2142            }
2143        }
2144
2145        @Override
2146        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2147            // Do nothing.
2148        }
2149    }
2150
2151    /**
2152     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2153     */
2154    private void handlePasteClip(ClipData clip) {
2155        removeTextChangedListener(mTextWatcher);
2156
2157        if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
2158            for (int i = 0; i < clip.getItemCount(); i++) {
2159                CharSequence paste = clip.getItemAt(i).getText();
2160                if (paste != null) {
2161                    int start = getSelectionStart();
2162                    int end = getSelectionEnd();
2163                    Editable editable = getText();
2164                    if (start >= 0 && end >= 0 && start != end) {
2165                        editable.append(paste, start, end);
2166                    } else {
2167                        editable.insert(end, paste);
2168                    }
2169                    handlePasteAndReplace();
2170                }
2171            }
2172        }
2173
2174        mHandler.post(mAddTextWatcher);
2175    }
2176
2177    @Override
2178    public boolean onTextContextMenuItem(int id) {
2179        if (id == android.R.id.paste) {
2180            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2181                    Context.CLIPBOARD_SERVICE);
2182            handlePasteClip(clipboard.getPrimaryClip());
2183            return true;
2184        }
2185        return super.onTextContextMenuItem(id);
2186    }
2187
2188    private void handlePasteAndReplace() {
2189        ArrayList<RecipientChip> created = handlePaste();
2190        if (created != null && created.size() > 0) {
2191            // Perform reverse lookups on the pasted contacts.
2192            IndividualReplacementTask replace = new IndividualReplacementTask();
2193            replace.execute(created);
2194        }
2195    }
2196
2197    // Visible for testing.
2198    /* package */ArrayList<RecipientChip> handlePaste() {
2199        String text = getText().toString();
2200        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2201        String lastAddress = text.substring(originalTokenStart);
2202        int tokenStart = originalTokenStart;
2203        int prevTokenStart = tokenStart;
2204        RecipientChip findChip = null;
2205        ArrayList<RecipientChip> created = new ArrayList<RecipientChip>();
2206        if (tokenStart != 0) {
2207            // There are things before this!
2208            while (tokenStart != 0 && findChip == null) {
2209                prevTokenStart = tokenStart;
2210                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2211                findChip = findChip(tokenStart);
2212            }
2213            if (tokenStart != originalTokenStart) {
2214                if (findChip != null) {
2215                    tokenStart = prevTokenStart;
2216                }
2217                int tokenEnd;
2218                RecipientChip createdChip;
2219                while (tokenStart < originalTokenStart) {
2220                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(text, tokenStart));
2221                    commitChip(tokenStart, tokenEnd, getText());
2222                    createdChip = findChip(tokenStart);
2223                    // +1 for the space at the end.
2224                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2225                    created.add(createdChip);
2226                }
2227            }
2228        }
2229        // Take a look at the last token. If the token has been completed with a
2230        // commit character, create a chip.
2231        if (isCompletedToken(lastAddress)) {
2232            Editable editable = getText();
2233            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2234            commitChip(tokenStart, editable.length(), editable);
2235            created.add(findChip(tokenStart));
2236        }
2237        return created;
2238    }
2239
2240    // Visible for testing.
2241    /* package */int movePastTerminators(int tokenEnd) {
2242        if (tokenEnd >= length()) {
2243            return tokenEnd;
2244        }
2245        char atEnd = getText().toString().charAt(tokenEnd);
2246        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2247            tokenEnd++;
2248        }
2249        // This token had not only an end token character, but also a space
2250        // separating it from the next token.
2251        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2252            tokenEnd++;
2253        }
2254        return tokenEnd;
2255    }
2256
2257    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2258        private RecipientChip createFreeChip(RecipientEntry entry) {
2259            try {
2260                if (mNoChips) {
2261                    return null;
2262                }
2263                return constructChipSpan(entry, -1, false);
2264            } catch (NullPointerException e) {
2265                Log.e(TAG, e.getMessage(), e);
2266                return null;
2267            }
2268        }
2269
2270        @Override
2271        protected Void doInBackground(Void... params) {
2272            if (mIndividualReplacements != null) {
2273                mIndividualReplacements.cancel(true);
2274            }
2275            // For each chip in the list, look up the matching contact.
2276            // If there is a match, replace that chip with the matching
2277            // chip.
2278            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
2279            RecipientChip[] existingChips = getSortedRecipients();
2280            for (int i = 0; i < existingChips.length; i++) {
2281                originalRecipients.add(existingChips[i]);
2282            }
2283            if (mRemovedSpans != null) {
2284                originalRecipients.addAll(mRemovedSpans);
2285            }
2286            ArrayList<String> addresses = new ArrayList<String>();
2287            RecipientChip chip;
2288            for (int i = 0; i < originalRecipients.size(); i++) {
2289                chip = originalRecipients.get(i);
2290                if (chip != null) {
2291                    addresses.add(createAddressText(chip.getEntry()));
2292                }
2293            }
2294            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2295                    .getMatchingRecipients(getContext(), addresses);
2296            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
2297            for (final RecipientChip temp : originalRecipients) {
2298                RecipientEntry entry = null;
2299                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2300                        && getSpannable().getSpanStart(temp) != -1) {
2301                    // Replace this.
2302                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
2303                            .getDestination())));
2304                }
2305                if (entry != null) {
2306                    replacements.add(createFreeChip(entry));
2307                } else {
2308                    replacements.add(temp);
2309                }
2310            }
2311            if (replacements != null && replacements.size() > 0) {
2312                mHandler.post(new Runnable() {
2313                    @Override
2314                    public void run() {
2315                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
2316                                .toString());
2317                        Editable oldText = getText();
2318                        int start, end;
2319                        int i = 0;
2320                        for (RecipientChip chip : originalRecipients) {
2321                            start = oldText.getSpanStart(chip);
2322                            if (start != -1) {
2323                                end = oldText.getSpanEnd(chip);
2324                                oldText.removeSpan(chip);
2325                                // Leave a spot for the space!
2326                                RecipientChip replacement = replacements.get(i);
2327                                text.setSpan(replacement, start, end,
2328                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2329                                replacement.setOriginalText(text.toString().substring(start, end));
2330                            }
2331                            i++;
2332                        }
2333                        originalRecipients.clear();
2334                        setText(text);
2335                    }
2336                });
2337            }
2338            return null;
2339        }
2340    }
2341
2342    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
2343        @SuppressWarnings("unchecked")
2344        @Override
2345        protected Void doInBackground(Object... params) {
2346            // For each chip in the list, look up the matching contact.
2347            // If there is a match, replace that chip with the matching
2348            // chip.
2349            final ArrayList<RecipientChip> originalRecipients =
2350                (ArrayList<RecipientChip>) params[0];
2351            ArrayList<String> addresses = new ArrayList<String>();
2352            RecipientChip chip;
2353            for (int i = 0; i < originalRecipients.size(); i++) {
2354                chip = originalRecipients.get(i);
2355                if (chip != null) {
2356                    addresses.add(createAddressText(chip.getEntry()));
2357                }
2358            }
2359            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2360                    .getMatchingRecipients(getContext(), addresses);
2361            for (final RecipientChip temp : originalRecipients) {
2362                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2363                        && getSpannable().getSpanStart(temp) != -1) {
2364                    // Replace this.
2365                    final RecipientEntry entry = createValidatedEntry(entries
2366                            .get(tokenizeAddress(temp.getEntry().getDestination()).toLowerCase()));
2367                    if (entry != null) {
2368                        mHandler.post(new Runnable() {
2369                            @Override
2370                            public void run() {
2371                                replaceChip(temp, entry);
2372                            }
2373                        });
2374                    }
2375                }
2376            }
2377            return null;
2378        }
2379    }
2380
2381
2382    /**
2383     * MoreImageSpan is a simple class created for tracking the existence of a
2384     * more chip across activity restarts/
2385     */
2386    private class MoreImageSpan extends ImageSpan {
2387        public MoreImageSpan(Drawable b) {
2388            super(b);
2389        }
2390    }
2391
2392    @Override
2393    public boolean onDown(MotionEvent e) {
2394        return false;
2395    }
2396
2397    @Override
2398    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2399        // Do nothing.
2400        return false;
2401    }
2402
2403    @Override
2404    public void onLongPress(MotionEvent event) {
2405        if (mSelectedChip != null) {
2406            return;
2407        }
2408        float x = event.getX();
2409        float y = event.getY();
2410        int offset = putOffsetInRange(getOffsetForPosition(x, y));
2411        RecipientChip currentChip = findChip(offset);
2412        if (currentChip != null) {
2413            if (mDragEnabled) {
2414                // Start drag-and-drop for the selected chip.
2415                startDrag(currentChip);
2416            } else {
2417                // Copy the selected chip email address.
2418                showCopyDialog(currentChip.getEntry().getDestination());
2419            }
2420        }
2421    }
2422
2423    /**
2424     * Enables drag-and-drop for chips.
2425     */
2426    public void enableDrag() {
2427        mDragEnabled = true;
2428    }
2429
2430    /**
2431     * Starts drag-and-drop for the selected chip.
2432     */
2433    private void startDrag(RecipientChip currentChip) {
2434        String address = currentChip.getEntry().getDestination();
2435        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2436
2437        // Start drag mode.
2438        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2439
2440        // Remove the current chip, so drag-and-drop will result in a move.
2441        // TODO (phamm): consider readd this chip if it's dropped outside a target.
2442        removeChip(currentChip);
2443    }
2444
2445    /**
2446     * Handles drag event.
2447     */
2448    @Override
2449    public boolean onDragEvent(DragEvent event) {
2450        switch (event.getAction()) {
2451            case DragEvent.ACTION_DRAG_STARTED:
2452                // Only handle plain text drag and drop.
2453                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2454            case DragEvent.ACTION_DRAG_ENTERED:
2455                requestFocus();
2456                return true;
2457            case DragEvent.ACTION_DROP:
2458                handlePasteClip(event.getClipData());
2459                return true;
2460        }
2461        return false;
2462    }
2463
2464    /**
2465     * Drag shadow for a {@link RecipientChip}.
2466     */
2467    private final class RecipientChipShadow extends DragShadowBuilder {
2468        private final RecipientChip mChip;
2469
2470        public RecipientChipShadow(RecipientChip chip) {
2471            mChip = chip;
2472        }
2473
2474        @Override
2475        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
2476            Rect rect = mChip.getDrawable().getBounds();
2477            shadowSize.set(rect.width(), rect.height());
2478            shadowTouchPoint.set(rect.centerX(), rect.centerY());
2479        }
2480
2481        @Override
2482        public void onDrawShadow(Canvas canvas) {
2483            mChip.getDrawable().draw(canvas);
2484        }
2485    }
2486
2487    private void showCopyDialog(final String address) {
2488        mCopyAddress = address;
2489        mCopyDialog.setTitle(address);
2490        mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
2491        mCopyDialog.setCancelable(true);
2492        mCopyDialog.setCanceledOnTouchOutside(true);
2493        Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
2494        button.setOnClickListener(this);
2495        int btnTitleId;
2496        if (isPhoneQuery()) {
2497            btnTitleId = R.string.copy_number;
2498        } else {
2499            btnTitleId = R.string.copy_email;
2500        }
2501        String buttonTitle = getContext().getResources().getString(btnTitleId);
2502        button.setText(buttonTitle);
2503        mCopyDialog.setOnDismissListener(this);
2504        mCopyDialog.show();
2505    }
2506
2507    @Override
2508    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
2509        // Do nothing.
2510        return false;
2511    }
2512
2513    @Override
2514    public void onShowPress(MotionEvent e) {
2515        // Do nothing.
2516    }
2517
2518    @Override
2519    public boolean onSingleTapUp(MotionEvent e) {
2520        // Do nothing.
2521        return false;
2522    }
2523
2524    @Override
2525    public void onDismiss(DialogInterface dialog) {
2526        mCopyAddress = null;
2527    }
2528
2529    @Override
2530    public void onClick(View v) {
2531        // Copy this to the clipboard.
2532        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2533                Context.CLIPBOARD_SERVICE);
2534        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
2535        mCopyDialog.dismiss();
2536    }
2537
2538    protected boolean isPhoneQuery() {
2539        return ((BaseRecipientAdapter)getAdapter()).getQueryType() ==
2540                BaseRecipientAdapter.QUERY_TYPE_PHONE;
2541    }
2542}
2543