blob: 9310639da06eb23bc3b291a88d59b9561214430f [file] [log] [blame]
Mindy Pereira9159cd22011-05-25 17:06:44 -07001/*
Scott Kennedy194d4272013-03-06 22:06:45 -08002
Mindy Pereira9159cd22011-05-25 17:06:44 -07003 * 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
18package com.android.ex.chips;
19
Jin Cao14efc572014-09-10 10:27:01 -070020import android.app.Activity;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070021import android.app.Dialog;
22import android.content.ClipData;
Mindy Pereira20c9d622011-10-12 13:18:04 -070023import android.content.ClipDescription;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070024import android.content.ClipboardManager;
Mindy Pereira9159cd22011-05-25 17:06:44 -070025import android.content.Context;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070026import android.content.DialogInterface;
27import android.content.DialogInterface.OnDismissListener;
Mindy Pereira52c441e2011-12-15 13:35:37 -080028import android.content.res.Resources;
Mindy Pereira22faaa62011-12-16 14:30:34 -080029import android.content.res.TypedArray;
Mindy Pereiracd611952011-06-01 17:02:20 -070030import android.graphics.Bitmap;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070031import android.graphics.BitmapFactory;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070032import android.graphics.BitmapShader;
Mindy Pereiracd611952011-06-01 17:02:20 -070033import android.graphics.Canvas;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070034import android.graphics.Color;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070035import android.graphics.Matrix;
Kevin Linb10d1c62014-01-24 12:45:00 -080036import android.graphics.Paint;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070037import android.graphics.Paint.Style;
Minh Phame51c7222011-10-12 11:33:26 -070038import android.graphics.Point;
Mindy Pereiracd611952011-06-01 17:02:20 -070039import android.graphics.Rect;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070040import android.graphics.RectF;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070041import android.graphics.Shader.TileMode;
Mindy Pereiracd611952011-06-01 17:02:20 -070042import android.graphics.drawable.BitmapDrawable;
Mindy Pereira9159cd22011-05-25 17:06:44 -070043import android.graphics.drawable.Drawable;
Jin Cao4db8ccc2014-07-30 10:11:07 -070044import android.graphics.drawable.StateListDrawable;
Mindy Pereira18529312011-06-28 11:00:52 -070045import android.os.AsyncTask;
Scott Kennedy1650ef62013-08-02 21:56:47 -070046import android.os.Build;
Mindy Pereira007a76b2011-06-14 11:39:36 -070047import android.os.Handler;
Scott Kennedy78f38a02013-02-27 11:21:40 -080048import android.os.Looper;
Mindy Pereira007a76b2011-06-14 11:39:36 -070049import android.os.Message;
Mindy Pereiradc04cd72011-09-16 15:42:09 -070050import android.os.Parcelable;
Mindy Pereira9159cd22011-05-25 17:06:44 -070051import android.text.Editable;
Gilles Debunne61b48cc2011-08-16 14:03:00 -070052import android.text.InputType;
Mindy Pereiracd611952011-06-01 17:02:20 -070053import android.text.Layout;
54import android.text.Spannable;
55import android.text.SpannableString;
Scott Kennedy0e128962013-04-11 10:52:08 -070056import android.text.SpannableStringBuilder;
Mindy Pereiracd611952011-06-01 17:02:20 -070057import android.text.Spanned;
58import android.text.TextPaint;
59import android.text.TextUtils;
Mindy Pereirab88ee452011-06-02 11:07:43 -070060import android.text.TextWatcher;
Mindy Pereiracd611952011-06-01 17:02:20 -070061import android.text.method.QwertyKeyListener;
Mindy Pereira3bb52162011-07-01 14:52:22 -070062import android.text.util.Rfc822Token;
63import android.text.util.Rfc822Tokenizer;
Mindy Pereira9159cd22011-05-25 17:06:44 -070064import android.util.AttributeSet;
Mindy Pereiracd611952011-06-01 17:02:20 -070065import android.util.Log;
mindyp093ecdd2012-12-14 10:40:51 -080066import android.util.TypedValue;
Mindy Pereirafd68ea62011-06-02 10:40:19 -070067import android.view.ActionMode;
Andy Stadleraa2afff2011-08-04 16:22:47 -070068import android.view.ActionMode.Callback;
Minh Phame51c7222011-10-12 11:33:26 -070069import android.view.DragEvent;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070070import android.view.GestureDetector;
Mindy Pereiracd611952011-06-01 17:02:20 -070071import android.view.KeyEvent;
Mindy Pereira750e6e52011-07-25 11:51:30 -070072import android.view.LayoutInflater;
Mindy Pereirafd68ea62011-06-02 10:40:19 -070073import android.view.Menu;
74import android.view.MenuItem;
Mindy Pereiracd611952011-06-01 17:02:20 -070075import android.view.MotionEvent;
76import android.view.View;
Gilles Debunne61b48cc2011-08-16 14:03:00 -070077import android.view.View.OnClickListener;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -070078import android.view.ViewParent;
Jin Cao04f06ea2014-09-22 14:58:28 -070079import android.view.accessibility.AccessibilityEvent;
80import android.view.accessibility.AccessibilityManager;
Mindy Pereira93364a62012-04-27 14:17:22 -070081import android.view.inputmethod.EditorInfo;
82import android.view.inputmethod.InputConnection;
Mindy Pereiracd611952011-06-01 17:02:20 -070083import android.widget.AdapterView;
84import android.widget.AdapterView.OnItemClickListener;
Tom Taylor80f4abf2012-04-06 13:37:20 -070085import android.widget.Button;
mindyp093ecdd2012-12-14 10:40:51 -080086import android.widget.Filterable;
Mindy Pereira95a69252011-06-17 15:02:03 -070087import android.widget.ListAdapter;
Mindy Pereiracd611952011-06-01 17:02:20 -070088import android.widget.ListPopupWindow;
Mindy Pereira007a76b2011-06-14 11:39:36 -070089import android.widget.ListView;
Mindy Pereira9159cd22011-05-25 17:06:44 -070090import android.widget.MultiAutoCompleteTextView;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -070091import android.widget.ScrollView;
Mindy Pereira750e6e52011-07-25 11:51:30 -070092import android.widget.TextView;
Daisuke Miyakawa7537f842011-05-31 15:47:25 -070093
mindyp16923ee2012-12-10 11:58:29 -080094import com.android.ex.chips.RecipientAlternatesAdapter.RecipientMatchCallback;
Scott Kennedy194d4272013-03-06 22:06:45 -080095import com.android.ex.chips.recipientchip.DrawableRecipientChip;
96import com.android.ex.chips.recipientchip.InvisibleRecipientChip;
Jin Cao6c2a0162014-08-17 15:00:50 -070097import com.android.ex.chips.recipientchip.ReplacementDrawableSpan;
Scott Kennedy194d4272013-03-06 22:06:45 -080098import com.android.ex.chips.recipientchip.VisibleRecipientChip;
Mindy Pereiracd611952011-06-01 17:02:20 -070099
Alon Albert76f1f2d2013-07-14 15:32:49 +0300100import java.util.ArrayList;
101import java.util.Arrays;
Alon Albert76f1f2d2013-07-14 15:32:49 +0300102import java.util.Collections;
103import java.util.Comparator;
Alon Albert76f1f2d2013-07-14 15:32:49 +0300104import java.util.List;
105import java.util.Map;
106import java.util.Set;
107import java.util.regex.Matcher;
108import java.util.regex.Pattern;
109
Mindy Pereira9159cd22011-05-25 17:06:44 -0700110/**
111 * RecipientEditTextView is an auto complete text view for use with applications
112 * that use the new Chips UI for addressing a message to recipients.
113 */
Mindy Pereira95a69252011-06-17 15:02:03 -0700114public class RecipientEditTextView extends MultiAutoCompleteTextView implements
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700115 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
Mindy Pereiraecee50c2011-09-09 16:30:20 -0700116 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
Jin Cao4db8ccc2014-07-30 10:11:07 -0700117 TextView.OnEditorActionListener, DropdownChipLayouter.ChipDeleteListener {
Jin Caoa21fd882014-08-10 13:07:11 -0700118 private static final String TAG = "RecipientEditTextView";
Mindy Pereiracd611952011-06-01 17:02:20 -0700119
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700120 private static final char COMMIT_CHAR_COMMA = ',';
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700121 private static final char COMMIT_CHAR_SEMICOLON = ';';
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700122 private static final char COMMIT_CHAR_SPACE = ' ';
Scott Kennedy03e9e982013-03-04 13:26:22 -0800123 private static final String SEPARATOR = String.valueOf(COMMIT_CHAR_COMMA)
124 + String.valueOf(COMMIT_CHAR_SPACE);
125
Jin Caoa21fd882014-08-10 13:07:11 -0700126 // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
127 // parens, so numbers such as "1 (425) 222-2342" match.
128 private static final Pattern PHONE_PATTERN
129 = Pattern.compile( // sdd = space, dot, or dash
130 "(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
131 + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?" // 1(<digits>)<sdd>*
132 + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
Mindy Pereiracd611952011-06-01 17:02:20 -0700133
Scott Kennedyf11483a2014-04-18 13:36:27 -0700134 private static final int DISMISS = "dismiss".hashCode();
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700135 private static final long DISMISS_DELAY = 300;
136
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700137 // TODO: get correct number/ algorithm from with UX.
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700138 // Visible for testing.
139 /*package*/ static final int CHIP_LIMIT = 2;
140
141 private static final int MAX_CHIPS_PARSED = 50;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700142
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700143 private static int sSelectedTextColor = -1;
Jin Cao14efc572014-09-10 10:27:01 -0700144 private static int sVisibleDisplayFrameTop = -1;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700145
146 // Resources for displaying chips.
Mindy Pereiracd611952011-06-01 17:02:20 -0700147 private Drawable mChipBackground = null;
Mindy Pereiracd611952011-06-01 17:02:20 -0700148 private Drawable mChipDelete = null;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700149 private Drawable mInvalidChipBackground;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700150 private Drawable mChipBackgroundPressed;
151
Jin Caoa21fd882014-08-10 13:07:11 -0700152 // Possible attr overrides
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700153 private float mChipHeight;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700154 private float mChipFontSize;
Mindy Pereiraffd270a2012-05-23 16:11:47 -0700155 private float mLineSpacingExtra;
Jin Cao58d541d2014-07-29 16:23:03 -0700156 private int mChipTextStartPadding;
157 private int mChipTextEndPadding;
Scott Kennedy15259d52014-07-09 17:28:47 -0700158 private final int mTextHeight;
Jin Caoa21fd882014-08-10 13:07:11 -0700159 private boolean mDisableDelete;
160 private int mMaxLines;
Mindy Pereiracd611952011-06-01 17:02:20 -0700161
Kevin Linb10d1c62014-01-24 12:45:00 -0800162 /**
163 * Enumerator for avatar position. See attr.xml for more details.
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800164 * 0 for end, 1 for start.
Kevin Linb10d1c62014-01-24 12:45:00 -0800165 */
166 private int mAvatarPosition;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800167 private static final int AVATAR_POSITION_END = 0;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800168 private static final int AVATAR_POSITION_START = 1;
Kevin Linb10d1c62014-01-24 12:45:00 -0800169
Jin Cao809c5952014-08-08 12:28:17 -0700170 private Paint mWorkPaint = new Paint();
171
Mindy Pereiracd611952011-06-01 17:02:20 -0700172 private Tokenizer mTokenizer;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700173 private Validator mValidator;
Jin Caoa21fd882014-08-10 13:07:11 -0700174 private Handler mHandler;
175 private TextWatcher mTextWatcher;
176 private DropdownChipLayouter mDropdownChipLayouter;
177
Jin Cao93d69f42014-10-07 12:27:49 -0700178 private View mDropdownAnchor = this;
Jin Caoa21fd882014-08-10 13:07:11 -0700179 private ListPopupWindow mAlternatesPopup;
180 private ListPopupWindow mAddressPopup;
181 private View mAlternatePopupAnchor;
182 private OnItemClickListener mAlternatesListener;
Mindy Pereiracd611952011-06-01 17:02:20 -0700183
Scott Kennedy194d4272013-03-06 22:06:45 -0800184 private DrawableRecipientChip mSelectedChip;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700185 private Bitmap mDefaultContactPhoto;
Jin Cao6c2a0162014-08-17 15:00:50 -0700186 private ReplacementDrawableSpan mMoreChip;
Mindy Pereira750e6e52011-07-25 11:51:30 -0700187 private TextView mMoreItem;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700188
Jin Cao04f06ea2014-09-22 14:58:28 -0700189 private boolean mIsAccessibilityOn;
Jin Caob1aeb7b2014-09-01 23:48:05 -0700190 private int mCurrentSuggestionCount;
191
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800192 // VisibleForTesting
193 final ArrayList<String> mPendingChips = new ArrayList<String>();
Mindy Pereiraf97eb412011-06-24 11:26:20 -0700194
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700195 private int mPendingChipsCount = 0;
Jin Caoa21fd882014-08-10 13:07:11 -0700196 private int mCheckedItem;
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700197 private boolean mNoChips = false;
Jin Caoa21fd882014-08-10 13:07:11 -0700198 private boolean mShouldShrink = true;
Jin Cao4de6a532014-08-08 11:34:10 -0700199
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800200 // VisibleForTesting
Scott Kennedy194d4272013-03-06 22:06:45 -0800201 ArrayList<DrawableRecipientChip> mTemporaryRecipients;
Mindy Pereira18529312011-06-28 11:00:52 -0700202
Scott Kennedy194d4272013-03-06 22:06:45 -0800203 private ArrayList<DrawableRecipientChip> mRemovedSpans;
Mindy Pereira3bb52162011-07-01 14:52:22 -0700204
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700205 // Chip copy fields.
206 private GestureDetector mGestureDetector;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700207 private Dialog mCopyDialog;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700208 private String mCopyAddress;
209
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700210 // Obtain the enclosing scroll view, if it exists, so that the view can be
211 // scrolled to show the last line of chips content.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700212 private ScrollView mScrollView;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700213 private boolean mTriedGettingScrollView;
Minh Phame51c7222011-10-12 11:33:26 -0700214 private boolean mDragEnabled = false;
215
Jin Caoa21fd882014-08-10 13:07:11 -0700216 private boolean mAttachedToWindow;
Tom Taylor4491a062012-11-15 13:57:41 -0800217
Mindy Pereira79fb4362011-06-21 14:37:07 -0700218 private final Runnable mAddTextWatcher = new Runnable() {
219 @Override
220 public void run() {
221 if (mTextWatcher == null) {
222 mTextWatcher = new RecipientTextWatcher();
223 addTextChangedListener(mTextWatcher);
224 }
225 }
226 };
227
Mindy Pereira18529312011-06-28 11:00:52 -0700228 private IndividualReplacementTask mIndividualReplacements;
229
Mindy Pereira2cac2312011-07-20 11:38:59 -0700230 private Runnable mHandlePendingChips = new Runnable() {
231
232 @Override
233 public void run() {
234 handlePendingChips();
Mindy Pereira2cac2312011-07-20 11:38:59 -0700235 }
236
237 };
238
Mindy Pereirad7192502011-09-22 08:04:45 -0700239 private Runnable mDelayedShrink = new Runnable() {
240
241 @Override
242 public void run() {
243 shrink();
244 }
245
246 };
247
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700248 private RecipientEntryItemClickedListener mRecipientEntryItemClickedListener;
249
250 public interface RecipientEntryItemClickedListener {
251 /**
252 * Callback that occurs whenever an auto-complete suggestion is clicked.
253 * @param charactersTyped the number of characters typed by the user to provide the
254 * auto-complete suggestions.
255 * @param position the position in the dropdown list that the user clicked
256 */
257 void onRecipientEntryItemClicked(int charactersTyped, int position);
258 }
259
Mindy Pereira9159cd22011-05-25 17:06:44 -0700260 public RecipientEditTextView(Context context, AttributeSet attrs) {
261 super(context, attrs);
Mindy Pereira22faaa62011-12-16 14:30:34 -0800262 setChipDimensions(context, attrs);
Scott Kennedy15259d52014-07-09 17:28:47 -0700263 mTextHeight = calculateTextHeight();
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700264 if (sSelectedTextColor == -1) {
265 sSelectedTextColor = context.getResources().getColor(android.R.color.white);
266 }
Mindy Pereira95a69252011-06-17 15:02:03 -0700267 mAlternatesPopup = new ListPopupWindow(context);
Jin Caoa21fd882014-08-10 13:07:11 -0700268 mAlternatesPopup.setBackgroundDrawable(null);
Mindy Pereira01382d72011-07-15 16:52:32 -0700269 mAddressPopup = new ListPopupWindow(context);
Jin Caoa21fd882014-08-10 13:07:11 -0700270 mAddressPopup.setBackgroundDrawable(null);
Mindy Pereirabfedc1e2011-09-07 12:17:12 -0700271 mCopyDialog = new Dialog(context);
Mindy Pereira95a69252011-06-17 15:02:03 -0700272 mAlternatesListener = new OnItemClickListener() {
273 @Override
274 public void onItemClick(AdapterView<?> adapterView,View view, int position,
275 long rowId) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700276 mAlternatesPopup.setOnItemClickListener(null);
Mindy Pereira95a69252011-06-17 15:02:03 -0700277 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
278 .getRecipientEntry(position));
279 Message delayed = Message.obtain(mHandler, DISMISS);
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700280 delayed.obj = mAlternatesPopup;
Mindy Pereira95a69252011-06-17 15:02:03 -0700281 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
282 clearComposingText();
283 }
284 };
Mindy Pereirae1bfc922011-08-16 14:00:01 -0700285 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
Mindy Pereirab88ee452011-06-02 11:07:43 -0700286 setOnItemClickListener(this);
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700287 setCustomSelectionActionModeCallback(this);
Mindy Pereira007a76b2011-06-14 11:39:36 -0700288 mHandler = new Handler() {
289 @Override
290 public void handleMessage(Message msg) {
291 if (msg.what == DISMISS) {
Mindy Pereira95a69252011-06-17 15:02:03 -0700292 ((ListPopupWindow) msg.obj).dismiss();
Mindy Pereira007a76b2011-06-14 11:39:36 -0700293 return;
294 }
295 super.handleMessage(msg);
296 }
297 };
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700298 mTextWatcher = new RecipientTextWatcher();
299 addTextChangedListener(mTextWatcher);
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700300 mGestureDetector = new GestureDetector(context, this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700301 setOnEditorActionListener(this);
Kevin Linb10d1c62014-01-24 12:45:00 -0800302
Jin Caoa20a8d02014-08-06 17:41:49 -0700303 setDropdownChipLayouter(new DropdownChipLayouter(LayoutInflater.from(context), context));
Kevin Linb10d1c62014-01-24 12:45:00 -0800304 }
305
Jin Cao04f06ea2014-09-22 14:58:28 -0700306 @Override
307 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
308 super.onLayout(changed, left, top, right, bottom);
309
310 final AccessibilityManager accessibilityManager =
311 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
312 mIsAccessibilityOn = accessibilityManager.isEnabled();
313 }
314
Scott Kennedy15259d52014-07-09 17:28:47 -0700315 private int calculateTextHeight() {
316 final Rect textBounds = new Rect();
317 final TextPaint paint = getPaint();
318
319 textBounds.setEmpty();
320 // First measure the bounds of a sample text.
321 final String textHeightSample = "a";
322 paint.getTextBounds(textHeightSample, 0, textHeightSample.length(), textBounds);
323
324 textBounds.left = 0;
325 textBounds.right = 0;
326
327 return textBounds.height();
328 }
329
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -0700330 public void setDropdownChipLayouter(DropdownChipLayouter dropdownChipLayouter) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800331 mDropdownChipLayouter = dropdownChipLayouter;
Jin Caoa20a8d02014-08-06 17:41:49 -0700332 mDropdownChipLayouter.setDeleteListener(this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700333 }
334
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700335 public void setRecipientEntryItemClickedListener(RecipientEntryItemClickedListener listener) {
336 mRecipientEntryItemClickedListener = listener;
337 }
338
Mindy Pereira93364a62012-04-27 14:17:22 -0700339 @Override
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700340 protected void onDetachedFromWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700341 super.onDetachedFromWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700342 mAttachedToWindow = false;
Jin Cao808d7132014-08-24 11:13:02 -0700343 dismissPopups();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700344 }
345
346 @Override
347 protected void onAttachedToWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700348 super.onAttachedToWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700349 mAttachedToWindow = true;
Jin Cao93d69f42014-10-07 12:27:49 -0700350
351 final int anchorId = getDropDownAnchor();
352 if (anchorId != View.NO_ID) {
353 mDropdownAnchor = getRootView().findViewById(anchorId);
354 }
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700355 }
356
357 @Override
Mindy Pereira93364a62012-04-27 14:17:22 -0700358 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
359 if (action == EditorInfo.IME_ACTION_DONE) {
360 if (commitDefault()) {
361 return true;
362 }
363 if (mSelectedChip != null) {
364 clearSelectedChip();
365 return true;
366 } else if (focusNext()) {
367 return true;
368 }
369 }
370 return false;
371 }
372
373 @Override
374 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
375 InputConnection connection = super.onCreateInputConnection(outAttrs);
376 int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
377 if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
378 // clear the existing action
379 outAttrs.imeOptions ^= imeActions;
380 // set the DONE action
381 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
382 }
383 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
384 outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
385 }
Scott Kennedy1af243f2013-01-29 23:38:43 -0800386
387 outAttrs.actionId = EditorInfo.IME_ACTION_DONE;
Kaikai Wanga5461b72014-09-18 17:38:46 -0700388
389 // Custom action labels are discouraged in L; a checkmark icon is shown in place of the
390 // custom text in this case.
391 outAttrs.actionLabel = Build.VERSION.SDK_INT >= Build.VERSION_CODES.L ? null :
392 getContext().getString(R.string.action_label);
Mindy Pereira93364a62012-04-27 14:17:22 -0700393 return connection;
Erike33555f2011-06-21 14:20:20 -0700394 }
Mindy Pereira7afe1602011-06-20 10:53:52 -0700395
Scott Kennedy194d4272013-03-06 22:06:45 -0800396 /*package*/ DrawableRecipientChip getLastChip() {
397 DrawableRecipientChip last = null;
398 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700399 if (chips != null && chips.length > 0) {
400 last = chips[chips.length - 1];
Erike33555f2011-06-21 14:20:20 -0700401 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700402 return last;
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700403 }
404
Ken Thai1248e532014-05-01 09:05:02 -0700405 /**
406 * @return The list of {@link RecipientEntry}s that have been selected by the user.
407 */
408 public List<RecipientEntry> getSelectedRecipients() {
409 DrawableRecipientChip[] chips =
410 getText().getSpans(0, getText().length(), DrawableRecipientChip.class);
411 List<RecipientEntry> results = new ArrayList();
412 if (chips == null) {
413 return results;
414 }
415
416 for (DrawableRecipientChip c : chips) {
417 results.add(c.getEntry());
418 }
419
420 return results;
421 }
422
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700423 @Override
424 public void onSelectionChanged(int start, int end) {
425 // When selection changes, see if it is inside the chips area.
426 // If so, move the cursor back after the chips again.
Scott Kennedy194d4272013-03-06 22:06:45 -0800427 DrawableRecipientChip last = getLastChip();
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700428 if (last != null && start < getSpannable().getSpanEnd(last)) {
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700429 // Grab the last chip and set the cursor to after it.
430 setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length()));
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700431 }
Mindy Pereira05dbd332011-06-03 09:37:44 -0700432 super.onSelectionChanged(start, end);
433 }
434
Mindy Pereiradc04cd72011-09-16 15:42:09 -0700435 @Override
436 public void onRestoreInstanceState(Parcelable state) {
437 if (!TextUtils.isEmpty(getText())) {
438 super.onRestoreInstanceState(null);
439 } else {
440 super.onRestoreInstanceState(state);
441 }
442 }
443
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700444 @Override
Mindy Pereiradaa640c2011-10-03 14:18:30 -0700445 public Parcelable onSaveInstanceState() {
446 // If the user changes orientation while they are editing, just roll back the selection.
447 clearSelectedChip();
448 return super.onSaveInstanceState();
449 }
450
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700451 /**
452 * Convenience method: Append the specified text slice to the TextView's
453 * display buffer, upgrading it to BufferType.EDITABLE if it was
454 * not already editable. Commas are excluded as they are added automatically
455 * by the view.
456 */
457 @Override
458 public void append(CharSequence text, int start, int end) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700459 // We don't care about watching text changes while appending.
460 if (mTextWatcher != null) {
461 removeTextChangedListener(mTextWatcher);
462 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700463 super.append(text, start, end);
464 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
mindyp01244682012-08-27 10:32:17 -0700465 String displayString = text.toString();
Scott Kennedy03e9e982013-03-04 13:26:22 -0800466
467 if (!displayString.trim().endsWith(String.valueOf(COMMIT_CHAR_COMMA))) {
468 // We have no separator, so we should add it
469 super.append(SEPARATOR, 0, SEPARATOR.length());
470 displayString += SEPARATOR;
mindyp01244682012-08-27 10:32:17 -0700471 }
Scott Kennedy03e9e982013-03-04 13:26:22 -0800472
mindyp20d7af72012-09-10 15:47:40 -0700473 if (!TextUtils.isEmpty(displayString)
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700474 && TextUtils.getTrimmedLength(displayString) > 0) {
475 mPendingChipsCount++;
Scott Kennedy03e9e982013-03-04 13:26:22 -0800476 mPendingChips.add(displayString);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700477 }
478 }
mindypabb864d2012-09-10 12:06:35 -0700479 // Put a message on the queue to make sure we ALWAYS handle pending
480 // chips.
Mindy Pereira2cac2312011-07-20 11:38:59 -0700481 if (mPendingChipsCount > 0) {
482 postHandlePendingChips();
483 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700484 mHandler.post(mAddTextWatcher);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700485 }
486
Mindy Pereira05dbd332011-06-03 09:37:44 -0700487 @Override
488 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700489 super.onFocusChanged(hasFocus, direction, previous);
Mindy Pereira05dbd332011-06-03 09:37:44 -0700490 if (!hasFocus) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700491 shrink();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700492 } else {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700493 expand();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700494 }
Mindy Pereira9159cd22011-05-25 17:06:44 -0700495 }
496
Jin Cao14efc572014-09-10 10:27:01 -0700497 // sVisibleDisplayFrameTop is computed on a on-demand basis because the view needs to be fully
498 // measured and created in order to calculate the visible display frame.
499 private int getVisibleDisplayFrameTop() {
500 if (sVisibleDisplayFrameTop == -1) {
501 final TypedValue tv = new TypedValue();
502 final Context context = getContext();
503 // Visible top is our visible display (due to status bar) plus the height of action bar.
504 if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
505 sVisibleDisplayFrameTop = TypedValue.complexToDimensionPixelSize(tv.data,
506 getResources().getDisplayMetrics());
507 }
508 // Compute the status bar height, or rather where our visible display starts
509 if (context instanceof Activity) {
510 final Rect visibleRect = new Rect();
511 ((Activity) context).getWindow().getDecorView()
512 .getWindowVisibleDisplayFrame(visibleRect);
513 sVisibleDisplayFrameTop += visibleRect.top;
514 }
mindyp093ecdd2012-12-14 10:40:51 -0800515 }
Jin Cao14efc572014-09-10 10:27:01 -0700516 return sVisibleDisplayFrameTop;
mindyp093ecdd2012-12-14 10:40:51 -0800517 }
518
Alice Yang6b7110f2013-04-26 12:50:35 -0700519 @Override
mindyp093ecdd2012-12-14 10:40:51 -0800520 public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
521 super.setAdapter(adapter);
Kevin Linb10d1c62014-01-24 12:45:00 -0800522 BaseRecipientAdapter baseAdapter = (BaseRecipientAdapter) adapter;
523 baseAdapter.registerUpdateObserver(new BaseRecipientAdapter.EntriesUpdatedObserver() {
524 @Override
525 public void onChanged(List<RecipientEntry> entries) {
526 // Scroll the chips field to the top of the screen so
527 // that the user can see as many results as possible.
528 if (entries != null && entries.size() > 0) {
529 scrollBottomIntoView();
Jin Caob1aeb7b2014-09-01 23:48:05 -0700530 // Here the current suggestion count is still the old one since we update
531 // the count at the bottom of this function.
532 if (mCurrentSuggestionCount == 0) {
533 // Announce the new number of possible choices for accessibility.
Jin Cao04f06ea2014-09-22 14:58:28 -0700534 announceForAccessibilityCompat(getContext().getString(
Jin Caob1aeb7b2014-09-01 23:48:05 -0700535 R.string.accessbility_suggestion_dropdown_opened));
536 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800537 }
Jin Cao93d69f42014-10-07 12:27:49 -0700538
539 // Set the dropdown height to be the remaining height from the anchor to the bottom.
Jin Caobd312312014-09-12 15:57:08 -0700540 final int[] coords = new int[2];
Jin Cao93d69f42014-10-07 12:27:49 -0700541 mDropdownAnchor.getLocationInWindow(coords);
Jin Caobd312312014-09-12 15:57:08 -0700542 final Rect displayFrame = new Rect();
543 getWindowVisibleDisplayFrame(displayFrame);
Jin Cao93d69f42014-10-07 12:27:49 -0700544 setDropDownHeight(displayFrame.bottom - coords[1] - mDropdownAnchor.getHeight());
Jin Caob1aeb7b2014-09-01 23:48:05 -0700545
546 mCurrentSuggestionCount = entries == null ? 0 : entries.size();
Kevin Linb10d1c62014-01-24 12:45:00 -0800547 }
548 });
549 baseAdapter.setDropdownChipLayouter(mDropdownChipLayouter);
mindyp093ecdd2012-12-14 10:40:51 -0800550 }
551
Jin Cao04f06ea2014-09-22 14:58:28 -0700552 private void announceForAccessibilityCompat(String text) {
553 if (mIsAccessibilityOn && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
554 final ViewParent parent = getParent();
555 if (parent != null) {
556 AccessibilityEvent event = AccessibilityEvent.obtain(
557 AccessibilityEvent.TYPE_ANNOUNCEMENT);
558 onInitializeAccessibilityEvent(event);
559 event.getText().add(text);
560 event.setContentDescription(null);
561 parent.requestSendAccessibilityEvent(this, event);
562 }
563 }
564 }
565
Kevin Lin53e718a2014-02-04 17:40:33 -0800566 protected void scrollBottomIntoView() {
mindyp093ecdd2012-12-14 10:40:51 -0800567 if (mScrollView != null && mShouldShrink) {
Jin Cao14efc572014-09-10 10:27:01 -0700568 final int[] location = new int[2];
569 getLocationInWindow(location);
mindyp093ecdd2012-12-14 10:40:51 -0800570 // Desired position shows at least 1 line of chips below the action
571 // bar. We add excess padding to make sure this is always below other
572 // content.
Jin Cao14efc572014-09-10 10:27:01 -0700573 final int height = getHeight();
574 final int currentPos = location[1] + height;
575 final int desiredPos = getVisibleDisplayFrameTop() + height / getLineCount();
mindyp093ecdd2012-12-14 10:40:51 -0800576 if (currentPos > desiredPos) {
577 mScrollView.scrollBy(0, currentPos - desiredPos);
578 }
579 }
580 }
581
Kevin Lin53e718a2014-02-04 17:40:33 -0800582 protected ScrollView getScrollView() {
Scott Kennedy7a4e6772013-11-21 14:31:33 -0800583 return mScrollView;
Kevin Lin53e718a2014-02-04 17:40:33 -0800584 }
585
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700586 @Override
587 public void performValidation() {
588 // Do nothing. Chips handles its own validation.
589 }
590
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700591 private void shrink() {
Mindy Pereira5c125af2011-12-13 11:04:13 -0800592 if (mTokenizer == null) {
593 return;
594 }
mindyp5e60c2b2012-11-06 17:47:40 -0800595 long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1;
596 if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT
597 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700598 clearSelectedChip();
599 } else {
Mindy Pereirad7192502011-09-22 08:04:45 -0700600 if (getWidth() <= 0) {
601 // We don't have the width yet which means the view hasn't been drawn yet
602 // and there is no reason to attempt to commit chips yet.
603 // This focus lost must be the result of an orientation change
604 // or an initial rendering.
605 // Re-post the shrink for later.
606 mHandler.removeCallbacks(mDelayedShrink);
607 mHandler.post(mDelayedShrink);
608 return;
609 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700610 // Reset any pending chips as they would have been handled
611 // when the field lost focus.
612 if (mPendingChipsCount > 0) {
Mindy Pereira2cac2312011-07-20 11:38:59 -0700613 postHandlePendingChips();
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700614 } else {
615 Editable editable = getText();
616 int end = getSelectionEnd();
617 int start = mTokenizer.findTokenStart(editable, end);
Scott Kennedy194d4272013-03-06 22:06:45 -0800618 DrawableRecipientChip[] chips =
619 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700620 if ((chips == null || chips.length == 0)) {
Mindy Pereirad7192502011-09-22 08:04:45 -0700621 Editable text = getText();
622 int whatEnd = mTokenizer.findTokenEnd(text, start);
623 // This token was already tokenized, so skip past the ending token.
Mindy Pereira448e90b2011-09-22 11:49:32 -0700624 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') {
mindyp4f82d882012-11-08 16:30:27 -0800625 whatEnd = movePastTerminators(whatEnd);
Mindy Pereirad7192502011-09-22 08:04:45 -0700626 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700627 // In the middle of chip; treat this as an edit
628 // and commit the whole token.
Mindy Pereirad7192502011-09-22 08:04:45 -0700629 int selEnd = getSelectionEnd();
Mindy Pereira63372312011-11-15 15:23:07 -0800630 if (whatEnd != selEnd) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700631 handleEdit(start, whatEnd);
632 } else {
633 commitChip(start, end, editable);
634 }
635 }
Mindy Pereiraa74f40d2011-07-12 09:07:17 -0700636 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700637 mHandler.post(mAddTextWatcher);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700638 }
Mindy Pereira3bb52162011-07-01 14:52:22 -0700639 createMoreChip();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700640 }
641
642 private void expand() {
mindyp374ccb22012-11-06 10:54:05 -0800643 if (mShouldShrink) {
644 setMaxLines(Integer.MAX_VALUE);
645 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700646 removeMoreChip();
647 setCursorVisible(true);
648 Editable text = getText();
649 setSelection(text != null && text.length() > 0 ? text.length() : 0);
Mindy Pereira18529312011-06-28 11:00:52 -0700650 // If there are any temporary chips, try replacing them now that the user
651 // has expanded the field.
652 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
653 new RecipientReplacementTask().execute();
654 mTemporaryRecipients = null;
655 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700656 }
657
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700658 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700659 paint.setTextSize(mChipFontSize);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700660 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
661 Log.d(TAG, "Max width is negative: " + maxWidth);
662 }
663 return TextUtils.ellipsize(text, paint, maxWidth,
664 TextUtils.TruncateAt.END);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700665 }
666
Kevin Linb10d1c62014-01-24 12:45:00 -0800667 /**
668 * Creates a bitmap of the given contact on a selected chip.
669 *
670 * @param contact The recipient entry to pull data from.
671 * @param paint The paint to use to draw the bitmap.
672 */
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800673 private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800674 paint.setColor(sSelectedTextColor);
Jin Cao35e82d42014-06-02 17:21:21 -0700675 final ChipBitmapContainer bitmapContainer = createChipBitmap(contact, paint,
Jin Cao33515e72014-08-05 21:13:27 -0700676 mChipBackgroundPressed, getResources().getColor(R.color.chip_background_selected));
Jin Cao35e82d42014-06-02 17:21:21 -0700677
678 if (bitmapContainer.loadIcon) {
Jin Cao809c5952014-08-08 12:28:17 -0700679 loadAvatarIcon(contact, bitmapContainer);
Mindy Pereiracd611952011-06-01 17:02:20 -0700680 }
Jin Cao35e82d42014-06-02 17:21:21 -0700681
682 return bitmapContainer.bitmap;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700683 }
684
Kevin Linb10d1c62014-01-24 12:45:00 -0800685 /**
686 * Creates a bitmap of the given contact on a selected chip.
687 *
688 * @param contact The recipient entry to pull data from.
689 * @param paint The paint to use to draw the bitmap.
690 */
Andrew Sapperstein1db635b2014-04-29 13:07:57 -0700691 private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800692 paint.setColor(getContext().getResources().getColor(android.R.color.black));
Jin Cao33515e72014-08-05 21:13:27 -0700693 ChipBitmapContainer bitmapContainer = createChipBitmap(contact, paint,
694 getChipBackground(contact), getDefaultChipBackgroundColor(contact));
Jin Cao35e82d42014-06-02 17:21:21 -0700695
696 if (bitmapContainer.loadIcon) {
Jin Cao809c5952014-08-08 12:28:17 -0700697 loadAvatarIcon(contact, bitmapContainer);
Jin Cao35e82d42014-06-02 17:21:21 -0700698 }
699 return bitmapContainer.bitmap;
Kevin Linb10d1c62014-01-24 12:45:00 -0800700 }
701
Jin Cao35e82d42014-06-02 17:21:21 -0700702 private ChipBitmapContainer createChipBitmap(RecipientEntry contact, TextPaint paint,
Jin Cao33515e72014-08-05 21:13:27 -0700703 Drawable overrideBackgroundDrawable, int backgroundColor) {
Jin Cao35e82d42014-06-02 17:21:21 -0700704 final ChipBitmapContainer result = new ChipBitmapContainer();
705
Kevin Linb10d1c62014-01-24 12:45:00 -0800706 Rect backgroundPadding = new Rect();
Jin Cao33515e72014-08-05 21:13:27 -0700707 if (overrideBackgroundDrawable != null) {
708 overrideBackgroundDrawable.getPadding(backgroundPadding);
709 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800710
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700711 // Ellipsize the text so that it takes AT MOST the entire width of the
712 // autocomplete text entry area. Make sure to leave space for padding
713 // on the sides.
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700714 int height = (int) mChipHeight;
Kevin Linb10d1c62014-01-24 12:45:00 -0800715 // Since the icon is a square, it's width is equal to the maximum height it can be inside
Jin Cao33515e72014-08-05 21:13:27 -0700716 // the chip. Don't include iconWidth for invalid contacts.
717 int iconWidth = contact.isValid() ?
718 height - backgroundPadding.top - backgroundPadding.bottom : 0;
Mindy Pereira6ed7ded2011-10-14 16:31:31 -0700719 float[] widths = new float[1];
720 paint.getTextWidths(" ", widths);
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700721 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
Kevin Lin9b398e32014-02-26 12:29:10 -0800722 calculateAvailableWidth() - iconWidth - widths[0] - backgroundPadding.left
Jin Cao33515e72014-08-05 21:13:27 -0700723 - backgroundPadding.right);
Kevin Linb10d1c62014-01-24 12:45:00 -0800724 int textWidth = (int) paint.measureText(ellipsizedText, 0, ellipsizedText.length());
725
Jin Cao33515e72014-08-05 21:13:27 -0700726 // Chip start padding is the same as the end padding if there is no contact image.
727 final int startPadding = contact.isValid() ? mChipTextStartPadding : mChipTextEndPadding;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700728 // Make sure there is a minimum chip width so the user can ALWAYS
729 // tap a chip without difficulty.
Jin Cao33515e72014-08-05 21:13:27 -0700730 int width = Math.max(iconWidth * 2, textWidth + startPadding + mChipTextEndPadding
Jin Cao58d541d2014-07-29 16:23:03 -0700731 + iconWidth + backgroundPadding.left + backgroundPadding.right);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700732
733 // Create the background of the chip.
Jin Cao35e82d42014-06-02 17:21:21 -0700734 result.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
735 final Canvas canvas = new Canvas(result.bitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700736
Jin Cao33515e72014-08-05 21:13:27 -0700737 // Check if the background drawable is set via attr
738 if (overrideBackgroundDrawable != null) {
739 overrideBackgroundDrawable.setBounds(0, 0, width, height);
740 overrideBackgroundDrawable.draw(canvas);
741 } else {
742 // Draw the default chip background
Jin Cao6c2a0162014-08-17 15:00:50 -0700743 mWorkPaint.reset();
744 mWorkPaint.setColor(backgroundColor);
Jin Cao568fb222014-08-19 13:50:59 -0700745 mWorkPaint.setAntiAlias(true);
Jin Cao33515e72014-08-05 21:13:27 -0700746 final float radius = height / 2;
747 canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius,
Jin Cao6c2a0162014-08-17 15:00:50 -0700748 mWorkPaint);
Jin Cao33515e72014-08-05 21:13:27 -0700749 }
750
Kevin Linb10d1c62014-01-24 12:45:00 -0800751 // Draw the text vertically aligned
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800752 int textX = shouldPositionAvatarOnRight() ?
Jin Cao58d541d2014-07-29 16:23:03 -0700753 mChipTextEndPadding + backgroundPadding.left :
754 width - backgroundPadding.right - mChipTextEndPadding - textWidth;
Kevin Linb10d1c62014-01-24 12:45:00 -0800755 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(),
Scott Kennedy15259d52014-07-09 17:28:47 -0700756 textX, getTextYOffset(height), paint);
Jin Cao35e82d42014-06-02 17:21:21 -0700757
758 // Set the variables that are needed to draw the icon bitmap once it's loaded
759 int iconX = shouldPositionAvatarOnRight() ? width - backgroundPadding.right - iconWidth :
760 backgroundPadding.left;
761 result.left = iconX;
762 result.top = backgroundPadding.top;
763 result.right = iconX + iconWidth;
764 result.bottom = height - backgroundPadding.bottom;
765
766 return result;
767 }
768
769 /**
770 * Helper function that draws the loaded icon bitmap into the chips bitmap
771 */
Jin Cao809c5952014-08-08 12:28:17 -0700772 private void drawIcon(ChipBitmapContainer bitMapResult, Bitmap icon) {
Jin Cao35e82d42014-06-02 17:21:21 -0700773 final Canvas canvas = new Canvas(bitMapResult.bitmap);
774 final RectF src = new RectF(0, 0, icon.getWidth(), icon.getHeight());
775 final RectF dst = new RectF(bitMapResult.left, bitMapResult.top, bitMapResult.right,
776 bitMapResult.bottom);
Jin Cao809c5952014-08-08 12:28:17 -0700777 drawIconOnCanvas(icon, canvas, src, dst);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700778 }
779
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700780 /**
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800781 * Returns true if the avatar should be positioned at the right edge of the chip.
782 * Takes into account both the set avatar position (start or end) as well as whether
783 * the layout direction is LTR or RTL.
784 */
785 private boolean shouldPositionAvatarOnRight() {
786 final boolean isRtl = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ?
787 getLayoutDirection() == LAYOUT_DIRECTION_RTL : false;
788 final boolean assignedPosition = mAvatarPosition == AVATAR_POSITION_END;
789 // If in Rtl mode, the position should be flipped.
790 return isRtl ? !assignedPosition : assignedPosition;
791 }
792
793 /**
Kevin Linb10d1c62014-01-24 12:45:00 -0800794 * Returns the avatar icon to use for this recipient entry. Returns null if we don't want to
795 * draw an icon for this recipient.
796 */
Jin Cao35e82d42014-06-02 17:21:21 -0700797 private void loadAvatarIcon(final RecipientEntry contact,
Jin Cao809c5952014-08-08 12:28:17 -0700798 final ChipBitmapContainer bitmapContainer) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800799 // Don't draw photos for recipients that have been typed in OR generated on the fly.
800 long contactId = contact.getContactId();
801 boolean drawPhotos = isPhoneQuery() ?
802 contactId != RecipientEntry.INVALID_CONTACT
803 : (contactId != RecipientEntry.INVALID_CONTACT
Jin Caobf84bd82014-07-31 10:59:27 -0700804 && contactId != RecipientEntry.GENERATED_CONTACT);
Kevin Linb10d1c62014-01-24 12:45:00 -0800805
806 if (drawPhotos) {
Jin Cao35e82d42014-06-02 17:21:21 -0700807 final byte[] origPhotoBytes = contact.getPhotoBytes();
Kevin Linb10d1c62014-01-24 12:45:00 -0800808 // There may not be a photo yet if anything but the first contact address
809 // was selected.
Jin Cao82d38852014-06-03 10:53:46 -0700810 if (origPhotoBytes == null) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800811 // TODO: cache this in the recipient entry?
Jin Cao35e82d42014-06-02 17:21:21 -0700812 getAdapter().fetchPhoto(contact, new PhotoManager.PhotoManagerCallback() {
Jin Cao52e48142014-06-04 18:01:20 -0700813 @Override
Andrew Sapperstein50429c52014-06-12 15:12:10 -0700814 public void onPhotoBytesPopulated() {
815 // Call through to the async version which will ensure
816 // proper threading.
817 onPhotoBytesAsynchronouslyPopulated();
818 }
819
820 @Override
Jin Cao52e48142014-06-04 18:01:20 -0700821 public void onPhotoBytesAsynchronouslyPopulated() {
822 final byte[] loadedPhotoBytes = contact.getPhotoBytes();
823 final Bitmap icon = BitmapFactory.decodeByteArray(loadedPhotoBytes, 0,
824 loadedPhotoBytes.length);
825 tryDrawAndInvalidate(icon);
826 }
Jin Cao0efdc532014-06-04 15:35:16 -0700827
Jin Cao52e48142014-06-04 18:01:20 -0700828 @Override
829 public void onPhotoBytesAsyncLoadFailed() {
830 // TODO: can the scaled down default photo be cached?
831 tryDrawAndInvalidate(mDefaultContactPhoto);
832 }
833
834 private void tryDrawAndInvalidate(Bitmap icon) {
Jin Cao809c5952014-08-08 12:28:17 -0700835 drawIcon(bitmapContainer, icon);
Jin Cao52e48142014-06-04 18:01:20 -0700836 // The caller might originated from a background task. However, if the
837 // background task has already completed, the view might be already drawn
838 // on the UI but the callback would happen on the background thread.
839 // So if we are on a background thread, post an invalidate call to the UI.
840 if (Looper.myLooper() == Looper.getMainLooper()) {
841 // The view might not redraw itself since it's loaded asynchronously
Jin Cao0efdc532014-06-04 15:35:16 -0700842 invalidate();
Jin Cao52e48142014-06-04 18:01:20 -0700843 } else {
844 post(new Runnable() {
845 @Override
846 public void run() {
847 invalidate();
848 }
849 });
Jin Cao0efdc532014-06-04 15:35:16 -0700850 }
Jin Cao52e48142014-06-04 18:01:20 -0700851 }
Jin Cao35e82d42014-06-02 17:21:21 -0700852 });
Kevin Linb10d1c62014-01-24 12:45:00 -0800853 } else {
Jin Cao35e82d42014-06-02 17:21:21 -0700854 final Bitmap icon = BitmapFactory.decodeByteArray(origPhotoBytes, 0,
855 origPhotoBytes.length);
Jin Cao809c5952014-08-08 12:28:17 -0700856 drawIcon(bitmapContainer, icon);
Kevin Linb10d1c62014-01-24 12:45:00 -0800857 }
858 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800859 }
860
861 /**
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700862 * Get the background drawable for a RecipientChip.
863 */
864 // Visible for testing.
mindypf30a4282012-12-03 12:16:33 -0800865 /* package */Drawable getChipBackground(RecipientEntry contact) {
866 return contact.isValid() ? mChipBackground : mInvalidChipBackground;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700867 }
868
Jin Cao33515e72014-08-05 21:13:27 -0700869 private int getDefaultChipBackgroundColor(RecipientEntry contact) {
870 return getResources().getColor(contact.isValid() ? R.color.chip_background :
871 R.color.chip_background_invalid);
872 }
873
Kevin Linb10d1c62014-01-24 12:45:00 -0800874 /**
875 * Given a height, returns a Y offset that will draw the text in the middle of the height.
876 */
Scott Kennedy15259d52014-07-09 17:28:47 -0700877 protected float getTextYOffset(int height) {
878 return height - ((height - mTextHeight) / 2);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700879 }
880
Kevin Linb10d1c62014-01-24 12:45:00 -0800881 /**
Scott Kennedyb8985b72014-01-28 16:36:19 -0800882 * Draws the icon onto the canvas given the source rectangle of the bitmap and the destination
Kevin Linb10d1c62014-01-24 12:45:00 -0800883 * rectangle of the canvas.
884 */
Jin Cao809c5952014-08-08 12:28:17 -0700885 protected void drawIconOnCanvas(Bitmap icon, Canvas canvas, RectF src, RectF dst) {
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700886 final Matrix matrix = new Matrix();
887
888 // Draw bitmap through shader first.
889 final BitmapShader shader = new BitmapShader(icon, TileMode.CLAMP, TileMode.CLAMP);
890 matrix.reset();
891
892 // Fit bitmap to bounds.
Kevin Linb10d1c62014-01-24 12:45:00 -0800893 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700894
895 shader.setLocalMatrix(matrix);
Jin Cao809c5952014-08-08 12:28:17 -0700896 mWorkPaint.reset();
897 mWorkPaint.setShader(shader);
898 mWorkPaint.setAntiAlias(true);
899 mWorkPaint.setFilterBitmap(true);
900 mWorkPaint.setDither(true);
901 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f, mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700902
903 // Then draw the border.
904 final float borderWidth = 1f;
Jin Cao809c5952014-08-08 12:28:17 -0700905 mWorkPaint.reset();
906 mWorkPaint.setColor(Color.TRANSPARENT);
907 mWorkPaint.setStyle(Style.STROKE);
908 mWorkPaint.setStrokeWidth(borderWidth);
909 mWorkPaint.setAntiAlias(true);
910 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f - borderWidth / 2, mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700911
Jin Cao809c5952014-08-08 12:28:17 -0700912 mWorkPaint.reset();
Kevin Linb10d1c62014-01-24 12:45:00 -0800913 }
914
Jin Cao33515e72014-08-05 21:13:27 -0700915 private DrawableRecipientChip constructChipSpan(RecipientEntry contact, boolean pressed) {
Mindy Pereiracd611952011-06-01 17:02:20 -0700916 TextPaint paint = getPaint();
917 float defaultSize = paint.getTextSize();
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700918 int defaultColor = paint.getColor();
Mindy Pereiracd611952011-06-01 17:02:20 -0700919
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700920 Bitmap tmpBitmap;
Mindy Pereiracd611952011-06-01 17:02:20 -0700921 if (pressed) {
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800922 tmpBitmap = createSelectedChip(contact, paint);
Mindy Pereiracd611952011-06-01 17:02:20 -0700923
Mindy Pereiracd611952011-06-01 17:02:20 -0700924 } else {
Andrew Sapperstein1db635b2014-04-29 13:07:57 -0700925 tmpBitmap = createUnselectedChip(contact, paint);
Mindy Pereiracd611952011-06-01 17:02:20 -0700926 }
927
Mindy Pereiracd611952011-06-01 17:02:20 -0700928 // Pass the full text, un-ellipsized, to the chip.
929 Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700930 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
Jin Cao6c2a0162014-08-17 15:00:50 -0700931 VisibleRecipientChip recipientChip =
932 new VisibleRecipientChip(result, contact);
933 recipientChip.setExtraMargin(mLineSpacingExtra);
Mindy Pereiracd611952011-06-01 17:02:20 -0700934 // Return text to the original size.
935 paint.setTextSize(defaultSize);
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700936 paint.setColor(defaultColor);
Mindy Pereiracd611952011-06-01 17:02:20 -0700937 return recipientChip;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700938 }
939
Mindy Pereiraa8166902011-06-09 17:53:23 -0700940 /**
Mindy Pereira34214202011-06-09 20:05:32 -0700941 * Calculate the bottom of the line the chip will be located on using:
942 * 1) which line the chip appears on
Mindy Pereira21625f82011-06-16 18:10:58 -0700943 * 2) the height of a chip
944 * 3) padding built into the edit text view
Mindy Pereiraa8166902011-06-09 17:53:23 -0700945 */
Mindy Pereira81fd3d12011-07-06 14:40:50 -0700946 private int calculateOffsetFromBottom(int line) {
Mindy Pereira21625f82011-06-16 18:10:58 -0700947 // Line offsets start at zero.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700948 int actualLine = getLineCount() - (line + 1);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700949 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
950 + getDropDownVerticalOffset();
Mindy Pereiraf621a602011-05-31 10:09:35 -0700951 }
952
Mindy Pereiraa8166902011-06-09 17:53:23 -0700953 /**
Jin Cao6fc1fee2014-07-29 17:56:44 -0700954 * Calculate the offset from bottom of the EditText to top of the provided line.
955 */
956 private int calculateOffsetFromBottomToTop(int line) {
957 return -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math
958 .abs(getLineCount() - line)) + getPaddingBottom());
959 }
960
961 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -0700962 * Get the max amount of space a chip can take up. The formula takes into
963 * account the width of the EditTextView, any view padding, and padding
964 * that will be added to the chip.
965 */
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800966 private float calculateAvailableWidth() {
Jin Cao58d541d2014-07-29 16:23:03 -0700967 return getWidth() - getPaddingLeft() - getPaddingRight() - mChipTextStartPadding
968 - mChipTextEndPadding;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700969 }
970
Mindy Pereira52c441e2011-12-15 13:35:37 -0800971
Mindy Pereira22faaa62011-12-16 14:30:34 -0800972 private void setChipDimensions(Context context, AttributeSet attrs) {
Mindy Pereira5da02342011-12-16 14:56:27 -0800973 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
974 0);
Mindy Pereira52c441e2011-12-15 13:35:37 -0800975 Resources r = getContext().getResources();
mindyp8c474ec2012-12-14 10:58:44 -0800976
Mindy Pereira22faaa62011-12-16 14:30:34 -0800977 mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
Mindy Pereira5da02342011-12-16 14:56:27 -0800978 mChipBackgroundPressed = a
979 .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed);
Jin Cao33515e72014-08-05 21:13:27 -0700980 mInvalidChipBackground = a
981 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
Mindy Pereira5da02342011-12-16 14:56:27 -0800982 mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
983 if (mChipDelete == null) {
Jin Caoa21fd882014-08-10 13:07:11 -0700984 mChipDelete = r.getDrawable(R.drawable.ic_cancel_wht_24dp);
Mindy Pereira5da02342011-12-16 14:56:27 -0800985 }
Jin Cao58d541d2014-07-29 16:23:03 -0700986 mChipTextStartPadding = mChipTextEndPadding
987 = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
988 if (mChipTextStartPadding == -1) {
989 mChipTextStartPadding = mChipTextEndPadding =
990 (int) r.getDimension(R.dimen.chip_padding);
991 }
992 // xml-overrides for each individual padding
993 // TODO: add these to attr?
994 int overridePadding = (int) r.getDimension(R.dimen.chip_padding_start);
995 if (overridePadding >= 0) {
996 mChipTextStartPadding = overridePadding;
997 }
998 overridePadding = (int) r.getDimension(R.dimen.chip_padding_end);
999 if (overridePadding >= 0) {
1000 mChipTextEndPadding = overridePadding;
Mindy Pereira5da02342011-12-16 14:56:27 -08001001 }
Mindy Pereira5da02342011-12-16 14:56:27 -08001002
1003 mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
1004
Mindy Pereira52c441e2011-12-15 13:35:37 -08001005 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
Mindy Pereira5da02342011-12-16 14:56:27 -08001006
1007 mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
1008 if (mChipHeight == -1) {
1009 mChipHeight = r.getDimension(R.dimen.chip_height);
1010 }
1011 mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
1012 if (mChipFontSize == -1) {
1013 mChipFontSize = r.getDimension(R.dimen.chip_text_size);
1014 }
Scott Kennedyb232e5c2014-07-09 16:29:35 -07001015 mAvatarPosition =
1016 a.getInt(R.styleable.RecipientEditTextView_avatarPosition, AVATAR_POSITION_START);
Scott Kennedyb8985b72014-01-28 16:36:19 -08001017 mDisableDelete = a.getBoolean(R.styleable.RecipientEditTextView_disableDelete, false);
Kevin Linb10d1c62014-01-24 12:45:00 -08001018
mindypf30a4282012-12-03 12:16:33 -08001019 mMaxLines = r.getInteger(R.integer.chips_max_lines);
Jin Cao6c2a0162014-08-17 15:00:50 -07001020 mLineSpacingExtra = r.getDimensionPixelOffset(R.dimen.line_spacing_extra);
Kevin Linb10d1c62014-01-24 12:45:00 -08001021
Mindy Pereiraef798002012-05-02 11:04:25 -07001022 a.recycle();
Mindy Pereira52c441e2011-12-15 13:35:37 -08001023 }
1024
Mindy Pereirad7192502011-09-22 08:04:45 -07001025 // Visible for testing.
1026 /* package */ void setMoreItem(TextView moreItem) {
1027 mMoreItem = moreItem;
1028 }
1029
Mindy Pereira97cb2592011-09-26 16:11:41 -07001030
1031 // Visible for testing.
1032 /* package */ void setChipBackground(Drawable chipBackground) {
1033 mChipBackground = chipBackground;
1034 }
1035
1036 // Visible for testing.
1037 /* package */ void setChipHeight(int height) {
1038 mChipHeight = height;
1039 }
1040
Kevin Linb10d1c62014-01-24 12:45:00 -08001041 public float getChipHeight() {
1042 return mChipHeight;
1043 }
1044
Mindy Pereira076d1f92011-08-08 11:53:12 -07001045 /**
1046 * Set whether to shrink the recipients field such that at most
1047 * one line of recipients chips are shown when the field loses
1048 * focus. By default, the number of displayed recipients will be
1049 * limited and a "more" chip will be shown when focus is lost.
1050 * @param shrink
1051 */
1052 public void setOnFocusListShrinkRecipients(boolean shrink) {
1053 mShouldShrink = shrink;
1054 }
1055
Mindy Pereiracd611952011-06-01 17:02:20 -07001056 @Override
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001057 public void onSizeChanged(int width, int height, int oldw, int oldh) {
1058 super.onSizeChanged(width, height, oldw, oldh);
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001059 if (width != 0 && height != 0) {
1060 if (mPendingChipsCount > 0) {
1061 postHandlePendingChips();
1062 } else {
1063 checkChipWidths();
1064 }
Mindy Pereira8005f422011-07-20 13:16:53 -07001065 }
Mindy Pereira18529312011-06-28 11:00:52 -07001066 // Try to find the scroll view parent, if it exists.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001067 if (mScrollView == null && !mTriedGettingScrollView) {
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001068 ViewParent parent = getParent();
1069 while (parent != null && !(parent instanceof ScrollView)) {
1070 parent = parent.getParent();
1071 }
1072 if (parent != null) {
1073 mScrollView = (ScrollView) parent;
1074 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001075 mTriedGettingScrollView = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001076 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001077 }
1078
Mindy Pereira2cac2312011-07-20 11:38:59 -07001079 private void postHandlePendingChips() {
1080 mHandler.removeCallbacks(mHandlePendingChips);
1081 mHandler.post(mHandlePendingChips);
1082 }
Mindy Pereira18529312011-06-28 11:00:52 -07001083
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001084 private void checkChipWidths() {
1085 // Check the widths of the associated chips.
Scott Kennedy194d4272013-03-06 22:06:45 -08001086 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001087 if (chips != null) {
1088 Rect bounds;
Scott Kennedy194d4272013-03-06 22:06:45 -08001089 for (DrawableRecipientChip chip : chips) {
mindypf30a4282012-12-03 12:16:33 -08001090 bounds = chip.getBounds();
Kevin Linc61c13f2014-02-28 15:04:40 -08001091 if (getWidth() > 0 && bounds.right - bounds.left >
1092 getWidth() - getPaddingLeft() - getPaddingRight()) {
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001093 // Need to redraw that chip.
1094 replaceChip(chip, chip.getEntry());
1095 }
1096 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001097 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001098 }
1099
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001100 // Visible for testing.
1101 /*package*/ void handlePendingChips() {
1102 if (getViewWidth() <= 0) {
Mindy Pereira8005f422011-07-20 13:16:53 -07001103 // The widget has not been sized yet.
1104 // This will be called as a result of onSizeChanged
1105 // at a later point.
1106 return;
1107 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001108 if (mPendingChipsCount <= 0) {
1109 return;
1110 }
1111
Mindy Pereira2cac2312011-07-20 11:38:59 -07001112 synchronized (mPendingChips) {
Mindy Pereira2cac2312011-07-20 11:38:59 -07001113 Editable editable = getText();
1114 // Tokenize!
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001115 if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
1116 for (int i = 0; i < mPendingChips.size(); i++) {
1117 String current = mPendingChips.get(i);
1118 int tokenStart = editable.toString().indexOf(current);
mindyp488718e2012-12-18 11:48:07 -08001119 // Always leave a space at the end between tokens.
1120 int tokenEnd = tokenStart + current.length() - 1;
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001121 if (tokenStart >= 0) {
1122 // When we have a valid token, include it with the token
1123 // to the left.
1124 if (tokenEnd < editable.length() - 2
1125 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
1126 tokenEnd++;
1127 }
mindypf30a4282012-12-03 12:16:33 -08001128 createReplacementChip(tokenStart, tokenEnd, editable, i < CHIP_LIMIT
1129 || !mShouldShrink);
Mindy Pereira2cac2312011-07-20 11:38:59 -07001130 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001131 mPendingChipsCount--;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001132 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001133 sanitizeEnd();
1134 } else {
1135 mNoChips = true;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001136 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001137
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001138 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
Mindy Pereira2cac2312011-07-20 11:38:59 -07001139 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
1140 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
1141 new RecipientReplacementTask().execute();
1142 mTemporaryRecipients = null;
1143 } else {
1144 // Create the "more" chip
1145 mIndividualReplacements = new IndividualReplacementTask();
Scott Kennedy194d4272013-03-06 22:06:45 -08001146 mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(
Mindy Pereira2cac2312011-07-20 11:38:59 -07001147 mTemporaryRecipients.subList(0, CHIP_LIMIT)));
mindyp5e60c2b2012-11-06 17:47:40 -08001148 if (mTemporaryRecipients.size() > CHIP_LIMIT) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001149 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>(
mindyp5e60c2b2012-11-06 17:47:40 -08001150 mTemporaryRecipients.subList(CHIP_LIMIT,
1151 mTemporaryRecipients.size()));
1152 } else {
1153 mTemporaryRecipients = null;
1154 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001155 createMoreChip();
1156 }
1157 } else {
1158 // There are too many recipients to look up, so just fall back
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001159 // to showing addresses for all of them.
Mindy Pereira2cac2312011-07-20 11:38:59 -07001160 mTemporaryRecipients = null;
Mindy Pereira18529312011-06-28 11:00:52 -07001161 createMoreChip();
1162 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001163 mPendingChipsCount = 0;
1164 mPendingChips.clear();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001165 }
1166 }
1167
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001168 // Visible for testing.
1169 /*package*/ int getViewWidth() {
1170 return getWidth();
1171 }
1172
Mindy Pereira3bb52162011-07-01 14:52:22 -07001173 /**
1174 * Remove any characters after the last valid chip.
1175 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001176 // Visible for testing.
1177 /*package*/ void sanitizeEnd() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001178 // Don't sanitize while we are waiting for pending chips to complete.
1179 if (mPendingChipsCount > 0) {
1180 return;
1181 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001182 // Find the last chip; eliminate any commit characters after it.
Scott Kennedy194d4272013-03-06 22:06:45 -08001183 DrawableRecipientChip[] chips = getSortedRecipients();
mindypf30a4282012-12-03 12:16:33 -08001184 Spannable spannable = getSpannable();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001185 if (chips != null && chips.length > 0) {
1186 int end;
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001187 mMoreChip = getMoreChip();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001188 if (mMoreChip != null) {
mindypf30a4282012-12-03 12:16:33 -08001189 end = spannable.getSpanEnd(mMoreChip);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001190 } else {
mindypf30a4282012-12-03 12:16:33 -08001191 end = getSpannable().getSpanEnd(getLastChip());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001192 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001193 Editable editable = getText();
1194 int length = editable.length();
1195 if (length > end) {
1196 // See what characters occur after that and eliminate them.
1197 if (Log.isLoggable(TAG, Log.DEBUG)) {
1198 Log.d(TAG, "There were extra characters after the last tokenizable entry."
1199 + editable);
1200 }
1201 editable.delete(end + 1, length);
1202 }
1203 }
1204 }
1205
1206 /**
1207 * Create a chip that represents just the email address of a recipient. At some later
1208 * point, this chip will be attached to a real contact entry, if one exists.
1209 */
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001210 // VisibleForTesting
1211 void createReplacementChip(int tokenStart, int tokenEnd, Editable editable,
mindypf30a4282012-12-03 12:16:33 -08001212 boolean visible) {
Mindy Pereira32366d42011-07-24 12:39:30 -07001213 if (alreadyHasChip(tokenStart, tokenEnd)) {
1214 // There is already a chip present at this location.
1215 // Don't recreate it.
1216 return;
1217 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07001218 String token = editable.toString().substring(tokenStart, tokenEnd);
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001219 final String trimmedToken = token.trim();
1220 int commitCharIndex = trimmedToken.lastIndexOf(COMMIT_CHAR_COMMA);
Tom Taylor41137c22013-03-26 12:22:56 -07001221 if (commitCharIndex != -1 && commitCharIndex == trimmedToken.length() - 1) {
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001222 token = trimmedToken.substring(0, trimmedToken.length() - 1);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001223 }
1224 RecipientEntry entry = createTokenizedEntry(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001225 if (entry != null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001226 DrawableRecipientChip chip = null;
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001227 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001228 if (!mNoChips) {
mindypf30a4282012-12-03 12:16:33 -08001229 chip = visible ?
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07001230 constructChipSpan(entry, false) : new InvisibleRecipientChip(entry);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001231 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001232 } catch (NullPointerException e) {
1233 Log.e(TAG, e.getMessage(), e);
1234 }
mindypcb76b4d2012-11-09 14:05:19 -08001235 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001236 // Add this chip to the list of entries "to replace"
1237 if (chip != null) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001238 if (mTemporaryRecipients == null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001239 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>();
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001240 }
Scott Kennedy0613ff82013-03-05 14:02:46 -08001241 chip.setOriginalText(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001242 mTemporaryRecipients.add(chip);
1243 }
Mindy Pereira18529312011-06-28 11:00:52 -07001244 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001245 }
1246
Tom Taylorabff6062012-04-17 09:04:56 -07001247 private static boolean isPhoneNumber(String number) {
1248 // TODO: replace this function with libphonenumber's isPossibleNumber (see
1249 // PhoneNumberUtil). One complication is that it requires the sender's region which
1250 // comes from the CurrentCountryIso. For now, let's just do this simple match.
1251 if (TextUtils.isEmpty(number)) {
1252 return false;
1253 }
1254
Tom Taylor4491a062012-11-15 13:57:41 -08001255 Matcher match = PHONE_PATTERN.matcher(number);
Tom Taylorabff6062012-04-17 09:04:56 -07001256 return match.matches();
1257 }
1258
Scott Kennedy983c99b2013-03-22 09:42:03 -07001259 // VisibleForTesting
1260 RecipientEntry createTokenizedEntry(final String token) {
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001261 if (TextUtils.isEmpty(token)) {
1262 return null;
1263 }
mindyp5e60c2b2012-11-06 17:47:40 -08001264 if (isPhoneQuery() && isPhoneNumber(token)) {
Tom Taylor0ba91332013-03-21 10:28:50 -07001265 return RecipientEntry.constructFakePhoneEntry(token, true);
mindyp5e60c2b2012-11-06 17:47:40 -08001266 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001267 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
Mindy Pereira01382d72011-07-15 16:52:32 -07001268 String display = null;
mindypf30a4282012-12-03 12:16:33 -08001269 boolean isValid = isValid(token);
1270 if (isValid && tokens != null && tokens.length > 0) {
Mindy Pereiraee58f492011-08-08 13:16:46 -07001271 // If we can get a name from tokenizing, then generate an entry from
1272 // this.
Mindy Pereira01382d72011-07-15 16:52:32 -07001273 display = tokens[0].getName();
1274 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001275 return RecipientEntry.constructGeneratedEntry(display, tokens[0].getAddress(),
1276 isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001277 } else {
1278 display = tokens[0].getAddress();
1279 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001280 return RecipientEntry.constructFakeEntry(display, isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001281 }
Mindy Pereira01382d72011-07-15 16:52:32 -07001282 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001283 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001284 // Unable to validate the token or to create a valid token from it.
1285 // Just create a chip the user can edit.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001286 String validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001287 if (mValidator != null && !isValid) {
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001288 // Try fixing up the entry using the validator.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001289 validatedToken = mValidator.fixText(token).toString();
1290 if (!TextUtils.isEmpty(validatedToken)) {
1291 if (validatedToken.contains(token)) {
mindypf30a4282012-12-03 12:16:33 -08001292 // protect against the case of a validator with a null
1293 // domain,
Mindy Pereiradbb85602011-09-16 14:02:14 -07001294 // which doesn't add a domain to the token
1295 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
1296 if (tokenized.length > 0) {
1297 validatedToken = tokenized[0].getAddress();
mindypf30a4282012-12-03 12:16:33 -08001298 isValid = true;
Mindy Pereiradbb85602011-09-16 14:02:14 -07001299 }
1300 } else {
mindypf30a4282012-12-03 12:16:33 -08001301 // We ran into a case where the token was invalid and
1302 // removed
1303 // by the validator. In this case, just use the original
1304 // token
Mindy Pereiradbb85602011-09-16 14:02:14 -07001305 // and let the user sort out the error chip.
1306 validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001307 isValid = false;
Erik184d3772011-08-04 16:07:00 -07001308 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001309 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001310 }
Mindy Pereiraee58f492011-08-08 13:16:46 -07001311 // Otherwise, fallback to just creating an editable email address chip.
mindypf30a4282012-12-03 12:16:33 -08001312 return RecipientEntry.constructFakeEntry(
1313 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid);
Mindy Pereira01382d72011-07-15 16:52:32 -07001314 }
1315
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001316 private boolean isValid(String text) {
1317 return mValidator == null ? true : mValidator.isValid(text);
1318 }
1319
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001320 private static String tokenizeAddress(String destination) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001321 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
1322 if (tokens != null && tokens.length > 0) {
1323 return tokens[0].getAddress();
1324 }
1325 return destination;
Mindy Pereira3bb52162011-07-01 14:52:22 -07001326 }
1327
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001328 @Override
Mindy Pereiracd611952011-06-01 17:02:20 -07001329 public void setTokenizer(Tokenizer tokenizer) {
1330 mTokenizer = tokenizer;
1331 super.setTokenizer(mTokenizer);
1332 }
1333
Mindy Pereiraa8166902011-06-09 17:53:23 -07001334 @Override
1335 public void setValidator(Validator validator) {
1336 mValidator = validator;
1337 super.setValidator(validator);
1338 }
1339
1340 /**
1341 * We cannot use the default mechanism for replaceText. Instead,
1342 * we override onItemClickListener so we can get all the associated
1343 * contact information including display text, address, and id.
1344 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001345 @Override
1346 protected void replaceText(CharSequence text) {
1347 return;
1348 }
1349
Mindy Pereiraa8166902011-06-09 17:53:23 -07001350 /**
1351 * Dismiss any selected chips when the back key is pressed.
1352 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001353 @Override
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001354 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001355 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) {
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001356 clearSelectedChip();
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001357 return true;
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001358 }
1359 return super.onKeyPreIme(keyCode, event);
1360 }
1361
Mindy Pereiraa8166902011-06-09 17:53:23 -07001362 /**
1363 * Monitor key presses in this view to see if the user types
1364 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
1365 * If the user has entered text that has contact matches and types
1366 * a commit key, create a chip from the topmost matching contact.
1367 * If the user has entered text that has no contact matches and types
1368 * a commit key, then create a chip from the text they have entered.
1369 */
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001370 @Override
Mindy Pereiracd611952011-06-01 17:02:20 -07001371 public boolean onKeyUp(int keyCode, KeyEvent event) {
1372 switch (keyCode) {
Mindy Pereira0f0df292011-06-16 20:49:51 -07001373 case KeyEvent.KEYCODE_TAB:
1374 if (event.hasNoModifiers()) {
1375 if (mSelectedChip != null) {
1376 clearSelectedChip();
1377 } else {
1378 commitDefault();
1379 }
Mindy Pereira0f0df292011-06-16 20:49:51 -07001380 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001381 break;
Mindy Pereiracd611952011-06-01 17:02:20 -07001382 }
1383 return super.onKeyUp(keyCode, event);
1384 }
1385
Mindy Pereira0f0df292011-06-16 20:49:51 -07001386 private boolean focusNext() {
1387 View next = focusSearch(View.FOCUS_DOWN);
1388 if (next != null) {
1389 next.requestFocus();
1390 return true;
1391 }
1392 return false;
1393 }
1394
Mindy Pereira34214202011-06-09 20:05:32 -07001395 /**
1396 * Create a chip from the default selection. If the popup is showing, the
Scott Kennedye4945e92014-04-21 20:17:43 -07001397 * default is the selected item (if one is selected), or the first item, in the popup
1398 * suggestions list. Otherwise, it is whatever the user had typed in. End represents where the
1399 * tokenizer should search for a token to turn into a chip.
Mindy Pereira34214202011-06-09 20:05:32 -07001400 * @return If a chip was created from a real contact.
1401 */
Mindy Pereiraa8166902011-06-09 17:53:23 -07001402 private boolean commitDefault() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001403 // If there is no tokenizer, don't try to commit.
1404 if (mTokenizer == null) {
1405 return false;
1406 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001407 Editable editable = getText();
Mindy Pereira34214202011-06-09 20:05:32 -07001408 int end = getSelectionEnd();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001409 int start = mTokenizer.findTokenStart(editable, end);
Mindy Pereira2b4ffc52011-06-20 13:20:09 -07001410
Mindy Pereira79fb4362011-06-21 14:37:07 -07001411 if (shouldCreateChip(start, end)) {
1412 int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1413 // In the middle of chip; treat this as an edit
1414 // and commit the whole token.
mindyp4f82d882012-11-08 16:30:27 -08001415 whatEnd = movePastTerminators(whatEnd);
Mindy Pereira79fb4362011-06-21 14:37:07 -07001416 if (whatEnd != getSelectionEnd()) {
1417 handleEdit(start, whatEnd);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001418 return true;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001419 }
1420 return commitChip(start, end , editable);
1421 }
1422 return false;
1423 }
1424
1425 private void commitByCharacter() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001426 // We can't possibly commit by character if we can't tokenize.
1427 if (mTokenizer == null) {
1428 return;
1429 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001430 Editable editable = getText();
1431 int end = getSelectionEnd();
1432 int start = mTokenizer.findTokenStart(editable, end);
1433 if (shouldCreateChip(start, end)) {
1434 commitChip(start, end, editable);
1435 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001436 setSelection(getText().length());
Mindy Pereira79fb4362011-06-21 14:37:07 -07001437 }
1438
1439 private boolean commitChip(int start, int end, Editable editable) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07001440 ListAdapter adapter = getAdapter();
1441 if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
Tom Taylorc7a87f02012-05-03 15:21:08 -07001442 && end == getSelectionEnd() && !isPhoneQuery()) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001443 // let's choose the selected or first entry if only the input text is NOT an email
1444 // address so we won't try to replace the user's potentially correct but
1445 // new/unencountered email input
Jin Caob3b248a2014-04-11 10:43:50 -07001446 if (!isValidEmailAddress(editable.toString().substring(start, end).trim())) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001447 final int selectedPosition = getListSelection();
1448 if (selectedPosition == -1) {
1449 // Nothing is selected; use the first item
1450 submitItemAtPosition(0);
1451 } else {
1452 submitItemAtPosition(selectedPosition);
1453 }
Jin Caob3b248a2014-04-11 10:43:50 -07001454 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001455 dismissDropDown();
1456 return true;
1457 } else {
1458 int tokenEnd = mTokenizer.findTokenEnd(editable, start);
Mindy Pereira20c9d622011-10-12 13:18:04 -07001459 if (editable.length() > tokenEnd + 1) {
1460 char charAt = editable.charAt(tokenEnd + 1);
1461 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1462 tokenEnd++;
1463 }
Mindy Pereirad7192502011-09-22 08:04:45 -07001464 }
Mindy Pereira62397a52011-10-03 13:46:43 -07001465 String text = editable.toString().substring(start, tokenEnd).trim();
Mindy Pereira79fb4362011-06-21 14:37:07 -07001466 clearComposingText();
1467 if (text != null && text.length() > 0 && !text.equals(" ")) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001468 RecipientEntry entry = createTokenizedEntry(text);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001469 if (entry != null) {
1470 QwertyKeyListener.markAsReplaced(editable, start, end, "");
1471 CharSequence chipText = createChip(entry, false);
Mindy Pereiraee6d83f2011-10-03 14:25:07 -07001472 if (chipText != null && start > -1 && end > -1) {
Mindy Pereiraf177bda2011-09-15 11:23:49 -07001473 editable.replace(start, end, chipText);
1474 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001475 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07001476 // Only dismiss the dropdown if it is related to the text we
1477 // just committed.
1478 // For paste, it may not be as there are possibly multiple
1479 // tokens being added.
1480 if (end == getSelectionEnd()) {
1481 dismissDropDown();
1482 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001483 sanitizeBetween();
Mindy Pereira0f0df292011-06-16 20:49:51 -07001484 return true;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001485 }
1486 }
1487 return false;
Mindy Pereira05dbd332011-06-03 09:37:44 -07001488 }
1489
Mindy Pereira01162ce2011-09-20 12:21:55 -07001490 // Visible for testing.
1491 /* package */ void sanitizeBetween() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001492 // Don't sanitize while we are waiting for content to chipify.
1493 if (mPendingChipsCount > 0) {
1494 return;
1495 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001496 // Find the last chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08001497 DrawableRecipientChip[] recips = getSortedRecipients();
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001498 if (recips != null && recips.length > 0) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001499 DrawableRecipientChip last = recips[recips.length - 1];
1500 DrawableRecipientChip beforeLast = null;
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001501 if (recips.length > 1) {
1502 beforeLast = recips[recips.length - 2];
1503 }
1504 int startLooking = 0;
1505 int end = getSpannable().getSpanStart(last);
1506 if (beforeLast != null) {
1507 startLooking = getSpannable().getSpanEnd(beforeLast);
Mindy Pereira399bda82011-09-20 11:18:26 -07001508 Editable text = getText();
Mindy Pereira01162ce2011-09-20 12:21:55 -07001509 if (startLooking == -1 || startLooking > text.length() - 1) {
Mindy Pereira399bda82011-09-20 11:18:26 -07001510 // There is nothing after this chip.
1511 return;
1512 }
1513 if (text.charAt(startLooking) == ' ') {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001514 startLooking++;
1515 }
1516 }
Mindy Pereirae13775c2011-11-17 11:14:12 -08001517 if (startLooking >= 0 && end >= 0 && startLooking < end) {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001518 getText().delete(startLooking, end);
1519 }
1520 }
1521 }
1522
Mindy Pereira79fb4362011-06-21 14:37:07 -07001523 private boolean shouldCreateChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001524 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
Mindy Pereira32366d42011-07-24 12:39:30 -07001525 }
1526
1527 private boolean alreadyHasChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001528 if (mNoChips) {
1529 return true;
1530 }
Scott Kennedy194d4272013-03-06 22:06:45 -08001531 DrawableRecipientChip[] chips =
1532 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereira32366d42011-07-24 12:39:30 -07001533 if ((chips == null || chips.length == 0)) {
1534 return false;
Mindy Pereira64af2da2011-06-15 11:14:07 -07001535 }
Mindy Pereira32366d42011-07-24 12:39:30 -07001536 return true;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001537 }
1538
1539 private void handleEdit(int start, int end) {
Mindy Pereiraa49e7fa2011-09-13 08:01:36 -07001540 if (start == -1 || end == -1) {
1541 // This chip no longer exists in the field.
1542 dismissDropDown();
1543 return;
1544 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001545 // This is in the middle of a chip, so select out the whole chip
1546 // and commit it.
1547 Editable editable = getText();
1548 setSelection(end);
1549 String text = getText().toString().substring(start, end);
Mindy Pereirafe52b972011-09-16 11:55:57 -07001550 if (!TextUtils.isEmpty(text)) {
mindypf30a4282012-12-03 12:16:33 -08001551 RecipientEntry entry = RecipientEntry.constructFakeEntry(text, isValid(text));
Mindy Pereirafe52b972011-09-16 11:55:57 -07001552 QwertyKeyListener.markAsReplaced(editable, start, end, "");
1553 CharSequence chipText = createChip(entry, false);
Mindy Pereira5cfd6fe2011-10-20 15:36:24 -07001554 int selEnd = getSelectionEnd();
1555 if (chipText != null && start > -1 && selEnd > -1) {
1556 editable.replace(start, selEnd, chipText);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001557 }
Mindy Pereirafe52b972011-09-16 11:55:57 -07001558 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001559 dismissDropDown();
Mindy Pereira64af2da2011-06-15 11:14:07 -07001560 }
1561
Mindy Pereiraa8166902011-06-09 17:53:23 -07001562 /**
1563 * If there is a selected chip, delegate the key events
1564 * to the selected chip.
1565 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001566 @Override
1567 public boolean onKeyDown(int keyCode, KeyEvent event) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001568 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1569 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1570 mAlternatesPopup.dismiss();
1571 }
1572 removeChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001573 }
1574
Scott Kennedy2fe0cff2013-02-14 18:39:37 -08001575 switch (keyCode) {
1576 case KeyEvent.KEYCODE_ENTER:
1577 case KeyEvent.KEYCODE_DPAD_CENTER:
1578 if (event.hasNoModifiers()) {
1579 if (commitDefault()) {
1580 return true;
1581 }
1582 if (mSelectedChip != null) {
1583 clearSelectedChip();
1584 return true;
1585 } else if (focusNext()) {
1586 return true;
1587 }
1588 }
1589 break;
1590 }
1591
Mindy Pereiracd611952011-06-01 17:02:20 -07001592 return super.onKeyDown(keyCode, event);
1593 }
1594
Mindy Pereira01162ce2011-09-20 12:21:55 -07001595 // Visible for testing.
1596 /* package */ Spannable getSpannable() {
Erike33555f2011-06-21 14:20:20 -07001597 return getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001598 }
1599
Scott Kennedy194d4272013-03-06 22:06:45 -08001600 private int getChipStart(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001601 return getSpannable().getSpanStart(chip);
1602 }
1603
Scott Kennedy194d4272013-03-06 22:06:45 -08001604 private int getChipEnd(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001605 return getSpannable().getSpanEnd(chip);
1606 }
1607
Mindy Pereiracd611952011-06-01 17:02:20 -07001608 /**
1609 * Instead of filtering on the entire contents of the edit box,
1610 * this subclass method filters on the range from
1611 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1612 * if the length of that range meets or exceeds {@link #getThreshold}
1613 * and makes sure that the range is not already a Chip.
1614 */
1615 @Override
1616 protected void performFiltering(CharSequence text, int keyCode) {
mindyp093ecdd2012-12-14 10:40:51 -08001617 boolean isCompletedToken = isCompletedToken(text);
1618 if (enoughToFilter() && !isCompletedToken) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001619 int end = getSelectionEnd();
1620 int start = mTokenizer.findTokenStart(text, end);
1621 // If this is a RecipientChip, don't filter
1622 // on its contents.
1623 Spannable span = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001624 DrawableRecipientChip[] chips = span.getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001625 if (chips != null && chips.length > 0) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001626 dismissDropDown();
Mindy Pereiracd611952011-06-01 17:02:20 -07001627 return;
1628 }
mindyp093ecdd2012-12-14 10:40:51 -08001629 } else if (isCompletedToken) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001630 dismissDropDown();
mindyp093ecdd2012-12-14 10:40:51 -08001631 return;
Mindy Pereiracd611952011-06-01 17:02:20 -07001632 }
1633 super.performFiltering(text, keyCode);
1634 }
1635
Mindy Pereira20c9d622011-10-12 13:18:04 -07001636 // Visible for testing.
1637 /*package*/ boolean isCompletedToken(CharSequence text) {
1638 if (TextUtils.isEmpty(text)) {
1639 return false;
1640 }
1641 // Check to see if this is a completed token before filtering.
1642 int end = text.length();
1643 int start = mTokenizer.findTokenStart(text, end);
1644 String token = text.toString().substring(start, end).trim();
1645 if (!TextUtils.isEmpty(token)) {
1646 char atEnd = token.charAt(token.length() - 1);
1647 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1648 }
1649 return false;
1650 }
1651
Mindy Pereiracd611952011-06-01 17:02:20 -07001652 private void clearSelectedChip() {
1653 if (mSelectedChip != null) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001654 unselectChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001655 mSelectedChip = null;
1656 }
Mindy Pereirab86dcd52011-06-02 13:52:30 -07001657 setCursorVisible(true);
Mindy Pereiracd611952011-06-01 17:02:20 -07001658 }
1659
Mindy Pereiraa8166902011-06-09 17:53:23 -07001660 /**
1661 * Monitor touch events in the RecipientEditTextView.
1662 * If the view does not have focus, any tap on the view
1663 * will just focus the view. If the view has focus, determine
1664 * if the touch target is a recipient chip. If it is and the chip
1665 * is not selected, select it and clear any other selected chips.
1666 * If it isn't, then select that chip.
1667 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001668 @Override
1669 public boolean onTouchEvent(MotionEvent event) {
Mindy Pereira05dbd332011-06-03 09:37:44 -07001670 if (!isFocused()) {
1671 // Ignore any chip taps until this view is focused.
1672 return super.onTouchEvent(event);
1673 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001674 boolean handled = super.onTouchEvent(event);
Mindy Pereira05dbd332011-06-03 09:37:44 -07001675 int action = event.getAction();
Mindy Pereiracd611952011-06-01 17:02:20 -07001676 boolean chipWasSelected = false;
Mindy Pereira2e905902011-09-08 16:17:04 -07001677 if (mSelectedChip == null) {
Mindy Pereira1d1ec852011-08-09 16:49:33 -07001678 mGestureDetector.onTouchEvent(event);
1679 }
Mindy Pereirabfedc1e2011-09-07 12:17:12 -07001680 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001681 float x = event.getX();
1682 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07001683 int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08001684 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereiracd611952011-06-01 17:02:20 -07001685 if (currentChip != null) {
1686 if (action == MotionEvent.ACTION_UP) {
1687 if (mSelectedChip != null && mSelectedChip != currentChip) {
1688 clearSelectedChip();
Mindy Pereira95a69252011-06-17 15:02:03 -07001689 mSelectedChip = selectChip(currentChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001690 } else if (mSelectedChip == null) {
Mindy Pereiraa8166902011-06-09 17:53:23 -07001691 setSelection(getText().length());
1692 commitDefault();
Mindy Pereira95a69252011-06-17 15:02:03 -07001693 mSelectedChip = selectChip(currentChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001694 } else {
Jin Caoa21fd882014-08-10 13:07:11 -07001695 onClick(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001696 }
1697 }
1698 chipWasSelected = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001699 handled = true;
mindyp5e60c2b2012-11-06 17:47:40 -08001700 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07001701 chipWasSelected = true;
Mindy Pereiracd611952011-06-01 17:02:20 -07001702 }
1703 }
1704 if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1705 clearSelectedChip();
1706 }
1707 return handled;
1708 }
1709
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001710 private void scrollLineIntoView(int line) {
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001711 if (mScrollView != null) {
mindyp093ecdd2012-12-14 10:40:51 -08001712 mScrollView.smoothScrollBy(0, calculateOffsetFromBottom(line));
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001713 }
1714 }
1715
Scott Kennedy272aae02013-04-05 17:17:24 -07001716 private void showAlternates(final DrawableRecipientChip currentChip,
Jin Cao9b166202014-08-08 13:26:14 -07001717 final ListPopupWindow alternatesPopup) {
Scott Kennedy272aae02013-04-05 17:17:24 -07001718 new AsyncTask<Void, Void, ListAdapter>() {
1719 @Override
1720 protected ListAdapter doInBackground(final Void... params) {
1721 return createAlternatesAdapter(currentChip);
1722 }
1723
Alice Yang6b7110f2013-04-26 12:50:35 -07001724 @Override
Scott Kennedy272aae02013-04-05 17:17:24 -07001725 protected void onPostExecute(final ListAdapter result) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07001726 if (!mAttachedToWindow) {
1727 return;
1728 }
Scott Kennedy272aae02013-04-05 17:17:24 -07001729 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07001730 int bottomOffset = calculateOffsetFromBottomToTop(line);
1731
Scott Kennedy272aae02013-04-05 17:17:24 -07001732 // Align the alternates popup with the left side of the View,
1733 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07001734 alternatesPopup.setAnchorView((mAlternatePopupAnchor != null) ?
1735 mAlternatePopupAnchor : RecipientEditTextView.this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07001736 alternatesPopup.setVerticalOffset(bottomOffset);
Scott Kennedy272aae02013-04-05 17:17:24 -07001737 alternatesPopup.setAdapter(result);
1738 alternatesPopup.setOnItemClickListener(mAlternatesListener);
1739 // Clear the checked item.
1740 mCheckedItem = -1;
1741 alternatesPopup.show();
1742 ListView listView = alternatesPopup.getListView();
1743 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1744 // Checked item would be -1 if the adapter has not
1745 // loaded the view that should be checked yet. The
1746 // variable will be set correctly when onCheckedItemChanged
1747 // is called in a separate thread.
1748 if (mCheckedItem != -1) {
1749 listView.setItemChecked(mCheckedItem, true);
1750 mCheckedItem = -1;
1751 }
1752 }
1753 }.execute((Void[]) null);
Mindy Pereira95a69252011-06-17 15:02:03 -07001754 }
1755
Scott Kennedy194d4272013-03-06 22:06:45 -08001756 private ListAdapter createAlternatesAdapter(DrawableRecipientChip chip) {
Scott Kennedy7a4e6772013-11-21 14:31:33 -08001757 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(),
1758 chip.getDirectoryId(), chip.getLookupKey(), chip.getDataId(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001759 getAdapter().getQueryType(), this, mDropdownChipLayouter,
1760 constructStateListDeleteDrawable());
Mindy Pereira95a69252011-06-17 15:02:03 -07001761 }
1762
Scott Kennedy194d4272013-03-06 22:06:45 -08001763 private ListAdapter createSingleAddressAdapter(DrawableRecipientChip currentChip) {
Kevin Linb10d1c62014-01-24 12:45:00 -08001764 return new SingleRecipientArrayAdapter(getContext(), currentChip.getEntry(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001765 mDropdownChipLayouter, constructStateListDeleteDrawable());
1766 }
1767
1768 private StateListDrawable constructStateListDeleteDrawable() {
1769 // Construct the StateListDrawable from deleteDrawable
1770 StateListDrawable deleteDrawable = new StateListDrawable();
Jin Caoa21fd882014-08-10 13:07:11 -07001771 if (!mDisableDelete) {
1772 deleteDrawable.addState(new int[]{android.R.attr.state_activated}, mChipDelete);
1773 }
Jin Cao4db8ccc2014-07-30 10:11:07 -07001774 deleteDrawable.addState(new int[0], null);
1775 return deleteDrawable;
Mindy Pereira01382d72011-07-15 16:52:32 -07001776 }
1777
Andy Stadleraa2afff2011-08-04 16:22:47 -07001778 @Override
Mindy Pereira95a69252011-06-17 15:02:03 -07001779 public void onCheckedItemChanged(int position) {
1780 ListView listView = mAlternatesPopup.getListView();
1781 if (listView != null && listView.getCheckedItemCount() == 0) {
1782 listView.setItemChecked(position, true);
Mindy Pereira95a69252011-06-17 15:02:03 -07001783 }
Mindy Pereira98b547f2011-09-08 09:27:39 -07001784 mCheckedItem = position;
Mindy Pereira95a69252011-06-17 15:02:03 -07001785 }
1786
Scott Kennedy1650ef62013-08-02 21:56:47 -07001787 private int putOffsetInRange(final float x, final float y) {
1788 final int offset;
1789
1790 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1791 offset = getOffsetForPosition(x, y);
1792 } else {
1793 offset = supportGetOffsetForPosition(x, y);
1794 }
1795
1796 return putOffsetInRange(offset);
1797 }
1798
Mindy Pereiracd611952011-06-01 17:02:20 -07001799 // TODO: This algorithm will need a lot of tweaking after more people have used
1800 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1801 // what comes before the finger.
1802 private int putOffsetInRange(int o) {
1803 int offset = o;
1804 Editable text = getText();
1805 int length = text.length();
1806 // Remove whitespace from end to find "real end"
1807 int realLength = length;
1808 for (int i = length - 1; i >= 0; i--) {
1809 if (text.charAt(i) == ' ') {
1810 realLength--;
1811 } else {
1812 break;
1813 }
1814 }
1815
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001816 // If the offset is beyond or at the end of the text,
1817 // leave it alone.
1818 if (offset >= realLength) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001819 return offset;
1820 }
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001821 Editable editable = getText();
Mindy Pereirab88ee452011-06-02 11:07:43 -07001822 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001823 // Keep walking backward!
1824 offset--;
1825 }
1826 return offset;
1827 }
1828
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001829 private static int findText(Editable text, int offset) {
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001830 if (text.charAt(offset) != ' ') {
1831 return offset;
1832 }
1833 return -1;
1834 }
1835
Scott Kennedy194d4272013-03-06 22:06:45 -08001836 private DrawableRecipientChip findChip(int offset) {
1837 DrawableRecipientChip[] chips =
1838 getSpannable().getSpans(0, getText().length(), DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001839 // Find the chip that contains this offset.
1840 for (int i = 0; i < chips.length; i++) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001841 DrawableRecipientChip chip = chips[i];
Mindy Pereira95a69252011-06-17 15:02:03 -07001842 int start = getChipStart(chip);
1843 int end = getChipEnd(chip);
1844 if (offset >= start && offset <= end) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001845 return chip;
1846 }
1847 }
1848 return null;
1849 }
1850
Mindy Pereira01162ce2011-09-20 12:21:55 -07001851 // Visible for testing.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001852 // Use this method to generate text to add to the list of addresses.
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001853 /* package */String createAddressText(RecipientEntry entry) {
Mindy Pereira3ea99552011-09-19 10:50:31 -07001854 String display = entry.getDisplayName();
1855 String address = entry.getDestination();
1856 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1857 display = null;
1858 }
Tom Taylorabff6062012-04-17 09:04:56 -07001859 String trimmedDisplayText;
Tom Taylorc7a87f02012-05-03 15:21:08 -07001860 if (isPhoneQuery() && isPhoneNumber(address)) {
Tom Taylorabff6062012-04-17 09:04:56 -07001861 trimmedDisplayText = address.trim();
1862 } else {
1863 if (address != null) {
1864 // Tokenize out the address in case the address already
1865 // contained the username as well.
1866 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1867 if (tokenized != null && tokenized.length > 0) {
1868 address = tokenized[0].getAddress();
1869 }
Mindy Pereiraee48f732011-09-20 08:13:39 -07001870 }
Tom Taylorabff6062012-04-17 09:04:56 -07001871 Rfc822Token token = new Rfc822Token(display, address, null);
1872 trimmedDisplayText = token.toString().trim();
Mindy Pereirad8c15c32011-09-19 15:02:05 -07001873 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001874 int index = trimmedDisplayText.indexOf(",");
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001875 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1876 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001877 .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1878 }
1879
1880 // Visible for testing.
1881 // Use this method to generate text to display in a chip.
1882 /*package*/ String createChipDisplayText(RecipientEntry entry) {
1883 String display = entry.getDisplayName();
1884 String address = entry.getDestination();
1885 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1886 display = null;
1887 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001888 if (!TextUtils.isEmpty(display)) {
1889 return display;
1890 } else if (!TextUtils.isEmpty(address)){
1891 return address;
1892 } else {
1893 return new Rfc822Token(display, address, null).toString();
1894 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001895 }
1896
Mindy Pereira0ab7e732011-06-08 10:17:39 -07001897 private CharSequence createChip(RecipientEntry entry, boolean pressed) {
Jin Cao4db8ccc2014-07-30 10:11:07 -07001898 final String displayText = createAddressText(entry);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001899 if (TextUtils.isEmpty(displayText)) {
1900 return null;
1901 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001902 // Always leave a blank space at the end of a chip.
Jin Cao4db8ccc2014-07-30 10:11:07 -07001903 final int textLength = displayText.length() - 1;
1904 final SpannableString chipText = new SpannableString(displayText);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001905 if (!mNoChips) {
1906 try {
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07001907 DrawableRecipientChip chip = constructChipSpan(entry, pressed);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001908 chipText.setSpan(chip, 0, textLength,
1909 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1910 chip.setOriginalText(chipText.toString());
1911 } catch (NullPointerException e) {
1912 Log.e(TAG, e.getMessage(), e);
1913 return null;
1914 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001915 }
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001916 onChipCreated(entry);
Mindy Pereiracd611952011-06-01 17:02:20 -07001917 return chipText;
1918 }
1919
Mindy Pereiraa8166902011-06-09 17:53:23 -07001920 /**
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001921 * A callback for subclasses to use to know when a chip was created with the
1922 * given RecipientEntry.
1923 */
1924 protected void onChipCreated(RecipientEntry entry) {}
1925
1926 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -07001927 * When an item in the suggestions list has been clicked, create a chip from the
1928 * contact information of the selected item.
1929 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001930 @Override
1931 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tom Taylor114c8932013-04-10 13:11:05 -07001932 if (position < 0) {
1933 return;
1934 }
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001935
1936 final int charactersTyped = submitItemAtPosition(position);
1937 if (charactersTyped > -1 && mRecipientEntryItemClickedListener != null) {
1938 mRecipientEntryItemClickedListener
1939 .onRecipientEntryItemClicked(charactersTyped, position);
1940 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001941 }
1942
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001943 private int submitItemAtPosition(int position) {
Scott Kennedy858e0942013-10-10 11:50:01 -07001944 RecipientEntry entry = createValidatedEntry(getAdapter().getItem(position));
Erikf7eaa5f2011-07-14 17:02:07 -07001945 if (entry == null) {
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001946 return -1;
Erikf7eaa5f2011-07-14 17:02:07 -07001947 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001948 clearComposingText();
1949
1950 int end = getSelectionEnd();
1951 int start = mTokenizer.findTokenStart(getText(), end);
1952
1953 Editable editable = getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001954 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereirae90bfad2011-07-26 14:51:41 -07001955 CharSequence chip = createChip(entry, false);
Mindy Pereira005b2e22011-11-01 10:26:58 -07001956 if (chip != null && start >= 0 && end >= 0) {
Mindy Pereirae90bfad2011-07-26 14:51:41 -07001957 editable.replace(start, end, chip);
1958 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001959 sanitizeBetween();
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001960
1961 return end - start;
Mindy Pereiracd611952011-06-01 17:02:20 -07001962 }
1963
Mindy Pereira3bb52162011-07-01 14:52:22 -07001964 private RecipientEntry createValidatedEntry(RecipientEntry item) {
1965 if (item == null) {
1966 return null;
1967 }
1968 final RecipientEntry entry;
1969 // If the display name and the address are the same, or if this is a
1970 // valid contact, but the destination is invalid, then make this a fake
1971 // recipient that is editable.
1972 String destination = item.getDestination();
mindyp5e60c2b2012-11-06 17:47:40 -08001973 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1974 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
mindypf30a4282012-12-03 12:16:33 -08001975 destination, item.isValid());
mindyp5e60c2b2012-11-06 17:47:40 -08001976 } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
Mindy Pereirab4e244a2011-10-14 11:13:29 -07001977 && (TextUtils.isEmpty(item.getDisplayName())
1978 || TextUtils.equals(item.getDisplayName(), destination)
1979 || (mValidator != null && !mValidator.isValid(destination)))) {
mindypf30a4282012-12-03 12:16:33 -08001980 entry = RecipientEntry.constructFakeEntry(destination, item.isValid());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001981 } else {
1982 entry = item;
1983 }
1984 return entry;
1985 }
1986
Mindy Pereira01162ce2011-09-20 12:21:55 -07001987 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08001988 /* package */DrawableRecipientChip[] getSortedRecipients() {
1989 DrawableRecipientChip[] recips = getSpannable()
1990 .getSpans(0, getText().length(), DrawableRecipientChip.class);
1991 ArrayList<DrawableRecipientChip> recipientsList = new ArrayList<DrawableRecipientChip>(
1992 Arrays.asList(recips));
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001993 final Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001994 Collections.sort(recipientsList, new Comparator<DrawableRecipientChip>() {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001995
1996 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08001997 public int compare(DrawableRecipientChip first, DrawableRecipientChip second) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001998 int firstStart = spannable.getSpanStart(first);
1999 int secondStart = spannable.getSpanStart(second);
2000 if (firstStart < secondStart) {
2001 return -1;
2002 } else if (firstStart > secondStart) {
2003 return 1;
2004 } else {
2005 return 0;
2006 }
2007 }
2008 });
Scott Kennedy194d4272013-03-06 22:06:45 -08002009 return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002010 }
2011
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002012 @Override
2013 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2014 return false;
2015 }
2016
2017 @Override
2018 public void onDestroyActionMode(ActionMode mode) {
2019 }
2020
2021 @Override
2022 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2023 return false;
2024 }
2025
Mindy Pereiraa8166902011-06-09 17:53:23 -07002026 /**
2027 * No chips are selectable.
2028 */
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002029 @Override
2030 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2031 return false;
2032 }
2033
Mindy Pereirad7192502011-09-22 08:04:45 -07002034 // Visible for testing.
Jin Cao6c2a0162014-08-17 15:00:50 -07002035 /* package */ReplacementDrawableSpan getMoreChip() {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002036 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
2037 MoreImageSpan.class);
2038 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
2039 }
2040
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002041 private MoreImageSpan createMoreSpan(int count) {
2042 String moreText = String.format(mMoreItem.getText().toString(), count);
Jin Cao6c2a0162014-08-17 15:00:50 -07002043 mWorkPaint.set(getPaint());
2044 mWorkPaint.setTextSize(mMoreItem.getTextSize());
2045 mWorkPaint.setColor(mMoreItem.getCurrentTextColor());
2046 final int width = (int) mWorkPaint.measureText(moreText) + mMoreItem.getPaddingLeft()
Mindy Pereira750e6e52011-07-25 11:51:30 -07002047 + mMoreItem.getPaddingRight();
Jin Cao6c2a0162014-08-17 15:00:50 -07002048 final int height = (int) mChipHeight;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002049 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2050 Canvas canvas = new Canvas(drawable);
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002051 int adjustedHeight = height;
2052 Layout layout = getLayout();
2053 if (layout != null) {
2054 adjustedHeight -= layout.getLineDescent(0);
2055 }
Jin Cao6c2a0162014-08-17 15:00:50 -07002056 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, mWorkPaint);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002057
2058 Drawable result = new BitmapDrawable(getResources(), drawable);
2059 result.setBounds(0, 0, width, height);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002060 return new MoreImageSpan(result);
2061 }
2062
2063 // Visible for testing.
2064 /*package*/ void createMoreChipPlainText() {
2065 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
2066 Editable text = getText();
2067 int start = 0;
2068 int end = start;
2069 for (int i = 0; i < CHIP_LIMIT; i++) {
2070 end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2071 start = end; // move to the next token and get its end.
2072 }
2073 // Now, count total addresses.
2074 start = 0;
2075 int tokenCount = countTokens(text);
2076 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
2077 SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
2078 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2079 text.replace(end, text.length(), chipText);
2080 mMoreChip = moreSpan;
2081 }
2082
2083 // Visible for testing.
2084 /* package */int countTokens(Editable text) {
2085 int tokenCount = 0;
2086 int start = 0;
2087 while (start < text.length()) {
2088 start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2089 tokenCount++;
2090 if (start >= text.length()) {
2091 break;
2092 }
2093 }
2094 return tokenCount;
2095 }
2096
2097 /**
2098 * Create the more chip. The more chip is text that replaces any chips that
2099 * do not fit in the pre-defined available space when the
2100 * RecipientEditTextView loses focus.
2101 */
2102 // Visible for testing.
2103 /* package */ void createMoreChip() {
2104 if (mNoChips) {
2105 createMoreChipPlainText();
2106 return;
2107 }
2108
2109 if (!mShouldShrink) {
2110 return;
2111 }
Jin Cao6c2a0162014-08-17 15:00:50 -07002112 ReplacementDrawableSpan[] tempMore = getSpannable().getSpans(0, getText().length(),
2113 MoreImageSpan.class);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002114 if (tempMore.length > 0) {
2115 getSpannable().removeSpan(tempMore[0]);
2116 }
Scott Kennedy194d4272013-03-06 22:06:45 -08002117 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002118
2119 if (recipients == null || recipients.length <= CHIP_LIMIT) {
Mindy Pereira3bb52162011-07-01 14:52:22 -07002120 mMoreChip = null;
2121 return;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002122 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002123 Spannable spannable = getSpannable();
2124 int numRecipients = recipients.length;
2125 int overage = numRecipients - CHIP_LIMIT;
2126 MoreImageSpan moreSpan = createMoreSpan(overage);
Scott Kennedy194d4272013-03-06 22:06:45 -08002127 mRemovedSpans = new ArrayList<DrawableRecipientChip>();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002128 int totalReplaceStart = 0;
2129 int totalReplaceEnd = 0;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002130 Editable text = getText();
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002131 for (int i = numRecipients - overage; i < recipients.length; i++) {
2132 mRemovedSpans.add(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002133 if (i == numRecipients - overage) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002134 totalReplaceStart = spannable.getSpanStart(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002135 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002136 if (i == recipients.length - 1) {
2137 totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002138 }
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002139 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
2140 int spanStart = spannable.getSpanStart(recipients[i]);
2141 int spanEnd = spannable.getSpanEnd(recipients[i]);
2142 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
Mindy Pereira18529312011-06-28 11:00:52 -07002143 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002144 spannable.removeSpan(recipients[i]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002145 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002146 if (totalReplaceEnd < text.length()) {
2147 totalReplaceEnd = text.length();
2148 }
Mindy Pereira18529312011-06-28 11:00:52 -07002149 int end = Math.max(totalReplaceStart, totalReplaceEnd);
2150 int start = Math.min(totalReplaceStart, totalReplaceEnd);
2151 SpannableString chipText = new SpannableString(text.subSequence(start, end));
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002152 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereira18529312011-06-28 11:00:52 -07002153 text.replace(start, end, chipText);
Mindy Pereira3bb52162011-07-01 14:52:22 -07002154 mMoreChip = moreSpan;
mindyp5e60c2b2012-11-06 17:47:40 -08002155 // If adding the +more chip goes over the limit, resize accordingly.
2156 if (!isPhoneQuery() && getLineCount() > mMaxLines) {
2157 setMaxLines(getLineCount());
2158 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002159 }
2160
Mindy Pereiraa8166902011-06-09 17:53:23 -07002161 /**
2162 * Replace the more chip, if it exists, with all of the recipient chips it had
2163 * replaced when the RecipientEditTextView gains focus.
2164 */
Mindy Pereirad7192502011-09-22 08:04:45 -07002165 // Visible for testing.
2166 /*package*/ void removeMoreChip() {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002167 if (mMoreChip != null) {
2168 Spannable span = getSpannable();
2169 span.removeSpan(mMoreChip);
2170 mMoreChip = null;
2171 // Re-add the spans that were removed.
2172 if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
2173 // Recreate each removed span.
Scott Kennedy194d4272013-03-06 22:06:45 -08002174 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereira54effe92011-09-09 09:46:38 -07002175 // Start the search for tokens after the last currently visible
2176 // chip.
Mindy Pereiraee48f732011-09-20 08:13:39 -07002177 if (recipients == null || recipients.length == 0) {
2178 return;
2179 }
Mindy Pereira54effe92011-09-09 09:46:38 -07002180 int end = span.getSpanEnd(recipients[recipients.length - 1]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002181 Editable editable = getText();
Scott Kennedy194d4272013-03-06 22:06:45 -08002182 for (DrawableRecipientChip chip : mRemovedSpans) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002183 int chipStart;
Mindy Pereira3bb52162011-07-01 14:52:22 -07002184 int chipEnd;
2185 String token;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002186 // Need to find the location of the chip, again.
2187 token = (String) chip.getOriginalText();
Mindy Pereira54effe92011-09-09 09:46:38 -07002188 // As we find the matching recipient for the remove spans,
2189 // reduce the size of the string we need to search.
2190 // That way, if there are duplicates, we always find the correct
2191 // recipient.
2192 chipStart = editable.toString().indexOf(token, end);
Mindy Pereira54effe92011-09-09 09:46:38 -07002193 end = chipEnd = Math.min(editable.length(), chipStart + token.length());
Mindy Pereira0d8b77a2011-07-08 10:26:30 -07002194 // Only set the span if we found a matching token.
2195 if (chipStart != -1) {
2196 editable.setSpan(chip, chipStart, chipEnd,
2197 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
2198 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002199 }
2200 mRemovedSpans.clear();
2201 }
2202 }
2203 }
2204
Mindy Pereiracd611952011-06-01 17:02:20 -07002205 /**
Mindy Pereira95a69252011-06-17 15:02:03 -07002206 * Show specified chip as selected. If the RecipientChip is just an email address,
2207 * selecting the chip will take the contents of the chip and place it at
2208 * the end of the RecipientEditTextView for inline editing. If the
2209 * RecipientChip is a complete contact, then selecting the chip
2210 * will change the background color of the chip, show the delete icon,
2211 * and a popup window with the address in use highlighted and any other
2212 * alternate addresses for the contact.
2213 * @param currentChip Chip to select.
2214 * @return A RecipientChip in the selected state or null if the chip
2215 * just contained an email address.
Mindy Pereiracd611952011-06-01 17:02:20 -07002216 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002217 private DrawableRecipientChip selectChip(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002218 if (shouldShowEditableText(currentChip)) {
Mindy Pereira01382d72011-07-15 16:52:32 -07002219 CharSequence text = currentChip.getValue();
2220 Editable editable = getText();
mindypf30a4282012-12-03 12:16:33 -08002221 Spannable spannable = getSpannable();
2222 int spanStart = spannable.getSpanStart(currentChip);
2223 int spanEnd = spannable.getSpanEnd(currentChip);
2224 spannable.removeSpan(currentChip);
Jin Cao15a5ebc2014-09-18 16:43:32 -07002225 // Don't need leading space if it's the only chip
2226 if (spanEnd - spanStart == editable.length() - 1) {
2227 spanEnd++;
2228 }
mindypf30a4282012-12-03 12:16:33 -08002229 editable.delete(spanStart, spanEnd);
Mindy Pereira01382d72011-07-15 16:52:32 -07002230 setCursorVisible(true);
2231 setSelection(editable.length());
mindypf30a4282012-12-03 12:16:33 -08002232 editable.append(text);
2233 return constructChipSpan(
2234 RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())),
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002235 true);
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002236 } else {
Mindy Pereira95a69252011-06-17 15:02:03 -07002237 int start = getChipStart(currentChip);
2238 int end = getChipEnd(currentChip);
2239 getSpannable().removeSpan(currentChip);
Scott Kennedy194d4272013-03-06 22:06:45 -08002240 DrawableRecipientChip newChip;
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002241 final boolean showAddress =
2242 currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT ||
2243 getAdapter().forceShowAddress();
Mindy Pereira95a69252011-06-17 15:02:03 -07002244 try {
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002245 if (showAddress && mNoChips) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002246 return null;
2247 }
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002248 newChip = constructChipSpan(currentChip.getEntry(), true);
Mindy Pereira95a69252011-06-17 15:02:03 -07002249 } catch (NullPointerException e) {
2250 Log.e(TAG, e.getMessage(), e);
Mindy Pereira0ab7e732011-06-08 10:17:39 -07002251 return null;
Mindy Pereiracd611952011-06-01 17:02:20 -07002252 }
Mindy Pereira0ab7e732011-06-08 10:17:39 -07002253 Editable editable = getText();
Mindy Pereira95a69252011-06-17 15:02:03 -07002254 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereira0ab7e732011-06-08 10:17:39 -07002255 if (start == -1 || end == -1) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002256 Log.d(TAG, "The chip being selected no longer exists but should.");
Mindy Pereiracd611952011-06-01 17:02:20 -07002257 } else {
Mindy Pereira04da3252011-07-06 16:09:25 -07002258 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiracd611952011-06-01 17:02:20 -07002259 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002260 newChip.setSelected(true);
mindyp5e60c2b2012-11-06 17:47:40 -08002261 if (shouldShowEditableText(newChip)) {
Mindy Pereira01382d72011-07-15 16:52:32 -07002262 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
2263 }
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002264 if (showAddress) {
Jin Cao9b166202014-08-08 13:26:14 -07002265 showAddress(newChip, mAddressPopup);
Mindy Pereira01382d72011-07-15 16:52:32 -07002266 } else {
Jin Cao9b166202014-08-08 13:26:14 -07002267 showAlternates(newChip, mAlternatesPopup);
Mindy Pereira01382d72011-07-15 16:52:32 -07002268 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07002269 setCursorVisible(false);
Mindy Pereira95a69252011-06-17 15:02:03 -07002270 return newChip;
Mindy Pereira95a69252011-06-17 15:02:03 -07002271 }
2272 }
2273
Scott Kennedy194d4272013-03-06 22:06:45 -08002274 private boolean shouldShowEditableText(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002275 long contactId = currentChip.getContactId();
2276 return contactId == RecipientEntry.INVALID_CONTACT
2277 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2278 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002279
Jin Cao9b166202014-08-08 13:26:14 -07002280 private void showAddress(final DrawableRecipientChip currentChip, final ListPopupWindow popup) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07002281 if (!mAttachedToWindow) {
2282 return;
2283 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002284 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07002285 int bottomOffset = calculateOffsetFromBottomToTop(line);
Mindy Pereira01382d72011-07-15 16:52:32 -07002286 // Align the alternates popup with the left side of the View,
2287 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07002288 popup.setAnchorView((mAlternatePopupAnchor != null) ? mAlternatePopupAnchor : this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07002289 popup.setVerticalOffset(bottomOffset);
Mindy Pereira01382d72011-07-15 16:52:32 -07002290 popup.setAdapter(createSingleAddressAdapter(currentChip));
2291 popup.setOnItemClickListener(new OnItemClickListener() {
2292 @Override
2293 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2294 unselectChip(currentChip);
Mindy Pereira01382d72011-07-15 16:52:32 -07002295 }
2296 });
2297 popup.show();
2298 ListView listView = popup.getListView();
2299 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2300 listView.setItemChecked(0, true);
2301 }
2302
Mindy Pereira95a69252011-06-17 15:02:03 -07002303 /**
2304 * Remove selection from this chip. Unselecting a RecipientChip will render
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002305 * the chip without a delete icon and with an unfocused background. This is
2306 * called when the RecipientChip no longer has focus.
Mindy Pereira95a69252011-06-17 15:02:03 -07002307 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002308 private void unselectChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002309 int start = getChipStart(chip);
2310 int end = getChipEnd(chip);
2311 Editable editable = getText();
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002312 mSelectedChip = null;
Mindy Pereira95a69252011-06-17 15:02:03 -07002313 if (start == -1 || end == -1) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002314 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002315 setSelection(editable.length());
2316 commitDefault();
Mindy Pereira95a69252011-06-17 15:02:03 -07002317 } else {
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002318 getSpannable().removeSpan(chip);
Mindy Pereira95a69252011-06-17 15:02:03 -07002319 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereira04da3252011-07-06 16:09:25 -07002320 editable.removeSpan(chip);
2321 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002322 if (!mNoChips) {
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002323 editable.setSpan(constructChipSpan(chip.getEntry(), false),
mindyp5e60c2b2012-11-06 17:47:40 -08002324 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002325 }
Mindy Pereira04da3252011-07-06 16:09:25 -07002326 } catch (NullPointerException e) {
2327 Log.e(TAG, e.getMessage(), e);
2328 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002329 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002330 setCursorVisible(true);
2331 setSelection(editable.length());
Jin Cao568fb222014-08-19 13:50:59 -07002332 dismissPopups();
Mindy Pereira95a69252011-06-17 15:02:03 -07002333 }
2334
Jin Cao4db8ccc2014-07-30 10:11:07 -07002335 @Override
2336 public void onChipDelete() {
2337 if (mSelectedChip != null) {
2338 removeChip(mSelectedChip);
Jin Cao4db8ccc2014-07-30 10:11:07 -07002339 }
Jin Cao568fb222014-08-19 13:50:59 -07002340 dismissPopups();
2341 }
2342
2343 private void dismissPopups() {
2344 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2345 mAlternatesPopup.dismiss();
2346 }
2347 if (mAddressPopup != null && mAddressPopup.isShowing()) {
2348 mAddressPopup.dismiss();
2349 }
Jin Cao4db8ccc2014-07-30 10:11:07 -07002350 }
2351
Mindy Pereira95a69252011-06-17 15:02:03 -07002352 /**
2353 * Remove the chip and any text associated with it from the RecipientEditTextView.
2354 */
Mindy Pereira97cb2592011-09-26 16:11:41 -07002355 // Visible for testing.
Kevin Linb10d1c62014-01-24 12:45:00 -08002356 /* package */void removeChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002357 Spannable spannable = getSpannable();
2358 int spanStart = spannable.getSpanStart(chip);
2359 int spanEnd = spannable.getSpanEnd(chip);
2360 Editable text = getText();
Mindy Pereira62397a52011-10-03 13:46:43 -07002361 int toDelete = spanEnd;
Mindy Pereira95a69252011-06-17 15:02:03 -07002362 boolean wasSelected = chip == mSelectedChip;
2363 // Clear that there is a selected chip before updating any text.
2364 if (wasSelected) {
2365 mSelectedChip = null;
2366 }
Mindy Pereira62397a52011-10-03 13:46:43 -07002367 // Always remove trailing spaces when removing a chip.
2368 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2369 toDelete++;
2370 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002371 spannable.removeSpan(chip);
Mindy Pereiraf6d4bfc2012-04-24 15:13:34 -07002372 if (spanStart >= 0 && toDelete > 0) {
2373 text.delete(spanStart, toDelete);
2374 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002375 if (wasSelected) {
2376 clearSelectedChip();
2377 }
2378 }
2379
2380 /**
2381 * Replace this currently selected chip with a new chip
2382 * that uses the contact data provided.
2383 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07002384 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002385 /*package*/ void replaceChip(DrawableRecipientChip chip, RecipientEntry entry) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002386 boolean wasSelected = chip == mSelectedChip;
2387 if (wasSelected) {
2388 mSelectedChip = null;
2389 }
2390 int start = getChipStart(chip);
2391 int end = getChipEnd(chip);
2392 getSpannable().removeSpan(chip);
2393 Editable editable = getText();
2394 CharSequence chipText = createChip(entry, false);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002395 if (chipText != null) {
2396 if (start == -1 || end == -1) {
2397 Log.e(TAG, "The chip to replace does not exist but should.");
2398 editable.insert(0, chipText);
2399 } else {
2400 if (!TextUtils.isEmpty(chipText)) {
2401 // There may be a space to replace with this chip's new
mindypb5afbc72012-10-03 11:57:42 -07002402 // associated space. Check for it
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002403 int toReplace = end;
2404 while (toReplace >= 0 && toReplace < editable.length()
2405 && editable.charAt(toReplace) == ' ') {
2406 toReplace++;
2407 }
2408 editable.replace(start, toReplace, chipText);
Mindy Pereira62397a52011-10-03 13:46:43 -07002409 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07002410 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002411 }
2412 setCursorVisible(true);
2413 if (wasSelected) {
2414 clearSelectedChip();
2415 }
2416 }
2417
2418 /**
2419 * Handle click events for a chip. When a selected chip receives a click
2420 * event, see if that event was in the delete icon. If so, delete it.
2421 * Otherwise, unselect the chip.
2422 */
Jin Caoa21fd882014-08-10 13:07:11 -07002423 public void onClick(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002424 if (chip.isSelected()) {
Jin Caoa21fd882014-08-10 13:07:11 -07002425 clearSelectedChip();
Mindy Pereiracd611952011-06-01 17:02:20 -07002426 }
Mindy Pereira9159cd22011-05-25 17:06:44 -07002427 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002428
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002429 private boolean chipsPending() {
2430 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2431 }
2432
Mindy Pereira883c4992011-08-04 18:01:30 -07002433 @Override
2434 public void removeTextChangedListener(TextWatcher watcher) {
2435 mTextWatcher = null;
2436 super.removeTextChangedListener(watcher);
2437 }
2438
Jin Caob3b248a2014-04-11 10:43:50 -07002439 private boolean isValidEmailAddress(String input) {
2440 return !TextUtils.isEmpty(input) && mValidator != null &&
2441 mValidator.isValid(input);
2442 }
2443
Mindy Pereira79fb4362011-06-21 14:37:07 -07002444 private class RecipientTextWatcher implements TextWatcher {
Mindy Pereira72a23392012-02-06 10:19:51 -08002445
Mindy Pereira79fb4362011-06-21 14:37:07 -07002446 @Override
2447 public void afterTextChanged(Editable s) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002448 // If the text has been set to null or empty, make sure we remove
2449 // all the spans we applied.
2450 if (TextUtils.isEmpty(s)) {
2451 // Remove all the chips spans.
2452 Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08002453 DrawableRecipientChip[] chips = spannable.getSpans(0, getText().length(),
2454 DrawableRecipientChip.class);
2455 for (DrawableRecipientChip chip : chips) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002456 spannable.removeSpan(chip);
2457 }
2458 if (mMoreChip != null) {
2459 spannable.removeSpan(mMoreChip);
2460 }
Kevin Lin41e93fb2014-02-03 17:35:29 -08002461 clearSelectedChip();
Mindy Pereira32366d42011-07-24 12:39:30 -07002462 return;
2463 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002464 // Get whether there are any recipients pending addition to the
2465 // view. If there are, don't do anything in the text watcher.
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002466 if (chipsPending()) {
Mindy Pereira79fb4362011-06-21 14:37:07 -07002467 return;
2468 }
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002469 // If the user is editing a chip, don't clear it.
mindypf30a4282012-12-03 12:16:33 -08002470 if (mSelectedChip != null) {
2471 if (!isGeneratedContact(mSelectedChip)) {
2472 setCursorVisible(true);
2473 setSelection(getText().length());
2474 clearSelectedChip();
2475 } else {
2476 return;
2477 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002478 }
2479 int length = s.length();
2480 // Make sure there is content there to parse and that it is
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002481 // not just the commit character.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002482 if (length > 1) {
mindypf30a4282012-12-03 12:16:33 -08002483 if (lastCharacterIsCommitCharacter(s)) {
2484 commitByCharacter();
2485 return;
2486 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002487 char last;
Mindy Pereira11a2adb2011-06-28 09:57:43 -07002488 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002489 int len = length() - 1;
2490 if (end != len) {
2491 last = s.charAt(end);
2492 } else {
2493 last = s.charAt(len);
2494 }
mindypf30a4282012-12-03 12:16:33 -08002495 if (last == COMMIT_CHAR_SPACE) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002496 if (!isPhoneQuery()) {
2497 // Check if this is a valid email address. If it is,
2498 // commit it.
2499 String text = getText().toString();
2500 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2501 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2502 tokenStart));
Jin Caob3b248a2014-04-11 10:43:50 -07002503 if (isValidEmailAddress(sub)) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002504 commitByCharacter();
2505 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002506 }
2507 }
2508 }
2509 }
2510
2511 @Override
2512 public void onTextChanged(CharSequence s, int start, int before, int count) {
mindypf30a4282012-12-03 12:16:33 -08002513 // The user deleted some text OR some text was replaced; check to
2514 // see if the insertion point is on a space
Mindy Pereira72a23392012-02-06 10:19:51 -08002515 // following a chip.
mindypf30a4282012-12-03 12:16:33 -08002516 if (before - count == 1) {
Mindy Pereira72a23392012-02-06 10:19:51 -08002517 // If the item deleted is a space, and the thing before the
2518 // space is a chip, delete the entire span.
2519 int selStart = getSelectionStart();
Scott Kennedy194d4272013-03-06 22:06:45 -08002520 DrawableRecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2521 DrawableRecipientChip.class);
Mindy Pereira72a23392012-02-06 10:19:51 -08002522 if (repl.length > 0) {
2523 // There is a chip there! Just remove it.
2524 Editable editable = getText();
2525 // Add the separator token.
2526 int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2527 int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
Mindy Pereira62fce932012-02-16 15:00:30 -08002528 tokenEnd = tokenEnd + 1;
2529 if (tokenEnd > editable.length()) {
2530 tokenEnd = editable.length();
2531 }
2532 editable.delete(tokenStart, tokenEnd);
Mindy Pereira72a23392012-02-06 10:19:51 -08002533 getSpannable().removeSpan(repl[0]);
2534 }
Mindy Pereira4e7d20f2012-07-16 08:09:01 -07002535 } else if (count > before) {
mindyp7e10c862012-11-27 11:13:26 -08002536 if (mSelectedChip != null
2537 && isGeneratedContact(mSelectedChip)) {
2538 if (lastCharacterIsCommitCharacter(s)) {
2539 commitByCharacter();
2540 return;
2541 }
2542 }
Mindy Pereira72a23392012-02-06 10:19:51 -08002543 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002544 }
2545
2546 @Override
2547 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002548 // Do nothing.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002549 }
2550 }
Mindy Pereira18529312011-06-28 11:00:52 -07002551
Alice Yangc1b52582013-03-04 19:54:00 -08002552 public boolean lastCharacterIsCommitCharacter(CharSequence s) {
mindypf30a4282012-12-03 12:16:33 -08002553 char last;
2554 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2555 int len = length() - 1;
2556 if (end != len) {
2557 last = s.charAt(end);
2558 } else {
2559 last = s.charAt(len);
2560 }
2561 return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON;
2562 }
2563
Scott Kennedy194d4272013-03-06 22:06:45 -08002564 public boolean isGeneratedContact(DrawableRecipientChip chip) {
mindypf30a4282012-12-03 12:16:33 -08002565 long contactId = chip.getContactId();
2566 return contactId == RecipientEntry.INVALID_CONTACT
2567 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2568 }
2569
Minh Phame51c7222011-10-12 11:33:26 -07002570 /**
2571 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2572 */
Régis Décamps219cbfb2014-06-04 14:29:54 +02002573 // Visible for testing.
2574 void handlePasteClip(ClipData clip) {
2575 if (clip == null) {
2576 // Do nothing.
2577 return;
2578 }
2579
2580 final ClipDescription clipDesc = clip.getDescription();
2581 boolean containsSupportedType = clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||
2582 clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML);
2583 if (!containsSupportedType) {
2584 return;
2585 }
2586
Minh Phame51c7222011-10-12 11:33:26 -07002587 removeTextChangedListener(mTextWatcher);
2588
Régis Décamps219cbfb2014-06-04 14:29:54 +02002589 final ClipDescription clipDescription = clip.getDescription();
2590 for (int i = 0; i < clip.getItemCount(); i++) {
2591 final String mimeType = clipDescription.getMimeType(i);
2592 final boolean supportedType = ClipDescription.MIMETYPE_TEXT_PLAIN.equals(mimeType) ||
2593 ClipDescription.MIMETYPE_TEXT_HTML.equals(mimeType);
2594 if (!supportedType) {
2595 // Only plain text and html can be pasted.
2596 continue;
2597 }
2598
2599 final CharSequence pastedItem = clip.getItemAt(i).getText();
2600 if (!TextUtils.isEmpty(pastedItem)) {
2601 final Editable editable = getText();
2602 final int start = getSelectionStart();
2603 final int end = getSelectionEnd();
2604 if (start < 0 || end < 1) {
2605 // No selection.
2606 editable.append(pastedItem);
2607 } else if (start == end) {
2608 // Insert at position.
2609 editable.insert(start, pastedItem);
2610 } else {
2611 editable.append(pastedItem, start, end);
Minh Phame51c7222011-10-12 11:33:26 -07002612 }
Régis Décamps219cbfb2014-06-04 14:29:54 +02002613 handlePasteAndReplace();
Minh Phame51c7222011-10-12 11:33:26 -07002614 }
2615 }
2616
2617 mHandler.post(mAddTextWatcher);
2618 }
2619
Mindy Pereira20c9d622011-10-12 13:18:04 -07002620 @Override
2621 public boolean onTextContextMenuItem(int id) {
2622 if (id == android.R.id.paste) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002623 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2624 Context.CLIPBOARD_SERVICE);
Minh Phame51c7222011-10-12 11:33:26 -07002625 handlePasteClip(clipboard.getPrimaryClip());
Mindy Pereira20c9d622011-10-12 13:18:04 -07002626 return true;
2627 }
2628 return super.onTextContextMenuItem(id);
2629 }
2630
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002631 private void handlePasteAndReplace() {
Scott Kennedy194d4272013-03-06 22:06:45 -08002632 ArrayList<DrawableRecipientChip> created = handlePaste();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002633 if (created != null && created.size() > 0) {
2634 // Perform reverse lookups on the pasted contacts.
2635 IndividualReplacementTask replace = new IndividualReplacementTask();
2636 replace.execute(created);
2637 }
2638 }
2639
Mindy Pereira20c9d622011-10-12 13:18:04 -07002640 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002641 /* package */ArrayList<DrawableRecipientChip> handlePaste() {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002642 String text = getText().toString();
2643 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2644 String lastAddress = text.substring(originalTokenStart);
2645 int tokenStart = originalTokenStart;
jli119X0cae8502012-10-18 12:55:47 +08002646 int prevTokenStart = 0;
Scott Kennedy194d4272013-03-06 22:06:45 -08002647 DrawableRecipientChip findChip = null;
2648 ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
Mindy Pereira20c9d622011-10-12 13:18:04 -07002649 if (tokenStart != 0) {
2650 // There are things before this!
jli119X0cae8502012-10-18 12:55:47 +08002651 while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002652 prevTokenStart = tokenStart;
2653 tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2654 findChip = findChip(tokenStart);
Tom Taylorfda01702013-01-14 16:52:25 -08002655 if (tokenStart == originalTokenStart && findChip == null) {
2656 break;
2657 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002658 }
2659 if (tokenStart != originalTokenStart) {
2660 if (findChip != null) {
2661 tokenStart = prevTokenStart;
2662 }
2663 int tokenEnd;
Scott Kennedy194d4272013-03-06 22:06:45 -08002664 DrawableRecipientChip createdChip;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002665 while (tokenStart < originalTokenStart) {
mindypb5afbc72012-10-03 11:57:42 -07002666 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2667 tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002668 commitChip(tokenStart, tokenEnd, getText());
2669 createdChip = findChip(tokenStart);
Mindy Pereirac52ea8e2012-06-04 15:24:55 -07002670 if (createdChip == null) {
2671 break;
2672 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002673 // +1 for the space at the end.
2674 tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002675 created.add(createdChip);
Mindy Pereira20c9d622011-10-12 13:18:04 -07002676 }
2677 }
2678 }
2679 // Take a look at the last token. If the token has been completed with a
2680 // commit character, create a chip.
2681 if (isCompletedToken(lastAddress)) {
2682 Editable editable = getText();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002683 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2684 commitChip(tokenStart, editable.length(), editable);
2685 created.add(findChip(tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002686 }
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002687 return created;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002688 }
2689
2690 // Visible for testing.
2691 /* package */int movePastTerminators(int tokenEnd) {
2692 if (tokenEnd >= length()) {
2693 return tokenEnd;
2694 }
2695 char atEnd = getText().toString().charAt(tokenEnd);
2696 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2697 tokenEnd++;
2698 }
2699 // This token had not only an end token character, but also a space
2700 // separating it from the next token.
2701 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2702 tokenEnd++;
2703 }
2704 return tokenEnd;
2705 }
2706
Mindy Pereira18529312011-06-28 11:00:52 -07002707 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
Scott Kennedy194d4272013-03-06 22:06:45 -08002708 private DrawableRecipientChip createFreeChip(RecipientEntry entry) {
Mindy Pereira18529312011-06-28 11:00:52 -07002709 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002710 if (mNoChips) {
2711 return null;
2712 }
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002713 return constructChipSpan(entry, false);
Mindy Pereira18529312011-06-28 11:00:52 -07002714 } catch (NullPointerException e) {
2715 Log.e(TAG, e.getMessage(), e);
2716 return null;
2717 }
2718 }
2719
2720 @Override
Scott Kennedy78f38a02013-02-27 11:21:40 -08002721 protected void onPreExecute() {
2722 // Ensure everything is in chip-form already, so we don't have text that slowly gets
2723 // replaced
Scott Kennedy194d4272013-03-06 22:06:45 -08002724 final List<DrawableRecipientChip> originalRecipients =
2725 new ArrayList<DrawableRecipientChip>();
2726 final DrawableRecipientChip[] existingChips = getSortedRecipients();
Scott Kennedy78f38a02013-02-27 11:21:40 -08002727 for (int i = 0; i < existingChips.length; i++) {
2728 originalRecipients.add(existingChips[i]);
2729 }
2730 if (mRemovedSpans != null) {
2731 originalRecipients.addAll(mRemovedSpans);
2732 }
2733
Scott Kennedy194d4272013-03-06 22:06:45 -08002734 final List<DrawableRecipientChip> replacements =
2735 new ArrayList<DrawableRecipientChip>(originalRecipients.size());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002736
Scott Kennedy194d4272013-03-06 22:06:45 -08002737 for (final DrawableRecipientChip chip : originalRecipients) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002738 if (RecipientEntry.isCreatedRecipient(chip.getEntry().getContactId())
2739 && getSpannable().getSpanStart(chip) != -1) {
2740 replacements.add(createFreeChip(chip.getEntry()));
2741 } else {
2742 replacements.add(null);
2743 }
2744 }
2745
2746 processReplacements(originalRecipients, replacements);
2747 }
2748
2749 @Override
Mindy Pereira18529312011-06-28 11:00:52 -07002750 protected Void doInBackground(Void... params) {
2751 if (mIndividualReplacements != null) {
2752 mIndividualReplacements.cancel(true);
2753 }
2754 // For each chip in the list, look up the matching contact.
2755 // If there is a match, replace that chip with the matching
2756 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002757 final ArrayList<DrawableRecipientChip> recipients =
2758 new ArrayList<DrawableRecipientChip>();
2759 DrawableRecipientChip[] existingChips = getSortedRecipients();
Mindy Pereira18529312011-06-28 11:00:52 -07002760 for (int i = 0; i < existingChips.length; i++) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002761 recipients.add(existingChips[i]);
Mindy Pereira18529312011-06-28 11:00:52 -07002762 }
2763 if (mRemovedSpans != null) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002764 recipients.addAll(mRemovedSpans);
Mindy Pereira18529312011-06-28 11:00:52 -07002765 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002766 ArrayList<String> addresses = new ArrayList<String>();
Scott Kennedy194d4272013-03-06 22:06:45 -08002767 DrawableRecipientChip chip;
Scott Kennedy78f38a02013-02-27 11:21:40 -08002768 for (int i = 0; i < recipients.size(); i++) {
2769 chip = recipients.get(i);
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002770 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002771 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002772 }
Mindy Pereira18529312011-06-28 11:00:52 -07002773 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002774 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002775 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002776 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002777 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002778 final ArrayList<DrawableRecipientChip> replacements =
2779 new ArrayList<DrawableRecipientChip>();
2780 for (final DrawableRecipientChip temp : recipients) {
mindyp16923ee2012-12-10 11:58:29 -08002781 RecipientEntry entry = null;
Alice Yangf0579ee2013-03-04 14:10:21 -08002782 if (temp != null && RecipientEntry.isCreatedRecipient(
2783 temp.getEntry().getContactId())
mindyp16923ee2012-12-10 11:58:29 -08002784 && getSpannable().getSpanStart(temp) != -1) {
2785 // Replace this.
2786 entry = createValidatedEntry(
2787 entries.get(tokenizeAddress(temp.getEntry()
2788 .getDestination())));
2789 }
2790 if (entry != null) {
2791 replacements.add(createFreeChip(entry));
2792 } else {
2793 replacements.add(null);
2794 }
Mindy Pereira18529312011-06-28 11:00:52 -07002795 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002796 processReplacements(recipients, replacements);
Mindy Pereira18529312011-06-28 11:00:52 -07002797 }
Scott Kennedy94fa3012013-02-15 18:22:05 -08002798
2799 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002800 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002801 final List<DrawableRecipientChip> replacements =
2802 new ArrayList<DrawableRecipientChip>(unfoundAddresses.size());
Scott Kennedy94fa3012013-02-15 18:22:05 -08002803
Scott Kennedy194d4272013-03-06 22:06:45 -08002804 for (final DrawableRecipientChip temp : recipients) {
Alice Yangad8781e2013-03-04 14:45:38 -08002805 if (temp != null && RecipientEntry.isCreatedRecipient(
2806 temp.getEntry().getContactId())
Scott Kennedy94fa3012013-02-15 18:22:05 -08002807 && getSpannable().getSpanStart(temp) != -1) {
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002808 if (unfoundAddresses.contains(
2809 temp.getEntry().getDestination())) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002810 replacements.add(createFreeChip(temp.getEntry()));
2811 } else {
2812 replacements.add(null);
2813 }
2814 } else {
2815 replacements.add(null);
2816 }
2817 }
2818
Scott Kennedy78f38a02013-02-27 11:21:40 -08002819 processReplacements(recipients, replacements);
Scott Kennedy94fa3012013-02-15 18:22:05 -08002820 }
mindyp16923ee2012-12-10 11:58:29 -08002821 });
Mindy Pereira18529312011-06-28 11:00:52 -07002822 return null;
2823 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002824
Scott Kennedy194d4272013-03-06 22:06:45 -08002825 private void processReplacements(final List<DrawableRecipientChip> recipients,
2826 final List<DrawableRecipientChip> replacements) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002827 if (replacements != null && replacements.size() > 0) {
2828 final Runnable runnable = new Runnable() {
2829 @Override
2830 public void run() {
Scott Kennedy0e128962013-04-11 10:52:08 -07002831 final Editable text = new SpannableStringBuilder(getText());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002832 int i = 0;
Scott Kennedy0e128962013-04-11 10:52:08 -07002833 for (final DrawableRecipientChip chip : recipients) {
2834 final DrawableRecipientChip replacement = replacements.get(i);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002835 if (replacement != null) {
2836 final RecipientEntry oldEntry = chip.getEntry();
2837 final RecipientEntry newEntry = replacement.getEntry();
2838 final boolean isBetter =
2839 RecipientAlternatesAdapter.getBetterRecipient(
2840 oldEntry, newEntry) == newEntry;
2841
2842 if (isBetter) {
2843 // Find the location of the chip in the text currently shown.
Scott Kennedy0e128962013-04-11 10:52:08 -07002844 final int start = text.getSpanStart(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002845 if (start != -1) {
2846 // Replacing the entirety of what the chip represented,
2847 // including the extra space dividing it from other chips.
Paul Westbrookb023f692013-04-22 12:27:35 -07002848 final int end =
2849 Math.min(text.getSpanEnd(chip) + 1, text.length());
Scott Kennedy0e128962013-04-11 10:52:08 -07002850 text.removeSpan(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002851 // Make sure we always have just 1 space at the end to
2852 // separate this chip from the next chip.
Scott Kennedy0e128962013-04-11 10:52:08 -07002853 final SpannableString displayText =
Scott Kennedy78f38a02013-02-27 11:21:40 -08002854 new SpannableString(createAddressText(
Scott Kennedy0e128962013-04-11 10:52:08 -07002855 replacement.getEntry()).trim() + " ");
Scott Kennedy78f38a02013-02-27 11:21:40 -08002856 displayText.setSpan(replacement, 0,
2857 displayText.length() - 1,
2858 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2859 // Replace the old text we found with with the new display
2860 // text, which now may also contain the display name of the
2861 // recipient.
Scott Kennedy0e128962013-04-11 10:52:08 -07002862 text.replace(start, end, displayText);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002863 replacement.setOriginalText(displayText.toString());
2864 replacements.set(i, null);
2865
2866 recipients.set(i, replacement);
2867 }
2868 }
2869 }
2870 i++;
2871 }
Scott Kennedy0e128962013-04-11 10:52:08 -07002872 setText(text);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002873 }
2874 };
2875
2876 if (Looper.myLooper() == Looper.getMainLooper()) {
2877 runnable.run();
2878 } else {
2879 mHandler.post(runnable);
2880 }
2881 }
2882 }
Mindy Pereira18529312011-06-28 11:00:52 -07002883 }
2884
Scott Kennedy78f38a02013-02-27 11:21:40 -08002885 private class IndividualReplacementTask
Scott Kennedy194d4272013-03-06 22:06:45 -08002886 extends AsyncTask<ArrayList<DrawableRecipientChip>, Void, Void> {
Mindy Pereira18529312011-06-28 11:00:52 -07002887 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08002888 protected Void doInBackground(ArrayList<DrawableRecipientChip>... params) {
Mindy Pereira18529312011-06-28 11:00:52 -07002889 // For each chip in the list, look up the matching contact.
2890 // If there is a match, replace that chip with the matching
2891 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002892 final ArrayList<DrawableRecipientChip> originalRecipients = params[0];
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002893 ArrayList<String> addresses = new ArrayList<String>();
Scott Kennedy194d4272013-03-06 22:06:45 -08002894 DrawableRecipientChip chip;
Mindy Pereira18529312011-06-28 11:00:52 -07002895 for (int i = 0; i < originalRecipients.size(); i++) {
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002896 chip = originalRecipients.get(i);
2897 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002898 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002899 }
Mindy Pereira18529312011-06-28 11:00:52 -07002900 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002901 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002902 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002903
2904 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002905 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002906 for (final DrawableRecipientChip temp : originalRecipients) {
mindyp16923ee2012-12-10 11:58:29 -08002907 if (RecipientEntry.isCreatedRecipient(temp.getEntry()
2908 .getContactId())
2909 && getSpannable().getSpanStart(temp) != -1) {
2910 // Replace this.
Alon Albert76f1f2d2013-07-14 15:32:49 +03002911 final RecipientEntry entry = createValidatedEntry(entries
mindyp16923ee2012-12-10 11:58:29 -08002912 .get(tokenizeAddress(temp.getEntry().getDestination())
2913 .toLowerCase()));
Alon Albert76f1f2d2013-07-14 15:32:49 +03002914 if (entry != null) {
mindyp16923ee2012-12-10 11:58:29 -08002915 mHandler.post(new Runnable() {
2916 @Override
2917 public void run() {
Alon Albert76f1f2d2013-07-14 15:32:49 +03002918 replaceChip(temp, entry);
mindyp16923ee2012-12-10 11:58:29 -08002919 }
2920 });
2921 }
2922 }
Mindy Pereira18529312011-06-28 11:00:52 -07002923 }
mindyp16923ee2012-12-10 11:58:29 -08002924 }
2925
Scott Kennedy94fa3012013-02-15 18:22:05 -08002926 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002927 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002928 // No action required
2929 }
mindyp16923ee2012-12-10 11:58:29 -08002930 });
Mindy Pereira18529312011-06-28 11:00:52 -07002931 return null;
2932 }
2933 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002934
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002935
2936 /**
2937 * MoreImageSpan is a simple class created for tracking the existence of a
2938 * more chip across activity restarts/
2939 */
Jin Cao6c2a0162014-08-17 15:00:50 -07002940 private class MoreImageSpan extends ReplacementDrawableSpan {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002941 public MoreImageSpan(Drawable b) {
2942 super(b);
Jin Cao6c2a0162014-08-17 15:00:50 -07002943 setExtraMargin(mLineSpacingExtra);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002944 }
2945 }
2946
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002947 @Override
2948 public boolean onDown(MotionEvent e) {
2949 return false;
2950 }
2951
2952 @Override
2953 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2954 // Do nothing.
2955 return false;
2956 }
2957
2958 @Override
2959 public void onLongPress(MotionEvent event) {
2960 if (mSelectedChip != null) {
2961 return;
2962 }
2963 float x = event.getX();
2964 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07002965 final int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08002966 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002967 if (currentChip != null) {
Minh Phame51c7222011-10-12 11:33:26 -07002968 if (mDragEnabled) {
2969 // Start drag-and-drop for the selected chip.
2970 startDrag(currentChip);
2971 } else {
2972 // Copy the selected chip email address.
2973 showCopyDialog(currentChip.getEntry().getDestination());
2974 }
2975 }
2976 }
2977
Scott Kennedy1650ef62013-08-02 21:56:47 -07002978 // The following methods are used to provide some functionality on older versions of Android
2979 // These methods were copied out of JB MR2's TextView
2980 /////////////////////////////////////////////////
2981 private int supportGetOffsetForPosition(float x, float y) {
2982 if (getLayout() == null) return -1;
2983 final int line = supportGetLineAtCoordinate(y);
2984 final int offset = supportGetOffsetAtCoordinate(line, x);
2985 return offset;
2986 }
2987
2988 private float supportConvertToLocalHorizontalCoordinate(float x) {
2989 x -= getTotalPaddingLeft();
2990 // Clamp the position to inside of the view.
2991 x = Math.max(0.0f, x);
2992 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
2993 x += getScrollX();
2994 return x;
2995 }
2996
2997 private int supportGetLineAtCoordinate(float y) {
2998 y -= getTotalPaddingLeft();
2999 // Clamp the position to inside of the view.
3000 y = Math.max(0.0f, y);
3001 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
3002 y += getScrollY();
3003 return getLayout().getLineForVertical((int) y);
3004 }
3005
3006 private int supportGetOffsetAtCoordinate(int line, float x) {
3007 x = supportConvertToLocalHorizontalCoordinate(x);
3008 return getLayout().getOffsetForHorizontal(line, x);
3009 }
3010 /////////////////////////////////////////////////
3011
Minh Phame51c7222011-10-12 11:33:26 -07003012 /**
3013 * Enables drag-and-drop for chips.
3014 */
3015 public void enableDrag() {
3016 mDragEnabled = true;
3017 }
3018
3019 /**
3020 * Starts drag-and-drop for the selected chip.
3021 */
Scott Kennedy194d4272013-03-06 22:06:45 -08003022 private void startDrag(DrawableRecipientChip currentChip) {
Minh Phame51c7222011-10-12 11:33:26 -07003023 String address = currentChip.getEntry().getDestination();
3024 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
3025
3026 // Start drag mode.
3027 startDrag(data, new RecipientChipShadow(currentChip), null, 0);
3028
3029 // Remove the current chip, so drag-and-drop will result in a move.
3030 // TODO (phamm): consider readd this chip if it's dropped outside a target.
3031 removeChip(currentChip);
3032 }
3033
3034 /**
3035 * Handles drag event.
3036 */
3037 @Override
3038 public boolean onDragEvent(DragEvent event) {
3039 switch (event.getAction()) {
3040 case DragEvent.ACTION_DRAG_STARTED:
3041 // Only handle plain text drag and drop.
3042 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
3043 case DragEvent.ACTION_DRAG_ENTERED:
3044 requestFocus();
3045 return true;
3046 case DragEvent.ACTION_DROP:
3047 handlePasteClip(event.getClipData());
3048 return true;
3049 }
3050 return false;
3051 }
3052
3053 /**
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07003054 * Drag shadow for a {@link DrawableRecipientChip}.
Minh Phame51c7222011-10-12 11:33:26 -07003055 */
3056 private final class RecipientChipShadow extends DragShadowBuilder {
Scott Kennedy194d4272013-03-06 22:06:45 -08003057 private final DrawableRecipientChip mChip;
Minh Phame51c7222011-10-12 11:33:26 -07003058
Scott Kennedy194d4272013-03-06 22:06:45 -08003059 public RecipientChipShadow(DrawableRecipientChip chip) {
Minh Phame51c7222011-10-12 11:33:26 -07003060 mChip = chip;
3061 }
3062
3063 @Override
3064 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
mindypf30a4282012-12-03 12:16:33 -08003065 Rect rect = mChip.getBounds();
Minh Phame51c7222011-10-12 11:33:26 -07003066 shadowSize.set(rect.width(), rect.height());
3067 shadowTouchPoint.set(rect.centerX(), rect.centerY());
3068 }
3069
3070 @Override
3071 public void onDrawShadow(Canvas canvas) {
mindypf30a4282012-12-03 12:16:33 -08003072 mChip.draw(canvas);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003073 }
3074 }
3075
3076 private void showCopyDialog(final String address) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07003077 if (!mAttachedToWindow) {
3078 return;
3079 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003080 mCopyAddress = address;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003081 mCopyDialog.setTitle(address);
Mindy Pereira76e62e32012-02-03 15:38:50 -08003082 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003083 mCopyDialog.setCancelable(true);
3084 mCopyDialog.setCanceledOnTouchOutside(true);
Tom Taylor80f4abf2012-04-06 13:37:20 -07003085 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
3086 button.setOnClickListener(this);
3087 int btnTitleId;
Tom Taylorc7a87f02012-05-03 15:21:08 -07003088 if (isPhoneQuery()) {
Tom Taylor80f4abf2012-04-06 13:37:20 -07003089 btnTitleId = R.string.copy_number;
3090 } else {
3091 btnTitleId = R.string.copy_email;
3092 }
3093 String buttonTitle = getContext().getResources().getString(btnTitleId);
3094 button.setText(buttonTitle);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003095 mCopyDialog.setOnDismissListener(this);
3096 mCopyDialog.show();
3097 }
3098
3099 @Override
3100 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
3101 // Do nothing.
3102 return false;
3103 }
3104
3105 @Override
3106 public void onShowPress(MotionEvent e) {
3107 // Do nothing.
3108 }
3109
3110 @Override
3111 public boolean onSingleTapUp(MotionEvent e) {
3112 // Do nothing.
3113 return false;
3114 }
3115
3116 @Override
3117 public void onDismiss(DialogInterface dialog) {
3118 mCopyAddress = null;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003119 }
3120
3121 @Override
3122 public void onClick(View v) {
3123 // Copy this to the clipboard.
3124 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
3125 Context.CLIPBOARD_SERVICE);
3126 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
3127 mCopyDialog.dismiss();
3128 }
Tom Taylorc7a87f02012-05-03 15:21:08 -07003129
3130 protected boolean isPhoneQuery() {
Mindy Pereiraca522712012-06-28 11:47:48 -07003131 return getAdapter() != null
Scott Kennedy858e0942013-10-10 11:50:01 -07003132 && getAdapter().getQueryType() == BaseRecipientAdapter.QUERY_TYPE_PHONE;
3133 }
3134
3135 @Override
3136 public BaseRecipientAdapter getAdapter() {
3137 return (BaseRecipientAdapter) super.getAdapter();
Tom Taylorc7a87f02012-05-03 15:21:08 -07003138 }
Kaikai Wang972def72014-05-27 21:59:52 -07003139
3140 /**
3141 * Append a new {@link RecipientEntry} to the end of the recipient chips, leaving any
3142 * unfinished text at the end.
3143 */
3144 public void appendRecipientEntry(final RecipientEntry entry) {
3145 clearComposingText();
3146
3147 final Editable editable = getText();
3148 int chipInsertionPoint = 0;
3149
3150 // Find the end of last chip and see if there's any unchipified text.
3151 final DrawableRecipientChip[] recips = getSortedRecipients();
3152 if (recips != null && recips.length > 0) {
3153 final DrawableRecipientChip last = recips[recips.length - 1];
3154 // The chip will be inserted at the end of last chip + 1. All the unfinished text after
3155 // the insertion point will be kept untouched.
3156 chipInsertionPoint = editable.getSpanEnd(last) + 1;
3157 }
3158
3159 final CharSequence chip = createChip(entry, false);
3160 if (chip != null) {
3161 editable.insert(chipInsertionPoint, chip);
3162 }
3163 }
Jin Cao35e82d42014-06-02 17:21:21 -07003164
Kaikai Wangcd980d92014-06-09 21:08:13 -07003165 /**
3166 * Remove all chips matching the given RecipientEntry.
3167 */
3168 public void removeRecipientEntry(final RecipientEntry entry) {
3169 final DrawableRecipientChip[] recips = getText()
3170 .getSpans(0, getText().length(), DrawableRecipientChip.class);
3171
3172 for (final DrawableRecipientChip recipient : recips) {
3173 final RecipientEntry existingEntry = recipient.getEntry();
3174 if (existingEntry != null && existingEntry.isValid() &&
3175 existingEntry.isSamePerson(entry)) {
3176 removeChip(recipient);
3177 }
3178 }
3179 }
3180
Jin Cao4de6a532014-08-08 11:34:10 -07003181 public void setAlternatePopupAnchor(View v) {
3182 mAlternatePopupAnchor = v;
3183 }
3184
Jin Cao35e82d42014-06-02 17:21:21 -07003185 private static class ChipBitmapContainer {
3186 Bitmap bitmap;
3187 // information used for positioning the loaded icon
3188 boolean loadIcon = true;
3189 float left;
3190 float top;
3191 float right;
3192 float bottom;
3193 }
Mindy Pereira18529312011-06-28 11:00:52 -07003194}