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