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