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