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