RecipientEditTextView.java revision e0bf819fff34b7678dd336e4fd010f04bb343eea
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 float mChipHeight;
104
105    private float mChipFontSize;
106
107    private Validator mValidator;
108
109    private Drawable mInvalidChipBackground;
110
111    private Handler mHandler;
112
113    private static int DISMISS = "dismiss".hashCode();
114
115    private static final long DISMISS_DELAY = 300;
116
117    private int mPendingChipsCount = 0;
118
119    private static int sSelectedTextColor = -1;
120
121    private static final char COMMIT_CHAR_COMMA = ',';
122
123    private static final char COMMIT_CHAR_SEMICOLON = ';';
124
125    private static final char COMMIT_CHAR_SPACE = ' ';
126
127    private ListPopupWindow mAlternatesPopup;
128
129    /**
130     * Used with {@link mAlternatesPopup}. Handles clicks to alternate addresses for a selected chip.
131     */
132    private OnItemClickListener mAlternatesListener;
133
134    private int mCheckedItem;
135
136    private TextWatcher mTextWatcher;
137
138    private final Runnable mAddTextWatcher = new Runnable() {
139        @Override
140        public void run() {
141            if (mTextWatcher == null) {
142                mTextWatcher = new RecipientTextWatcher();
143                addTextChangedListener(mTextWatcher);
144            }
145        }
146    };
147
148    public RecipientEditTextView(Context context, AttributeSet attrs) {
149        super(context, attrs);
150        if (sSelectedTextColor == -1) {
151            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
152        }
153        mAlternatesPopup = new ListPopupWindow(context);
154        mAlternatesListener = new OnItemClickListener() {
155            @Override
156            public void onItemClick(AdapterView<?> adapterView,View view, int position,
157                    long rowId) {
158                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
159                        .getRecipientEntry(position));
160                Message delayed = Message.obtain(mHandler, DISMISS);
161                delayed.obj = RecipientEditTextView.this.mAlternatesPopup;
162                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
163                clearComposingText();
164            }
165        };
166        setSuggestionsEnabled(false);
167        setOnItemClickListener(this);
168        setCustomSelectionActionModeCallback(this);
169        mHandler = new Handler() {
170            @Override
171            public void handleMessage(Message msg) {
172                if (msg.what == DISMISS) {
173                    ((ListPopupWindow) msg.obj).dismiss();
174                    return;
175                }
176                super.handleMessage(msg);
177            }
178        };
179    }
180
181    @Override
182    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
183        super.setAdapter(adapter);
184        if (adapter == null) {
185            return;
186        }
187        // Start the filtering process as soon as possible. This will
188        // cause any needed services to be started and make the first filter
189        // query come back more quickly.
190        Filter f = ((Filterable) adapter).getFilter();
191        f.filter(null);
192    }
193
194    @Override
195    public void onSelectionChanged(int start, int end) {
196        // When selection changes, see if it is inside the chips area.
197        // If so, move the cursor back after the chips again.
198        Spannable span = getSpannable();
199        int textLength = getText().length();
200        RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class);
201        if (chips != null && chips.length > 0) {
202            if (chips != null && chips.length > 0) {
203                // Grab the last chip and set the cursor to after it.
204                setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength));
205            }
206        }
207        super.onSelectionChanged(start, end);
208    }
209
210    /**
211     * Convenience method: Append the specified text slice to the TextView's
212     * display buffer, upgrading it to BufferType.EDITABLE if it was
213     * not already editable. Commas are excluded as they are added automatically
214     * by the view.
215     */
216    @Override
217    public void append(CharSequence text, int start, int end) {
218        super.append(text, start, end);
219        if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
220            final String displayString = (String) text;
221            int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA);
222            if (seperatorPos != 0 && !TextUtils.isEmpty(displayString)
223                    && TextUtils.getTrimmedLength(displayString) > 0) {
224                mPendingChipsCount++;
225            }
226        }
227    }
228
229    @Override
230    public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
231        if (!hasFocus) {
232            shrink();
233            // Reset any pending chips as they would have been handled
234            // when the field lost focus.
235            mPendingChipsCount = 0;
236            mHandler.post(mAddTextWatcher);
237        } else {
238            expand();
239        }
240        super.onFocusChanged(hasFocus, direction, previous);
241    }
242
243    private void shrink() {
244        if (mSelectedChip != null) {
245            clearSelectedChip();
246        } else {
247            commitDefault();
248        }
249        mMoreChip = createMoreChip();
250    }
251
252    private void expand() {
253        removeMoreChip();
254        setCursorVisible(true);
255        Editable text = getText();
256        setSelection(text != null && text.length() > 0 ? text.length() : 0);
257    }
258
259    private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
260        paint.setTextSize(mChipFontSize);
261        if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
262            Log.d(TAG, "Max width is negative: " + maxWidth);
263        }
264        return TextUtils.ellipsize(text, paint, maxWidth,
265                TextUtils.TruncateAt.END);
266    }
267
268    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
269        // Ellipsize the text so that it takes AT MOST the entire width of the
270        // autocomplete text entry area. Make sure to leave space for padding
271        // on the sides.
272        int height = (int) mChipHeight;
273        int deleteWidth = height;
274        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
275                calculateAvailableWidth(true) - deleteWidth);
276
277        // Make sure there is a minimum chip width so the user can ALWAYS
278        // tap a chip without difficulty.
279        int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
280                ellipsizedText.length()))
281                + (mChipPadding * 2) + deleteWidth);
282
283        // Create the background of the chip.
284        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
285        Canvas canvas = new Canvas(tmpBitmap);
286        if (mChipBackgroundPressed != null) {
287            mChipBackgroundPressed.setBounds(0, 0, width, height);
288            mChipBackgroundPressed.draw(canvas);
289            paint.setColor(sSelectedTextColor);
290            // Align the display text with where the user enters text.
291            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, height
292                    - Math.abs(height - mChipFontSize)/2, paint);
293            // Make the delete a square.
294            mChipDelete.setBounds(width - deleteWidth, 0, width, height);
295            mChipDelete.draw(canvas);
296        } else {
297            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
298        }
299        return tmpBitmap;
300    }
301
302
303    /**
304     * Get the background drawable for a RecipientChip.
305     */
306    public Drawable getChipBackground(RecipientEntry contact) {
307        return mValidator != null && mValidator.isValid(contact.getDestination()) ?
308                mChipBackground : mInvalidChipBackground;
309    }
310
311    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
312        // Ellipsize the text so that it takes AT MOST the entire width of the
313        // autocomplete text entry area. Make sure to leave space for padding
314        // on the sides.
315        int height = (int) mChipHeight;
316        int iconWidth = height;
317        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
318                calculateAvailableWidth(false) - iconWidth);
319        // Make sure there is a minimum chip width so the user can ALWAYS
320        // tap a chip without difficulty.
321        int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
322                ellipsizedText.length()))
323                + (mChipPadding * 2) + iconWidth);
324
325        // Create the background of the chip.
326        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
327        Canvas canvas = new Canvas(tmpBitmap);
328        Drawable background = getChipBackground(contact);
329        if (background != null) {
330            background.setBounds(0, 0, width, height);
331            background.draw(canvas);
332
333            // Don't draw photos for recipients that have been typed in.
334            if (contact.getContactId() != INVALID_CONTACT) {
335                byte[] photoBytes = contact.getPhotoBytes();
336                // There may not be a photo yet if anything but the first contact address
337                // was selected.
338                if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
339                    // TODO: cache this in the recipient entry?
340                    ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
341                            .getPhotoThumbnailUri());
342                    photoBytes = contact.getPhotoBytes();
343                }
344
345                Bitmap photo;
346                if (photoBytes != null) {
347                    photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
348                } else {
349                    // TODO: can the scaled down default photo be cached?
350                    photo = mDefaultContactPhoto;
351                }
352                // Draw the photo on the left side.
353                Matrix matrix = new Matrix();
354                RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
355                RectF dst = new RectF(0, 0, iconWidth, height);
356                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
357                canvas.drawBitmap(photo, matrix, paint);
358            } else {
359                // Don't leave any space for the icon. It isn't being drawn.
360                iconWidth = 0;
361            }
362
363            // Align the display text with where the user enters text.
364            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding + iconWidth,
365                    height - Math.abs(height - mChipFontSize) / 2, paint);
366        } else {
367            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
368        }
369        return tmpBitmap;
370    }
371
372    public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
373            throws NullPointerException {
374        if (mChipBackground == null) {
375            throw new NullPointerException(
376                    "Unable to render any chips as setChipDimensions was not called.");
377        }
378        Layout layout = getLayout();
379
380        TextPaint paint = getPaint();
381        float defaultSize = paint.getTextSize();
382        int defaultColor = paint.getColor();
383
384        Bitmap tmpBitmap;
385        if (pressed) {
386            tmpBitmap = createSelectedChip(contact, paint, layout);
387
388        } else {
389            tmpBitmap = createUnselectedChip(contact, paint, layout);
390        }
391
392        // Pass the full text, un-ellipsized, to the chip.
393        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
394        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
395        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
396        // Return text to the original size.
397        paint.setTextSize(defaultSize);
398        paint.setColor(defaultColor);
399        return recipientChip;
400    }
401
402    /**
403     * Calculate the bottom of the line the chip will be located on using:
404     * 1) which line the chip appears on
405     * 2) the height of a chip
406     * 3) padding built into the edit text view
407     * 4) the position of the autocomplete view on the screen, taking into account
408     * that any top padding will move this down visually
409     */
410    private int calculateLineBottom(int yOffset, int line, int chipHeight) {
411        // Line offsets start at zero.
412        int actualLine = line + 1;
413        return yOffset + (actualLine * (chipHeight + getPaddingBottom())) + getPaddingTop();
414    }
415
416    /**
417     * Get the max amount of space a chip can take up. The formula takes into
418     * account the width of the EditTextView, any view padding, and padding
419     * that will be added to the chip.
420     */
421    private float calculateAvailableWidth(boolean pressed) {
422        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
423    }
424
425    /**
426     * Set all chip dimensions and resources. This has to be done from the
427     * application as this is a static library.
428     * @param chipBackground
429     * @param chipBackgroundPressed
430     * @param invalidChip
431     * @param chipDelete
432     * @param defaultContact
433     * @param moreResource
434     * @param alternatesLayout
435     * @param chipHeight
436     * @param padding Padding around the text in a chip
437     */
438    public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed,
439            Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource,
440            int alternatesLayout, float chipHeight, float padding,
441            float chipFontSize) {
442        mChipBackground = chipBackground;
443        mChipBackgroundPressed = chipBackgroundPressed;
444        mChipDelete = chipDelete;
445        mChipPadding = (int) padding;
446        mAlternatesLayout = alternatesLayout;
447        mDefaultContactPhoto = defaultContact;
448        mMoreString = moreResource;
449        mChipHeight = chipHeight;
450        mChipFontSize = chipFontSize;
451        mInvalidChipBackground = invalidChip;
452    }
453
454    @Override
455    public void onSizeChanged(int width, int height, int oldw, int oldh) {
456        super.onSizeChanged(width, height, oldw, oldh);
457        // Check for any pending tokens created before layout had been completed
458        // on the view.
459        if (width != 0 && height != 0) {
460            if (mPendingChipsCount > 0) {
461                Editable editable = getText();
462                // Tokenize!
463                int startingPos = 0;
464                while (startingPos < editable.length() && mPendingChipsCount > 0) {
465                    int tokenEnd = mTokenizer.findTokenEnd(editable, startingPos);
466                    int tokenStart = mTokenizer.findTokenStart(editable, tokenEnd);
467                    if (findChip(tokenStart) == null) {
468                        // Always include seperators with the token to the
469                        // left.
470                        if (tokenEnd < editable.length() - 1
471                                && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
472                            tokenEnd++;
473                        }
474                        startingPos = tokenEnd;
475                        String token = editable.toString().substring(tokenStart, tokenEnd);
476                        int seperatorPos = token.indexOf(COMMIT_CHAR_COMMA);
477                        if (seperatorPos != -1) {
478                            token = token.substring(0, seperatorPos);
479                        }
480                        editable.replace(tokenStart, tokenEnd, createChip(RecipientEntry
481                                .constructFakeEntry(token), false));
482                    }
483                    mPendingChipsCount--;
484                }
485            }
486            mPendingChipsCount = 0;
487            mHandler.post(mAddTextWatcher);
488        }
489    }
490
491    @Override
492    public void setTokenizer(Tokenizer tokenizer) {
493        mTokenizer = tokenizer;
494        super.setTokenizer(mTokenizer);
495    }
496
497    @Override
498    public void setValidator(Validator validator) {
499        mValidator = validator;
500        super.setValidator(validator);
501    }
502
503    /**
504     * We cannot use the default mechanism for replaceText. Instead,
505     * we override onItemClickListener so we can get all the associated
506     * contact information including display text, address, and id.
507     */
508    @Override
509    protected void replaceText(CharSequence text) {
510        return;
511    }
512
513    /**
514     * Dismiss any selected chips when the back key is pressed.
515     */
516    @Override
517    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
518        if (keyCode == KeyEvent.KEYCODE_BACK) {
519            clearSelectedChip();
520        }
521        return super.onKeyPreIme(keyCode, event);
522    }
523
524    /**
525     * Monitor key presses in this view to see if the user types
526     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
527     * If the user has entered text that has contact matches and types
528     * a commit key, create a chip from the topmost matching contact.
529     * If the user has entered text that has no contact matches and types
530     * a commit key, then create a chip from the text they have entered.
531     */
532    @Override
533    public boolean onKeyUp(int keyCode, KeyEvent event) {
534        switch (keyCode) {
535            case KeyEvent.KEYCODE_ENTER:
536            case KeyEvent.KEYCODE_DPAD_CENTER:
537                if (event.hasNoModifiers()) {
538                    if (commitDefault()) {
539                        return true;
540                    }
541                    if (mSelectedChip != null) {
542                        clearSelectedChip();
543                        return true;
544                    } else if (focusNext()) {
545                        return true;
546                    }
547                }
548                break;
549            case KeyEvent.KEYCODE_TAB:
550                if (event.hasNoModifiers()) {
551                    if (mSelectedChip != null) {
552                        clearSelectedChip();
553                    } else {
554                        commitDefault();
555                    }
556                    if (focusNext()) {
557                        return true;
558                    }
559                }
560        }
561        return super.onKeyUp(keyCode, event);
562    }
563
564    private boolean focusNext() {
565        View next = focusSearch(View.FOCUS_DOWN);
566        if (next != null) {
567            next.requestFocus();
568            return true;
569        }
570        return false;
571    }
572
573    /**
574     * Create a chip from the default selection. If the popup is showing, the
575     * default is the first item in the popup suggestions list. Otherwise, it is
576     * whatever the user had typed in. End represents where the the tokenizer
577     * should search for a token to turn into a chip.
578     * @return If a chip was created from a real contact.
579     */
580    private boolean commitDefault() {
581        Editable editable = getText();
582        int end = getSelectionEnd();
583        int start = mTokenizer.findTokenStart(editable, end);
584
585        if (shouldCreateChip(start, end)) {
586            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
587            // In the middle of chip; treat this as an edit
588            // and commit the whole token.
589            if (whatEnd != getSelectionEnd()) {
590                handleEdit(start, whatEnd);
591                return true;
592            }
593            return commitChip(start, end , editable);
594        }
595        return false;
596    }
597
598    private void commitByCharacter() {
599        Editable editable = getText();
600        int end = getSelectionEnd();
601        int start = mTokenizer.findTokenStart(editable, end);
602        if (shouldCreateChip(start, end)) {
603            commitChip(start, end, editable);
604        }
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 (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    }
650
651    /**
652     * If there is a selected chip, delegate the key events
653     * to the selected chip.
654     */
655    @Override
656    public boolean onKeyDown(int keyCode, KeyEvent event) {
657        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
658            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
659                mAlternatesPopup.dismiss();
660            }
661            removeChip(mSelectedChip);
662        }
663
664        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
665            return true;
666        }
667
668        return super.onKeyDown(keyCode, event);
669    }
670
671    private Spannable getSpannable() {
672        return getText();
673    }
674
675    private int getChipStart(RecipientChip chip) {
676        return getSpannable().getSpanStart(chip);
677    }
678
679    private int getChipEnd(RecipientChip chip) {
680        return getSpannable().getSpanEnd(chip);
681    }
682
683    /**
684     * Instead of filtering on the entire contents of the edit box,
685     * this subclass method filters on the range from
686     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
687     * if the length of that range meets or exceeds {@link #getThreshold}
688     * and makes sure that the range is not already a Chip.
689     */
690    @Override
691    protected void performFiltering(CharSequence text, int keyCode) {
692        if (enoughToFilter()) {
693            int end = getSelectionEnd();
694            int start = mTokenizer.findTokenStart(text, end);
695            // If this is a RecipientChip, don't filter
696            // on its contents.
697            Spannable span = getSpannable();
698            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
699            if (chips != null && chips.length > 0) {
700                return;
701            }
702        }
703        super.performFiltering(text, keyCode);
704    }
705
706    private void clearSelectedChip() {
707        if (mSelectedChip != null) {
708            unselectChip(mSelectedChip);
709            mSelectedChip = null;
710        }
711        setCursorVisible(true);
712    }
713
714    /**
715     * Monitor touch events in the RecipientEditTextView.
716     * If the view does not have focus, any tap on the view
717     * will just focus the view. If the view has focus, determine
718     * if the touch target is a recipient chip. If it is and the chip
719     * is not selected, select it and clear any other selected chips.
720     * If it isn't, then select that chip.
721     */
722    @Override
723    public boolean onTouchEvent(MotionEvent event) {
724        if (!isFocused()) {
725            // Ignore any chip taps until this view is focused.
726            return super.onTouchEvent(event);
727        }
728
729        boolean handled = super.onTouchEvent(event);
730        int action = event.getAction();
731        boolean chipWasSelected = false;
732
733        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
734            float x = event.getX();
735            float y = event.getY();
736            int offset = putOffsetInRange(getOffsetForPosition(x, y));
737            RecipientChip currentChip = findChip(offset);
738            if (currentChip != null) {
739                if (action == MotionEvent.ACTION_UP) {
740                    if (mSelectedChip != null && mSelectedChip != currentChip) {
741                        clearSelectedChip();
742                        mSelectedChip = selectChip(currentChip);
743                    } else if (mSelectedChip == null) {
744                        // Selection may have moved due to the tap event,
745                        // but make sure we correctly reset selection to the
746                        // end so that any unfinished chips are committed.
747                        setSelection(getText().length());
748                        commitDefault();
749                        mSelectedChip = selectChip(currentChip);
750                    } else {
751                        onClick(mSelectedChip, offset, x, y);
752                    }
753                }
754                chipWasSelected = true;
755            }
756        }
757        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
758            clearSelectedChip();
759        }
760        return handled;
761    }
762
763    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
764            int width, Context context) {
765        int line = getLayout().getLineForOffset(getChipStart(currentChip));
766        int[] xy = getLocationOnScreen();
767        int bottom = calculateLineBottom(xy[1], line, (int) mChipHeight);
768        View anchorView = new View(context);
769        anchorView.setBottom(bottom);
770        anchorView.setTop(bottom);
771        anchorView.setLeft(xy[0]);
772        anchorView.setRight(xy[0]);
773        // Align the alternates popup with the left side of the View,
774        // regardless of the position of the chip tapped.
775        alternatesPopup.setWidth(width);
776        alternatesPopup.setAnchorView(anchorView);
777        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
778        alternatesPopup.setOnItemClickListener(mAlternatesListener); // currentChip);
779        alternatesPopup.show();
780        ListView listView = alternatesPopup.getListView();
781        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
782        // Checked item would be -1 if the adapter has not
783        // loaded the view that should be checked yet. The
784        // variable will be set correctly when onCheckedItemChanged
785        // is called in a separate thread.
786        if (mCheckedItem != -1) {
787            listView.setItemChecked(mCheckedItem, true);
788            mCheckedItem = -1;
789        }
790    }
791
792    private int[] getLocationOnScreen() {
793        int[] xy = new int[2];
794        getLocationOnScreen(xy);
795        return xy;
796    }
797
798    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
799        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
800                mAlternatesLayout, this);
801    }
802
803    public void onCheckedItemChanged(int position) {
804        ListView listView = mAlternatesPopup.getListView();
805        if (listView != null && listView.getCheckedItemCount() == 0) {
806            listView.setItemChecked(position, true);
807        } else {
808            mCheckedItem = position;
809        }
810    }
811
812    // TODO: This algorithm will need a lot of tweaking after more people have used
813    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
814    // what comes before the finger.
815    private int putOffsetInRange(int o) {
816        int offset = o;
817        Editable text = getText();
818        int length = text.length();
819        // Remove whitespace from end to find "real end"
820        int realLength = length;
821        for (int i = length - 1; i >= 0; i--) {
822            if (text.charAt(i) == ' ') {
823                realLength--;
824            } else {
825                break;
826            }
827        }
828
829        // If the offset is beyond or at the end of the text,
830        // leave it alone.
831        if (offset >= realLength) {
832            return offset;
833        }
834        Editable editable = getText();
835        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
836            // Keep walking backward!
837            offset--;
838        }
839        return offset;
840    }
841
842    private int findText(Editable text, int offset) {
843        if (text.charAt(offset) != ' ') {
844            return offset;
845        }
846        return -1;
847    }
848
849    private RecipientChip findChip(int offset) {
850        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
851        // Find the chip that contains this offset.
852        for (int i = 0; i < chips.length; i++) {
853            RecipientChip chip = chips[i];
854            int start = getChipStart(chip);
855            int end = getChipEnd(chip);
856            if (offset >= start && offset <= end) {
857                return chip;
858            }
859        }
860        return null;
861    }
862
863    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
864        String displayText = entry.getDestination();
865        displayText = (String) mTokenizer.terminateToken(displayText);
866        // Always leave a blank space at the end of a chip.
867        int textLength = displayText.length() - 1;
868        SpannableString chipText = new SpannableString(displayText);
869        int end = getSelectionEnd();
870        int start = mTokenizer.findTokenStart(getText(), end);
871        try {
872            chipText.setSpan(constructChipSpan(entry, start, pressed), 0, textLength,
873                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
874        } catch (NullPointerException e) {
875            Log.e(TAG, e.getMessage(), e);
876            return null;
877        }
878
879        return chipText;
880    }
881
882    /**
883     * When an item in the suggestions list has been clicked, create a chip from the
884     * contact information of the selected item.
885     */
886    @Override
887    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
888        submitItemAtPosition(position);
889    }
890
891    private void submitItemAtPosition(int position) {
892        RecipientEntry entry = (RecipientEntry) getAdapter().getItem(position);
893        // If the display name and the address are the same, then make this
894        // a fake recipient that is editable.
895        if (TextUtils.equals(entry.getDisplayName(), entry.getDestination())) {
896            entry = RecipientEntry.constructFakeEntry(entry.getDestination());
897        }
898        clearComposingText();
899
900        int end = getSelectionEnd();
901        int start = mTokenizer.findTokenStart(getText(), end);
902
903        Editable editable = getText();
904        QwertyKeyListener.markAsReplaced(editable, start, end, "");
905        editable.replace(start, end, createChip(entry, false));
906    }
907
908    /** Returns a collection of contact Id for each chip inside this View. */
909    /* package */ Collection<Long> getContactIds() {
910        final Set<Long> result = new HashSet<Long>();
911        RecipientChip[] chips = getRecipients();
912        if (chips != null) {
913            for (RecipientChip chip : chips) {
914                result.add(chip.getContactId());
915            }
916        }
917        return result;
918    }
919
920    private RecipientChip[] getRecipients() {
921        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
922    }
923
924    /** Returns a collection of data Id for each chip inside this View. May be null. */
925    /* package */ Collection<Long> getDataIds() {
926        final Set<Long> result = new HashSet<Long>();
927        RecipientChip [] chips = getRecipients();
928        if (chips != null) {
929            for (RecipientChip chip : chips) {
930                result.add(chip.getDataId());
931            }
932        }
933        return result;
934    }
935
936
937    @Override
938    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
939        return false;
940    }
941
942    @Override
943    public void onDestroyActionMode(ActionMode mode) {
944    }
945
946    @Override
947    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
948        return false;
949    }
950
951    /**
952     * No chips are selectable.
953     */
954    @Override
955    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
956        return false;
957    }
958
959    /**
960     * Create the more chip. The more chip is text that replaces any chips that
961     * do not fit in the pre-defined available space when the
962     * RecipientEditTextView loses focus.
963     */
964    private ImageSpan createMoreChip() {
965        RecipientChip[] recipients = getRecipients();
966        if (recipients == null || recipients.length <= CHIP_LIMIT) {
967            return null;
968        }
969        int numRecipients = recipients.length;
970        int overage = numRecipients - CHIP_LIMIT;
971        Editable text = getText();
972        // TODO: get the correct size from visual design.
973        int width = (int) Math.floor(getWidth() * MORE_WIDTH_FACTOR);
974        int height = getLineHeight();
975        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
976        Canvas canvas = new Canvas(drawable);
977        String moreText = getResources().getString(mMoreString, overage);
978        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
979                getPaint());
980
981        Drawable result = new BitmapDrawable(getResources(), drawable);
982        result.setBounds(0, 0, width, height);
983        ImageSpan moreSpan = new ImageSpan(result);
984        Spannable spannable = getSpannable();
985        // Remove the overage chips.
986        RecipientChip[] chips = spannable.getSpans(0, text.length(), RecipientChip.class);
987        if (chips == null || chips.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>(chips.length);
993        int totalReplaceStart = 0;
994        int totalReplaceEnd = 0;
995        for (int i = numRecipients - overage; i < chips.length; i++) {
996            mRemovedSpans.add(chips[i]);
997            if (i == numRecipients - overage) {
998                totalReplaceStart = spannable.getSpanStart(chips[i]);
999            }
1000            if (i == chips.length - 1) {
1001                totalReplaceEnd = spannable.getSpanEnd(chips[i]);
1002            }
1003            chips[i].storeChipStart(spannable.getSpanStart(chips[i]));
1004            chips[i].storeChipEnd(spannable.getSpanEnd(chips[i]));
1005            spannable.removeSpan(chips[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 class RecipientTextWatcher implements TextWatcher {
1220        @Override
1221        public void afterTextChanged(Editable s) {
1222            if (mPendingChipsCount > 0) {
1223                return;
1224            }
1225            if (mSelectedChip != null) {
1226                setCursorVisible(true);
1227                setSelection(getText().length());
1228                clearSelectedChip();
1229            }
1230            int length = s.length();
1231            // Make sure there is content there to parse and that it is
1232            // not
1233            // just the commit character.
1234            if (length > 1) {
1235                char last = s.charAt(length() - 1);
1236                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1237                    commitByCharacter();
1238                } else if (last == COMMIT_CHAR_SPACE) {
1239                    // Check if this is a valid email address. If it is,
1240                    // commit it.
1241                    String text = getText().toString();
1242                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1243                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1244                            tokenStart));
1245                    if (mValidator != null && mValidator.isValid(sub)) {
1246                        commitByCharacter();
1247                    }
1248                }
1249            }
1250        }
1251
1252        @Override
1253        public void onTextChanged(CharSequence s, int start, int before, int count) {
1254        }
1255
1256        @Override
1257        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1258        }
1259    }
1260
1261}
1262