blob: 1780c6e71dc17e3f47385d403864f21beabbf306 [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
Mindy Pereira1d1ec852011-08-09 16:49:33 -070020import android.app.Dialog;
21import android.content.ClipData;
Mindy Pereira20c9d622011-10-12 13:18:04 -070022import android.content.ClipDescription;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070023import android.content.ClipboardManager;
Mindy Pereira9159cd22011-05-25 17:06:44 -070024import android.content.Context;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070025import android.content.DialogInterface;
26import android.content.DialogInterface.OnDismissListener;
Mindy Pereira52c441e2011-12-15 13:35:37 -080027import android.content.res.Resources;
Mindy Pereira22faaa62011-12-16 14:30:34 -080028import android.content.res.TypedArray;
Mindy Pereiracd611952011-06-01 17:02:20 -070029import android.graphics.Bitmap;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070030import android.graphics.BitmapFactory;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070031import android.graphics.BitmapShader;
Mindy Pereiracd611952011-06-01 17:02:20 -070032import android.graphics.Canvas;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070033import android.graphics.Color;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070034import android.graphics.Matrix;
Kevin Linb10d1c62014-01-24 12:45:00 -080035import android.graphics.Paint;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070036import android.graphics.Paint.Style;
Minh Phame51c7222011-10-12 11:33:26 -070037import android.graphics.Point;
Mindy Pereiracd611952011-06-01 17:02:20 -070038import android.graphics.Rect;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070039import android.graphics.RectF;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070040import android.graphics.Shader.TileMode;
Mindy Pereiracd611952011-06-01 17:02:20 -070041import android.graphics.drawable.BitmapDrawable;
Mindy Pereira9159cd22011-05-25 17:06:44 -070042import android.graphics.drawable.Drawable;
Jin Cao4db8ccc2014-07-30 10:11:07 -070043import android.graphics.drawable.StateListDrawable;
Mindy Pereira18529312011-06-28 11:00:52 -070044import android.os.AsyncTask;
Scott Kennedy1650ef62013-08-02 21:56:47 -070045import android.os.Build;
Mindy Pereira007a76b2011-06-14 11:39:36 -070046import android.os.Handler;
Scott Kennedy78f38a02013-02-27 11:21:40 -080047import android.os.Looper;
Mindy Pereira007a76b2011-06-14 11:39:36 -070048import android.os.Message;
Mindy Pereiradc04cd72011-09-16 15:42:09 -070049import android.os.Parcelable;
Mindy Pereira9159cd22011-05-25 17:06:44 -070050import android.text.Editable;
Gilles Debunne61b48cc2011-08-16 14:03:00 -070051import android.text.InputType;
Mindy Pereiracd611952011-06-01 17:02:20 -070052import android.text.Layout;
53import android.text.Spannable;
54import android.text.SpannableString;
Scott Kennedy0e128962013-04-11 10:52:08 -070055import android.text.SpannableStringBuilder;
Mindy Pereiracd611952011-06-01 17:02:20 -070056import android.text.Spanned;
57import android.text.TextPaint;
58import android.text.TextUtils;
Mindy Pereirab88ee452011-06-02 11:07:43 -070059import android.text.TextWatcher;
Mindy Pereiracd611952011-06-01 17:02:20 -070060import android.text.method.QwertyKeyListener;
Mindy Pereira3bb52162011-07-01 14:52:22 -070061import android.text.util.Rfc822Token;
62import android.text.util.Rfc822Tokenizer;
Mindy Pereira9159cd22011-05-25 17:06:44 -070063import android.util.AttributeSet;
Mindy Pereiracd611952011-06-01 17:02:20 -070064import android.util.Log;
mindyp093ecdd2012-12-14 10:40:51 -080065import android.util.TypedValue;
Mindy Pereirafd68ea62011-06-02 10:40:19 -070066import android.view.ActionMode;
Andy Stadleraa2afff2011-08-04 16:22:47 -070067import android.view.ActionMode.Callback;
Minh Phame51c7222011-10-12 11:33:26 -070068import android.view.DragEvent;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070069import android.view.GestureDetector;
Mindy Pereiracd611952011-06-01 17:02:20 -070070import android.view.KeyEvent;
Mindy Pereira750e6e52011-07-25 11:51:30 -070071import android.view.LayoutInflater;
Mindy Pereirafd68ea62011-06-02 10:40:19 -070072import android.view.Menu;
73import android.view.MenuItem;
Mindy Pereiracd611952011-06-01 17:02:20 -070074import android.view.MotionEvent;
75import android.view.View;
Gilles Debunne61b48cc2011-08-16 14:03:00 -070076import android.view.View.OnClickListener;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -070077import android.view.ViewParent;
Mindy Pereira93364a62012-04-27 14:17:22 -070078import android.view.inputmethod.EditorInfo;
79import android.view.inputmethod.InputConnection;
Mindy Pereiracd611952011-06-01 17:02:20 -070080import android.widget.AdapterView;
81import android.widget.AdapterView.OnItemClickListener;
Tom Taylor80f4abf2012-04-06 13:37:20 -070082import android.widget.Button;
mindyp093ecdd2012-12-14 10:40:51 -080083import android.widget.Filterable;
Mindy Pereira95a69252011-06-17 15:02:03 -070084import android.widget.ListAdapter;
Mindy Pereiracd611952011-06-01 17:02:20 -070085import android.widget.ListPopupWindow;
Mindy Pereira007a76b2011-06-14 11:39:36 -070086import android.widget.ListView;
Mindy Pereira9159cd22011-05-25 17:06:44 -070087import android.widget.MultiAutoCompleteTextView;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -070088import android.widget.ScrollView;
Mindy Pereira750e6e52011-07-25 11:51:30 -070089import android.widget.TextView;
Daisuke Miyakawa7537f842011-05-31 15:47:25 -070090
mindyp16923ee2012-12-10 11:58:29 -080091import com.android.ex.chips.RecipientAlternatesAdapter.RecipientMatchCallback;
Scott Kennedy194d4272013-03-06 22:06:45 -080092import com.android.ex.chips.recipientchip.DrawableRecipientChip;
93import com.android.ex.chips.recipientchip.InvisibleRecipientChip;
Jin Cao6c2a0162014-08-17 15:00:50 -070094import com.android.ex.chips.recipientchip.ReplacementDrawableSpan;
Scott Kennedy194d4272013-03-06 22:06:45 -080095import com.android.ex.chips.recipientchip.VisibleRecipientChip;
Mindy Pereiracd611952011-06-01 17:02:20 -070096
Alon Albert76f1f2d2013-07-14 15:32:49 +030097import java.util.ArrayList;
98import java.util.Arrays;
Alon Albert76f1f2d2013-07-14 15:32:49 +030099import java.util.Collections;
100import java.util.Comparator;
Alon Albert76f1f2d2013-07-14 15:32:49 +0300101import java.util.List;
102import java.util.Map;
103import java.util.Set;
104import java.util.regex.Matcher;
105import java.util.regex.Pattern;
106
Mindy Pereira9159cd22011-05-25 17:06:44 -0700107/**
108 * RecipientEditTextView is an auto complete text view for use with applications
109 * that use the new Chips UI for addressing a message to recipients.
110 */
Mindy Pereira95a69252011-06-17 15:02:03 -0700111public class RecipientEditTextView extends MultiAutoCompleteTextView implements
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700112 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
Mindy Pereiraecee50c2011-09-09 16:30:20 -0700113 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
Jin Cao4db8ccc2014-07-30 10:11:07 -0700114 TextView.OnEditorActionListener, DropdownChipLayouter.ChipDeleteListener {
Jin Caoa21fd882014-08-10 13:07:11 -0700115 private static final String TAG = "RecipientEditTextView";
Mindy Pereiracd611952011-06-01 17:02:20 -0700116
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700117 private static final char COMMIT_CHAR_COMMA = ',';
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700118 private static final char COMMIT_CHAR_SEMICOLON = ';';
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700119 private static final char COMMIT_CHAR_SPACE = ' ';
Scott Kennedy03e9e982013-03-04 13:26:22 -0800120 private static final String SEPARATOR = String.valueOf(COMMIT_CHAR_COMMA)
121 + String.valueOf(COMMIT_CHAR_SPACE);
122
Jin Caoa21fd882014-08-10 13:07:11 -0700123 // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
124 // parens, so numbers such as "1 (425) 222-2342" match.
125 private static final Pattern PHONE_PATTERN
126 = Pattern.compile( // sdd = space, dot, or dash
127 "(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
128 + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?" // 1(<digits>)<sdd>*
129 + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
Mindy Pereiracd611952011-06-01 17:02:20 -0700130
Scott Kennedyf11483a2014-04-18 13:36:27 -0700131 private static final int DISMISS = "dismiss".hashCode();
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700132 private static final long DISMISS_DELAY = 300;
133
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700134 // TODO: get correct number/ algorithm from with UX.
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700135 // Visible for testing.
136 /*package*/ static final int CHIP_LIMIT = 2;
137
138 private static final int MAX_CHIPS_PARSED = 50;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700139
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700140 private static int sSelectedTextColor = -1;
Jin Caoa21fd882014-08-10 13:07:11 -0700141 private static int sExcessTopPadding = -1;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700142
143 // Resources for displaying chips.
Mindy Pereiracd611952011-06-01 17:02:20 -0700144 private Drawable mChipBackground = null;
Mindy Pereiracd611952011-06-01 17:02:20 -0700145 private Drawable mChipDelete = null;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700146 private Drawable mInvalidChipBackground;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700147 private Drawable mChipBackgroundPressed;
148
Jin Caoa21fd882014-08-10 13:07:11 -0700149 // Possible attr overrides
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700150 private float mChipHeight;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700151 private float mChipFontSize;
Mindy Pereiraffd270a2012-05-23 16:11:47 -0700152 private float mLineSpacingExtra;
Jin Cao58d541d2014-07-29 16:23:03 -0700153 private int mChipTextStartPadding;
154 private int mChipTextEndPadding;
Scott Kennedy15259d52014-07-09 17:28:47 -0700155 private final int mTextHeight;
Jin Caoa21fd882014-08-10 13:07:11 -0700156 private boolean mDisableDelete;
157 private int mMaxLines;
158 private int mActionBarHeight;
Mindy Pereiracd611952011-06-01 17:02:20 -0700159
Kevin Linb10d1c62014-01-24 12:45:00 -0800160 /**
161 * Enumerator for avatar position. See attr.xml for more details.
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800162 * 0 for end, 1 for start.
Kevin Linb10d1c62014-01-24 12:45:00 -0800163 */
164 private int mAvatarPosition;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800165 private static final int AVATAR_POSITION_END = 0;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800166 private static final int AVATAR_POSITION_START = 1;
Kevin Linb10d1c62014-01-24 12:45:00 -0800167
Jin Cao809c5952014-08-08 12:28:17 -0700168 private Paint mWorkPaint = new Paint();
169
Mindy Pereiracd611952011-06-01 17:02:20 -0700170 private Tokenizer mTokenizer;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700171 private Validator mValidator;
Jin Caoa21fd882014-08-10 13:07:11 -0700172 private Handler mHandler;
173 private TextWatcher mTextWatcher;
174 private DropdownChipLayouter mDropdownChipLayouter;
175
176 private ListPopupWindow mAlternatesPopup;
177 private ListPopupWindow mAddressPopup;
178 private View mAlternatePopupAnchor;
179 private OnItemClickListener mAlternatesListener;
Mindy Pereiracd611952011-06-01 17:02:20 -0700180
Scott Kennedy194d4272013-03-06 22:06:45 -0800181 private DrawableRecipientChip mSelectedChip;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700182 private Bitmap mDefaultContactPhoto;
Jin Cao6c2a0162014-08-17 15:00:50 -0700183 private ReplacementDrawableSpan mMoreChip;
Mindy Pereira750e6e52011-07-25 11:51:30 -0700184 private TextView mMoreItem;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700185
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800186 // VisibleForTesting
187 final ArrayList<String> mPendingChips = new ArrayList<String>();
Mindy Pereiraf97eb412011-06-24 11:26:20 -0700188
Mindy Pereira007a76b2011-06-14 11:39:36 -0700189
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700190 private int mPendingChipsCount = 0;
Jin Caoa21fd882014-08-10 13:07:11 -0700191 private int mCheckedItem;
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700192 private boolean mNoChips = false;
Jin Caoa21fd882014-08-10 13:07:11 -0700193 private boolean mShouldShrink = true;
Jin Cao4de6a532014-08-08 11:34:10 -0700194
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800195 // VisibleForTesting
Scott Kennedy194d4272013-03-06 22:06:45 -0800196 ArrayList<DrawableRecipientChip> mTemporaryRecipients;
Mindy Pereira18529312011-06-28 11:00:52 -0700197
Scott Kennedy194d4272013-03-06 22:06:45 -0800198 private ArrayList<DrawableRecipientChip> mRemovedSpans;
Mindy Pereira3bb52162011-07-01 14:52:22 -0700199
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700200 // Chip copy fields.
201 private GestureDetector mGestureDetector;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700202 private Dialog mCopyDialog;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700203 private String mCopyAddress;
204
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700205 // Obtain the enclosing scroll view, if it exists, so that the view can be
206 // scrolled to show the last line of chips content.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700207 private ScrollView mScrollView;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700208 private boolean mTriedGettingScrollView;
Minh Phame51c7222011-10-12 11:33:26 -0700209 private boolean mDragEnabled = false;
210
Jin Caoa21fd882014-08-10 13:07:11 -0700211 private boolean mAttachedToWindow;
Tom Taylor4491a062012-11-15 13:57:41 -0800212
Mindy Pereira79fb4362011-06-21 14:37:07 -0700213 private final Runnable mAddTextWatcher = new Runnable() {
214 @Override
215 public void run() {
216 if (mTextWatcher == null) {
217 mTextWatcher = new RecipientTextWatcher();
218 addTextChangedListener(mTextWatcher);
219 }
220 }
221 };
222
Mindy Pereira18529312011-06-28 11:00:52 -0700223 private IndividualReplacementTask mIndividualReplacements;
224
Mindy Pereira2cac2312011-07-20 11:38:59 -0700225 private Runnable mHandlePendingChips = new Runnable() {
226
227 @Override
228 public void run() {
229 handlePendingChips();
Mindy Pereira2cac2312011-07-20 11:38:59 -0700230 }
231
232 };
233
Mindy Pereirad7192502011-09-22 08:04:45 -0700234 private Runnable mDelayedShrink = new Runnable() {
235
236 @Override
237 public void run() {
238 shrink();
239 }
240
241 };
242
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700243 private RecipientEntryItemClickedListener mRecipientEntryItemClickedListener;
244
245 public interface RecipientEntryItemClickedListener {
246 /**
247 * Callback that occurs whenever an auto-complete suggestion is clicked.
248 * @param charactersTyped the number of characters typed by the user to provide the
249 * auto-complete suggestions.
250 * @param position the position in the dropdown list that the user clicked
251 */
252 void onRecipientEntryItemClicked(int charactersTyped, int position);
253 }
254
Mindy Pereira9159cd22011-05-25 17:06:44 -0700255 public RecipientEditTextView(Context context, AttributeSet attrs) {
256 super(context, attrs);
Mindy Pereira22faaa62011-12-16 14:30:34 -0800257 setChipDimensions(context, attrs);
Scott Kennedy15259d52014-07-09 17:28:47 -0700258 mTextHeight = calculateTextHeight();
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700259 if (sSelectedTextColor == -1) {
260 sSelectedTextColor = context.getResources().getColor(android.R.color.white);
261 }
Mindy Pereira95a69252011-06-17 15:02:03 -0700262 mAlternatesPopup = new ListPopupWindow(context);
Jin Caoa21fd882014-08-10 13:07:11 -0700263 mAlternatesPopup.setBackgroundDrawable(null);
Mindy Pereira01382d72011-07-15 16:52:32 -0700264 mAddressPopup = new ListPopupWindow(context);
Jin Caoa21fd882014-08-10 13:07:11 -0700265 mAddressPopup.setBackgroundDrawable(null);
Mindy Pereirabfedc1e2011-09-07 12:17:12 -0700266 mCopyDialog = new Dialog(context);
Mindy Pereira95a69252011-06-17 15:02:03 -0700267 mAlternatesListener = new OnItemClickListener() {
268 @Override
269 public void onItemClick(AdapterView<?> adapterView,View view, int position,
270 long rowId) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700271 mAlternatesPopup.setOnItemClickListener(null);
Mindy Pereira95a69252011-06-17 15:02:03 -0700272 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
273 .getRecipientEntry(position));
274 Message delayed = Message.obtain(mHandler, DISMISS);
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700275 delayed.obj = mAlternatesPopup;
Mindy Pereira95a69252011-06-17 15:02:03 -0700276 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
277 clearComposingText();
278 }
279 };
Mindy Pereirae1bfc922011-08-16 14:00:01 -0700280 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
Mindy Pereirab88ee452011-06-02 11:07:43 -0700281 setOnItemClickListener(this);
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700282 setCustomSelectionActionModeCallback(this);
Mindy Pereira007a76b2011-06-14 11:39:36 -0700283 mHandler = new Handler() {
284 @Override
285 public void handleMessage(Message msg) {
286 if (msg.what == DISMISS) {
Mindy Pereira95a69252011-06-17 15:02:03 -0700287 ((ListPopupWindow) msg.obj).dismiss();
Mindy Pereira007a76b2011-06-14 11:39:36 -0700288 return;
289 }
290 super.handleMessage(msg);
291 }
292 };
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700293 mTextWatcher = new RecipientTextWatcher();
294 addTextChangedListener(mTextWatcher);
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700295 mGestureDetector = new GestureDetector(context, this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700296 setOnEditorActionListener(this);
Kevin Linb10d1c62014-01-24 12:45:00 -0800297
Jin Caoa20a8d02014-08-06 17:41:49 -0700298 setDropdownChipLayouter(new DropdownChipLayouter(LayoutInflater.from(context), context));
Kevin Linb10d1c62014-01-24 12:45:00 -0800299 }
300
Scott Kennedy15259d52014-07-09 17:28:47 -0700301 private int calculateTextHeight() {
302 final Rect textBounds = new Rect();
303 final TextPaint paint = getPaint();
304
305 textBounds.setEmpty();
306 // First measure the bounds of a sample text.
307 final String textHeightSample = "a";
308 paint.getTextBounds(textHeightSample, 0, textHeightSample.length(), textBounds);
309
310 textBounds.left = 0;
311 textBounds.right = 0;
312
313 return textBounds.height();
314 }
315
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -0700316 public void setDropdownChipLayouter(DropdownChipLayouter dropdownChipLayouter) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800317 mDropdownChipLayouter = dropdownChipLayouter;
Jin Caoa20a8d02014-08-06 17:41:49 -0700318 mDropdownChipLayouter.setDeleteListener(this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700319 }
320
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700321 public void setRecipientEntryItemClickedListener(RecipientEntryItemClickedListener listener) {
322 mRecipientEntryItemClickedListener = listener;
323 }
324
Mindy Pereira93364a62012-04-27 14:17:22 -0700325 @Override
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700326 protected void onDetachedFromWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700327 super.onDetachedFromWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700328 mAttachedToWindow = false;
329 }
330
331 @Override
332 protected void onAttachedToWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700333 super.onAttachedToWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700334 mAttachedToWindow = true;
335 }
336
337 @Override
Mindy Pereira93364a62012-04-27 14:17:22 -0700338 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
339 if (action == EditorInfo.IME_ACTION_DONE) {
340 if (commitDefault()) {
341 return true;
342 }
343 if (mSelectedChip != null) {
344 clearSelectedChip();
345 return true;
346 } else if (focusNext()) {
347 return true;
348 }
349 }
350 return false;
351 }
352
353 @Override
354 public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
355 InputConnection connection = super.onCreateInputConnection(outAttrs);
356 int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
357 if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
358 // clear the existing action
359 outAttrs.imeOptions ^= imeActions;
360 // set the DONE action
361 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
362 }
363 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
364 outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
365 }
Scott Kennedy1af243f2013-01-29 23:38:43 -0800366
367 outAttrs.actionId = EditorInfo.IME_ACTION_DONE;
Andrew Sappersteinf585f362014-08-06 15:06:00 -0700368 outAttrs.actionLabel = getContext().getString(R.string.action_label);
Mindy Pereira93364a62012-04-27 14:17:22 -0700369 return connection;
Erike33555f2011-06-21 14:20:20 -0700370 }
Mindy Pereira7afe1602011-06-20 10:53:52 -0700371
Scott Kennedy194d4272013-03-06 22:06:45 -0800372 /*package*/ DrawableRecipientChip getLastChip() {
373 DrawableRecipientChip last = null;
374 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700375 if (chips != null && chips.length > 0) {
376 last = chips[chips.length - 1];
Erike33555f2011-06-21 14:20:20 -0700377 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700378 return last;
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700379 }
380
Ken Thai1248e532014-05-01 09:05:02 -0700381 /**
382 * @return The list of {@link RecipientEntry}s that have been selected by the user.
383 */
384 public List<RecipientEntry> getSelectedRecipients() {
385 DrawableRecipientChip[] chips =
386 getText().getSpans(0, getText().length(), DrawableRecipientChip.class);
387 List<RecipientEntry> results = new ArrayList();
388 if (chips == null) {
389 return results;
390 }
391
392 for (DrawableRecipientChip c : chips) {
393 results.add(c.getEntry());
394 }
395
396 return results;
397 }
398
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700399 @Override
400 public void onSelectionChanged(int start, int end) {
401 // When selection changes, see if it is inside the chips area.
402 // If so, move the cursor back after the chips again.
Scott Kennedy194d4272013-03-06 22:06:45 -0800403 DrawableRecipientChip last = getLastChip();
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700404 if (last != null && start < getSpannable().getSpanEnd(last)) {
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700405 // Grab the last chip and set the cursor to after it.
406 setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length()));
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700407 }
Mindy Pereira05dbd332011-06-03 09:37:44 -0700408 super.onSelectionChanged(start, end);
409 }
410
Mindy Pereiradc04cd72011-09-16 15:42:09 -0700411 @Override
412 public void onRestoreInstanceState(Parcelable state) {
413 if (!TextUtils.isEmpty(getText())) {
414 super.onRestoreInstanceState(null);
415 } else {
416 super.onRestoreInstanceState(state);
417 }
418 }
419
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700420 @Override
Mindy Pereiradaa640c2011-10-03 14:18:30 -0700421 public Parcelable onSaveInstanceState() {
422 // If the user changes orientation while they are editing, just roll back the selection.
423 clearSelectedChip();
424 return super.onSaveInstanceState();
425 }
426
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700427 /**
428 * Convenience method: Append the specified text slice to the TextView's
429 * display buffer, upgrading it to BufferType.EDITABLE if it was
430 * not already editable. Commas are excluded as they are added automatically
431 * by the view.
432 */
433 @Override
434 public void append(CharSequence text, int start, int end) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700435 // We don't care about watching text changes while appending.
436 if (mTextWatcher != null) {
437 removeTextChangedListener(mTextWatcher);
438 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700439 super.append(text, start, end);
440 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
mindyp01244682012-08-27 10:32:17 -0700441 String displayString = text.toString();
Scott Kennedy03e9e982013-03-04 13:26:22 -0800442
443 if (!displayString.trim().endsWith(String.valueOf(COMMIT_CHAR_COMMA))) {
444 // We have no separator, so we should add it
445 super.append(SEPARATOR, 0, SEPARATOR.length());
446 displayString += SEPARATOR;
mindyp01244682012-08-27 10:32:17 -0700447 }
Scott Kennedy03e9e982013-03-04 13:26:22 -0800448
mindyp20d7af72012-09-10 15:47:40 -0700449 if (!TextUtils.isEmpty(displayString)
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700450 && TextUtils.getTrimmedLength(displayString) > 0) {
451 mPendingChipsCount++;
Scott Kennedy03e9e982013-03-04 13:26:22 -0800452 mPendingChips.add(displayString);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700453 }
454 }
mindypabb864d2012-09-10 12:06:35 -0700455 // Put a message on the queue to make sure we ALWAYS handle pending
456 // chips.
Mindy Pereira2cac2312011-07-20 11:38:59 -0700457 if (mPendingChipsCount > 0) {
458 postHandlePendingChips();
459 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700460 mHandler.post(mAddTextWatcher);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700461 }
462
Mindy Pereira05dbd332011-06-03 09:37:44 -0700463 @Override
464 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700465 super.onFocusChanged(hasFocus, direction, previous);
Mindy Pereira05dbd332011-06-03 09:37:44 -0700466 if (!hasFocus) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700467 shrink();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700468 } else {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700469 expand();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700470 }
Mindy Pereira9159cd22011-05-25 17:06:44 -0700471 }
472
mindyp093ecdd2012-12-14 10:40:51 -0800473 private int getExcessTopPadding() {
474 if (sExcessTopPadding == -1) {
mindype7f7a7d2012-12-17 12:04:01 -0800475 sExcessTopPadding = (int) (mChipHeight + mLineSpacingExtra);
mindyp093ecdd2012-12-14 10:40:51 -0800476 }
477 return sExcessTopPadding;
478 }
479
Alice Yang6b7110f2013-04-26 12:50:35 -0700480 @Override
mindyp093ecdd2012-12-14 10:40:51 -0800481 public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
482 super.setAdapter(adapter);
Kevin Linb10d1c62014-01-24 12:45:00 -0800483 BaseRecipientAdapter baseAdapter = (BaseRecipientAdapter) adapter;
484 baseAdapter.registerUpdateObserver(new BaseRecipientAdapter.EntriesUpdatedObserver() {
485 @Override
486 public void onChanged(List<RecipientEntry> entries) {
487 // Scroll the chips field to the top of the screen so
488 // that the user can see as many results as possible.
489 if (entries != null && entries.size() > 0) {
490 scrollBottomIntoView();
491 }
492 }
493 });
494 baseAdapter.setDropdownChipLayouter(mDropdownChipLayouter);
mindyp093ecdd2012-12-14 10:40:51 -0800495 }
496
Kevin Lin53e718a2014-02-04 17:40:33 -0800497 protected void scrollBottomIntoView() {
mindyp093ecdd2012-12-14 10:40:51 -0800498 if (mScrollView != null && mShouldShrink) {
499 int[] location = new int[2];
500 getLocationOnScreen(location);
501 int height = getHeight();
502 int currentPos = location[1] + height;
503 // Desired position shows at least 1 line of chips below the action
504 // bar. We add excess padding to make sure this is always below other
505 // content.
506 int desiredPos = (int) mChipHeight + mActionBarHeight + getExcessTopPadding();
507 if (currentPos > desiredPos) {
508 mScrollView.scrollBy(0, currentPos - desiredPos);
509 }
510 }
511 }
512
Kevin Lin53e718a2014-02-04 17:40:33 -0800513 protected ScrollView getScrollView() {
Scott Kennedy7a4e6772013-11-21 14:31:33 -0800514 return mScrollView;
Kevin Lin53e718a2014-02-04 17:40:33 -0800515 }
516
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700517 @Override
518 public void performValidation() {
519 // Do nothing. Chips handles its own validation.
520 }
521
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700522 private void shrink() {
Mindy Pereira5c125af2011-12-13 11:04:13 -0800523 if (mTokenizer == null) {
524 return;
525 }
mindyp5e60c2b2012-11-06 17:47:40 -0800526 long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1;
527 if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT
528 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700529 clearSelectedChip();
530 } else {
Mindy Pereirad7192502011-09-22 08:04:45 -0700531 if (getWidth() <= 0) {
532 // We don't have the width yet which means the view hasn't been drawn yet
533 // and there is no reason to attempt to commit chips yet.
534 // This focus lost must be the result of an orientation change
535 // or an initial rendering.
536 // Re-post the shrink for later.
537 mHandler.removeCallbacks(mDelayedShrink);
538 mHandler.post(mDelayedShrink);
539 return;
540 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700541 // Reset any pending chips as they would have been handled
542 // when the field lost focus.
543 if (mPendingChipsCount > 0) {
Mindy Pereira2cac2312011-07-20 11:38:59 -0700544 postHandlePendingChips();
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700545 } else {
546 Editable editable = getText();
547 int end = getSelectionEnd();
548 int start = mTokenizer.findTokenStart(editable, end);
Scott Kennedy194d4272013-03-06 22:06:45 -0800549 DrawableRecipientChip[] chips =
550 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700551 if ((chips == null || chips.length == 0)) {
Mindy Pereirad7192502011-09-22 08:04:45 -0700552 Editable text = getText();
553 int whatEnd = mTokenizer.findTokenEnd(text, start);
554 // This token was already tokenized, so skip past the ending token.
Mindy Pereira448e90b2011-09-22 11:49:32 -0700555 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') {
mindyp4f82d882012-11-08 16:30:27 -0800556 whatEnd = movePastTerminators(whatEnd);
Mindy Pereirad7192502011-09-22 08:04:45 -0700557 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700558 // In the middle of chip; treat this as an edit
559 // and commit the whole token.
Mindy Pereirad7192502011-09-22 08:04:45 -0700560 int selEnd = getSelectionEnd();
Mindy Pereira63372312011-11-15 15:23:07 -0800561 if (whatEnd != selEnd) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700562 handleEdit(start, whatEnd);
563 } else {
564 commitChip(start, end, editable);
565 }
566 }
Mindy Pereiraa74f40d2011-07-12 09:07:17 -0700567 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700568 mHandler.post(mAddTextWatcher);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700569 }
Mindy Pereira3bb52162011-07-01 14:52:22 -0700570 createMoreChip();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700571 }
572
573 private void expand() {
mindyp374ccb22012-11-06 10:54:05 -0800574 if (mShouldShrink) {
575 setMaxLines(Integer.MAX_VALUE);
576 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700577 removeMoreChip();
578 setCursorVisible(true);
579 Editable text = getText();
580 setSelection(text != null && text.length() > 0 ? text.length() : 0);
Mindy Pereira18529312011-06-28 11:00:52 -0700581 // If there are any temporary chips, try replacing them now that the user
582 // has expanded the field.
583 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
584 new RecipientReplacementTask().execute();
585 mTemporaryRecipients = null;
586 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700587 }
588
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700589 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700590 paint.setTextSize(mChipFontSize);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700591 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
592 Log.d(TAG, "Max width is negative: " + maxWidth);
593 }
594 return TextUtils.ellipsize(text, paint, maxWidth,
595 TextUtils.TruncateAt.END);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700596 }
597
Kevin Linb10d1c62014-01-24 12:45:00 -0800598 /**
599 * Creates a bitmap of the given contact on a selected chip.
600 *
601 * @param contact The recipient entry to pull data from.
602 * @param paint The paint to use to draw the bitmap.
603 */
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800604 private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800605 paint.setColor(sSelectedTextColor);
Jin Cao35e82d42014-06-02 17:21:21 -0700606 final ChipBitmapContainer bitmapContainer = createChipBitmap(contact, paint,
Jin Cao33515e72014-08-05 21:13:27 -0700607 mChipBackgroundPressed, getResources().getColor(R.color.chip_background_selected));
Jin Cao35e82d42014-06-02 17:21:21 -0700608
609 if (bitmapContainer.loadIcon) {
Jin Cao809c5952014-08-08 12:28:17 -0700610 loadAvatarIcon(contact, bitmapContainer);
Mindy Pereiracd611952011-06-01 17:02:20 -0700611 }
Jin Cao35e82d42014-06-02 17:21:21 -0700612
613 return bitmapContainer.bitmap;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700614 }
615
Kevin Linb10d1c62014-01-24 12:45:00 -0800616 /**
617 * Creates a bitmap of the given contact on a selected chip.
618 *
619 * @param contact The recipient entry to pull data from.
620 * @param paint The paint to use to draw the bitmap.
621 */
Andrew Sapperstein1db635b2014-04-29 13:07:57 -0700622 private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800623 paint.setColor(getContext().getResources().getColor(android.R.color.black));
Jin Cao33515e72014-08-05 21:13:27 -0700624 ChipBitmapContainer bitmapContainer = createChipBitmap(contact, paint,
625 getChipBackground(contact), getDefaultChipBackgroundColor(contact));
Jin Cao35e82d42014-06-02 17:21:21 -0700626
627 if (bitmapContainer.loadIcon) {
Jin Cao809c5952014-08-08 12:28:17 -0700628 loadAvatarIcon(contact, bitmapContainer);
Jin Cao35e82d42014-06-02 17:21:21 -0700629 }
630 return bitmapContainer.bitmap;
Kevin Linb10d1c62014-01-24 12:45:00 -0800631 }
632
Jin Cao35e82d42014-06-02 17:21:21 -0700633 private ChipBitmapContainer createChipBitmap(RecipientEntry contact, TextPaint paint,
Jin Cao33515e72014-08-05 21:13:27 -0700634 Drawable overrideBackgroundDrawable, int backgroundColor) {
Jin Cao35e82d42014-06-02 17:21:21 -0700635 final ChipBitmapContainer result = new ChipBitmapContainer();
636
Kevin Linb10d1c62014-01-24 12:45:00 -0800637 Rect backgroundPadding = new Rect();
Jin Cao33515e72014-08-05 21:13:27 -0700638 if (overrideBackgroundDrawable != null) {
639 overrideBackgroundDrawable.getPadding(backgroundPadding);
640 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800641
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700642 // Ellipsize the text so that it takes AT MOST the entire width of the
643 // autocomplete text entry area. Make sure to leave space for padding
644 // on the sides.
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700645 int height = (int) mChipHeight;
Kevin Linb10d1c62014-01-24 12:45:00 -0800646 // 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 -0700647 // the chip. Don't include iconWidth for invalid contacts.
648 int iconWidth = contact.isValid() ?
649 height - backgroundPadding.top - backgroundPadding.bottom : 0;
Mindy Pereira6ed7ded2011-10-14 16:31:31 -0700650 float[] widths = new float[1];
651 paint.getTextWidths(" ", widths);
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700652 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
Kevin Lin9b398e32014-02-26 12:29:10 -0800653 calculateAvailableWidth() - iconWidth - widths[0] - backgroundPadding.left
Jin Cao33515e72014-08-05 21:13:27 -0700654 - backgroundPadding.right);
Kevin Linb10d1c62014-01-24 12:45:00 -0800655 int textWidth = (int) paint.measureText(ellipsizedText, 0, ellipsizedText.length());
656
Jin Cao33515e72014-08-05 21:13:27 -0700657 // Chip start padding is the same as the end padding if there is no contact image.
658 final int startPadding = contact.isValid() ? mChipTextStartPadding : mChipTextEndPadding;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700659 // Make sure there is a minimum chip width so the user can ALWAYS
660 // tap a chip without difficulty.
Jin Cao33515e72014-08-05 21:13:27 -0700661 int width = Math.max(iconWidth * 2, textWidth + startPadding + mChipTextEndPadding
Jin Cao58d541d2014-07-29 16:23:03 -0700662 + iconWidth + backgroundPadding.left + backgroundPadding.right);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700663
664 // Create the background of the chip.
Jin Cao35e82d42014-06-02 17:21:21 -0700665 result.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
666 final Canvas canvas = new Canvas(result.bitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700667
Jin Cao33515e72014-08-05 21:13:27 -0700668 // Check if the background drawable is set via attr
669 if (overrideBackgroundDrawable != null) {
670 overrideBackgroundDrawable.setBounds(0, 0, width, height);
671 overrideBackgroundDrawable.draw(canvas);
672 } else {
673 // Draw the default chip background
Jin Cao6c2a0162014-08-17 15:00:50 -0700674 mWorkPaint.reset();
675 mWorkPaint.setColor(backgroundColor);
Jin Cao33515e72014-08-05 21:13:27 -0700676 final float radius = height / 2;
677 canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius,
Jin Cao6c2a0162014-08-17 15:00:50 -0700678 mWorkPaint);
Jin Cao33515e72014-08-05 21:13:27 -0700679 }
680
Kevin Linb10d1c62014-01-24 12:45:00 -0800681 // Draw the text vertically aligned
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800682 int textX = shouldPositionAvatarOnRight() ?
Jin Cao58d541d2014-07-29 16:23:03 -0700683 mChipTextEndPadding + backgroundPadding.left :
684 width - backgroundPadding.right - mChipTextEndPadding - textWidth;
Kevin Linb10d1c62014-01-24 12:45:00 -0800685 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(),
Scott Kennedy15259d52014-07-09 17:28:47 -0700686 textX, getTextYOffset(height), paint);
Jin Cao35e82d42014-06-02 17:21:21 -0700687
688 // Set the variables that are needed to draw the icon bitmap once it's loaded
689 int iconX = shouldPositionAvatarOnRight() ? width - backgroundPadding.right - iconWidth :
690 backgroundPadding.left;
691 result.left = iconX;
692 result.top = backgroundPadding.top;
693 result.right = iconX + iconWidth;
694 result.bottom = height - backgroundPadding.bottom;
695
696 return result;
697 }
698
699 /**
700 * Helper function that draws the loaded icon bitmap into the chips bitmap
701 */
Jin Cao809c5952014-08-08 12:28:17 -0700702 private void drawIcon(ChipBitmapContainer bitMapResult, Bitmap icon) {
Jin Cao35e82d42014-06-02 17:21:21 -0700703 final Canvas canvas = new Canvas(bitMapResult.bitmap);
704 final RectF src = new RectF(0, 0, icon.getWidth(), icon.getHeight());
705 final RectF dst = new RectF(bitMapResult.left, bitMapResult.top, bitMapResult.right,
706 bitMapResult.bottom);
Jin Cao809c5952014-08-08 12:28:17 -0700707 drawIconOnCanvas(icon, canvas, src, dst);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700708 }
709
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700710 /**
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800711 * Returns true if the avatar should be positioned at the right edge of the chip.
712 * Takes into account both the set avatar position (start or end) as well as whether
713 * the layout direction is LTR or RTL.
714 */
715 private boolean shouldPositionAvatarOnRight() {
716 final boolean isRtl = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ?
717 getLayoutDirection() == LAYOUT_DIRECTION_RTL : false;
718 final boolean assignedPosition = mAvatarPosition == AVATAR_POSITION_END;
719 // If in Rtl mode, the position should be flipped.
720 return isRtl ? !assignedPosition : assignedPosition;
721 }
722
723 /**
Kevin Linb10d1c62014-01-24 12:45:00 -0800724 * Returns the avatar icon to use for this recipient entry. Returns null if we don't want to
725 * draw an icon for this recipient.
726 */
Jin Cao35e82d42014-06-02 17:21:21 -0700727 private void loadAvatarIcon(final RecipientEntry contact,
Jin Cao809c5952014-08-08 12:28:17 -0700728 final ChipBitmapContainer bitmapContainer) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800729 // Don't draw photos for recipients that have been typed in OR generated on the fly.
730 long contactId = contact.getContactId();
731 boolean drawPhotos = isPhoneQuery() ?
732 contactId != RecipientEntry.INVALID_CONTACT
733 : (contactId != RecipientEntry.INVALID_CONTACT
Jin Caobf84bd82014-07-31 10:59:27 -0700734 && contactId != RecipientEntry.GENERATED_CONTACT);
Kevin Linb10d1c62014-01-24 12:45:00 -0800735
736 if (drawPhotos) {
Jin Cao35e82d42014-06-02 17:21:21 -0700737 final byte[] origPhotoBytes = contact.getPhotoBytes();
Kevin Linb10d1c62014-01-24 12:45:00 -0800738 // There may not be a photo yet if anything but the first contact address
739 // was selected.
Jin Cao82d38852014-06-03 10:53:46 -0700740 if (origPhotoBytes == null) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800741 // TODO: cache this in the recipient entry?
Jin Cao35e82d42014-06-02 17:21:21 -0700742 getAdapter().fetchPhoto(contact, new PhotoManager.PhotoManagerCallback() {
Jin Cao52e48142014-06-04 18:01:20 -0700743 @Override
Andrew Sapperstein50429c52014-06-12 15:12:10 -0700744 public void onPhotoBytesPopulated() {
745 // Call through to the async version which will ensure
746 // proper threading.
747 onPhotoBytesAsynchronouslyPopulated();
748 }
749
750 @Override
Jin Cao52e48142014-06-04 18:01:20 -0700751 public void onPhotoBytesAsynchronouslyPopulated() {
752 final byte[] loadedPhotoBytes = contact.getPhotoBytes();
753 final Bitmap icon = BitmapFactory.decodeByteArray(loadedPhotoBytes, 0,
754 loadedPhotoBytes.length);
755 tryDrawAndInvalidate(icon);
756 }
Jin Cao0efdc532014-06-04 15:35:16 -0700757
Jin Cao52e48142014-06-04 18:01:20 -0700758 @Override
759 public void onPhotoBytesAsyncLoadFailed() {
760 // TODO: can the scaled down default photo be cached?
761 tryDrawAndInvalidate(mDefaultContactPhoto);
762 }
763
764 private void tryDrawAndInvalidate(Bitmap icon) {
Jin Cao809c5952014-08-08 12:28:17 -0700765 drawIcon(bitmapContainer, icon);
Jin Cao52e48142014-06-04 18:01:20 -0700766 // The caller might originated from a background task. However, if the
767 // background task has already completed, the view might be already drawn
768 // on the UI but the callback would happen on the background thread.
769 // So if we are on a background thread, post an invalidate call to the UI.
770 if (Looper.myLooper() == Looper.getMainLooper()) {
771 // The view might not redraw itself since it's loaded asynchronously
Jin Cao0efdc532014-06-04 15:35:16 -0700772 invalidate();
Jin Cao52e48142014-06-04 18:01:20 -0700773 } else {
774 post(new Runnable() {
775 @Override
776 public void run() {
777 invalidate();
778 }
779 });
Jin Cao0efdc532014-06-04 15:35:16 -0700780 }
Jin Cao52e48142014-06-04 18:01:20 -0700781 }
Jin Cao35e82d42014-06-02 17:21:21 -0700782 });
Kevin Linb10d1c62014-01-24 12:45:00 -0800783 } else {
Jin Cao35e82d42014-06-02 17:21:21 -0700784 final Bitmap icon = BitmapFactory.decodeByteArray(origPhotoBytes, 0,
785 origPhotoBytes.length);
Jin Cao809c5952014-08-08 12:28:17 -0700786 drawIcon(bitmapContainer, icon);
Kevin Linb10d1c62014-01-24 12:45:00 -0800787 }
788 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800789 }
790
791 /**
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700792 * Get the background drawable for a RecipientChip.
793 */
794 // Visible for testing.
mindypf30a4282012-12-03 12:16:33 -0800795 /* package */Drawable getChipBackground(RecipientEntry contact) {
796 return contact.isValid() ? mChipBackground : mInvalidChipBackground;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700797 }
798
Jin Cao33515e72014-08-05 21:13:27 -0700799 private int getDefaultChipBackgroundColor(RecipientEntry contact) {
800 return getResources().getColor(contact.isValid() ? R.color.chip_background :
801 R.color.chip_background_invalid);
802 }
803
Kevin Linb10d1c62014-01-24 12:45:00 -0800804 /**
805 * Given a height, returns a Y offset that will draw the text in the middle of the height.
806 */
Scott Kennedy15259d52014-07-09 17:28:47 -0700807 protected float getTextYOffset(int height) {
808 return height - ((height - mTextHeight) / 2);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700809 }
810
Kevin Linb10d1c62014-01-24 12:45:00 -0800811 /**
Scott Kennedyb8985b72014-01-28 16:36:19 -0800812 * Draws the icon onto the canvas given the source rectangle of the bitmap and the destination
Kevin Linb10d1c62014-01-24 12:45:00 -0800813 * rectangle of the canvas.
814 */
Jin Cao809c5952014-08-08 12:28:17 -0700815 protected void drawIconOnCanvas(Bitmap icon, Canvas canvas, RectF src, RectF dst) {
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700816 final Matrix matrix = new Matrix();
817
818 // Draw bitmap through shader first.
819 final BitmapShader shader = new BitmapShader(icon, TileMode.CLAMP, TileMode.CLAMP);
820 matrix.reset();
821
822 // Fit bitmap to bounds.
Kevin Linb10d1c62014-01-24 12:45:00 -0800823 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700824
825 shader.setLocalMatrix(matrix);
Jin Cao809c5952014-08-08 12:28:17 -0700826 mWorkPaint.reset();
827 mWorkPaint.setShader(shader);
828 mWorkPaint.setAntiAlias(true);
829 mWorkPaint.setFilterBitmap(true);
830 mWorkPaint.setDither(true);
831 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f, mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700832
833 // Then draw the border.
834 final float borderWidth = 1f;
Jin Cao809c5952014-08-08 12:28:17 -0700835 mWorkPaint.reset();
836 mWorkPaint.setColor(Color.TRANSPARENT);
837 mWorkPaint.setStyle(Style.STROKE);
838 mWorkPaint.setStrokeWidth(borderWidth);
839 mWorkPaint.setAntiAlias(true);
840 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f - borderWidth / 2, mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700841
Jin Cao809c5952014-08-08 12:28:17 -0700842 mWorkPaint.reset();
Kevin Linb10d1c62014-01-24 12:45:00 -0800843 }
844
Jin Cao33515e72014-08-05 21:13:27 -0700845 private DrawableRecipientChip constructChipSpan(RecipientEntry contact, boolean pressed) {
Mindy Pereiracd611952011-06-01 17:02:20 -0700846 TextPaint paint = getPaint();
847 float defaultSize = paint.getTextSize();
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700848 int defaultColor = paint.getColor();
Mindy Pereiracd611952011-06-01 17:02:20 -0700849
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700850 Bitmap tmpBitmap;
Mindy Pereiracd611952011-06-01 17:02:20 -0700851 if (pressed) {
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800852 tmpBitmap = createSelectedChip(contact, paint);
Mindy Pereiracd611952011-06-01 17:02:20 -0700853
Mindy Pereiracd611952011-06-01 17:02:20 -0700854 } else {
Andrew Sapperstein1db635b2014-04-29 13:07:57 -0700855 tmpBitmap = createUnselectedChip(contact, paint);
Mindy Pereiracd611952011-06-01 17:02:20 -0700856 }
857
Mindy Pereiracd611952011-06-01 17:02:20 -0700858 // Pass the full text, un-ellipsized, to the chip.
859 Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700860 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
Jin Cao6c2a0162014-08-17 15:00:50 -0700861 VisibleRecipientChip recipientChip =
862 new VisibleRecipientChip(result, contact);
863 recipientChip.setExtraMargin(mLineSpacingExtra);
Mindy Pereiracd611952011-06-01 17:02:20 -0700864 // Return text to the original size.
865 paint.setTextSize(defaultSize);
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700866 paint.setColor(defaultColor);
Mindy Pereiracd611952011-06-01 17:02:20 -0700867 return recipientChip;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700868 }
869
Mindy Pereiraa8166902011-06-09 17:53:23 -0700870 /**
Mindy Pereira34214202011-06-09 20:05:32 -0700871 * Calculate the bottom of the line the chip will be located on using:
872 * 1) which line the chip appears on
Mindy Pereira21625f82011-06-16 18:10:58 -0700873 * 2) the height of a chip
874 * 3) padding built into the edit text view
Mindy Pereiraa8166902011-06-09 17:53:23 -0700875 */
Mindy Pereira81fd3d12011-07-06 14:40:50 -0700876 private int calculateOffsetFromBottom(int line) {
Mindy Pereira21625f82011-06-16 18:10:58 -0700877 // Line offsets start at zero.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700878 int actualLine = getLineCount() - (line + 1);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700879 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
880 + getDropDownVerticalOffset();
Mindy Pereiraf621a602011-05-31 10:09:35 -0700881 }
882
Mindy Pereiraa8166902011-06-09 17:53:23 -0700883 /**
Jin Cao6fc1fee2014-07-29 17:56:44 -0700884 * Calculate the offset from bottom of the EditText to top of the provided line.
885 */
886 private int calculateOffsetFromBottomToTop(int line) {
887 return -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math
888 .abs(getLineCount() - line)) + getPaddingBottom());
889 }
890
891 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -0700892 * Get the max amount of space a chip can take up. The formula takes into
893 * account the width of the EditTextView, any view padding, and padding
894 * that will be added to the chip.
895 */
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800896 private float calculateAvailableWidth() {
Jin Cao58d541d2014-07-29 16:23:03 -0700897 return getWidth() - getPaddingLeft() - getPaddingRight() - mChipTextStartPadding
898 - mChipTextEndPadding;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700899 }
900
Mindy Pereira52c441e2011-12-15 13:35:37 -0800901
Mindy Pereira22faaa62011-12-16 14:30:34 -0800902 private void setChipDimensions(Context context, AttributeSet attrs) {
Mindy Pereira5da02342011-12-16 14:56:27 -0800903 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
904 0);
Mindy Pereira52c441e2011-12-15 13:35:37 -0800905 Resources r = getContext().getResources();
mindyp8c474ec2012-12-14 10:58:44 -0800906
Mindy Pereira22faaa62011-12-16 14:30:34 -0800907 mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
Mindy Pereira5da02342011-12-16 14:56:27 -0800908 mChipBackgroundPressed = a
909 .getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed);
Jin Cao33515e72014-08-05 21:13:27 -0700910 mInvalidChipBackground = a
911 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
Mindy Pereira5da02342011-12-16 14:56:27 -0800912 mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
913 if (mChipDelete == null) {
Jin Caoa21fd882014-08-10 13:07:11 -0700914 mChipDelete = r.getDrawable(R.drawable.ic_cancel_wht_24dp);
Mindy Pereira5da02342011-12-16 14:56:27 -0800915 }
Jin Cao58d541d2014-07-29 16:23:03 -0700916 mChipTextStartPadding = mChipTextEndPadding
917 = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
918 if (mChipTextStartPadding == -1) {
919 mChipTextStartPadding = mChipTextEndPadding =
920 (int) r.getDimension(R.dimen.chip_padding);
921 }
922 // xml-overrides for each individual padding
923 // TODO: add these to attr?
924 int overridePadding = (int) r.getDimension(R.dimen.chip_padding_start);
925 if (overridePadding >= 0) {
926 mChipTextStartPadding = overridePadding;
927 }
928 overridePadding = (int) r.getDimension(R.dimen.chip_padding_end);
929 if (overridePadding >= 0) {
930 mChipTextEndPadding = overridePadding;
Mindy Pereira5da02342011-12-16 14:56:27 -0800931 }
Mindy Pereira5da02342011-12-16 14:56:27 -0800932
933 mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
934
Mindy Pereira52c441e2011-12-15 13:35:37 -0800935 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
Mindy Pereira5da02342011-12-16 14:56:27 -0800936
937 mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
938 if (mChipHeight == -1) {
939 mChipHeight = r.getDimension(R.dimen.chip_height);
940 }
941 mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
942 if (mChipFontSize == -1) {
943 mChipFontSize = r.getDimension(R.dimen.chip_text_size);
944 }
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700945 mAvatarPosition =
946 a.getInt(R.styleable.RecipientEditTextView_avatarPosition, AVATAR_POSITION_START);
Scott Kennedyb8985b72014-01-28 16:36:19 -0800947 mDisableDelete = a.getBoolean(R.styleable.RecipientEditTextView_disableDelete, false);
Kevin Linb10d1c62014-01-24 12:45:00 -0800948
mindypf30a4282012-12-03 12:16:33 -0800949 mMaxLines = r.getInteger(R.integer.chips_max_lines);
Jin Cao6c2a0162014-08-17 15:00:50 -0700950 mLineSpacingExtra = r.getDimensionPixelOffset(R.dimen.line_spacing_extra);
mindyp093ecdd2012-12-14 10:40:51 -0800951 TypedValue tv = new TypedValue();
952 if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
953 mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources()
954 .getDisplayMetrics());
955 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800956
Mindy Pereiraef798002012-05-02 11:04:25 -0700957 a.recycle();
Mindy Pereira52c441e2011-12-15 13:35:37 -0800958 }
959
Mindy Pereirad7192502011-09-22 08:04:45 -0700960 // Visible for testing.
961 /* package */ void setMoreItem(TextView moreItem) {
962 mMoreItem = moreItem;
963 }
964
Mindy Pereira97cb2592011-09-26 16:11:41 -0700965
966 // Visible for testing.
967 /* package */ void setChipBackground(Drawable chipBackground) {
968 mChipBackground = chipBackground;
969 }
970
971 // Visible for testing.
972 /* package */ void setChipHeight(int height) {
973 mChipHeight = height;
974 }
975
Kevin Linb10d1c62014-01-24 12:45:00 -0800976 public float getChipHeight() {
977 return mChipHeight;
978 }
979
Mindy Pereira076d1f92011-08-08 11:53:12 -0700980 /**
981 * Set whether to shrink the recipients field such that at most
982 * one line of recipients chips are shown when the field loses
983 * focus. By default, the number of displayed recipients will be
984 * limited and a "more" chip will be shown when focus is lost.
985 * @param shrink
986 */
987 public void setOnFocusListShrinkRecipients(boolean shrink) {
988 mShouldShrink = shrink;
989 }
990
Mindy Pereiracd611952011-06-01 17:02:20 -0700991 @Override
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700992 public void onSizeChanged(int width, int height, int oldw, int oldh) {
993 super.onSizeChanged(width, height, oldw, oldh);
Mindy Pereiradb1ca652011-09-26 08:49:35 -0700994 if (width != 0 && height != 0) {
995 if (mPendingChipsCount > 0) {
996 postHandlePendingChips();
997 } else {
998 checkChipWidths();
999 }
Mindy Pereira8005f422011-07-20 13:16:53 -07001000 }
Mindy Pereira18529312011-06-28 11:00:52 -07001001 // Try to find the scroll view parent, if it exists.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001002 if (mScrollView == null && !mTriedGettingScrollView) {
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001003 ViewParent parent = getParent();
1004 while (parent != null && !(parent instanceof ScrollView)) {
1005 parent = parent.getParent();
1006 }
1007 if (parent != null) {
1008 mScrollView = (ScrollView) parent;
1009 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001010 mTriedGettingScrollView = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001011 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001012 }
1013
Mindy Pereira2cac2312011-07-20 11:38:59 -07001014 private void postHandlePendingChips() {
1015 mHandler.removeCallbacks(mHandlePendingChips);
1016 mHandler.post(mHandlePendingChips);
1017 }
Mindy Pereira18529312011-06-28 11:00:52 -07001018
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001019 private void checkChipWidths() {
1020 // Check the widths of the associated chips.
Scott Kennedy194d4272013-03-06 22:06:45 -08001021 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001022 if (chips != null) {
1023 Rect bounds;
Scott Kennedy194d4272013-03-06 22:06:45 -08001024 for (DrawableRecipientChip chip : chips) {
mindypf30a4282012-12-03 12:16:33 -08001025 bounds = chip.getBounds();
Kevin Linc61c13f2014-02-28 15:04:40 -08001026 if (getWidth() > 0 && bounds.right - bounds.left >
1027 getWidth() - getPaddingLeft() - getPaddingRight()) {
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001028 // Need to redraw that chip.
1029 replaceChip(chip, chip.getEntry());
1030 }
1031 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001032 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001033 }
1034
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001035 // Visible for testing.
1036 /*package*/ void handlePendingChips() {
1037 if (getViewWidth() <= 0) {
Mindy Pereira8005f422011-07-20 13:16:53 -07001038 // The widget has not been sized yet.
1039 // This will be called as a result of onSizeChanged
1040 // at a later point.
1041 return;
1042 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001043 if (mPendingChipsCount <= 0) {
1044 return;
1045 }
1046
Mindy Pereira2cac2312011-07-20 11:38:59 -07001047 synchronized (mPendingChips) {
Mindy Pereira2cac2312011-07-20 11:38:59 -07001048 Editable editable = getText();
1049 // Tokenize!
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001050 if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
1051 for (int i = 0; i < mPendingChips.size(); i++) {
1052 String current = mPendingChips.get(i);
1053 int tokenStart = editable.toString().indexOf(current);
mindyp488718e2012-12-18 11:48:07 -08001054 // Always leave a space at the end between tokens.
1055 int tokenEnd = tokenStart + current.length() - 1;
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001056 if (tokenStart >= 0) {
1057 // When we have a valid token, include it with the token
1058 // to the left.
1059 if (tokenEnd < editable.length() - 2
1060 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
1061 tokenEnd++;
1062 }
mindypf30a4282012-12-03 12:16:33 -08001063 createReplacementChip(tokenStart, tokenEnd, editable, i < CHIP_LIMIT
1064 || !mShouldShrink);
Mindy Pereira2cac2312011-07-20 11:38:59 -07001065 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001066 mPendingChipsCount--;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001067 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001068 sanitizeEnd();
1069 } else {
1070 mNoChips = true;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001071 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001072
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001073 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
Mindy Pereira2cac2312011-07-20 11:38:59 -07001074 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
1075 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
1076 new RecipientReplacementTask().execute();
1077 mTemporaryRecipients = null;
1078 } else {
1079 // Create the "more" chip
1080 mIndividualReplacements = new IndividualReplacementTask();
Scott Kennedy194d4272013-03-06 22:06:45 -08001081 mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(
Mindy Pereira2cac2312011-07-20 11:38:59 -07001082 mTemporaryRecipients.subList(0, CHIP_LIMIT)));
mindyp5e60c2b2012-11-06 17:47:40 -08001083 if (mTemporaryRecipients.size() > CHIP_LIMIT) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001084 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>(
mindyp5e60c2b2012-11-06 17:47:40 -08001085 mTemporaryRecipients.subList(CHIP_LIMIT,
1086 mTemporaryRecipients.size()));
1087 } else {
1088 mTemporaryRecipients = null;
1089 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001090 createMoreChip();
1091 }
1092 } else {
1093 // There are too many recipients to look up, so just fall back
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001094 // to showing addresses for all of them.
Mindy Pereira2cac2312011-07-20 11:38:59 -07001095 mTemporaryRecipients = null;
Mindy Pereira18529312011-06-28 11:00:52 -07001096 createMoreChip();
1097 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001098 mPendingChipsCount = 0;
1099 mPendingChips.clear();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001100 }
1101 }
1102
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001103 // Visible for testing.
1104 /*package*/ int getViewWidth() {
1105 return getWidth();
1106 }
1107
Mindy Pereira3bb52162011-07-01 14:52:22 -07001108 /**
1109 * Remove any characters after the last valid chip.
1110 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001111 // Visible for testing.
1112 /*package*/ void sanitizeEnd() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001113 // Don't sanitize while we are waiting for pending chips to complete.
1114 if (mPendingChipsCount > 0) {
1115 return;
1116 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001117 // Find the last chip; eliminate any commit characters after it.
Scott Kennedy194d4272013-03-06 22:06:45 -08001118 DrawableRecipientChip[] chips = getSortedRecipients();
mindypf30a4282012-12-03 12:16:33 -08001119 Spannable spannable = getSpannable();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001120 if (chips != null && chips.length > 0) {
1121 int end;
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001122 mMoreChip = getMoreChip();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001123 if (mMoreChip != null) {
mindypf30a4282012-12-03 12:16:33 -08001124 end = spannable.getSpanEnd(mMoreChip);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001125 } else {
mindypf30a4282012-12-03 12:16:33 -08001126 end = getSpannable().getSpanEnd(getLastChip());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001127 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001128 Editable editable = getText();
1129 int length = editable.length();
1130 if (length > end) {
1131 // See what characters occur after that and eliminate them.
1132 if (Log.isLoggable(TAG, Log.DEBUG)) {
1133 Log.d(TAG, "There were extra characters after the last tokenizable entry."
1134 + editable);
1135 }
1136 editable.delete(end + 1, length);
1137 }
1138 }
1139 }
1140
1141 /**
1142 * Create a chip that represents just the email address of a recipient. At some later
1143 * point, this chip will be attached to a real contact entry, if one exists.
1144 */
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001145 // VisibleForTesting
1146 void createReplacementChip(int tokenStart, int tokenEnd, Editable editable,
mindypf30a4282012-12-03 12:16:33 -08001147 boolean visible) {
Mindy Pereira32366d42011-07-24 12:39:30 -07001148 if (alreadyHasChip(tokenStart, tokenEnd)) {
1149 // There is already a chip present at this location.
1150 // Don't recreate it.
1151 return;
1152 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07001153 String token = editable.toString().substring(tokenStart, tokenEnd);
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001154 final String trimmedToken = token.trim();
1155 int commitCharIndex = trimmedToken.lastIndexOf(COMMIT_CHAR_COMMA);
Tom Taylor41137c22013-03-26 12:22:56 -07001156 if (commitCharIndex != -1 && commitCharIndex == trimmedToken.length() - 1) {
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001157 token = trimmedToken.substring(0, trimmedToken.length() - 1);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001158 }
1159 RecipientEntry entry = createTokenizedEntry(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001160 if (entry != null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001161 DrawableRecipientChip chip = null;
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001162 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001163 if (!mNoChips) {
mindypf30a4282012-12-03 12:16:33 -08001164 chip = visible ?
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07001165 constructChipSpan(entry, false) : new InvisibleRecipientChip(entry);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001166 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001167 } catch (NullPointerException e) {
1168 Log.e(TAG, e.getMessage(), e);
1169 }
mindypcb76b4d2012-11-09 14:05:19 -08001170 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001171 // Add this chip to the list of entries "to replace"
1172 if (chip != null) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001173 if (mTemporaryRecipients == null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001174 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>();
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001175 }
Scott Kennedy0613ff82013-03-05 14:02:46 -08001176 chip.setOriginalText(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001177 mTemporaryRecipients.add(chip);
1178 }
Mindy Pereira18529312011-06-28 11:00:52 -07001179 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001180 }
1181
Tom Taylorabff6062012-04-17 09:04:56 -07001182 private static boolean isPhoneNumber(String number) {
1183 // TODO: replace this function with libphonenumber's isPossibleNumber (see
1184 // PhoneNumberUtil). One complication is that it requires the sender's region which
1185 // comes from the CurrentCountryIso. For now, let's just do this simple match.
1186 if (TextUtils.isEmpty(number)) {
1187 return false;
1188 }
1189
Tom Taylor4491a062012-11-15 13:57:41 -08001190 Matcher match = PHONE_PATTERN.matcher(number);
Tom Taylorabff6062012-04-17 09:04:56 -07001191 return match.matches();
1192 }
1193
Scott Kennedy983c99b2013-03-22 09:42:03 -07001194 // VisibleForTesting
1195 RecipientEntry createTokenizedEntry(final String token) {
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001196 if (TextUtils.isEmpty(token)) {
1197 return null;
1198 }
mindyp5e60c2b2012-11-06 17:47:40 -08001199 if (isPhoneQuery() && isPhoneNumber(token)) {
Tom Taylor0ba91332013-03-21 10:28:50 -07001200 return RecipientEntry.constructFakePhoneEntry(token, true);
mindyp5e60c2b2012-11-06 17:47:40 -08001201 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001202 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
Mindy Pereira01382d72011-07-15 16:52:32 -07001203 String display = null;
mindypf30a4282012-12-03 12:16:33 -08001204 boolean isValid = isValid(token);
1205 if (isValid && tokens != null && tokens.length > 0) {
Mindy Pereiraee58f492011-08-08 13:16:46 -07001206 // If we can get a name from tokenizing, then generate an entry from
1207 // this.
Mindy Pereira01382d72011-07-15 16:52:32 -07001208 display = tokens[0].getName();
1209 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001210 return RecipientEntry.constructGeneratedEntry(display, tokens[0].getAddress(),
1211 isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001212 } else {
1213 display = tokens[0].getAddress();
1214 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001215 return RecipientEntry.constructFakeEntry(display, isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001216 }
Mindy Pereira01382d72011-07-15 16:52:32 -07001217 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001218 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001219 // Unable to validate the token or to create a valid token from it.
1220 // Just create a chip the user can edit.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001221 String validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001222 if (mValidator != null && !isValid) {
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001223 // Try fixing up the entry using the validator.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001224 validatedToken = mValidator.fixText(token).toString();
1225 if (!TextUtils.isEmpty(validatedToken)) {
1226 if (validatedToken.contains(token)) {
mindypf30a4282012-12-03 12:16:33 -08001227 // protect against the case of a validator with a null
1228 // domain,
Mindy Pereiradbb85602011-09-16 14:02:14 -07001229 // which doesn't add a domain to the token
1230 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
1231 if (tokenized.length > 0) {
1232 validatedToken = tokenized[0].getAddress();
mindypf30a4282012-12-03 12:16:33 -08001233 isValid = true;
Mindy Pereiradbb85602011-09-16 14:02:14 -07001234 }
1235 } else {
mindypf30a4282012-12-03 12:16:33 -08001236 // We ran into a case where the token was invalid and
1237 // removed
1238 // by the validator. In this case, just use the original
1239 // token
Mindy Pereiradbb85602011-09-16 14:02:14 -07001240 // and let the user sort out the error chip.
1241 validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001242 isValid = false;
Erik184d3772011-08-04 16:07:00 -07001243 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001244 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001245 }
Mindy Pereiraee58f492011-08-08 13:16:46 -07001246 // Otherwise, fallback to just creating an editable email address chip.
mindypf30a4282012-12-03 12:16:33 -08001247 return RecipientEntry.constructFakeEntry(
1248 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid);
Mindy Pereira01382d72011-07-15 16:52:32 -07001249 }
1250
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001251 private boolean isValid(String text) {
1252 return mValidator == null ? true : mValidator.isValid(text);
1253 }
1254
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001255 private static String tokenizeAddress(String destination) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001256 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
1257 if (tokens != null && tokens.length > 0) {
1258 return tokens[0].getAddress();
1259 }
1260 return destination;
Mindy Pereira3bb52162011-07-01 14:52:22 -07001261 }
1262
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001263 @Override
Mindy Pereiracd611952011-06-01 17:02:20 -07001264 public void setTokenizer(Tokenizer tokenizer) {
1265 mTokenizer = tokenizer;
1266 super.setTokenizer(mTokenizer);
1267 }
1268
Mindy Pereiraa8166902011-06-09 17:53:23 -07001269 @Override
1270 public void setValidator(Validator validator) {
1271 mValidator = validator;
1272 super.setValidator(validator);
1273 }
1274
1275 /**
1276 * We cannot use the default mechanism for replaceText. Instead,
1277 * we override onItemClickListener so we can get all the associated
1278 * contact information including display text, address, and id.
1279 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001280 @Override
1281 protected void replaceText(CharSequence text) {
1282 return;
1283 }
1284
Mindy Pereiraa8166902011-06-09 17:53:23 -07001285 /**
1286 * Dismiss any selected chips when the back key is pressed.
1287 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001288 @Override
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001289 public boolean onKeyPreIme(int keyCode, KeyEvent event) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001290 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) {
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001291 clearSelectedChip();
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001292 return true;
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001293 }
1294 return super.onKeyPreIme(keyCode, event);
1295 }
1296
Mindy Pereiraa8166902011-06-09 17:53:23 -07001297 /**
1298 * Monitor key presses in this view to see if the user types
1299 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
1300 * If the user has entered text that has contact matches and types
1301 * a commit key, create a chip from the topmost matching contact.
1302 * If the user has entered text that has no contact matches and types
1303 * a commit key, then create a chip from the text they have entered.
1304 */
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001305 @Override
Mindy Pereiracd611952011-06-01 17:02:20 -07001306 public boolean onKeyUp(int keyCode, KeyEvent event) {
1307 switch (keyCode) {
Mindy Pereira0f0df292011-06-16 20:49:51 -07001308 case KeyEvent.KEYCODE_TAB:
1309 if (event.hasNoModifiers()) {
1310 if (mSelectedChip != null) {
1311 clearSelectedChip();
1312 } else {
1313 commitDefault();
1314 }
Mindy Pereira0f0df292011-06-16 20:49:51 -07001315 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001316 break;
Mindy Pereiracd611952011-06-01 17:02:20 -07001317 }
1318 return super.onKeyUp(keyCode, event);
1319 }
1320
Mindy Pereira0f0df292011-06-16 20:49:51 -07001321 private boolean focusNext() {
1322 View next = focusSearch(View.FOCUS_DOWN);
1323 if (next != null) {
1324 next.requestFocus();
1325 return true;
1326 }
1327 return false;
1328 }
1329
Mindy Pereira34214202011-06-09 20:05:32 -07001330 /**
1331 * Create a chip from the default selection. If the popup is showing, the
Scott Kennedye4945e92014-04-21 20:17:43 -07001332 * default is the selected item (if one is selected), or the first item, in the popup
1333 * suggestions list. Otherwise, it is whatever the user had typed in. End represents where the
1334 * tokenizer should search for a token to turn into a chip.
Mindy Pereira34214202011-06-09 20:05:32 -07001335 * @return If a chip was created from a real contact.
1336 */
Mindy Pereiraa8166902011-06-09 17:53:23 -07001337 private boolean commitDefault() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001338 // If there is no tokenizer, don't try to commit.
1339 if (mTokenizer == null) {
1340 return false;
1341 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001342 Editable editable = getText();
Mindy Pereira34214202011-06-09 20:05:32 -07001343 int end = getSelectionEnd();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001344 int start = mTokenizer.findTokenStart(editable, end);
Mindy Pereira2b4ffc52011-06-20 13:20:09 -07001345
Mindy Pereira79fb4362011-06-21 14:37:07 -07001346 if (shouldCreateChip(start, end)) {
1347 int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1348 // In the middle of chip; treat this as an edit
1349 // and commit the whole token.
mindyp4f82d882012-11-08 16:30:27 -08001350 whatEnd = movePastTerminators(whatEnd);
Mindy Pereira79fb4362011-06-21 14:37:07 -07001351 if (whatEnd != getSelectionEnd()) {
1352 handleEdit(start, whatEnd);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001353 return true;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001354 }
1355 return commitChip(start, end , editable);
1356 }
1357 return false;
1358 }
1359
1360 private void commitByCharacter() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001361 // We can't possibly commit by character if we can't tokenize.
1362 if (mTokenizer == null) {
1363 return;
1364 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001365 Editable editable = getText();
1366 int end = getSelectionEnd();
1367 int start = mTokenizer.findTokenStart(editable, end);
1368 if (shouldCreateChip(start, end)) {
1369 commitChip(start, end, editable);
1370 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001371 setSelection(getText().length());
Mindy Pereira79fb4362011-06-21 14:37:07 -07001372 }
1373
1374 private boolean commitChip(int start, int end, Editable editable) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07001375 ListAdapter adapter = getAdapter();
1376 if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
Tom Taylorc7a87f02012-05-03 15:21:08 -07001377 && end == getSelectionEnd() && !isPhoneQuery()) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001378 // let's choose the selected or first entry if only the input text is NOT an email
1379 // address so we won't try to replace the user's potentially correct but
1380 // new/unencountered email input
Jin Caob3b248a2014-04-11 10:43:50 -07001381 if (!isValidEmailAddress(editable.toString().substring(start, end).trim())) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001382 final int selectedPosition = getListSelection();
1383 if (selectedPosition == -1) {
1384 // Nothing is selected; use the first item
1385 submitItemAtPosition(0);
1386 } else {
1387 submitItemAtPosition(selectedPosition);
1388 }
Jin Caob3b248a2014-04-11 10:43:50 -07001389 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001390 dismissDropDown();
1391 return true;
1392 } else {
1393 int tokenEnd = mTokenizer.findTokenEnd(editable, start);
Mindy Pereira20c9d622011-10-12 13:18:04 -07001394 if (editable.length() > tokenEnd + 1) {
1395 char charAt = editable.charAt(tokenEnd + 1);
1396 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1397 tokenEnd++;
1398 }
Mindy Pereirad7192502011-09-22 08:04:45 -07001399 }
Mindy Pereira62397a52011-10-03 13:46:43 -07001400 String text = editable.toString().substring(start, tokenEnd).trim();
Mindy Pereira79fb4362011-06-21 14:37:07 -07001401 clearComposingText();
1402 if (text != null && text.length() > 0 && !text.equals(" ")) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001403 RecipientEntry entry = createTokenizedEntry(text);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001404 if (entry != null) {
1405 QwertyKeyListener.markAsReplaced(editable, start, end, "");
1406 CharSequence chipText = createChip(entry, false);
Mindy Pereiraee6d83f2011-10-03 14:25:07 -07001407 if (chipText != null && start > -1 && end > -1) {
Mindy Pereiraf177bda2011-09-15 11:23:49 -07001408 editable.replace(start, end, chipText);
1409 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001410 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07001411 // Only dismiss the dropdown if it is related to the text we
1412 // just committed.
1413 // For paste, it may not be as there are possibly multiple
1414 // tokens being added.
1415 if (end == getSelectionEnd()) {
1416 dismissDropDown();
1417 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001418 sanitizeBetween();
Mindy Pereira0f0df292011-06-16 20:49:51 -07001419 return true;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001420 }
1421 }
1422 return false;
Mindy Pereira05dbd332011-06-03 09:37:44 -07001423 }
1424
Mindy Pereira01162ce2011-09-20 12:21:55 -07001425 // Visible for testing.
1426 /* package */ void sanitizeBetween() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001427 // Don't sanitize while we are waiting for content to chipify.
1428 if (mPendingChipsCount > 0) {
1429 return;
1430 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001431 // Find the last chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08001432 DrawableRecipientChip[] recips = getSortedRecipients();
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001433 if (recips != null && recips.length > 0) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001434 DrawableRecipientChip last = recips[recips.length - 1];
1435 DrawableRecipientChip beforeLast = null;
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001436 if (recips.length > 1) {
1437 beforeLast = recips[recips.length - 2];
1438 }
1439 int startLooking = 0;
1440 int end = getSpannable().getSpanStart(last);
1441 if (beforeLast != null) {
1442 startLooking = getSpannable().getSpanEnd(beforeLast);
Mindy Pereira399bda82011-09-20 11:18:26 -07001443 Editable text = getText();
Mindy Pereira01162ce2011-09-20 12:21:55 -07001444 if (startLooking == -1 || startLooking > text.length() - 1) {
Mindy Pereira399bda82011-09-20 11:18:26 -07001445 // There is nothing after this chip.
1446 return;
1447 }
1448 if (text.charAt(startLooking) == ' ') {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001449 startLooking++;
1450 }
1451 }
Mindy Pereirae13775c2011-11-17 11:14:12 -08001452 if (startLooking >= 0 && end >= 0 && startLooking < end) {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001453 getText().delete(startLooking, end);
1454 }
1455 }
1456 }
1457
Mindy Pereira79fb4362011-06-21 14:37:07 -07001458 private boolean shouldCreateChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001459 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
Mindy Pereira32366d42011-07-24 12:39:30 -07001460 }
1461
1462 private boolean alreadyHasChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001463 if (mNoChips) {
1464 return true;
1465 }
Scott Kennedy194d4272013-03-06 22:06:45 -08001466 DrawableRecipientChip[] chips =
1467 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereira32366d42011-07-24 12:39:30 -07001468 if ((chips == null || chips.length == 0)) {
1469 return false;
Mindy Pereira64af2da2011-06-15 11:14:07 -07001470 }
Mindy Pereira32366d42011-07-24 12:39:30 -07001471 return true;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001472 }
1473
1474 private void handleEdit(int start, int end) {
Mindy Pereiraa49e7fa2011-09-13 08:01:36 -07001475 if (start == -1 || end == -1) {
1476 // This chip no longer exists in the field.
1477 dismissDropDown();
1478 return;
1479 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001480 // This is in the middle of a chip, so select out the whole chip
1481 // and commit it.
1482 Editable editable = getText();
1483 setSelection(end);
1484 String text = getText().toString().substring(start, end);
Mindy Pereirafe52b972011-09-16 11:55:57 -07001485 if (!TextUtils.isEmpty(text)) {
mindypf30a4282012-12-03 12:16:33 -08001486 RecipientEntry entry = RecipientEntry.constructFakeEntry(text, isValid(text));
Mindy Pereirafe52b972011-09-16 11:55:57 -07001487 QwertyKeyListener.markAsReplaced(editable, start, end, "");
1488 CharSequence chipText = createChip(entry, false);
Mindy Pereira5cfd6fe2011-10-20 15:36:24 -07001489 int selEnd = getSelectionEnd();
1490 if (chipText != null && start > -1 && selEnd > -1) {
1491 editable.replace(start, selEnd, chipText);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001492 }
Mindy Pereirafe52b972011-09-16 11:55:57 -07001493 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001494 dismissDropDown();
Mindy Pereira64af2da2011-06-15 11:14:07 -07001495 }
1496
Mindy Pereiraa8166902011-06-09 17:53:23 -07001497 /**
1498 * If there is a selected chip, delegate the key events
1499 * to the selected chip.
1500 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001501 @Override
1502 public boolean onKeyDown(int keyCode, KeyEvent event) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001503 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1504 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1505 mAlternatesPopup.dismiss();
1506 }
1507 removeChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001508 }
1509
Scott Kennedy2fe0cff2013-02-14 18:39:37 -08001510 switch (keyCode) {
1511 case KeyEvent.KEYCODE_ENTER:
1512 case KeyEvent.KEYCODE_DPAD_CENTER:
1513 if (event.hasNoModifiers()) {
1514 if (commitDefault()) {
1515 return true;
1516 }
1517 if (mSelectedChip != null) {
1518 clearSelectedChip();
1519 return true;
1520 } else if (focusNext()) {
1521 return true;
1522 }
1523 }
1524 break;
1525 }
1526
Mindy Pereiracd611952011-06-01 17:02:20 -07001527 return super.onKeyDown(keyCode, event);
1528 }
1529
Mindy Pereira01162ce2011-09-20 12:21:55 -07001530 // Visible for testing.
1531 /* package */ Spannable getSpannable() {
Erike33555f2011-06-21 14:20:20 -07001532 return getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001533 }
1534
Scott Kennedy194d4272013-03-06 22:06:45 -08001535 private int getChipStart(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001536 return getSpannable().getSpanStart(chip);
1537 }
1538
Scott Kennedy194d4272013-03-06 22:06:45 -08001539 private int getChipEnd(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001540 return getSpannable().getSpanEnd(chip);
1541 }
1542
Mindy Pereiracd611952011-06-01 17:02:20 -07001543 /**
1544 * Instead of filtering on the entire contents of the edit box,
1545 * this subclass method filters on the range from
1546 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1547 * if the length of that range meets or exceeds {@link #getThreshold}
1548 * and makes sure that the range is not already a Chip.
1549 */
1550 @Override
1551 protected void performFiltering(CharSequence text, int keyCode) {
mindyp093ecdd2012-12-14 10:40:51 -08001552 boolean isCompletedToken = isCompletedToken(text);
1553 if (enoughToFilter() && !isCompletedToken) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001554 int end = getSelectionEnd();
1555 int start = mTokenizer.findTokenStart(text, end);
1556 // If this is a RecipientChip, don't filter
1557 // on its contents.
1558 Spannable span = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001559 DrawableRecipientChip[] chips = span.getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001560 if (chips != null && chips.length > 0) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001561 dismissDropDown();
Mindy Pereiracd611952011-06-01 17:02:20 -07001562 return;
1563 }
mindyp093ecdd2012-12-14 10:40:51 -08001564 } else if (isCompletedToken) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001565 dismissDropDown();
mindyp093ecdd2012-12-14 10:40:51 -08001566 return;
Mindy Pereiracd611952011-06-01 17:02:20 -07001567 }
1568 super.performFiltering(text, keyCode);
1569 }
1570
Mindy Pereira20c9d622011-10-12 13:18:04 -07001571 // Visible for testing.
1572 /*package*/ boolean isCompletedToken(CharSequence text) {
1573 if (TextUtils.isEmpty(text)) {
1574 return false;
1575 }
1576 // Check to see if this is a completed token before filtering.
1577 int end = text.length();
1578 int start = mTokenizer.findTokenStart(text, end);
1579 String token = text.toString().substring(start, end).trim();
1580 if (!TextUtils.isEmpty(token)) {
1581 char atEnd = token.charAt(token.length() - 1);
1582 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1583 }
1584 return false;
1585 }
1586
Mindy Pereiracd611952011-06-01 17:02:20 -07001587 private void clearSelectedChip() {
1588 if (mSelectedChip != null) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001589 unselectChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001590 mSelectedChip = null;
1591 }
Mindy Pereirab86dcd52011-06-02 13:52:30 -07001592 setCursorVisible(true);
Mindy Pereiracd611952011-06-01 17:02:20 -07001593 }
1594
Mindy Pereiraa8166902011-06-09 17:53:23 -07001595 /**
1596 * Monitor touch events in the RecipientEditTextView.
1597 * If the view does not have focus, any tap on the view
1598 * will just focus the view. If the view has focus, determine
1599 * if the touch target is a recipient chip. If it is and the chip
1600 * is not selected, select it and clear any other selected chips.
1601 * If it isn't, then select that chip.
1602 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001603 @Override
1604 public boolean onTouchEvent(MotionEvent event) {
Mindy Pereira05dbd332011-06-03 09:37:44 -07001605 if (!isFocused()) {
1606 // Ignore any chip taps until this view is focused.
1607 return super.onTouchEvent(event);
1608 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001609 boolean handled = super.onTouchEvent(event);
Mindy Pereira05dbd332011-06-03 09:37:44 -07001610 int action = event.getAction();
Mindy Pereiracd611952011-06-01 17:02:20 -07001611 boolean chipWasSelected = false;
Mindy Pereira2e905902011-09-08 16:17:04 -07001612 if (mSelectedChip == null) {
Mindy Pereira1d1ec852011-08-09 16:49:33 -07001613 mGestureDetector.onTouchEvent(event);
1614 }
Mindy Pereirabfedc1e2011-09-07 12:17:12 -07001615 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001616 float x = event.getX();
1617 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07001618 int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08001619 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereiracd611952011-06-01 17:02:20 -07001620 if (currentChip != null) {
1621 if (action == MotionEvent.ACTION_UP) {
1622 if (mSelectedChip != null && mSelectedChip != currentChip) {
1623 clearSelectedChip();
Mindy Pereira95a69252011-06-17 15:02:03 -07001624 mSelectedChip = selectChip(currentChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001625 } else if (mSelectedChip == null) {
Mindy Pereiraa8166902011-06-09 17:53:23 -07001626 setSelection(getText().length());
1627 commitDefault();
Mindy Pereira95a69252011-06-17 15:02:03 -07001628 mSelectedChip = selectChip(currentChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001629 } else {
Jin Caoa21fd882014-08-10 13:07:11 -07001630 onClick(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001631 }
1632 }
1633 chipWasSelected = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001634 handled = true;
mindyp5e60c2b2012-11-06 17:47:40 -08001635 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07001636 chipWasSelected = true;
Mindy Pereiracd611952011-06-01 17:02:20 -07001637 }
1638 }
1639 if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1640 clearSelectedChip();
1641 }
1642 return handled;
1643 }
1644
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001645 private void scrollLineIntoView(int line) {
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001646 if (mScrollView != null) {
mindyp093ecdd2012-12-14 10:40:51 -08001647 mScrollView.smoothScrollBy(0, calculateOffsetFromBottom(line));
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001648 }
1649 }
1650
Scott Kennedy272aae02013-04-05 17:17:24 -07001651 private void showAlternates(final DrawableRecipientChip currentChip,
Jin Cao9b166202014-08-08 13:26:14 -07001652 final ListPopupWindow alternatesPopup) {
Scott Kennedy272aae02013-04-05 17:17:24 -07001653 new AsyncTask<Void, Void, ListAdapter>() {
1654 @Override
1655 protected ListAdapter doInBackground(final Void... params) {
1656 return createAlternatesAdapter(currentChip);
1657 }
1658
Alice Yang6b7110f2013-04-26 12:50:35 -07001659 @Override
Scott Kennedy272aae02013-04-05 17:17:24 -07001660 protected void onPostExecute(final ListAdapter result) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07001661 if (!mAttachedToWindow) {
1662 return;
1663 }
Scott Kennedy272aae02013-04-05 17:17:24 -07001664 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07001665 int bottomOffset = calculateOffsetFromBottomToTop(line);
1666
Scott Kennedy272aae02013-04-05 17:17:24 -07001667 // Align the alternates popup with the left side of the View,
1668 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07001669 alternatesPopup.setAnchorView((mAlternatePopupAnchor != null) ?
1670 mAlternatePopupAnchor : RecipientEditTextView.this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07001671 alternatesPopup.setVerticalOffset(bottomOffset);
Scott Kennedy272aae02013-04-05 17:17:24 -07001672 alternatesPopup.setAdapter(result);
1673 alternatesPopup.setOnItemClickListener(mAlternatesListener);
1674 // Clear the checked item.
1675 mCheckedItem = -1;
1676 alternatesPopup.show();
1677 ListView listView = alternatesPopup.getListView();
1678 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1679 // Checked item would be -1 if the adapter has not
1680 // loaded the view that should be checked yet. The
1681 // variable will be set correctly when onCheckedItemChanged
1682 // is called in a separate thread.
1683 if (mCheckedItem != -1) {
1684 listView.setItemChecked(mCheckedItem, true);
1685 mCheckedItem = -1;
1686 }
1687 }
1688 }.execute((Void[]) null);
Mindy Pereira95a69252011-06-17 15:02:03 -07001689 }
1690
Scott Kennedy194d4272013-03-06 22:06:45 -08001691 private ListAdapter createAlternatesAdapter(DrawableRecipientChip chip) {
Scott Kennedy7a4e6772013-11-21 14:31:33 -08001692 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(),
1693 chip.getDirectoryId(), chip.getLookupKey(), chip.getDataId(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001694 getAdapter().getQueryType(), this, mDropdownChipLayouter,
1695 constructStateListDeleteDrawable());
Mindy Pereira95a69252011-06-17 15:02:03 -07001696 }
1697
Scott Kennedy194d4272013-03-06 22:06:45 -08001698 private ListAdapter createSingleAddressAdapter(DrawableRecipientChip currentChip) {
Kevin Linb10d1c62014-01-24 12:45:00 -08001699 return new SingleRecipientArrayAdapter(getContext(), currentChip.getEntry(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001700 mDropdownChipLayouter, constructStateListDeleteDrawable());
1701 }
1702
1703 private StateListDrawable constructStateListDeleteDrawable() {
1704 // Construct the StateListDrawable from deleteDrawable
1705 StateListDrawable deleteDrawable = new StateListDrawable();
Jin Caoa21fd882014-08-10 13:07:11 -07001706 if (!mDisableDelete) {
1707 deleteDrawable.addState(new int[]{android.R.attr.state_activated}, mChipDelete);
1708 }
Jin Cao4db8ccc2014-07-30 10:11:07 -07001709 deleteDrawable.addState(new int[0], null);
1710 return deleteDrawable;
Mindy Pereira01382d72011-07-15 16:52:32 -07001711 }
1712
Andy Stadleraa2afff2011-08-04 16:22:47 -07001713 @Override
Mindy Pereira95a69252011-06-17 15:02:03 -07001714 public void onCheckedItemChanged(int position) {
1715 ListView listView = mAlternatesPopup.getListView();
1716 if (listView != null && listView.getCheckedItemCount() == 0) {
1717 listView.setItemChecked(position, true);
Mindy Pereira95a69252011-06-17 15:02:03 -07001718 }
Mindy Pereira98b547f2011-09-08 09:27:39 -07001719 mCheckedItem = position;
Mindy Pereira95a69252011-06-17 15:02:03 -07001720 }
1721
Scott Kennedy1650ef62013-08-02 21:56:47 -07001722 private int putOffsetInRange(final float x, final float y) {
1723 final int offset;
1724
1725 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1726 offset = getOffsetForPosition(x, y);
1727 } else {
1728 offset = supportGetOffsetForPosition(x, y);
1729 }
1730
1731 return putOffsetInRange(offset);
1732 }
1733
Mindy Pereiracd611952011-06-01 17:02:20 -07001734 // TODO: This algorithm will need a lot of tweaking after more people have used
1735 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1736 // what comes before the finger.
1737 private int putOffsetInRange(int o) {
1738 int offset = o;
1739 Editable text = getText();
1740 int length = text.length();
1741 // Remove whitespace from end to find "real end"
1742 int realLength = length;
1743 for (int i = length - 1; i >= 0; i--) {
1744 if (text.charAt(i) == ' ') {
1745 realLength--;
1746 } else {
1747 break;
1748 }
1749 }
1750
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001751 // If the offset is beyond or at the end of the text,
1752 // leave it alone.
1753 if (offset >= realLength) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001754 return offset;
1755 }
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001756 Editable editable = getText();
Mindy Pereirab88ee452011-06-02 11:07:43 -07001757 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001758 // Keep walking backward!
1759 offset--;
1760 }
1761 return offset;
1762 }
1763
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001764 private static int findText(Editable text, int offset) {
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001765 if (text.charAt(offset) != ' ') {
1766 return offset;
1767 }
1768 return -1;
1769 }
1770
Scott Kennedy194d4272013-03-06 22:06:45 -08001771 private DrawableRecipientChip findChip(int offset) {
1772 DrawableRecipientChip[] chips =
1773 getSpannable().getSpans(0, getText().length(), DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001774 // Find the chip that contains this offset.
1775 for (int i = 0; i < chips.length; i++) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001776 DrawableRecipientChip chip = chips[i];
Mindy Pereira95a69252011-06-17 15:02:03 -07001777 int start = getChipStart(chip);
1778 int end = getChipEnd(chip);
1779 if (offset >= start && offset <= end) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001780 return chip;
1781 }
1782 }
1783 return null;
1784 }
1785
Mindy Pereira01162ce2011-09-20 12:21:55 -07001786 // Visible for testing.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001787 // Use this method to generate text to add to the list of addresses.
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001788 /* package */String createAddressText(RecipientEntry entry) {
Mindy Pereira3ea99552011-09-19 10:50:31 -07001789 String display = entry.getDisplayName();
1790 String address = entry.getDestination();
1791 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1792 display = null;
1793 }
Tom Taylorabff6062012-04-17 09:04:56 -07001794 String trimmedDisplayText;
Tom Taylorc7a87f02012-05-03 15:21:08 -07001795 if (isPhoneQuery() && isPhoneNumber(address)) {
Tom Taylorabff6062012-04-17 09:04:56 -07001796 trimmedDisplayText = address.trim();
1797 } else {
1798 if (address != null) {
1799 // Tokenize out the address in case the address already
1800 // contained the username as well.
1801 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1802 if (tokenized != null && tokenized.length > 0) {
1803 address = tokenized[0].getAddress();
1804 }
Mindy Pereiraee48f732011-09-20 08:13:39 -07001805 }
Tom Taylorabff6062012-04-17 09:04:56 -07001806 Rfc822Token token = new Rfc822Token(display, address, null);
1807 trimmedDisplayText = token.toString().trim();
Mindy Pereirad8c15c32011-09-19 15:02:05 -07001808 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001809 int index = trimmedDisplayText.indexOf(",");
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001810 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1811 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001812 .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1813 }
1814
1815 // Visible for testing.
1816 // Use this method to generate text to display in a chip.
1817 /*package*/ String createChipDisplayText(RecipientEntry entry) {
1818 String display = entry.getDisplayName();
1819 String address = entry.getDestination();
1820 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1821 display = null;
1822 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001823 if (!TextUtils.isEmpty(display)) {
1824 return display;
1825 } else if (!TextUtils.isEmpty(address)){
1826 return address;
1827 } else {
1828 return new Rfc822Token(display, address, null).toString();
1829 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001830 }
1831
Mindy Pereira0ab7e732011-06-08 10:17:39 -07001832 private CharSequence createChip(RecipientEntry entry, boolean pressed) {
Jin Cao4db8ccc2014-07-30 10:11:07 -07001833 final String displayText = createAddressText(entry);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001834 if (TextUtils.isEmpty(displayText)) {
1835 return null;
1836 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001837 // Always leave a blank space at the end of a chip.
Jin Cao4db8ccc2014-07-30 10:11:07 -07001838 final int textLength = displayText.length() - 1;
1839 final SpannableString chipText = new SpannableString(displayText);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001840 if (!mNoChips) {
1841 try {
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07001842 DrawableRecipientChip chip = constructChipSpan(entry, pressed);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001843 chipText.setSpan(chip, 0, textLength,
1844 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1845 chip.setOriginalText(chipText.toString());
1846 } catch (NullPointerException e) {
1847 Log.e(TAG, e.getMessage(), e);
1848 return null;
1849 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001850 }
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001851 onChipCreated(entry);
Mindy Pereiracd611952011-06-01 17:02:20 -07001852 return chipText;
1853 }
1854
Mindy Pereiraa8166902011-06-09 17:53:23 -07001855 /**
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001856 * A callback for subclasses to use to know when a chip was created with the
1857 * given RecipientEntry.
1858 */
1859 protected void onChipCreated(RecipientEntry entry) {}
1860
1861 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -07001862 * When an item in the suggestions list has been clicked, create a chip from the
1863 * contact information of the selected item.
1864 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001865 @Override
1866 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tom Taylor114c8932013-04-10 13:11:05 -07001867 if (position < 0) {
1868 return;
1869 }
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001870
1871 final int charactersTyped = submitItemAtPosition(position);
1872 if (charactersTyped > -1 && mRecipientEntryItemClickedListener != null) {
1873 mRecipientEntryItemClickedListener
1874 .onRecipientEntryItemClicked(charactersTyped, position);
1875 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001876 }
1877
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001878 private int submitItemAtPosition(int position) {
Scott Kennedy858e0942013-10-10 11:50:01 -07001879 RecipientEntry entry = createValidatedEntry(getAdapter().getItem(position));
Erikf7eaa5f2011-07-14 17:02:07 -07001880 if (entry == null) {
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001881 return -1;
Erikf7eaa5f2011-07-14 17:02:07 -07001882 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001883 clearComposingText();
1884
1885 int end = getSelectionEnd();
1886 int start = mTokenizer.findTokenStart(getText(), end);
1887
1888 Editable editable = getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001889 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereirae90bfad2011-07-26 14:51:41 -07001890 CharSequence chip = createChip(entry, false);
Mindy Pereira005b2e22011-11-01 10:26:58 -07001891 if (chip != null && start >= 0 && end >= 0) {
Mindy Pereirae90bfad2011-07-26 14:51:41 -07001892 editable.replace(start, end, chip);
1893 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001894 sanitizeBetween();
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001895
1896 return end - start;
Mindy Pereiracd611952011-06-01 17:02:20 -07001897 }
1898
Mindy Pereira3bb52162011-07-01 14:52:22 -07001899 private RecipientEntry createValidatedEntry(RecipientEntry item) {
1900 if (item == null) {
1901 return null;
1902 }
1903 final RecipientEntry entry;
1904 // If the display name and the address are the same, or if this is a
1905 // valid contact, but the destination is invalid, then make this a fake
1906 // recipient that is editable.
1907 String destination = item.getDestination();
mindyp5e60c2b2012-11-06 17:47:40 -08001908 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1909 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
mindypf30a4282012-12-03 12:16:33 -08001910 destination, item.isValid());
mindyp5e60c2b2012-11-06 17:47:40 -08001911 } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
Mindy Pereirab4e244a2011-10-14 11:13:29 -07001912 && (TextUtils.isEmpty(item.getDisplayName())
1913 || TextUtils.equals(item.getDisplayName(), destination)
1914 || (mValidator != null && !mValidator.isValid(destination)))) {
mindypf30a4282012-12-03 12:16:33 -08001915 entry = RecipientEntry.constructFakeEntry(destination, item.isValid());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001916 } else {
1917 entry = item;
1918 }
1919 return entry;
1920 }
1921
Mindy Pereira01162ce2011-09-20 12:21:55 -07001922 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08001923 /* package */DrawableRecipientChip[] getSortedRecipients() {
1924 DrawableRecipientChip[] recips = getSpannable()
1925 .getSpans(0, getText().length(), DrawableRecipientChip.class);
1926 ArrayList<DrawableRecipientChip> recipientsList = new ArrayList<DrawableRecipientChip>(
1927 Arrays.asList(recips));
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001928 final Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001929 Collections.sort(recipientsList, new Comparator<DrawableRecipientChip>() {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001930
1931 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08001932 public int compare(DrawableRecipientChip first, DrawableRecipientChip second) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001933 int firstStart = spannable.getSpanStart(first);
1934 int secondStart = spannable.getSpanStart(second);
1935 if (firstStart < secondStart) {
1936 return -1;
1937 } else if (firstStart > secondStart) {
1938 return 1;
1939 } else {
1940 return 0;
1941 }
1942 }
1943 });
Scott Kennedy194d4272013-03-06 22:06:45 -08001944 return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001945 }
1946
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001947 @Override
1948 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1949 return false;
1950 }
1951
1952 @Override
1953 public void onDestroyActionMode(ActionMode mode) {
1954 }
1955
1956 @Override
1957 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
1958 return false;
1959 }
1960
Mindy Pereiraa8166902011-06-09 17:53:23 -07001961 /**
1962 * No chips are selectable.
1963 */
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001964 @Override
1965 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
1966 return false;
1967 }
1968
Mindy Pereirad7192502011-09-22 08:04:45 -07001969 // Visible for testing.
Jin Cao6c2a0162014-08-17 15:00:50 -07001970 /* package */ReplacementDrawableSpan getMoreChip() {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001971 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
1972 MoreImageSpan.class);
1973 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
1974 }
1975
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001976 private MoreImageSpan createMoreSpan(int count) {
1977 String moreText = String.format(mMoreItem.getText().toString(), count);
Jin Cao6c2a0162014-08-17 15:00:50 -07001978 mWorkPaint.set(getPaint());
1979 mWorkPaint.setTextSize(mMoreItem.getTextSize());
1980 mWorkPaint.setColor(mMoreItem.getCurrentTextColor());
1981 final int width = (int) mWorkPaint.measureText(moreText) + mMoreItem.getPaddingLeft()
Mindy Pereira750e6e52011-07-25 11:51:30 -07001982 + mMoreItem.getPaddingRight();
Jin Cao6c2a0162014-08-17 15:00:50 -07001983 final int height = (int) mChipHeight;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001984 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
1985 Canvas canvas = new Canvas(drawable);
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001986 int adjustedHeight = height;
1987 Layout layout = getLayout();
1988 if (layout != null) {
1989 adjustedHeight -= layout.getLineDescent(0);
1990 }
Jin Cao6c2a0162014-08-17 15:00:50 -07001991 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, mWorkPaint);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001992
1993 Drawable result = new BitmapDrawable(getResources(), drawable);
1994 result.setBounds(0, 0, width, height);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001995 return new MoreImageSpan(result);
1996 }
1997
1998 // Visible for testing.
1999 /*package*/ void createMoreChipPlainText() {
2000 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
2001 Editable text = getText();
2002 int start = 0;
2003 int end = start;
2004 for (int i = 0; i < CHIP_LIMIT; i++) {
2005 end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2006 start = end; // move to the next token and get its end.
2007 }
2008 // Now, count total addresses.
2009 start = 0;
2010 int tokenCount = countTokens(text);
2011 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
2012 SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
2013 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2014 text.replace(end, text.length(), chipText);
2015 mMoreChip = moreSpan;
2016 }
2017
2018 // Visible for testing.
2019 /* package */int countTokens(Editable text) {
2020 int tokenCount = 0;
2021 int start = 0;
2022 while (start < text.length()) {
2023 start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2024 tokenCount++;
2025 if (start >= text.length()) {
2026 break;
2027 }
2028 }
2029 return tokenCount;
2030 }
2031
2032 /**
2033 * Create the more chip. The more chip is text that replaces any chips that
2034 * do not fit in the pre-defined available space when the
2035 * RecipientEditTextView loses focus.
2036 */
2037 // Visible for testing.
2038 /* package */ void createMoreChip() {
2039 if (mNoChips) {
2040 createMoreChipPlainText();
2041 return;
2042 }
2043
2044 if (!mShouldShrink) {
2045 return;
2046 }
Jin Cao6c2a0162014-08-17 15:00:50 -07002047 ReplacementDrawableSpan[] tempMore = getSpannable().getSpans(0, getText().length(),
2048 MoreImageSpan.class);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002049 if (tempMore.length > 0) {
2050 getSpannable().removeSpan(tempMore[0]);
2051 }
Scott Kennedy194d4272013-03-06 22:06:45 -08002052 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002053
2054 if (recipients == null || recipients.length <= CHIP_LIMIT) {
Mindy Pereira3bb52162011-07-01 14:52:22 -07002055 mMoreChip = null;
2056 return;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002057 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002058 Spannable spannable = getSpannable();
2059 int numRecipients = recipients.length;
2060 int overage = numRecipients - CHIP_LIMIT;
2061 MoreImageSpan moreSpan = createMoreSpan(overage);
Scott Kennedy194d4272013-03-06 22:06:45 -08002062 mRemovedSpans = new ArrayList<DrawableRecipientChip>();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002063 int totalReplaceStart = 0;
2064 int totalReplaceEnd = 0;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002065 Editable text = getText();
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002066 for (int i = numRecipients - overage; i < recipients.length; i++) {
2067 mRemovedSpans.add(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002068 if (i == numRecipients - overage) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002069 totalReplaceStart = spannable.getSpanStart(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002070 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002071 if (i == recipients.length - 1) {
2072 totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002073 }
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002074 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
2075 int spanStart = spannable.getSpanStart(recipients[i]);
2076 int spanEnd = spannable.getSpanEnd(recipients[i]);
2077 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
Mindy Pereira18529312011-06-28 11:00:52 -07002078 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002079 spannable.removeSpan(recipients[i]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002080 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002081 if (totalReplaceEnd < text.length()) {
2082 totalReplaceEnd = text.length();
2083 }
Mindy Pereira18529312011-06-28 11:00:52 -07002084 int end = Math.max(totalReplaceStart, totalReplaceEnd);
2085 int start = Math.min(totalReplaceStart, totalReplaceEnd);
2086 SpannableString chipText = new SpannableString(text.subSequence(start, end));
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002087 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereira18529312011-06-28 11:00:52 -07002088 text.replace(start, end, chipText);
Mindy Pereira3bb52162011-07-01 14:52:22 -07002089 mMoreChip = moreSpan;
mindyp5e60c2b2012-11-06 17:47:40 -08002090 // If adding the +more chip goes over the limit, resize accordingly.
2091 if (!isPhoneQuery() && getLineCount() > mMaxLines) {
2092 setMaxLines(getLineCount());
2093 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002094 }
2095
Mindy Pereiraa8166902011-06-09 17:53:23 -07002096 /**
2097 * Replace the more chip, if it exists, with all of the recipient chips it had
2098 * replaced when the RecipientEditTextView gains focus.
2099 */
Mindy Pereirad7192502011-09-22 08:04:45 -07002100 // Visible for testing.
2101 /*package*/ void removeMoreChip() {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002102 if (mMoreChip != null) {
2103 Spannable span = getSpannable();
2104 span.removeSpan(mMoreChip);
2105 mMoreChip = null;
2106 // Re-add the spans that were removed.
2107 if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
2108 // Recreate each removed span.
Scott Kennedy194d4272013-03-06 22:06:45 -08002109 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereira54effe92011-09-09 09:46:38 -07002110 // Start the search for tokens after the last currently visible
2111 // chip.
Mindy Pereiraee48f732011-09-20 08:13:39 -07002112 if (recipients == null || recipients.length == 0) {
2113 return;
2114 }
Mindy Pereira54effe92011-09-09 09:46:38 -07002115 int end = span.getSpanEnd(recipients[recipients.length - 1]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002116 Editable editable = getText();
Scott Kennedy194d4272013-03-06 22:06:45 -08002117 for (DrawableRecipientChip chip : mRemovedSpans) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002118 int chipStart;
Mindy Pereira3bb52162011-07-01 14:52:22 -07002119 int chipEnd;
2120 String token;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002121 // Need to find the location of the chip, again.
2122 token = (String) chip.getOriginalText();
Mindy Pereira54effe92011-09-09 09:46:38 -07002123 // As we find the matching recipient for the remove spans,
2124 // reduce the size of the string we need to search.
2125 // That way, if there are duplicates, we always find the correct
2126 // recipient.
2127 chipStart = editable.toString().indexOf(token, end);
Mindy Pereira54effe92011-09-09 09:46:38 -07002128 end = chipEnd = Math.min(editable.length(), chipStart + token.length());
Mindy Pereira0d8b77a2011-07-08 10:26:30 -07002129 // Only set the span if we found a matching token.
2130 if (chipStart != -1) {
2131 editable.setSpan(chip, chipStart, chipEnd,
2132 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
2133 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002134 }
2135 mRemovedSpans.clear();
2136 }
2137 }
2138 }
2139
Mindy Pereiracd611952011-06-01 17:02:20 -07002140 /**
Mindy Pereira95a69252011-06-17 15:02:03 -07002141 * Show specified chip as selected. If the RecipientChip is just an email address,
2142 * selecting the chip will take the contents of the chip and place it at
2143 * the end of the RecipientEditTextView for inline editing. If the
2144 * RecipientChip is a complete contact, then selecting the chip
2145 * will change the background color of the chip, show the delete icon,
2146 * and a popup window with the address in use highlighted and any other
2147 * alternate addresses for the contact.
2148 * @param currentChip Chip to select.
2149 * @return A RecipientChip in the selected state or null if the chip
2150 * just contained an email address.
Mindy Pereiracd611952011-06-01 17:02:20 -07002151 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002152 private DrawableRecipientChip selectChip(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002153 if (shouldShowEditableText(currentChip)) {
Mindy Pereira01382d72011-07-15 16:52:32 -07002154 CharSequence text = currentChip.getValue();
2155 Editable editable = getText();
mindypf30a4282012-12-03 12:16:33 -08002156 Spannable spannable = getSpannable();
2157 int spanStart = spannable.getSpanStart(currentChip);
2158 int spanEnd = spannable.getSpanEnd(currentChip);
2159 spannable.removeSpan(currentChip);
2160 editable.delete(spanStart, spanEnd);
Mindy Pereira01382d72011-07-15 16:52:32 -07002161 setCursorVisible(true);
2162 setSelection(editable.length());
mindypf30a4282012-12-03 12:16:33 -08002163 editable.append(text);
2164 return constructChipSpan(
2165 RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())),
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002166 true);
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002167 } else {
Mindy Pereira95a69252011-06-17 15:02:03 -07002168 int start = getChipStart(currentChip);
2169 int end = getChipEnd(currentChip);
2170 getSpannable().removeSpan(currentChip);
Scott Kennedy194d4272013-03-06 22:06:45 -08002171 DrawableRecipientChip newChip;
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002172 final boolean showAddress =
2173 currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT ||
2174 getAdapter().forceShowAddress();
Mindy Pereira95a69252011-06-17 15:02:03 -07002175 try {
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002176 if (showAddress && mNoChips) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002177 return null;
2178 }
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002179 newChip = constructChipSpan(currentChip.getEntry(), true);
Mindy Pereira95a69252011-06-17 15:02:03 -07002180 } catch (NullPointerException e) {
2181 Log.e(TAG, e.getMessage(), e);
Mindy Pereira0ab7e732011-06-08 10:17:39 -07002182 return null;
Mindy Pereiracd611952011-06-01 17:02:20 -07002183 }
Mindy Pereira0ab7e732011-06-08 10:17:39 -07002184 Editable editable = getText();
Mindy Pereira95a69252011-06-17 15:02:03 -07002185 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereira0ab7e732011-06-08 10:17:39 -07002186 if (start == -1 || end == -1) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002187 Log.d(TAG, "The chip being selected no longer exists but should.");
Mindy Pereiracd611952011-06-01 17:02:20 -07002188 } else {
Mindy Pereira04da3252011-07-06 16:09:25 -07002189 editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiracd611952011-06-01 17:02:20 -07002190 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002191 newChip.setSelected(true);
mindyp5e60c2b2012-11-06 17:47:40 -08002192 if (shouldShowEditableText(newChip)) {
Mindy Pereira01382d72011-07-15 16:52:32 -07002193 scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
2194 }
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002195 if (showAddress) {
Jin Cao9b166202014-08-08 13:26:14 -07002196 showAddress(newChip, mAddressPopup);
Mindy Pereira01382d72011-07-15 16:52:32 -07002197 } else {
Jin Cao9b166202014-08-08 13:26:14 -07002198 showAlternates(newChip, mAlternatesPopup);
Mindy Pereira01382d72011-07-15 16:52:32 -07002199 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07002200 setCursorVisible(false);
Mindy Pereira95a69252011-06-17 15:02:03 -07002201 return newChip;
Mindy Pereira95a69252011-06-17 15:02:03 -07002202 }
2203 }
2204
Scott Kennedy194d4272013-03-06 22:06:45 -08002205 private boolean shouldShowEditableText(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002206 long contactId = currentChip.getContactId();
2207 return contactId == RecipientEntry.INVALID_CONTACT
2208 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2209 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002210
Jin Cao9b166202014-08-08 13:26:14 -07002211 private void showAddress(final DrawableRecipientChip currentChip, final ListPopupWindow popup) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07002212 if (!mAttachedToWindow) {
2213 return;
2214 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002215 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07002216 int bottomOffset = calculateOffsetFromBottomToTop(line);
Mindy Pereira01382d72011-07-15 16:52:32 -07002217 // Align the alternates popup with the left side of the View,
2218 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07002219 popup.setAnchorView((mAlternatePopupAnchor != null) ? mAlternatePopupAnchor : this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07002220 popup.setVerticalOffset(bottomOffset);
Mindy Pereira01382d72011-07-15 16:52:32 -07002221 popup.setAdapter(createSingleAddressAdapter(currentChip));
2222 popup.setOnItemClickListener(new OnItemClickListener() {
2223 @Override
2224 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2225 unselectChip(currentChip);
2226 popup.dismiss();
2227 }
2228 });
2229 popup.show();
2230 ListView listView = popup.getListView();
2231 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2232 listView.setItemChecked(0, true);
2233 }
2234
Mindy Pereira95a69252011-06-17 15:02:03 -07002235 /**
2236 * Remove selection from this chip. Unselecting a RecipientChip will render
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002237 * the chip without a delete icon and with an unfocused background. This is
2238 * called when the RecipientChip no longer has focus.
Mindy Pereira95a69252011-06-17 15:02:03 -07002239 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002240 private void unselectChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002241 int start = getChipStart(chip);
2242 int end = getChipEnd(chip);
2243 Editable editable = getText();
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002244 mSelectedChip = null;
Mindy Pereira95a69252011-06-17 15:02:03 -07002245 if (start == -1 || end == -1) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002246 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002247 setSelection(editable.length());
2248 commitDefault();
Mindy Pereira95a69252011-06-17 15:02:03 -07002249 } else {
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002250 getSpannable().removeSpan(chip);
Mindy Pereira95a69252011-06-17 15:02:03 -07002251 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereira04da3252011-07-06 16:09:25 -07002252 editable.removeSpan(chip);
2253 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002254 if (!mNoChips) {
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002255 editable.setSpan(constructChipSpan(chip.getEntry(), false),
mindyp5e60c2b2012-11-06 17:47:40 -08002256 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002257 }
Mindy Pereira04da3252011-07-06 16:09:25 -07002258 } catch (NullPointerException e) {
2259 Log.e(TAG, e.getMessage(), e);
2260 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002261 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002262 setCursorVisible(true);
2263 setSelection(editable.length());
2264 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2265 mAlternatesPopup.dismiss();
2266 }
2267 }
2268
Jin Cao4db8ccc2014-07-30 10:11:07 -07002269 @Override
2270 public void onChipDelete() {
2271 if (mSelectedChip != null) {
2272 removeChip(mSelectedChip);
Jin Cao4db8ccc2014-07-30 10:11:07 -07002273 }
Jin Caoa21fd882014-08-10 13:07:11 -07002274 mAddressPopup.dismiss();
2275 mAlternatesPopup.dismiss();
Jin Cao4db8ccc2014-07-30 10:11:07 -07002276 }
2277
Mindy Pereira95a69252011-06-17 15:02:03 -07002278 /**
2279 * Remove the chip and any text associated with it from the RecipientEditTextView.
2280 */
Mindy Pereira97cb2592011-09-26 16:11:41 -07002281 // Visible for testing.
Kevin Linb10d1c62014-01-24 12:45:00 -08002282 /* package */void removeChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002283 Spannable spannable = getSpannable();
2284 int spanStart = spannable.getSpanStart(chip);
2285 int spanEnd = spannable.getSpanEnd(chip);
2286 Editable text = getText();
Mindy Pereira62397a52011-10-03 13:46:43 -07002287 int toDelete = spanEnd;
Mindy Pereira95a69252011-06-17 15:02:03 -07002288 boolean wasSelected = chip == mSelectedChip;
2289 // Clear that there is a selected chip before updating any text.
2290 if (wasSelected) {
2291 mSelectedChip = null;
2292 }
Mindy Pereira62397a52011-10-03 13:46:43 -07002293 // Always remove trailing spaces when removing a chip.
2294 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2295 toDelete++;
2296 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002297 spannable.removeSpan(chip);
Mindy Pereiraf6d4bfc2012-04-24 15:13:34 -07002298 if (spanStart >= 0 && toDelete > 0) {
2299 text.delete(spanStart, toDelete);
2300 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002301 if (wasSelected) {
2302 clearSelectedChip();
2303 }
2304 }
2305
2306 /**
2307 * Replace this currently selected chip with a new chip
2308 * that uses the contact data provided.
2309 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07002310 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002311 /*package*/ void replaceChip(DrawableRecipientChip chip, RecipientEntry entry) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002312 boolean wasSelected = chip == mSelectedChip;
2313 if (wasSelected) {
2314 mSelectedChip = null;
2315 }
2316 int start = getChipStart(chip);
2317 int end = getChipEnd(chip);
2318 getSpannable().removeSpan(chip);
2319 Editable editable = getText();
2320 CharSequence chipText = createChip(entry, false);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002321 if (chipText != null) {
2322 if (start == -1 || end == -1) {
2323 Log.e(TAG, "The chip to replace does not exist but should.");
2324 editable.insert(0, chipText);
2325 } else {
2326 if (!TextUtils.isEmpty(chipText)) {
2327 // There may be a space to replace with this chip's new
mindypb5afbc72012-10-03 11:57:42 -07002328 // associated space. Check for it
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002329 int toReplace = end;
2330 while (toReplace >= 0 && toReplace < editable.length()
2331 && editable.charAt(toReplace) == ' ') {
2332 toReplace++;
2333 }
2334 editable.replace(start, toReplace, chipText);
Mindy Pereira62397a52011-10-03 13:46:43 -07002335 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07002336 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002337 }
2338 setCursorVisible(true);
2339 if (wasSelected) {
2340 clearSelectedChip();
2341 }
2342 }
2343
2344 /**
2345 * Handle click events for a chip. When a selected chip receives a click
2346 * event, see if that event was in the delete icon. If so, delete it.
2347 * Otherwise, unselect the chip.
2348 */
Jin Caoa21fd882014-08-10 13:07:11 -07002349 public void onClick(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002350 if (chip.isSelected()) {
Jin Caoa21fd882014-08-10 13:07:11 -07002351 clearSelectedChip();
Mindy Pereiracd611952011-06-01 17:02:20 -07002352 }
Mindy Pereira9159cd22011-05-25 17:06:44 -07002353 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002354
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002355 private boolean chipsPending() {
2356 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2357 }
2358
Mindy Pereira883c4992011-08-04 18:01:30 -07002359 @Override
2360 public void removeTextChangedListener(TextWatcher watcher) {
2361 mTextWatcher = null;
2362 super.removeTextChangedListener(watcher);
2363 }
2364
Jin Caob3b248a2014-04-11 10:43:50 -07002365 private boolean isValidEmailAddress(String input) {
2366 return !TextUtils.isEmpty(input) && mValidator != null &&
2367 mValidator.isValid(input);
2368 }
2369
Mindy Pereira79fb4362011-06-21 14:37:07 -07002370 private class RecipientTextWatcher implements TextWatcher {
Mindy Pereira72a23392012-02-06 10:19:51 -08002371
Mindy Pereira79fb4362011-06-21 14:37:07 -07002372 @Override
2373 public void afterTextChanged(Editable s) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002374 // If the text has been set to null or empty, make sure we remove
2375 // all the spans we applied.
2376 if (TextUtils.isEmpty(s)) {
2377 // Remove all the chips spans.
2378 Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08002379 DrawableRecipientChip[] chips = spannable.getSpans(0, getText().length(),
2380 DrawableRecipientChip.class);
2381 for (DrawableRecipientChip chip : chips) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002382 spannable.removeSpan(chip);
2383 }
2384 if (mMoreChip != null) {
2385 spannable.removeSpan(mMoreChip);
2386 }
Kevin Lin41e93fb2014-02-03 17:35:29 -08002387 clearSelectedChip();
Mindy Pereira32366d42011-07-24 12:39:30 -07002388 return;
2389 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002390 // Get whether there are any recipients pending addition to the
2391 // view. If there are, don't do anything in the text watcher.
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002392 if (chipsPending()) {
Mindy Pereira79fb4362011-06-21 14:37:07 -07002393 return;
2394 }
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002395 // If the user is editing a chip, don't clear it.
mindypf30a4282012-12-03 12:16:33 -08002396 if (mSelectedChip != null) {
2397 if (!isGeneratedContact(mSelectedChip)) {
2398 setCursorVisible(true);
2399 setSelection(getText().length());
2400 clearSelectedChip();
2401 } else {
2402 return;
2403 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002404 }
2405 int length = s.length();
2406 // Make sure there is content there to parse and that it is
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002407 // not just the commit character.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002408 if (length > 1) {
mindypf30a4282012-12-03 12:16:33 -08002409 if (lastCharacterIsCommitCharacter(s)) {
2410 commitByCharacter();
2411 return;
2412 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002413 char last;
Mindy Pereira11a2adb2011-06-28 09:57:43 -07002414 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002415 int len = length() - 1;
2416 if (end != len) {
2417 last = s.charAt(end);
2418 } else {
2419 last = s.charAt(len);
2420 }
mindypf30a4282012-12-03 12:16:33 -08002421 if (last == COMMIT_CHAR_SPACE) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002422 if (!isPhoneQuery()) {
2423 // Check if this is a valid email address. If it is,
2424 // commit it.
2425 String text = getText().toString();
2426 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2427 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2428 tokenStart));
Jin Caob3b248a2014-04-11 10:43:50 -07002429 if (isValidEmailAddress(sub)) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002430 commitByCharacter();
2431 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002432 }
2433 }
2434 }
2435 }
2436
2437 @Override
2438 public void onTextChanged(CharSequence s, int start, int before, int count) {
mindypf30a4282012-12-03 12:16:33 -08002439 // The user deleted some text OR some text was replaced; check to
2440 // see if the insertion point is on a space
Mindy Pereira72a23392012-02-06 10:19:51 -08002441 // following a chip.
mindypf30a4282012-12-03 12:16:33 -08002442 if (before - count == 1) {
Mindy Pereira72a23392012-02-06 10:19:51 -08002443 // If the item deleted is a space, and the thing before the
2444 // space is a chip, delete the entire span.
2445 int selStart = getSelectionStart();
Scott Kennedy194d4272013-03-06 22:06:45 -08002446 DrawableRecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2447 DrawableRecipientChip.class);
Mindy Pereira72a23392012-02-06 10:19:51 -08002448 if (repl.length > 0) {
2449 // There is a chip there! Just remove it.
2450 Editable editable = getText();
2451 // Add the separator token.
2452 int tokenStart = mTokenizer.findTokenStart(editable, selStart);
2453 int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
Mindy Pereira62fce932012-02-16 15:00:30 -08002454 tokenEnd = tokenEnd + 1;
2455 if (tokenEnd > editable.length()) {
2456 tokenEnd = editable.length();
2457 }
2458 editable.delete(tokenStart, tokenEnd);
Mindy Pereira72a23392012-02-06 10:19:51 -08002459 getSpannable().removeSpan(repl[0]);
2460 }
Mindy Pereira4e7d20f2012-07-16 08:09:01 -07002461 } else if (count > before) {
mindyp7e10c862012-11-27 11:13:26 -08002462 if (mSelectedChip != null
2463 && isGeneratedContact(mSelectedChip)) {
2464 if (lastCharacterIsCommitCharacter(s)) {
2465 commitByCharacter();
2466 return;
2467 }
2468 }
Mindy Pereira72a23392012-02-06 10:19:51 -08002469 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002470 }
2471
2472 @Override
2473 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002474 // Do nothing.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002475 }
2476 }
Mindy Pereira18529312011-06-28 11:00:52 -07002477
Alice Yangc1b52582013-03-04 19:54:00 -08002478 public boolean lastCharacterIsCommitCharacter(CharSequence s) {
mindypf30a4282012-12-03 12:16:33 -08002479 char last;
2480 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2481 int len = length() - 1;
2482 if (end != len) {
2483 last = s.charAt(end);
2484 } else {
2485 last = s.charAt(len);
2486 }
2487 return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON;
2488 }
2489
Scott Kennedy194d4272013-03-06 22:06:45 -08002490 public boolean isGeneratedContact(DrawableRecipientChip chip) {
mindypf30a4282012-12-03 12:16:33 -08002491 long contactId = chip.getContactId();
2492 return contactId == RecipientEntry.INVALID_CONTACT
2493 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2494 }
2495
Minh Phame51c7222011-10-12 11:33:26 -07002496 /**
2497 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2498 */
Régis Décamps219cbfb2014-06-04 14:29:54 +02002499 // Visible for testing.
2500 void handlePasteClip(ClipData clip) {
2501 if (clip == null) {
2502 // Do nothing.
2503 return;
2504 }
2505
2506 final ClipDescription clipDesc = clip.getDescription();
2507 boolean containsSupportedType = clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||
2508 clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML);
2509 if (!containsSupportedType) {
2510 return;
2511 }
2512
Minh Phame51c7222011-10-12 11:33:26 -07002513 removeTextChangedListener(mTextWatcher);
2514
Régis Décamps219cbfb2014-06-04 14:29:54 +02002515 final ClipDescription clipDescription = clip.getDescription();
2516 for (int i = 0; i < clip.getItemCount(); i++) {
2517 final String mimeType = clipDescription.getMimeType(i);
2518 final boolean supportedType = ClipDescription.MIMETYPE_TEXT_PLAIN.equals(mimeType) ||
2519 ClipDescription.MIMETYPE_TEXT_HTML.equals(mimeType);
2520 if (!supportedType) {
2521 // Only plain text and html can be pasted.
2522 continue;
2523 }
2524
2525 final CharSequence pastedItem = clip.getItemAt(i).getText();
2526 if (!TextUtils.isEmpty(pastedItem)) {
2527 final Editable editable = getText();
2528 final int start = getSelectionStart();
2529 final int end = getSelectionEnd();
2530 if (start < 0 || end < 1) {
2531 // No selection.
2532 editable.append(pastedItem);
2533 } else if (start == end) {
2534 // Insert at position.
2535 editable.insert(start, pastedItem);
2536 } else {
2537 editable.append(pastedItem, start, end);
Minh Phame51c7222011-10-12 11:33:26 -07002538 }
Régis Décamps219cbfb2014-06-04 14:29:54 +02002539 handlePasteAndReplace();
Minh Phame51c7222011-10-12 11:33:26 -07002540 }
2541 }
2542
2543 mHandler.post(mAddTextWatcher);
2544 }
2545
Mindy Pereira20c9d622011-10-12 13:18:04 -07002546 @Override
2547 public boolean onTextContextMenuItem(int id) {
2548 if (id == android.R.id.paste) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002549 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2550 Context.CLIPBOARD_SERVICE);
Minh Phame51c7222011-10-12 11:33:26 -07002551 handlePasteClip(clipboard.getPrimaryClip());
Mindy Pereira20c9d622011-10-12 13:18:04 -07002552 return true;
2553 }
2554 return super.onTextContextMenuItem(id);
2555 }
2556
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002557 private void handlePasteAndReplace() {
Scott Kennedy194d4272013-03-06 22:06:45 -08002558 ArrayList<DrawableRecipientChip> created = handlePaste();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002559 if (created != null && created.size() > 0) {
2560 // Perform reverse lookups on the pasted contacts.
2561 IndividualReplacementTask replace = new IndividualReplacementTask();
2562 replace.execute(created);
2563 }
2564 }
2565
Mindy Pereira20c9d622011-10-12 13:18:04 -07002566 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002567 /* package */ArrayList<DrawableRecipientChip> handlePaste() {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002568 String text = getText().toString();
2569 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2570 String lastAddress = text.substring(originalTokenStart);
2571 int tokenStart = originalTokenStart;
jli119X0cae8502012-10-18 12:55:47 +08002572 int prevTokenStart = 0;
Scott Kennedy194d4272013-03-06 22:06:45 -08002573 DrawableRecipientChip findChip = null;
2574 ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
Mindy Pereira20c9d622011-10-12 13:18:04 -07002575 if (tokenStart != 0) {
2576 // There are things before this!
jli119X0cae8502012-10-18 12:55:47 +08002577 while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002578 prevTokenStart = tokenStart;
2579 tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2580 findChip = findChip(tokenStart);
Tom Taylorfda01702013-01-14 16:52:25 -08002581 if (tokenStart == originalTokenStart && findChip == null) {
2582 break;
2583 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002584 }
2585 if (tokenStart != originalTokenStart) {
2586 if (findChip != null) {
2587 tokenStart = prevTokenStart;
2588 }
2589 int tokenEnd;
Scott Kennedy194d4272013-03-06 22:06:45 -08002590 DrawableRecipientChip createdChip;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002591 while (tokenStart < originalTokenStart) {
mindypb5afbc72012-10-03 11:57:42 -07002592 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2593 tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002594 commitChip(tokenStart, tokenEnd, getText());
2595 createdChip = findChip(tokenStart);
Mindy Pereirac52ea8e2012-06-04 15:24:55 -07002596 if (createdChip == null) {
2597 break;
2598 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002599 // +1 for the space at the end.
2600 tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002601 created.add(createdChip);
Mindy Pereira20c9d622011-10-12 13:18:04 -07002602 }
2603 }
2604 }
2605 // Take a look at the last token. If the token has been completed with a
2606 // commit character, create a chip.
2607 if (isCompletedToken(lastAddress)) {
2608 Editable editable = getText();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002609 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2610 commitChip(tokenStart, editable.length(), editable);
2611 created.add(findChip(tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002612 }
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002613 return created;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002614 }
2615
2616 // Visible for testing.
2617 /* package */int movePastTerminators(int tokenEnd) {
2618 if (tokenEnd >= length()) {
2619 return tokenEnd;
2620 }
2621 char atEnd = getText().toString().charAt(tokenEnd);
2622 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2623 tokenEnd++;
2624 }
2625 // This token had not only an end token character, but also a space
2626 // separating it from the next token.
2627 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2628 tokenEnd++;
2629 }
2630 return tokenEnd;
2631 }
2632
Mindy Pereira18529312011-06-28 11:00:52 -07002633 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
Scott Kennedy194d4272013-03-06 22:06:45 -08002634 private DrawableRecipientChip createFreeChip(RecipientEntry entry) {
Mindy Pereira18529312011-06-28 11:00:52 -07002635 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002636 if (mNoChips) {
2637 return null;
2638 }
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002639 return constructChipSpan(entry, false);
Mindy Pereira18529312011-06-28 11:00:52 -07002640 } catch (NullPointerException e) {
2641 Log.e(TAG, e.getMessage(), e);
2642 return null;
2643 }
2644 }
2645
2646 @Override
Scott Kennedy78f38a02013-02-27 11:21:40 -08002647 protected void onPreExecute() {
2648 // Ensure everything is in chip-form already, so we don't have text that slowly gets
2649 // replaced
Scott Kennedy194d4272013-03-06 22:06:45 -08002650 final List<DrawableRecipientChip> originalRecipients =
2651 new ArrayList<DrawableRecipientChip>();
2652 final DrawableRecipientChip[] existingChips = getSortedRecipients();
Scott Kennedy78f38a02013-02-27 11:21:40 -08002653 for (int i = 0; i < existingChips.length; i++) {
2654 originalRecipients.add(existingChips[i]);
2655 }
2656 if (mRemovedSpans != null) {
2657 originalRecipients.addAll(mRemovedSpans);
2658 }
2659
Scott Kennedy194d4272013-03-06 22:06:45 -08002660 final List<DrawableRecipientChip> replacements =
2661 new ArrayList<DrawableRecipientChip>(originalRecipients.size());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002662
Scott Kennedy194d4272013-03-06 22:06:45 -08002663 for (final DrawableRecipientChip chip : originalRecipients) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002664 if (RecipientEntry.isCreatedRecipient(chip.getEntry().getContactId())
2665 && getSpannable().getSpanStart(chip) != -1) {
2666 replacements.add(createFreeChip(chip.getEntry()));
2667 } else {
2668 replacements.add(null);
2669 }
2670 }
2671
2672 processReplacements(originalRecipients, replacements);
2673 }
2674
2675 @Override
Mindy Pereira18529312011-06-28 11:00:52 -07002676 protected Void doInBackground(Void... params) {
2677 if (mIndividualReplacements != null) {
2678 mIndividualReplacements.cancel(true);
2679 }
2680 // For each chip in the list, look up the matching contact.
2681 // If there is a match, replace that chip with the matching
2682 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002683 final ArrayList<DrawableRecipientChip> recipients =
2684 new ArrayList<DrawableRecipientChip>();
2685 DrawableRecipientChip[] existingChips = getSortedRecipients();
Mindy Pereira18529312011-06-28 11:00:52 -07002686 for (int i = 0; i < existingChips.length; i++) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002687 recipients.add(existingChips[i]);
Mindy Pereira18529312011-06-28 11:00:52 -07002688 }
2689 if (mRemovedSpans != null) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002690 recipients.addAll(mRemovedSpans);
Mindy Pereira18529312011-06-28 11:00:52 -07002691 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002692 ArrayList<String> addresses = new ArrayList<String>();
Scott Kennedy194d4272013-03-06 22:06:45 -08002693 DrawableRecipientChip chip;
Scott Kennedy78f38a02013-02-27 11:21:40 -08002694 for (int i = 0; i < recipients.size(); i++) {
2695 chip = recipients.get(i);
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002696 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002697 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002698 }
Mindy Pereira18529312011-06-28 11:00:52 -07002699 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002700 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002701 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002702 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002703 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002704 final ArrayList<DrawableRecipientChip> replacements =
2705 new ArrayList<DrawableRecipientChip>();
2706 for (final DrawableRecipientChip temp : recipients) {
mindyp16923ee2012-12-10 11:58:29 -08002707 RecipientEntry entry = null;
Alice Yangf0579ee2013-03-04 14:10:21 -08002708 if (temp != null && RecipientEntry.isCreatedRecipient(
2709 temp.getEntry().getContactId())
mindyp16923ee2012-12-10 11:58:29 -08002710 && getSpannable().getSpanStart(temp) != -1) {
2711 // Replace this.
2712 entry = createValidatedEntry(
2713 entries.get(tokenizeAddress(temp.getEntry()
2714 .getDestination())));
2715 }
2716 if (entry != null) {
2717 replacements.add(createFreeChip(entry));
2718 } else {
2719 replacements.add(null);
2720 }
Mindy Pereira18529312011-06-28 11:00:52 -07002721 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002722 processReplacements(recipients, replacements);
Mindy Pereira18529312011-06-28 11:00:52 -07002723 }
Scott Kennedy94fa3012013-02-15 18:22:05 -08002724
2725 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002726 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002727 final List<DrawableRecipientChip> replacements =
2728 new ArrayList<DrawableRecipientChip>(unfoundAddresses.size());
Scott Kennedy94fa3012013-02-15 18:22:05 -08002729
Scott Kennedy194d4272013-03-06 22:06:45 -08002730 for (final DrawableRecipientChip temp : recipients) {
Alice Yangad8781e2013-03-04 14:45:38 -08002731 if (temp != null && RecipientEntry.isCreatedRecipient(
2732 temp.getEntry().getContactId())
Scott Kennedy94fa3012013-02-15 18:22:05 -08002733 && getSpannable().getSpanStart(temp) != -1) {
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002734 if (unfoundAddresses.contains(
2735 temp.getEntry().getDestination())) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002736 replacements.add(createFreeChip(temp.getEntry()));
2737 } else {
2738 replacements.add(null);
2739 }
2740 } else {
2741 replacements.add(null);
2742 }
2743 }
2744
Scott Kennedy78f38a02013-02-27 11:21:40 -08002745 processReplacements(recipients, replacements);
Scott Kennedy94fa3012013-02-15 18:22:05 -08002746 }
mindyp16923ee2012-12-10 11:58:29 -08002747 });
Mindy Pereira18529312011-06-28 11:00:52 -07002748 return null;
2749 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002750
Scott Kennedy194d4272013-03-06 22:06:45 -08002751 private void processReplacements(final List<DrawableRecipientChip> recipients,
2752 final List<DrawableRecipientChip> replacements) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002753 if (replacements != null && replacements.size() > 0) {
2754 final Runnable runnable = new Runnable() {
2755 @Override
2756 public void run() {
Scott Kennedy0e128962013-04-11 10:52:08 -07002757 final Editable text = new SpannableStringBuilder(getText());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002758 int i = 0;
Scott Kennedy0e128962013-04-11 10:52:08 -07002759 for (final DrawableRecipientChip chip : recipients) {
2760 final DrawableRecipientChip replacement = replacements.get(i);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002761 if (replacement != null) {
2762 final RecipientEntry oldEntry = chip.getEntry();
2763 final RecipientEntry newEntry = replacement.getEntry();
2764 final boolean isBetter =
2765 RecipientAlternatesAdapter.getBetterRecipient(
2766 oldEntry, newEntry) == newEntry;
2767
2768 if (isBetter) {
2769 // Find the location of the chip in the text currently shown.
Scott Kennedy0e128962013-04-11 10:52:08 -07002770 final int start = text.getSpanStart(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002771 if (start != -1) {
2772 // Replacing the entirety of what the chip represented,
2773 // including the extra space dividing it from other chips.
Paul Westbrookb023f692013-04-22 12:27:35 -07002774 final int end =
2775 Math.min(text.getSpanEnd(chip) + 1, text.length());
Scott Kennedy0e128962013-04-11 10:52:08 -07002776 text.removeSpan(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002777 // Make sure we always have just 1 space at the end to
2778 // separate this chip from the next chip.
Scott Kennedy0e128962013-04-11 10:52:08 -07002779 final SpannableString displayText =
Scott Kennedy78f38a02013-02-27 11:21:40 -08002780 new SpannableString(createAddressText(
Scott Kennedy0e128962013-04-11 10:52:08 -07002781 replacement.getEntry()).trim() + " ");
Scott Kennedy78f38a02013-02-27 11:21:40 -08002782 displayText.setSpan(replacement, 0,
2783 displayText.length() - 1,
2784 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2785 // Replace the old text we found with with the new display
2786 // text, which now may also contain the display name of the
2787 // recipient.
Scott Kennedy0e128962013-04-11 10:52:08 -07002788 text.replace(start, end, displayText);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002789 replacement.setOriginalText(displayText.toString());
2790 replacements.set(i, null);
2791
2792 recipients.set(i, replacement);
2793 }
2794 }
2795 }
2796 i++;
2797 }
Scott Kennedy0e128962013-04-11 10:52:08 -07002798 setText(text);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002799 }
2800 };
2801
2802 if (Looper.myLooper() == Looper.getMainLooper()) {
2803 runnable.run();
2804 } else {
2805 mHandler.post(runnable);
2806 }
2807 }
2808 }
Mindy Pereira18529312011-06-28 11:00:52 -07002809 }
2810
Scott Kennedy78f38a02013-02-27 11:21:40 -08002811 private class IndividualReplacementTask
Scott Kennedy194d4272013-03-06 22:06:45 -08002812 extends AsyncTask<ArrayList<DrawableRecipientChip>, Void, Void> {
Mindy Pereira18529312011-06-28 11:00:52 -07002813 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08002814 protected Void doInBackground(ArrayList<DrawableRecipientChip>... params) {
Mindy Pereira18529312011-06-28 11:00:52 -07002815 // For each chip in the list, look up the matching contact.
2816 // If there is a match, replace that chip with the matching
2817 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002818 final ArrayList<DrawableRecipientChip> originalRecipients = params[0];
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002819 ArrayList<String> addresses = new ArrayList<String>();
Scott Kennedy194d4272013-03-06 22:06:45 -08002820 DrawableRecipientChip chip;
Mindy Pereira18529312011-06-28 11:00:52 -07002821 for (int i = 0; i < originalRecipients.size(); i++) {
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002822 chip = originalRecipients.get(i);
2823 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002824 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002825 }
Mindy Pereira18529312011-06-28 11:00:52 -07002826 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002827 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002828 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002829
2830 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002831 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002832 for (final DrawableRecipientChip temp : originalRecipients) {
mindyp16923ee2012-12-10 11:58:29 -08002833 if (RecipientEntry.isCreatedRecipient(temp.getEntry()
2834 .getContactId())
2835 && getSpannable().getSpanStart(temp) != -1) {
2836 // Replace this.
Alon Albert76f1f2d2013-07-14 15:32:49 +03002837 final RecipientEntry entry = createValidatedEntry(entries
mindyp16923ee2012-12-10 11:58:29 -08002838 .get(tokenizeAddress(temp.getEntry().getDestination())
2839 .toLowerCase()));
Alon Albert76f1f2d2013-07-14 15:32:49 +03002840 if (entry != null) {
mindyp16923ee2012-12-10 11:58:29 -08002841 mHandler.post(new Runnable() {
2842 @Override
2843 public void run() {
Alon Albert76f1f2d2013-07-14 15:32:49 +03002844 replaceChip(temp, entry);
mindyp16923ee2012-12-10 11:58:29 -08002845 }
2846 });
2847 }
2848 }
Mindy Pereira18529312011-06-28 11:00:52 -07002849 }
mindyp16923ee2012-12-10 11:58:29 -08002850 }
2851
Scott Kennedy94fa3012013-02-15 18:22:05 -08002852 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002853 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002854 // No action required
2855 }
mindyp16923ee2012-12-10 11:58:29 -08002856 });
Mindy Pereira18529312011-06-28 11:00:52 -07002857 return null;
2858 }
2859 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002860
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002861
2862 /**
2863 * MoreImageSpan is a simple class created for tracking the existence of a
2864 * more chip across activity restarts/
2865 */
Jin Cao6c2a0162014-08-17 15:00:50 -07002866 private class MoreImageSpan extends ReplacementDrawableSpan {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002867 public MoreImageSpan(Drawable b) {
2868 super(b);
Jin Cao6c2a0162014-08-17 15:00:50 -07002869 setExtraMargin(mLineSpacingExtra);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002870 }
2871 }
2872
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002873 @Override
2874 public boolean onDown(MotionEvent e) {
2875 return false;
2876 }
2877
2878 @Override
2879 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2880 // Do nothing.
2881 return false;
2882 }
2883
2884 @Override
2885 public void onLongPress(MotionEvent event) {
2886 if (mSelectedChip != null) {
2887 return;
2888 }
2889 float x = event.getX();
2890 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07002891 final int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08002892 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002893 if (currentChip != null) {
Minh Phame51c7222011-10-12 11:33:26 -07002894 if (mDragEnabled) {
2895 // Start drag-and-drop for the selected chip.
2896 startDrag(currentChip);
2897 } else {
2898 // Copy the selected chip email address.
2899 showCopyDialog(currentChip.getEntry().getDestination());
2900 }
2901 }
2902 }
2903
Scott Kennedy1650ef62013-08-02 21:56:47 -07002904 // The following methods are used to provide some functionality on older versions of Android
2905 // These methods were copied out of JB MR2's TextView
2906 /////////////////////////////////////////////////
2907 private int supportGetOffsetForPosition(float x, float y) {
2908 if (getLayout() == null) return -1;
2909 final int line = supportGetLineAtCoordinate(y);
2910 final int offset = supportGetOffsetAtCoordinate(line, x);
2911 return offset;
2912 }
2913
2914 private float supportConvertToLocalHorizontalCoordinate(float x) {
2915 x -= getTotalPaddingLeft();
2916 // Clamp the position to inside of the view.
2917 x = Math.max(0.0f, x);
2918 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
2919 x += getScrollX();
2920 return x;
2921 }
2922
2923 private int supportGetLineAtCoordinate(float y) {
2924 y -= getTotalPaddingLeft();
2925 // Clamp the position to inside of the view.
2926 y = Math.max(0.0f, y);
2927 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
2928 y += getScrollY();
2929 return getLayout().getLineForVertical((int) y);
2930 }
2931
2932 private int supportGetOffsetAtCoordinate(int line, float x) {
2933 x = supportConvertToLocalHorizontalCoordinate(x);
2934 return getLayout().getOffsetForHorizontal(line, x);
2935 }
2936 /////////////////////////////////////////////////
2937
Minh Phame51c7222011-10-12 11:33:26 -07002938 /**
2939 * Enables drag-and-drop for chips.
2940 */
2941 public void enableDrag() {
2942 mDragEnabled = true;
2943 }
2944
2945 /**
2946 * Starts drag-and-drop for the selected chip.
2947 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002948 private void startDrag(DrawableRecipientChip currentChip) {
Minh Phame51c7222011-10-12 11:33:26 -07002949 String address = currentChip.getEntry().getDestination();
2950 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2951
2952 // Start drag mode.
2953 startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2954
2955 // Remove the current chip, so drag-and-drop will result in a move.
2956 // TODO (phamm): consider readd this chip if it's dropped outside a target.
2957 removeChip(currentChip);
2958 }
2959
2960 /**
2961 * Handles drag event.
2962 */
2963 @Override
2964 public boolean onDragEvent(DragEvent event) {
2965 switch (event.getAction()) {
2966 case DragEvent.ACTION_DRAG_STARTED:
2967 // Only handle plain text drag and drop.
2968 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2969 case DragEvent.ACTION_DRAG_ENTERED:
2970 requestFocus();
2971 return true;
2972 case DragEvent.ACTION_DROP:
2973 handlePasteClip(event.getClipData());
2974 return true;
2975 }
2976 return false;
2977 }
2978
2979 /**
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07002980 * Drag shadow for a {@link DrawableRecipientChip}.
Minh Phame51c7222011-10-12 11:33:26 -07002981 */
2982 private final class RecipientChipShadow extends DragShadowBuilder {
Scott Kennedy194d4272013-03-06 22:06:45 -08002983 private final DrawableRecipientChip mChip;
Minh Phame51c7222011-10-12 11:33:26 -07002984
Scott Kennedy194d4272013-03-06 22:06:45 -08002985 public RecipientChipShadow(DrawableRecipientChip chip) {
Minh Phame51c7222011-10-12 11:33:26 -07002986 mChip = chip;
2987 }
2988
2989 @Override
2990 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
mindypf30a4282012-12-03 12:16:33 -08002991 Rect rect = mChip.getBounds();
Minh Phame51c7222011-10-12 11:33:26 -07002992 shadowSize.set(rect.width(), rect.height());
2993 shadowTouchPoint.set(rect.centerX(), rect.centerY());
2994 }
2995
2996 @Override
2997 public void onDrawShadow(Canvas canvas) {
mindypf30a4282012-12-03 12:16:33 -08002998 mChip.draw(canvas);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002999 }
3000 }
3001
3002 private void showCopyDialog(final String address) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07003003 if (!mAttachedToWindow) {
3004 return;
3005 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003006 mCopyAddress = address;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003007 mCopyDialog.setTitle(address);
Mindy Pereira76e62e32012-02-03 15:38:50 -08003008 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003009 mCopyDialog.setCancelable(true);
3010 mCopyDialog.setCanceledOnTouchOutside(true);
Tom Taylor80f4abf2012-04-06 13:37:20 -07003011 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
3012 button.setOnClickListener(this);
3013 int btnTitleId;
Tom Taylorc7a87f02012-05-03 15:21:08 -07003014 if (isPhoneQuery()) {
Tom Taylor80f4abf2012-04-06 13:37:20 -07003015 btnTitleId = R.string.copy_number;
3016 } else {
3017 btnTitleId = R.string.copy_email;
3018 }
3019 String buttonTitle = getContext().getResources().getString(btnTitleId);
3020 button.setText(buttonTitle);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003021 mCopyDialog.setOnDismissListener(this);
3022 mCopyDialog.show();
3023 }
3024
3025 @Override
3026 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
3027 // Do nothing.
3028 return false;
3029 }
3030
3031 @Override
3032 public void onShowPress(MotionEvent e) {
3033 // Do nothing.
3034 }
3035
3036 @Override
3037 public boolean onSingleTapUp(MotionEvent e) {
3038 // Do nothing.
3039 return false;
3040 }
3041
3042 @Override
3043 public void onDismiss(DialogInterface dialog) {
3044 mCopyAddress = null;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003045 }
3046
3047 @Override
3048 public void onClick(View v) {
3049 // Copy this to the clipboard.
3050 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
3051 Context.CLIPBOARD_SERVICE);
3052 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
3053 mCopyDialog.dismiss();
3054 }
Tom Taylorc7a87f02012-05-03 15:21:08 -07003055
3056 protected boolean isPhoneQuery() {
Mindy Pereiraca522712012-06-28 11:47:48 -07003057 return getAdapter() != null
Scott Kennedy858e0942013-10-10 11:50:01 -07003058 && getAdapter().getQueryType() == BaseRecipientAdapter.QUERY_TYPE_PHONE;
3059 }
3060
3061 @Override
3062 public BaseRecipientAdapter getAdapter() {
3063 return (BaseRecipientAdapter) super.getAdapter();
Tom Taylorc7a87f02012-05-03 15:21:08 -07003064 }
Kaikai Wang972def72014-05-27 21:59:52 -07003065
3066 /**
3067 * Append a new {@link RecipientEntry} to the end of the recipient chips, leaving any
3068 * unfinished text at the end.
3069 */
3070 public void appendRecipientEntry(final RecipientEntry entry) {
3071 clearComposingText();
3072
3073 final Editable editable = getText();
3074 int chipInsertionPoint = 0;
3075
3076 // Find the end of last chip and see if there's any unchipified text.
3077 final DrawableRecipientChip[] recips = getSortedRecipients();
3078 if (recips != null && recips.length > 0) {
3079 final DrawableRecipientChip last = recips[recips.length - 1];
3080 // The chip will be inserted at the end of last chip + 1. All the unfinished text after
3081 // the insertion point will be kept untouched.
3082 chipInsertionPoint = editable.getSpanEnd(last) + 1;
3083 }
3084
3085 final CharSequence chip = createChip(entry, false);
3086 if (chip != null) {
3087 editable.insert(chipInsertionPoint, chip);
3088 }
3089 }
Jin Cao35e82d42014-06-02 17:21:21 -07003090
Kaikai Wangcd980d92014-06-09 21:08:13 -07003091 /**
3092 * Remove all chips matching the given RecipientEntry.
3093 */
3094 public void removeRecipientEntry(final RecipientEntry entry) {
3095 final DrawableRecipientChip[] recips = getText()
3096 .getSpans(0, getText().length(), DrawableRecipientChip.class);
3097
3098 for (final DrawableRecipientChip recipient : recips) {
3099 final RecipientEntry existingEntry = recipient.getEntry();
3100 if (existingEntry != null && existingEntry.isValid() &&
3101 existingEntry.isSamePerson(entry)) {
3102 removeChip(recipient);
3103 }
3104 }
3105 }
3106
Jin Cao4de6a532014-08-08 11:34:10 -07003107 public void setAlternatePopupAnchor(View v) {
3108 mAlternatePopupAnchor = v;
3109 }
3110
Jin Cao35e82d42014-06-02 17:21:21 -07003111 private static class ChipBitmapContainer {
3112 Bitmap bitmap;
3113 // information used for positioning the loaded icon
3114 boolean loadIcon = true;
3115 float left;
3116 float top;
3117 float right;
3118 float bottom;
3119 }
Mindy Pereira18529312011-06-28 11:00:52 -07003120}