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