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