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