RecipientEditTextView.java revision 567ef28b55e35104060a3f3e7413b63e4590c73b
1bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant/*
2bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Copyright (C) 2011 The Android Open Source Project
3f5256e16dfc425c1d466f6308d4026d529ce9e0bHoward Hinnant *
4bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Licensed under the Apache License, Version 2.0 (the "License");
5b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant * you may not use this file except in compliance with the License.
6b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant * You may obtain a copy of the License at
7bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *
8bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *      http://www.apache.org/licenses/LICENSE-2.0
9bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant *
10bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Unless required by applicable law or agreed to in writing, software
11bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * distributed under the License is distributed on an "AS IS" BASIS,
12bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * See the License for the specific language governing permissions and
14bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * limitations under the License.
15bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant */
16bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
17bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantpackage com.android.ex.chips;
18bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
19061d0cc4db18d17bf01ed14c5db0be098205bd47Marshall Clowimport android.app.Dialog;
2070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.content.ClipData;
21bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.content.ClipboardManager;
22bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.content.Context;
23bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.content.DialogInterface;
24bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.content.DialogInterface.OnDismissListener;
25bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.Bitmap;
26bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.BitmapFactory;
27bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.Canvas;
28bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.Matrix;
29bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.Rect;
30bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.RectF;
31bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.drawable.BitmapDrawable;
32bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.graphics.drawable.Drawable;
33bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.os.AsyncTask;
34bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.os.Handler;
35bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.os.Message;
36bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.text.Editable;
37bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.text.Layout;
38bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.text.Spannable;
39bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.text.SpannableString;
40bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.text.SpannableStringBuilder;
41bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.text.Spanned;
4270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.text.TextPaint;
4370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.text.TextUtils;
4470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.text.TextWatcher;
4570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.text.method.QwertyKeyListener;
4670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.text.style.ImageSpan;
4770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.text.util.Rfc822Token;
4870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.text.util.Rfc822Tokenizer;
4970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.util.AttributeSet;
5070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.util.Log;
5170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.ActionMode;
5270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.ActionMode.Callback;
5370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.View.OnClickListener;
5470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.GestureDetector;
5570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.KeyEvent;
5670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.LayoutInflater;
5770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.Menu;
5870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.MenuItem;
5970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.MotionEvent;
6070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.View;
6170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.view.ViewParent;
6270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantimport android.widget.AdapterView;
63bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantimport android.widget.AdapterView.OnItemClickListener;
64import android.widget.Filterable;
65import android.widget.ListAdapter;
66import android.widget.ListPopupWindow;
67import android.widget.ListView;
68import android.widget.MultiAutoCompleteTextView;
69import android.widget.ScrollView;
70import android.widget.TextView;
71
72import java.util.ArrayList;
73import java.util.Collection;
74import java.util.HashMap;
75import java.util.HashSet;
76import java.util.Set;
77
78/**
79 * RecipientEditTextView is an auto complete text view for use with applications
80 * that use the new Chips UI for addressing a message to recipients.
81 */
82public class RecipientEditTextView extends MultiAutoCompleteTextView implements
83        OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
84        GestureDetector.OnGestureListener, OnDismissListener, OnClickListener {
85
86    private static final String TAG = "RecipientEditTextView";
87
88    // TODO: get correct number/ algorithm from with UX.
89    private static final int CHIP_LIMIT = 2;
90
91    private Drawable mChipBackground = null;
92
93    private Drawable mChipDelete = null;
94
95    private int mChipPadding;
96
97    private Tokenizer mTokenizer;
98
99    private Drawable mChipBackgroundPressed;
100
101    private RecipientChip mSelectedChip;
102
103    private int mAlternatesLayout;
104
105    private Bitmap mDefaultContactPhoto;
106
107    private ImageSpan mMoreChip;
108
109    private TextView mMoreItem;
110
111    private final ArrayList<String> mPendingChips = new ArrayList<String>();
112
113    private float mChipHeight;
114
115    private float mChipFontSize;
116
117    private Validator mValidator;
118
119    private Drawable mInvalidChipBackground;
120
121    private Handler mHandler;
122
123    private static int DISMISS = "dismiss".hashCode();
124
125    private static final long DISMISS_DELAY = 300;
126
127    private int mPendingChipsCount = 0;
128
129    private static int sSelectedTextColor = -1;
130
131    private static final char COMMIT_CHAR_COMMA = ',';
132
133    private static final char COMMIT_CHAR_SEMICOLON = ';';
134
135    private static final char COMMIT_CHAR_SPACE = ' ';
136
137    private ListPopupWindow mAlternatesPopup;
138
139    private ListPopupWindow mAddressPopup;
140
141    private ArrayList<RecipientChip> mTemporaryRecipients;
142
143    private ArrayList<RecipientChip> mRemovedSpans;
144
145    private boolean mShouldShrink = true;
146
147    // Chip copy fields.
148    private GestureDetector mGestureDetector;
149
150    private Dialog mCopyDialog;
151
152    private int mCopyViewRes;
153
154    private String mCopyAddress;
155
156    /**
157     * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a
158     * selected chip.
159     */
160    private OnItemClickListener mAlternatesListener;
161
162    private int mCheckedItem;
163    private TextWatcher mTextWatcher;
164
165    private ScrollView mScrollView;
166
167    private boolean mTried;
168
169    private final Runnable mAddTextWatcher = new Runnable() {
170        @Override
171        public void run() {
172            if (mTextWatcher == null) {
173                mTextWatcher = new RecipientTextWatcher();
174                addTextChangedListener(mTextWatcher);
175            }
176        }
177    };
178
179    private IndividualReplacementTask mIndividualReplacements;
180
181    private Runnable mHandlePendingChips = new Runnable() {
182
183        @Override
184        public void run() {
185            handlePendingChips();
186        }
187
188    };
189
190    public RecipientEditTextView(Context context, AttributeSet attrs) {
191        super(context, attrs);
192        if (sSelectedTextColor == -1) {
193            sSelectedTextColor = context.getResources().getColor(android.R.color.white);
194        }
195        mAlternatesPopup = new ListPopupWindow(context);
196        mAddressPopup = new ListPopupWindow(context);
197        mAlternatesListener = new OnItemClickListener() {
198            @Override
199            public void onItemClick(AdapterView<?> adapterView,View view, int position,
200                    long rowId) {
201                mAlternatesPopup.setOnItemClickListener(null);
202                replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
203                        .getRecipientEntry(position));
204                Message delayed = Message.obtain(mHandler, DISMISS);
205                delayed.obj = mAlternatesPopup;
206                mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
207                clearComposingText();
208            }
209        };
210        setSuggestionsEnabled(false);
211        setOnItemClickListener(this);
212        setCustomSelectionActionModeCallback(this);
213        mHandler = new Handler() {
214            @Override
215            public void handleMessage(Message msg) {
216                if (msg.what == DISMISS) {
217                    ((ListPopupWindow) msg.obj).dismiss();
218                    return;
219                }
220                super.handleMessage(msg);
221            }
222        };
223        mTextWatcher = new RecipientTextWatcher();
224        addTextChangedListener(mTextWatcher);
225        mGestureDetector = new GestureDetector(context, this);
226    }
227
228    @Override
229    public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
230        super.setAdapter(adapter);
231        if (adapter == null) {
232            return;
233        }
234    }
235
236    @Override
237    public void onSelectionChanged(int start, int end) {
238        // When selection changes, see if it is inside the chips area.
239        // If so, move the cursor back after the chips again.
240        Spannable span = getSpannable();
241        int textLength = getText().length();
242        RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class);
243        if (chips != null && chips.length > 0) {
244            if (chips != null && chips.length > 0) {
245                // Grab the last chip and set the cursor to after it.
246                setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength));
247            }
248        }
249        super.onSelectionChanged(start, end);
250    }
251
252    /**
253     * Convenience method: Append the specified text slice to the TextView's
254     * display buffer, upgrading it to BufferType.EDITABLE if it was
255     * not already editable. Commas are excluded as they are added automatically
256     * by the view.
257     */
258    @Override
259    public void append(CharSequence text, int start, int end) {
260        // We don't care about watching text changes while appending.
261        if (mTextWatcher != null) {
262            removeTextChangedListener(mTextWatcher);
263        }
264        super.append(text, start, end);
265        if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
266            final String displayString = (String) text;
267            int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA);
268            if (seperatorPos != 0 && !TextUtils.isEmpty(displayString)
269                    && TextUtils.getTrimmedLength(displayString) > 0) {
270                mPendingChipsCount++;
271                mPendingChips.add((String)text);
272            }
273        }
274        // Put a message on the queue to make sure we ALWAYS handle pending chips.
275        if (mPendingChipsCount > 0) {
276            postHandlePendingChips();
277        }
278        mHandler.post(mAddTextWatcher);
279    }
280
281    @Override
282    public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
283        if (!hasFocus) {
284            shrink();
285        } else {
286            expand();
287            scrollLineIntoView(getLineCount());
288        }
289        super.onFocusChanged(hasFocus, direction, previous);
290    }
291
292    private void shrink() {
293        if (mSelectedChip != null) {
294            clearSelectedChip();
295        } else {
296            // Reset any pending chips as they would have been handled
297            // when the field lost focus.
298            if (mPendingChipsCount > 0) {
299                postHandlePendingChips();
300            } else {
301                Editable editable = getText();
302                int end = getSelectionEnd();
303                int start = mTokenizer.findTokenStart(editable, end);
304                RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
305                if ((chips == null || chips.length == 0)) {
306                    int whatEnd = mTokenizer.findTokenEnd(getText(), start);
307                    // In the middle of chip; treat this as an edit
308                    // and commit the whole token.
309                    if (whatEnd != getSelectionEnd()) {
310                        handleEdit(start, whatEnd);
311                    } else {
312                        commitChip(start, end, editable);
313                    }
314                }
315            }
316            mHandler.post(mAddTextWatcher);
317        }
318        createMoreChip();
319    }
320
321    private void expand() {
322        removeMoreChip();
323        setCursorVisible(true);
324        Editable text = getText();
325        setSelection(text != null && text.length() > 0 ? text.length() : 0);
326        // If there are any temporary chips, try replacing them now that the user
327        // has expanded the field.
328        if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
329            new RecipientReplacementTask().execute();
330            mTemporaryRecipients = null;
331        }
332    }
333
334    private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
335        paint.setTextSize(mChipFontSize);
336        if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
337            Log.d(TAG, "Max width is negative: " + maxWidth);
338        }
339        return TextUtils.ellipsize(text, paint, maxWidth,
340                TextUtils.TruncateAt.END);
341    }
342
343    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
344        // Ellipsize the text so that it takes AT MOST the entire width of the
345        // autocomplete text entry area. Make sure to leave space for padding
346        // on the sides.
347        int height = (int) mChipHeight;
348        int deleteWidth = height;
349        CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint,
350                calculateAvailableWidth(true) - deleteWidth);
351
352        // Make sure there is a minimum chip width so the user can ALWAYS
353        // tap a chip without difficulty.
354        int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
355                ellipsizedText.length()))
356                + (mChipPadding * 2) + deleteWidth);
357
358        // Create the background of the chip.
359        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
360        Canvas canvas = new Canvas(tmpBitmap);
361        if (mChipBackgroundPressed != null) {
362            mChipBackgroundPressed.setBounds(0, 0, width, height);
363            mChipBackgroundPressed.draw(canvas);
364            paint.setColor(sSelectedTextColor);
365            // Align the display text with where the user enters text.
366            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, height
367                    - Math.abs(height - mChipFontSize)/2, paint);
368            // Make the delete a square.
369            mChipDelete.setBounds(width - deleteWidth, 0, width, height);
370            mChipDelete.draw(canvas);
371        } else {
372            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
373        }
374        return tmpBitmap;
375    }
376
377
378    /**
379     * Get the background drawable for a RecipientChip.
380     */
381    public Drawable getChipBackground(RecipientEntry contact) {
382        return (mValidator != null && mValidator.isValid(contact.getDestination())) ?
383                mChipBackground : mInvalidChipBackground;
384    }
385
386    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
387        // Ellipsize the text so that it takes AT MOST the entire width of the
388        // autocomplete text entry area. Make sure to leave space for padding
389        // on the sides.
390        int height = (int) mChipHeight;
391        int iconWidth = height;
392        String displayText =
393            !TextUtils.isEmpty(contact.getDisplayName()) ? contact.getDisplayName() :
394            !TextUtils.isEmpty(contact.getDestination()) ? contact.getDestination() : "";
395        CharSequence ellipsizedText = ellipsizeText(displayText, paint,
396                calculateAvailableWidth(false) - iconWidth);
397        // Make sure there is a minimum chip width so the user can ALWAYS
398        // tap a chip without difficulty.
399        int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
400                ellipsizedText.length()))
401                + (mChipPadding * 2) + iconWidth);
402
403        // Create the background of the chip.
404        Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
405        Canvas canvas = new Canvas(tmpBitmap);
406        Drawable background = getChipBackground(contact);
407        if (background != null) {
408            background.setBounds(0, 0, width, height);
409            background.draw(canvas);
410
411            // Don't draw photos for recipients that have been typed in.
412            if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) {
413                byte[] photoBytes = contact.getPhotoBytes();
414                // There may not be a photo yet if anything but the first contact address
415                // was selected.
416                if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
417                    // TODO: cache this in the recipient entry?
418                    ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
419                            .getPhotoThumbnailUri());
420                    photoBytes = contact.getPhotoBytes();
421                }
422
423                Bitmap photo;
424                if (photoBytes != null) {
425                    photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
426                } else {
427                    // TODO: can the scaled down default photo be cached?
428                    photo = mDefaultContactPhoto;
429                }
430                // Draw the photo on the left side.
431                Matrix matrix = new Matrix();
432                RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
433                RectF dst = new RectF(width - iconWidth, 0, width, height);
434                matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);
435                canvas.drawBitmap(photo, matrix, paint);
436            } else {
437                // Don't leave any space for the icon. It isn't being drawn.
438                iconWidth = 0;
439            }
440
441            // Align the display text with where the user enters text.
442            canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
443                    height - Math.abs(height - mChipFontSize) / 2, paint);
444        } else {
445            Log.w(TAG, "Unable to draw a background for the chips as it was never set");
446        }
447        return tmpBitmap;
448    }
449
450    public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
451            throws NullPointerException {
452        if (mChipBackground == null) {
453            throw new NullPointerException(
454                    "Unable to render any chips as setChipDimensions was not called.");
455        }
456        Layout layout = getLayout();
457
458        TextPaint paint = getPaint();
459        float defaultSize = paint.getTextSize();
460        int defaultColor = paint.getColor();
461
462        Bitmap tmpBitmap;
463        if (pressed) {
464            tmpBitmap = createSelectedChip(contact, paint, layout);
465
466        } else {
467            tmpBitmap = createUnselectedChip(contact, paint, layout);
468        }
469
470        // Pass the full text, un-ellipsized, to the chip.
471        Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
472        result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
473        RecipientChip recipientChip = new RecipientChip(result, contact, offset);
474        // Return text to the original size.
475        paint.setTextSize(defaultSize);
476        paint.setColor(defaultColor);
477        return recipientChip;
478    }
479
480    /**
481     * Calculate the bottom of the line the chip will be located on using:
482     * 1) which line the chip appears on
483     * 2) the height of a chip
484     * 3) padding built into the edit text view
485     */
486    private int calculateOffsetFromBottom(int line) {
487        // Line offsets start at zero.
488        int actualLine = getLineCount() - (line + 1);
489        return -((actualLine * ((int)mChipHeight) + getPaddingBottom()) + getPaddingTop());
490    }
491
492    /**
493     * Get the max amount of space a chip can take up. The formula takes into
494     * account the width of the EditTextView, any view padding, and padding
495     * that will be added to the chip.
496     */
497    private float calculateAvailableWidth(boolean pressed) {
498        return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
499    }
500
501    /**
502     * Set all chip dimensions and resources. This has to be done from the
503     * application as this is a static library.
504     * @param chipBackground
505     * @param chipBackgroundPressed
506     * @param invalidChip
507     * @param chipDelete
508     * @param defaultContact
509     * @param moreResource
510     * @param alternatesLayout
511     * @param chipHeight
512     * @param padding Padding around the text in a chip
513     * @param chipFontSize
514     * @param copyViewRes
515     */
516    public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed,
517            Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource,
518            int alternatesLayout, float chipHeight, float padding,
519            float chipFontSize, int copyViewRes) {
520        mChipBackground = chipBackground;
521        mChipBackgroundPressed = chipBackgroundPressed;
522        mChipDelete = chipDelete;
523        mChipPadding = (int) padding;
524        mAlternatesLayout = alternatesLayout;
525        mDefaultContactPhoto = defaultContact;
526        mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(moreResource, null);
527        mChipHeight = chipHeight;
528        mChipFontSize = chipFontSize;
529        mInvalidChipBackground = invalidChip;
530        mCopyViewRes = copyViewRes;
531    }
532
533    /**
534     * Set whether to shrink the recipients field such that at most
535     * one line of recipients chips are shown when the field loses
536     * focus. By default, the number of displayed recipients will be
537     * limited and a "more" chip will be shown when focus is lost.
538     * @param shrink
539     */
540    public void setOnFocusListShrinkRecipients(boolean shrink) {
541        mShouldShrink = shrink;
542    }
543
544    @Override
545    public void onSizeChanged(int width, int height, int oldw, int oldh) {
546        super.onSizeChanged(width, height, oldw, oldh);
547        if (width != 0 && height != 0 && mPendingChipsCount > 0) {
548            postHandlePendingChips();
549        }
550        // Try to find the scroll view parent, if it exists.
551        if (mScrollView == null && !mTried) {
552            ViewParent parent = getParent();
553            while (parent != null && !(parent instanceof ScrollView)) {
554                parent = parent.getParent();
555            }
556            if (parent != null) {
557                mScrollView = (ScrollView) parent;
558            }
559            mTried = true;
560        }
561    }
562
563    private void postHandlePendingChips() {
564        mHandler.removeCallbacks(mHandlePendingChips);
565        mHandler.post(mHandlePendingChips);
566    }
567
568    private void handlePendingChips() {
569        if (mPendingChipsCount <= 0) {
570            return;
571        }
572        if (getWidth() <= 0) {
573            // The widget has not been sized yet.
574            // This will be called as a result of onSizeChanged
575            // at a later point.
576            return;
577        }
578        synchronized (mPendingChips) {
579            mTemporaryRecipients = new ArrayList<RecipientChip>(mPendingChipsCount);
580            Editable editable = getText();
581            // Tokenize!
582            for (int i = 0; i < mPendingChips.size(); i++) {
583                String current = mPendingChips.get(i);
584                int tokenStart = editable.toString().indexOf(current);
585                int tokenEnd = tokenStart + current.length();
586                if (tokenStart >= 0) {
587                    // When we have a valid token, include it with the token
588                    // to the left.
589                    if (tokenEnd < editable.length() - 2
590                            && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
591                        tokenEnd++;
592                    }
593                    createReplacementChip(tokenStart, tokenEnd, editable);
594                }
595                mPendingChipsCount--;
596            }
597            sanitizeSpannable();
598            if (mTemporaryRecipients != null
599                    && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
600                if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
601                    new RecipientReplacementTask().execute();
602                    mTemporaryRecipients = null;
603                } else {
604                    // Create the "more" chip
605                    mIndividualReplacements = new IndividualReplacementTask();
606                    mIndividualReplacements.execute(new ArrayList<RecipientChip>(
607                            mTemporaryRecipients.subList(0, CHIP_LIMIT)));
608
609                    createMoreChip();
610                }
611            } else {
612                // There are too many recipients to look up, so just fall back
613                // to
614                // showing addresses for all of them.
615                mTemporaryRecipients = null;
616                createMoreChip();
617            }
618            mPendingChipsCount = 0;
619            mPendingChips.clear();
620        }
621    }
622
623    /**
624     * Remove any characters after the last valid chip.
625     */
626    private void sanitizeSpannable() {
627        // Find the last chip; eliminate any commit characters after it.
628        RecipientChip[] chips = getRecipients();
629        if (chips != null && chips.length > 0) {
630            int end;
631            ImageSpan lastSpan;
632            if (mMoreChip != null) {
633                lastSpan = mMoreChip;
634            } else {
635                lastSpan = chips[chips.length - 1];
636            }
637            end = getSpannable().getSpanEnd(lastSpan);
638            Editable editable = getText();
639            int length = editable.length();
640            if (length > end) {
641                // See what characters occur after that and eliminate them.
642                if (Log.isLoggable(TAG, Log.DEBUG)) {
643                    Log.d(TAG, "There were extra characters after the last tokenizable entry."
644                            + editable);
645                }
646                editable.delete(end + 1, length);
647            }
648        }
649    }
650
651    /**
652     * Create a chip that represents just the email address of a recipient. At some later
653     * point, this chip will be attached to a real contact entry, if one exists.
654     */
655    private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
656        if (alreadyHasChip(tokenStart, tokenEnd)) {
657            // There is already a chip present at this location.
658            // Don't recreate it.
659            return;
660        }
661        String token = editable.toString().substring(tokenStart, tokenEnd);
662        int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
663        if (commitCharIndex == token.length() - 1) {
664            token = token.substring(0, token.length() - 1);
665        }
666        RecipientEntry entry = createTokenizedEntry(token);
667        if (entry != null) {
668            String destText = entry.getDestination();
669            destText = (String) mTokenizer.terminateToken(destText);
670            // Always leave a blank space at the end of a chip.
671            int textLength = destText.length() - 1;
672            SpannableString chipText = new SpannableString(destText);
673            int end = getSelectionEnd();
674            int start = mTokenizer.findTokenStart(getText(), end);
675            RecipientChip chip = null;
676            try {
677                chip = constructChipSpan(entry, start, false);
678                chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
679            } catch (NullPointerException e) {
680                Log.e(TAG, e.getMessage(), e);
681            }
682
683            editable.replace(tokenStart, tokenEnd, chipText);
684            // Add this chip to the list of entries "to replace"
685            if (chip != null) {
686                mTemporaryRecipients.add(chip);
687            }
688        }
689    }
690
691    private RecipientEntry createTokenizedEntry(String token) {
692        if (TextUtils.isEmpty(token)) {
693            return null;
694        }
695        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
696        String display = null;
697        if (isValid(token) && tokens != null && tokens.length > 0) {
698            // If we can get a name from tokenizing, then generate an entry from
699            // this.
700            display = tokens[0].getName();
701            if (!TextUtils.isEmpty(display)) {
702                return RecipientEntry.constructGeneratedEntry(display, token);
703            } else {
704                display = tokens[0].getAddress();
705                if (!TextUtils.isEmpty(display)) {
706                    return RecipientEntry.constructFakeEntry(display);
707                }
708            }
709        }
710        // Unable to validate the token or to create a valid token from it.
711        // Just create a chip the user can edit.
712        if (mValidator != null && !mValidator.isValid(token)) {
713            // Try fixing up the entry using the validator.
714            token = mValidator.fixText(token).toString();
715            if (!TextUtils.isEmpty(token)) {
716                // protect against the case of a validator with a null domain,
717                // which doesn't add a domain to the token
718                Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(token);
719                if (tokenized.length > 0) {
720                    token = tokenized[0].getAddress();
721                }
722            }
723        }
724        // Otherwise, fallback to just creating an editable email address chip.
725        return RecipientEntry.constructFakeEntry(token);
726    }
727
728    private boolean isValid(String text) {
729        return mValidator == null ? true : mValidator.isValid(text);
730    }
731
732    private String tokenizeAddress(String destination) {
733        Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
734        if (tokens != null && tokens.length > 0) {
735            return tokens[0].getAddress();
736        }
737        return destination;
738    }
739
740    @Override
741    public void setTokenizer(Tokenizer tokenizer) {
742        mTokenizer = tokenizer;
743        super.setTokenizer(mTokenizer);
744    }
745
746    @Override
747    public void setValidator(Validator validator) {
748        mValidator = validator;
749        super.setValidator(validator);
750    }
751
752    /**
753     * We cannot use the default mechanism for replaceText. Instead,
754     * we override onItemClickListener so we can get all the associated
755     * contact information including display text, address, and id.
756     */
757    @Override
758    protected void replaceText(CharSequence text) {
759        return;
760    }
761
762    /**
763     * Dismiss any selected chips when the back key is pressed.
764     */
765    @Override
766    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
767        if (keyCode == KeyEvent.KEYCODE_BACK) {
768            clearSelectedChip();
769        }
770        return super.onKeyPreIme(keyCode, event);
771    }
772
773    /**
774     * Monitor key presses in this view to see if the user types
775     * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
776     * If the user has entered text that has contact matches and types
777     * a commit key, create a chip from the topmost matching contact.
778     * If the user has entered text that has no contact matches and types
779     * a commit key, then create a chip from the text they have entered.
780     */
781    @Override
782    public boolean onKeyUp(int keyCode, KeyEvent event) {
783        switch (keyCode) {
784            case KeyEvent.KEYCODE_ENTER:
785            case KeyEvent.KEYCODE_DPAD_CENTER:
786                if (event.hasNoModifiers()) {
787                    if (commitDefault()) {
788                        return true;
789                    }
790                    if (mSelectedChip != null) {
791                        clearSelectedChip();
792                        return true;
793                    } else if (focusNext()) {
794                        return true;
795                    }
796                }
797                break;
798            case KeyEvent.KEYCODE_TAB:
799                if (event.hasNoModifiers()) {
800                    if (mSelectedChip != null) {
801                        clearSelectedChip();
802                    } else {
803                        commitDefault();
804                    }
805                    if (focusNext()) {
806                        return true;
807                    }
808                }
809        }
810        return super.onKeyUp(keyCode, event);
811    }
812
813    private boolean focusNext() {
814        View next = focusSearch(View.FOCUS_DOWN);
815        if (next != null) {
816            next.requestFocus();
817            return true;
818        }
819        return false;
820    }
821
822    /**
823     * Create a chip from the default selection. If the popup is showing, the
824     * default is the first item in the popup suggestions list. Otherwise, it is
825     * whatever the user had typed in. End represents where the the tokenizer
826     * should search for a token to turn into a chip.
827     * @return If a chip was created from a real contact.
828     */
829    private boolean commitDefault() {
830        Editable editable = getText();
831        int end = getSelectionEnd();
832        int start = mTokenizer.findTokenStart(editable, end);
833
834        if (shouldCreateChip(start, end)) {
835            int whatEnd = mTokenizer.findTokenEnd(getText(), start);
836            // In the middle of chip; treat this as an edit
837            // and commit the whole token.
838            if (whatEnd != getSelectionEnd()) {
839                handleEdit(start, whatEnd);
840                return true;
841            }
842            return commitChip(start, end , editable);
843        }
844        return false;
845    }
846
847    private void commitByCharacter() {
848        Editable editable = getText();
849        int end = getSelectionEnd();
850        int start = mTokenizer.findTokenStart(editable, end);
851        if (shouldCreateChip(start, end)) {
852            commitChip(start, end, editable);
853        }
854        setSelection(getText().length());
855    }
856
857    private boolean commitChip(int start, int end, Editable editable) {
858        if (getAdapter().getCount() > 0 && enoughToFilter()) {
859            // choose the first entry.
860            submitItemAtPosition(0);
861            dismissDropDown();
862            return true;
863        } else {
864            int tokenEnd = mTokenizer.findTokenEnd(editable, start);
865            String text = editable.toString().substring(start, tokenEnd).trim();
866            clearComposingText();
867            if (text != null && text.length() > 0 && !text.equals(" ")) {
868                RecipientEntry entry = createTokenizedEntry(text);
869                if (entry != null) {
870                    QwertyKeyListener.markAsReplaced(editable, start, end, "");
871                    CharSequence chipText = createChip(entry, false);
872                    editable.replace(start, end, chipText);
873                }
874                dismissDropDown();
875                return true;
876            }
877        }
878        return false;
879    }
880
881    private boolean shouldCreateChip(int start, int end) {
882        return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
883    }
884
885    private boolean alreadyHasChip(int start, int end) {
886        RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
887        if ((chips == null || chips.length == 0)) {
888            return false;
889        }
890        return true;
891    }
892
893    private void handleEdit(int start, int end) {
894        // This is in the middle of a chip, so select out the whole chip
895        // and commit it.
896        Editable editable = getText();
897        setSelection(end);
898        String text = getText().toString().substring(start, end);
899        RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
900        QwertyKeyListener.markAsReplaced(editable, start, end, "");
901        CharSequence chipText = createChip(entry, false);
902        editable.replace(start, getSelectionEnd(), chipText);
903        dismissDropDown();
904    }
905
906    /**
907     * If there is a selected chip, delegate the key events
908     * to the selected chip.
909     */
910    @Override
911    public boolean onKeyDown(int keyCode, KeyEvent event) {
912        if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
913            if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
914                mAlternatesPopup.dismiss();
915            }
916            removeChip(mSelectedChip);
917        }
918
919        if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
920            return true;
921        }
922
923        return super.onKeyDown(keyCode, event);
924    }
925
926    private Spannable getSpannable() {
927        return getText();
928    }
929
930    private int getChipStart(RecipientChip chip) {
931        return getSpannable().getSpanStart(chip);
932    }
933
934    private int getChipEnd(RecipientChip chip) {
935        return getSpannable().getSpanEnd(chip);
936    }
937
938    /**
939     * Instead of filtering on the entire contents of the edit box,
940     * this subclass method filters on the range from
941     * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
942     * if the length of that range meets or exceeds {@link #getThreshold}
943     * and makes sure that the range is not already a Chip.
944     */
945    @Override
946    protected void performFiltering(CharSequence text, int keyCode) {
947        if (enoughToFilter()) {
948            int end = getSelectionEnd();
949            int start = mTokenizer.findTokenStart(text, end);
950            // If this is a RecipientChip, don't filter
951            // on its contents.
952            Spannable span = getSpannable();
953            RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
954            if (chips != null && chips.length > 0) {
955                return;
956            }
957        }
958        super.performFiltering(text, keyCode);
959    }
960
961    private void clearSelectedChip() {
962        if (mSelectedChip != null) {
963            unselectChip(mSelectedChip);
964            mSelectedChip = null;
965        }
966        setCursorVisible(true);
967    }
968
969    /**
970     * Monitor touch events in the RecipientEditTextView.
971     * If the view does not have focus, any tap on the view
972     * will just focus the view. If the view has focus, determine
973     * if the touch target is a recipient chip. If it is and the chip
974     * is not selected, select it and clear any other selected chips.
975     * If it isn't, then select that chip.
976     */
977    @Override
978    public boolean onTouchEvent(MotionEvent event) {
979        if (!isFocused()) {
980            // Ignore any chip taps until this view is focused.
981            return super.onTouchEvent(event);
982        }
983
984        boolean handled = super.onTouchEvent(event);
985        int action = event.getAction();
986        boolean chipWasSelected = false;
987        if (action == MotionEvent.ACTION_DOWN && mSelectedChip == null) {
988            mGestureDetector.onTouchEvent(event);
989        }
990        if (mCopyDialog == null && action == MotionEvent.ACTION_UP) {
991            float x = event.getX();
992            float y = event.getY();
993            int offset = putOffsetInRange(getOffsetForPosition(x, y));
994            RecipientChip currentChip = findChip(offset);
995            if (currentChip != null) {
996                if (action == MotionEvent.ACTION_UP) {
997                    if (mSelectedChip != null && mSelectedChip != currentChip) {
998                        clearSelectedChip();
999                        mSelectedChip = selectChip(currentChip);
1000                    } else if (mSelectedChip == null) {
1001                        // Selection may have moved due to the tap event,
1002                        // but make sure we correctly reset selection to the
1003                        // end so that any unfinished chips are committed.
1004                        setSelection(getText().length());
1005                        commitDefault();
1006                        mSelectedChip = selectChip(currentChip);
1007                    } else {
1008                        onClick(mSelectedChip, offset, x, y);
1009                    }
1010                }
1011                chipWasSelected = true;
1012                handled = true;
1013            }
1014        }
1015        if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1016            clearSelectedChip();
1017        }
1018        return handled;
1019    }
1020
1021    private void scrollLineIntoView(int line) {
1022        if (mScrollView != null) {
1023            mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
1024        }
1025    }
1026
1027    private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
1028            int width, Context context) {
1029        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1030        int bottom = calculateOffsetFromBottom(line);
1031        // Align the alternates popup with the left side of the View,
1032        // regardless of the position of the chip tapped.
1033        alternatesPopup.setWidth(width);
1034        alternatesPopup.setAnchorView(this);
1035        alternatesPopup.setVerticalOffset(bottom);
1036        alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
1037        alternatesPopup.setOnItemClickListener(mAlternatesListener);
1038        alternatesPopup.show();
1039        ListView listView = alternatesPopup.getListView();
1040        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1041        // Checked item would be -1 if the adapter has not
1042        // loaded the view that should be checked yet. The
1043        // variable will be set correctly when onCheckedItemChanged
1044        // is called in a separate thread.
1045        if (mCheckedItem != -1) {
1046            listView.setItemChecked(mCheckedItem, true);
1047            mCheckedItem = -1;
1048        }
1049    }
1050
1051    private ListAdapter createAlternatesAdapter(RecipientChip chip) {
1052        return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
1053                mAlternatesLayout, this);
1054    }
1055
1056    private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
1057        return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
1058                .getEntry());
1059    }
1060
1061    @Override
1062    public void onCheckedItemChanged(int position) {
1063        ListView listView = mAlternatesPopup.getListView();
1064        if (listView != null && listView.getCheckedItemCount() == 0) {
1065            listView.setItemChecked(position, true);
1066        } else {
1067            mCheckedItem = position;
1068        }
1069    }
1070
1071    // TODO: This algorithm will need a lot of tweaking after more people have used
1072    // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1073    // what comes before the finger.
1074    private int putOffsetInRange(int o) {
1075        int offset = o;
1076        Editable text = getText();
1077        int length = text.length();
1078        // Remove whitespace from end to find "real end"
1079        int realLength = length;
1080        for (int i = length - 1; i >= 0; i--) {
1081            if (text.charAt(i) == ' ') {
1082                realLength--;
1083            } else {
1084                break;
1085            }
1086        }
1087
1088        // If the offset is beyond or at the end of the text,
1089        // leave it alone.
1090        if (offset >= realLength) {
1091            return offset;
1092        }
1093        Editable editable = getText();
1094        while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
1095            // Keep walking backward!
1096            offset--;
1097        }
1098        return offset;
1099    }
1100
1101    private int findText(Editable text, int offset) {
1102        if (text.charAt(offset) != ' ') {
1103            return offset;
1104        }
1105        return -1;
1106    }
1107
1108    private RecipientChip findChip(int offset) {
1109        RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1110        // Find the chip that contains this offset.
1111        for (int i = 0; i < chips.length; i++) {
1112            RecipientChip chip = chips[i];
1113            int start = getChipStart(chip);
1114            int end = getChipEnd(chip);
1115            if (offset >= start && offset <= end) {
1116                return chip;
1117            }
1118        }
1119        return null;
1120    }
1121
1122    private CharSequence createChip(RecipientEntry entry, boolean pressed) {
1123        String displayText = entry.getDestination();
1124        displayText = (String) mTokenizer.terminateToken(displayText);
1125        // Always leave a blank space at the end of a chip.
1126        int textLength = displayText.length()-1;
1127        SpannableString chipText = new SpannableString(displayText);
1128        int end = getSelectionEnd();
1129        int start = mTokenizer.findTokenStart(getText(), end);
1130        try {
1131            chipText.setSpan(constructChipSpan(entry, start, pressed), 0, textLength,
1132                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1133        } catch (NullPointerException e) {
1134            Log.e(TAG, e.getMessage(), e);
1135            return null;
1136        }
1137
1138        return chipText;
1139    }
1140
1141    /**
1142     * When an item in the suggestions list has been clicked, create a chip from the
1143     * contact information of the selected item.
1144     */
1145    @Override
1146    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1147        submitItemAtPosition(position);
1148    }
1149
1150    private void submitItemAtPosition(int position) {
1151        RecipientEntry entry = createValidatedEntry(
1152                (RecipientEntry)getAdapter().getItem(position));
1153        if (entry == null) {
1154            return;
1155        }
1156        clearComposingText();
1157
1158        int end = getSelectionEnd();
1159        int start = mTokenizer.findTokenStart(getText(), end);
1160
1161        Editable editable = getText();
1162        QwertyKeyListener.markAsReplaced(editable, start, end, "");
1163        CharSequence chip = createChip(entry, false);
1164        if (chip != null) {
1165            editable.replace(start, end, chip);
1166        }
1167    }
1168
1169    private RecipientEntry createValidatedEntry(RecipientEntry item) {
1170        if (item == null) {
1171            return null;
1172        }
1173        final RecipientEntry entry;
1174        // If the display name and the address are the same, or if this is a
1175        // valid contact, but the destination is invalid, then make this a fake
1176        // recipient that is editable.
1177        String destination = item.getDestination();
1178        if (TextUtils.isEmpty(item.getDisplayName())
1179                || TextUtils.equals(item.getDisplayName(), destination)
1180                || (mValidator != null && !mValidator.isValid(destination))) {
1181            entry = RecipientEntry.constructFakeEntry(destination);
1182        } else {
1183            entry = item;
1184        }
1185        return entry;
1186    }
1187
1188    /** Returns a collection of contact Id for each chip inside this View. */
1189    /* package */ Collection<Long> getContactIds() {
1190        final Set<Long> result = new HashSet<Long>();
1191        RecipientChip[] chips = getRecipients();
1192        if (chips != null) {
1193            for (RecipientChip chip : chips) {
1194                result.add(chip.getContactId());
1195            }
1196        }
1197        return result;
1198    }
1199
1200    private RecipientChip[] getRecipients() {
1201        return getSpannable().getSpans(0, getText().length(), RecipientChip.class);
1202    }
1203
1204    /** Returns a collection of data Id for each chip inside this View. May be null. */
1205    /* package */ Collection<Long> getDataIds() {
1206        final Set<Long> result = new HashSet<Long>();
1207        RecipientChip [] chips = getRecipients();
1208        if (chips != null) {
1209            for (RecipientChip chip : chips) {
1210                result.add(chip.getDataId());
1211            }
1212        }
1213        return result;
1214    }
1215
1216
1217    @Override
1218    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1219        return false;
1220    }
1221
1222    @Override
1223    public void onDestroyActionMode(ActionMode mode) {
1224    }
1225
1226    @Override
1227    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1228        return false;
1229    }
1230
1231    /**
1232     * No chips are selectable.
1233     */
1234    @Override
1235    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1236        return false;
1237    }
1238
1239    /**
1240     * Create the more chip. The more chip is text that replaces any chips that
1241     * do not fit in the pre-defined available space when the
1242     * RecipientEditTextView loses focus.
1243     */
1244    private void createMoreChip() {
1245        if (!mShouldShrink) {
1246            return;
1247        }
1248
1249        RecipientChip[] recipients = getRecipients();
1250        if (recipients == null || recipients.length <= CHIP_LIMIT) {
1251            mMoreChip = null;
1252            return;
1253        }
1254        int numRecipients = recipients.length;
1255        int overage = numRecipients - CHIP_LIMIT;
1256        Editable text = getText();
1257        String moreText = String.format(mMoreItem.getText().toString(), overage);
1258        TextPaint morePaint = new TextPaint(getPaint());
1259        morePaint.setTextSize(mMoreItem.getTextSize());
1260        morePaint.setColor(mMoreItem.getCurrentTextColor());
1261        int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
1262                + mMoreItem.getPaddingRight();
1263        int height = getLineHeight();
1264        Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1265        Canvas canvas = new Canvas(drawable);
1266        canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0),
1267                morePaint);
1268
1269        Drawable result = new BitmapDrawable(getResources(), drawable);
1270        result.setBounds(0, 0, width, height);
1271        ImageSpan moreSpan = new ImageSpan(result);
1272        Spannable spannable = getSpannable();
1273        // Remove the overage chips.
1274        if (recipients == null || recipients.length == 0) {
1275            Log.w(TAG,
1276                    "We have recipients. Tt should not be possible to have zero RecipientChips.");
1277            mMoreChip = null;
1278            return;
1279        }
1280        mRemovedSpans = new ArrayList<RecipientChip>();
1281        int totalReplaceStart = 0;
1282        int totalReplaceEnd = 0;
1283        for (int i = numRecipients - overage; i < recipients.length; i++) {
1284            mRemovedSpans.add(recipients[i]);
1285            if (i == numRecipients - overage) {
1286                totalReplaceStart = spannable.getSpanStart(recipients[i]);
1287            }
1288            if (i == recipients.length - 1) {
1289                totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
1290            }
1291            if (mTemporaryRecipients != null && !mTemporaryRecipients.contains(recipients[i])) {
1292                recipients[i].storeChipStart(spannable.getSpanStart(recipients[i]));
1293                recipients[i].storeChipEnd(spannable.getSpanEnd(recipients[i]));
1294            }
1295            spannable.removeSpan(recipients[i]);
1296        }
1297        // TODO: why would these ever be backwards?
1298        int end = Math.max(totalReplaceStart, totalReplaceEnd);
1299        int start = Math.min(totalReplaceStart, totalReplaceEnd);
1300        SpannableString chipText = new SpannableString(text.subSequence(start, end));
1301        chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1302        text.replace(start, end, chipText);
1303        mMoreChip = moreSpan;
1304    }
1305
1306    /**
1307     * Replace the more chip, if it exists, with all of the recipient chips it had
1308     * replaced when the RecipientEditTextView gains focus.
1309     */
1310    private void removeMoreChip() {
1311        if (mMoreChip != null) {
1312            Spannable span = getSpannable();
1313            span.removeSpan(mMoreChip);
1314            mMoreChip = null;
1315            // Re-add the spans that were removed.
1316            if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
1317                // Recreate each removed span.
1318                Editable editable = getText();
1319                for (RecipientChip chip : mRemovedSpans) {
1320                    int chipStart = chip.getStoredChipStart();
1321                    int chipEnd;
1322                    String token;
1323                    if (chipStart == -1) {
1324                        // Need to find the location of the chip, again.
1325                        token = (String)mTokenizer.terminateToken(chip.getEntry().getDestination());
1326                        chipStart = editable.toString().indexOf(token);
1327                        // -1 for the space!
1328                        chipEnd = chipStart + token.length() - 1;
1329                    } else {
1330                        chipEnd = Math.min(editable.length(), chip.getStoredChipEnd());
1331                    }
1332                    if (Log.isLoggable(TAG, Log.DEBUG) && chipEnd != chip.getStoredChipEnd()) {
1333                        Log.d(TAG,
1334                                "Unexpectedly, the chip ended after the end of the editable text. "
1335                                        + "Chip End " + chip.getStoredChipEnd()
1336                                        + "Editable length " + editable.length());
1337                    }
1338                    // Only set the span if we found a matching token.
1339                    if (chipStart != -1) {
1340                        editable.setSpan(chip, chipStart, chipEnd,
1341                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
1342                    }
1343                }
1344                mRemovedSpans.clear();
1345            }
1346        }
1347    }
1348
1349    /**
1350     * Show specified chip as selected. If the RecipientChip is just an email address,
1351     * selecting the chip will take the contents of the chip and place it at
1352     * the end of the RecipientEditTextView for inline editing. If the
1353     * RecipientChip is a complete contact, then selecting the chip
1354     * will change the background color of the chip, show the delete icon,
1355     * and a popup window with the address in use highlighted and any other
1356     * alternate addresses for the contact.
1357     * @param currentChip Chip to select.
1358     * @return A RecipientChip in the selected state or null if the chip
1359     * just contained an email address.
1360     */
1361    public RecipientChip selectChip(RecipientChip currentChip) {
1362        if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
1363            CharSequence text = currentChip.getValue();
1364            Editable editable = getText();
1365            removeChip(currentChip);
1366            editable.append(text);
1367            setCursorVisible(true);
1368            setSelection(editable.length());
1369            return null;
1370        } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1371            int start = getChipStart(currentChip);
1372            int end = getChipEnd(currentChip);
1373            getSpannable().removeSpan(currentChip);
1374            RecipientChip newChip;
1375            try {
1376                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1377            } catch (NullPointerException e) {
1378                Log.e(TAG, e.getMessage(), e);
1379                return null;
1380            }
1381            Editable editable = getText();
1382            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1383            if (start == -1 || end == -1) {
1384                Log.d(TAG, "The chip being selected no longer exists but should.");
1385            } else {
1386                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1387            }
1388            newChip.setSelected(true);
1389            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1390                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1391            }
1392            showAddress(newChip, mAddressPopup, getWidth(), getContext());
1393            setCursorVisible(false);
1394            return newChip;
1395        } else {
1396            int start = getChipStart(currentChip);
1397            int end = getChipEnd(currentChip);
1398            getSpannable().removeSpan(currentChip);
1399            RecipientChip newChip;
1400            try {
1401                newChip = constructChipSpan(currentChip.getEntry(), start, true);
1402            } catch (NullPointerException e) {
1403                Log.e(TAG, e.getMessage(), e);
1404                return null;
1405            }
1406            Editable editable = getText();
1407            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1408            if (start == -1 || end == -1) {
1409                Log.d(TAG, "The chip being selected no longer exists but should.");
1410            } else {
1411                editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1412            }
1413            newChip.setSelected(true);
1414            if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
1415                scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
1416            }
1417            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
1418            setCursorVisible(false);
1419            return newChip;
1420        }
1421    }
1422
1423
1424    private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
1425            int width, Context context) {
1426        int line = getLayout().getLineForOffset(getChipStart(currentChip));
1427        int bottom = calculateOffsetFromBottom(line);
1428        // Align the alternates popup with the left side of the View,
1429        // regardless of the position of the chip tapped.
1430        popup.setWidth(width);
1431        popup.setAnchorView(this);
1432        popup.setVerticalOffset(bottom);
1433        popup.setAdapter(createSingleAddressAdapter(currentChip));
1434        popup.setOnItemClickListener(new OnItemClickListener() {
1435            @Override
1436            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
1437                unselectChip(currentChip);
1438                popup.dismiss();
1439            }
1440        });
1441        popup.show();
1442        ListView listView = popup.getListView();
1443        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1444        listView.setItemChecked(0, true);
1445    }
1446
1447    /**
1448     * Remove selection from this chip. Unselecting a RecipientChip will render
1449     * the chip without a delete icon and with an unfocused background. This
1450     * is called when the RecipientChip no longer has focus.
1451     */
1452    public void unselectChip(RecipientChip chip) {
1453        int start = getChipStart(chip);
1454        int end = getChipEnd(chip);
1455        Editable editable = getText();
1456        mSelectedChip = null;
1457        if (start == -1 || end == -1) {
1458            Log.e(TAG, "The chip being unselected no longer exists but should.");
1459        } else {
1460            getSpannable().removeSpan(chip);
1461            QwertyKeyListener.markAsReplaced(editable, start, end, "");
1462            editable.removeSpan(chip);
1463            try {
1464                editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
1465                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1466            } catch (NullPointerException e) {
1467                Log.e(TAG, e.getMessage(), e);
1468            }
1469        }
1470        setCursorVisible(true);
1471        setSelection(editable.length());
1472        if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1473            mAlternatesPopup.dismiss();
1474        }
1475    }
1476
1477
1478    /**
1479     * Return whether this chip contains the position passed in.
1480     */
1481    public boolean matchesChip(RecipientChip chip, int offset) {
1482        int start = getChipStart(chip);
1483        int end = getChipEnd(chip);
1484        if (start == -1 || end == -1) {
1485            return false;
1486        }
1487        return (offset >= start && offset <= end);
1488    }
1489
1490
1491    /**
1492     * Return whether a touch event was inside the delete target of
1493     * a selected chip. It is in the delete target if:
1494     * 1) the x and y points of the event are within the
1495     * delete assset.
1496     * 2) the point tapped would have caused a cursor to appear
1497     * right after the selected chip.
1498     * @return boolean
1499     */
1500    private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
1501        // Figure out the bounds of this chip and whether or not
1502        // the user clicked in the X portion.
1503        return chip.isSelected() && offset == getChipEnd(chip);
1504    }
1505
1506    /**
1507     * Remove the chip and any text associated with it from the RecipientEditTextView.
1508     */
1509    private void removeChip(RecipientChip chip) {
1510        Spannable spannable = getSpannable();
1511        int spanStart = spannable.getSpanStart(chip);
1512        int spanEnd = spannable.getSpanEnd(chip);
1513        Editable text = getText();
1514        int toDelete = spanEnd;
1515        boolean wasSelected = chip == mSelectedChip;
1516        // Clear that there is a selected chip before updating any text.
1517        if (wasSelected) {
1518            mSelectedChip = null;
1519        }
1520        // Always remove trailing spaces when removing a chip.
1521        while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
1522            toDelete++;
1523        }
1524        spannable.removeSpan(chip);
1525        text.delete(spanStart, toDelete);
1526        if (wasSelected) {
1527            clearSelectedChip();
1528        }
1529    }
1530
1531    /**
1532     * Replace this currently selected chip with a new chip
1533     * that uses the contact data provided.
1534     */
1535    public void replaceChip(RecipientChip chip, RecipientEntry entry) {
1536        boolean wasSelected = chip == mSelectedChip;
1537        if (wasSelected) {
1538            mSelectedChip = null;
1539        }
1540        int start = getChipStart(chip);
1541        int end = getChipEnd(chip);
1542        getSpannable().removeSpan(chip);
1543        Editable editable = getText();
1544        CharSequence chipText = createChip(entry, false);
1545        if (start == -1 || end == -1) {
1546            Log.e(TAG, "The chip to replace does not exist but should.");
1547            editable.insert(0, chipText);
1548        } else {
1549            // There may be a space to replace with this chip's new associated
1550            // space. Check for it.
1551            int toReplace = end;
1552            while (toReplace >= 0 && toReplace < editable.length()
1553                    && editable.charAt(toReplace) == ' ') {
1554                toReplace++;
1555            }
1556            editable.replace(start, toReplace, chipText);
1557        }
1558        setCursorVisible(true);
1559        if (wasSelected) {
1560            clearSelectedChip();
1561        }
1562    }
1563
1564    /**
1565     * Handle click events for a chip. When a selected chip receives a click
1566     * event, see if that event was in the delete icon. If so, delete it.
1567     * Otherwise, unselect the chip.
1568     */
1569    public void onClick(RecipientChip chip, int offset, float x, float y) {
1570        if (chip.isSelected()) {
1571            if (isInDelete(chip, offset, x, y)) {
1572                removeChip(chip);
1573            } else {
1574                clearSelectedChip();
1575            }
1576        }
1577    }
1578
1579    private boolean chipsPending() {
1580        return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
1581    }
1582
1583    @Override
1584    public void removeTextChangedListener(TextWatcher watcher) {
1585        mTextWatcher = null;
1586        super.removeTextChangedListener(watcher);
1587    }
1588
1589    private class RecipientTextWatcher implements TextWatcher {
1590        @Override
1591        public void afterTextChanged(Editable s) {
1592            // If the text has been set to null or empty, make sure we remove
1593            // all the spans we applied.
1594            if (TextUtils.isEmpty(s)) {
1595                // Remove all the chips spans.
1596                Spannable spannable = getSpannable();
1597                RecipientChip[] chips = spannable.getSpans(0, getText().length(),
1598                        RecipientChip.class);
1599                for (RecipientChip chip : chips) {
1600                    spannable.removeSpan(chip);
1601                }
1602                if (mMoreChip != null) {
1603                    spannable.removeSpan(mMoreChip);
1604                }
1605                return;
1606            }
1607            // Get whether there are any recipients pending addition to the
1608            // view. If there are, don't do anything in the text watcher.
1609            if (chipsPending()) {
1610                return;
1611            }
1612            if (mSelectedChip != null) {
1613                setCursorVisible(true);
1614                setSelection(getText().length());
1615                clearSelectedChip();
1616            }
1617            int length = s.length();
1618            // Make sure there is content there to parse and that it is
1619            // not just the commit character.
1620            if (length > 1) {
1621                char last;
1622                int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
1623                int len = length() - 1;
1624                if (end != len) {
1625                    last = s.charAt(end);
1626                } else {
1627                    last = s.charAt(len);
1628                }
1629                if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
1630                    commitByCharacter();
1631                } else if (last == COMMIT_CHAR_SPACE) {
1632                    // Check if this is a valid email address. If it is,
1633                    // commit it.
1634                    String text = getText().toString();
1635                    int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
1636                    String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
1637                            tokenStart));
1638                    if (mValidator != null && mValidator.isValid(sub)) {
1639                        commitByCharacter();
1640                    }
1641                }
1642            }
1643        }
1644
1645        @Override
1646        public void onTextChanged(CharSequence s, int start, int before, int count) {
1647            // Do nothing.
1648        }
1649
1650        @Override
1651        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1652        }
1653    }
1654
1655    private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
1656        private RecipientChip createFreeChip(RecipientEntry entry) {
1657            String displayText = entry.getDestination();
1658            displayText = (String) mTokenizer.terminateToken(displayText);
1659            try {
1660                return constructChipSpan(entry, -1, false);
1661            } catch (NullPointerException e) {
1662                Log.e(TAG, e.getMessage(), e);
1663                return null;
1664            }
1665        }
1666
1667        @Override
1668        protected Void doInBackground(Void... params) {
1669            if (mIndividualReplacements != null) {
1670                mIndividualReplacements.cancel(true);
1671            }
1672            // For each chip in the list, look up the matching contact.
1673            // If there is a match, replace that chip with the matching
1674            // chip.
1675            final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
1676            RecipientChip[] existingChips = getSpannable().getSpans(0, getText().length(),
1677                    RecipientChip.class);
1678            for (int i = 0; i < existingChips.length; i++) {
1679                originalRecipients.add(existingChips[i]);
1680            }
1681            if (mRemovedSpans != null) {
1682                originalRecipients.addAll(mRemovedSpans);
1683            }
1684            String[] addresses = new String[originalRecipients.size()];
1685            for (int i = 0; i < originalRecipients.size(); i++) {
1686                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1687            }
1688            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1689                    .getMatchingRecipients(getContext(), addresses);
1690            final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
1691            for (final RecipientChip temp : originalRecipients) {
1692                RecipientEntry entry = null;
1693                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1694                        && getSpannable().getSpanStart(temp) != -1) {
1695                    // Replace this.
1696                    entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
1697                            .getDestination())));
1698                }
1699                if (entry != null) {
1700                    replacements.add(createFreeChip(entry));
1701                } else {
1702                    replacements.add(temp);
1703                }
1704            }
1705            if (replacements != null && replacements.size() > 0) {
1706                mHandler.post(new Runnable() {
1707                    @Override
1708                    public void run() {
1709                        SpannableStringBuilder text = new SpannableStringBuilder(getText()
1710                                .toString());
1711                        Editable oldText = getText();
1712                        int start, end;
1713                        int i = 0;
1714                        for (RecipientChip chip : originalRecipients) {
1715                            start = oldText.getSpanStart(chip);
1716                            if (start != -1) {
1717                                end = oldText.getSpanEnd(chip);
1718                                text.removeSpan(chip);
1719                                // Leave a spot for the space!
1720                                text.setSpan(replacements.get(i), start, end,
1721                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1722                            }
1723                            i++;
1724                        }
1725                        Editable editable = getText();
1726                        editable.clear();
1727                        editable.insert(0, text);
1728                        originalRecipients.clear();
1729                    }
1730                });
1731            }
1732            return null;
1733        }
1734    }
1735
1736    private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
1737        @SuppressWarnings("unchecked")
1738        @Override
1739        protected Void doInBackground(Object... params) {
1740            // For each chip in the list, look up the matching contact.
1741            // If there is a match, replace that chip with the matching
1742            // chip.
1743            final ArrayList<RecipientChip> originalRecipients =
1744                (ArrayList<RecipientChip>) params[0];
1745            String[] addresses = new String[originalRecipients.size()];
1746            for (int i = 0; i < originalRecipients.size(); i++) {
1747                addresses[i] = originalRecipients.get(i).getEntry().getDestination();
1748            }
1749            HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
1750                    .getMatchingRecipients(getContext(), addresses);
1751            for (final RecipientChip temp : originalRecipients) {
1752                if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
1753                        && getSpannable().getSpanStart(temp) != -1) {
1754                    // Replace this.
1755                    final RecipientEntry entry = createValidatedEntry(entries
1756                            .get(tokenizeAddress(temp.getEntry().getDestination())));
1757                    if (entry != null) {
1758                        mHandler.post(new Runnable() {
1759                            @Override
1760                            public void run() {
1761                                replaceChip(temp, entry);
1762                            }
1763                        });
1764                    }
1765                }
1766            }
1767            return null;
1768        }
1769    }
1770
1771    @Override
1772    public boolean onDown(MotionEvent e) {
1773        return false;
1774    }
1775
1776    @Override
1777    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
1778        // Do nothing.
1779        return false;
1780    }
1781
1782    @Override
1783    public void onLongPress(MotionEvent event) {
1784        if (mSelectedChip != null) {
1785            return;
1786        }
1787        float x = event.getX();
1788        float y = event.getY();
1789        int offset = putOffsetInRange(getOffsetForPosition(x, y));
1790        RecipientChip currentChip = findChip(offset);
1791        if (currentChip != null) {
1792            // Copy the selected chip email address.
1793            showCopyDialog(currentChip.getEntry().getDestination());
1794        }
1795    }
1796
1797    private void showCopyDialog(final String address) {
1798        mCopyAddress = address;
1799        mCopyDialog = new Dialog(getContext());
1800        mCopyDialog.setTitle(address);
1801        mCopyDialog.setContentView(mCopyViewRes);
1802        mCopyDialog.setCancelable(true);
1803        mCopyDialog.setCanceledOnTouchOutside(true);
1804        mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this);
1805        mCopyDialog.setOnDismissListener(this);
1806        mCopyDialog.show();
1807    }
1808
1809    @Override
1810    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
1811        // Do nothing.
1812        return false;
1813    }
1814
1815    @Override
1816    public void onShowPress(MotionEvent e) {
1817        // Do nothing.
1818    }
1819
1820    @Override
1821    public boolean onSingleTapUp(MotionEvent e) {
1822        // Do nothing.
1823        return false;
1824    }
1825
1826    @Override
1827    public void onDismiss(DialogInterface dialog) {
1828        mCopyAddress = null;
1829        mCopyDialog = null;
1830    }
1831
1832    @Override
1833    public void onClick(View v) {
1834        // Copy this to the clipboard.
1835        ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
1836                Context.CLIPBOARD_SERVICE);
1837        clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
1838        mCopyDialog.dismiss();
1839    }
1840}
1841