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