RecipientEditTextView.java revision 7ccedccdc10a58d94d2d4895c9637a5b77cf0427
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  - (int)paint.descent();
577        return height - ((height - textHeight) / 2);
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    }
678
679    // Visible for testing.
680    /* package */ void setMoreItem(TextView moreItem) {
681        mMoreItem = moreItem;
682    }
683
684
685    // Visible for testing.
686    /* package */ void setChipBackground(Drawable chipBackground) {
687        mChipBackground = chipBackground;
688    }
689
690    // Visible for testing.
691    /* package */ void setChipHeight(int height) {
692        mChipHeight = height;
693    }
694
695    /**
696     * Set whether to shrink the recipients field such that at most
697     * one line of recipients chips are shown when the field loses
698     * focus. By default, the number of displayed recipients will be
699     * limited and a "more" chip will be shown when focus is lost.
700     * @param shrink
701     */
702    public void setOnFocusListShrinkRecipients(boolean shrink) {
703        mShouldShrink = shrink;
704    }
705
706    @Override
707    public void onSizeChanged(int width, int height, int oldw, int oldh) {
708        super.onSizeChanged(width, height, oldw, oldh);
709        if (width != 0 && height != 0) {
710            if (mPendingChipsCount > 0) {
711                postHandlePendingChips();
712            } else {
713                checkChipWidths();
714            }
715        }
716        // Try to find the scroll view parent, if it exists.
717        if (mScrollView == null && !mTriedGettingScrollView) {
718            ViewParent parent = getParent();
719            while (parent != null && !(parent instanceof ScrollView)) {
720                parent = parent.getParent();
721            }
722            if (parent != null) {
723                mScrollView = (ScrollView) parent;
724            }
725            mTriedGettingScrollView = true;
726        }
727    }
728
729    private void postHandlePendingChips() {
730        mHandler.removeCallbacks(mHandlePendingChips);
731        mHandler.post(mHandlePendingChips);
732    }
733
734    private void checkChipWidths() {
735        // Check the widths of the associated chips.
736        RecipientChip[] chips = getSortedRecipients();
737        if (chips != null) {
738            Rect bounds;
739            for (RecipientChip chip : chips) {
740                bounds = chip.getDrawable().getBounds();
741                if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) {
742                    // Need to redraw that chip.
743                    replaceChip(chip, chip.getEntry());
744                }
745            }
746        }
747    }
748
749    // Visible for testing.
750    /*package*/ void handlePendingChips() {
751        if (getViewWidth() <= 0) {
752            // The widget has not been sized yet.
753            // This will be called as a result of onSizeChanged
754            // at a later point.
755            return;
756        }
757        if (mPendingChipsCount <= 0) {
758            return;
759        }
760
761        synchronized (mPendingChips) {
762            Editable editable = getText();
763            // Tokenize!
764            if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
765                for (int i = 0; i < mPendingChips.size(); i++) {
766                    String current = mPendingChips.get(i);
767                    int tokenStart = editable.toString().indexOf(current);
768                    int tokenEnd = tokenStart + current.length();
769                    if (tokenStart >= 0) {
770                        // When we have a valid token, include it with the token
771                        // to the left.
772                        if (tokenEnd < editable.length() - 2
773                                && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
774                            tokenEnd++;
775                        }
776                        createReplacementChip(tokenStart, tokenEnd, editable);
777                    }
778                    mPendingChipsCount--;
779                }
780                sanitizeEnd();
781            } else {
782                mNoChips = true;
783            }
784
785            if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
786                    && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
787                if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
788                    new RecipientReplacementTask().execute();
789                    mTemporaryRecipients = null;
790                } else {
791                    // Create the "more" chip
792                    mIndividualReplacements = new IndividualReplacementTask();
793                    mIndividualReplacements.execute(new ArrayList<RecipientChip>(
794                            mTemporaryRecipients.subList(0, CHIP_LIMIT)));
795
796                    createMoreChip();
797                }
798            } else {
799                // There are too many recipients to look up, so just fall back
800                // to showing addresses for all of them.
801                mTemporaryRecipients = null;
802                createMoreChip();
803            }
804            mPendingChipsCount = 0;
805            mPendingChips.clear();
806        }
807    }
808
809    // Visible for testing.
810    /*package*/ int getViewWidth() {
811        return getWidth();
812    }
813
814    /**
815     * Remove any characters after the last valid chip.
816     */
817    // Visible for testing.
818    /*package*/ void sanitizeEnd() {
819        // Don't sanitize while we are waiting for pending chips to complete.
820        if (mPendingChipsCount > 0) {
821            return;
822        }
823        // Find the last chip; eliminate any commit characters after it.
824        RecipientChip[] chips = getSortedRecipients();
825        if (chips != null && chips.length > 0) {
826            int end;
827            ImageSpan lastSpan;
828            mMoreChip = getMoreChip();
829            if (mMoreChip != null) {
830                lastSpan = mMoreChip;
831            } else {
832                lastSpan = getLastChip();
833            }
834            end = getSpannable().getSpanEnd(lastSpan);
835            Editable editable = getText();
836            int length = editable.length();
837            if (length > end) {
838                // See what characters occur after that and eliminate them.
839                if (Log.isLoggable(TAG, Log.DEBUG)) {
840                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
841                            + editable);
842                }
843                editable.delete(end + 1, length);
844            }
845        }
846    }
847
848    /**
849     * Create a chip that represents just the email address of a recipient. At some later
850     * point, this chip will be attached to a real contact entry, if one exists.
851     */
852    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
853        if (alreadyHasChip(tokenStart, tokenEnd)) {
854            // There is already a chip present at this location.
855            // Don't recreate it.
856            return;
857        }
858        String token = editable.toString().substring(tokenStart, tokenEnd);
859        int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
860        if (commitCharIndex == token.length() - 1) {
861            token = token.substring(0, token.length() - 1);
862        }
863        RecipientEntry entry = createTokenizedEntry(token);
864        if (entry != null) {
865            String destText = createAddressText(entry);
866            // Always leave a blank space at the end of a chip.
867            int textLength = destText.length() - 1;
868            SpannableString chipText = new SpannableString(destText);
869            int end = getSelectionEnd();
870            int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0;
871            RecipientChip chip = null;
872            try {
873                if (!mNoChips) {
874                    chip = constructChipSpan(entry, start, false);
875                    chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
876                }
877            } catch (NullPointerException e) {
878                Log.e(TAG, e.getMessage(), e);
879            }
880            editable.replace(tokenStart, tokenEnd, chipText);
881            // Add this chip to the list of entries "to replace"
882            if (chip != null) {
883                if (mTemporaryRecipients == null) {
884                    mTemporaryRecipients = new ArrayList<RecipientChip>();
885                }
886                chip.setOriginalText(chipText.toString());
887                mTemporaryRecipients.add(chip);
888            }
889        }
890    }
891
892    private static boolean isPhoneNumber(String number) {
893        // TODO: replace this function with libphonenumber's isPossibleNumber (see
894        // PhoneNumberUtil). One complication is that it requires the sender's region which
895        // comes from the CurrentCountryIso. For now, let's just do this simple match.
896        if (TextUtils.isEmpty(number)) {
897            return false;
898        }
899
900        Matcher match = Patterns.PHONE.matcher(number);
901        return match.matches();
902    }
903
904    private RecipientEntry createTokenizedEntry(String token) {
905        if (TextUtils.isEmpty(token)) {
906            return null;
907        }
908        if (((BaseRecipientAdapter)getAdapter()).getQueryType() ==
909                    BaseRecipientAdapter.QUERY_TYPE_PHONE && 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()) {
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 (((BaseRecipientAdapter)getAdapter()).getQueryType() ==
1454                BaseRecipientAdapter.QUERY_TYPE_PHONE && isPhoneNumber(address)) {
1455            trimmedDisplayText = address.trim();
1456        } else {
1457            if (address != null) {
1458                // Tokenize out the address in case the address already
1459                // contained the username as well.
1460                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1461                if (tokenized != null && tokenized.length > 0) {
1462                    address = tokenized[0].getAddress();
1463                }
1464            }
1465            Rfc822Token token = new Rfc822Token(display, address, null);
1466            trimmedDisplayText = token.toString().trim();
1467        }
1468        int index = trimmedDisplayText.indexOf(",");
1469        return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1470                && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1471                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1472    }
1473
1474    // Visible for testing.
1475    // Use this method to generate text to display in a chip.
1476    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1477        String display = entry.getDisplayName();
1478        String address = entry.getDestination();
1479        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1480            display = null;
1481        }
1482        if (address != null && !(((BaseRecipientAdapter)getAdapter()).getQueryType() ==
1483                BaseRecipientAdapter.QUERY_TYPE_PHONE && isPhoneNumber(address))) {
1484            // Tokenize out the address in case the address already
1485            // contained the username as well.
1486            Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1487            if (tokenized != null && tokenized.length > 0) {
1488                address = tokenized[0].getAddress();
1489            }
1490        }
1491        if (!TextUtils.isEmpty(display)) {
1492            return display;
1493        } else if (!TextUtils.isEmpty(address)){
1494            return address;
1495        } else {
1496            return new Rfc822Token(display, address, null).toString();
1497        }
1498    }
1499
1500    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1501        String displayText = createAddressText(entry);
1502        if (TextUtils.isEmpty(displayText)) {
1503            return null;
1504        }
1505        SpannableString chipText = null;
1506        // Always leave a blank space at the end of a chip.
1507        int end = getSelectionEnd();
1508        int start = mTokenizer.findTokenStart(getText(), end);
1509        int textLength = displayText.length()-1;
1510        chipText = new SpannableString(displayText);
1511        if (!mNoChips) {
1512            try {
1513                RecipientChip chip = constructChipSpan(entry, start, pressed);
1514                chipText.setSpan(chip, 0, textLength,
1515                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1516                chip.setOriginalText(chipText.toString());
1517            } catch (NullPointerException e) {
1518                Log.e(TAG, e.getMessage(), e);
1519                return null;
1520            }
1521        }
1522        return chipText;
1523    }
1524
1525    /**
1526     * When an item in the suggestions list has been clicked, create a chip from the
1527     * contact information of the selected item.
1528     */
1529    @Override
1530    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1531        submitItemAtPosition(position);
1532    }
1533
1534    private void submitItemAtPosition(int position) {
1535        RecipientEntry entry = createValidatedEntry(
1536                (RecipientEntry)getAdapter().getItem(position));
1537        if (entry == null) {
1538            return;
1539        }
1540        clearComposingText();
1541
1542        int end = getSelectionEnd();
1543        int start = mTokenizer.findTokenStart(getText(), end);
1544
1545        Editable editable = getText();
1546        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1547        CharSequence chip = createChip(entry, false);
1548        if (chip != null && start >= 0 && end >= 0) {
1549            editable.replace(start, end, chip);
1550        }
1551        sanitizeBetween();
1552    }
1553
1554    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1555        if (item == null) {
1556            return null;
1557        }
1558        final RecipientEntry entry;
1559        // If the display name and the address are the same, or if this is a
1560        // valid contact, but the destination is invalid, then make this a fake
1561        // recipient that is editable.
1562        String destination = item.getDestination();
1563        if (RecipientEntry.isCreatedRecipient(item.getContactId())
1564                && (TextUtils.isEmpty(item.getDisplayName())
1565                        || TextUtils.equals(item.getDisplayName(), destination)
1566                        || (mValidator != null && !mValidator.isValid(destination)))) {
1567            entry = RecipientEntry.constructFakeEntry(destination);
1568        } else {
1569            entry = item;
1570        }
1571        return entry;
1572    }
1573
1574    /** Returns a collection of contact Id for each chip inside this View. */
1575    /* package */ Collection<Long> getContactIds() {
1576        final Set<Long> result = new HashSet<Long>();
1577        RecipientChip[] chips = getSortedRecipients();
1578        if (chips != null) {
1579            for (RecipientChip chip : chips) {
1580                result.add(chip.getContactId());
1581            }
1582        }
1583        return result;
1584    }
1585
1586
1587    /** Returns a collection of data Id for each chip inside this View. May be null. */
1588    /* package */ Collection<Long> getDataIds() {
1589        final Set<Long> result = new HashSet<Long>();
1590        RecipientChip [] chips = getSortedRecipients();
1591        if (chips != null) {
1592            for (RecipientChip chip : chips) {
1593                result.add(chip.getDataId());
1594            }
1595        }
1596        return result;
1597    }
1598
1599    // Visible for testing.
1600    /* package */RecipientChip[] getSortedRecipients() {
1601        RecipientChip[] recips = getSpannable()
1602                .getSpans(0, getText().length(), RecipientChip.class);
1603        ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
1604                .asList(recips));
1605        final Spannable spannable = getSpannable();
1606        Collections.sort(recipientsList, new Comparator<RecipientChip>() {
1607
1608            @Override
1609            public int compare(RecipientChip first, RecipientChip second) {
1610                int firstStart = spannable.getSpanStart(first);
1611                int secondStart = spannable.getSpanStart(second);
1612                if (firstStart < secondStart) {
1613                    return -1;
1614                } else if (firstStart > secondStart) {
1615                    return 1;
1616                } else {
1617                    return 0;
1618                }
1619            }
1620        });
1621        return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
1622    }
1623
1624    @Override
1625    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1626        return false;
1627    }
1628
1629    @Override
1630    public void onDestroyActionMode(ActionMode mode) {
1631    }
1632
1633    @Override
1634    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1635        return false;
1636    }
1637
1638    /**
1639     * No chips are selectable.
1640     */
1641    @Override
1642    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1643        return false;
1644    }
1645
1646    // Visible for testing.
1647    /* package */ImageSpan getMoreChip() {
1648        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1649                MoreImageSpan.class);
1650        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1651    }
1652
1653    private MoreImageSpan createMoreSpan(int count) {
1654        String moreText = String.format(mMoreItem.getText().toString(), count);
1655        TextPaint morePaint = new TextPaint(getPaint());
1656        morePaint.setTextSize(mMoreItem.getTextSize());
1657        morePaint.setColor(mMoreItem.getCurrentTextColor());
1658        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1659                + mMoreItem.getPaddingRight();
1660        int height = getLineHeight();
1661        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1662        Canvas canvas = new Canvas(drawable);
1663        int adjustedHeight = height;
1664        Layout layout = getLayout();
1665        if (layout != null) {
1666            adjustedHeight -= layout.getLineDescent(0);
1667        }
1668        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1669
1670        Drawable result = new BitmapDrawable(getResources(), drawable);
1671        result.setBounds(0, 0, width, height);
1672        return new MoreImageSpan(result);
1673    }
1674
1675    // Visible for testing.
1676    /*package*/ void createMoreChipPlainText() {
1677        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
1678        Editable text = getText();
1679        int start = 0;
1680        int end = start;
1681        for (int i = 0; i < CHIP_LIMIT; i++) {
1682            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1683            start = end; // move to the next token and get its end.
1684        }
1685        // Now, count total addresses.
1686        start = 0;
1687        int tokenCount = countTokens(text);
1688        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
1689        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
1690        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1691        text.replace(end, text.length(), chipText);
1692        mMoreChip = moreSpan;
1693    }
1694
1695    // Visible for testing.
1696    /* package */int countTokens(Editable text) {
1697        int tokenCount = 0;
1698        int start = 0;
1699        while (start < text.length()) {
1700            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1701            tokenCount++;
1702            if (start >= text.length()) {
1703                break;
1704            }
1705        }
1706        return tokenCount;
1707    }
1708
1709    /**
1710     * Create the more chip. The more chip is text that replaces any chips that
1711     * do not fit in the pre-defined available space when the
1712     * RecipientEditTextView loses focus.
1713     */
1714    // Visible for testing.
1715    /* package */ void createMoreChip() {
1716        if (mNoChips) {
1717            createMoreChipPlainText();
1718            return;
1719        }
1720
1721        if (!mShouldShrink) {
1722            return;
1723        }
1724
1725        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
1726        if (tempMore.length > 0) {
1727            getSpannable().removeSpan(tempMore[0]);
1728        }
1729        RecipientChip[] recipients = getSortedRecipients();
1730
1731        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1732            mMoreChip = null;
1733            return;
1734        }
1735        Spannable spannable = getSpannable();
1736        int numRecipients = recipients.length;
1737        int overage = numRecipients - CHIP_LIMIT;
1738        MoreImageSpan moreSpan = createMoreSpan(overage);
1739        mRemovedSpans = new ArrayList<RecipientChip>();
1740        int totalReplaceStart = 0;
1741        int totalReplaceEnd = 0;
1742        Editable text = getText();
1743        for (int i = numRecipients - overage; i < recipients.length; i++) {
1744            mRemovedSpans.add(recipients[i]);
1745            if (i == numRecipients - overage) {
1746                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1747            }
1748            if (i == recipients.length - 1) {
1749                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1750            }
1751            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
1752                int spanStart = spannable.getSpanStart(recipients[i]);
1753                int spanEnd = spannable.getSpanEnd(recipients[i]);
1754                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
1755            }
1756            spannable.removeSpan(recipients[i]);
1757        }
1758        if (totalReplaceEnd < text.length()) {
1759            totalReplaceEnd = text.length();
1760        }
1761        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1762        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1763        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1764        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1765        text.replace(start, end, chipText);
1766        mMoreChip = moreSpan;
1767    }
1768
1769    /**
1770     * Replace the more chip, if it exists, with all of the recipient chips it had
1771     * replaced when the RecipientEditTextView gains focus.
1772     */
1773    // Visible for testing.
1774    /*package*/ void removeMoreChip() {
1775        if (mMoreChip != null) {
1776            Spannable span = getSpannable();
1777            span.removeSpan(mMoreChip);
1778            mMoreChip = null;
1779            // Re-add the spans that were removed.
1780            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1781                // Recreate each removed span.
1782                RecipientChip[] recipients = getSortedRecipients();
1783                // Start the search for tokens after the last currently visible
1784                // chip.
1785                if (recipients == null || recipients.length == 0) {
1786                    return;
1787                }
1788                int end = span.getSpanEnd(recipients[recipients.length - 1]);
1789                Editable editable = getText();
1790                for (RecipientChip chip : mRemovedSpans) {
1791                    int chipStart;
1792                    int chipEnd;
1793                    String token;
1794                    // Need to find the location of the chip, again.
1795                    token = (String) chip.getOriginalText();
1796                    // As we find the matching recipient for the remove spans,
1797                    // reduce the size of the string we need to search.
1798                    // That way, if there are duplicates, we always find the correct
1799                    // recipient.
1800                    chipStart = editable.toString().indexOf(token, end);
1801                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
1802                    // Only set the span if we found a matching token.
1803                    if (chipStart != -1) {
1804                        editable.setSpan(chip, chipStart, chipEnd,
1805                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1806                    }
1807                }
1808                mRemovedSpans.clear();
1809            }
1810        }
1811    }
1812
1813    /**
1814     * Show specified chip as selected. If the RecipientChip is just an email address,
1815     * selecting the chip will take the contents of the chip and place it at
1816     * the end of the RecipientEditTextView for inline editing. If the
1817     * RecipientChip is a complete contact, then selecting the chip
1818     * will change the background color of the chip, show the delete icon,
1819     * and a popup window with the address in use highlighted and any other
1820     * alternate addresses for the contact.
1821     * @param currentChip Chip to select.
1822     * @return A RecipientChip in the selected state or null if the chip
1823     * just contained an email address.
1824     */
1825    private RecipientChip selectChip(RecipientChip currentChip) {
1826        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1827            CharSequence text = currentChip.getValue();
1828            Editable editable = getText();
1829            removeChip(currentChip);
1830            editable.append(text);
1831            setCursorVisible(true);
1832            setSelection(editable.length());
1833            return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
1834        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1835            int start = getChipStart(currentChip);
1836            int end = getChipEnd(currentChip);
1837            getSpannable().removeSpan(currentChip);
1838            RecipientChip newChip;
1839            try {
1840                if (mNoChips) {
1841                    return null;
1842                }
1843                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1844            } catch (NullPointerException e) {
1845                Log.e(TAG, e.getMessage(), e);
1846                return null;
1847            }
1848            Editable editable = getText();
1849            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1850            if (start == -1 || end == -1) {
1851                Log.d(TAG, "The chip being selected no longer exists but should.");
1852            } else {
1853                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1854            }
1855            newChip.setSelected(true);
1856            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1857                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1858            }
1859            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1860            setCursorVisible(false);
1861            return newChip;
1862        } else {
1863            int start = getChipStart(currentChip);
1864            int end = getChipEnd(currentChip);
1865            getSpannable().removeSpan(currentChip);
1866            RecipientChip newChip;
1867            try {
1868                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1869            } catch (NullPointerException e) {
1870                Log.e(TAG, e.getMessage(), e);
1871                return null;
1872            }
1873            Editable editable = getText();
1874            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1875            if (start == -1 || end == -1) {
1876                Log.d(TAG, "The chip being selected no longer exists but should.");
1877            } else {
1878                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1879            }
1880            newChip.setSelected(true);
1881            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1882                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1883            }
1884            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1885            setCursorVisible(false);
1886            return newChip;
1887        }
1888    }
1889
1890
1891    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1892            int width, Context context) {
1893        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1894        int bottom = calculateOffsetFromBottom(line);
1895        // Align the alternates popup with the left side of the View,
1896        // regardless of the position of the chip tapped.
1897        setEnabled(false);
1898        popup.setWidth(width);
1899        popup.setAnchorView(this);
1900        popup.setVerticalOffset(bottom);
1901        popup.setAdapter(createSingleAddressAdapter(currentChip));
1902        popup.setOnItemClickListener(new OnItemClickListener() {
1903            @Override
1904            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1905                unselectChip(currentChip);
1906                popup.dismiss();
1907            }
1908        });
1909        popup.show();
1910        ListView listView = popup.getListView();
1911        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1912        listView.setItemChecked(0, true);
1913    }
1914
1915    /**
1916     * Remove selection from this chip. Unselecting a RecipientChip will render
1917     * the chip without a delete icon and with an unfocused background. This is
1918     * called when the RecipientChip no longer has focus.
1919     */
1920    private void unselectChip(RecipientChip chip) {
1921        int start = getChipStart(chip);
1922        int end = getChipEnd(chip);
1923        Editable editable = getText();
1924        mSelectedChip = null;
1925        if (start == -1 || end == -1) {
1926            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
1927            setSelection(editable.length());
1928            commitDefault();
1929        } else {
1930            getSpannable().removeSpan(chip);
1931            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1932            editable.removeSpan(chip);
1933            try {
1934                if (!mNoChips) {
1935                    editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1936                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1937                }
1938            } catch (NullPointerException e) {
1939                Log.e(TAG, e.getMessage(), e);
1940            }
1941        }
1942        setCursorVisible(true);
1943        setSelection(editable.length());
1944        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1945            mAlternatesPopup.dismiss();
1946        }
1947    }
1948
1949    /**
1950     * Return whether a touch event was inside the delete target of
1951     * a selected chip. It is in the delete target if:
1952     * 1) the x and y points of the event are within the
1953     * delete assset.
1954     * 2) the point tapped would have caused a cursor to appear
1955     * right after the selected chip.
1956     * @return boolean
1957     */
1958    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1959        // Figure out the bounds of this chip and whether or not
1960        // the user clicked in the X portion.
1961        return chip.isSelected() && offset == getChipEnd(chip);
1962    }
1963
1964    /**
1965     * Remove the chip and any text associated with it from the RecipientEditTextView.
1966     */
1967    // Visible for testing.
1968    /*pacakge*/ void removeChip(RecipientChip chip) {
1969        Spannable spannable = getSpannable();
1970        int spanStart = spannable.getSpanStart(chip);
1971        int spanEnd = spannable.getSpanEnd(chip);
1972        Editable text = getText();
1973        int toDelete = spanEnd;
1974        boolean wasSelected = chip == mSelectedChip;
1975        // Clear that there is a selected chip before updating any text.
1976        if (wasSelected) {
1977            mSelectedChip = null;
1978        }
1979        // Always remove trailing spaces when removing a chip.
1980        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1981            toDelete++;
1982        }
1983        spannable.removeSpan(chip);
1984        if (spanStart >= 0 && toDelete > 0) {
1985            text.delete(spanStart, toDelete);
1986        }
1987        if (wasSelected) {
1988            clearSelectedChip();
1989        }
1990    }
1991
1992    /**
1993     * Replace this currently selected chip with a new chip
1994     * that uses the contact data provided.
1995     */
1996    // Visible for testing.
1997    /*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) {
1998        boolean wasSelected = chip == mSelectedChip;
1999        if (wasSelected) {
2000            mSelectedChip = null;
2001        }
2002        int start = getChipStart(chip);
2003        int end = getChipEnd(chip);
2004        getSpannable().removeSpan(chip);
2005        Editable editable = getText();
2006        CharSequence chipText = createChip(entry, false);
2007        if (chipText != null) {
2008            if (start == -1 || end == -1) {
2009                Log.e(TAG, "The chip to replace does not exist but should.");
2010                editable.insert(0, chipText);
2011            } else {
2012                if (!TextUtils.isEmpty(chipText)) {
2013                    // There may be a space to replace with this chip's new
2014                    // associated
2015                    // space. Check for it
2016                    int toReplace = end;
2017                    while (toReplace >= 0 && toReplace < editable.length()
2018                            && editable.charAt(toReplace) == ' ') {
2019                        toReplace++;
2020                    }
2021                    editable.replace(start, toReplace, chipText);
2022                }
2023            }
2024        }
2025        setCursorVisible(true);
2026        if (wasSelected) {
2027            clearSelectedChip();
2028        }
2029    }
2030
2031    /**
2032     * Handle click events for a chip. When a selected chip receives a click
2033     * event, see if that event was in the delete icon. If so, delete it.
2034     * Otherwise, unselect the chip.
2035     */
2036    public void onClick(RecipientChip chip, int offset, float x, float y) {
2037        if (chip.isSelected()) {
2038            if (isInDelete(chip, offset, x, y)) {
2039                removeChip(chip);
2040            } else {
2041                clearSelectedChip();
2042            }
2043        }
2044    }
2045
2046    private boolean chipsPending() {
2047        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2048    }
2049
2050    @Override
2051    public void removeTextChangedListener(TextWatcher watcher) {
2052        mTextWatcher = null;
2053        super.removeTextChangedListener(watcher);
2054    }
2055
2056    private class RecipientTextWatcher implements TextWatcher {
2057
2058        @Override
2059        public void afterTextChanged(Editable s) {
2060            // If the text has been set to null or empty, make sure we remove
2061            // all the spans we applied.
2062            if (TextUtils.isEmpty(s)) {
2063                // Remove all the chips spans.
2064                Spannable spannable = getSpannable();
2065                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
2066                        RecipientChip.class);
2067                for (RecipientChip chip : chips) {
2068                    spannable.removeSpan(chip);
2069                }
2070                if (mMoreChip != null) {
2071                    spannable.removeSpan(mMoreChip);
2072                }
2073                return;
2074            }
2075            // Get whether there are any recipients pending addition to the
2076            // view. If there are, don't do anything in the text watcher.
2077            if (chipsPending()) {
2078                return;
2079            }
2080            // If the user is editing a chip, don't clear it.
2081            if (mSelectedChip != null
2082                    && mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
2083                setCursorVisible(true);
2084                setSelection(getText().length());
2085                clearSelectedChip();
2086            }
2087            int length = s.length();
2088            // Make sure there is content there to parse and that it is
2089            // not just the commit character.
2090            if (length > 1) {
2091                char last;
2092                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2093                int len = length() - 1;
2094                if (end != len) {
2095                    last = s.charAt(end);
2096                } else {
2097                    last = s.charAt(len);
2098                }
2099                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
2100                    commitByCharacter();
2101                } else if (last == COMMIT_CHAR_SPACE) {
2102                    // Check if this is a valid email address. If it is,
2103                    // commit it.
2104                    String text = getText().toString();
2105                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2106                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2107                            tokenStart));
2108                    if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) {
2109                        commitByCharacter();
2110                    }
2111                }
2112            }
2113        }
2114
2115        @Override
2116        public void onTextChanged(CharSequence s, int start, int before, int count) {
2117            // This is a delete; check to see if the insertion point is on a space
2118            // following a chip.
2119            if (before > count) {
2120                // If the item deleted is a space, and the thing before the
2121                // space is a chip, delete the entire span.
2122                int selStart = getSelectionStart();
2123                RecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2124                        RecipientChip.class);
2125                if (repl.length > 0) {
2126                    // There is a chip there! Just remove it.
2127                    Editable editable = getText();
2128                    // Add the separator token.
2129                    int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2130                    int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
2131                    tokenEnd = tokenEnd + 1;
2132                    if (tokenEnd > editable.length()) {
2133                        tokenEnd = editable.length();
2134                    }
2135                    editable.delete(tokenStart, tokenEnd);
2136                    getSpannable().removeSpan(repl[0]);
2137                }
2138            }
2139        }
2140
2141        @Override
2142        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2143            // Do nothing.
2144        }
2145    }
2146
2147    /**
2148     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2149     */
2150    private void handlePasteClip(ClipData clip) {
2151        removeTextChangedListener(mTextWatcher);
2152
2153        if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
2154            for (int i = 0; i < clip.getItemCount(); i++) {
2155                CharSequence paste = clip.getItemAt(i).getText();
2156                if (paste != null) {
2157                    int start = getSelectionStart();
2158                    int end = getSelectionEnd();
2159                    Editable editable = getText();
2160                    if (start >= 0 && end >= 0 && start != end) {
2161                        editable.append(paste, start, end);
2162                    } else {
2163                        editable.insert(end, paste);
2164                    }
2165                    handlePasteAndReplace();
2166                }
2167            }
2168        }
2169
2170        mHandler.post(mAddTextWatcher);
2171    }
2172
2173    @Override
2174    public boolean onTextContextMenuItem(int id) {
2175        if (id == android.R.id.paste) {
2176            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2177                    Context.CLIPBOARD_SERVICE);
2178            handlePasteClip(clipboard.getPrimaryClip());
2179            return true;
2180        }
2181        return super.onTextContextMenuItem(id);
2182    }
2183
2184    private void handlePasteAndReplace() {
2185        ArrayList<RecipientChip> created = handlePaste();
2186        if (created != null && created.size() > 0) {
2187            // Perform reverse lookups on the pasted contacts.
2188            IndividualReplacementTask replace = new IndividualReplacementTask();
2189            replace.execute(created);
2190        }
2191    }
2192
2193    // Visible for testing.
2194    /* package */ArrayList<RecipientChip> handlePaste() {
2195        String text = getText().toString();
2196        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2197        String lastAddress = text.substring(originalTokenStart);
2198        int tokenStart = originalTokenStart;
2199        int prevTokenStart = tokenStart;
2200        RecipientChip findChip = null;
2201        ArrayList<RecipientChip> created = new ArrayList<RecipientChip>();
2202        if (tokenStart != 0) {
2203            // There are things before this!
2204            while (tokenStart != 0 && findChip == null) {
2205                prevTokenStart = tokenStart;
2206                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2207                findChip = findChip(tokenStart);
2208            }
2209            if (tokenStart != originalTokenStart) {
2210                if (findChip != null) {
2211                    tokenStart = prevTokenStart;
2212                }
2213                int tokenEnd;
2214                RecipientChip createdChip;
2215                while (tokenStart < originalTokenStart) {
2216                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(text, tokenStart));
2217                    commitChip(tokenStart, tokenEnd, getText());
2218                    createdChip = findChip(tokenStart);
2219                    // +1 for the space at the end.
2220                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2221                    created.add(createdChip);
2222                }
2223            }
2224        }
2225        // Take a look at the last token. If the token has been completed with a
2226        // commit character, create a chip.
2227        if (isCompletedToken(lastAddress)) {
2228            Editable editable = getText();
2229            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2230            commitChip(tokenStart, editable.length(), editable);
2231            created.add(findChip(tokenStart));
2232        }
2233        return created;
2234    }
2235
2236    // Visible for testing.
2237    /* package */int movePastTerminators(int tokenEnd) {
2238        if (tokenEnd >= length()) {
2239            return tokenEnd;
2240        }
2241        char atEnd = getText().toString().charAt(tokenEnd);
2242        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2243            tokenEnd++;
2244        }
2245        // This token had not only an end token character, but also a space
2246        // separating it from the next token.
2247        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2248            tokenEnd++;
2249        }
2250        return tokenEnd;
2251    }
2252
2253    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2254        private RecipientChip createFreeChip(RecipientEntry entry) {
2255            try {
2256                if (mNoChips) {
2257                    return null;
2258                }
2259                return constructChipSpan(entry, -1, false);
2260            } catch (NullPointerException e) {
2261                Log.e(TAG, e.getMessage(), e);
2262                return null;
2263            }
2264        }
2265
2266        @Override
2267        protected Void doInBackground(Void... params) {
2268            if (mIndividualReplacements != null) {
2269                mIndividualReplacements.cancel(true);
2270            }
2271            // For each chip in the list, look up the matching contact.
2272            // If there is a match, replace that chip with the matching
2273            // chip.
2274            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
2275            RecipientChip[] existingChips = getSortedRecipients();
2276            for (int i = 0; i < existingChips.length; i++) {
2277                originalRecipients.add(existingChips[i]);
2278            }
2279            if (mRemovedSpans != null) {
2280                originalRecipients.addAll(mRemovedSpans);
2281            }
2282            String[] addresses = new String[originalRecipients.size()];
2283            RecipientChip chip;
2284            for (int i = 0; i < originalRecipients.size(); i++) {
2285                chip = originalRecipients.get(i);
2286                if (chip != null) {
2287                    addresses[i] = createAddressText(chip.getEntry());
2288                }
2289            }
2290            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2291                    .getMatchingRecipients(getContext(), addresses);
2292            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
2293            for (final RecipientChip temp : originalRecipients) {
2294                RecipientEntry entry = null;
2295                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2296                        && getSpannable().getSpanStart(temp) != -1) {
2297                    // Replace this.
2298                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
2299                            .getDestination())));
2300                }
2301                if (entry != null) {
2302                    replacements.add(createFreeChip(entry));
2303                } else {
2304                    replacements.add(temp);
2305                }
2306            }
2307            if (replacements != null && replacements.size() > 0) {
2308                mHandler.post(new Runnable() {
2309                    @Override
2310                    public void run() {
2311                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
2312                                .toString());
2313                        Editable oldText = getText();
2314                        int start, end;
2315                        int i = 0;
2316                        for (RecipientChip chip : originalRecipients) {
2317                            start = oldText.getSpanStart(chip);
2318                            if (start != -1) {
2319                                end = oldText.getSpanEnd(chip);
2320                                oldText.removeSpan(chip);
2321                                // Leave a spot for the space!
2322                                RecipientChip replacement = replacements.get(i);
2323                                text.setSpan(replacement, start, end,
2324                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2325                                replacement.setOriginalText(text.toString().substring(start, end));
2326                            }
2327                            i++;
2328                        }
2329                        originalRecipients.clear();
2330                        setText(text);
2331                    }
2332                });
2333            }
2334            return null;
2335        }
2336    }
2337
2338    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
2339        @SuppressWarnings("unchecked")
2340        @Override
2341        protected Void doInBackground(Object... params) {
2342            // For each chip in the list, look up the matching contact.
2343            // If there is a match, replace that chip with the matching
2344            // chip.
2345            final ArrayList<RecipientChip> originalRecipients =
2346                (ArrayList<RecipientChip>) params[0];
2347            String[] addresses = new String[originalRecipients.size()];
2348            RecipientChip chip;
2349            for (int i = 0; i < originalRecipients.size(); i++) {
2350                chip = originalRecipients.get(i);
2351                if (chip != null) {
2352                    addresses[i] = createAddressText(chip.getEntry());
2353                }
2354            }
2355            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
2356                    .getMatchingRecipients(getContext(), addresses);
2357            for (final RecipientChip temp : originalRecipients) {
2358                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
2359                        && getSpannable().getSpanStart(temp) != -1) {
2360                    // Replace this.
2361                    final RecipientEntry entry = createValidatedEntry(entries
2362                            .get(tokenizeAddress(temp.getEntry().getDestination()).toLowerCase()));
2363                    if (entry != null) {
2364                        mHandler.post(new Runnable() {
2365                            @Override
2366                            public void run() {
2367                                replaceChip(temp, entry);
2368                            }
2369                        });
2370                    }
2371                }
2372            }
2373            return null;
2374        }
2375    }
2376
2377
2378    /**
2379     * MoreImageSpan is a simple class created for tracking the existence of a
2380     * more chip across activity restarts/
2381     */
2382    private class MoreImageSpan extends ImageSpan {
2383        public MoreImageSpan(Drawable b) {
2384            super(b);
2385        }
2386    }
2387
2388    @Override
2389    public boolean onDown(MotionEvent e) {
2390        return false;
2391    }
2392
2393    @Override
2394    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2395        // Do nothing.
2396        return false;
2397    }
2398
2399    @Override
2400    public void onLongPress(MotionEvent event) {
2401        if (mSelectedChip != null) {
2402            return;
2403        }
2404        float x = event.getX();
2405        float y = event.getY();
2406        int offset = putOffsetInRange(getOffsetForPosition(x, y));
2407        RecipientChip currentChip = findChip(offset);
2408        if (currentChip != null) {
2409            if (mDragEnabled) {
2410                // Start drag-and-drop for the selected chip.
2411                startDrag(currentChip);
2412            } else {
2413                // Copy the selected chip email address.
2414                showCopyDialog(currentChip.getEntry().getDestination());
2415            }
2416        }
2417    }
2418
2419    /**
2420     * Enables drag-and-drop for chips.
2421     */
2422    public void enableDrag() {
2423        mDragEnabled = true;
2424    }
2425
2426    /**
2427     * Starts drag-and-drop for the selected chip.
2428     */
2429    private void startDrag(RecipientChip currentChip) {
2430        String address = currentChip.getEntry().getDestination();
2431        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2432
2433        // Start drag mode.
2434        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2435
2436        // Remove the current chip, so drag-and-drop will result in a move.
2437        // TODO (phamm): consider readd this chip if it's dropped outside a target.
2438        removeChip(currentChip);
2439    }
2440
2441    /**
2442     * Handles drag event.
2443     */
2444    @Override
2445    public boolean onDragEvent(DragEvent event) {
2446        switch (event.getAction()) {
2447            case DragEvent.ACTION_DRAG_STARTED:
2448                // Only handle plain text drag and drop.
2449                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2450            case DragEvent.ACTION_DRAG_ENTERED:
2451                requestFocus();
2452                return true;
2453            case DragEvent.ACTION_DROP:
2454                handlePasteClip(event.getClipData());
2455                return true;
2456        }
2457        return false;
2458    }
2459
2460    /**
2461     * Drag shadow for a {@link RecipientChip}.
2462     */
2463    private final class RecipientChipShadow extends DragShadowBuilder {
2464        private final RecipientChip mChip;
2465
2466        public RecipientChipShadow(RecipientChip chip) {
2467            mChip = chip;
2468        }
2469
2470        @Override
2471        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
2472            Rect rect = mChip.getDrawable().getBounds();
2473            shadowSize.set(rect.width(), rect.height());
2474            shadowTouchPoint.set(rect.centerX(), rect.centerY());
2475        }
2476
2477        @Override
2478        public void onDrawShadow(Canvas canvas) {
2479            mChip.getDrawable().draw(canvas);
2480        }
2481    }
2482
2483    private void showCopyDialog(final String address) {
2484        mCopyAddress = address;
2485        mCopyDialog.setTitle(address);
2486        mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
2487        mCopyDialog.setCancelable(true);
2488        mCopyDialog.setCanceledOnTouchOutside(true);
2489        Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
2490        button.setOnClickListener(this);
2491        int btnTitleId;
2492        if (((BaseRecipientAdapter)getAdapter()).getQueryType() ==
2493                BaseRecipientAdapter.QUERY_TYPE_PHONE) {
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