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