RecipientEditTextView.java revision cd980d9f73bfa02155f7bb092ae1fb212ed6e8e2
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;
763                            if (loadedPhotoBytes != null) {
764                                icon = BitmapFactory.decodeByteArray(loadedPhotoBytes, 0,
765                                        loadedPhotoBytes.length);
766                            } else {
767                                // TODO: can the scaled down default photo be cached?
768                                icon = mDefaultContactPhoto;
769                            }
770                            // This is called on the main thread so we can draw the icon here
771                            drawIcon(bitmapContainer, icon, paint);
772                            // The view might not redraw itself since it's loaded in the background
773                            invalidate();
774                        }
775                });
776            } else {
777                final Bitmap icon = BitmapFactory.decodeByteArray(origPhotoBytes, 0,
778                        origPhotoBytes.length);
779                drawIcon(bitmapContainer, icon, paint);
780            }
781        }
782    }
783
784    /**
785     * Get the background drawable for a RecipientChip.
786     */
787    // Visible for testing.
788    /* package */Drawable getChipBackground(RecipientEntry contact) {
789        return contact.isValid() ? mChipBackground : mInvalidChipBackground;
790    }
791
792    /**
793     * Given a height, returns a Y offset that will draw the text in the middle of the height.
794     */
795    protected float getTextYOffset(String text, TextPaint paint, int height) {
796        Rect bounds = new Rect();
797        paint.getTextBounds(text, 0, text.length(), bounds);
798        int textHeight = bounds.bottom - bounds.top ;
799        return height - ((height - textHeight) / 2) - (int)paint.descent();
800    }
801
802    /**
803     * Draws the icon onto the canvas given the source rectangle of the bitmap and the destination
804     * rectangle of the canvas.
805     */
806    protected void drawIconOnCanvas(Bitmap icon, Canvas canvas, Paint paint, RectF src, RectF dst) {
807        Matrix matrix = new Matrix();
808        matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
809        canvas.drawBitmap(icon, matrix, paint);
810    }
811
812    private DrawableRecipientChip constructChipSpan(RecipientEntry contact, boolean pressed)
813            throws NullPointerException {
814        if (mChipBackground == null) {
815            throw new NullPointerException(
816                    "Unable to render any chips as setChipDimensions was not called.");
817        }
818
819        TextPaint paint = getPaint();
820        float defaultSize = paint.getTextSize();
821        int defaultColor = paint.getColor();
822
823        Bitmap tmpBitmap;
824        if (pressed) {
825            tmpBitmap = createSelectedChip(contact, paint);
826
827        } else {
828            tmpBitmap = createUnselectedChip(contact, paint);
829        }
830
831        // Pass the full text, un-ellipsized, to the chip.
832        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
833        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
834        DrawableRecipientChip recipientChip =
835                new VisibleRecipientChip(result, contact, getImageSpanAlignment());
836        // Return text to the original size.
837        paint.setTextSize(defaultSize);
838        paint.setColor(defaultColor);
839        return recipientChip;
840    }
841
842    private int getImageSpanAlignment() {
843        switch (mImageSpanAlignment) {
844            case IMAGE_SPAN_ALIGNMENT_BASELINE:
845                return ImageSpan.ALIGN_BASELINE;
846            case IMAGE_SPAN_ALIGNMENT_BOTTOM:
847                return ImageSpan.ALIGN_BOTTOM;
848            default:
849                return ImageSpan.ALIGN_BOTTOM;
850        }
851    }
852
853    /**
854     * Calculate the bottom of the line the chip will be located on using:
855     * 1) which line the chip appears on
856     * 2) the height of a chip
857     * 3) padding built into the edit text view
858     */
859    private int calculateOffsetFromBottom(int line) {
860        // Line offsets start at zero.
861        int actualLine = getLineCount() - (line + 1);
862        return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
863                + getDropDownVerticalOffset();
864    }
865
866    /**
867     * Get the max amount of space a chip can take up. The formula takes into
868     * account the width of the EditTextView, any view padding, and padding
869     * that will be added to the chip.
870     */
871    private float calculateAvailableWidth() {
872        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
873    }
874
875
876    private void setChipDimensions(Context context, AttributeSet attrs) {
877        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
878                0);
879        Resources r = getContext().getResources();
880
881        mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
882        if (mChipBackground == null) {
883            mChipBackground = r.getDrawable(R.drawable.chip_background);
884        }
885        mChipBackgroundPressed = a
886                .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed);
887        if (mChipBackgroundPressed == null) {
888            mChipBackgroundPressed = r.getDrawable(R.drawable.chip_background_selected);
889        }
890        mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
891        if (mChipDelete == null) {
892            mChipDelete = r.getDrawable(R.drawable.chip_delete);
893        }
894        mChipPadding = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
895        if (mChipPadding == -1) {
896            mChipPadding = (int) r.getDimension(R.dimen.chip_padding);
897        }
898
899        mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
900
901        mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
902
903        mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
904        if (mChipHeight == -1) {
905            mChipHeight = r.getDimension(R.dimen.chip_height);
906        }
907        mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
908        if (mChipFontSize == -1) {
909            mChipFontSize = r.getDimension(R.dimen.chip_text_size);
910        }
911        mInvalidChipBackground = a
912                .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
913        if (mInvalidChipBackground == null) {
914            mInvalidChipBackground = r.getDrawable(R.drawable.chip_background_invalid);
915        }
916        mAvatarPosition = a.getInt(R.styleable.RecipientEditTextView_avatarPosition, 0);
917        mImageSpanAlignment = a.getInt(R.styleable.RecipientEditTextView_imageSpanAlignment, 0);
918        mDisableDelete = a.getBoolean(R.styleable.RecipientEditTextView_disableDelete, false);
919
920        mLineSpacingExtra =  r.getDimension(R.dimen.line_spacing_extra);
921        mMaxLines = r.getInteger(R.integer.chips_max_lines);
922        TypedValue tv = new TypedValue();
923        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
924            mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources()
925                    .getDisplayMetrics());
926        }
927
928        a.recycle();
929    }
930
931    // Visible for testing.
932    /* package */ void setMoreItem(TextView moreItem) {
933        mMoreItem = moreItem;
934    }
935
936
937    // Visible for testing.
938    /* package */ void setChipBackground(Drawable chipBackground) {
939        mChipBackground = chipBackground;
940    }
941
942    // Visible for testing.
943    /* package */ void setChipHeight(int height) {
944        mChipHeight = height;
945    }
946
947    public float getChipHeight() {
948        return mChipHeight;
949    }
950
951    /**
952     * Set whether to shrink the recipients field such that at most
953     * one line of recipients chips are shown when the field loses
954     * focus. By default, the number of displayed recipients will be
955     * limited and a "more" chip will be shown when focus is lost.
956     * @param shrink
957     */
958    public void setOnFocusListShrinkRecipients(boolean shrink) {
959        mShouldShrink = shrink;
960    }
961
962    @Override
963    public void onSizeChanged(int width, int height, int oldw, int oldh) {
964        super.onSizeChanged(width, height, oldw, oldh);
965        if (width != 0 && height != 0) {
966            if (mPendingChipsCount > 0) {
967                postHandlePendingChips();
968            } else {
969                checkChipWidths();
970            }
971        }
972        // Try to find the scroll view parent, if it exists.
973        if (mScrollView == null && !mTriedGettingScrollView) {
974            ViewParent parent = getParent();
975            while (parent != null && !(parent instanceof ScrollView)) {
976                parent = parent.getParent();
977            }
978            if (parent != null) {
979                mScrollView = (ScrollView) parent;
980            }
981            mTriedGettingScrollView = true;
982        }
983    }
984
985    private void postHandlePendingChips() {
986        mHandler.removeCallbacks(mHandlePendingChips);
987        mHandler.post(mHandlePendingChips);
988    }
989
990    private void checkChipWidths() {
991        // Check the widths of the associated chips.
992        DrawableRecipientChip[] chips = getSortedRecipients();
993        if (chips != null) {
994            Rect bounds;
995            for (DrawableRecipientChip chip : chips) {
996                bounds = chip.getBounds();
997                if (getWidth() > 0 && bounds.right - bounds.left >
998                        getWidth() - getPaddingLeft() - getPaddingRight()) {
999                    // Need to redraw that chip.
1000                    replaceChip(chip, chip.getEntry());
1001                }
1002            }
1003        }
1004    }
1005
1006    // Visible for testing.
1007    /*package*/ void handlePendingChips() {
1008        if (getViewWidth() <= 0) {
1009            // The widget has not been sized yet.
1010            // This will be called as a result of onSizeChanged
1011            // at a later point.
1012            return;
1013        }
1014        if (mPendingChipsCount <= 0) {
1015            return;
1016        }
1017
1018        synchronized (mPendingChips) {
1019            Editable editable = getText();
1020            // Tokenize!
1021            if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
1022                for (int i = 0; i < mPendingChips.size(); i++) {
1023                    String current = mPendingChips.get(i);
1024                    int tokenStart = editable.toString().indexOf(current);
1025                    // Always leave a space at the end between tokens.
1026                    int tokenEnd = tokenStart + current.length() - 1;
1027                    if (tokenStart >= 0) {
1028                        // When we have a valid token, include it with the token
1029                        // to the left.
1030                        if (tokenEnd < editable.length() - 2
1031                                && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
1032                            tokenEnd++;
1033                        }
1034                        createReplacementChip(tokenStart, tokenEnd, editable, i < CHIP_LIMIT
1035                                || !mShouldShrink);
1036                    }
1037                    mPendingChipsCount--;
1038                }
1039                sanitizeEnd();
1040            } else {
1041                mNoChips = true;
1042            }
1043
1044            if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
1045                    && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
1046                if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
1047                    new RecipientReplacementTask().execute();
1048                    mTemporaryRecipients = null;
1049                } else {
1050                    // Create the "more" chip
1051                    mIndividualReplacements = new IndividualReplacementTask();
1052                    mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(
1053                            mTemporaryRecipients.subList(0, CHIP_LIMIT)));
1054                    if (mTemporaryRecipients.size() > CHIP_LIMIT) {
1055                        mTemporaryRecipients = new ArrayList<DrawableRecipientChip>(
1056                                mTemporaryRecipients.subList(CHIP_LIMIT,
1057                                        mTemporaryRecipients.size()));
1058                    } else {
1059                        mTemporaryRecipients = null;
1060                    }
1061                    createMoreChip();
1062                }
1063            } else {
1064                // There are too many recipients to look up, so just fall back
1065                // to showing addresses for all of them.
1066                mTemporaryRecipients = null;
1067                createMoreChip();
1068            }
1069            mPendingChipsCount = 0;
1070            mPendingChips.clear();
1071        }
1072    }
1073
1074    // Visible for testing.
1075    /*package*/ int getViewWidth() {
1076        return getWidth();
1077    }
1078
1079    /**
1080     * Remove any characters after the last valid chip.
1081     */
1082    // Visible for testing.
1083    /*package*/ void sanitizeEnd() {
1084        // Don't sanitize while we are waiting for pending chips to complete.
1085        if (mPendingChipsCount > 0) {
1086            return;
1087        }
1088        // Find the last chip; eliminate any commit characters after it.
1089        DrawableRecipientChip[] chips = getSortedRecipients();
1090        Spannable spannable = getSpannable();
1091        if (chips != null && chips.length > 0) {
1092            int end;
1093            mMoreChip = getMoreChip();
1094            if (mMoreChip != null) {
1095                end = spannable.getSpanEnd(mMoreChip);
1096            } else {
1097                end = getSpannable().getSpanEnd(getLastChip());
1098            }
1099            Editable editable = getText();
1100            int length = editable.length();
1101            if (length > end) {
1102                // See what characters occur after that and eliminate them.
1103                if (Log.isLoggable(TAG, Log.DEBUG)) {
1104                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
1105                            + editable);
1106                }
1107                editable.delete(end + 1, length);
1108            }
1109        }
1110    }
1111
1112    /**
1113     * Create a chip that represents just the email address of a recipient. At some later
1114     * point, this chip will be attached to a real contact entry, if one exists.
1115     */
1116    // VisibleForTesting
1117    void createReplacementChip(int tokenStart, int tokenEnd, Editable editable,
1118            boolean visible) {
1119        if (alreadyHasChip(tokenStart, tokenEnd)) {
1120            // There is already a chip present at this location.
1121            // Don't recreate it.
1122            return;
1123        }
1124        String token = editable.toString().substring(tokenStart, tokenEnd);
1125        final String trimmedToken = token.trim();
1126        int commitCharIndex = trimmedToken.lastIndexOf(COMMIT_CHAR_COMMA);
1127        if (commitCharIndex != -1 && commitCharIndex == trimmedToken.length() - 1) {
1128            token = trimmedToken.substring(0, trimmedToken.length() - 1);
1129        }
1130        RecipientEntry entry = createTokenizedEntry(token);
1131        if (entry != null) {
1132            DrawableRecipientChip chip = null;
1133            try {
1134                if (!mNoChips) {
1135                    chip = visible ?
1136                            constructChipSpan(entry, false) : new InvisibleRecipientChip(entry);
1137                }
1138            } catch (NullPointerException e) {
1139                Log.e(TAG, e.getMessage(), e);
1140            }
1141            editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1142            // Add this chip to the list of entries "to replace"
1143            if (chip != null) {
1144                if (mTemporaryRecipients == null) {
1145                    mTemporaryRecipients = new ArrayList<DrawableRecipientChip>();
1146                }
1147                chip.setOriginalText(token);
1148                mTemporaryRecipients.add(chip);
1149            }
1150        }
1151    }
1152
1153    private static boolean isPhoneNumber(String number) {
1154        // TODO: replace this function with libphonenumber's isPossibleNumber (see
1155        // PhoneNumberUtil). One complication is that it requires the sender's region which
1156        // comes from the CurrentCountryIso. For now, let's just do this simple match.
1157        if (TextUtils.isEmpty(number)) {
1158            return false;
1159        }
1160
1161        Matcher match = PHONE_PATTERN.matcher(number);
1162        return match.matches();
1163    }
1164
1165    // VisibleForTesting
1166    RecipientEntry createTokenizedEntry(final String token) {
1167        if (TextUtils.isEmpty(token)) {
1168            return null;
1169        }
1170        if (isPhoneQuery() && isPhoneNumber(token)) {
1171            return RecipientEntry.constructFakePhoneEntry(token, true);
1172        }
1173        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
1174        String display = null;
1175        boolean isValid = isValid(token);
1176        if (isValid && tokens != null && tokens.length > 0) {
1177            // If we can get a name from tokenizing, then generate an entry from
1178            // this.
1179            display = tokens[0].getName();
1180            if (!TextUtils.isEmpty(display)) {
1181                return RecipientEntry.constructGeneratedEntry(display, tokens[0].getAddress(),
1182                        isValid);
1183            } else {
1184                display = tokens[0].getAddress();
1185                if (!TextUtils.isEmpty(display)) {
1186                    return RecipientEntry.constructFakeEntry(display, isValid);
1187                }
1188            }
1189        }
1190        // Unable to validate the token or to create a valid token from it.
1191        // Just create a chip the user can edit.
1192        String validatedToken = null;
1193        if (mValidator != null && !isValid) {
1194            // Try fixing up the entry using the validator.
1195            validatedToken = mValidator.fixText(token).toString();
1196            if (!TextUtils.isEmpty(validatedToken)) {
1197                if (validatedToken.contains(token)) {
1198                    // protect against the case of a validator with a null
1199                    // domain,
1200                    // which doesn't add a domain to the token
1201                    Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
1202                    if (tokenized.length > 0) {
1203                        validatedToken = tokenized[0].getAddress();
1204                        isValid = true;
1205                    }
1206                } else {
1207                    // We ran into a case where the token was invalid and
1208                    // removed
1209                    // by the validator. In this case, just use the original
1210                    // token
1211                    // and let the user sort out the error chip.
1212                    validatedToken = null;
1213                    isValid = false;
1214                }
1215            }
1216        }
1217        // Otherwise, fallback to just creating an editable email address chip.
1218        return RecipientEntry.constructFakeEntry(
1219                !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid);
1220    }
1221
1222    private boolean isValid(String text) {
1223        return mValidator == null ? true : mValidator.isValid(text);
1224    }
1225
1226    private static String tokenizeAddress(String destination) {
1227        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
1228        if (tokens != null && tokens.length > 0) {
1229            return tokens[0].getAddress();
1230        }
1231        return destination;
1232    }
1233
1234    @Override
1235    public void setTokenizer(Tokenizer tokenizer) {
1236        mTokenizer = tokenizer;
1237        super.setTokenizer(mTokenizer);
1238    }
1239
1240    @Override
1241    public void setValidator(Validator validator) {
1242        mValidator = validator;
1243        super.setValidator(validator);
1244    }
1245
1246    /**
1247     * We cannot use the default mechanism for replaceText. Instead,
1248     * we override onItemClickListener so we can get all the associated
1249     * contact information including display text, address, and id.
1250     */
1251    @Override
1252    protected void replaceText(CharSequence text) {
1253        return;
1254    }
1255
1256    /**
1257     * Dismiss any selected chips when the back key is pressed.
1258     */
1259    @Override
1260    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
1261        if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) {
1262            clearSelectedChip();
1263            return true;
1264        }
1265        return super.onKeyPreIme(keyCode, event);
1266    }
1267
1268    /**
1269     * Monitor key presses in this view to see if the user types
1270     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
1271     * If the user has entered text that has contact matches and types
1272     * a commit key, create a chip from the topmost matching contact.
1273     * If the user has entered text that has no contact matches and types
1274     * a commit key, then create a chip from the text they have entered.
1275     */
1276    @Override
1277    public boolean onKeyUp(int keyCode, KeyEvent event) {
1278        switch (keyCode) {
1279            case KeyEvent.KEYCODE_TAB:
1280                if (event.hasNoModifiers()) {
1281                    if (mSelectedChip != null) {
1282                        clearSelectedChip();
1283                    } else {
1284                        commitDefault();
1285                    }
1286                }
1287                break;
1288        }
1289        return super.onKeyUp(keyCode, event);
1290    }
1291
1292    private boolean focusNext() {
1293        View next = focusSearch(View.FOCUS_DOWN);
1294        if (next != null) {
1295            next.requestFocus();
1296            return true;
1297        }
1298        return false;
1299    }
1300
1301    /**
1302     * Create a chip from the default selection. If the popup is showing, the
1303     * default is the selected item (if one is selected), or the first item, in the popup
1304     * suggestions list. Otherwise, it is whatever the user had typed in. End represents where the
1305     * tokenizer should search for a token to turn into a chip.
1306     * @return If a chip was created from a real contact.
1307     */
1308    private boolean commitDefault() {
1309        // If there is no tokenizer, don't try to commit.
1310        if (mTokenizer == null) {
1311            return false;
1312        }
1313        Editable editable = getText();
1314        int end = getSelectionEnd();
1315        int start = mTokenizer.findTokenStart(editable, end);
1316
1317        if (shouldCreateChip(start, end)) {
1318            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1319            // In the middle of chip; treat this as an edit
1320            // and commit the whole token.
1321            whatEnd = movePastTerminators(whatEnd);
1322            if (whatEnd != getSelectionEnd()) {
1323                handleEdit(start, whatEnd);
1324                return true;
1325            }
1326            return commitChip(start, end , editable);
1327        }
1328        return false;
1329    }
1330
1331    private void commitByCharacter() {
1332        // We can't possibly commit by character if we can't tokenize.
1333        if (mTokenizer == null) {
1334            return;
1335        }
1336        Editable editable = getText();
1337        int end = getSelectionEnd();
1338        int start = mTokenizer.findTokenStart(editable, end);
1339        if (shouldCreateChip(start, end)) {
1340            commitChip(start, end, editable);
1341        }
1342        setSelection(getText().length());
1343    }
1344
1345    private boolean commitChip(int start, int end, Editable editable) {
1346        ListAdapter adapter = getAdapter();
1347        if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
1348                && end == getSelectionEnd() && !isPhoneQuery()) {
1349            // let's choose the selected or first entry if only the input text is NOT an email
1350            // address so we won't try to replace the user's potentially correct but
1351            // new/unencountered email input
1352            if (!isValidEmailAddress(editable.toString().substring(start, end).trim())) {
1353                final int selectedPosition = getListSelection();
1354                if (selectedPosition == -1) {
1355                    // Nothing is selected; use the first item
1356                    submitItemAtPosition(0);
1357                } else {
1358                    submitItemAtPosition(selectedPosition);
1359                }
1360            }
1361            dismissDropDown();
1362            return true;
1363        } else {
1364            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
1365            if (editable.length() > tokenEnd + 1) {
1366                char charAt = editable.charAt(tokenEnd + 1);
1367                if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1368                    tokenEnd++;
1369                }
1370            }
1371            String text = editable.toString().substring(start, tokenEnd).trim();
1372            clearComposingText();
1373            if (text != null && text.length() > 0 && !text.equals(" ")) {
1374                RecipientEntry entry = createTokenizedEntry(text);
1375                if (entry != null) {
1376                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
1377                    CharSequence chipText = createChip(entry, false);
1378                    if (chipText != null && start > -1 && end > -1) {
1379                        editable.replace(start, end, chipText);
1380                    }
1381                }
1382                // Only dismiss the dropdown if it is related to the text we
1383                // just committed.
1384                // For paste, it may not be as there are possibly multiple
1385                // tokens being added.
1386                if (end == getSelectionEnd()) {
1387                    dismissDropDown();
1388                }
1389                sanitizeBetween();
1390                return true;
1391            }
1392        }
1393        return false;
1394    }
1395
1396    // Visible for testing.
1397    /* package */ void sanitizeBetween() {
1398        // Don't sanitize while we are waiting for content to chipify.
1399        if (mPendingChipsCount > 0) {
1400            return;
1401        }
1402        // Find the last chip.
1403        DrawableRecipientChip[] recips = getSortedRecipients();
1404        if (recips != null && recips.length > 0) {
1405            DrawableRecipientChip last = recips[recips.length - 1];
1406            DrawableRecipientChip beforeLast = null;
1407            if (recips.length > 1) {
1408                beforeLast = recips[recips.length - 2];
1409            }
1410            int startLooking = 0;
1411            int end = getSpannable().getSpanStart(last);
1412            if (beforeLast != null) {
1413                startLooking = getSpannable().getSpanEnd(beforeLast);
1414                Editable text = getText();
1415                if (startLooking == -1 || startLooking > text.length() - 1) {
1416                    // There is nothing after this chip.
1417                    return;
1418                }
1419                if (text.charAt(startLooking) == ' ') {
1420                    startLooking++;
1421                }
1422            }
1423            if (startLooking >= 0 && end >= 0 && startLooking < end) {
1424                getText().delete(startLooking, end);
1425            }
1426        }
1427    }
1428
1429    private boolean shouldCreateChip(int start, int end) {
1430        return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
1431    }
1432
1433    private boolean alreadyHasChip(int start, int end) {
1434        if (mNoChips) {
1435            return true;
1436        }
1437        DrawableRecipientChip[] chips =
1438                getSpannable().getSpans(start, end, DrawableRecipientChip.class);
1439        if ((chips == null || chips.length == 0)) {
1440            return false;
1441        }
1442        return true;
1443    }
1444
1445    private void handleEdit(int start, int end) {
1446        if (start == -1 || end == -1) {
1447            // This chip no longer exists in the field.
1448            dismissDropDown();
1449            return;
1450        }
1451        // This is in the middle of a chip, so select out the whole chip
1452        // and commit it.
1453        Editable editable = getText();
1454        setSelection(end);
1455        String text = getText().toString().substring(start, end);
1456        if (!TextUtils.isEmpty(text)) {
1457            RecipientEntry entry = RecipientEntry.constructFakeEntry(text, isValid(text));
1458            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1459            CharSequence chipText = createChip(entry, false);
1460            int selEnd = getSelectionEnd();
1461            if (chipText != null && start > -1 && selEnd > -1) {
1462                editable.replace(start, selEnd, chipText);
1463            }
1464        }
1465        dismissDropDown();
1466    }
1467
1468    /**
1469     * If there is a selected chip, delegate the key events
1470     * to the selected chip.
1471     */
1472    @Override
1473    public boolean onKeyDown(int keyCode, KeyEvent event) {
1474        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1475            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1476                mAlternatesPopup.dismiss();
1477            }
1478            removeChip(mSelectedChip);
1479        }
1480
1481        switch (keyCode) {
1482            case KeyEvent.KEYCODE_ENTER:
1483            case KeyEvent.KEYCODE_DPAD_CENTER:
1484                if (event.hasNoModifiers()) {
1485                    if (commitDefault()) {
1486                        return true;
1487                    }
1488                    if (mSelectedChip != null) {
1489                        clearSelectedChip();
1490                        return true;
1491                    } else if (focusNext()) {
1492                        return true;
1493                    }
1494                }
1495                break;
1496        }
1497
1498        return super.onKeyDown(keyCode, event);
1499    }
1500
1501    // Visible for testing.
1502    /* package */ Spannable getSpannable() {
1503        return getText();
1504    }
1505
1506    private int getChipStart(DrawableRecipientChip chip) {
1507        return getSpannable().getSpanStart(chip);
1508    }
1509
1510    private int getChipEnd(DrawableRecipientChip chip) {
1511        return getSpannable().getSpanEnd(chip);
1512    }
1513
1514    /**
1515     * Instead of filtering on the entire contents of the edit box,
1516     * this subclass method filters on the range from
1517     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1518     * if the length of that range meets or exceeds {@link #getThreshold}
1519     * and makes sure that the range is not already a Chip.
1520     */
1521    @Override
1522    protected void performFiltering(CharSequence text, int keyCode) {
1523        boolean isCompletedToken = isCompletedToken(text);
1524        if (enoughToFilter() && !isCompletedToken) {
1525            int end = getSelectionEnd();
1526            int start = mTokenizer.findTokenStart(text, end);
1527            // If this is a RecipientChip, don't filter
1528            // on its contents.
1529            Spannable span = getSpannable();
1530            DrawableRecipientChip[] chips = span.getSpans(start, end, DrawableRecipientChip.class);
1531            if (chips != null && chips.length > 0) {
1532                dismissDropDown();
1533                return;
1534            }
1535        } else if (isCompletedToken) {
1536            dismissDropDown();
1537            return;
1538        }
1539        super.performFiltering(text, keyCode);
1540    }
1541
1542    // Visible for testing.
1543    /*package*/ boolean isCompletedToken(CharSequence text) {
1544        if (TextUtils.isEmpty(text)) {
1545            return false;
1546        }
1547        // Check to see if this is a completed token before filtering.
1548        int end = text.length();
1549        int start = mTokenizer.findTokenStart(text, end);
1550        String token = text.toString().substring(start, end).trim();
1551        if (!TextUtils.isEmpty(token)) {
1552            char atEnd = token.charAt(token.length() - 1);
1553            return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1554        }
1555        return false;
1556    }
1557
1558    private void clearSelectedChip() {
1559        if (mSelectedChip != null) {
1560            unselectChip(mSelectedChip);
1561            mSelectedChip = null;
1562        }
1563        setCursorVisible(true);
1564    }
1565
1566    /**
1567     * Monitor touch events in the RecipientEditTextView.
1568     * If the view does not have focus, any tap on the view
1569     * will just focus the view. If the view has focus, determine
1570     * if the touch target is a recipient chip. If it is and the chip
1571     * is not selected, select it and clear any other selected chips.
1572     * If it isn't, then select that chip.
1573     */
1574    @Override
1575    public boolean onTouchEvent(MotionEvent event) {
1576        if (!isFocused()) {
1577            // Ignore any chip taps until this view is focused.
1578            return super.onTouchEvent(event);
1579        }
1580        boolean handled = super.onTouchEvent(event);
1581        int action = event.getAction();
1582        boolean chipWasSelected = false;
1583        if (mSelectedChip == null) {
1584            mGestureDetector.onTouchEvent(event);
1585        }
1586        if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
1587            float x = event.getX();
1588            float y = event.getY();
1589            int offset = putOffsetInRange(x, y);
1590            DrawableRecipientChip currentChip = findChip(offset);
1591            if (currentChip != null) {
1592                if (action == MotionEvent.ACTION_UP) {
1593                    if (mSelectedChip != null && mSelectedChip != currentChip) {
1594                        clearSelectedChip();
1595                        mSelectedChip = selectChip(currentChip);
1596                    } else if (mSelectedChip == null) {
1597                        setSelection(getText().length());
1598                        commitDefault();
1599                        mSelectedChip = selectChip(currentChip);
1600                    } else {
1601                        onClick(mSelectedChip, offset, x, y);
1602                    }
1603                }
1604                chipWasSelected = true;
1605                handled = true;
1606            } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
1607                chipWasSelected = true;
1608            }
1609        }
1610        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1611            clearSelectedChip();
1612        }
1613        return handled;
1614    }
1615
1616    private void scrollLineIntoView(int line) {
1617        if (mScrollView != null) {
1618            mScrollView.smoothScrollBy(0, calculateOffsetFromBottom(line));
1619        }
1620    }
1621
1622    private void showAlternates(final DrawableRecipientChip currentChip,
1623            final ListPopupWindow alternatesPopup, final int width) {
1624        new AsyncTask<Void, Void, ListAdapter>() {
1625            @Override
1626            protected ListAdapter doInBackground(final Void... params) {
1627                return createAlternatesAdapter(currentChip);
1628            }
1629
1630            @Override
1631            protected void onPostExecute(final ListAdapter result) {
1632                if (!mAttachedToWindow) {
1633                    return;
1634                }
1635                int line = getLayout().getLineForOffset(getChipStart(currentChip));
1636                int bottom;
1637                if (line == getLineCount() -1) {
1638                    bottom = 0;
1639                } else {
1640                    bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math
1641                            .abs(getLineCount() - 1 - line)));
1642                }
1643                // Align the alternates popup with the left side of the View,
1644                // regardless of the position of the chip tapped.
1645                alternatesPopup.setWidth(width);
1646                alternatesPopup.setAnchorView(RecipientEditTextView.this);
1647                alternatesPopup.setVerticalOffset(bottom);
1648                alternatesPopup.setAdapter(result);
1649                alternatesPopup.setOnItemClickListener(mAlternatesListener);
1650                // Clear the checked item.
1651                mCheckedItem = -1;
1652                alternatesPopup.show();
1653                ListView listView = alternatesPopup.getListView();
1654                listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1655                // Checked item would be -1 if the adapter has not
1656                // loaded the view that should be checked yet. The
1657                // variable will be set correctly when onCheckedItemChanged
1658                // is called in a separate thread.
1659                if (mCheckedItem != -1) {
1660                    listView.setItemChecked(mCheckedItem, true);
1661                    mCheckedItem = -1;
1662                }
1663            }
1664        }.execute((Void[]) null);
1665    }
1666
1667    private ListAdapter createAlternatesAdapter(DrawableRecipientChip chip) {
1668        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(),
1669                chip.getDirectoryId(), chip.getLookupKey(), chip.getDataId(),
1670                getAdapter().getQueryType(), this, mDropdownChipLayouter);
1671    }
1672
1673    private ListAdapter createSingleAddressAdapter(DrawableRecipientChip currentChip) {
1674        return new SingleRecipientArrayAdapter(getContext(), currentChip.getEntry(),
1675                mDropdownChipLayouter);
1676    }
1677
1678    @Override
1679    public void onCheckedItemChanged(int position) {
1680        ListView listView = mAlternatesPopup.getListView();
1681        if (listView != null && listView.getCheckedItemCount() == 0) {
1682            listView.setItemChecked(position, true);
1683        }
1684        mCheckedItem = position;
1685    }
1686
1687    private int putOffsetInRange(final float x, final float y) {
1688        final int offset;
1689
1690        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1691            offset = getOffsetForPosition(x, y);
1692        } else {
1693            offset = supportGetOffsetForPosition(x, y);
1694        }
1695
1696        return putOffsetInRange(offset);
1697    }
1698
1699    // TODO: This algorithm will need a lot of tweaking after more people have used
1700    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1701    // what comes before the finger.
1702    private int putOffsetInRange(int o) {
1703        int offset = o;
1704        Editable text = getText();
1705        int length = text.length();
1706        // Remove whitespace from end to find "real end"
1707        int realLength = length;
1708        for (int i = length - 1; i >= 0; i--) {
1709            if (text.charAt(i) == ' ') {
1710                realLength--;
1711            } else {
1712                break;
1713            }
1714        }
1715
1716        // If the offset is beyond or at the end of the text,
1717        // leave it alone.
1718        if (offset >= realLength) {
1719            return offset;
1720        }
1721        Editable editable = getText();
1722        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1723            // Keep walking backward!
1724            offset--;
1725        }
1726        return offset;
1727    }
1728
1729    private static int findText(Editable text, int offset) {
1730        if (text.charAt(offset) != ' ') {
1731            return offset;
1732        }
1733        return -1;
1734    }
1735
1736    private DrawableRecipientChip findChip(int offset) {
1737        DrawableRecipientChip[] chips =
1738                getSpannable().getSpans(0, getText().length(), DrawableRecipientChip.class);
1739        // Find the chip that contains this offset.
1740        for (int i = 0; i < chips.length; i++) {
1741            DrawableRecipientChip chip = chips[i];
1742            int start = getChipStart(chip);
1743            int end = getChipEnd(chip);
1744            if (offset >= start && offset <= end) {
1745                return chip;
1746            }
1747        }
1748        return null;
1749    }
1750
1751    // Visible for testing.
1752    // Use this method to generate text to add to the list of addresses.
1753    /* package */String createAddressText(RecipientEntry entry) {
1754        String display = entry.getDisplayName();
1755        String address = entry.getDestination();
1756        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1757            display = null;
1758        }
1759        String trimmedDisplayText;
1760        if (isPhoneQuery() && isPhoneNumber(address)) {
1761            trimmedDisplayText = address.trim();
1762        } else {
1763            if (address != null) {
1764                // Tokenize out the address in case the address already
1765                // contained the username as well.
1766                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1767                if (tokenized != null && tokenized.length > 0) {
1768                    address = tokenized[0].getAddress();
1769                }
1770            }
1771            Rfc822Token token = new Rfc822Token(display, address, null);
1772            trimmedDisplayText = token.toString().trim();
1773        }
1774        int index = trimmedDisplayText.indexOf(",");
1775        return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1776                && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
1777                .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1778    }
1779
1780    // Visible for testing.
1781    // Use this method to generate text to display in a chip.
1782    /*package*/ String createChipDisplayText(RecipientEntry entry) {
1783        String display = entry.getDisplayName();
1784        String address = entry.getDestination();
1785        if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1786            display = null;
1787        }
1788        if (!TextUtils.isEmpty(display)) {
1789            return display;
1790        } else if (!TextUtils.isEmpty(address)){
1791            return address;
1792        } else {
1793            return new Rfc822Token(display, address, null).toString();
1794        }
1795    }
1796
1797    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1798        String displayText = createAddressText(entry);
1799        if (TextUtils.isEmpty(displayText)) {
1800            return null;
1801        }
1802        SpannableString chipText = null;
1803        // Always leave a blank space at the end of a chip.
1804        int textLength = displayText.length() - 1;
1805        chipText = new SpannableString(displayText);
1806        if (!mNoChips) {
1807            try {
1808                DrawableRecipientChip chip = constructChipSpan(entry, pressed);
1809                chipText.setSpan(chip, 0, textLength,
1810                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1811                chip.setOriginalText(chipText.toString());
1812            } catch (NullPointerException e) {
1813                Log.e(TAG, e.getMessage(), e);
1814                return null;
1815            }
1816        }
1817        return chipText;
1818    }
1819
1820    /**
1821     * When an item in the suggestions list has been clicked, create a chip from the
1822     * contact information of the selected item.
1823     */
1824    @Override
1825    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1826        if (position < 0) {
1827            return;
1828        }
1829
1830        final int charactersTyped = submitItemAtPosition(position);
1831        if (charactersTyped > -1 && mRecipientEntryItemClickedListener != null) {
1832            mRecipientEntryItemClickedListener
1833                    .onRecipientEntryItemClicked(charactersTyped, position);
1834        }
1835    }
1836
1837    private int submitItemAtPosition(int position) {
1838        RecipientEntry entry = createValidatedEntry(getAdapter().getItem(position));
1839        if (entry == null) {
1840            return -1;
1841        }
1842        clearComposingText();
1843
1844        int end = getSelectionEnd();
1845        int start = mTokenizer.findTokenStart(getText(), end);
1846
1847        Editable editable = getText();
1848        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1849        CharSequence chip = createChip(entry, false);
1850        if (chip != null && start >= 0 && end >= 0) {
1851            editable.replace(start, end, chip);
1852        }
1853        sanitizeBetween();
1854
1855        return end - start;
1856    }
1857
1858    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1859        if (item == null) {
1860            return null;
1861        }
1862        final RecipientEntry entry;
1863        // If the display name and the address are the same, or if this is a
1864        // valid contact, but the destination is invalid, then make this a fake
1865        // recipient that is editable.
1866        String destination = item.getDestination();
1867        if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1868            entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
1869                    destination, item.isValid());
1870        } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
1871                && (TextUtils.isEmpty(item.getDisplayName())
1872                        || TextUtils.equals(item.getDisplayName(), destination)
1873                        || (mValidator != null && !mValidator.isValid(destination)))) {
1874            entry = RecipientEntry.constructFakeEntry(destination, item.isValid());
1875        } else {
1876            entry = item;
1877        }
1878        return entry;
1879    }
1880
1881    // Visible for testing.
1882    /* package */DrawableRecipientChip[] getSortedRecipients() {
1883        DrawableRecipientChip[] recips = getSpannable()
1884                .getSpans(0, getText().length(), DrawableRecipientChip.class);
1885        ArrayList<DrawableRecipientChip> recipientsList = new ArrayList<DrawableRecipientChip>(
1886                Arrays.asList(recips));
1887        final Spannable spannable = getSpannable();
1888        Collections.sort(recipientsList, new Comparator<DrawableRecipientChip>() {
1889
1890            @Override
1891            public int compare(DrawableRecipientChip first, DrawableRecipientChip second) {
1892                int firstStart = spannable.getSpanStart(first);
1893                int secondStart = spannable.getSpanStart(second);
1894                if (firstStart < secondStart) {
1895                    return -1;
1896                } else if (firstStart > secondStart) {
1897                    return 1;
1898                } else {
1899                    return 0;
1900                }
1901            }
1902        });
1903        return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
1904    }
1905
1906    @Override
1907    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1908        return false;
1909    }
1910
1911    @Override
1912    public void onDestroyActionMode(ActionMode mode) {
1913    }
1914
1915    @Override
1916    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1917        return false;
1918    }
1919
1920    /**
1921     * No chips are selectable.
1922     */
1923    @Override
1924    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1925        return false;
1926    }
1927
1928    // Visible for testing.
1929    /* package */ImageSpan getMoreChip() {
1930        MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1931                MoreImageSpan.class);
1932        return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1933    }
1934
1935    private MoreImageSpan createMoreSpan(int count) {
1936        String moreText = String.format(mMoreItem.getText().toString(), count);
1937        TextPaint morePaint = new TextPaint(getPaint());
1938        morePaint.setTextSize(mMoreItem.getTextSize());
1939        morePaint.setColor(mMoreItem.getCurrentTextColor());
1940        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1941                + mMoreItem.getPaddingRight();
1942        int height = getLineHeight();
1943        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1944        Canvas canvas = new Canvas(drawable);
1945        int adjustedHeight = height;
1946        Layout layout = getLayout();
1947        if (layout != null) {
1948            adjustedHeight -= layout.getLineDescent(0);
1949        }
1950        canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
1951
1952        Drawable result = new BitmapDrawable(getResources(), drawable);
1953        result.setBounds(0, 0, width, height);
1954        return new MoreImageSpan(result);
1955    }
1956
1957    // Visible for testing.
1958    /*package*/ void createMoreChipPlainText() {
1959        // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
1960        Editable text = getText();
1961        int start = 0;
1962        int end = start;
1963        for (int i = 0; i < CHIP_LIMIT; i++) {
1964            end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1965            start = end; // move to the next token and get its end.
1966        }
1967        // Now, count total addresses.
1968        start = 0;
1969        int tokenCount = countTokens(text);
1970        MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
1971        SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
1972        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1973        text.replace(end, text.length(), chipText);
1974        mMoreChip = moreSpan;
1975    }
1976
1977    // Visible for testing.
1978    /* package */int countTokens(Editable text) {
1979        int tokenCount = 0;
1980        int start = 0;
1981        while (start < text.length()) {
1982            start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
1983            tokenCount++;
1984            if (start >= text.length()) {
1985                break;
1986            }
1987        }
1988        return tokenCount;
1989    }
1990
1991    /**
1992     * Create the more chip. The more chip is text that replaces any chips that
1993     * do not fit in the pre-defined available space when the
1994     * RecipientEditTextView loses focus.
1995     */
1996    // Visible for testing.
1997    /* package */ void createMoreChip() {
1998        if (mNoChips) {
1999            createMoreChipPlainText();
2000            return;
2001        }
2002
2003        if (!mShouldShrink) {
2004            return;
2005        }
2006        ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
2007        if (tempMore.length > 0) {
2008            getSpannable().removeSpan(tempMore[0]);
2009        }
2010        DrawableRecipientChip[] recipients = getSortedRecipients();
2011
2012        if (recipients == null || recipients.length <= CHIP_LIMIT) {
2013            mMoreChip = null;
2014            return;
2015        }
2016        Spannable spannable = getSpannable();
2017        int numRecipients = recipients.length;
2018        int overage = numRecipients - CHIP_LIMIT;
2019        MoreImageSpan moreSpan = createMoreSpan(overage);
2020        mRemovedSpans = new ArrayList<DrawableRecipientChip>();
2021        int totalReplaceStart = 0;
2022        int totalReplaceEnd = 0;
2023        Editable text = getText();
2024        for (int i = numRecipients - overage; i < recipients.length; i++) {
2025            mRemovedSpans.add(recipients[i]);
2026            if (i == numRecipients - overage) {
2027                totalReplaceStart = spannable.getSpanStart(recipients[i]);
2028            }
2029            if (i == recipients.length - 1) {
2030                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
2031            }
2032            if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
2033                int spanStart = spannable.getSpanStart(recipients[i]);
2034                int spanEnd = spannable.getSpanEnd(recipients[i]);
2035                recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
2036            }
2037            spannable.removeSpan(recipients[i]);
2038        }
2039        if (totalReplaceEnd < text.length()) {
2040            totalReplaceEnd = text.length();
2041        }
2042        int end = Math.max(totalReplaceStart, totalReplaceEnd);
2043        int start = Math.min(totalReplaceStart, totalReplaceEnd);
2044        SpannableString chipText = new SpannableString(text.subSequence(start, end));
2045        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2046        text.replace(start, end, chipText);
2047        mMoreChip = moreSpan;
2048        // If adding the +more chip goes over the limit, resize accordingly.
2049        if (!isPhoneQuery() && getLineCount() > mMaxLines) {
2050            setMaxLines(getLineCount());
2051        }
2052    }
2053
2054    /**
2055     * Replace the more chip, if it exists, with all of the recipient chips it had
2056     * replaced when the RecipientEditTextView gains focus.
2057     */
2058    // Visible for testing.
2059    /*package*/ void removeMoreChip() {
2060        if (mMoreChip != null) {
2061            Spannable span = getSpannable();
2062            span.removeSpan(mMoreChip);
2063            mMoreChip = null;
2064            // Re-add the spans that were removed.
2065            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
2066                // Recreate each removed span.
2067                DrawableRecipientChip[] recipients = getSortedRecipients();
2068                // Start the search for tokens after the last currently visible
2069                // chip.
2070                if (recipients == null || recipients.length == 0) {
2071                    return;
2072                }
2073                int end = span.getSpanEnd(recipients[recipients.length - 1]);
2074                Editable editable = getText();
2075                for (DrawableRecipientChip chip : mRemovedSpans) {
2076                    int chipStart;
2077                    int chipEnd;
2078                    String token;
2079                    // Need to find the location of the chip, again.
2080                    token = (String) chip.getOriginalText();
2081                    // As we find the matching recipient for the remove spans,
2082                    // reduce the size of the string we need to search.
2083                    // That way, if there are duplicates, we always find the correct
2084                    // recipient.
2085                    chipStart = editable.toString().indexOf(token, end);
2086                    end = chipEnd = Math.min(editable.length(), chipStart + token.length());
2087                    // Only set the span if we found a matching token.
2088                    if (chipStart != -1) {
2089                        editable.setSpan(chip, chipStart, chipEnd,
2090                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
2091                    }
2092                }
2093                mRemovedSpans.clear();
2094            }
2095        }
2096    }
2097
2098    /**
2099     * Show specified chip as selected. If the RecipientChip is just an email address,
2100     * selecting the chip will take the contents of the chip and place it at
2101     * the end of the RecipientEditTextView for inline editing. If the
2102     * RecipientChip is a complete contact, then selecting the chip
2103     * will change the background color of the chip, show the delete icon,
2104     * and a popup window with the address in use highlighted and any other
2105     * alternate addresses for the contact.
2106     * @param currentChip Chip to select.
2107     * @return A RecipientChip in the selected state or null if the chip
2108     * just contained an email address.
2109     */
2110    private DrawableRecipientChip selectChip(DrawableRecipientChip currentChip) {
2111        if (shouldShowEditableText(currentChip)) {
2112            CharSequence text = currentChip.getValue();
2113            Editable editable = getText();
2114            Spannable spannable = getSpannable();
2115            int spanStart = spannable.getSpanStart(currentChip);
2116            int spanEnd = spannable.getSpanEnd(currentChip);
2117            spannable.removeSpan(currentChip);
2118            editable.delete(spanStart, spanEnd);
2119            setCursorVisible(true);
2120            setSelection(editable.length());
2121            editable.append(text);
2122            return constructChipSpan(
2123                    RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())),
2124                    true);
2125        } else {
2126            int start = getChipStart(currentChip);
2127            int end = getChipEnd(currentChip);
2128            getSpannable().removeSpan(currentChip);
2129            DrawableRecipientChip newChip;
2130            final boolean showAddress =
2131                    currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT ||
2132                    getAdapter().forceShowAddress();
2133            try {
2134                if (showAddress && mNoChips) {
2135                    return null;
2136                }
2137                newChip = constructChipSpan(currentChip.getEntry(), true);
2138            } catch (NullPointerException e) {
2139                Log.e(TAG, e.getMessage(), e);
2140                return null;
2141            }
2142            Editable editable = getText();
2143            QwertyKeyListener.markAsReplaced(editable, start, end, "");
2144            if (start == -1 || end == -1) {
2145                Log.d(TAG, "The chip being selected no longer exists but should.");
2146            } else {
2147                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2148            }
2149            newChip.setSelected(true);
2150            if (shouldShowEditableText(newChip)) {
2151                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
2152            }
2153            if (showAddress) {
2154                showAddress(newChip, mAddressPopup, getWidth());
2155            } else {
2156                showAlternates(newChip, mAlternatesPopup, getWidth());
2157            }
2158            setCursorVisible(false);
2159            return newChip;
2160        }
2161    }
2162
2163    private boolean shouldShowEditableText(DrawableRecipientChip currentChip) {
2164        long contactId = currentChip.getContactId();
2165        return contactId == RecipientEntry.INVALID_CONTACT
2166                || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2167    }
2168
2169    private void showAddress(final DrawableRecipientChip currentChip, final ListPopupWindow popup,
2170            int width) {
2171        if (!mAttachedToWindow) {
2172            return;
2173        }
2174        int line = getLayout().getLineForOffset(getChipStart(currentChip));
2175        int bottom = calculateOffsetFromBottom(line);
2176        // Align the alternates popup with the left side of the View,
2177        // regardless of the position of the chip tapped.
2178        popup.setWidth(width);
2179        popup.setAnchorView(this);
2180        popup.setVerticalOffset(bottom);
2181        popup.setAdapter(createSingleAddressAdapter(currentChip));
2182        popup.setOnItemClickListener(new OnItemClickListener() {
2183            @Override
2184            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2185                unselectChip(currentChip);
2186                popup.dismiss();
2187            }
2188        });
2189        popup.show();
2190        ListView listView = popup.getListView();
2191        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2192        listView.setItemChecked(0, true);
2193    }
2194
2195    /**
2196     * Remove selection from this chip. Unselecting a RecipientChip will render
2197     * the chip without a delete icon and with an unfocused background. This is
2198     * called when the RecipientChip no longer has focus.
2199     */
2200    private void unselectChip(DrawableRecipientChip chip) {
2201        int start = getChipStart(chip);
2202        int end = getChipEnd(chip);
2203        Editable editable = getText();
2204        mSelectedChip = null;
2205        if (start == -1 || end == -1) {
2206            Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
2207            setSelection(editable.length());
2208            commitDefault();
2209        } else {
2210            getSpannable().removeSpan(chip);
2211            QwertyKeyListener.markAsReplaced(editable, start, end, "");
2212            editable.removeSpan(chip);
2213            try {
2214                if (!mNoChips) {
2215                    editable.setSpan(constructChipSpan(chip.getEntry(), false),
2216                            start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2217                }
2218            } catch (NullPointerException e) {
2219                Log.e(TAG, e.getMessage(), e);
2220            }
2221        }
2222        setCursorVisible(true);
2223        setSelection(editable.length());
2224        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2225            mAlternatesPopup.dismiss();
2226        }
2227    }
2228
2229    /**
2230     * Return whether a touch event was inside the delete target of
2231     * a selected chip. It is in the delete target if:
2232     * 1) the x and y points of the event are within the
2233     * delete assset.
2234     * 2) the point tapped would have caused a cursor to appear
2235     * right after the selected chip.
2236     * @return boolean
2237     */
2238    private boolean isInDelete(DrawableRecipientChip chip, int offset, float x, float y) {
2239        // Figure out the bounds of this chip and whether or not
2240        // the user clicked in the X portion.
2241        // TODO: Should x and y be used, or removed?
2242        if (mDisableDelete) {
2243            return false;
2244        }
2245
2246        return chip.isSelected() &&
2247                ((mAvatarPosition == AVATAR_POSITION_END && offset == getChipEnd(chip)) ||
2248                (mAvatarPosition != AVATAR_POSITION_END && offset == getChipStart(chip)));
2249    }
2250
2251    /**
2252     * Remove the chip and any text associated with it from the RecipientEditTextView.
2253     */
2254    // Visible for testing.
2255    /* package */void removeChip(DrawableRecipientChip chip) {
2256        Spannable spannable = getSpannable();
2257        int spanStart = spannable.getSpanStart(chip);
2258        int spanEnd = spannable.getSpanEnd(chip);
2259        Editable text = getText();
2260        int toDelete = spanEnd;
2261        boolean wasSelected = chip == mSelectedChip;
2262        // Clear that there is a selected chip before updating any text.
2263        if (wasSelected) {
2264            mSelectedChip = null;
2265        }
2266        // Always remove trailing spaces when removing a chip.
2267        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2268            toDelete++;
2269        }
2270        spannable.removeSpan(chip);
2271        if (spanStart >= 0 && toDelete > 0) {
2272            text.delete(spanStart, toDelete);
2273        }
2274        if (wasSelected) {
2275            clearSelectedChip();
2276        }
2277    }
2278
2279    /**
2280     * Replace this currently selected chip with a new chip
2281     * that uses the contact data provided.
2282     */
2283    // Visible for testing.
2284    /*package*/ void replaceChip(DrawableRecipientChip chip, RecipientEntry entry) {
2285        boolean wasSelected = chip == mSelectedChip;
2286        if (wasSelected) {
2287            mSelectedChip = null;
2288        }
2289        int start = getChipStart(chip);
2290        int end = getChipEnd(chip);
2291        getSpannable().removeSpan(chip);
2292        Editable editable = getText();
2293        CharSequence chipText = createChip(entry, false);
2294        if (chipText != null) {
2295            if (start == -1 || end == -1) {
2296                Log.e(TAG, "The chip to replace does not exist but should.");
2297                editable.insert(0, chipText);
2298            } else {
2299                if (!TextUtils.isEmpty(chipText)) {
2300                    // There may be a space to replace with this chip's new
2301                    // associated space. Check for it
2302                    int toReplace = end;
2303                    while (toReplace >= 0 && toReplace < editable.length()
2304                            && editable.charAt(toReplace) == ' ') {
2305                        toReplace++;
2306                    }
2307                    editable.replace(start, toReplace, chipText);
2308                }
2309            }
2310        }
2311        setCursorVisible(true);
2312        if (wasSelected) {
2313            clearSelectedChip();
2314        }
2315    }
2316
2317    /**
2318     * Handle click events for a chip. When a selected chip receives a click
2319     * event, see if that event was in the delete icon. If so, delete it.
2320     * Otherwise, unselect the chip.
2321     */
2322    public void onClick(DrawableRecipientChip chip, int offset, float x, float y) {
2323        if (chip.isSelected()) {
2324            if (isInDelete(chip, offset, x, y)) {
2325                removeChip(chip);
2326            } else {
2327                clearSelectedChip();
2328            }
2329        }
2330    }
2331
2332    private boolean chipsPending() {
2333        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2334    }
2335
2336    @Override
2337    public void removeTextChangedListener(TextWatcher watcher) {
2338        mTextWatcher = null;
2339        super.removeTextChangedListener(watcher);
2340    }
2341
2342    private boolean isValidEmailAddress(String input) {
2343        return !TextUtils.isEmpty(input) && mValidator != null &&
2344                mValidator.isValid(input);
2345    }
2346
2347    private class RecipientTextWatcher implements TextWatcher {
2348
2349        @Override
2350        public void afterTextChanged(Editable s) {
2351            // If the text has been set to null or empty, make sure we remove
2352            // all the spans we applied.
2353            if (TextUtils.isEmpty(s)) {
2354                // Remove all the chips spans.
2355                Spannable spannable = getSpannable();
2356                DrawableRecipientChip[] chips = spannable.getSpans(0, getText().length(),
2357                        DrawableRecipientChip.class);
2358                for (DrawableRecipientChip chip : chips) {
2359                    spannable.removeSpan(chip);
2360                }
2361                if (mMoreChip != null) {
2362                    spannable.removeSpan(mMoreChip);
2363                }
2364                clearSelectedChip();
2365                return;
2366            }
2367            // Get whether there are any recipients pending addition to the
2368            // view. If there are, don't do anything in the text watcher.
2369            if (chipsPending()) {
2370                return;
2371            }
2372            // If the user is editing a chip, don't clear it.
2373            if (mSelectedChip != null) {
2374                if (!isGeneratedContact(mSelectedChip)) {
2375                    setCursorVisible(true);
2376                    setSelection(getText().length());
2377                    clearSelectedChip();
2378                } else {
2379                    return;
2380                }
2381            }
2382            int length = s.length();
2383            // Make sure there is content there to parse and that it is
2384            // not just the commit character.
2385            if (length > 1) {
2386                if (lastCharacterIsCommitCharacter(s)) {
2387                    commitByCharacter();
2388                    return;
2389                }
2390                char last;
2391                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2392                int len = length() - 1;
2393                if (end != len) {
2394                    last = s.charAt(end);
2395                } else {
2396                    last = s.charAt(len);
2397                }
2398                if (last == COMMIT_CHAR_SPACE) {
2399                    if (!isPhoneQuery()) {
2400                        // Check if this is a valid email address. If it is,
2401                        // commit it.
2402                        String text = getText().toString();
2403                        int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2404                        String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2405                                tokenStart));
2406                        if (isValidEmailAddress(sub)) {
2407                            commitByCharacter();
2408                        }
2409                    }
2410                }
2411            }
2412        }
2413
2414        @Override
2415        public void onTextChanged(CharSequence s, int start, int before, int count) {
2416            // The user deleted some text OR some text was replaced; check to
2417            // see if the insertion point is on a space
2418            // following a chip.
2419            if (before - count == 1) {
2420                // If the item deleted is a space, and the thing before the
2421                // space is a chip, delete the entire span.
2422                int selStart = getSelectionStart();
2423                DrawableRecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2424                        DrawableRecipientChip.class);
2425                if (repl.length > 0) {
2426                    // There is a chip there! Just remove it.
2427                    Editable editable = getText();
2428                    // Add the separator token.
2429                    int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2430                    int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
2431                    tokenEnd = tokenEnd + 1;
2432                    if (tokenEnd > editable.length()) {
2433                        tokenEnd = editable.length();
2434                    }
2435                    editable.delete(tokenStart, tokenEnd);
2436                    getSpannable().removeSpan(repl[0]);
2437                }
2438            } else if (count > before) {
2439                if (mSelectedChip != null
2440                    && isGeneratedContact(mSelectedChip)) {
2441                    if (lastCharacterIsCommitCharacter(s)) {
2442                        commitByCharacter();
2443                        return;
2444                    }
2445                }
2446            }
2447        }
2448
2449        @Override
2450        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2451            // Do nothing.
2452        }
2453    }
2454
2455   public boolean lastCharacterIsCommitCharacter(CharSequence s) {
2456        char last;
2457        int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2458        int len = length() - 1;
2459        if (end != len) {
2460            last = s.charAt(end);
2461        } else {
2462            last = s.charAt(len);
2463        }
2464        return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON;
2465    }
2466
2467    public boolean isGeneratedContact(DrawableRecipientChip chip) {
2468        long contactId = chip.getContactId();
2469        return contactId == RecipientEntry.INVALID_CONTACT
2470                || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2471    }
2472
2473    /**
2474     * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2475     */
2476    private void handlePasteClip(ClipData clip) {
2477        removeTextChangedListener(mTextWatcher);
2478
2479        if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
2480            for (int i = 0; i < clip.getItemCount(); i++) {
2481                CharSequence paste = clip.getItemAt(i).getText();
2482                if (paste != null) {
2483                    int start = getSelectionStart();
2484                    int end = getSelectionEnd();
2485                    Editable editable = getText();
2486                    if (start >= 0 && end >= 0 && start != end) {
2487                        editable.append(paste, start, end);
2488                    } else {
2489                        editable.insert(end, paste);
2490                    }
2491                    handlePasteAndReplace();
2492                }
2493            }
2494        }
2495
2496        mHandler.post(mAddTextWatcher);
2497    }
2498
2499    @Override
2500    public boolean onTextContextMenuItem(int id) {
2501        if (id == android.R.id.paste) {
2502            ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2503                    Context.CLIPBOARD_SERVICE);
2504            handlePasteClip(clipboard.getPrimaryClip());
2505            return true;
2506        }
2507        return super.onTextContextMenuItem(id);
2508    }
2509
2510    private void handlePasteAndReplace() {
2511        ArrayList<DrawableRecipientChip> created = handlePaste();
2512        if (created != null && created.size() > 0) {
2513            // Perform reverse lookups on the pasted contacts.
2514            IndividualReplacementTask replace = new IndividualReplacementTask();
2515            replace.execute(created);
2516        }
2517    }
2518
2519    // Visible for testing.
2520    /* package */ArrayList<DrawableRecipientChip> handlePaste() {
2521        String text = getText().toString();
2522        int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2523        String lastAddress = text.substring(originalTokenStart);
2524        int tokenStart = originalTokenStart;
2525        int prevTokenStart = 0;
2526        DrawableRecipientChip findChip = null;
2527        ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
2528        if (tokenStart != 0) {
2529            // There are things before this!
2530            while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
2531                prevTokenStart = tokenStart;
2532                tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2533                findChip = findChip(tokenStart);
2534                if (tokenStart == originalTokenStart && findChip == null) {
2535                    break;
2536                }
2537            }
2538            if (tokenStart != originalTokenStart) {
2539                if (findChip != null) {
2540                    tokenStart = prevTokenStart;
2541                }
2542                int tokenEnd;
2543                DrawableRecipientChip createdChip;
2544                while (tokenStart < originalTokenStart) {
2545                    tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2546                            tokenStart));
2547                    commitChip(tokenStart, tokenEnd, getText());
2548                    createdChip = findChip(tokenStart);
2549                    if (createdChip == null) {
2550                        break;
2551                    }
2552                    // +1 for the space at the end.
2553                    tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
2554                    created.add(createdChip);
2555                }
2556            }
2557        }
2558        // Take a look at the last token. If the token has been completed with a
2559        // commit character, create a chip.
2560        if (isCompletedToken(lastAddress)) {
2561            Editable editable = getText();
2562            tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2563            commitChip(tokenStart, editable.length(), editable);
2564            created.add(findChip(tokenStart));
2565        }
2566        return created;
2567    }
2568
2569    // Visible for testing.
2570    /* package */int movePastTerminators(int tokenEnd) {
2571        if (tokenEnd >= length()) {
2572            return tokenEnd;
2573        }
2574        char atEnd = getText().toString().charAt(tokenEnd);
2575        if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2576            tokenEnd++;
2577        }
2578        // This token had not only an end token character, but also a space
2579        // separating it from the next token.
2580        if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2581            tokenEnd++;
2582        }
2583        return tokenEnd;
2584    }
2585
2586    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
2587        private DrawableRecipientChip createFreeChip(RecipientEntry entry) {
2588            try {
2589                if (mNoChips) {
2590                    return null;
2591                }
2592                return constructChipSpan(entry, false);
2593            } catch (NullPointerException e) {
2594                Log.e(TAG, e.getMessage(), e);
2595                return null;
2596            }
2597        }
2598
2599        @Override
2600        protected void onPreExecute() {
2601            // Ensure everything is in chip-form already, so we don't have text that slowly gets
2602            // replaced
2603            final List<DrawableRecipientChip> originalRecipients =
2604                    new ArrayList<DrawableRecipientChip>();
2605            final DrawableRecipientChip[] existingChips = getSortedRecipients();
2606            for (int i = 0; i < existingChips.length; i++) {
2607                originalRecipients.add(existingChips[i]);
2608            }
2609            if (mRemovedSpans != null) {
2610                originalRecipients.addAll(mRemovedSpans);
2611            }
2612
2613            final List<DrawableRecipientChip> replacements =
2614                    new ArrayList<DrawableRecipientChip>(originalRecipients.size());
2615
2616            for (final DrawableRecipientChip chip : originalRecipients) {
2617                if (RecipientEntry.isCreatedRecipient(chip.getEntry().getContactId())
2618                        && getSpannable().getSpanStart(chip) != -1) {
2619                    replacements.add(createFreeChip(chip.getEntry()));
2620                } else {
2621                    replacements.add(null);
2622                }
2623            }
2624
2625            processReplacements(originalRecipients, replacements);
2626        }
2627
2628        @Override
2629        protected Void doInBackground(Void... params) {
2630            if (mIndividualReplacements != null) {
2631                mIndividualReplacements.cancel(true);
2632            }
2633            // For each chip in the list, look up the matching contact.
2634            // If there is a match, replace that chip with the matching
2635            // chip.
2636            final ArrayList<DrawableRecipientChip> recipients =
2637                    new ArrayList<DrawableRecipientChip>();
2638            DrawableRecipientChip[] existingChips = getSortedRecipients();
2639            for (int i = 0; i < existingChips.length; i++) {
2640                recipients.add(existingChips[i]);
2641            }
2642            if (mRemovedSpans != null) {
2643                recipients.addAll(mRemovedSpans);
2644            }
2645            ArrayList<String> addresses = new ArrayList<String>();
2646            DrawableRecipientChip chip;
2647            for (int i = 0; i < recipients.size(); i++) {
2648                chip = recipients.get(i);
2649                if (chip != null) {
2650                    addresses.add(createAddressText(chip.getEntry()));
2651                }
2652            }
2653            final BaseRecipientAdapter adapter = getAdapter();
2654            adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
2655                        @Override
2656                        public void matchesFound(Map<String, RecipientEntry> entries) {
2657                            final ArrayList<DrawableRecipientChip> replacements =
2658                                    new ArrayList<DrawableRecipientChip>();
2659                            for (final DrawableRecipientChip temp : recipients) {
2660                                RecipientEntry entry = null;
2661                                if (temp != null && RecipientEntry.isCreatedRecipient(
2662                                        temp.getEntry().getContactId())
2663                                        && getSpannable().getSpanStart(temp) != -1) {
2664                                    // Replace this.
2665                                    entry = createValidatedEntry(
2666                                            entries.get(tokenizeAddress(temp.getEntry()
2667                                                    .getDestination())));
2668                                }
2669                                if (entry != null) {
2670                                    replacements.add(createFreeChip(entry));
2671                                } else {
2672                                    replacements.add(null);
2673                                }
2674                            }
2675                            processReplacements(recipients, replacements);
2676                        }
2677
2678                        @Override
2679                        public void matchesNotFound(final Set<String> unfoundAddresses) {
2680                            final List<DrawableRecipientChip> replacements =
2681                                    new ArrayList<DrawableRecipientChip>(unfoundAddresses.size());
2682
2683                            for (final DrawableRecipientChip temp : recipients) {
2684                                if (temp != null && RecipientEntry.isCreatedRecipient(
2685                                        temp.getEntry().getContactId())
2686                                        && getSpannable().getSpanStart(temp) != -1) {
2687                                    if (unfoundAddresses.contains(
2688                                            temp.getEntry().getDestination())) {
2689                                        replacements.add(createFreeChip(temp.getEntry()));
2690                                    } else {
2691                                        replacements.add(null);
2692                                    }
2693                                } else {
2694                                    replacements.add(null);
2695                                }
2696                            }
2697
2698                            processReplacements(recipients, replacements);
2699                        }
2700                    });
2701            return null;
2702        }
2703
2704        private void processReplacements(final List<DrawableRecipientChip> recipients,
2705                final List<DrawableRecipientChip> replacements) {
2706            if (replacements != null && replacements.size() > 0) {
2707                final Runnable runnable = new Runnable() {
2708                    @Override
2709                    public void run() {
2710                        final Editable text = new SpannableStringBuilder(getText());
2711                        int i = 0;
2712                        for (final DrawableRecipientChip chip : recipients) {
2713                            final DrawableRecipientChip replacement = replacements.get(i);
2714                            if (replacement != null) {
2715                                final RecipientEntry oldEntry = chip.getEntry();
2716                                final RecipientEntry newEntry = replacement.getEntry();
2717                                final boolean isBetter =
2718                                        RecipientAlternatesAdapter.getBetterRecipient(
2719                                                oldEntry, newEntry) == newEntry;
2720
2721                                if (isBetter) {
2722                                    // Find the location of the chip in the text currently shown.
2723                                    final int start = text.getSpanStart(chip);
2724                                    if (start != -1) {
2725                                        // Replacing the entirety of what the chip represented,
2726                                        // including the extra space dividing it from other chips.
2727                                        final int end =
2728                                                Math.min(text.getSpanEnd(chip) + 1, text.length());
2729                                        text.removeSpan(chip);
2730                                        // Make sure we always have just 1 space at the end to
2731                                        // separate this chip from the next chip.
2732                                        final SpannableString displayText =
2733                                                new SpannableString(createAddressText(
2734                                                        replacement.getEntry()).trim() + " ");
2735                                        displayText.setSpan(replacement, 0,
2736                                                displayText.length() - 1,
2737                                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2738                                        // Replace the old text we found with with the new display
2739                                        // text, which now may also contain the display name of the
2740                                        // recipient.
2741                                        text.replace(start, end, displayText);
2742                                        replacement.setOriginalText(displayText.toString());
2743                                        replacements.set(i, null);
2744
2745                                        recipients.set(i, replacement);
2746                                    }
2747                                }
2748                            }
2749                            i++;
2750                        }
2751                        setText(text);
2752                    }
2753                };
2754
2755                if (Looper.myLooper() == Looper.getMainLooper()) {
2756                    runnable.run();
2757                } else {
2758                    mHandler.post(runnable);
2759                }
2760            }
2761        }
2762    }
2763
2764    private class IndividualReplacementTask
2765            extends AsyncTask<ArrayList<DrawableRecipientChip>, Void, Void> {
2766        @Override
2767        protected Void doInBackground(ArrayList<DrawableRecipientChip>... params) {
2768            // For each chip in the list, look up the matching contact.
2769            // If there is a match, replace that chip with the matching
2770            // chip.
2771            final ArrayList<DrawableRecipientChip> originalRecipients = params[0];
2772            ArrayList<String> addresses = new ArrayList<String>();
2773            DrawableRecipientChip chip;
2774            for (int i = 0; i < originalRecipients.size(); i++) {
2775                chip = originalRecipients.get(i);
2776                if (chip != null) {
2777                    addresses.add(createAddressText(chip.getEntry()));
2778                }
2779            }
2780            final BaseRecipientAdapter adapter = getAdapter();
2781            adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
2782
2783                        @Override
2784                        public void matchesFound(Map<String, RecipientEntry> entries) {
2785                            for (final DrawableRecipientChip temp : originalRecipients) {
2786                                if (RecipientEntry.isCreatedRecipient(temp.getEntry()
2787                                        .getContactId())
2788                                        && getSpannable().getSpanStart(temp) != -1) {
2789                                    // Replace this.
2790                                    final RecipientEntry entry = createValidatedEntry(entries
2791                                            .get(tokenizeAddress(temp.getEntry().getDestination())
2792                                                    .toLowerCase()));
2793                                    if (entry != null) {
2794                                        mHandler.post(new Runnable() {
2795                                            @Override
2796                                            public void run() {
2797                                                replaceChip(temp, entry);
2798                                            }
2799                                        });
2800                                    }
2801                                }
2802                            }
2803                        }
2804
2805                        @Override
2806                        public void matchesNotFound(final Set<String> unfoundAddresses) {
2807                            // No action required
2808                        }
2809                    });
2810            return null;
2811        }
2812    }
2813
2814
2815    /**
2816     * MoreImageSpan is a simple class created for tracking the existence of a
2817     * more chip across activity restarts/
2818     */
2819    private class MoreImageSpan extends ImageSpan {
2820        public MoreImageSpan(Drawable b) {
2821            super(b);
2822        }
2823    }
2824
2825    @Override
2826    public boolean onDown(MotionEvent e) {
2827        return false;
2828    }
2829
2830    @Override
2831    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2832        // Do nothing.
2833        return false;
2834    }
2835
2836    @Override
2837    public void onLongPress(MotionEvent event) {
2838        if (mSelectedChip != null) {
2839            return;
2840        }
2841        float x = event.getX();
2842        float y = event.getY();
2843        final int offset = putOffsetInRange(x, y);
2844        DrawableRecipientChip currentChip = findChip(offset);
2845        if (currentChip != null) {
2846            if (mDragEnabled) {
2847                // Start drag-and-drop for the selected chip.
2848                startDrag(currentChip);
2849            } else {
2850                // Copy the selected chip email address.
2851                showCopyDialog(currentChip.getEntry().getDestination());
2852            }
2853        }
2854    }
2855
2856    // The following methods are used to provide some functionality on older versions of Android
2857    // These methods were copied out of JB MR2's TextView
2858    /////////////////////////////////////////////////
2859    private int supportGetOffsetForPosition(float x, float y) {
2860        if (getLayout() == null) return -1;
2861        final int line = supportGetLineAtCoordinate(y);
2862        final int offset = supportGetOffsetAtCoordinate(line, x);
2863        return offset;
2864    }
2865
2866    private float supportConvertToLocalHorizontalCoordinate(float x) {
2867        x -= getTotalPaddingLeft();
2868        // Clamp the position to inside of the view.
2869        x = Math.max(0.0f, x);
2870        x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
2871        x += getScrollX();
2872        return x;
2873    }
2874
2875    private int supportGetLineAtCoordinate(float y) {
2876        y -= getTotalPaddingLeft();
2877        // Clamp the position to inside of the view.
2878        y = Math.max(0.0f, y);
2879        y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
2880        y += getScrollY();
2881        return getLayout().getLineForVertical((int) y);
2882    }
2883
2884    private int supportGetOffsetAtCoordinate(int line, float x) {
2885        x = supportConvertToLocalHorizontalCoordinate(x);
2886        return getLayout().getOffsetForHorizontal(line, x);
2887    }
2888    /////////////////////////////////////////////////
2889
2890    /**
2891     * Enables drag-and-drop for chips.
2892     */
2893    public void enableDrag() {
2894        mDragEnabled = true;
2895    }
2896
2897    /**
2898     * Starts drag-and-drop for the selected chip.
2899     */
2900    private void startDrag(DrawableRecipientChip currentChip) {
2901        String address = currentChip.getEntry().getDestination();
2902        ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2903
2904        // Start drag mode.
2905        startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2906
2907        // Remove the current chip, so drag-and-drop will result in a move.
2908        // TODO (phamm): consider readd this chip if it's dropped outside a target.
2909        removeChip(currentChip);
2910    }
2911
2912    /**
2913     * Handles drag event.
2914     */
2915    @Override
2916    public boolean onDragEvent(DragEvent event) {
2917        switch (event.getAction()) {
2918            case DragEvent.ACTION_DRAG_STARTED:
2919                // Only handle plain text drag and drop.
2920                return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2921            case DragEvent.ACTION_DRAG_ENTERED:
2922                requestFocus();
2923                return true;
2924            case DragEvent.ACTION_DROP:
2925                handlePasteClip(event.getClipData());
2926                return true;
2927        }
2928        return false;
2929    }
2930
2931    /**
2932     * Drag shadow for a {@link DrawableRecipientChip}.
2933     */
2934    private final class RecipientChipShadow extends DragShadowBuilder {
2935        private final DrawableRecipientChip mChip;
2936
2937        public RecipientChipShadow(DrawableRecipientChip chip) {
2938            mChip = chip;
2939        }
2940
2941        @Override
2942        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
2943            Rect rect = mChip.getBounds();
2944            shadowSize.set(rect.width(), rect.height());
2945            shadowTouchPoint.set(rect.centerX(), rect.centerY());
2946        }
2947
2948        @Override
2949        public void onDrawShadow(Canvas canvas) {
2950            mChip.draw(canvas);
2951        }
2952    }
2953
2954    private void showCopyDialog(final String address) {
2955        if (!mAttachedToWindow) {
2956            return;
2957        }
2958        mCopyAddress = address;
2959        mCopyDialog.setTitle(address);
2960        mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
2961        mCopyDialog.setCancelable(true);
2962        mCopyDialog.setCanceledOnTouchOutside(true);
2963        Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
2964        button.setOnClickListener(this);
2965        int btnTitleId;
2966        if (isPhoneQuery()) {
2967            btnTitleId = R.string.copy_number;
2968        } else {
2969            btnTitleId = R.string.copy_email;
2970        }
2971        String buttonTitle = getContext().getResources().getString(btnTitleId);
2972        button.setText(buttonTitle);
2973        mCopyDialog.setOnDismissListener(this);
2974        mCopyDialog.show();
2975    }
2976
2977    @Override
2978    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
2979        // Do nothing.
2980        return false;
2981    }
2982
2983    @Override
2984    public void onShowPress(MotionEvent e) {
2985        // Do nothing.
2986    }
2987
2988    @Override
2989    public boolean onSingleTapUp(MotionEvent e) {
2990        // Do nothing.
2991        return false;
2992    }
2993
2994    @Override
2995    public void onDismiss(DialogInterface dialog) {
2996        mCopyAddress = null;
2997    }
2998
2999    @Override
3000    public void onClick(View v) {
3001        // Copy this to the clipboard.
3002        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
3003                Context.CLIPBOARD_SERVICE);
3004        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
3005        mCopyDialog.dismiss();
3006    }
3007
3008    protected boolean isPhoneQuery() {
3009        return getAdapter() != null
3010                && getAdapter().getQueryType() == BaseRecipientAdapter.QUERY_TYPE_PHONE;
3011    }
3012
3013    @Override
3014    public BaseRecipientAdapter getAdapter() {
3015        return (BaseRecipientAdapter) super.getAdapter();
3016    }
3017
3018    /**
3019     * Append a new {@link RecipientEntry} to the end of the recipient chips, leaving any
3020     * unfinished text at the end.
3021     */
3022    public void appendRecipientEntry(final RecipientEntry entry) {
3023        clearComposingText();
3024
3025        final Editable editable = getText();
3026        int chipInsertionPoint = 0;
3027
3028        // Find the end of last chip and see if there's any unchipified text.
3029        final DrawableRecipientChip[] recips = getSortedRecipients();
3030        if (recips != null && recips.length > 0) {
3031            final DrawableRecipientChip last = recips[recips.length - 1];
3032            // The chip will be inserted at the end of last chip + 1. All the unfinished text after
3033            // the insertion point will be kept untouched.
3034            chipInsertionPoint = editable.getSpanEnd(last) + 1;
3035        }
3036
3037        final CharSequence chip = createChip(entry, false);
3038        if (chip != null) {
3039            editable.insert(chipInsertionPoint, chip);
3040        }
3041    }
3042
3043    /**
3044     * Remove all chips matching the given RecipientEntry.
3045     */
3046    public void removeRecipientEntry(final RecipientEntry entry) {
3047        final DrawableRecipientChip[] recips = getText()
3048                .getSpans(0, getText().length(), DrawableRecipientChip.class);
3049
3050        for (final DrawableRecipientChip recipient : recips) {
3051            final RecipientEntry existingEntry = recipient.getEntry();
3052            if (existingEntry != null && existingEntry.isValid() &&
3053                    existingEntry.isSamePerson(entry)) {
3054                removeChip(recipient);
3055            }
3056        }
3057    }
3058
3059    private static class ChipBitmapContainer {
3060        Bitmap bitmap;
3061        // information used for positioning the loaded icon
3062        boolean loadIcon = true;
3063        float left;
3064        float top;
3065        float right;
3066        float bottom;
3067    }
3068}
3069