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