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