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