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