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