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