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