RecipientEditTextView.java revision ab5a9644d4ab95fe753a07b2bdf4202d78fa8af7
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.content.Context;
20import android.graphics.Bitmap;
21import android.graphics.BitmapFactory;
22import android.graphics.Canvas;
23import android.graphics.Matrix;
24import android.graphics.Rect;
25import android.graphics.RectF;
26import android.graphics.drawable.BitmapDrawable;
27import android.graphics.drawable.Drawable;
28import android.os.Handler;
29import android.os.Message;
30import android.text.Editable;
31import android.text.Layout;
32import android.text.Spannable;
33import android.text.SpannableString;
34import android.text.Spanned;
35import android.text.TextPaint;
36import android.text.TextUtils;
37import android.text.TextWatcher;
38import android.text.method.QwertyKeyListener;
39import android.text.style.ImageSpan;
40import android.util.AttributeSet;
41import android.util.Log;
42import android.view.ActionMode;
43import android.view.KeyEvent;
44import android.view.Menu;
45import android.view.MenuItem;
46import android.view.MotionEvent;
47import android.view.View;
48import android.view.ActionMode.Callback;
49import android.widget.AdapterView;
50import android.widget.AdapterView.OnItemClickListener;
51import android.widget.Filter;
52import android.widget.Filterable;
53import android.widget.ListAdapter;
54import android.widget.ListPopupWindow;
55import android.widget.ListView;
56import android.widget.MultiAutoCompleteTextView;
57
58import java.util.Collection;
59import java.util.HashSet;
60import java.util.Set;
61
62import java.util.ArrayList;
63
64/**
65 * RecipientEditTextView is an auto complete text view for use with applications
66 * that use the new Chips UI for addressing a message to recipients.
67 */
68public class RecipientEditTextView extends MultiAutoCompleteTextView implements
69        OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener {
70
71    private static final String TAG = "RecipientEditTextView";
72
73    // TODO: get correct number/ algorithm from with UX.
74    private static final int CHIP_LIMIT = 2;
75
76    private static final int INVALID_CONTACT = -1;
77
78    // TODO: get correct size from UX.
79    private static final float MORE_WIDTH_FACTOR = 0.25f;
80
81    private Drawable mChipBackground = null;
82
83    private Drawable mChipDelete = null;
84
85    private int mChipPadding;
86
87    private Tokenizer mTokenizer;
88
89    private Drawable mChipBackgroundPressed;
90
91    private RecipientChip mSelectedChip;
92
93    private int mAlternatesLayout;
94
95    private Bitmap mDefaultContactPhoto;
96
97    private ImageSpan mMoreChip;
98
99    private int mMoreString;
100
101    private ArrayList<RecipientChip> mRemovedSpans;
102
103    private final ArrayList<String> mPendingChips = new ArrayList<String>();
104
105    private float mChipHeight;
106
107    private float mChipFontSize;
108
109    private Validator mValidator;
110
111    private Drawable mInvalidChipBackground;
112
113    private Handler mHandler;
114
115    private static int DISMISS = "dismiss".hashCode();
116
117    private static final long DISMISS_DELAY = 300;
118
119    private int mPendingChipsCount = 0;
120
121    private static int sSelectedTextColor = -1;
122
123    private static final char COMMIT_CHAR_COMMA = ',';
124
125    private static final char COMMIT_CHAR_SEMICOLON = ';';
126
127    private static final char COMMIT_CHAR_SPACE = ' ';
128
129    private ListPopupWindow mAlternatesPopup;
130
131    /**
132     * Used with {@link mAlternatesPopup}. Handles clicks to alternate addresses for a selected chip.
133     */
134    private OnItemClickListener mAlternatesListener;
135
136    private int mCheckedItem;
137
138    private TextWatcher mTextWatcher;
139
140    private final Runnable mAddTextWatcher = new Runnable() {
141        @Override
142        public void run() {
143            if (mTextWatcher == null) {
144                mTextWatcher = new RecipientTextWatcher();
145                addTextChangedListener(mTextWatcher);
146            }
147        }
148    };
149
150    public RecipientEditTextView(Context context, AttributeSet attrs) {
151        super(context, attrs);
152        if (sSelectedTextColor == -1) {
153            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
154        }
155        mAlternatesPopup = new ListPopupWindow(context);
156        mAlternatesListener = new OnItemClickListener() {
157            @Override
158            public void onItemClick(AdapterView<?> adapterView,View view, int position,
159                    long rowId) {
160                mAlternatesPopup.setOnItemClickListener(null);
161                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
162                        .getRecipientEntry(position));
163                Message delayed = Message.obtain(mHandler, DISMISS);
164                delayed.obj = mAlternatesPopup;
165                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
166                clearComposingText();
167            }
168        };
169        setSuggestionsEnabled(false);
170        setOnItemClickListener(this);
171        setCustomSelectionActionModeCallback(this);
172        mHandler = new Handler() {
173            @Override
174            public void handleMessage(Message msg) {
175                if (msg.what == DISMISS) {
176                    ((ListPopupWindow) msg.obj).dismiss();
177                    return;
178                }
179                super.handleMessage(msg);
180            }
181        };
182    }
183
184    @Override
185    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
186        super.setAdapter(adapter);
187        if (adapter == null) {
188            return;
189        }
190        // Start the filtering process as soon as possible. This will
191        // cause any needed services to be started and make the first filter
192        // query come back more quickly.
193        Filter f = ((Filterable) adapter).getFilter();
194        f.filter(null);
195    }
196
197    @Override
198    public void onSelectionChanged(int start, int end) {
199        // When selection changes, see if it is inside the chips area.
200        // If so, move the cursor back after the chips again.
201        Spannable span = getSpannable();
202        int textLength = getText().length();
203        RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class);
204        if (chips != null && chips.length > 0) {
205            if (chips != null && chips.length > 0) {
206                // Grab the last chip and set the cursor to after it.
207                setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength));
208            }
209        }
210        super.onSelectionChanged(start, end);
211    }
212
213    /**
214     * Convenience method: Append the specified text slice to the TextView's
215     * display buffer, upgrading it to BufferType.EDITABLE if it was
216     * not already editable. Commas are excluded as they are added automatically
217     * by the view.
218     */
219    @Override
220    public void append(CharSequence text, int start, int end) {
221        super.append(text, start, end);
222        if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
223            final String displayString = (String) text;
224            int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA);
225            if (seperatorPos != 0 && !TextUtils.isEmpty(displayString)
226                    && TextUtils.getTrimmedLength(displayString) > 0) {
227                mPendingChipsCount++;
228                mPendingChips.add((String)text);
229            }
230        }
231    }
232
233    @Override
234    public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
235        if (!hasFocus) {
236            shrink();
237            // Reset any pending chips as they would have been handled
238            // when the field lost focus.
239            mPendingChipsCount = 0;
240            mPendingChips.clear();
241            mHandler.post(mAddTextWatcher);
242        } else {
243            expand();
244        }
245        super.onFocusChanged(hasFocus, direction, previous);
246    }
247
248    private void shrink() {
249        if (mSelectedChip != null) {
250            clearSelectedChip();
251        } else {
252            commitDefault();
253        }
254        mMoreChip = createMoreChip();
255    }
256
257    private void expand() {
258        removeMoreChip();
259        setCursorVisible(true);
260        Editable text = getText();
261        setSelection(text != null && text.length() > 0 ? text.length() : 0);
262    }
263
264    private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
265        paint.setTextSize(mChipFontSize);
266        if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
267            Log.d(TAG, "Max width is negative: " + maxWidth);
268        }
269        return TextUtils.ellipsize(text, paint, maxWidth,
270                TextUtils.TruncateAt.END);
271    }
272
273    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
274        // Ellipsize the text so that it takes AT MOST the entire width of the
275        // autocomplete text entry area. Make sure to leave space for padding
276        // on the sides.
277        int height = (int) mChipHeight;
278        int deleteWidth = height;
279        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
280                calculateAvailableWidth(true) - deleteWidth);
281
282        // Make sure there is a minimum chip width so the user can ALWAYS
283        // tap a chip without difficulty.
284        int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
285                ellipsizedText.length()))
286                + (mChipPadding * 2) + deleteWidth);
287
288        // Create the background of the chip.
289        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
290        Canvas canvas = new Canvas(tmpBitmap);
291        if (mChipBackgroundPressed != null) {
292            mChipBackgroundPressed.setBounds(0, 0, width, height);
293            mChipBackgroundPressed.draw(canvas);
294            paint.setColor(sSelectedTextColor);
295            // Align the display text with where the user enters text.
296            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, height
297                    - Math.abs(height - mChipFontSize)/2, paint);
298            // Make the delete a square.
299            mChipDelete.setBounds(width - deleteWidth, 0, width, height);
300            mChipDelete.draw(canvas);
301        } else {
302            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
303        }
304        return tmpBitmap;
305    }
306
307
308    /**
309     * Get the background drawable for a RecipientChip.
310     */
311    public Drawable getChipBackground(RecipientEntry contact) {
312        return (mValidator != null && mValidator.isValid(contact.getDestination())) ?
313                mChipBackground : mInvalidChipBackground;
314    }
315
316    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
317        // Ellipsize the text so that it takes AT MOST the entire width of the
318        // autocomplete text entry area. Make sure to leave space for padding
319        // on the sides.
320        int height = (int) mChipHeight;
321        int iconWidth = height;
322        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
323                calculateAvailableWidth(false) - iconWidth);
324        // Make sure there is a minimum chip width so the user can ALWAYS
325        // tap a chip without difficulty.
326        int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
327                ellipsizedText.length()))
328                + (mChipPadding * 2) + iconWidth);
329
330        // Create the background of the chip.
331        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
332        Canvas canvas = new Canvas(tmpBitmap);
333        Drawable background = getChipBackground(contact);
334        if (background != null) {
335            background.setBounds(0, 0, width, height);
336            background.draw(canvas);
337
338            // Don't draw photos for recipients that have been typed in.
339            if (contact.getContactId() != INVALID_CONTACT) {
340                byte[] photoBytes = contact.getPhotoBytes();
341                // There may not be a photo yet if anything but the first contact address
342                // was selected.
343                if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
344                    // TODO: cache this in the recipient entry?
345                    ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
346                            .getPhotoThumbnailUri());
347                    photoBytes = contact.getPhotoBytes();
348                }
349
350                Bitmap photo;
351                if (photoBytes != null) {
352                    photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
353                } else {
354                    // TODO: can the scaled down default photo be cached?
355                    photo = mDefaultContactPhoto;
356                }
357                // Draw the photo on the left side.
358                Matrix matrix = new Matrix();
359                RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
360                RectF dst = new RectF(0, 0, iconWidth, height);
361                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
362                canvas.drawBitmap(photo, matrix, paint);
363            } else {
364                // Don't leave any space for the icon. It isn't being drawn.
365                iconWidth = 0;
366            }
367
368            // Align the display text with where the user enters text.
369            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding + iconWidth,
370                    height - Math.abs(height - mChipFontSize) / 2, paint);
371        } else {
372            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
373        }
374        return tmpBitmap;
375    }
376
377    public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
378            throws NullPointerException {
379        if (mChipBackground == null) {
380            throw new NullPointerException(
381                    "Unable to render any chips as setChipDimensions was not called.");
382        }
383        Layout layout = getLayout();
384
385        TextPaint paint = getPaint();
386        float defaultSize = paint.getTextSize();
387        int defaultColor = paint.getColor();
388
389        Bitmap tmpBitmap;
390        if (pressed) {
391            tmpBitmap = createSelectedChip(contact, paint, layout);
392
393        } else {
394            tmpBitmap = createUnselectedChip(contact, paint, layout);
395        }
396
397        // Pass the full text, un-ellipsized, to the chip.
398        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
399        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
400        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
401        // Return text to the original size.
402        paint.setTextSize(defaultSize);
403        paint.setColor(defaultColor);
404        return recipientChip;
405    }
406
407    /**
408     * Calculate the bottom of the line the chip will be located on using:
409     * 1) which line the chip appears on
410     * 2) the height of a chip
411     * 3) padding built into the edit text view
412     * 4) the position of the autocomplete view on the screen, taking into account
413     * that any top padding will move this down visually
414     */
415    private int calculateLineBottom(int yOffset, int line, int chipHeight) {
416        // Line offsets start at zero.
417        int actualLine = line + 1;
418        return yOffset + (actualLine * (chipHeight + getPaddingBottom())) + getPaddingTop();
419    }
420
421    /**
422     * Get the max amount of space a chip can take up. The formula takes into
423     * account the width of the EditTextView, any view padding, and padding
424     * that will be added to the chip.
425     */
426    private float calculateAvailableWidth(boolean pressed) {
427        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
428    }
429
430    /**
431     * Set all chip dimensions and resources. This has to be done from the
432     * application as this is a static library.
433     * @param chipBackground
434     * @param chipBackgroundPressed
435     * @param invalidChip
436     * @param chipDelete
437     * @param defaultContact
438     * @param moreResource
439     * @param alternatesLayout
440     * @param chipHeight
441     * @param padding Padding around the text in a chip
442     */
443    public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed,
444            Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource,
445            int alternatesLayout, float chipHeight, float padding,
446            float chipFontSize) {
447        mChipBackground = chipBackground;
448        mChipBackgroundPressed = chipBackgroundPressed;
449        mChipDelete = chipDelete;
450        mChipPadding = (int) padding;
451        mAlternatesLayout = alternatesLayout;
452        mDefaultContactPhoto = defaultContact;
453        mMoreString = moreResource;
454        mChipHeight = chipHeight;
455        mChipFontSize = chipFontSize;
456        mInvalidChipBackground = invalidChip;
457    }
458
459    @Override
460    public void onSizeChanged(int width, int height, int oldw, int oldh) {
461        super.onSizeChanged(width, height, oldw, oldh);
462        // Check for any pending tokens created before layout had been completed
463        // on the view.
464        if (width != 0 && height != 0) {
465            if (mPendingChipsCount > 0) {
466                Editable editable = getText();
467                // Tokenize!
468                for (int i = 0; i < mPendingChips.size(); i++) {
469                    String current = mPendingChips.get(i);
470                    int tokenStart = editable.toString().indexOf(current);
471                    int tokenEnd = tokenStart + current.length();
472                    // Always include seperators with the token to the
473                    // left.
474                    if (tokenEnd < editable.length() - 1
475                            && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
476                        tokenEnd++;
477                    }
478                    String token = editable.toString().substring(tokenStart, tokenEnd);
479                    editable.replace(tokenStart, tokenEnd, createChip(RecipientEntry
480                            .constructFakeEntry(token), false));
481                }
482                mPendingChipsCount--;
483            }
484            mPendingChipsCount = 0;
485            mPendingChips.clear();
486            mHandler.post(mAddTextWatcher);
487        }
488    }
489
490    @Override
491    public void setTokenizer(Tokenizer tokenizer) {
492        mTokenizer = tokenizer;
493        super.setTokenizer(mTokenizer);
494    }
495
496    @Override
497    public void setValidator(Validator validator) {
498        mValidator = validator;
499        super.setValidator(validator);
500    }
501
502    /**
503     * We cannot use the default mechanism for replaceText. Instead,
504     * we override onItemClickListener so we can get all the associated
505     * contact information including display text, address, and id.
506     */
507    @Override
508    protected void replaceText(CharSequence text) {
509        return;
510    }
511
512    /**
513     * Dismiss any selected chips when the back key is pressed.
514     */
515    @Override
516    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
517        if (keyCode == KeyEvent.KEYCODE_BACK) {
518            clearSelectedChip();
519        }
520        return super.onKeyPreIme(keyCode, event);
521    }
522
523    /**
524     * Monitor key presses in this view to see if the user types
525     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
526     * If the user has entered text that has contact matches and types
527     * a commit key, create a chip from the topmost matching contact.
528     * If the user has entered text that has no contact matches and types
529     * a commit key, then create a chip from the text they have entered.
530     */
531    @Override
532    public boolean onKeyUp(int keyCode, KeyEvent event) {
533        switch (keyCode) {
534            case KeyEvent.KEYCODE_ENTER:
535            case KeyEvent.KEYCODE_DPAD_CENTER:
536                if (event.hasNoModifiers()) {
537                    if (commitDefault()) {
538                        return true;
539                    }
540                    if (mSelectedChip != null) {
541                        clearSelectedChip();
542                        return true;
543                    } else if (focusNext()) {
544                        return true;
545                    }
546                }
547                break;
548            case KeyEvent.KEYCODE_TAB:
549                if (event.hasNoModifiers()) {
550                    if (mSelectedChip != null) {
551                        clearSelectedChip();
552                    } else {
553                        commitDefault();
554                    }
555                    if (focusNext()) {
556                        return true;
557                    }
558                }
559        }
560        return super.onKeyUp(keyCode, event);
561    }
562
563    private boolean focusNext() {
564        View next = focusSearch(View.FOCUS_DOWN);
565        if (next != null) {
566            next.requestFocus();
567            return true;
568        }
569        return false;
570    }
571
572    /**
573     * Create a chip from the default selection. If the popup is showing, the
574     * default is the first item in the popup suggestions list. Otherwise, it is
575     * whatever the user had typed in. End represents where the the tokenizer
576     * should search for a token to turn into a chip.
577     * @return If a chip was created from a real contact.
578     */
579    private boolean commitDefault() {
580        Editable editable = getText();
581        int end = getSelectionEnd();
582        int start = mTokenizer.findTokenStart(editable, end);
583
584        if (shouldCreateChip(start, end)) {
585            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
586            // In the middle of chip; treat this as an edit
587            // and commit the whole token.
588            if (whatEnd != getSelectionEnd()) {
589                handleEdit(start, whatEnd);
590                return true;
591            }
592            return commitChip(start, end , editable);
593        }
594        return false;
595    }
596
597    private void commitByCharacter() {
598        Editable editable = getText();
599        int end = getSelectionEnd();
600        int start = mTokenizer.findTokenStart(editable, end);
601        if (shouldCreateChip(start, end)) {
602            commitChip(start, end, editable);
603        }
604        setSelection(getText().length());
605    }
606
607    private boolean commitChip(int start, int end, Editable editable) {
608        if (getAdapter().getCount() > 0) {
609            // choose the first entry.
610            submitItemAtPosition(0);
611            dismissDropDown();
612            return true;
613        } else {
614            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
615            String text = editable.toString().substring(start, tokenEnd).trim();
616            clearComposingText();
617            if (text != null && text.length() > 0 && !text.equals(" ")) {
618                RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
619                QwertyKeyListener.markAsReplaced(editable, start, end, "");
620                CharSequence chipText = createChip(entry, false);
621                editable.replace(start, end, chipText);
622                dismissDropDown();
623                return true;
624            }
625        }
626        return false;
627    }
628
629    private boolean shouldCreateChip(int start, int end) {
630        if (hasFocus() && enoughToFilter()) {
631            RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
632            if ((chips == null || chips.length == 0)) {
633                return true;
634            }
635        }
636        return false;
637    }
638
639    private void handleEdit(int start, int end) {
640        // This is in the middle of a chip, so select out the whole chip
641        // and commit it.
642        Editable editable = getText();
643        setSelection(end);
644        String text = getText().toString().substring(start, end);
645        RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
646        QwertyKeyListener.markAsReplaced(editable, start, end, "");
647        CharSequence chipText = createChip(entry, false);
648        editable.replace(start, getSelectionEnd(), chipText);
649        dismissDropDown();
650    }
651
652    /**
653     * If there is a selected chip, delegate the key events
654     * to the selected chip.
655     */
656    @Override
657    public boolean onKeyDown(int keyCode, KeyEvent event) {
658        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
659            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
660                mAlternatesPopup.dismiss();
661            }
662            removeChip(mSelectedChip);
663        }
664
665        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
666            return true;
667        }
668
669        return super.onKeyDown(keyCode, event);
670    }
671
672    private Spannable getSpannable() {
673        return getText();
674    }
675
676    private int getChipStart(RecipientChip chip) {
677        return getSpannable().getSpanStart(chip);
678    }
679
680    private int getChipEnd(RecipientChip chip) {
681        return getSpannable().getSpanEnd(chip);
682    }
683
684    /**
685     * Instead of filtering on the entire contents of the edit box,
686     * this subclass method filters on the range from
687     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
688     * if the length of that range meets or exceeds {@link #getThreshold}
689     * and makes sure that the range is not already a Chip.
690     */
691    @Override
692    protected void performFiltering(CharSequence text, int keyCode) {
693        if (enoughToFilter()) {
694            int end = getSelectionEnd();
695            int start = mTokenizer.findTokenStart(text, end);
696            // If this is a RecipientChip, don't filter
697            // on its contents.
698            Spannable span = getSpannable();
699            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
700            if (chips != null && chips.length > 0) {
701                return;
702            }
703        }
704        super.performFiltering(text, keyCode);
705    }
706
707    private void clearSelectedChip() {
708        if (mSelectedChip != null) {
709            unselectChip(mSelectedChip);
710            mSelectedChip = null;
711        }
712        setCursorVisible(true);
713    }
714
715    /**
716     * Monitor touch events in the RecipientEditTextView.
717     * If the view does not have focus, any tap on the view
718     * will just focus the view. If the view has focus, determine
719     * if the touch target is a recipient chip. If it is and the chip
720     * is not selected, select it and clear any other selected chips.
721     * If it isn't, then select that chip.
722     */
723    @Override
724    public boolean onTouchEvent(MotionEvent event) {
725        if (!isFocused()) {
726            // Ignore any chip taps until this view is focused.
727            return super.onTouchEvent(event);
728        }
729
730        boolean handled = super.onTouchEvent(event);
731        int action = event.getAction();
732        boolean chipWasSelected = false;
733
734        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
735            float x = event.getX();
736            float y = event.getY();
737            int offset = putOffsetInRange(getOffsetForPosition(x, y));
738            RecipientChip currentChip = findChip(offset);
739            if (currentChip != null) {
740                if (action == MotionEvent.ACTION_UP) {
741                    if (mSelectedChip != null && mSelectedChip != currentChip) {
742                        clearSelectedChip();
743                        mSelectedChip = selectChip(currentChip);
744                    } else if (mSelectedChip == null) {
745                        // Selection may have moved due to the tap event,
746                        // but make sure we correctly reset selection to the
747                        // end so that any unfinished chips are committed.
748                        setSelection(getText().length());
749                        commitDefault();
750                        mSelectedChip = selectChip(currentChip);
751                    } else {
752                        onClick(mSelectedChip, offset, x, y);
753                    }
754                }
755                chipWasSelected = true;
756            }
757        }
758        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
759            clearSelectedChip();
760        }
761        return handled;
762    }
763
764    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
765            int width, Context context) {
766        int line = getLayout().getLineForOffset(getChipStart(currentChip));
767        int[] xy = getLocationOnScreen();
768        int bottom = calculateLineBottom(xy[1], line, (int) mChipHeight);
769        View anchorView = new View(context);
770        anchorView.setBottom(bottom);
771        anchorView.setTop(bottom);
772        anchorView.setLeft(xy[0]);
773        anchorView.setRight(xy[0]);
774        // Align the alternates popup with the left side of the View,
775        // regardless of the position of the chip tapped.
776        alternatesPopup.setWidth(width);
777        alternatesPopup.setAnchorView(anchorView);
778        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
779        alternatesPopup.setOnItemClickListener(mAlternatesListener);
780        alternatesPopup.show();
781        ListView listView = alternatesPopup.getListView();
782        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
783        // Checked item would be -1 if the adapter has not
784        // loaded the view that should be checked yet. The
785        // variable will be set correctly when onCheckedItemChanged
786        // is called in a separate thread.
787        if (mCheckedItem != -1) {
788            listView.setItemChecked(mCheckedItem, true);
789            mCheckedItem = -1;
790        }
791    }
792
793    private int[] getLocationOnScreen() {
794        int[] xy = new int[2];
795        getLocationOnScreen(xy);
796        return xy;
797    }
798
799    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
800        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
801                mAlternatesLayout, this);
802    }
803
804    public void onCheckedItemChanged(int position) {
805        ListView listView = mAlternatesPopup.getListView();
806        if (listView != null && listView.getCheckedItemCount() == 0) {
807            listView.setItemChecked(position, true);
808        } else {
809            mCheckedItem = position;
810        }
811    }
812
813    // TODO: This algorithm will need a lot of tweaking after more people have used
814    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
815    // what comes before the finger.
816    private int putOffsetInRange(int o) {
817        int offset = o;
818        Editable text = getText();
819        int length = text.length();
820        // Remove whitespace from end to find "real end"
821        int realLength = length;
822        for (int i = length - 1; i >= 0; i--) {
823            if (text.charAt(i) == ' ') {
824                realLength--;
825            } else {
826                break;
827            }
828        }
829
830        // If the offset is beyond or at the end of the text,
831        // leave it alone.
832        if (offset >= realLength) {
833            return offset;
834        }
835        Editable editable = getText();
836        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
837            // Keep walking backward!
838            offset--;
839        }
840        return offset;
841    }
842
843    private int findText(Editable text, int offset) {
844        if (text.charAt(offset) != ' ') {
845            return offset;
846        }
847        return -1;
848    }
849
850    private RecipientChip findChip(int offset) {
851        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
852        // Find the chip that contains this offset.
853        for (int i = 0; i < chips.length; i++) {
854            RecipientChip chip = chips[i];
855            int start = getChipStart(chip);
856            int end = getChipEnd(chip);
857            if (offset >= start && offset <= end) {
858                return chip;
859            }
860        }
861        return null;
862    }
863
864    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
865        String displayText = entry.getDestination();
866        displayText = (String) mTokenizer.terminateToken(displayText);
867        // Always leave a blank space at the end of a chip.
868        int textLength = displayText.length() - 1;
869        SpannableString chipText = new SpannableString(displayText);
870        int end = getSelectionEnd();
871        int start = mTokenizer.findTokenStart(getText(), end);
872        try {
873            chipText.setSpan(constructChipSpan(entry, start, pressed), 0, textLength,
874                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
875        } catch (NullPointerException e) {
876            Log.e(TAG, e.getMessage(), e);
877            return null;
878        }
879
880        return chipText;
881    }
882
883    /**
884     * When an item in the suggestions list has been clicked, create a chip from the
885     * contact information of the selected item.
886     */
887    @Override
888    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
889        submitItemAtPosition(position);
890    }
891
892    private void submitItemAtPosition(int position) {
893        RecipientEntry entry = (RecipientEntry) getAdapter().getItem(position);
894        // If the display name and the address are the same, then make this
895        // a fake recipient that is editable.
896        if (TextUtils.equals(entry.getDisplayName(), entry.getDestination())) {
897            entry = RecipientEntry.constructFakeEntry(entry.getDestination());
898        }
899        clearComposingText();
900
901        int end = getSelectionEnd();
902        int start = mTokenizer.findTokenStart(getText(), end);
903
904        Editable editable = getText();
905        QwertyKeyListener.markAsReplaced(editable, start, end, "");
906        editable.replace(start, end, createChip(entry, false));
907    }
908
909    /** Returns a collection of contact Id for each chip inside this View. */
910    /* package */ Collection<Long> getContactIds() {
911        final Set<Long> result = new HashSet<Long>();
912        RecipientChip[] chips = getRecipients();
913        if (chips != null) {
914            for (RecipientChip chip : chips) {
915                result.add(chip.getContactId());
916            }
917        }
918        return result;
919    }
920
921    private RecipientChip[] getRecipients() {
922        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
923    }
924
925    /** Returns a collection of data Id for each chip inside this View. May be null. */
926    /* package */ Collection<Long> getDataIds() {
927        final Set<Long> result = new HashSet<Long>();
928        RecipientChip [] chips = getRecipients();
929        if (chips != null) {
930            for (RecipientChip chip : chips) {
931                result.add(chip.getDataId());
932            }
933        }
934        return result;
935    }
936
937
938    @Override
939    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
940        return false;
941    }
942
943    @Override
944    public void onDestroyActionMode(ActionMode mode) {
945    }
946
947    @Override
948    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
949        return false;
950    }
951
952    /**
953     * No chips are selectable.
954     */
955    @Override
956    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
957        return false;
958    }
959
960    /**
961     * Create the more chip. The more chip is text that replaces any chips that
962     * do not fit in the pre-defined available space when the
963     * RecipientEditTextView loses focus.
964     */
965    private ImageSpan createMoreChip() {
966        RecipientChip[] recipients = getRecipients();
967        if (recipients == null || recipients.length <= CHIP_LIMIT) {
968            return null;
969        }
970        int numRecipients = recipients.length;
971        int overage = numRecipients - CHIP_LIMIT;
972        Editable text = getText();
973        // TODO: get the correct size from visual design.
974        int width = (int) Math.floor(getWidth() * MORE_WIDTH_FACTOR);
975        int height = getLineHeight();
976        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
977        Canvas canvas = new Canvas(drawable);
978        String moreText = getResources().getString(mMoreString, overage);
979        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
980                getPaint());
981
982        Drawable result = new BitmapDrawable(getResources(), drawable);
983        result.setBounds(0, 0, width, height);
984        ImageSpan moreSpan = new ImageSpan(result);
985        Spannable spannable = getSpannable();
986        // Remove the overage chips.
987        if (recipients == null || recipients.length == 0) {
988            Log.w(TAG,
989                "We have recipients. Tt should not be possible to have zero RecipientChips.");
990            return null;
991        }
992        mRemovedSpans = new ArrayList<RecipientChip>();
993        int totalReplaceStart = 0;
994        int totalReplaceEnd = 0;
995        for (int i = numRecipients - overage; i < recipients.length; i++) {
996            mRemovedSpans.add(recipients[i]);
997            if (i == numRecipients - overage) {
998                totalReplaceStart = spannable.getSpanStart(recipients[i]);
999            }
1000            if (i == recipients.length - 1) {
1001                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1002            }
1003            recipients[i].storeChipStart(spannable.getSpanStart(recipients[i]));
1004            recipients[i].storeChipEnd(spannable.getSpanEnd(recipients[i]));
1005            spannable.removeSpan(recipients[i]);
1006        }
1007        SpannableString chipText = new SpannableString(text.subSequence(totalReplaceStart,
1008                totalReplaceEnd));
1009        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1010        text.replace(totalReplaceStart, totalReplaceEnd, chipText);
1011        return moreSpan;
1012    }
1013
1014    /**
1015     * Replace the more chip, if it exists, with all of the recipient chips it had
1016     * replaced when the RecipientEditTextView gains focus.
1017     */
1018    private void removeMoreChip() {
1019        if (mMoreChip != null) {
1020            Spannable span = getSpannable();
1021            span.removeSpan(mMoreChip);
1022            mMoreChip = null;
1023            // Re-add the spans that were removed.
1024            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1025                // Recreate each removed span.
1026                Editable editable = getText();
1027                SpannableString associatedText;
1028                for (RecipientChip chip : mRemovedSpans) {
1029                    int chipStart = chip.getStoredChipStart();
1030                    int chipEnd = Math.min(editable.length(), chip.getStoredChipEnd());
1031                    if (Log.isLoggable(TAG, Log.DEBUG) && chipEnd != chip.getStoredChipEnd()) {
1032                        Log.d(TAG,
1033                                "Unexpectedly, the chip ended after the end of the editable text. "
1034                                        + "Chip End " + chip.getStoredChipEnd()
1035                                        + "Editable length " + editable.length());
1036                    }
1037                    associatedText = new SpannableString(editable.subSequence(chipStart, chipEnd));
1038                    associatedText.setSpan(chip, 0, associatedText.length(),
1039                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1040                    editable.replace(chipStart, chipEnd, associatedText);
1041                }
1042                mRemovedSpans.clear();
1043            }
1044        }
1045    }
1046
1047    /**
1048     * Show specified chip as selected. If the RecipientChip is just an email address,
1049     * selecting the chip will take the contents of the chip and place it at
1050     * the end of the RecipientEditTextView for inline editing. If the
1051     * RecipientChip is a complete contact, then selecting the chip
1052     * will change the background color of the chip, show the delete icon,
1053     * and a popup window with the address in use highlighted and any other
1054     * alternate addresses for the contact.
1055     * @param currentChip Chip to select.
1056     * @return A RecipientChip in the selected state or null if the chip
1057     * just contained an email address.
1058     */
1059    public RecipientChip selectChip(RecipientChip currentChip) {
1060        if (currentChip.getContactId() != INVALID_CONTACT) {
1061            int start = getChipStart(currentChip);
1062            int end = getChipEnd(currentChip);
1063            getSpannable().removeSpan(currentChip);
1064            RecipientChip newChip;
1065            CharSequence displayText = mTokenizer.terminateToken(currentChip.getValue());
1066            // Always leave a blank space at the end of a chip.
1067            int textLength = displayText.length() - 1;
1068            SpannableString chipText = new SpannableString(displayText);
1069            try {
1070                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1071                chipText.setSpan(newChip, 0, textLength,
1072                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1073            } catch (NullPointerException e) {
1074                Log.e(TAG, e.getMessage(), e);
1075                return null;
1076            }
1077            Editable editable = getText();
1078            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1079            if (start == -1 || end == -1) {
1080                Log.d(TAG, "The chip being selected no longer exists but should.");
1081            } else {
1082                editable.replace(start, end, chipText);
1083            }
1084            newChip.setSelected(true);
1085            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1086            setCursorVisible(false);
1087            return newChip;
1088        } else {
1089            CharSequence text = currentChip.getValue();
1090            Editable editable = getText();
1091            removeChip(currentChip);
1092            editable.append(text);
1093            setCursorVisible(true);
1094            setSelection(editable.length());
1095            return null;
1096        }
1097    }
1098
1099
1100    /**
1101     * Remove selection from this chip. Unselecting a RecipientChip will render
1102     * the chip without a delete icon and with an unfocused background. This
1103     * is called when the RecipientChip no longer has focus.
1104     */
1105    public void unselectChip(RecipientChip chip) {
1106        int start = getChipStart(chip);
1107        int end = getChipEnd(chip);
1108        Editable editable = getText();
1109        mSelectedChip = null;
1110        if (start == -1 || end == -1) {
1111            Log.e(TAG, "The chip being unselected no longer exists but should.");
1112        } else {
1113            getSpannable().removeSpan(chip);
1114            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1115            editable.replace(start, end, createChip(chip.getEntry(), false));
1116        }
1117        setCursorVisible(true);
1118        setSelection(editable.length());
1119        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1120            mAlternatesPopup.dismiss();
1121        }
1122    }
1123
1124
1125    /**
1126     * Return whether this chip contains the position passed in.
1127     */
1128    public boolean matchesChip(RecipientChip chip, int offset) {
1129        int start = getChipStart(chip);
1130        int end = getChipEnd(chip);
1131        if (start == -1 || end == -1) {
1132            return false;
1133        }
1134        return (offset >= start && offset <= end);
1135    }
1136
1137
1138    /**
1139     * Return whether a touch event was inside the delete target of
1140     * a selected chip. It is in the delete target if:
1141     * 1) the x and y points of the event are within the
1142     * delete assset.
1143     * 2) the point tapped would have caused a cursor to appear
1144     * right after the selected chip.
1145     * @return boolean
1146     */
1147    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1148        // Figure out the bounds of this chip and whether or not
1149        // the user clicked in the X portion.
1150        return chip.isSelected() && offset == getChipEnd(chip);
1151    }
1152
1153    /**
1154     * Remove the chip and any text associated with it from the RecipientEditTextView.
1155     */
1156    private void removeChip(RecipientChip chip) {
1157        Spannable spannable = getSpannable();
1158        int spanStart = spannable.getSpanStart(chip);
1159        int spanEnd = spannable.getSpanEnd(chip);
1160        Editable text = getText();
1161        int toDelete = spanEnd;
1162        boolean wasSelected = chip == mSelectedChip;
1163        // Clear that there is a selected chip before updating any text.
1164        if (wasSelected) {
1165            mSelectedChip = null;
1166        }
1167        // Always remove trailing spaces when removing a chip.
1168        while (toDelete >= 0 && toDelete < text.length() - 1 && text.charAt(toDelete) == ' ') {
1169            toDelete++;
1170        }
1171        spannable.removeSpan(chip);
1172        text.delete(spanStart, toDelete);
1173        if (wasSelected) {
1174            clearSelectedChip();
1175        }
1176    }
1177
1178    /**
1179     * Replace this currently selected chip with a new chip
1180     * that uses the contact data provided.
1181     */
1182    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1183        boolean wasSelected = chip == mSelectedChip;
1184        if (wasSelected) {
1185            mSelectedChip = null;
1186        }
1187        int start = getChipStart(chip);
1188        int end = getChipEnd(chip);
1189        getSpannable().removeSpan(chip);
1190        Editable editable = getText();
1191        CharSequence chipText = createChip(entry, false);
1192        if (start == -1 || end == -1) {
1193            Log.e(TAG, "The chip to replace does not exist but should.");
1194            editable.insert(0, chipText);
1195        } else {
1196            editable.replace(start, end, chipText);
1197        }
1198        setCursorVisible(true);
1199        if (wasSelected) {
1200            clearSelectedChip();
1201        }
1202    }
1203
1204    /**
1205     * Handle click events for a chip. When a selected chip receives a click
1206     * event, see if that event was in the delete icon. If so, delete it.
1207     * Otherwise, unselect the chip.
1208     */
1209    public void onClick(RecipientChip chip, int offset, float x, float y) {
1210        if (chip.isSelected()) {
1211            if (isInDelete(chip, offset, x, y)) {
1212                removeChip(chip);
1213            } else {
1214                clearSelectedChip();
1215            }
1216        }
1217    }
1218
1219    private boolean chipsPending() {
1220        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1221    }
1222
1223    private class RecipientTextWatcher implements TextWatcher {
1224        @Override
1225        public void afterTextChanged(Editable s) {
1226            // Get whether there are any recipients pending addition to the view.
1227            // If there are, don't do anything in the text watcher.
1228            if (chipsPending()) {
1229                return;
1230            }
1231            if (mSelectedChip != null) {
1232                setCursorVisible(true);
1233                setSelection(getText().length());
1234                clearSelectedChip();
1235            }
1236            int length = s.length();
1237            // Make sure there is content there to parse and that it is
1238            // not just the commit character.
1239            if (length > 1) {
1240                char last;
1241                int end = getSelectionEnd() - 1;
1242                int len = length() - 1;
1243                if (end != len) {
1244                    last = s.charAt(end);
1245                } else {
1246                    last = s.charAt(len);
1247                }
1248                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1249                    commitByCharacter();
1250                } else if (last == COMMIT_CHAR_SPACE) {
1251                    // Check if this is a valid email address. If it is,
1252                    // commit it.
1253                    String text = getText().toString();
1254                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1255                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1256                            tokenStart));
1257                    if (mValidator != null && mValidator.isValid(sub)) {
1258                        commitByCharacter();
1259                    }
1260                }
1261            }
1262        }
1263
1264        @Override
1265        public void onTextChanged(CharSequence s, int start, int before, int count) {
1266        }
1267
1268        @Override
1269        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1270        }
1271    }
1272
1273}
1274