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