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