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