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