Merge "Initial clean up of the chips code" into jb-ub-mail-ur9
diff --git a/src/com/android/ex/chips/BaseRecipientAdapter.java b/src/com/android/ex/chips/BaseRecipientAdapter.java
index f742cf1..71b610e 100644
--- a/src/com/android/ex/chips/BaseRecipientAdapter.java
+++ b/src/com/android/ex/chips/BaseRecipientAdapter.java
@@ -234,8 +234,8 @@
                     }
 
                     // We'll copy this result to mEntry in publicResults() (run in the UX thread).
-                    final List<RecipientEntry> entries = constructEntryList(false,
-                            entryMap, nonAggregatedEntries, existingDestinations);
+                    final List<RecipientEntry> entries = constructEntryList(
+                            entryMap, nonAggregatedEntries);
 
                     // After having local results, check the size of results. If the results are
                     // not enough, we search remote directories, which will take longer time.
@@ -424,8 +424,7 @@
             }
 
             // Show the list again without "waiting" message.
-            updateEntries(constructEntryList(false,
-                    mEntryMap, mNonAggregatedEntries, mExistingDestinations));
+            updateEntries(constructEntryList(mEntryMap, mNonAggregatedEntries));
         }
     }
 
@@ -482,8 +481,7 @@
         @Override
         public void handleMessage(Message msg) {
             if (mRemainingDirectoryCount > 0) {
-                updateEntries(constructEntryList(true,
-                        mEntryMap, mNonAggregatedEntries, mExistingDestinations));
+                updateEntries(constructEntryList(mEntryMap, mNonAggregatedEntries));
             }
         }
 
@@ -634,7 +632,7 @@
         mDelayedMessageHandler.sendDelayedLoadMessage();
     }
 
-    private void putOneEntry(TemporaryEntry entry, boolean isAggregatedEntry,
+    private static void putOneEntry(TemporaryEntry entry, boolean isAggregatedEntry,
             LinkedHashMap<Long, List<RecipientEntry>> entryMap,
             List<RecipientEntry> nonAggregatedEntries,
             Set<String> existingDestinations) {
@@ -675,10 +673,8 @@
      * thread to get one from directories.
      */
     private List<RecipientEntry> constructEntryList(
-            boolean showMessageIfDirectoryLoadRemaining,
             LinkedHashMap<Long, List<RecipientEntry>> entryMap,
-            List<RecipientEntry> nonAggregatedEntries,
-            Set<String> existingDestinations) {
+            List<RecipientEntry> nonAggregatedEntries) {
         final List<RecipientEntry> entries = new ArrayList<RecipientEntry>();
         int validEntryCount = 0;
         for (Map.Entry<Long, List<RecipientEntry>> mapEntry : entryMap.entrySet()) {
@@ -912,7 +908,7 @@
             if (imageView != null) {
                 imageView.setVisibility(View.VISIBLE);
                 final byte[] photoBytes = entry.getPhotoBytes();
-                if (photoBytes != null && imageView != null) {
+                if (photoBytes != null) {
                     final Bitmap photo = BitmapFactory.decodeByteArray(photoBytes, 0,
                             photoBytes.length);
                     imageView.setImageBitmap(photo);
diff --git a/src/com/android/ex/chips/InvisibleRecipientChip.java b/src/com/android/ex/chips/InvisibleRecipientChip.java
index 452c2b8..ac83480 100644
--- a/src/com/android/ex/chips/InvisibleRecipientChip.java
+++ b/src/com/android/ex/chips/InvisibleRecipientChip.java
@@ -41,7 +41,7 @@
 
     private CharSequence mOriginalText;
 
-    public InvisibleRecipientChip(RecipientEntry entry, int offset) {
+    public InvisibleRecipientChip(RecipientEntry entry) {
         super();
         mDisplay = entry.getDisplayName();
         mValue = entry.getDestination().trim();
@@ -54,6 +54,7 @@
      * Set the selected state of the chip.
      * @param selected
      */
+    @Override
     public void setSelected(boolean selected) {
         mSelected = selected;
     }
@@ -61,6 +62,7 @@
     /**
      * Return true if the chip is selected.
      */
+    @Override
     public boolean isSelected() {
         return mSelected;
     }
@@ -68,6 +70,7 @@
     /**
      * Get the text displayed in the chip.
      */
+    @Override
     public CharSequence getDisplay() {
         return mDisplay;
     }
@@ -75,6 +78,7 @@
     /**
      * Get the text value this chip represents.
      */
+    @Override
     public CharSequence getValue() {
         return mValue;
     }
@@ -82,6 +86,7 @@
     /**
      * Get the id of the contact associated with this chip.
      */
+    @Override
     public long getContactId() {
         return mContactId;
     }
@@ -89,6 +94,7 @@
     /**
      * Get the id of the data associated with this chip.
      */
+    @Override
     public long getDataId() {
         return mDataId;
     }
@@ -96,17 +102,21 @@
     /**
      * Get associated RecipientEntry.
      */
+    @Override
     public RecipientEntry getEntry() {
         return mEntry;
     }
 
+    @Override
     public void setOriginalText(String text) {
-        if (!TextUtils.isEmpty(text)) {
-            text = text.trim();
+        if (TextUtils.isEmpty(text)) {
+            mOriginalText = text;
+        } else {
+            mOriginalText = text.trim();
         }
-        mOriginalText = text;
     }
 
+    @Override
     public CharSequence getOriginalText() {
         return !TextUtils.isEmpty(mOriginalText) ? mOriginalText : mEntry.getDestination();
     }
diff --git a/src/com/android/ex/chips/RecipientAlternatesAdapter.java b/src/com/android/ex/chips/RecipientAlternatesAdapter.java
index 07aa994..465c90e 100644
--- a/src/com/android/ex/chips/RecipientAlternatesAdapter.java
+++ b/src/com/android/ex/chips/RecipientAlternatesAdapter.java
@@ -70,7 +70,7 @@
         /**
          * Called with all addresses that could not be resolved to valid recipients.
          */
-        public void matchesNotFound(Set<String> addresses);
+        public void matchesNotFound(Set<String> unfoundAddresses);
     }
 
     public static void getMatchingRecipients(Context context, ArrayList<String> inAddresses,
@@ -299,12 +299,12 @@
         return cursor;
     }
 
-    public RecipientAlternatesAdapter(Context context, long contactId, long currentId, int viewId,
+    public RecipientAlternatesAdapter(Context context, long contactId, long currentId,
             OnCheckedItemChangedListener listener) {
-        this(context, contactId, currentId, viewId, QUERY_TYPE_EMAIL, listener);
+        this(context, contactId, currentId, QUERY_TYPE_EMAIL, listener);
     }
 
-    public RecipientAlternatesAdapter(Context context, long contactId, long currentId, int viewId,
+    public RecipientAlternatesAdapter(Context context, long contactId, long currentId,
             int queryMode, OnCheckedItemChangedListener listener) {
         super(context, getCursorForConstruction(context, contactId, queryMode), 0);
         mLayoutInflater = LayoutInflater.from(context);
diff --git a/src/com/android/ex/chips/RecipientEditTextView.java b/src/com/android/ex/chips/RecipientEditTextView.java
index a4c7f79..f53ae25 100644
--- a/src/com/android/ex/chips/RecipientEditTextView.java
+++ b/src/com/android/ex/chips/RecipientEditTextView.java
@@ -105,8 +105,6 @@
 
     private static final char COMMIT_CHAR_COMMA = ',';
 
-    private static final char NAME_WRAPPER_CHAR = '"';
-
     private static final char COMMIT_CHAR_SEMICOLON = ';';
 
     private static final char COMMIT_CHAR_SPACE = ' ';
@@ -485,7 +483,7 @@
                 TextUtils.TruncateAt.END);
     }
 
-    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
+    private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint) {
         // Ellipsize the text so that it takes AT MOST the entire width of the
         // autocomplete text entry area. Make sure to leave space for padding
         // on the sides.
@@ -494,7 +492,7 @@
         float[] widths = new float[1];
         paint.getTextWidths(" ", widths);
         CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
-                calculateAvailableWidth(true) - deleteWidth - widths[0]);
+                calculateAvailableWidth() - deleteWidth - widths[0]);
 
         // Make sure there is a minimum chip width so the user can ALWAYS
         // tap a chip without difficulty.
@@ -527,7 +525,7 @@
     }
 
 
-    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout,
+    private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint,
             boolean leaveBlankIconSpacer) {
         // Ellipsize the text so that it takes AT MOST the entire width of the
         // autocomplete text entry area. Make sure to leave space for padding
@@ -537,7 +535,7 @@
         float[] widths = new float[1];
         paint.getTextWidths(" ", widths);
         CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
-                calculateAvailableWidth(false) - iconWidth - widths[0]);
+                calculateAvailableWidth() - iconWidth - widths[0]);
         // Make sure there is a minimum chip width so the user can ALWAYS
         // tap a chip without difficulty.
         int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
@@ -611,20 +609,19 @@
         return contact.isValid() ? mChipBackground : mInvalidChipBackground;
     }
 
-    private float getTextYOffset(String text, TextPaint paint, int height) {
+    private static float getTextYOffset(String text, TextPaint paint, int height) {
         Rect bounds = new Rect();
         paint.getTextBounds(text, 0, text.length(), bounds);
         int textHeight = bounds.bottom - bounds.top ;
         return height - ((height - textHeight) / 2) - (int)paint.descent();
     }
 
-    private RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed,
+    private RecipientChip constructChipSpan(RecipientEntry contact, boolean pressed,
             boolean leaveIconSpace) throws NullPointerException {
         if (mChipBackground == null) {
             throw new NullPointerException(
                     "Unable to render any chips as setChipDimensions was not called.");
         }
-        Layout layout = getLayout();
 
         TextPaint paint = getPaint();
         float defaultSize = paint.getTextSize();
@@ -632,16 +629,16 @@
 
         Bitmap tmpBitmap;
         if (pressed) {
-            tmpBitmap = createSelectedChip(contact, paint, layout);
+            tmpBitmap = createSelectedChip(contact, paint);
 
         } else {
-            tmpBitmap = createUnselectedChip(contact, paint, layout, leaveIconSpace);
+            tmpBitmap = createUnselectedChip(contact, paint, leaveIconSpace);
         }
 
         // Pass the full text, un-ellipsized, to the chip.
         Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
         result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
-        RecipientChip recipientChip = new VisibleRecipientChip(result, contact, offset);
+        RecipientChip recipientChip = new VisibleRecipientChip(result, contact);
         // Return text to the original size.
         paint.setTextSize(defaultSize);
         paint.setColor(defaultColor);
@@ -666,7 +663,7 @@
      * account the width of the EditTextView, any view padding, and padding
      * that will be added to the chip.
      */
-    private float calculateAvailableWidth(boolean pressed) {
+    private float calculateAvailableWidth() {
         return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
     }
 
@@ -920,8 +917,6 @@
         }
         RecipientEntry entry = createTokenizedEntry(token);
         if (entry != null) {
-            String destText = createAddressText(entry);
-            SpannableString chipText = new SpannableString(destText);
             RecipientChip chip = null;
             try {
                 if (!mNoChips) {
@@ -933,8 +928,8 @@
                             || TextUtils.equals(entry.getDisplayName(),
                                     entry.getDestination());
                     chip = visible ?
-                            constructChipSpan(entry, tokenStart, false, leaveSpace)
-                            : new InvisibleRecipientChip(entry, commitCharIndex);
+                            constructChipSpan(entry, false, leaveSpace)
+                            : new InvisibleRecipientChip(entry);
                 }
             } catch (NullPointerException e) {
                 Log.e(TAG, e.getMessage(), e);
@@ -1023,7 +1018,7 @@
         return mValidator == null ? true : mValidator.isValid(text);
     }
 
-    private String tokenizeAddress(String destination) {
+    private static String tokenizeAddress(String destination) {
         Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
         if (tokens != null && tokens.length > 0) {
             return tokens[0].getAddress();
@@ -1407,7 +1402,7 @@
     }
 
     private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
-            int width, Context context) {
+            int width) {
         int line = getLayout().getLineForOffset(getChipStart(currentChip));
         int bottom;
         if (line == getLineCount() -1) {
@@ -1440,7 +1435,7 @@
 
     private ListAdapter createAlternatesAdapter(RecipientChip chip) {
         return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
-                mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this);
+                ((BaseRecipientAdapter)getAdapter()).getQueryType(), this);
     }
 
     private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
@@ -1487,7 +1482,7 @@
         return offset;
     }
 
-    private int findText(Editable text, int offset) {
+    private static int findText(Editable text, int offset) {
         if (text.charAt(offset) != ' ') {
             return offset;
         }
@@ -1561,13 +1556,11 @@
         }
         SpannableString chipText = null;
         // Always leave a blank space at the end of a chip.
-        int end = getSelectionEnd();
-        int start = mTokenizer.findTokenStart(getText(), end);
-        int textLength = displayText.length()-1;
+        int textLength = displayText.length() - 1;
         chipText = new SpannableString(displayText);
         if (!mNoChips) {
             try {
-                RecipientChip chip = constructChipSpan(entry, start, pressed,
+                RecipientChip chip = constructChipSpan(entry, pressed,
                         false /* leave space for contact icon */);
                 chipText.setSpan(chip, 0, textLength,
                         Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
@@ -1900,7 +1893,7 @@
             editable.append(text);
             return constructChipSpan(
                     RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())),
-                    getSelectionStart(), true, false);
+                    true, false);
         } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
             int start = getChipStart(currentChip);
             int end = getChipEnd(currentChip);
@@ -1910,7 +1903,7 @@
                 if (mNoChips) {
                     return null;
                 }
-                newChip = constructChipSpan(currentChip.getEntry(), start, true, false);
+                newChip = constructChipSpan(currentChip.getEntry(), true, false);
             } catch (NullPointerException e) {
                 Log.e(TAG, e.getMessage(), e);
                 return null;
@@ -1926,7 +1919,7 @@
             if (shouldShowEditableText(newChip)) {
                 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
             }
-            showAddress(newChip, mAddressPopup, getWidth(), getContext());
+            showAddress(newChip, mAddressPopup, getWidth());
             setCursorVisible(false);
             return newChip;
         } else {
@@ -1935,7 +1928,7 @@
             getSpannable().removeSpan(currentChip);
             RecipientChip newChip;
             try {
-                newChip = constructChipSpan(currentChip.getEntry(), start, true, false);
+                newChip = constructChipSpan(currentChip.getEntry(), true, false);
             } catch (NullPointerException e) {
                 Log.e(TAG, e.getMessage(), e);
                 return null;
@@ -1951,7 +1944,7 @@
             if (shouldShowEditableText(newChip)) {
                 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
             }
-            showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
+            showAlternates(newChip, mAlternatesPopup, getWidth());
             setCursorVisible(false);
             return newChip;
         }
@@ -1964,7 +1957,7 @@
     }
 
     private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
-            int width, Context context) {
+            int width) {
         int line = getLayout().getLineForOffset(getChipStart(currentChip));
         int bottom = calculateOffsetFromBottom(line);
         // Align the alternates popup with the left side of the View,
@@ -2006,7 +1999,7 @@
             editable.removeSpan(chip);
             try {
                 if (!mNoChips) {
-                    editable.setSpan(constructChipSpan(chip.getEntry(), start, false, false),
+                    editable.setSpan(constructChipSpan(chip.getEntry(), false, false),
                             start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                 }
             } catch (NullPointerException e) {
@@ -2032,6 +2025,7 @@
     private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
         // Figure out the bounds of this chip and whether or not
         // the user clicked in the X portion.
+        // TODO: Should x and y be used, or removed?
         return chip.isSelected() && offset == getChipEnd(chip);
     }
 
@@ -2406,7 +2400,7 @@
                 if (mNoChips) {
                     return null;
                 }
-                return constructChipSpan(entry, -1, false,
+                return constructChipSpan(entry, false,
                         false /*leave space for contact icon */);
             } catch (NullPointerException e) {
                 Log.e(TAG, e.getMessage(), e);
@@ -2494,15 +2488,16 @@
                         }
 
                         @Override
-                        public void matchesNotFound(final Set<String> addresses) {
+                        public void matchesNotFound(final Set<String> unfoundAddresses) {
                             final List<RecipientChip> replacements =
-                                    new ArrayList<RecipientChip>(addresses.size());
+                                    new ArrayList<RecipientChip>(unfoundAddresses.size());
 
                             for (final RecipientChip temp : recipients) {
                                 if (temp != null && RecipientEntry.isCreatedRecipient(
                                         temp.getEntry().getContactId())
                                         && getSpannable().getSpanStart(temp) != -1) {
-                                    if (addresses.contains(temp.getEntry().getDestination())) {
+                                    if (unfoundAddresses.contains(
+                                            temp.getEntry().getDestination())) {
                                         replacements.add(createFreeChip(temp.getEntry()));
                                     } else {
                                         replacements.add(null);
@@ -2628,7 +2623,7 @@
                         }
 
                         @Override
-                        public void matchesNotFound(final Set<String> addresses) {
+                        public void matchesNotFound(final Set<String> unfoundAddresses) {
                             // No action required
                         }
                     });
diff --git a/src/com/android/ex/chips/SingleRecipientArrayAdapter.java b/src/com/android/ex/chips/SingleRecipientArrayAdapter.java
index 8131fc3..0571a4e 100644
--- a/src/com/android/ex/chips/SingleRecipientArrayAdapter.java
+++ b/src/com/android/ex/chips/SingleRecipientArrayAdapter.java
@@ -43,7 +43,7 @@
         if (convertView == null) {
             convertView = newView();
         }
-        bindView(convertView, convertView.getContext(), getItem(position));
+        bindView(convertView, getItem(position));
         return convertView;
     }
 
@@ -51,7 +51,7 @@
         return mLayoutInflater.inflate(mLayoutId, null);
     }
 
-    private void bindView(View view, Context context, RecipientEntry entry) {
+    private static void bindView(View view, RecipientEntry entry) {
         TextView display = (TextView) view.findViewById(android.R.id.title);
         ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
         display.setText(entry.getDisplayName());
diff --git a/src/com/android/ex/chips/VisibleRecipientChip.java b/src/com/android/ex/chips/VisibleRecipientChip.java
index 49be32f..395fd0a 100644
--- a/src/com/android/ex/chips/VisibleRecipientChip.java
+++ b/src/com/android/ex/chips/VisibleRecipientChip.java
@@ -42,7 +42,7 @@
 
     private CharSequence mOriginalText;
 
-    public VisibleRecipientChip(Drawable drawable, RecipientEntry entry, int offset) {
+    public VisibleRecipientChip(Drawable drawable, RecipientEntry entry) {
         super(drawable, DynamicDrawableSpan.ALIGN_BOTTOM);
         mDisplay = entry.getDisplayName();
         mValue = entry.getDestination().trim();
@@ -55,6 +55,7 @@
      * Set the selected state of the chip.
      * @param selected
      */
+    @Override
     public void setSelected(boolean selected) {
         mSelected = selected;
     }
@@ -62,6 +63,7 @@
     /**
      * Return true if the chip is selected.
      */
+    @Override
     public boolean isSelected() {
         return mSelected;
     }
@@ -69,6 +71,7 @@
     /**
      * Get the text displayed in the chip.
      */
+    @Override
     public CharSequence getDisplay() {
         return mDisplay;
     }
@@ -76,6 +79,7 @@
     /**
      * Get the text value this chip represents.
      */
+    @Override
     public CharSequence getValue() {
         return mValue;
     }
@@ -83,6 +87,7 @@
     /**
      * Get the id of the contact associated with this chip.
      */
+    @Override
     public long getContactId() {
         return mContactId;
     }
@@ -90,6 +95,7 @@
     /**
      * Get the id of the data associated with this chip.
      */
+    @Override
     public long getDataId() {
         return mDataId;
     }
@@ -97,17 +103,21 @@
     /**
      * Get associated RecipientEntry.
      */
+    @Override
     public RecipientEntry getEntry() {
         return mEntry;
     }
 
+    @Override
     public void setOriginalText(String text) {
-        if (!TextUtils.isEmpty(text)) {
-            text = text.trim();
+        if (TextUtils.isEmpty(text)) {
+            mOriginalText = text;
+        } else {
+            mOriginalText = text.trim();
         }
-        mOriginalText = text;
     }
 
+    @Override
     public CharSequence getOriginalText() {
         return !TextUtils.isEmpty(mOriginalText) ? mOriginalText : mEntry.getDestination();
     }
diff --git a/tests/src/com/android/ex/chips/ChipsTest.java b/tests/src/com/android/ex/chips/ChipsTest.java
index 534b34f..3d020a3 100644
--- a/tests/src/com/android/ex/chips/ChipsTest.java
+++ b/tests/src/com/android/ex/chips/ChipsTest.java
@@ -254,8 +254,8 @@
         String first = (String) mTokenizer.terminateToken("FIRST");
         String second = (String) mTokenizer.terminateToken("SECOND");
         String third = (String) mTokenizer.terminateToken("THIRD");
-        String fourth = (String) ("FOURTH,");
-        String fifth = (String) ("FIFTH,");
+        String fourth = "FOURTH,";
+        String fifth = "FIFTH,";
         mEditable = new SpannableStringBuilder();
         mEditable.append(first+second+third+fourth+fifth);
         assertEquals(view.countTokens(mEditable), 5);
@@ -926,7 +926,7 @@
         }
         mMockRecips = new RecipientChip[size];
         for (int i = 0; i < size; i++) {
-            mMockRecips[i] = new VisibleRecipientChip(null, mMockEntries[i], i);
+            mMockRecips[i] = new VisibleRecipientChip(null, mMockEntries[i]);
         }
     }
 }