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