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