Home | History | Annotate | Download | only in chips
      1 /*
      2 
      3  * Copyright (C) 2011 The Android Open Source Project
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *      http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  */
     17 
     18 package com.android.ex.chips;
     19 
     20 import android.app.Dialog;
     21 import android.content.ClipData;
     22 import android.content.ClipDescription;
     23 import android.content.ClipboardManager;
     24 import android.content.Context;
     25 import android.content.DialogInterface;
     26 import android.content.DialogInterface.OnDismissListener;
     27 import android.content.res.Resources;
     28 import android.content.res.TypedArray;
     29 import android.graphics.Bitmap;
     30 import android.graphics.BitmapFactory;
     31 import android.graphics.Canvas;
     32 import android.graphics.Matrix;
     33 import android.graphics.Point;
     34 import android.graphics.Rect;
     35 import android.graphics.RectF;
     36 import android.graphics.drawable.BitmapDrawable;
     37 import android.graphics.drawable.Drawable;
     38 import android.os.AsyncTask;
     39 import android.os.Build;
     40 import android.os.Handler;
     41 import android.os.Looper;
     42 import android.os.Message;
     43 import android.os.Parcelable;
     44 import android.text.Editable;
     45 import android.text.InputType;
     46 import android.text.Layout;
     47 import android.text.Spannable;
     48 import android.text.SpannableString;
     49 import android.text.SpannableStringBuilder;
     50 import android.text.Spanned;
     51 import android.text.TextPaint;
     52 import android.text.TextUtils;
     53 import android.text.TextWatcher;
     54 import android.text.method.QwertyKeyListener;
     55 import android.text.style.ImageSpan;
     56 import android.text.util.Rfc822Token;
     57 import android.text.util.Rfc822Tokenizer;
     58 import android.util.AttributeSet;
     59 import android.util.Log;
     60 import android.util.TypedValue;
     61 import android.view.ActionMode;
     62 import android.view.ActionMode.Callback;
     63 import android.view.DragEvent;
     64 import android.view.GestureDetector;
     65 import android.view.KeyEvent;
     66 import android.view.LayoutInflater;
     67 import android.view.Menu;
     68 import android.view.MenuItem;
     69 import android.view.MotionEvent;
     70 import android.view.View;
     71 import android.view.View.OnClickListener;
     72 import android.view.ViewParent;
     73 import android.view.inputmethod.EditorInfo;
     74 import android.view.inputmethod.InputConnection;
     75 import android.widget.AdapterView;
     76 import android.widget.AdapterView.OnItemClickListener;
     77 import android.widget.Button;
     78 import android.widget.Filterable;
     79 import android.widget.ListAdapter;
     80 import android.widget.ListPopupWindow;
     81 import android.widget.ListView;
     82 import android.widget.MultiAutoCompleteTextView;
     83 import android.widget.ScrollView;
     84 import android.widget.TextView;
     85 
     86 import com.android.ex.chips.RecipientAlternatesAdapter.RecipientMatchCallback;
     87 import com.android.ex.chips.recipientchip.DrawableRecipientChip;
     88 import com.android.ex.chips.recipientchip.InvisibleRecipientChip;
     89 import com.android.ex.chips.recipientchip.VisibleRecipientChip;
     90 
     91 import java.util.ArrayList;
     92 import java.util.Arrays;
     93 import java.util.Collection;
     94 import java.util.Collections;
     95 import java.util.Comparator;
     96 import java.util.HashSet;
     97 import java.util.List;
     98 import java.util.Map;
     99 import java.util.Set;
    100 import java.util.regex.Matcher;
    101 import java.util.regex.Pattern;
    102 
    103 /**
    104  * RecipientEditTextView is an auto complete text view for use with applications
    105  * that use the new Chips UI for addressing a message to recipients.
    106  */
    107 public class RecipientEditTextView extends MultiAutoCompleteTextView implements
    108         OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
    109         GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
    110         TextView.OnEditorActionListener {
    111 
    112     private static final char COMMIT_CHAR_COMMA = ',';
    113 
    114     private static final char COMMIT_CHAR_SEMICOLON = ';';
    115 
    116     private static final char COMMIT_CHAR_SPACE = ' ';
    117 
    118     private static final String SEPARATOR = String.valueOf(COMMIT_CHAR_COMMA)
    119             + String.valueOf(COMMIT_CHAR_SPACE);
    120 
    121     private static final String TAG = "RecipientEditTextView";
    122 
    123     private static int DISMISS = "dismiss".hashCode();
    124 
    125     private static final long DISMISS_DELAY = 300;
    126 
    127     // TODO: get correct number/ algorithm from with UX.
    128     // Visible for testing.
    129     /*package*/ static final int CHIP_LIMIT = 2;
    130 
    131     private static final int MAX_CHIPS_PARSED = 50;
    132 
    133     private static int sSelectedTextColor = -1;
    134 
    135     // Resources for displaying chips.
    136     private Drawable mChipBackground = null;
    137 
    138     private Drawable mChipDelete = null;
    139 
    140     private Drawable mInvalidChipBackground;
    141 
    142     private Drawable mChipBackgroundPressed;
    143 
    144     private float mChipHeight;
    145 
    146     private float mChipFontSize;
    147 
    148     private float mLineSpacingExtra;
    149 
    150     private int mChipPadding;
    151 
    152     private Tokenizer mTokenizer;
    153 
    154     private Validator mValidator;
    155 
    156     private DrawableRecipientChip mSelectedChip;
    157 
    158     private int mAlternatesLayout;
    159 
    160     private Bitmap mDefaultContactPhoto;
    161 
    162     private ImageSpan mMoreChip;
    163 
    164     private TextView mMoreItem;
    165 
    166     // VisibleForTesting
    167     final ArrayList<String> mPendingChips = new ArrayList<String>();
    168 
    169     private Handler mHandler;
    170 
    171     private int mPendingChipsCount = 0;
    172 
    173     private boolean mNoChips = false;
    174 
    175     private ListPopupWindow mAlternatesPopup;
    176 
    177     private ListPopupWindow mAddressPopup;
    178 
    179     // VisibleForTesting
    180     ArrayList<DrawableRecipientChip> mTemporaryRecipients;
    181 
    182     private ArrayList<DrawableRecipientChip> mRemovedSpans;
    183 
    184     private boolean mShouldShrink = true;
    185 
    186     // Chip copy fields.
    187     private GestureDetector mGestureDetector;
    188 
    189     private Dialog mCopyDialog;
    190 
    191     private String mCopyAddress;
    192 
    193     /**
    194      * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a
    195      * selected chip.
    196      */
    197     private OnItemClickListener mAlternatesListener;
    198 
    199     private int mCheckedItem;
    200 
    201     private TextWatcher mTextWatcher;
    202 
    203     // Obtain the enclosing scroll view, if it exists, so that the view can be
    204     // scrolled to show the last line of chips content.
    205     private ScrollView mScrollView;
    206 
    207     private boolean mTriedGettingScrollView;
    208 
    209     private boolean mDragEnabled = false;
    210 
    211     // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
    212     // parens, so numbers such as "1 (425) 222-2342" match.
    213     private static final Pattern PHONE_PATTERN
    214         = Pattern.compile(                                  // sdd = space, dot, or dash
    215                 "(\\+[0-9]+[\\- \\.]*)?"                    // +<digits><sdd>*
    216                 + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?"         // 1(<digits>)<sdd>*
    217                 + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
    218 
    219     private final Runnable mAddTextWatcher = new Runnable() {
    220         @Override
    221         public void run() {
    222             if (mTextWatcher == null) {
    223                 mTextWatcher = new RecipientTextWatcher();
    224                 addTextChangedListener(mTextWatcher);
    225             }
    226         }
    227     };
    228 
    229     private IndividualReplacementTask mIndividualReplacements;
    230 
    231     private Runnable mHandlePendingChips = new Runnable() {
    232 
    233         @Override
    234         public void run() {
    235             handlePendingChips();
    236         }
    237 
    238     };
    239 
    240     private Runnable mDelayedShrink = new Runnable() {
    241 
    242         @Override
    243         public void run() {
    244             shrink();
    245         }
    246 
    247     };
    248 
    249     private int mMaxLines;
    250 
    251     private static int sExcessTopPadding = -1;
    252 
    253     private int mActionBarHeight;
    254 
    255     private boolean mAttachedToWindow;
    256 
    257     public RecipientEditTextView(Context context, AttributeSet attrs) {
    258         super(context, attrs);
    259         setChipDimensions(context, attrs);
    260         if (sSelectedTextColor == -1) {
    261             sSelectedTextColor = context.getResources().getColor(android.R.color.white);
    262         }
    263         mAlternatesPopup = new ListPopupWindow(context);
    264         mAddressPopup = new ListPopupWindow(context);
    265         mCopyDialog = new Dialog(context);
    266         mAlternatesListener = new OnItemClickListener() {
    267             @Override
    268             public void onItemClick(AdapterView<?> adapterView,View view, int position,
    269                     long rowId) {
    270                 mAlternatesPopup.setOnItemClickListener(null);
    271                 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
    272                         .getRecipientEntry(position));
    273                 Message delayed = Message.obtain(mHandler, DISMISS);
    274                 delayed.obj = mAlternatesPopup;
    275                 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
    276                 clearComposingText();
    277             }
    278         };
    279         setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    280         setOnItemClickListener(this);
    281         setCustomSelectionActionModeCallback(this);
    282         mHandler = new Handler() {
    283             @Override
    284             public void handleMessage(Message msg) {
    285                 if (msg.what == DISMISS) {
    286                     ((ListPopupWindow) msg.obj).dismiss();
    287                     return;
    288                 }
    289                 super.handleMessage(msg);
    290             }
    291         };
    292         mTextWatcher = new RecipientTextWatcher();
    293         addTextChangedListener(mTextWatcher);
    294         mGestureDetector = new GestureDetector(context, this);
    295         setOnEditorActionListener(this);
    296     }
    297 
    298     @Override
    299     protected void onDetachedFromWindow() {
    300         mAttachedToWindow = false;
    301     }
    302 
    303     @Override
    304     protected void onAttachedToWindow() {
    305         mAttachedToWindow = true;
    306     }
    307 
    308     @Override
    309     public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
    310         if (action == EditorInfo.IME_ACTION_DONE) {
    311             if (commitDefault()) {
    312                 return true;
    313             }
    314             if (mSelectedChip != null) {
    315                 clearSelectedChip();
    316                 return true;
    317             } else if (focusNext()) {
    318                 return true;
    319             }
    320         }
    321         return false;
    322     }
    323 
    324     @Override
    325     public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
    326         InputConnection connection = super.onCreateInputConnection(outAttrs);
    327         int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
    328         if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
    329             // clear the existing action
    330             outAttrs.imeOptions ^= imeActions;
    331             // set the DONE action
    332             outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
    333         }
    334         if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
    335             outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
    336         }
    337 
    338         outAttrs.actionId = EditorInfo.IME_ACTION_DONE;
    339         outAttrs.actionLabel = getContext().getString(R.string.done);
    340         return connection;
    341     }
    342 
    343     /*package*/ DrawableRecipientChip getLastChip() {
    344         DrawableRecipientChip last = null;
    345         DrawableRecipientChip[] chips = getSortedRecipients();
    346         if (chips != null && chips.length > 0) {
    347             last = chips[chips.length - 1];
    348         }
    349         return last;
    350     }
    351 
    352     @Override
    353     public void onSelectionChanged(int start, int end) {
    354         // When selection changes, see if it is inside the chips area.
    355         // If so, move the cursor back after the chips again.
    356         DrawableRecipientChip last = getLastChip();
    357         if (last != null && start < getSpannable().getSpanEnd(last)) {
    358             // Grab the last chip and set the cursor to after it.
    359             setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length()));
    360         }
    361         super.onSelectionChanged(start, end);
    362     }
    363 
    364     @Override
    365     public void onRestoreInstanceState(Parcelable state) {
    366         if (!TextUtils.isEmpty(getText())) {
    367             super.onRestoreInstanceState(null);
    368         } else {
    369             super.onRestoreInstanceState(state);
    370         }
    371     }
    372 
    373     @Override
    374     public Parcelable onSaveInstanceState() {
    375         // If the user changes orientation while they are editing, just roll back the selection.
    376         clearSelectedChip();
    377         return super.onSaveInstanceState();
    378     }
    379 
    380     /**
    381      * Convenience method: Append the specified text slice to the TextView's
    382      * display buffer, upgrading it to BufferType.EDITABLE if it was
    383      * not already editable. Commas are excluded as they are added automatically
    384      * by the view.
    385      */
    386     @Override
    387     public void append(CharSequence text, int start, int end) {
    388         // We don't care about watching text changes while appending.
    389         if (mTextWatcher != null) {
    390             removeTextChangedListener(mTextWatcher);
    391         }
    392         super.append(text, start, end);
    393         if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
    394             String displayString = text.toString();
    395 
    396             if (!displayString.trim().endsWith(String.valueOf(COMMIT_CHAR_COMMA))) {
    397                 // We have no separator, so we should add it
    398                 super.append(SEPARATOR, 0, SEPARATOR.length());
    399                 displayString += SEPARATOR;
    400             }
    401 
    402             if (!TextUtils.isEmpty(displayString)
    403                     && TextUtils.getTrimmedLength(displayString) > 0) {
    404                 mPendingChipsCount++;
    405                 mPendingChips.add(displayString);
    406             }
    407         }
    408         // Put a message on the queue to make sure we ALWAYS handle pending
    409         // chips.
    410         if (mPendingChipsCount > 0) {
    411             postHandlePendingChips();
    412         }
    413         mHandler.post(mAddTextWatcher);
    414     }
    415 
    416     @Override
    417     public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
    418         super.onFocusChanged(hasFocus, direction, previous);
    419         if (!hasFocus) {
    420             shrink();
    421         } else {
    422             expand();
    423         }
    424     }
    425 
    426     private int getExcessTopPadding() {
    427         if (sExcessTopPadding == -1) {
    428             sExcessTopPadding = (int) (mChipHeight + mLineSpacingExtra);
    429         }
    430         return sExcessTopPadding;
    431     }
    432 
    433     @Override
    434     public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
    435         super.setAdapter(adapter);
    436         ((BaseRecipientAdapter) adapter)
    437                 .registerUpdateObserver(new BaseRecipientAdapter.EntriesUpdatedObserver() {
    438                     @Override
    439                     public void onChanged(List<RecipientEntry> entries) {
    440                         // Scroll the chips field to the top of the screen so
    441                         // that the user can see as many results as possible.
    442                         if (entries != null && entries.size() > 0) {
    443                             scrollBottomIntoView();
    444                         }
    445                     }
    446                 });
    447     }
    448 
    449     private void scrollBottomIntoView() {
    450         if (mScrollView != null && mShouldShrink) {
    451             int[] location = new int[2];
    452             getLocationOnScreen(location);
    453             int height = getHeight();
    454             int currentPos = location[1] + height;
    455             // Desired position shows at least 1 line of chips below the action
    456             // bar. We add excess padding to make sure this is always below other
    457             // content.
    458             int desiredPos = (int) mChipHeight + mActionBarHeight + getExcessTopPadding();
    459             if (currentPos > desiredPos) {
    460                 mScrollView.scrollBy(0, currentPos - desiredPos);
    461             }
    462         }
    463     }
    464 
    465     @Override
    466     public void performValidation() {
    467         // Do nothing. Chips handles its own validation.
    468     }
    469 
    470     private void shrink() {
    471         if (mTokenizer == null) {
    472             return;
    473         }
    474         long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1;
    475         if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT
    476                 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) {
    477             clearSelectedChip();
    478         } else {
    479             if (getWidth() <= 0) {
    480                 // We don't have the width yet which means the view hasn't been drawn yet
    481                 // and there is no reason to attempt to commit chips yet.
    482                 // This focus lost must be the result of an orientation change
    483                 // or an initial rendering.
    484                 // Re-post the shrink for later.
    485                 mHandler.removeCallbacks(mDelayedShrink);
    486                 mHandler.post(mDelayedShrink);
    487                 return;
    488             }
    489             // Reset any pending chips as they would have been handled
    490             // when the field lost focus.
    491             if (mPendingChipsCount > 0) {
    492                 postHandlePendingChips();
    493             } else {
    494                 Editable editable = getText();
    495                 int end = getSelectionEnd();
    496                 int start = mTokenizer.findTokenStart(editable, end);
    497                 DrawableRecipientChip[] chips =
    498                         getSpannable().getSpans(start, end, DrawableRecipientChip.class);
    499                 if ((chips == null || chips.length == 0)) {
    500                     Editable text = getText();
    501                     int whatEnd = mTokenizer.findTokenEnd(text, start);
    502                     // This token was already tokenized, so skip past the ending token.
    503                     if (whatEnd < text.length() && text.charAt(whatEnd) == ',') {
    504                         whatEnd = movePastTerminators(whatEnd);
    505                     }
    506                     // In the middle of chip; treat this as an edit
    507                     // and commit the whole token.
    508                     int selEnd = getSelectionEnd();
    509                     if (whatEnd != selEnd) {
    510                         handleEdit(start, whatEnd);
    511                     } else {
    512                         commitChip(start, end, editable);
    513                     }
    514                 }
    515             }
    516             mHandler.post(mAddTextWatcher);
    517         }
    518         createMoreChip();
    519     }
    520 
    521     private void expand() {
    522         if (mShouldShrink) {
    523             setMaxLines(Integer.MAX_VALUE);
    524         }
    525         removeMoreChip();
    526         setCursorVisible(true);
    527         Editable text = getText();
    528         setSelection(text != null && text.length() > 0 ? text.length() : 0);
    529         // If there are any temporary chips, try replacing them now that the user
    530         // has expanded the field.
    531         if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
    532             new RecipientReplacementTask().execute();
    533             mTemporaryRecipients = null;
    534         }
    535     }
    536 
    537     private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
    538         paint.setTextSize(mChipFontSize);
    539         if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
    540             Log.d(TAG, "Max width is negative: " + maxWidth);
    541         }
    542         return TextUtils.ellipsize(text, paint, maxWidth,
    543                 TextUtils.TruncateAt.END);
    544     }
    545 
    546     private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint) {
    547         // Ellipsize the text so that it takes AT MOST the entire width of the
    548         // autocomplete text entry area. Make sure to leave space for padding
    549         // on the sides.
    550         int height = (int) mChipHeight;
    551         int deleteWidth = height;
    552         float[] widths = new float[1];
    553         paint.getTextWidths(" ", widths);
    554         CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
    555                 calculateAvailableWidth() - deleteWidth - widths[0]);
    556 
    557         // Make sure there is a minimum chip width so the user can ALWAYS
    558         // tap a chip without difficulty.
    559         int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
    560                 ellipsizedText.length()))
    561                 + (mChipPadding * 2) + deleteWidth);
    562 
    563         // Create the background of the chip.
    564         Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    565         Canvas canvas = new Canvas(tmpBitmap);
    566         if (mChipBackgroundPressed != null) {
    567             mChipBackgroundPressed.setBounds(0, 0, width, height);
    568             mChipBackgroundPressed.draw(canvas);
    569             paint.setColor(sSelectedTextColor);
    570             // Vertically center the text in the chip.
    571             canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
    572                     getTextYOffset((String) ellipsizedText, paint, height), paint);
    573             // Make the delete a square.
    574             Rect backgroundPadding = new Rect();
    575             mChipBackgroundPressed.getPadding(backgroundPadding);
    576             mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left,
    577                     0 + backgroundPadding.top,
    578                     width - backgroundPadding.right,
    579                     height - backgroundPadding.bottom);
    580             mChipDelete.draw(canvas);
    581         } else {
    582             Log.w(TAG, "Unable to draw a background for the chips as it was never set");
    583         }
    584         return tmpBitmap;
    585     }
    586 
    587 
    588     private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint,
    589             boolean leaveBlankIconSpacer) {
    590         // Ellipsize the text so that it takes AT MOST the entire width of the
    591         // autocomplete text entry area. Make sure to leave space for padding
    592         // on the sides.
    593         int height = (int) mChipHeight;
    594         int iconWidth = height;
    595         float[] widths = new float[1];
    596         paint.getTextWidths(" ", widths);
    597         CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
    598                 calculateAvailableWidth() - iconWidth - widths[0]);
    599         // Make sure there is a minimum chip width so the user can ALWAYS
    600         // tap a chip without difficulty.
    601         int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
    602                 ellipsizedText.length()))
    603                 + (mChipPadding * 2) + iconWidth);
    604 
    605         // Create the background of the chip.
    606         Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    607         Canvas canvas = new Canvas(tmpBitmap);
    608         Drawable background = getChipBackground(contact);
    609         if (background != null) {
    610             background.setBounds(0, 0, width, height);
    611             background.draw(canvas);
    612 
    613             // Don't draw photos for recipients that have been typed in OR generated on the fly.
    614             long contactId = contact.getContactId();
    615             boolean drawPhotos = isPhoneQuery() ?
    616                     contactId != RecipientEntry.INVALID_CONTACT
    617                     : (contactId != RecipientEntry.INVALID_CONTACT
    618                             && (contactId != RecipientEntry.GENERATED_CONTACT &&
    619                                     !TextUtils.isEmpty(contact.getDisplayName())));
    620             if (drawPhotos) {
    621                 byte[] photoBytes = contact.getPhotoBytes();
    622                 // There may not be a photo yet if anything but the first contact address
    623                 // was selected.
    624                 if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
    625                     // TODO: cache this in the recipient entry?
    626                     ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
    627                             .getPhotoThumbnailUri());
    628                     photoBytes = contact.getPhotoBytes();
    629                 }
    630 
    631                 Bitmap photo;
    632                 if (photoBytes != null) {
    633                     photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
    634                 } else {
    635                     // TODO: can the scaled down default photo be cached?
    636                     photo = mDefaultContactPhoto;
    637                 }
    638                 // Draw the photo on the left side.
    639                 if (photo != null) {
    640                     RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
    641                     Rect backgroundPadding = new Rect();
    642                     mChipBackground.getPadding(backgroundPadding);
    643                     RectF dst = new RectF(width - iconWidth + backgroundPadding.left,
    644                             0 + backgroundPadding.top,
    645                             width - backgroundPadding.right,
    646                             height - backgroundPadding.bottom);
    647                     Matrix matrix = new Matrix();
    648                     matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
    649                     canvas.drawBitmap(photo, matrix, paint);
    650                 }
    651             } else if (!leaveBlankIconSpacer || isPhoneQuery()) {
    652                 iconWidth = 0;
    653             }
    654             paint.setColor(getContext().getResources().getColor(android.R.color.black));
    655             // Vertically center the text in the chip.
    656             canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
    657                     getTextYOffset((String)ellipsizedText, paint, height), paint);
    658         } else {
    659             Log.w(TAG, "Unable to draw a background for the chips as it was never set");
    660         }
    661         return tmpBitmap;
    662     }
    663 
    664     /**
    665      * Get the background drawable for a RecipientChip.
    666      */
    667     // Visible for testing.
    668     /* package */Drawable getChipBackground(RecipientEntry contact) {
    669         return contact.isValid() ? mChipBackground : mInvalidChipBackground;
    670     }
    671 
    672     private static float getTextYOffset(String text, TextPaint paint, int height) {
    673         Rect bounds = new Rect();
    674         paint.getTextBounds(text, 0, text.length(), bounds);
    675         int textHeight = bounds.bottom - bounds.top ;
    676         return height - ((height - textHeight) / 2) - (int)paint.descent();
    677     }
    678 
    679     private DrawableRecipientChip constructChipSpan(RecipientEntry contact, boolean pressed,
    680             boolean leaveIconSpace) throws NullPointerException {
    681         if (mChipBackground == null) {
    682             throw new NullPointerException(
    683                     "Unable to render any chips as setChipDimensions was not called.");
    684         }
    685 
    686         TextPaint paint = getPaint();
    687         float defaultSize = paint.getTextSize();
    688         int defaultColor = paint.getColor();
    689 
    690         Bitmap tmpBitmap;
    691         if (pressed) {
    692             tmpBitmap = createSelectedChip(contact, paint);
    693 
    694         } else {
    695             tmpBitmap = createUnselectedChip(contact, paint, leaveIconSpace);
    696         }
    697 
    698         // Pass the full text, un-ellipsized, to the chip.
    699         Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
    700         result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
    701         DrawableRecipientChip recipientChip = new VisibleRecipientChip(result, contact);
    702         // Return text to the original size.
    703         paint.setTextSize(defaultSize);
    704         paint.setColor(defaultColor);
    705         return recipientChip;
    706     }
    707 
    708     /**
    709      * Calculate the bottom of the line the chip will be located on using:
    710      * 1) which line the chip appears on
    711      * 2) the height of a chip
    712      * 3) padding built into the edit text view
    713      */
    714     private int calculateOffsetFromBottom(int line) {
    715         // Line offsets start at zero.
    716         int actualLine = getLineCount() - (line + 1);
    717         return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
    718                 + getDropDownVerticalOffset();
    719     }
    720 
    721     /**
    722      * Get the max amount of space a chip can take up. The formula takes into
    723      * account the width of the EditTextView, any view padding, and padding
    724      * that will be added to the chip.
    725      */
    726     private float calculateAvailableWidth() {
    727         return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
    728     }
    729 
    730 
    731     private void setChipDimensions(Context context, AttributeSet attrs) {
    732         TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
    733                 0);
    734         Resources r = getContext().getResources();
    735 
    736         mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
    737         if (mChipBackground == null) {
    738             mChipBackground = r.getDrawable(R.drawable.chip_background);
    739         }
    740         mChipBackgroundPressed = a
    741                 .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed);
    742         if (mChipBackgroundPressed == null) {
    743             mChipBackgroundPressed = r.getDrawable(R.drawable.chip_background_selected);
    744         }
    745         mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
    746         if (mChipDelete == null) {
    747             mChipDelete = r.getDrawable(R.drawable.chip_delete);
    748         }
    749         mChipPadding = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
    750         if (mChipPadding == -1) {
    751             mChipPadding = (int) r.getDimension(R.dimen.chip_padding);
    752         }
    753         mAlternatesLayout = a.getResourceId(R.styleable.RecipientEditTextView_chipAlternatesLayout,
    754                 -1);
    755         if (mAlternatesLayout == -1) {
    756             mAlternatesLayout = R.layout.chips_alternate_item;
    757         }
    758 
    759         mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
    760 
    761         mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
    762 
    763         mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
    764         if (mChipHeight == -1) {
    765             mChipHeight = r.getDimension(R.dimen.chip_height);
    766         }
    767         mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
    768         if (mChipFontSize == -1) {
    769             mChipFontSize = r.getDimension(R.dimen.chip_text_size);
    770         }
    771         mInvalidChipBackground = a
    772                 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
    773         if (mInvalidChipBackground == null) {
    774             mInvalidChipBackground = r.getDrawable(R.drawable.chip_background_invalid);
    775         }
    776         mLineSpacingExtra =  r.getDimension(R.dimen.line_spacing_extra);
    777         mMaxLines = r.getInteger(R.integer.chips_max_lines);
    778         TypedValue tv = new TypedValue();
    779         if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    780             mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources()
    781                     .getDisplayMetrics());
    782         }
    783         a.recycle();
    784     }
    785 
    786     // Visible for testing.
    787     /* package */ void setMoreItem(TextView moreItem) {
    788         mMoreItem = moreItem;
    789     }
    790 
    791 
    792     // Visible for testing.
    793     /* package */ void setChipBackground(Drawable chipBackground) {
    794         mChipBackground = chipBackground;
    795     }
    796 
    797     // Visible for testing.
    798     /* package */ void setChipHeight(int height) {
    799         mChipHeight = height;
    800     }
    801 
    802     /**
    803      * Set whether to shrink the recipients field such that at most
    804      * one line of recipients chips are shown when the field loses
    805      * focus. By default, the number of displayed recipients will be
    806      * limited and a "more" chip will be shown when focus is lost.
    807      * @param shrink
    808      */
    809     public void setOnFocusListShrinkRecipients(boolean shrink) {
    810         mShouldShrink = shrink;
    811     }
    812 
    813     @Override
    814     public void onSizeChanged(int width, int height, int oldw, int oldh) {
    815         super.onSizeChanged(width, height, oldw, oldh);
    816         if (width != 0 && height != 0) {
    817             if (mPendingChipsCount > 0) {
    818                 postHandlePendingChips();
    819             } else {
    820                 checkChipWidths();
    821             }
    822         }
    823         // Try to find the scroll view parent, if it exists.
    824         if (mScrollView == null && !mTriedGettingScrollView) {
    825             ViewParent parent = getParent();
    826             while (parent != null && !(parent instanceof ScrollView)) {
    827                 parent = parent.getParent();
    828             }
    829             if (parent != null) {
    830                 mScrollView = (ScrollView) parent;
    831             }
    832             mTriedGettingScrollView = true;
    833         }
    834     }
    835 
    836     private void postHandlePendingChips() {
    837         mHandler.removeCallbacks(mHandlePendingChips);
    838         mHandler.post(mHandlePendingChips);
    839     }
    840 
    841     private void checkChipWidths() {
    842         // Check the widths of the associated chips.
    843         DrawableRecipientChip[] chips = getSortedRecipients();
    844         if (chips != null) {
    845             Rect bounds;
    846             for (DrawableRecipientChip chip : chips) {
    847                 bounds = chip.getBounds();
    848                 if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) {
    849                     // Need to redraw that chip.
    850                     replaceChip(chip, chip.getEntry());
    851                 }
    852             }
    853         }
    854     }
    855 
    856     // Visible for testing.
    857     /*package*/ void handlePendingChips() {
    858         if (getViewWidth() <= 0) {
    859             // The widget has not been sized yet.
    860             // This will be called as a result of onSizeChanged
    861             // at a later point.
    862             return;
    863         }
    864         if (mPendingChipsCount <= 0) {
    865             return;
    866         }
    867 
    868         synchronized (mPendingChips) {
    869             Editable editable = getText();
    870             // Tokenize!
    871             if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
    872                 for (int i = 0; i < mPendingChips.size(); i++) {
    873                     String current = mPendingChips.get(i);
    874                     int tokenStart = editable.toString().indexOf(current);
    875                     // Always leave a space at the end between tokens.
    876                     int tokenEnd = tokenStart + current.length() - 1;
    877                     if (tokenStart >= 0) {
    878                         // When we have a valid token, include it with the token
    879                         // to the left.
    880                         if (tokenEnd < editable.length() - 2
    881                                 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
    882                             tokenEnd++;
    883                         }
    884                         createReplacementChip(tokenStart, tokenEnd, editable, i < CHIP_LIMIT
    885                                 || !mShouldShrink);
    886                     }
    887                     mPendingChipsCount--;
    888                 }
    889                 sanitizeEnd();
    890             } else {
    891                 mNoChips = true;
    892             }
    893 
    894             if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
    895                     && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
    896                 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
    897                     new RecipientReplacementTask().execute();
    898                     mTemporaryRecipients = null;
    899                 } else {
    900                     // Create the "more" chip
    901                     mIndividualReplacements = new IndividualReplacementTask();
    902                     mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(
    903                             mTemporaryRecipients.subList(0, CHIP_LIMIT)));
    904                     if (mTemporaryRecipients.size() > CHIP_LIMIT) {
    905                         mTemporaryRecipients = new ArrayList<DrawableRecipientChip>(
    906                                 mTemporaryRecipients.subList(CHIP_LIMIT,
    907                                         mTemporaryRecipients.size()));
    908                     } else {
    909                         mTemporaryRecipients = null;
    910                     }
    911                     createMoreChip();
    912                 }
    913             } else {
    914                 // There are too many recipients to look up, so just fall back
    915                 // to showing addresses for all of them.
    916                 mTemporaryRecipients = null;
    917                 createMoreChip();
    918             }
    919             mPendingChipsCount = 0;
    920             mPendingChips.clear();
    921         }
    922     }
    923 
    924     // Visible for testing.
    925     /*package*/ int getViewWidth() {
    926         return getWidth();
    927     }
    928 
    929     /**
    930      * Remove any characters after the last valid chip.
    931      */
    932     // Visible for testing.
    933     /*package*/ void sanitizeEnd() {
    934         // Don't sanitize while we are waiting for pending chips to complete.
    935         if (mPendingChipsCount > 0) {
    936             return;
    937         }
    938         // Find the last chip; eliminate any commit characters after it.
    939         DrawableRecipientChip[] chips = getSortedRecipients();
    940         Spannable spannable = getSpannable();
    941         if (chips != null && chips.length > 0) {
    942             int end;
    943             mMoreChip = getMoreChip();
    944             if (mMoreChip != null) {
    945                 end = spannable.getSpanEnd(mMoreChip);
    946             } else {
    947                 end = getSpannable().getSpanEnd(getLastChip());
    948             }
    949             Editable editable = getText();
    950             int length = editable.length();
    951             if (length > end) {
    952                 // See what characters occur after that and eliminate them.
    953                 if (Log.isLoggable(TAG, Log.DEBUG)) {
    954                     Log.d(TAG, "There were extra characters after the last tokenizable entry."
    955                             + editable);
    956                 }
    957                 editable.delete(end + 1, length);
    958             }
    959         }
    960     }
    961 
    962     /**
    963      * Create a chip that represents just the email address of a recipient. At some later
    964      * point, this chip will be attached to a real contact entry, if one exists.
    965      */
    966     // VisibleForTesting
    967     void createReplacementChip(int tokenStart, int tokenEnd, Editable editable,
    968             boolean visible) {
    969         if (alreadyHasChip(tokenStart, tokenEnd)) {
    970             // There is already a chip present at this location.
    971             // Don't recreate it.
    972             return;
    973         }
    974         String token = editable.toString().substring(tokenStart, tokenEnd);
    975         final String trimmedToken = token.trim();
    976         int commitCharIndex = trimmedToken.lastIndexOf(COMMIT_CHAR_COMMA);
    977         if (commitCharIndex != -1 && commitCharIndex == trimmedToken.length() - 1) {
    978             token = trimmedToken.substring(0, trimmedToken.length() - 1);
    979         }
    980         RecipientEntry entry = createTokenizedEntry(token);
    981         if (entry != null) {
    982             DrawableRecipientChip chip = null;
    983             try {
    984                 if (!mNoChips) {
    985                     /*
    986                      * leave space for the contact icon if this is not just an
    987                      * email address
    988                      */
    989                     boolean leaveSpace = TextUtils.isEmpty(entry.getDisplayName())
    990                             || TextUtils.equals(entry.getDisplayName(),
    991                                     entry.getDestination());
    992                     chip = visible ?
    993                             constructChipSpan(entry, false, leaveSpace)
    994                             : new InvisibleRecipientChip(entry);
    995                 }
    996             } catch (NullPointerException e) {
    997                 Log.e(TAG, e.getMessage(), e);
    998             }
    999             editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   1000             // Add this chip to the list of entries "to replace"
   1001             if (chip != null) {
   1002                 if (mTemporaryRecipients == null) {
   1003                     mTemporaryRecipients = new ArrayList<DrawableRecipientChip>();
   1004                 }
   1005                 chip.setOriginalText(token);
   1006                 mTemporaryRecipients.add(chip);
   1007             }
   1008         }
   1009     }
   1010 
   1011     private static boolean isPhoneNumber(String number) {
   1012         // TODO: replace this function with libphonenumber's isPossibleNumber (see
   1013         // PhoneNumberUtil). One complication is that it requires the sender's region which
   1014         // comes from the CurrentCountryIso. For now, let's just do this simple match.
   1015         if (TextUtils.isEmpty(number)) {
   1016             return false;
   1017         }
   1018 
   1019         Matcher match = PHONE_PATTERN.matcher(number);
   1020         return match.matches();
   1021     }
   1022 
   1023     // VisibleForTesting
   1024     RecipientEntry createTokenizedEntry(final String token) {
   1025         if (TextUtils.isEmpty(token)) {
   1026             return null;
   1027         }
   1028         if (isPhoneQuery() && isPhoneNumber(token)) {
   1029             return RecipientEntry.constructFakePhoneEntry(token, true);
   1030         }
   1031         Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
   1032         String display = null;
   1033         boolean isValid = isValid(token);
   1034         if (isValid && tokens != null && tokens.length > 0) {
   1035             // If we can get a name from tokenizing, then generate an entry from
   1036             // this.
   1037             display = tokens[0].getName();
   1038             if (!TextUtils.isEmpty(display)) {
   1039                 return RecipientEntry.constructGeneratedEntry(display, tokens[0].getAddress(),
   1040                         isValid);
   1041             } else {
   1042                 display = tokens[0].getAddress();
   1043                 if (!TextUtils.isEmpty(display)) {
   1044                     return RecipientEntry.constructFakeEntry(display, isValid);
   1045                 }
   1046             }
   1047         }
   1048         // Unable to validate the token or to create a valid token from it.
   1049         // Just create a chip the user can edit.
   1050         String validatedToken = null;
   1051         if (mValidator != null && !isValid) {
   1052             // Try fixing up the entry using the validator.
   1053             validatedToken = mValidator.fixText(token).toString();
   1054             if (!TextUtils.isEmpty(validatedToken)) {
   1055                 if (validatedToken.contains(token)) {
   1056                     // protect against the case of a validator with a null
   1057                     // domain,
   1058                     // which doesn't add a domain to the token
   1059                     Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
   1060                     if (tokenized.length > 0) {
   1061                         validatedToken = tokenized[0].getAddress();
   1062                         isValid = true;
   1063                     }
   1064                 } else {
   1065                     // We ran into a case where the token was invalid and
   1066                     // removed
   1067                     // by the validator. In this case, just use the original
   1068                     // token
   1069                     // and let the user sort out the error chip.
   1070                     validatedToken = null;
   1071                     isValid = false;
   1072                 }
   1073             }
   1074         }
   1075         // Otherwise, fallback to just creating an editable email address chip.
   1076         return RecipientEntry.constructFakeEntry(
   1077                 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid);
   1078     }
   1079 
   1080     private boolean isValid(String text) {
   1081         return mValidator == null ? true : mValidator.isValid(text);
   1082     }
   1083 
   1084     private static String tokenizeAddress(String destination) {
   1085         Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
   1086         if (tokens != null && tokens.length > 0) {
   1087             return tokens[0].getAddress();
   1088         }
   1089         return destination;
   1090     }
   1091 
   1092     @Override
   1093     public void setTokenizer(Tokenizer tokenizer) {
   1094         mTokenizer = tokenizer;
   1095         super.setTokenizer(mTokenizer);
   1096     }
   1097 
   1098     @Override
   1099     public void setValidator(Validator validator) {
   1100         mValidator = validator;
   1101         super.setValidator(validator);
   1102     }
   1103 
   1104     /**
   1105      * We cannot use the default mechanism for replaceText. Instead,
   1106      * we override onItemClickListener so we can get all the associated
   1107      * contact information including display text, address, and id.
   1108      */
   1109     @Override
   1110     protected void replaceText(CharSequence text) {
   1111         return;
   1112     }
   1113 
   1114     /**
   1115      * Dismiss any selected chips when the back key is pressed.
   1116      */
   1117     @Override
   1118     public boolean onKeyPreIme(int keyCode, KeyEvent event) {
   1119         if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) {
   1120             clearSelectedChip();
   1121             return true;
   1122         }
   1123         return super.onKeyPreIme(keyCode, event);
   1124     }
   1125 
   1126     /**
   1127      * Monitor key presses in this view to see if the user types
   1128      * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
   1129      * If the user has entered text that has contact matches and types
   1130      * a commit key, create a chip from the topmost matching contact.
   1131      * If the user has entered text that has no contact matches and types
   1132      * a commit key, then create a chip from the text they have entered.
   1133      */
   1134     @Override
   1135     public boolean onKeyUp(int keyCode, KeyEvent event) {
   1136         switch (keyCode) {
   1137             case KeyEvent.KEYCODE_TAB:
   1138                 if (event.hasNoModifiers()) {
   1139                     if (mSelectedChip != null) {
   1140                         clearSelectedChip();
   1141                     } else {
   1142                         commitDefault();
   1143                     }
   1144                 }
   1145                 break;
   1146         }
   1147         return super.onKeyUp(keyCode, event);
   1148     }
   1149 
   1150     private boolean focusNext() {
   1151         View next = focusSearch(View.FOCUS_DOWN);
   1152         if (next != null) {
   1153             next.requestFocus();
   1154             return true;
   1155         }
   1156         return false;
   1157     }
   1158 
   1159     /**
   1160      * Create a chip from the default selection. If the popup is showing, the
   1161      * default is the first item in the popup suggestions list. Otherwise, it is
   1162      * whatever the user had typed in. End represents where the the tokenizer
   1163      * should search for a token to turn into a chip.
   1164      * @return If a chip was created from a real contact.
   1165      */
   1166     private boolean commitDefault() {
   1167         // If there is no tokenizer, don't try to commit.
   1168         if (mTokenizer == null) {
   1169             return false;
   1170         }
   1171         Editable editable = getText();
   1172         int end = getSelectionEnd();
   1173         int start = mTokenizer.findTokenStart(editable, end);
   1174 
   1175         if (shouldCreateChip(start, end)) {
   1176             int whatEnd = mTokenizer.findTokenEnd(getText(), start);
   1177             // In the middle of chip; treat this as an edit
   1178             // and commit the whole token.
   1179             whatEnd = movePastTerminators(whatEnd);
   1180             if (whatEnd != getSelectionEnd()) {
   1181                 handleEdit(start, whatEnd);
   1182                 return true;
   1183             }
   1184             return commitChip(start, end , editable);
   1185         }
   1186         return false;
   1187     }
   1188 
   1189     private void commitByCharacter() {
   1190         // We can't possibly commit by character if we can't tokenize.
   1191         if (mTokenizer == null) {
   1192             return;
   1193         }
   1194         Editable editable = getText();
   1195         int end = getSelectionEnd();
   1196         int start = mTokenizer.findTokenStart(editable, end);
   1197         if (shouldCreateChip(start, end)) {
   1198             commitChip(start, end, editable);
   1199         }
   1200         setSelection(getText().length());
   1201     }
   1202 
   1203     private boolean commitChip(int start, int end, Editable editable) {
   1204         ListAdapter adapter = getAdapter();
   1205         if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
   1206                 && end == getSelectionEnd() && !isPhoneQuery()) {
   1207             // choose the first entry.
   1208             submitItemAtPosition(0);
   1209             dismissDropDown();
   1210             return true;
   1211         } else {
   1212             int tokenEnd = mTokenizer.findTokenEnd(editable, start);
   1213             if (editable.length() > tokenEnd + 1) {
   1214                 char charAt = editable.charAt(tokenEnd + 1);
   1215                 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
   1216                     tokenEnd++;
   1217                 }
   1218             }
   1219             String text = editable.toString().substring(start, tokenEnd).trim();
   1220             clearComposingText();
   1221             if (text != null && text.length() > 0 && !text.equals(" ")) {
   1222                 RecipientEntry entry = createTokenizedEntry(text);
   1223                 if (entry != null) {
   1224                     QwertyKeyListener.markAsReplaced(editable, start, end, "");
   1225                     CharSequence chipText = createChip(entry, false);
   1226                     if (chipText != null && start > -1 && end > -1) {
   1227                         editable.replace(start, end, chipText);
   1228                     }
   1229                 }
   1230                 // Only dismiss the dropdown if it is related to the text we
   1231                 // just committed.
   1232                 // For paste, it may not be as there are possibly multiple
   1233                 // tokens being added.
   1234                 if (end == getSelectionEnd()) {
   1235                     dismissDropDown();
   1236                 }
   1237                 sanitizeBetween();
   1238                 return true;
   1239             }
   1240         }
   1241         return false;
   1242     }
   1243 
   1244     // Visible for testing.
   1245     /* package */ void sanitizeBetween() {
   1246         // Don't sanitize while we are waiting for content to chipify.
   1247         if (mPendingChipsCount > 0) {
   1248             return;
   1249         }
   1250         // Find the last chip.
   1251         DrawableRecipientChip[] recips = getSortedRecipients();
   1252         if (recips != null && recips.length > 0) {
   1253             DrawableRecipientChip last = recips[recips.length - 1];
   1254             DrawableRecipientChip beforeLast = null;
   1255             if (recips.length > 1) {
   1256                 beforeLast = recips[recips.length - 2];
   1257             }
   1258             int startLooking = 0;
   1259             int end = getSpannable().getSpanStart(last);
   1260             if (beforeLast != null) {
   1261                 startLooking = getSpannable().getSpanEnd(beforeLast);
   1262                 Editable text = getText();
   1263                 if (startLooking == -1 || startLooking > text.length() - 1) {
   1264                     // There is nothing after this chip.
   1265                     return;
   1266                 }
   1267                 if (text.charAt(startLooking) == ' ') {
   1268                     startLooking++;
   1269                 }
   1270             }
   1271             if (startLooking >= 0 && end >= 0 && startLooking < end) {
   1272                 getText().delete(startLooking, end);
   1273             }
   1274         }
   1275     }
   1276 
   1277     private boolean shouldCreateChip(int start, int end) {
   1278         return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
   1279     }
   1280 
   1281     private boolean alreadyHasChip(int start, int end) {
   1282         if (mNoChips) {
   1283             return true;
   1284         }
   1285         DrawableRecipientChip[] chips =
   1286                 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
   1287         if ((chips == null || chips.length == 0)) {
   1288             return false;
   1289         }
   1290         return true;
   1291     }
   1292 
   1293     private void handleEdit(int start, int end) {
   1294         if (start == -1 || end == -1) {
   1295             // This chip no longer exists in the field.
   1296             dismissDropDown();
   1297             return;
   1298         }
   1299         // This is in the middle of a chip, so select out the whole chip
   1300         // and commit it.
   1301         Editable editable = getText();
   1302         setSelection(end);
   1303         String text = getText().toString().substring(start, end);
   1304         if (!TextUtils.isEmpty(text)) {
   1305             RecipientEntry entry = RecipientEntry.constructFakeEntry(text, isValid(text));
   1306             QwertyKeyListener.markAsReplaced(editable, start, end, "");
   1307             CharSequence chipText = createChip(entry, false);
   1308             int selEnd = getSelectionEnd();
   1309             if (chipText != null && start > -1 && selEnd > -1) {
   1310                 editable.replace(start, selEnd, chipText);
   1311             }
   1312         }
   1313         dismissDropDown();
   1314     }
   1315 
   1316     /**
   1317      * If there is a selected chip, delegate the key events
   1318      * to the selected chip.
   1319      */
   1320     @Override
   1321     public boolean onKeyDown(int keyCode, KeyEvent event) {
   1322         if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
   1323             if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
   1324                 mAlternatesPopup.dismiss();
   1325             }
   1326             removeChip(mSelectedChip);
   1327         }
   1328 
   1329         switch (keyCode) {
   1330             case KeyEvent.KEYCODE_ENTER:
   1331             case KeyEvent.KEYCODE_DPAD_CENTER:
   1332                 if (event.hasNoModifiers()) {
   1333                     if (commitDefault()) {
   1334                         return true;
   1335                     }
   1336                     if (mSelectedChip != null) {
   1337                         clearSelectedChip();
   1338                         return true;
   1339                     } else if (focusNext()) {
   1340                         return true;
   1341                     }
   1342                 }
   1343                 break;
   1344         }
   1345 
   1346         return super.onKeyDown(keyCode, event);
   1347     }
   1348 
   1349     // Visible for testing.
   1350     /* package */ Spannable getSpannable() {
   1351         return getText();
   1352     }
   1353 
   1354     private int getChipStart(DrawableRecipientChip chip) {
   1355         return getSpannable().getSpanStart(chip);
   1356     }
   1357 
   1358     private int getChipEnd(DrawableRecipientChip chip) {
   1359         return getSpannable().getSpanEnd(chip);
   1360     }
   1361 
   1362     /**
   1363      * Instead of filtering on the entire contents of the edit box,
   1364      * this subclass method filters on the range from
   1365      * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
   1366      * if the length of that range meets or exceeds {@link #getThreshold}
   1367      * and makes sure that the range is not already a Chip.
   1368      */
   1369     @Override
   1370     protected void performFiltering(CharSequence text, int keyCode) {
   1371         boolean isCompletedToken = isCompletedToken(text);
   1372         if (enoughToFilter() && !isCompletedToken) {
   1373             int end = getSelectionEnd();
   1374             int start = mTokenizer.findTokenStart(text, end);
   1375             // If this is a RecipientChip, don't filter
   1376             // on its contents.
   1377             Spannable span = getSpannable();
   1378             DrawableRecipientChip[] chips = span.getSpans(start, end, DrawableRecipientChip.class);
   1379             if (chips != null && chips.length > 0) {
   1380                 return;
   1381             }
   1382         } else if (isCompletedToken) {
   1383             return;
   1384         }
   1385         super.performFiltering(text, keyCode);
   1386     }
   1387 
   1388     // Visible for testing.
   1389     /*package*/ boolean isCompletedToken(CharSequence text) {
   1390         if (TextUtils.isEmpty(text)) {
   1391             return false;
   1392         }
   1393         // Check to see if this is a completed token before filtering.
   1394         int end = text.length();
   1395         int start = mTokenizer.findTokenStart(text, end);
   1396         String token = text.toString().substring(start, end).trim();
   1397         if (!TextUtils.isEmpty(token)) {
   1398             char atEnd = token.charAt(token.length() - 1);
   1399             return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
   1400         }
   1401         return false;
   1402     }
   1403 
   1404     private void clearSelectedChip() {
   1405         if (mSelectedChip != null) {
   1406             unselectChip(mSelectedChip);
   1407             mSelectedChip = null;
   1408         }
   1409         setCursorVisible(true);
   1410     }
   1411 
   1412     /**
   1413      * Monitor touch events in the RecipientEditTextView.
   1414      * If the view does not have focus, any tap on the view
   1415      * will just focus the view. If the view has focus, determine
   1416      * if the touch target is a recipient chip. If it is and the chip
   1417      * is not selected, select it and clear any other selected chips.
   1418      * If it isn't, then select that chip.
   1419      */
   1420     @Override
   1421     public boolean onTouchEvent(MotionEvent event) {
   1422         if (!isFocused()) {
   1423             // Ignore any chip taps until this view is focused.
   1424             return super.onTouchEvent(event);
   1425         }
   1426         boolean handled = super.onTouchEvent(event);
   1427         int action = event.getAction();
   1428         boolean chipWasSelected = false;
   1429         if (mSelectedChip == null) {
   1430             mGestureDetector.onTouchEvent(event);
   1431         }
   1432         if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
   1433             float x = event.getX();
   1434             float y = event.getY();
   1435             int offset = putOffsetInRange(x, y);
   1436             DrawableRecipientChip currentChip = findChip(offset);
   1437             if (currentChip != null) {
   1438                 if (action == MotionEvent.ACTION_UP) {
   1439                     if (mSelectedChip != null && mSelectedChip != currentChip) {
   1440                         clearSelectedChip();
   1441                         mSelectedChip = selectChip(currentChip);
   1442                     } else if (mSelectedChip == null) {
   1443                         setSelection(getText().length());
   1444                         commitDefault();
   1445                         mSelectedChip = selectChip(currentChip);
   1446                     } else {
   1447                         onClick(mSelectedChip, offset, x, y);
   1448                     }
   1449                 }
   1450                 chipWasSelected = true;
   1451                 handled = true;
   1452             } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
   1453                 chipWasSelected = true;
   1454             }
   1455         }
   1456         if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
   1457             clearSelectedChip();
   1458         }
   1459         return handled;
   1460     }
   1461 
   1462     private void scrollLineIntoView(int line) {
   1463         if (mScrollView != null) {
   1464             mScrollView.smoothScrollBy(0, calculateOffsetFromBottom(line));
   1465         }
   1466     }
   1467 
   1468     private void showAlternates(final DrawableRecipientChip currentChip,
   1469             final ListPopupWindow alternatesPopup, final int width) {
   1470         new AsyncTask<Void, Void, ListAdapter>() {
   1471             @Override
   1472             protected ListAdapter doInBackground(final Void... params) {
   1473                 return createAlternatesAdapter(currentChip);
   1474             }
   1475 
   1476             @Override
   1477             protected void onPostExecute(final ListAdapter result) {
   1478                 if (!mAttachedToWindow) {
   1479                     return;
   1480                 }
   1481                 int line = getLayout().getLineForOffset(getChipStart(currentChip));
   1482                 int bottom;
   1483                 if (line == getLineCount() -1) {
   1484                     bottom = 0;
   1485                 } else {
   1486                     bottom = -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math
   1487                             .abs(getLineCount() - 1 - line)));
   1488                 }
   1489                 // Align the alternates popup with the left side of the View,
   1490                 // regardless of the position of the chip tapped.
   1491                 alternatesPopup.setWidth(width);
   1492                 alternatesPopup.setAnchorView(RecipientEditTextView.this);
   1493                 alternatesPopup.setVerticalOffset(bottom);
   1494                 alternatesPopup.setAdapter(result);
   1495                 alternatesPopup.setOnItemClickListener(mAlternatesListener);
   1496                 // Clear the checked item.
   1497                 mCheckedItem = -1;
   1498                 alternatesPopup.show();
   1499                 ListView listView = alternatesPopup.getListView();
   1500                 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
   1501                 // Checked item would be -1 if the adapter has not
   1502                 // loaded the view that should be checked yet. The
   1503                 // variable will be set correctly when onCheckedItemChanged
   1504                 // is called in a separate thread.
   1505                 if (mCheckedItem != -1) {
   1506                     listView.setItemChecked(mCheckedItem, true);
   1507                     mCheckedItem = -1;
   1508                 }
   1509             }
   1510         }.execute((Void[]) null);
   1511     }
   1512 
   1513     private ListAdapter createAlternatesAdapter(DrawableRecipientChip chip) {
   1514         return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
   1515                 ((BaseRecipientAdapter)getAdapter()).getQueryType(), this);
   1516     }
   1517 
   1518     private ListAdapter createSingleAddressAdapter(DrawableRecipientChip currentChip) {
   1519         return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
   1520                 .getEntry());
   1521     }
   1522 
   1523     @Override
   1524     public void onCheckedItemChanged(int position) {
   1525         ListView listView = mAlternatesPopup.getListView();
   1526         if (listView != null && listView.getCheckedItemCount() == 0) {
   1527             listView.setItemChecked(position, true);
   1528         }
   1529         mCheckedItem = position;
   1530     }
   1531 
   1532     private int putOffsetInRange(final float x, final float y) {
   1533         final int offset;
   1534 
   1535         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
   1536             offset = getOffsetForPosition(x, y);
   1537         } else {
   1538             offset = supportGetOffsetForPosition(x, y);
   1539         }
   1540 
   1541         return putOffsetInRange(offset);
   1542     }
   1543 
   1544     // TODO: This algorithm will need a lot of tweaking after more people have used
   1545     // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
   1546     // what comes before the finger.
   1547     private int putOffsetInRange(int o) {
   1548         int offset = o;
   1549         Editable text = getText();
   1550         int length = text.length();
   1551         // Remove whitespace from end to find "real end"
   1552         int realLength = length;
   1553         for (int i = length - 1; i >= 0; i--) {
   1554             if (text.charAt(i) == ' ') {
   1555                 realLength--;
   1556             } else {
   1557                 break;
   1558             }
   1559         }
   1560 
   1561         // If the offset is beyond or at the end of the text,
   1562         // leave it alone.
   1563         if (offset >= realLength) {
   1564             return offset;
   1565         }
   1566         Editable editable = getText();
   1567         while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
   1568             // Keep walking backward!
   1569             offset--;
   1570         }
   1571         return offset;
   1572     }
   1573 
   1574     private static int findText(Editable text, int offset) {
   1575         if (text.charAt(offset) != ' ') {
   1576             return offset;
   1577         }
   1578         return -1;
   1579     }
   1580 
   1581     private DrawableRecipientChip findChip(int offset) {
   1582         DrawableRecipientChip[] chips =
   1583                 getSpannable().getSpans(0, getText().length(), DrawableRecipientChip.class);
   1584         // Find the chip that contains this offset.
   1585         for (int i = 0; i < chips.length; i++) {
   1586             DrawableRecipientChip chip = chips[i];
   1587             int start = getChipStart(chip);
   1588             int end = getChipEnd(chip);
   1589             if (offset >= start && offset <= end) {
   1590                 return chip;
   1591             }
   1592         }
   1593         return null;
   1594     }
   1595 
   1596     // Visible for testing.
   1597     // Use this method to generate text to add to the list of addresses.
   1598     /* package */String createAddressText(RecipientEntry entry) {
   1599         String display = entry.getDisplayName();
   1600         String address = entry.getDestination();
   1601         if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
   1602             display = null;
   1603         }
   1604         String trimmedDisplayText;
   1605         if (isPhoneQuery() && isPhoneNumber(address)) {
   1606             trimmedDisplayText = address.trim();
   1607         } else {
   1608             if (address != null) {
   1609                 // Tokenize out the address in case the address already
   1610                 // contained the username as well.
   1611                 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
   1612                 if (tokenized != null && tokenized.length > 0) {
   1613                     address = tokenized[0].getAddress();
   1614                 }
   1615             }
   1616             Rfc822Token token = new Rfc822Token(display, address, null);
   1617             trimmedDisplayText = token.toString().trim();
   1618         }
   1619         int index = trimmedDisplayText.indexOf(",");
   1620         return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
   1621                 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
   1622                 .terminateToken(trimmedDisplayText) : trimmedDisplayText;
   1623     }
   1624 
   1625     // Visible for testing.
   1626     // Use this method to generate text to display in a chip.
   1627     /*package*/ String createChipDisplayText(RecipientEntry entry) {
   1628         String display = entry.getDisplayName();
   1629         String address = entry.getDestination();
   1630         if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
   1631             display = null;
   1632         }
   1633         if (!TextUtils.isEmpty(display)) {
   1634             return display;
   1635         } else if (!TextUtils.isEmpty(address)){
   1636             return address;
   1637         } else {
   1638             return new Rfc822Token(display, address, null).toString();
   1639         }
   1640     }
   1641 
   1642     private CharSequence createChip(RecipientEntry entry, boolean pressed) {
   1643         String displayText = createAddressText(entry);
   1644         if (TextUtils.isEmpty(displayText)) {
   1645             return null;
   1646         }
   1647         SpannableString chipText = null;
   1648         // Always leave a blank space at the end of a chip.
   1649         int textLength = displayText.length() - 1;
   1650         chipText = new SpannableString(displayText);
   1651         if (!mNoChips) {
   1652             try {
   1653                 DrawableRecipientChip chip = constructChipSpan(entry, pressed,
   1654                         false /* leave space for contact icon */);
   1655                 chipText.setSpan(chip, 0, textLength,
   1656                         Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   1657                 chip.setOriginalText(chipText.toString());
   1658             } catch (NullPointerException e) {
   1659                 Log.e(TAG, e.getMessage(), e);
   1660                 return null;
   1661             }
   1662         }
   1663         return chipText;
   1664     }
   1665 
   1666     /**
   1667      * When an item in the suggestions list has been clicked, create a chip from the
   1668      * contact information of the selected item.
   1669      */
   1670     @Override
   1671     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   1672         if (position < 0) {
   1673             return;
   1674         }
   1675         submitItemAtPosition(position);
   1676     }
   1677 
   1678     private void submitItemAtPosition(int position) {
   1679         RecipientEntry entry = createValidatedEntry(
   1680                 (RecipientEntry)getAdapter().getItem(position));
   1681         if (entry == null) {
   1682             return;
   1683         }
   1684         clearComposingText();
   1685 
   1686         int end = getSelectionEnd();
   1687         int start = mTokenizer.findTokenStart(getText(), end);
   1688 
   1689         Editable editable = getText();
   1690         QwertyKeyListener.markAsReplaced(editable, start, end, "");
   1691         CharSequence chip = createChip(entry, false);
   1692         if (chip != null && start >= 0 && end >= 0) {
   1693             editable.replace(start, end, chip);
   1694         }
   1695         sanitizeBetween();
   1696     }
   1697 
   1698     private RecipientEntry createValidatedEntry(RecipientEntry item) {
   1699         if (item == null) {
   1700             return null;
   1701         }
   1702         final RecipientEntry entry;
   1703         // If the display name and the address are the same, or if this is a
   1704         // valid contact, but the destination is invalid, then make this a fake
   1705         // recipient that is editable.
   1706         String destination = item.getDestination();
   1707         if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
   1708             entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
   1709                     destination, item.isValid());
   1710         } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
   1711                 && (TextUtils.isEmpty(item.getDisplayName())
   1712                         || TextUtils.equals(item.getDisplayName(), destination)
   1713                         || (mValidator != null && !mValidator.isValid(destination)))) {
   1714             entry = RecipientEntry.constructFakeEntry(destination, item.isValid());
   1715         } else {
   1716             entry = item;
   1717         }
   1718         return entry;
   1719     }
   1720 
   1721     /** Returns a collection of contact Id for each chip inside this View. */
   1722     /* package */ Collection<Long> getContactIds() {
   1723         final Set<Long> result = new HashSet<Long>();
   1724         DrawableRecipientChip[] chips = getSortedRecipients();
   1725         if (chips != null) {
   1726             for (DrawableRecipientChip chip : chips) {
   1727                 result.add(chip.getContactId());
   1728             }
   1729         }
   1730         return result;
   1731     }
   1732 
   1733 
   1734     /** Returns a collection of data Id for each chip inside this View. May be null. */
   1735     /* package */ Collection<Long> getDataIds() {
   1736         final Set<Long> result = new HashSet<Long>();
   1737         DrawableRecipientChip [] chips = getSortedRecipients();
   1738         if (chips != null) {
   1739             for (DrawableRecipientChip chip : chips) {
   1740                 result.add(chip.getDataId());
   1741             }
   1742         }
   1743         return result;
   1744     }
   1745 
   1746     // Visible for testing.
   1747     /* package */DrawableRecipientChip[] getSortedRecipients() {
   1748         DrawableRecipientChip[] recips = getSpannable()
   1749                 .getSpans(0, getText().length(), DrawableRecipientChip.class);
   1750         ArrayList<DrawableRecipientChip> recipientsList = new ArrayList<DrawableRecipientChip>(
   1751                 Arrays.asList(recips));
   1752         final Spannable spannable = getSpannable();
   1753         Collections.sort(recipientsList, new Comparator<DrawableRecipientChip>() {
   1754 
   1755             @Override
   1756             public int compare(DrawableRecipientChip first, DrawableRecipientChip second) {
   1757                 int firstStart = spannable.getSpanStart(first);
   1758                 int secondStart = spannable.getSpanStart(second);
   1759                 if (firstStart < secondStart) {
   1760                     return -1;
   1761                 } else if (firstStart > secondStart) {
   1762                     return 1;
   1763                 } else {
   1764                     return 0;
   1765                 }
   1766             }
   1767         });
   1768         return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
   1769     }
   1770 
   1771     @Override
   1772     public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
   1773         return false;
   1774     }
   1775 
   1776     @Override
   1777     public void onDestroyActionMode(ActionMode mode) {
   1778     }
   1779 
   1780     @Override
   1781     public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
   1782         return false;
   1783     }
   1784 
   1785     /**
   1786      * No chips are selectable.
   1787      */
   1788     @Override
   1789     public boolean onCreateActionMode(ActionMode mode, Menu menu) {
   1790         return false;
   1791     }
   1792 
   1793     // Visible for testing.
   1794     /* package */ImageSpan getMoreChip() {
   1795         MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
   1796                 MoreImageSpan.class);
   1797         return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
   1798     }
   1799 
   1800     private MoreImageSpan createMoreSpan(int count) {
   1801         String moreText = String.format(mMoreItem.getText().toString(), count);
   1802         TextPaint morePaint = new TextPaint(getPaint());
   1803         morePaint.setTextSize(mMoreItem.getTextSize());
   1804         morePaint.setColor(mMoreItem.getCurrentTextColor());
   1805         int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
   1806                 + mMoreItem.getPaddingRight();
   1807         int height = getLineHeight();
   1808         Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
   1809         Canvas canvas = new Canvas(drawable);
   1810         int adjustedHeight = height;
   1811         Layout layout = getLayout();
   1812         if (layout != null) {
   1813             adjustedHeight -= layout.getLineDescent(0);
   1814         }
   1815         canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
   1816 
   1817         Drawable result = new BitmapDrawable(getResources(), drawable);
   1818         result.setBounds(0, 0, width, height);
   1819         return new MoreImageSpan(result);
   1820     }
   1821 
   1822     // Visible for testing.
   1823     /*package*/ void createMoreChipPlainText() {
   1824         // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
   1825         Editable text = getText();
   1826         int start = 0;
   1827         int end = start;
   1828         for (int i = 0; i < CHIP_LIMIT; i++) {
   1829             end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
   1830             start = end; // move to the next token and get its end.
   1831         }
   1832         // Now, count total addresses.
   1833         start = 0;
   1834         int tokenCount = countTokens(text);
   1835         MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
   1836         SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
   1837         chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   1838         text.replace(end, text.length(), chipText);
   1839         mMoreChip = moreSpan;
   1840     }
   1841 
   1842     // Visible for testing.
   1843     /* package */int countTokens(Editable text) {
   1844         int tokenCount = 0;
   1845         int start = 0;
   1846         while (start < text.length()) {
   1847             start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
   1848             tokenCount++;
   1849             if (start >= text.length()) {
   1850                 break;
   1851             }
   1852         }
   1853         return tokenCount;
   1854     }
   1855 
   1856     /**
   1857      * Create the more chip. The more chip is text that replaces any chips that
   1858      * do not fit in the pre-defined available space when the
   1859      * RecipientEditTextView loses focus.
   1860      */
   1861     // Visible for testing.
   1862     /* package */ void createMoreChip() {
   1863         if (mNoChips) {
   1864             createMoreChipPlainText();
   1865             return;
   1866         }
   1867 
   1868         if (!mShouldShrink) {
   1869             return;
   1870         }
   1871         ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
   1872         if (tempMore.length > 0) {
   1873             getSpannable().removeSpan(tempMore[0]);
   1874         }
   1875         DrawableRecipientChip[] recipients = getSortedRecipients();
   1876 
   1877         if (recipients == null || recipients.length <= CHIP_LIMIT) {
   1878             mMoreChip = null;
   1879             return;
   1880         }
   1881         Spannable spannable = getSpannable();
   1882         int numRecipients = recipients.length;
   1883         int overage = numRecipients - CHIP_LIMIT;
   1884         MoreImageSpan moreSpan = createMoreSpan(overage);
   1885         mRemovedSpans = new ArrayList<DrawableRecipientChip>();
   1886         int totalReplaceStart = 0;
   1887         int totalReplaceEnd = 0;
   1888         Editable text = getText();
   1889         for (int i = numRecipients - overage; i < recipients.length; i++) {
   1890             mRemovedSpans.add(recipients[i]);
   1891             if (i == numRecipients - overage) {
   1892                 totalReplaceStart = spannable.getSpanStart(recipients[i]);
   1893             }
   1894             if (i == recipients.length - 1) {
   1895                 totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
   1896             }
   1897             if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
   1898                 int spanStart = spannable.getSpanStart(recipients[i]);
   1899                 int spanEnd = spannable.getSpanEnd(recipients[i]);
   1900                 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
   1901             }
   1902             spannable.removeSpan(recipients[i]);
   1903         }
   1904         if (totalReplaceEnd < text.length()) {
   1905             totalReplaceEnd = text.length();
   1906         }
   1907         int end = Math.max(totalReplaceStart, totalReplaceEnd);
   1908         int start = Math.min(totalReplaceStart, totalReplaceEnd);
   1909         SpannableString chipText = new SpannableString(text.subSequence(start, end));
   1910         chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   1911         text.replace(start, end, chipText);
   1912         mMoreChip = moreSpan;
   1913         // If adding the +more chip goes over the limit, resize accordingly.
   1914         if (!isPhoneQuery() && getLineCount() > mMaxLines) {
   1915             setMaxLines(getLineCount());
   1916         }
   1917     }
   1918 
   1919     /**
   1920      * Replace the more chip, if it exists, with all of the recipient chips it had
   1921      * replaced when the RecipientEditTextView gains focus.
   1922      */
   1923     // Visible for testing.
   1924     /*package*/ void removeMoreChip() {
   1925         if (mMoreChip != null) {
   1926             Spannable span = getSpannable();
   1927             span.removeSpan(mMoreChip);
   1928             mMoreChip = null;
   1929             // Re-add the spans that were removed.
   1930             if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
   1931                 // Recreate each removed span.
   1932                 DrawableRecipientChip[] recipients = getSortedRecipients();
   1933                 // Start the search for tokens after the last currently visible
   1934                 // chip.
   1935                 if (recipients == null || recipients.length == 0) {
   1936                     return;
   1937                 }
   1938                 int end = span.getSpanEnd(recipients[recipients.length - 1]);
   1939                 Editable editable = getText();
   1940                 for (DrawableRecipientChip chip : mRemovedSpans) {
   1941                     int chipStart;
   1942                     int chipEnd;
   1943                     String token;
   1944                     // Need to find the location of the chip, again.
   1945                     token = (String) chip.getOriginalText();
   1946                     // As we find the matching recipient for the remove spans,
   1947                     // reduce the size of the string we need to search.
   1948                     // That way, if there are duplicates, we always find the correct
   1949                     // recipient.
   1950                     chipStart = editable.toString().indexOf(token, end);
   1951                     end = chipEnd = Math.min(editable.length(), chipStart + token.length());
   1952                     // Only set the span if we found a matching token.
   1953                     if (chipStart != -1) {
   1954                         editable.setSpan(chip, chipStart, chipEnd,
   1955                                 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   1956                     }
   1957                 }
   1958                 mRemovedSpans.clear();
   1959             }
   1960         }
   1961     }
   1962 
   1963     /**
   1964      * Show specified chip as selected. If the RecipientChip is just an email address,
   1965      * selecting the chip will take the contents of the chip and place it at
   1966      * the end of the RecipientEditTextView for inline editing. If the
   1967      * RecipientChip is a complete contact, then selecting the chip
   1968      * will change the background color of the chip, show the delete icon,
   1969      * and a popup window with the address in use highlighted and any other
   1970      * alternate addresses for the contact.
   1971      * @param currentChip Chip to select.
   1972      * @return A RecipientChip in the selected state or null if the chip
   1973      * just contained an email address.
   1974      */
   1975     private DrawableRecipientChip selectChip(DrawableRecipientChip currentChip) {
   1976         if (shouldShowEditableText(currentChip)) {
   1977             CharSequence text = currentChip.getValue();
   1978             Editable editable = getText();
   1979             Spannable spannable = getSpannable();
   1980             int spanStart = spannable.getSpanStart(currentChip);
   1981             int spanEnd = spannable.getSpanEnd(currentChip);
   1982             spannable.removeSpan(currentChip);
   1983             editable.delete(spanStart, spanEnd);
   1984             setCursorVisible(true);
   1985             setSelection(editable.length());
   1986             editable.append(text);
   1987             return constructChipSpan(
   1988                     RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())),
   1989                     true, false);
   1990         } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT
   1991                 || currentChip.isGalContact()) {
   1992             int start = getChipStart(currentChip);
   1993             int end = getChipEnd(currentChip);
   1994             getSpannable().removeSpan(currentChip);
   1995             DrawableRecipientChip newChip;
   1996             try {
   1997                 if (mNoChips) {
   1998                     return null;
   1999                 }
   2000                 newChip = constructChipSpan(currentChip.getEntry(), true, false);
   2001             } catch (NullPointerException e) {
   2002                 Log.e(TAG, e.getMessage(), e);
   2003                 return null;
   2004             }
   2005             Editable editable = getText();
   2006             QwertyKeyListener.markAsReplaced(editable, start, end, "");
   2007             if (start == -1 || end == -1) {
   2008                 Log.d(TAG, "The chip being selected no longer exists but should.");
   2009             } else {
   2010                 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   2011             }
   2012             newChip.setSelected(true);
   2013             if (shouldShowEditableText(newChip)) {
   2014                 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
   2015             }
   2016             showAddress(newChip, mAddressPopup, getWidth());
   2017             setCursorVisible(false);
   2018             return newChip;
   2019         } else {
   2020             int start = getChipStart(currentChip);
   2021             int end = getChipEnd(currentChip);
   2022             getSpannable().removeSpan(currentChip);
   2023             DrawableRecipientChip newChip;
   2024             try {
   2025                 newChip = constructChipSpan(currentChip.getEntry(), true, false);
   2026             } catch (NullPointerException e) {
   2027                 Log.e(TAG, e.getMessage(), e);
   2028                 return null;
   2029             }
   2030             Editable editable = getText();
   2031             QwertyKeyListener.markAsReplaced(editable, start, end, "");
   2032             if (start == -1 || end == -1) {
   2033                 Log.d(TAG, "The chip being selected no longer exists but should.");
   2034             } else {
   2035                 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   2036             }
   2037             newChip.setSelected(true);
   2038             if (shouldShowEditableText(newChip)) {
   2039                 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
   2040             }
   2041             showAlternates(newChip, mAlternatesPopup, getWidth());
   2042             setCursorVisible(false);
   2043             return newChip;
   2044         }
   2045     }
   2046 
   2047     private boolean shouldShowEditableText(DrawableRecipientChip currentChip) {
   2048         long contactId = currentChip.getContactId();
   2049         return contactId == RecipientEntry.INVALID_CONTACT
   2050                 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
   2051     }
   2052 
   2053     private void showAddress(final DrawableRecipientChip currentChip, final ListPopupWindow popup,
   2054             int width) {
   2055         if (!mAttachedToWindow) {
   2056             return;
   2057         }
   2058         int line = getLayout().getLineForOffset(getChipStart(currentChip));
   2059         int bottom = calculateOffsetFromBottom(line);
   2060         // Align the alternates popup with the left side of the View,
   2061         // regardless of the position of the chip tapped.
   2062         popup.setWidth(width);
   2063         popup.setAnchorView(this);
   2064         popup.setVerticalOffset(bottom);
   2065         popup.setAdapter(createSingleAddressAdapter(currentChip));
   2066         popup.setOnItemClickListener(new OnItemClickListener() {
   2067             @Override
   2068             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   2069                 unselectChip(currentChip);
   2070                 popup.dismiss();
   2071             }
   2072         });
   2073         popup.show();
   2074         ListView listView = popup.getListView();
   2075         listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
   2076         listView.setItemChecked(0, true);
   2077     }
   2078 
   2079     /**
   2080      * Remove selection from this chip. Unselecting a RecipientChip will render
   2081      * the chip without a delete icon and with an unfocused background. This is
   2082      * called when the RecipientChip no longer has focus.
   2083      */
   2084     private void unselectChip(DrawableRecipientChip chip) {
   2085         int start = getChipStart(chip);
   2086         int end = getChipEnd(chip);
   2087         Editable editable = getText();
   2088         mSelectedChip = null;
   2089         if (start == -1 || end == -1) {
   2090             Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
   2091             setSelection(editable.length());
   2092             commitDefault();
   2093         } else {
   2094             getSpannable().removeSpan(chip);
   2095             QwertyKeyListener.markAsReplaced(editable, start, end, "");
   2096             editable.removeSpan(chip);
   2097             try {
   2098                 if (!mNoChips) {
   2099                     editable.setSpan(constructChipSpan(chip.getEntry(), false, false),
   2100                             start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   2101                 }
   2102             } catch (NullPointerException e) {
   2103                 Log.e(TAG, e.getMessage(), e);
   2104             }
   2105         }
   2106         setCursorVisible(true);
   2107         setSelection(editable.length());
   2108         if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
   2109             mAlternatesPopup.dismiss();
   2110         }
   2111     }
   2112 
   2113     /**
   2114      * Return whether a touch event was inside the delete target of
   2115      * a selected chip. It is in the delete target if:
   2116      * 1) the x and y points of the event are within the
   2117      * delete assset.
   2118      * 2) the point tapped would have caused a cursor to appear
   2119      * right after the selected chip.
   2120      * @return boolean
   2121      */
   2122     private boolean isInDelete(DrawableRecipientChip chip, int offset, float x, float y) {
   2123         // Figure out the bounds of this chip and whether or not
   2124         // the user clicked in the X portion.
   2125         // TODO: Should x and y be used, or removed?
   2126         return chip.isSelected() && offset == getChipEnd(chip);
   2127     }
   2128 
   2129     /**
   2130      * Remove the chip and any text associated with it from the RecipientEditTextView.
   2131      */
   2132     // Visible for testing.
   2133     /*pacakge*/ void removeChip(DrawableRecipientChip chip) {
   2134         Spannable spannable = getSpannable();
   2135         int spanStart = spannable.getSpanStart(chip);
   2136         int spanEnd = spannable.getSpanEnd(chip);
   2137         Editable text = getText();
   2138         int toDelete = spanEnd;
   2139         boolean wasSelected = chip == mSelectedChip;
   2140         // Clear that there is a selected chip before updating any text.
   2141         if (wasSelected) {
   2142             mSelectedChip = null;
   2143         }
   2144         // Always remove trailing spaces when removing a chip.
   2145         while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
   2146             toDelete++;
   2147         }
   2148         spannable.removeSpan(chip);
   2149         if (spanStart >= 0 && toDelete > 0) {
   2150             text.delete(spanStart, toDelete);
   2151         }
   2152         if (wasSelected) {
   2153             clearSelectedChip();
   2154         }
   2155     }
   2156 
   2157     /**
   2158      * Replace this currently selected chip with a new chip
   2159      * that uses the contact data provided.
   2160      */
   2161     // Visible for testing.
   2162     /*package*/ void replaceChip(DrawableRecipientChip chip, RecipientEntry entry) {
   2163         boolean wasSelected = chip == mSelectedChip;
   2164         if (wasSelected) {
   2165             mSelectedChip = null;
   2166         }
   2167         int start = getChipStart(chip);
   2168         int end = getChipEnd(chip);
   2169         getSpannable().removeSpan(chip);
   2170         Editable editable = getText();
   2171         CharSequence chipText = createChip(entry, false);
   2172         if (chipText != null) {
   2173             if (start == -1 || end == -1) {
   2174                 Log.e(TAG, "The chip to replace does not exist but should.");
   2175                 editable.insert(0, chipText);
   2176             } else {
   2177                 if (!TextUtils.isEmpty(chipText)) {
   2178                     // There may be a space to replace with this chip's new
   2179                     // associated space. Check for it
   2180                     int toReplace = end;
   2181                     while (toReplace >= 0 && toReplace < editable.length()
   2182                             && editable.charAt(toReplace) == ' ') {
   2183                         toReplace++;
   2184                     }
   2185                     editable.replace(start, toReplace, chipText);
   2186                 }
   2187             }
   2188         }
   2189         setCursorVisible(true);
   2190         if (wasSelected) {
   2191             clearSelectedChip();
   2192         }
   2193     }
   2194 
   2195     /**
   2196      * Handle click events for a chip. When a selected chip receives a click
   2197      * event, see if that event was in the delete icon. If so, delete it.
   2198      * Otherwise, unselect the chip.
   2199      */
   2200     public void onClick(DrawableRecipientChip chip, int offset, float x, float y) {
   2201         if (chip.isSelected()) {
   2202             if (isInDelete(chip, offset, x, y)) {
   2203                 removeChip(chip);
   2204             } else {
   2205                 clearSelectedChip();
   2206             }
   2207         }
   2208     }
   2209 
   2210     private boolean chipsPending() {
   2211         return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
   2212     }
   2213 
   2214     @Override
   2215     public void removeTextChangedListener(TextWatcher watcher) {
   2216         mTextWatcher = null;
   2217         super.removeTextChangedListener(watcher);
   2218     }
   2219 
   2220     private class RecipientTextWatcher implements TextWatcher {
   2221 
   2222         @Override
   2223         public void afterTextChanged(Editable s) {
   2224             // If the text has been set to null or empty, make sure we remove
   2225             // all the spans we applied.
   2226             if (TextUtils.isEmpty(s)) {
   2227                 // Remove all the chips spans.
   2228                 Spannable spannable = getSpannable();
   2229                 DrawableRecipientChip[] chips = spannable.getSpans(0, getText().length(),
   2230                         DrawableRecipientChip.class);
   2231                 for (DrawableRecipientChip chip : chips) {
   2232                     spannable.removeSpan(chip);
   2233                 }
   2234                 if (mMoreChip != null) {
   2235                     spannable.removeSpan(mMoreChip);
   2236                 }
   2237                 return;
   2238             }
   2239             // Get whether there are any recipients pending addition to the
   2240             // view. If there are, don't do anything in the text watcher.
   2241             if (chipsPending()) {
   2242                 return;
   2243             }
   2244             // If the user is editing a chip, don't clear it.
   2245             if (mSelectedChip != null) {
   2246                 if (!isGeneratedContact(mSelectedChip)) {
   2247                     setCursorVisible(true);
   2248                     setSelection(getText().length());
   2249                     clearSelectedChip();
   2250                 } else {
   2251                     return;
   2252                 }
   2253             }
   2254             int length = s.length();
   2255             // Make sure there is content there to parse and that it is
   2256             // not just the commit character.
   2257             if (length > 1) {
   2258                 if (lastCharacterIsCommitCharacter(s)) {
   2259                     commitByCharacter();
   2260                     return;
   2261                 }
   2262                 char last;
   2263                 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
   2264                 int len = length() - 1;
   2265                 if (end != len) {
   2266                     last = s.charAt(end);
   2267                 } else {
   2268                     last = s.charAt(len);
   2269                 }
   2270                 if (last == COMMIT_CHAR_SPACE) {
   2271                     if (!isPhoneQuery()) {
   2272                         // Check if this is a valid email address. If it is,
   2273                         // commit it.
   2274                         String text = getText().toString();
   2275                         int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
   2276                         String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
   2277                                 tokenStart));
   2278                         if (!TextUtils.isEmpty(sub) && mValidator != null &&
   2279                                 mValidator.isValid(sub)) {
   2280                             commitByCharacter();
   2281                         }
   2282                     }
   2283                 }
   2284             }
   2285         }
   2286 
   2287         @Override
   2288         public void onTextChanged(CharSequence s, int start, int before, int count) {
   2289             // The user deleted some text OR some text was replaced; check to
   2290             // see if the insertion point is on a space
   2291             // following a chip.
   2292             if (before - count == 1) {
   2293                 // If the item deleted is a space, and the thing before the
   2294                 // space is a chip, delete the entire span.
   2295                 int selStart = getSelectionStart();
   2296                 DrawableRecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
   2297                         DrawableRecipientChip.class);
   2298                 if (repl.length > 0) {
   2299                     // There is a chip there! Just remove it.
   2300                     Editable editable = getText();
   2301                     // Add the separator token.
   2302                     int tokenStart = mTokenizer.findTokenStart(editable, selStart);
   2303                     int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
   2304                     tokenEnd = tokenEnd + 1;
   2305                     if (tokenEnd > editable.length()) {
   2306                         tokenEnd = editable.length();
   2307                     }
   2308                     editable.delete(tokenStart, tokenEnd);
   2309                     getSpannable().removeSpan(repl[0]);
   2310                 }
   2311             } else if (count > before) {
   2312                 if (mSelectedChip != null
   2313                     && isGeneratedContact(mSelectedChip)) {
   2314                     if (lastCharacterIsCommitCharacter(s)) {
   2315                         commitByCharacter();
   2316                         return;
   2317                     }
   2318                 }
   2319             }
   2320         }
   2321 
   2322         @Override
   2323         public void beforeTextChanged(CharSequence s, int start, int count, int after) {
   2324             // Do nothing.
   2325         }
   2326     }
   2327 
   2328    public boolean lastCharacterIsCommitCharacter(CharSequence s) {
   2329         char last;
   2330         int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
   2331         int len = length() - 1;
   2332         if (end != len) {
   2333             last = s.charAt(end);
   2334         } else {
   2335             last = s.charAt(len);
   2336         }
   2337         return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON;
   2338     }
   2339 
   2340     public boolean isGeneratedContact(DrawableRecipientChip chip) {
   2341         long contactId = chip.getContactId();
   2342         return contactId == RecipientEntry.INVALID_CONTACT
   2343                 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
   2344     }
   2345 
   2346     /**
   2347      * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
   2348      */
   2349     private void handlePasteClip(ClipData clip) {
   2350         removeTextChangedListener(mTextWatcher);
   2351 
   2352         if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
   2353             for (int i = 0; i < clip.getItemCount(); i++) {
   2354                 CharSequence paste = clip.getItemAt(i).getText();
   2355                 if (paste != null) {
   2356                     int start = getSelectionStart();
   2357                     int end = getSelectionEnd();
   2358                     Editable editable = getText();
   2359                     if (start >= 0 && end >= 0 && start != end) {
   2360                         editable.append(paste, start, end);
   2361                     } else {
   2362                         editable.insert(end, paste);
   2363                     }
   2364                     handlePasteAndReplace();
   2365                 }
   2366             }
   2367         }
   2368 
   2369         mHandler.post(mAddTextWatcher);
   2370     }
   2371 
   2372     @Override
   2373     public boolean onTextContextMenuItem(int id) {
   2374         if (id == android.R.id.paste) {
   2375             ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
   2376                     Context.CLIPBOARD_SERVICE);
   2377             handlePasteClip(clipboard.getPrimaryClip());
   2378             return true;
   2379         }
   2380         return super.onTextContextMenuItem(id);
   2381     }
   2382 
   2383     private void handlePasteAndReplace() {
   2384         ArrayList<DrawableRecipientChip> created = handlePaste();
   2385         if (created != null && created.size() > 0) {
   2386             // Perform reverse lookups on the pasted contacts.
   2387             IndividualReplacementTask replace = new IndividualReplacementTask();
   2388             replace.execute(created);
   2389         }
   2390     }
   2391 
   2392     // Visible for testing.
   2393     /* package */ArrayList<DrawableRecipientChip> handlePaste() {
   2394         String text = getText().toString();
   2395         int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
   2396         String lastAddress = text.substring(originalTokenStart);
   2397         int tokenStart = originalTokenStart;
   2398         int prevTokenStart = 0;
   2399         DrawableRecipientChip findChip = null;
   2400         ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
   2401         if (tokenStart != 0) {
   2402             // There are things before this!
   2403             while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
   2404                 prevTokenStart = tokenStart;
   2405                 tokenStart = mTokenizer.findTokenStart(text, tokenStart);
   2406                 findChip = findChip(tokenStart);
   2407                 if (tokenStart == originalTokenStart && findChip == null) {
   2408                     break;
   2409                 }
   2410             }
   2411             if (tokenStart != originalTokenStart) {
   2412                 if (findChip != null) {
   2413                     tokenStart = prevTokenStart;
   2414                 }
   2415                 int tokenEnd;
   2416                 DrawableRecipientChip createdChip;
   2417                 while (tokenStart < originalTokenStart) {
   2418                     tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
   2419                             tokenStart));
   2420                     commitChip(tokenStart, tokenEnd, getText());
   2421                     createdChip = findChip(tokenStart);
   2422                     if (createdChip == null) {
   2423                         break;
   2424                     }
   2425                     // +1 for the space at the end.
   2426                     tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
   2427                     created.add(createdChip);
   2428                 }
   2429             }
   2430         }
   2431         // Take a look at the last token. If the token has been completed with a
   2432         // commit character, create a chip.
   2433         if (isCompletedToken(lastAddress)) {
   2434             Editable editable = getText();
   2435             tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
   2436             commitChip(tokenStart, editable.length(), editable);
   2437             created.add(findChip(tokenStart));
   2438         }
   2439         return created;
   2440     }
   2441 
   2442     // Visible for testing.
   2443     /* package */int movePastTerminators(int tokenEnd) {
   2444         if (tokenEnd >= length()) {
   2445             return tokenEnd;
   2446         }
   2447         char atEnd = getText().toString().charAt(tokenEnd);
   2448         if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
   2449             tokenEnd++;
   2450         }
   2451         // This token had not only an end token character, but also a space
   2452         // separating it from the next token.
   2453         if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
   2454             tokenEnd++;
   2455         }
   2456         return tokenEnd;
   2457     }
   2458 
   2459     private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
   2460         private DrawableRecipientChip createFreeChip(RecipientEntry entry) {
   2461             try {
   2462                 if (mNoChips) {
   2463                     return null;
   2464                 }
   2465                 return constructChipSpan(entry, false,
   2466                         false /*leave space for contact icon */);
   2467             } catch (NullPointerException e) {
   2468                 Log.e(TAG, e.getMessage(), e);
   2469                 return null;
   2470             }
   2471         }
   2472 
   2473         @Override
   2474         protected void onPreExecute() {
   2475             // Ensure everything is in chip-form already, so we don't have text that slowly gets
   2476             // replaced
   2477             final List<DrawableRecipientChip> originalRecipients =
   2478                     new ArrayList<DrawableRecipientChip>();
   2479             final DrawableRecipientChip[] existingChips = getSortedRecipients();
   2480             for (int i = 0; i < existingChips.length; i++) {
   2481                 originalRecipients.add(existingChips[i]);
   2482             }
   2483             if (mRemovedSpans != null) {
   2484                 originalRecipients.addAll(mRemovedSpans);
   2485             }
   2486 
   2487             final List<DrawableRecipientChip> replacements =
   2488                     new ArrayList<DrawableRecipientChip>(originalRecipients.size());
   2489 
   2490             for (final DrawableRecipientChip chip : originalRecipients) {
   2491                 if (RecipientEntry.isCreatedRecipient(chip.getEntry().getContactId())
   2492                         && getSpannable().getSpanStart(chip) != -1) {
   2493                     replacements.add(createFreeChip(chip.getEntry()));
   2494                 } else {
   2495                     replacements.add(null);
   2496                 }
   2497             }
   2498 
   2499             processReplacements(originalRecipients, replacements);
   2500         }
   2501 
   2502         @Override
   2503         protected Void doInBackground(Void... params) {
   2504             if (mIndividualReplacements != null) {
   2505                 mIndividualReplacements.cancel(true);
   2506             }
   2507             // For each chip in the list, look up the matching contact.
   2508             // If there is a match, replace that chip with the matching
   2509             // chip.
   2510             final ArrayList<DrawableRecipientChip> recipients =
   2511                     new ArrayList<DrawableRecipientChip>();
   2512             DrawableRecipientChip[] existingChips = getSortedRecipients();
   2513             for (int i = 0; i < existingChips.length; i++) {
   2514                 recipients.add(existingChips[i]);
   2515             }
   2516             if (mRemovedSpans != null) {
   2517                 recipients.addAll(mRemovedSpans);
   2518             }
   2519             ArrayList<String> addresses = new ArrayList<String>();
   2520             DrawableRecipientChip chip;
   2521             for (int i = 0; i < recipients.size(); i++) {
   2522                 chip = recipients.get(i);
   2523                 if (chip != null) {
   2524                     addresses.add(createAddressText(chip.getEntry()));
   2525                 }
   2526             }
   2527             final BaseRecipientAdapter adapter = (BaseRecipientAdapter) getAdapter();
   2528             RecipientAlternatesAdapter.getMatchingRecipients(getContext(), adapter, addresses,
   2529                     adapter.getAccount(), new RecipientMatchCallback() {
   2530                         @Override
   2531                         public void matchesFound(Map<String, RecipientEntry> entries) {
   2532                             final ArrayList<DrawableRecipientChip> replacements =
   2533                                     new ArrayList<DrawableRecipientChip>();
   2534                             for (final DrawableRecipientChip temp : recipients) {
   2535                                 RecipientEntry entry = null;
   2536                                 if (temp != null && RecipientEntry.isCreatedRecipient(
   2537                                         temp.getEntry().getContactId())
   2538                                         && getSpannable().getSpanStart(temp) != -1) {
   2539                                     // Replace this.
   2540                                     entry = createValidatedEntry(
   2541                                             entries.get(tokenizeAddress(temp.getEntry()
   2542                                                     .getDestination())));
   2543                                 }
   2544                                 if (entry != null) {
   2545                                     replacements.add(createFreeChip(entry));
   2546                                 } else {
   2547                                     replacements.add(null);
   2548                                 }
   2549                             }
   2550                             processReplacements(recipients, replacements);
   2551                         }
   2552 
   2553                         @Override
   2554                         public void matchesNotFound(final Set<String> unfoundAddresses) {
   2555                             final List<DrawableRecipientChip> replacements =
   2556                                     new ArrayList<DrawableRecipientChip>(unfoundAddresses.size());
   2557 
   2558                             for (final DrawableRecipientChip temp : recipients) {
   2559                                 if (temp != null && RecipientEntry.isCreatedRecipient(
   2560                                         temp.getEntry().getContactId())
   2561                                         && getSpannable().getSpanStart(temp) != -1) {
   2562                                     if (unfoundAddresses.contains(
   2563                                             temp.getEntry().getDestination())) {
   2564                                         replacements.add(createFreeChip(temp.getEntry()));
   2565                                     } else {
   2566                                         replacements.add(null);
   2567                                     }
   2568                                 } else {
   2569                                     replacements.add(null);
   2570                                 }
   2571                             }
   2572 
   2573                             processReplacements(recipients, replacements);
   2574                         }
   2575                     });
   2576             return null;
   2577         }
   2578 
   2579         private void processReplacements(final List<DrawableRecipientChip> recipients,
   2580                 final List<DrawableRecipientChip> replacements) {
   2581             if (replacements != null && replacements.size() > 0) {
   2582                 final Runnable runnable = new Runnable() {
   2583                     @Override
   2584                     public void run() {
   2585                         final Editable text = new SpannableStringBuilder(getText());
   2586                         int i = 0;
   2587                         for (final DrawableRecipientChip chip : recipients) {
   2588                             final DrawableRecipientChip replacement = replacements.get(i);
   2589                             if (replacement != null) {
   2590                                 final RecipientEntry oldEntry = chip.getEntry();
   2591                                 final RecipientEntry newEntry = replacement.getEntry();
   2592                                 final boolean isBetter =
   2593                                         RecipientAlternatesAdapter.getBetterRecipient(
   2594                                                 oldEntry, newEntry) == newEntry;
   2595 
   2596                                 if (isBetter) {
   2597                                     // Find the location of the chip in the text currently shown.
   2598                                     final int start = text.getSpanStart(chip);
   2599                                     if (start != -1) {
   2600                                         // Replacing the entirety of what the chip represented,
   2601                                         // including the extra space dividing it from other chips.
   2602                                         final int end =
   2603                                                 Math.min(text.getSpanEnd(chip) + 1, text.length());
   2604                                         text.removeSpan(chip);
   2605                                         // Make sure we always have just 1 space at the end to
   2606                                         // separate this chip from the next chip.
   2607                                         final SpannableString displayText =
   2608                                                 new SpannableString(createAddressText(
   2609                                                         replacement.getEntry()).trim() + " ");
   2610                                         displayText.setSpan(replacement, 0,
   2611                                                 displayText.length() - 1,
   2612                                                 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
   2613                                         // Replace the old text we found with with the new display
   2614                                         // text, which now may also contain the display name of the
   2615                                         // recipient.
   2616                                         text.replace(start, end, displayText);
   2617                                         replacement.setOriginalText(displayText.toString());
   2618                                         replacements.set(i, null);
   2619 
   2620                                         recipients.set(i, replacement);
   2621                                     }
   2622                                 }
   2623                             }
   2624                             i++;
   2625                         }
   2626                         setText(text);
   2627                     }
   2628                 };
   2629 
   2630                 if (Looper.myLooper() == Looper.getMainLooper()) {
   2631                     runnable.run();
   2632                 } else {
   2633                     mHandler.post(runnable);
   2634                 }
   2635             }
   2636         }
   2637     }
   2638 
   2639     private class IndividualReplacementTask
   2640             extends AsyncTask<ArrayList<DrawableRecipientChip>, Void, Void> {
   2641         @Override
   2642         protected Void doInBackground(ArrayList<DrawableRecipientChip>... params) {
   2643             // For each chip in the list, look up the matching contact.
   2644             // If there is a match, replace that chip with the matching
   2645             // chip.
   2646             final ArrayList<DrawableRecipientChip> originalRecipients = params[0];
   2647             ArrayList<String> addresses = new ArrayList<String>();
   2648             DrawableRecipientChip chip;
   2649             for (int i = 0; i < originalRecipients.size(); i++) {
   2650                 chip = originalRecipients.get(i);
   2651                 if (chip != null) {
   2652                     addresses.add(createAddressText(chip.getEntry()));
   2653                 }
   2654             }
   2655             final BaseRecipientAdapter adapter = (BaseRecipientAdapter) getAdapter();
   2656             RecipientAlternatesAdapter.getMatchingRecipients(getContext(), adapter, addresses,
   2657                     ((BaseRecipientAdapter) getAdapter()).getAccount(),
   2658                     new RecipientMatchCallback() {
   2659 
   2660                         @Override
   2661                         public void matchesFound(Map<String, RecipientEntry> entries) {
   2662                             for (final DrawableRecipientChip temp : originalRecipients) {
   2663                                 if (RecipientEntry.isCreatedRecipient(temp.getEntry()
   2664                                         .getContactId())
   2665                                         && getSpannable().getSpanStart(temp) != -1) {
   2666                                     // Replace this.
   2667                                     final RecipientEntry entry = createValidatedEntry(entries
   2668                                             .get(tokenizeAddress(temp.getEntry().getDestination())
   2669                                                     .toLowerCase()));
   2670                                     if (entry != null) {
   2671                                         mHandler.post(new Runnable() {
   2672                                             @Override
   2673                                             public void run() {
   2674                                                 replaceChip(temp, entry);
   2675                                             }
   2676                                         });
   2677                                     }
   2678                                 }
   2679                             }
   2680                         }
   2681 
   2682                         @Override
   2683                         public void matchesNotFound(final Set<String> unfoundAddresses) {
   2684                             // No action required
   2685                         }
   2686                     });
   2687             return null;
   2688         }
   2689     }
   2690 
   2691 
   2692     /**
   2693      * MoreImageSpan is a simple class created for tracking the existence of a
   2694      * more chip across activity restarts/
   2695      */
   2696     private class MoreImageSpan extends ImageSpan {
   2697         public MoreImageSpan(Drawable b) {
   2698             super(b);
   2699         }
   2700     }
   2701 
   2702     @Override
   2703     public boolean onDown(MotionEvent e) {
   2704         return false;
   2705     }
   2706 
   2707     @Override
   2708     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
   2709         // Do nothing.
   2710         return false;
   2711     }
   2712 
   2713     @Override
   2714     public void onLongPress(MotionEvent event) {
   2715         if (mSelectedChip != null) {
   2716             return;
   2717         }
   2718         float x = event.getX();
   2719         float y = event.getY();
   2720         final int offset = putOffsetInRange(x, y);
   2721         DrawableRecipientChip currentChip = findChip(offset);
   2722         if (currentChip != null) {
   2723             if (mDragEnabled) {
   2724                 // Start drag-and-drop for the selected chip.
   2725                 startDrag(currentChip);
   2726             } else {
   2727                 // Copy the selected chip email address.
   2728                 showCopyDialog(currentChip.getEntry().getDestination());
   2729             }
   2730         }
   2731     }
   2732 
   2733     // The following methods are used to provide some functionality on older versions of Android
   2734     // These methods were copied out of JB MR2's TextView
   2735     /////////////////////////////////////////////////
   2736     private int supportGetOffsetForPosition(float x, float y) {
   2737         if (getLayout() == null) return -1;
   2738         final int line = supportGetLineAtCoordinate(y);
   2739         final int offset = supportGetOffsetAtCoordinate(line, x);
   2740         return offset;
   2741     }
   2742 
   2743     private float supportConvertToLocalHorizontalCoordinate(float x) {
   2744         x -= getTotalPaddingLeft();
   2745         // Clamp the position to inside of the view.
   2746         x = Math.max(0.0f, x);
   2747         x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
   2748         x += getScrollX();
   2749         return x;
   2750     }
   2751 
   2752     private int supportGetLineAtCoordinate(float y) {
   2753         y -= getTotalPaddingLeft();
   2754         // Clamp the position to inside of the view.
   2755         y = Math.max(0.0f, y);
   2756         y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
   2757         y += getScrollY();
   2758         return getLayout().getLineForVertical((int) y);
   2759     }
   2760 
   2761     private int supportGetOffsetAtCoordinate(int line, float x) {
   2762         x = supportConvertToLocalHorizontalCoordinate(x);
   2763         return getLayout().getOffsetForHorizontal(line, x);
   2764     }
   2765     /////////////////////////////////////////////////
   2766 
   2767     /**
   2768      * Enables drag-and-drop for chips.
   2769      */
   2770     public void enableDrag() {
   2771         mDragEnabled = true;
   2772     }
   2773 
   2774     /**
   2775      * Starts drag-and-drop for the selected chip.
   2776      */
   2777     private void startDrag(DrawableRecipientChip currentChip) {
   2778         String address = currentChip.getEntry().getDestination();
   2779         ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
   2780 
   2781         // Start drag mode.
   2782         startDrag(data, new RecipientChipShadow(currentChip), null, 0);
   2783 
   2784         // Remove the current chip, so drag-and-drop will result in a move.
   2785         // TODO (phamm): consider readd this chip if it's dropped outside a target.
   2786         removeChip(currentChip);
   2787     }
   2788 
   2789     /**
   2790      * Handles drag event.
   2791      */
   2792     @Override
   2793     public boolean onDragEvent(DragEvent event) {
   2794         switch (event.getAction()) {
   2795             case DragEvent.ACTION_DRAG_STARTED:
   2796                 // Only handle plain text drag and drop.
   2797                 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
   2798             case DragEvent.ACTION_DRAG_ENTERED:
   2799                 requestFocus();
   2800                 return true;
   2801             case DragEvent.ACTION_DROP:
   2802                 handlePasteClip(event.getClipData());
   2803                 return true;
   2804         }
   2805         return false;
   2806     }
   2807 
   2808     /**
   2809      * Drag shadow for a {@link RecipientChip}.
   2810      */
   2811     private final class RecipientChipShadow extends DragShadowBuilder {
   2812         private final DrawableRecipientChip mChip;
   2813 
   2814         public RecipientChipShadow(DrawableRecipientChip chip) {
   2815             mChip = chip;
   2816         }
   2817 
   2818         @Override
   2819         public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
   2820             Rect rect = mChip.getBounds();
   2821             shadowSize.set(rect.width(), rect.height());
   2822             shadowTouchPoint.set(rect.centerX(), rect.centerY());
   2823         }
   2824 
   2825         @Override
   2826         public void onDrawShadow(Canvas canvas) {
   2827             mChip.draw(canvas);
   2828         }
   2829     }
   2830 
   2831     private void showCopyDialog(final String address) {
   2832         if (!mAttachedToWindow) {
   2833             return;
   2834         }
   2835         mCopyAddress = address;
   2836         mCopyDialog.setTitle(address);
   2837         mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
   2838         mCopyDialog.setCancelable(true);
   2839         mCopyDialog.setCanceledOnTouchOutside(true);
   2840         Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
   2841         button.setOnClickListener(this);
   2842         int btnTitleId;
   2843         if (isPhoneQuery()) {
   2844             btnTitleId = R.string.copy_number;
   2845         } else {
   2846             btnTitleId = R.string.copy_email;
   2847         }
   2848         String buttonTitle = getContext().getResources().getString(btnTitleId);
   2849         button.setText(buttonTitle);
   2850         mCopyDialog.setOnDismissListener(this);
   2851         mCopyDialog.show();
   2852     }
   2853 
   2854     @Override
   2855     public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
   2856         // Do nothing.
   2857         return false;
   2858     }
   2859 
   2860     @Override
   2861     public void onShowPress(MotionEvent e) {
   2862         // Do nothing.
   2863     }
   2864 
   2865     @Override
   2866     public boolean onSingleTapUp(MotionEvent e) {
   2867         // Do nothing.
   2868         return false;
   2869     }
   2870 
   2871     @Override
   2872     public void onDismiss(DialogInterface dialog) {
   2873         mCopyAddress = null;
   2874     }
   2875 
   2876     @Override
   2877     public void onClick(View v) {
   2878         // Copy this to the clipboard.
   2879         ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
   2880                 Context.CLIPBOARD_SERVICE);
   2881         clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
   2882         mCopyDialog.dismiss();
   2883     }
   2884 
   2885     protected boolean isPhoneQuery() {
   2886         return getAdapter() != null
   2887                 && ((BaseRecipientAdapter) getAdapter()).getQueryType()
   2888                     == BaseRecipientAdapter.QUERY_TYPE_PHONE;
   2889     }
   2890 }
   2891