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