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