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