blob: dd83360c9a7f07bb3118fcbb5d90614b72171c10 [file] [log] [blame]
Mindy Pereira9159cd22011-05-25 17:06:44 -07001/*
Scott Kennedy194d4272013-03-06 22:06:45 -08002
Mindy Pereira9159cd22011-05-25 17:06:44 -07003 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.ex.chips;
19
Jin Caoffc01112014-12-15 16:24:37 -080020import android.annotation.TargetApi;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070021import android.app.Dialog;
22import android.content.ClipData;
Mindy Pereira20c9d622011-10-12 13:18:04 -070023import android.content.ClipDescription;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070024import android.content.ClipboardManager;
Mindy Pereira9159cd22011-05-25 17:06:44 -070025import android.content.Context;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070026import android.content.DialogInterface;
27import android.content.DialogInterface.OnDismissListener;
Mindy Pereira52c441e2011-12-15 13:35:37 -080028import android.content.res.Resources;
Mindy Pereira22faaa62011-12-16 14:30:34 -080029import android.content.res.TypedArray;
Mindy Pereiracd611952011-06-01 17:02:20 -070030import android.graphics.Bitmap;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070031import android.graphics.BitmapFactory;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070032import android.graphics.BitmapShader;
Mindy Pereiracd611952011-06-01 17:02:20 -070033import android.graphics.Canvas;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070034import android.graphics.Color;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070035import android.graphics.Matrix;
Kevin Linb10d1c62014-01-24 12:45:00 -080036import android.graphics.Paint;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070037import android.graphics.Paint.Style;
Minh Phame51c7222011-10-12 11:33:26 -070038import android.graphics.Point;
Mindy Pereiracd611952011-06-01 17:02:20 -070039import android.graphics.Rect;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -070040import android.graphics.RectF;
Scott Kennedyb232e5c2014-07-09 16:29:35 -070041import android.graphics.Shader.TileMode;
Mindy Pereiracd611952011-06-01 17:02:20 -070042import android.graphics.drawable.BitmapDrawable;
Mindy Pereira9159cd22011-05-25 17:06:44 -070043import android.graphics.drawable.Drawable;
Jin Cao4db8ccc2014-07-30 10:11:07 -070044import android.graphics.drawable.StateListDrawable;
Mindy Pereira18529312011-06-28 11:00:52 -070045import android.os.AsyncTask;
Scott Kennedy1650ef62013-08-02 21:56:47 -070046import android.os.Build;
Mindy Pereira007a76b2011-06-14 11:39:36 -070047import android.os.Handler;
Scott Kennedy78f38a02013-02-27 11:21:40 -080048import android.os.Looper;
Mindy Pereira007a76b2011-06-14 11:39:36 -070049import android.os.Message;
Mindy Pereiradc04cd72011-09-16 15:42:09 -070050import android.os.Parcelable;
Jin Caoffc01112014-12-15 16:24:37 -080051import android.support.annotation.NonNull;
Mindy Pereira9159cd22011-05-25 17:06:44 -070052import android.text.Editable;
Gilles Debunne61b48cc2011-08-16 14:03:00 -070053import android.text.InputType;
Mindy Pereiracd611952011-06-01 17:02:20 -070054import android.text.Layout;
55import android.text.Spannable;
56import android.text.SpannableString;
Scott Kennedy0e128962013-04-11 10:52:08 -070057import android.text.SpannableStringBuilder;
Mindy Pereiracd611952011-06-01 17:02:20 -070058import android.text.Spanned;
59import android.text.TextPaint;
60import android.text.TextUtils;
Mindy Pereirab88ee452011-06-02 11:07:43 -070061import android.text.TextWatcher;
Mindy Pereiracd611952011-06-01 17:02:20 -070062import android.text.method.QwertyKeyListener;
Mindy Pereira3bb52162011-07-01 14:52:22 -070063import android.text.util.Rfc822Token;
64import android.text.util.Rfc822Tokenizer;
Mindy Pereira9159cd22011-05-25 17:06:44 -070065import android.util.AttributeSet;
Mindy Pereiracd611952011-06-01 17:02:20 -070066import android.util.Log;
Mindy Pereirafd68ea62011-06-02 10:40:19 -070067import android.view.ActionMode;
Andy Stadleraa2afff2011-08-04 16:22:47 -070068import android.view.ActionMode.Callback;
Minh Phame51c7222011-10-12 11:33:26 -070069import android.view.DragEvent;
Mindy Pereira1d1ec852011-08-09 16:49:33 -070070import android.view.GestureDetector;
Mindy Pereiracd611952011-06-01 17:02:20 -070071import android.view.KeyEvent;
Mindy Pereira750e6e52011-07-25 11:51:30 -070072import android.view.LayoutInflater;
Mindy Pereirafd68ea62011-06-02 10:40:19 -070073import android.view.Menu;
74import android.view.MenuItem;
Mindy Pereiracd611952011-06-01 17:02:20 -070075import android.view.MotionEvent;
76import android.view.View;
Gilles Debunne61b48cc2011-08-16 14:03:00 -070077import android.view.View.OnClickListener;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -070078import android.view.ViewParent;
Jin Cao04f06ea2014-09-22 14:58:28 -070079import android.view.accessibility.AccessibilityEvent;
80import android.view.accessibility.AccessibilityManager;
Mindy Pereira93364a62012-04-27 14:17:22 -070081import android.view.inputmethod.EditorInfo;
82import android.view.inputmethod.InputConnection;
Mindy Pereiracd611952011-06-01 17:02:20 -070083import android.widget.AdapterView;
84import android.widget.AdapterView.OnItemClickListener;
Tom Taylor80f4abf2012-04-06 13:37:20 -070085import android.widget.Button;
mindyp093ecdd2012-12-14 10:40:51 -080086import android.widget.Filterable;
Mindy Pereira95a69252011-06-17 15:02:03 -070087import android.widget.ListAdapter;
Mindy Pereiracd611952011-06-01 17:02:20 -070088import android.widget.ListPopupWindow;
Mindy Pereira007a76b2011-06-14 11:39:36 -070089import android.widget.ListView;
Mindy Pereira9159cd22011-05-25 17:06:44 -070090import android.widget.MultiAutoCompleteTextView;
Jin Cao939f5f12014-11-10 11:06:12 -080091import android.widget.PopupWindow;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -070092import android.widget.ScrollView;
Mindy Pereira750e6e52011-07-25 11:51:30 -070093import android.widget.TextView;
Daisuke Miyakawa7537f842011-05-31 15:47:25 -070094
mindyp16923ee2012-12-10 11:58:29 -080095import com.android.ex.chips.RecipientAlternatesAdapter.RecipientMatchCallback;
Scott Kennedy194d4272013-03-06 22:06:45 -080096import com.android.ex.chips.recipientchip.DrawableRecipientChip;
97import com.android.ex.chips.recipientchip.InvisibleRecipientChip;
Jin Cao6c2a0162014-08-17 15:00:50 -070098import com.android.ex.chips.recipientchip.ReplacementDrawableSpan;
Scott Kennedy194d4272013-03-06 22:06:45 -080099import com.android.ex.chips.recipientchip.VisibleRecipientChip;
Mindy Pereiracd611952011-06-01 17:02:20 -0700100
Alon Albert76f1f2d2013-07-14 15:32:49 +0300101import java.util.ArrayList;
102import java.util.Arrays;
Alon Albert76f1f2d2013-07-14 15:32:49 +0300103import java.util.Collections;
104import java.util.Comparator;
Alon Albert76f1f2d2013-07-14 15:32:49 +0300105import java.util.List;
106import java.util.Map;
107import java.util.Set;
108import java.util.regex.Matcher;
109import java.util.regex.Pattern;
110
Mindy Pereira9159cd22011-05-25 17:06:44 -0700111/**
112 * RecipientEditTextView is an auto complete text view for use with applications
113 * that use the new Chips UI for addressing a message to recipients.
114 */
Mindy Pereira95a69252011-06-17 15:02:03 -0700115public class RecipientEditTextView extends MultiAutoCompleteTextView implements
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700116 OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
Mindy Pereiraecee50c2011-09-09 16:30:20 -0700117 GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
Jin Cao4db8ccc2014-07-30 10:11:07 -0700118 TextView.OnEditorActionListener, DropdownChipLayouter.ChipDeleteListener {
Jin Caoa21fd882014-08-10 13:07:11 -0700119 private static final String TAG = "RecipientEditTextView";
Mindy Pereiracd611952011-06-01 17:02:20 -0700120
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700121 private static final char COMMIT_CHAR_COMMA = ',';
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700122 private static final char COMMIT_CHAR_SEMICOLON = ';';
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700123 private static final char COMMIT_CHAR_SPACE = ' ';
Scott Kennedy03e9e982013-03-04 13:26:22 -0800124 private static final String SEPARATOR = String.valueOf(COMMIT_CHAR_COMMA)
125 + String.valueOf(COMMIT_CHAR_SPACE);
126
Jin Caoa21fd882014-08-10 13:07:11 -0700127 // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
128 // parens, so numbers such as "1 (425) 222-2342" match.
129 private static final Pattern PHONE_PATTERN
130 = Pattern.compile( // sdd = space, dot, or dash
131 "(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
132 + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?" // 1(<digits>)<sdd>*
133 + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
Mindy Pereiracd611952011-06-01 17:02:20 -0700134
Scott Kennedyf11483a2014-04-18 13:36:27 -0700135 private static final int DISMISS = "dismiss".hashCode();
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700136 private static final long DISMISS_DELAY = 300;
137
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700138 // TODO: get correct number/ algorithm from with UX.
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700139 // Visible for testing.
140 /*package*/ static final int CHIP_LIMIT = 2;
141
142 private static final int MAX_CHIPS_PARSED = 50;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700143
Kaikai Wangcb11fce2014-12-09 14:20:57 -0800144 private int mSelectedChipTextColor;
145 private int mUnselectedChipTextColor;
146 private int mSelectedChipBackgroundColor;
147 private int mUnselectedChipBackgroundColor;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700148
Jin Caofcaf9862014-10-08 12:15:10 -0700149 // Work variables to avoid re-allocation on every typed character.
150 private final Rect mRect = new Rect();
151 private final int[] mCoords = new int[2];
152
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700153 // Resources for displaying chips.
Mindy Pereiracd611952011-06-01 17:02:20 -0700154 private Drawable mChipBackground = null;
Mindy Pereiracd611952011-06-01 17:02:20 -0700155 private Drawable mChipDelete = null;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700156 private Drawable mInvalidChipBackground;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700157
Jin Caoa21fd882014-08-10 13:07:11 -0700158 // Possible attr overrides
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700159 private float mChipHeight;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700160 private float mChipFontSize;
Mindy Pereiraffd270a2012-05-23 16:11:47 -0700161 private float mLineSpacingExtra;
Jin Cao58d541d2014-07-29 16:23:03 -0700162 private int mChipTextStartPadding;
163 private int mChipTextEndPadding;
Scott Kennedy15259d52014-07-09 17:28:47 -0700164 private final int mTextHeight;
Jin Caoa21fd882014-08-10 13:07:11 -0700165 private boolean mDisableDelete;
166 private int mMaxLines;
Mindy Pereiracd611952011-06-01 17:02:20 -0700167
Kevin Linb10d1c62014-01-24 12:45:00 -0800168 /**
169 * Enumerator for avatar position. See attr.xml for more details.
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800170 * 0 for end, 1 for start.
Kevin Linb10d1c62014-01-24 12:45:00 -0800171 */
172 private int mAvatarPosition;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800173 private static final int AVATAR_POSITION_END = 0;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800174 private static final int AVATAR_POSITION_START = 1;
Kevin Linb10d1c62014-01-24 12:45:00 -0800175
Jin Cao809c5952014-08-08 12:28:17 -0700176 private Paint mWorkPaint = new Paint();
177
Mindy Pereiracd611952011-06-01 17:02:20 -0700178 private Tokenizer mTokenizer;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700179 private Validator mValidator;
Jin Caoa21fd882014-08-10 13:07:11 -0700180 private Handler mHandler;
181 private TextWatcher mTextWatcher;
182 private DropdownChipLayouter mDropdownChipLayouter;
183
Jin Cao93d69f42014-10-07 12:27:49 -0700184 private View mDropdownAnchor = this;
Jin Caoa21fd882014-08-10 13:07:11 -0700185 private ListPopupWindow mAlternatesPopup;
186 private ListPopupWindow mAddressPopup;
187 private View mAlternatePopupAnchor;
188 private OnItemClickListener mAlternatesListener;
Mindy Pereiracd611952011-06-01 17:02:20 -0700189
Scott Kennedy194d4272013-03-06 22:06:45 -0800190 private DrawableRecipientChip mSelectedChip;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700191 private Bitmap mDefaultContactPhoto;
Jin Cao6c2a0162014-08-17 15:00:50 -0700192 private ReplacementDrawableSpan mMoreChip;
Mindy Pereira750e6e52011-07-25 11:51:30 -0700193 private TextView mMoreItem;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700194
Jin Cao04f06ea2014-09-22 14:58:28 -0700195 private boolean mIsAccessibilityOn;
Jin Caob1aeb7b2014-09-01 23:48:05 -0700196 private int mCurrentSuggestionCount;
197
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800198 // VisibleForTesting
199 final ArrayList<String> mPendingChips = new ArrayList<String>();
Mindy Pereiraf97eb412011-06-24 11:26:20 -0700200
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700201 private int mPendingChipsCount = 0;
Jin Caoa21fd882014-08-10 13:07:11 -0700202 private int mCheckedItem;
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700203 private boolean mNoChips = false;
Jin Caoa21fd882014-08-10 13:07:11 -0700204 private boolean mShouldShrink = true;
Scott Kennedy654c9672014-12-12 14:24:17 -0800205 private boolean mRequiresShrinkWhenNotGone = false;
Jin Cao4de6a532014-08-08 11:34:10 -0700206
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800207 // VisibleForTesting
Scott Kennedy194d4272013-03-06 22:06:45 -0800208 ArrayList<DrawableRecipientChip> mTemporaryRecipients;
Mindy Pereira18529312011-06-28 11:00:52 -0700209
Scott Kennedy194d4272013-03-06 22:06:45 -0800210 private ArrayList<DrawableRecipientChip> mRemovedSpans;
Mindy Pereira3bb52162011-07-01 14:52:22 -0700211
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700212 // Chip copy fields.
213 private GestureDetector mGestureDetector;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700214 private Dialog mCopyDialog;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700215 private String mCopyAddress;
216
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700217 // Obtain the enclosing scroll view, if it exists, so that the view can be
218 // scrolled to show the last line of chips content.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700219 private ScrollView mScrollView;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700220 private boolean mTriedGettingScrollView;
Minh Phame51c7222011-10-12 11:33:26 -0700221 private boolean mDragEnabled = false;
222
Jin Caoa21fd882014-08-10 13:07:11 -0700223 private boolean mAttachedToWindow;
Tom Taylor4491a062012-11-15 13:57:41 -0800224
Mindy Pereira79fb4362011-06-21 14:37:07 -0700225 private final Runnable mAddTextWatcher = new Runnable() {
226 @Override
227 public void run() {
228 if (mTextWatcher == null) {
229 mTextWatcher = new RecipientTextWatcher();
230 addTextChangedListener(mTextWatcher);
231 }
232 }
233 };
234
Mindy Pereira18529312011-06-28 11:00:52 -0700235 private IndividualReplacementTask mIndividualReplacements;
236
Mindy Pereira2cac2312011-07-20 11:38:59 -0700237 private Runnable mHandlePendingChips = new Runnable() {
238
239 @Override
240 public void run() {
241 handlePendingChips();
Mindy Pereira2cac2312011-07-20 11:38:59 -0700242 }
243
244 };
245
Mindy Pereirad7192502011-09-22 08:04:45 -0700246 private Runnable mDelayedShrink = new Runnable() {
247
248 @Override
249 public void run() {
250 shrink();
251 }
252
253 };
254
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700255 private RecipientEntryItemClickedListener mRecipientEntryItemClickedListener;
256
257 public interface RecipientEntryItemClickedListener {
258 /**
259 * Callback that occurs whenever an auto-complete suggestion is clicked.
260 * @param charactersTyped the number of characters typed by the user to provide the
261 * auto-complete suggestions.
262 * @param position the position in the dropdown list that the user clicked
263 */
264 void onRecipientEntryItemClicked(int charactersTyped, int position);
265 }
266
Mindy Pereira9159cd22011-05-25 17:06:44 -0700267 public RecipientEditTextView(Context context, AttributeSet attrs) {
268 super(context, attrs);
Mindy Pereira22faaa62011-12-16 14:30:34 -0800269 setChipDimensions(context, attrs);
Scott Kennedy15259d52014-07-09 17:28:47 -0700270 mTextHeight = calculateTextHeight();
Mindy Pereira95a69252011-06-17 15:02:03 -0700271 mAlternatesPopup = new ListPopupWindow(context);
Jin Cao939f5f12014-11-10 11:06:12 -0800272 setupPopupWindow(mAlternatesPopup);
Mindy Pereira01382d72011-07-15 16:52:32 -0700273 mAddressPopup = new ListPopupWindow(context);
Jin Cao939f5f12014-11-10 11:06:12 -0800274 setupPopupWindow(mAddressPopup);
Mindy Pereirabfedc1e2011-09-07 12:17:12 -0700275 mCopyDialog = new Dialog(context);
Mindy Pereira95a69252011-06-17 15:02:03 -0700276 mAlternatesListener = new OnItemClickListener() {
277 @Override
278 public void onItemClick(AdapterView<?> adapterView,View view, int position,
279 long rowId) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700280 mAlternatesPopup.setOnItemClickListener(null);
Mindy Pereira95a69252011-06-17 15:02:03 -0700281 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
282 .getRecipientEntry(position));
283 Message delayed = Message.obtain(mHandler, DISMISS);
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700284 delayed.obj = mAlternatesPopup;
Mindy Pereira95a69252011-06-17 15:02:03 -0700285 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
286 clearComposingText();
287 }
288 };
Mindy Pereirae1bfc922011-08-16 14:00:01 -0700289 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
Mindy Pereirab88ee452011-06-02 11:07:43 -0700290 setOnItemClickListener(this);
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700291 setCustomSelectionActionModeCallback(this);
Mindy Pereira007a76b2011-06-14 11:39:36 -0700292 mHandler = new Handler() {
293 @Override
294 public void handleMessage(Message msg) {
295 if (msg.what == DISMISS) {
Mindy Pereira95a69252011-06-17 15:02:03 -0700296 ((ListPopupWindow) msg.obj).dismiss();
Mindy Pereira007a76b2011-06-14 11:39:36 -0700297 return;
298 }
299 super.handleMessage(msg);
300 }
301 };
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700302 mTextWatcher = new RecipientTextWatcher();
303 addTextChangedListener(mTextWatcher);
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700304 mGestureDetector = new GestureDetector(context, this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700305 setOnEditorActionListener(this);
Kevin Linb10d1c62014-01-24 12:45:00 -0800306
Jin Caoa20a8d02014-08-06 17:41:49 -0700307 setDropdownChipLayouter(new DropdownChipLayouter(LayoutInflater.from(context), context));
Kevin Linb10d1c62014-01-24 12:45:00 -0800308 }
309
Jin Cao939f5f12014-11-10 11:06:12 -0800310 private void setupPopupWindow(ListPopupWindow popup) {
Jin Cao939f5f12014-11-10 11:06:12 -0800311 popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
312 @Override
313 public void onDismiss() {
314 clearSelectedChip();
315 }
316 });
317 }
318
Jin Cao04f06ea2014-09-22 14:58:28 -0700319 @Override
320 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
321 super.onLayout(changed, left, top, right, bottom);
322
323 final AccessibilityManager accessibilityManager =
324 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
325 mIsAccessibilityOn = accessibilityManager.isEnabled();
326 }
327
Scott Kennedy15259d52014-07-09 17:28:47 -0700328 private int calculateTextHeight() {
Scott Kennedy15259d52014-07-09 17:28:47 -0700329 final TextPaint paint = getPaint();
330
Jin Caofcaf9862014-10-08 12:15:10 -0700331 mRect.setEmpty();
Scott Kennedy15259d52014-07-09 17:28:47 -0700332 // First measure the bounds of a sample text.
333 final String textHeightSample = "a";
Jin Caofcaf9862014-10-08 12:15:10 -0700334 paint.getTextBounds(textHeightSample, 0, textHeightSample.length(), mRect);
Scott Kennedy15259d52014-07-09 17:28:47 -0700335
Jin Caofcaf9862014-10-08 12:15:10 -0700336 mRect.left = 0;
337 mRect.right = 0;
Scott Kennedy15259d52014-07-09 17:28:47 -0700338
Jin Caofcaf9862014-10-08 12:15:10 -0700339 return mRect.height();
Scott Kennedy15259d52014-07-09 17:28:47 -0700340 }
341
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -0700342 public void setDropdownChipLayouter(DropdownChipLayouter dropdownChipLayouter) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800343 mDropdownChipLayouter = dropdownChipLayouter;
Jin Caoa20a8d02014-08-06 17:41:49 -0700344 mDropdownChipLayouter.setDeleteListener(this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700345 }
346
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700347 public void setRecipientEntryItemClickedListener(RecipientEntryItemClickedListener listener) {
348 mRecipientEntryItemClickedListener = listener;
349 }
350
Mindy Pereira93364a62012-04-27 14:17:22 -0700351 @Override
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700352 protected void onDetachedFromWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700353 super.onDetachedFromWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700354 mAttachedToWindow = false;
Jin Cao808d7132014-08-24 11:13:02 -0700355 dismissPopups();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700356 }
357
358 @Override
359 protected void onAttachedToWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700360 super.onAttachedToWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700361 mAttachedToWindow = true;
Jin Cao93d69f42014-10-07 12:27:49 -0700362
363 final int anchorId = getDropDownAnchor();
364 if (anchorId != View.NO_ID) {
365 mDropdownAnchor = getRootView().findViewById(anchorId);
366 }
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700367 }
368
369 @Override
Kevin Lin494bec82014-12-02 15:37:57 -0800370 public void setDropDownAnchor(int anchorId) {
371 super.setDropDownAnchor(anchorId);
372 if (anchorId != View.NO_ID) {
373 mDropdownAnchor = getRootView().findViewById(anchorId);
374 }
375 }
376
377 @Override
Mindy Pereira93364a62012-04-27 14:17:22 -0700378 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
379 if (action == EditorInfo.IME_ACTION_DONE) {
380 if (commitDefault()) {
381 return true;
382 }
383 if (mSelectedChip != null) {
384 clearSelectedChip();
385 return true;
386 } else if (focusNext()) {
387 return true;
388 }
389 }
390 return false;
391 }
392
393 @Override
Jin Caoffc01112014-12-15 16:24:37 -0800394 public InputConnection onCreateInputConnection(@NonNull EditorInfo outAttrs) {
Mindy Pereira93364a62012-04-27 14:17:22 -0700395 InputConnection connection = super.onCreateInputConnection(outAttrs);
396 int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
397 if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
398 // clear the existing action
399 outAttrs.imeOptions ^= imeActions;
400 // set the DONE action
401 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
402 }
403 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
404 outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
405 }
Scott Kennedy1af243f2013-01-29 23:38:43 -0800406
407 outAttrs.actionId = EditorInfo.IME_ACTION_DONE;
Kaikai Wanga5461b72014-09-18 17:38:46 -0700408
409 // Custom action labels are discouraged in L; a checkmark icon is shown in place of the
410 // custom text in this case.
Kaikai Wangbae3fba2014-10-29 10:55:35 -0700411 outAttrs.actionLabel = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? null :
Kaikai Wanga5461b72014-09-18 17:38:46 -0700412 getContext().getString(R.string.action_label);
Mindy Pereira93364a62012-04-27 14:17:22 -0700413 return connection;
Erike33555f2011-06-21 14:20:20 -0700414 }
Mindy Pereira7afe1602011-06-20 10:53:52 -0700415
Scott Kennedy194d4272013-03-06 22:06:45 -0800416 /*package*/ DrawableRecipientChip getLastChip() {
417 DrawableRecipientChip last = null;
418 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700419 if (chips != null && chips.length > 0) {
420 last = chips[chips.length - 1];
Erike33555f2011-06-21 14:20:20 -0700421 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700422 return last;
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700423 }
424
Ken Thai1248e532014-05-01 09:05:02 -0700425 /**
426 * @return The list of {@link RecipientEntry}s that have been selected by the user.
427 */
428 public List<RecipientEntry> getSelectedRecipients() {
429 DrawableRecipientChip[] chips =
430 getText().getSpans(0, getText().length(), DrawableRecipientChip.class);
Jin Caoffc01112014-12-15 16:24:37 -0800431 List<RecipientEntry> results = new ArrayList<RecipientEntry>();
Ken Thai1248e532014-05-01 09:05:02 -0700432 if (chips == null) {
433 return results;
434 }
435
436 for (DrawableRecipientChip c : chips) {
437 results.add(c.getEntry());
438 }
439
440 return results;
441 }
442
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700443 @Override
444 public void onSelectionChanged(int start, int end) {
445 // When selection changes, see if it is inside the chips area.
446 // If so, move the cursor back after the chips again.
Jin Caoffc01112014-12-15 16:24:37 -0800447 // Only exception is when we change the selection due to a selected chip.
Scott Kennedy194d4272013-03-06 22:06:45 -0800448 DrawableRecipientChip last = getLastChip();
Jin Caoffc01112014-12-15 16:24:37 -0800449 if (mSelectedChip == null && last != null && start < getSpannable().getSpanEnd(last)) {
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700450 // Grab the last chip and set the cursor to after it.
451 setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length()));
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700452 }
Mindy Pereira05dbd332011-06-03 09:37:44 -0700453 super.onSelectionChanged(start, end);
454 }
455
Mindy Pereiradc04cd72011-09-16 15:42:09 -0700456 @Override
457 public void onRestoreInstanceState(Parcelable state) {
458 if (!TextUtils.isEmpty(getText())) {
459 super.onRestoreInstanceState(null);
460 } else {
461 super.onRestoreInstanceState(state);
462 }
463 }
464
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700465 @Override
Mindy Pereiradaa640c2011-10-03 14:18:30 -0700466 public Parcelable onSaveInstanceState() {
467 // If the user changes orientation while they are editing, just roll back the selection.
468 clearSelectedChip();
469 return super.onSaveInstanceState();
470 }
471
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700472 /**
473 * Convenience method: Append the specified text slice to the TextView's
474 * display buffer, upgrading it to BufferType.EDITABLE if it was
475 * not already editable. Commas are excluded as they are added automatically
476 * by the view.
477 */
478 @Override
479 public void append(CharSequence text, int start, int end) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700480 // We don't care about watching text changes while appending.
481 if (mTextWatcher != null) {
482 removeTextChangedListener(mTextWatcher);
483 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700484 super.append(text, start, end);
485 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
mindyp01244682012-08-27 10:32:17 -0700486 String displayString = text.toString();
Scott Kennedy03e9e982013-03-04 13:26:22 -0800487
488 if (!displayString.trim().endsWith(String.valueOf(COMMIT_CHAR_COMMA))) {
489 // We have no separator, so we should add it
490 super.append(SEPARATOR, 0, SEPARATOR.length());
491 displayString += SEPARATOR;
mindyp01244682012-08-27 10:32:17 -0700492 }
Scott Kennedy03e9e982013-03-04 13:26:22 -0800493
mindyp20d7af72012-09-10 15:47:40 -0700494 if (!TextUtils.isEmpty(displayString)
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700495 && TextUtils.getTrimmedLength(displayString) > 0) {
496 mPendingChipsCount++;
Scott Kennedy03e9e982013-03-04 13:26:22 -0800497 mPendingChips.add(displayString);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700498 }
499 }
mindypabb864d2012-09-10 12:06:35 -0700500 // Put a message on the queue to make sure we ALWAYS handle pending
501 // chips.
Mindy Pereira2cac2312011-07-20 11:38:59 -0700502 if (mPendingChipsCount > 0) {
503 postHandlePendingChips();
504 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700505 mHandler.post(mAddTextWatcher);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700506 }
507
Mindy Pereira05dbd332011-06-03 09:37:44 -0700508 @Override
509 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700510 super.onFocusChanged(hasFocus, direction, previous);
Mindy Pereira05dbd332011-06-03 09:37:44 -0700511 if (!hasFocus) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700512 shrink();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700513 } else {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700514 expand();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700515 }
Mindy Pereira9159cd22011-05-25 17:06:44 -0700516 }
517
Alice Yang6b7110f2013-04-26 12:50:35 -0700518 @Override
Jin Caoffc01112014-12-15 16:24:37 -0800519 public <T extends ListAdapter & Filterable> void setAdapter(@NonNull T adapter) {
mindyp093ecdd2012-12-14 10:40:51 -0800520 super.setAdapter(adapter);
Kevin Linb10d1c62014-01-24 12:45:00 -0800521 BaseRecipientAdapter baseAdapter = (BaseRecipientAdapter) adapter;
522 baseAdapter.registerUpdateObserver(new BaseRecipientAdapter.EntriesUpdatedObserver() {
523 @Override
524 public void onChanged(List<RecipientEntry> entries) {
525 // Scroll the chips field to the top of the screen so
526 // that the user can see as many results as possible.
527 if (entries != null && entries.size() > 0) {
528 scrollBottomIntoView();
Jin Caob1aeb7b2014-09-01 23:48:05 -0700529 // Here the current suggestion count is still the old one since we update
530 // the count at the bottom of this function.
531 if (mCurrentSuggestionCount == 0) {
532 // Announce the new number of possible choices for accessibility.
Jin Cao04f06ea2014-09-22 14:58:28 -0700533 announceForAccessibilityCompat(getContext().getString(
Jin Caob1aeb7b2014-09-01 23:48:05 -0700534 R.string.accessbility_suggestion_dropdown_opened));
535 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800536 }
Jin Cao93d69f42014-10-07 12:27:49 -0700537
538 // Set the dropdown height to be the remaining height from the anchor to the bottom.
Jin Caofcaf9862014-10-08 12:15:10 -0700539 mDropdownAnchor.getLocationInWindow(mCoords);
540 getWindowVisibleDisplayFrame(mRect);
Jin Cao732fe3e2014-11-06 13:35:35 -0800541 setDropDownHeight(mRect.bottom - mCoords[1] - mDropdownAnchor.getHeight() -
542 getDropDownVerticalOffset());
Jin Caob1aeb7b2014-09-01 23:48:05 -0700543
544 mCurrentSuggestionCount = entries == null ? 0 : entries.size();
Kevin Linb10d1c62014-01-24 12:45:00 -0800545 }
546 });
547 baseAdapter.setDropdownChipLayouter(mDropdownChipLayouter);
mindyp093ecdd2012-12-14 10:40:51 -0800548 }
549
Jin Caoffc01112014-12-15 16:24:37 -0800550 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
Jin Cao04f06ea2014-09-22 14:58:28 -0700551 private void announceForAccessibilityCompat(String text) {
Jin Caoffc01112014-12-15 16:24:37 -0800552 if (mIsAccessibilityOn && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Jin Cao04f06ea2014-09-22 14:58:28 -0700553 final ViewParent parent = getParent();
554 if (parent != null) {
555 AccessibilityEvent event = AccessibilityEvent.obtain(
556 AccessibilityEvent.TYPE_ANNOUNCEMENT);
557 onInitializeAccessibilityEvent(event);
558 event.getText().add(text);
559 event.setContentDescription(null);
560 parent.requestSendAccessibilityEvent(this, event);
561 }
562 }
563 }
564
Kevin Lin53e718a2014-02-04 17:40:33 -0800565 protected void scrollBottomIntoView() {
mindyp093ecdd2012-12-14 10:40:51 -0800566 if (mScrollView != null && mShouldShrink) {
Jin Caofcaf9862014-10-08 12:15:10 -0700567 getLocationInWindow(mCoords);
mindyp093ecdd2012-12-14 10:40:51 -0800568 // Desired position shows at least 1 line of chips below the action
569 // bar. We add excess padding to make sure this is always below other
570 // content.
Jin Cao14efc572014-09-10 10:27:01 -0700571 final int height = getHeight();
Jin Caofcaf9862014-10-08 12:15:10 -0700572 final int currentPos = mCoords[1] + height;
Jin Caof6ddb752014-10-13 13:21:42 -0700573 mScrollView.getLocationInWindow(mCoords);
574 final int desiredPos = mCoords[1] + height / getLineCount();
mindyp093ecdd2012-12-14 10:40:51 -0800575 if (currentPos > desiredPos) {
576 mScrollView.scrollBy(0, currentPos - desiredPos);
577 }
578 }
579 }
580
Kevin Lin53e718a2014-02-04 17:40:33 -0800581 protected ScrollView getScrollView() {
Scott Kennedy7a4e6772013-11-21 14:31:33 -0800582 return mScrollView;
Kevin Lin53e718a2014-02-04 17:40:33 -0800583 }
584
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700585 @Override
586 public void performValidation() {
587 // Do nothing. Chips handles its own validation.
588 }
589
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700590 private void shrink() {
Mindy Pereira5c125af2011-12-13 11:04:13 -0800591 if (mTokenizer == null) {
592 return;
593 }
mindyp5e60c2b2012-11-06 17:47:40 -0800594 long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1;
595 if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT
596 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700597 clearSelectedChip();
598 } else {
Mindy Pereirad7192502011-09-22 08:04:45 -0700599 if (getWidth() <= 0) {
Mindy Pereirad7192502011-09-22 08:04:45 -0700600 mHandler.removeCallbacks(mDelayedShrink);
Scott Kennedy654c9672014-12-12 14:24:17 -0800601
602 if (getVisibility() == GONE) {
603 // We aren't going to have a width any time soon, so defer
604 // this until we're not GONE.
605 mRequiresShrinkWhenNotGone = true;
606 } else {
607 // We don't have the width yet which means the view hasn't been drawn yet
608 // and there is no reason to attempt to commit chips yet.
609 // This focus lost must be the result of an orientation change
610 // or an initial rendering.
611 // Re-post the shrink for later.
612 mHandler.post(mDelayedShrink);
613 }
Mindy Pereirad7192502011-09-22 08:04:45 -0700614 return;
615 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700616 // Reset any pending chips as they would have been handled
617 // when the field lost focus.
618 if (mPendingChipsCount > 0) {
Mindy Pereira2cac2312011-07-20 11:38:59 -0700619 postHandlePendingChips();
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700620 } else {
621 Editable editable = getText();
622 int end = getSelectionEnd();
623 int start = mTokenizer.findTokenStart(editable, end);
Scott Kennedy194d4272013-03-06 22:06:45 -0800624 DrawableRecipientChip[] chips =
625 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700626 if ((chips == null || chips.length == 0)) {
Mindy Pereirad7192502011-09-22 08:04:45 -0700627 Editable text = getText();
628 int whatEnd = mTokenizer.findTokenEnd(text, start);
629 // This token was already tokenized, so skip past the ending token.
Mindy Pereira448e90b2011-09-22 11:49:32 -0700630 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') {
mindyp4f82d882012-11-08 16:30:27 -0800631 whatEnd = movePastTerminators(whatEnd);
Mindy Pereirad7192502011-09-22 08:04:45 -0700632 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700633 // In the middle of chip; treat this as an edit
634 // and commit the whole token.
Mindy Pereirad7192502011-09-22 08:04:45 -0700635 int selEnd = getSelectionEnd();
Mindy Pereira63372312011-11-15 15:23:07 -0800636 if (whatEnd != selEnd) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700637 handleEdit(start, whatEnd);
638 } else {
639 commitChip(start, end, editable);
640 }
641 }
Mindy Pereiraa74f40d2011-07-12 09:07:17 -0700642 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700643 mHandler.post(mAddTextWatcher);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700644 }
Mindy Pereira3bb52162011-07-01 14:52:22 -0700645 createMoreChip();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700646 }
647
648 private void expand() {
mindyp374ccb22012-11-06 10:54:05 -0800649 if (mShouldShrink) {
650 setMaxLines(Integer.MAX_VALUE);
651 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700652 removeMoreChip();
653 setCursorVisible(true);
654 Editable text = getText();
655 setSelection(text != null && text.length() > 0 ? text.length() : 0);
Mindy Pereira18529312011-06-28 11:00:52 -0700656 // If there are any temporary chips, try replacing them now that the user
657 // has expanded the field.
658 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
659 new RecipientReplacementTask().execute();
660 mTemporaryRecipients = null;
661 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700662 }
663
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700664 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700665 paint.setTextSize(mChipFontSize);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700666 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
667 Log.d(TAG, "Max width is negative: " + maxWidth);
668 }
669 return TextUtils.ellipsize(text, paint, maxWidth,
670 TextUtils.TruncateAt.END);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700671 }
672
Kevin Linb10d1c62014-01-24 12:45:00 -0800673 /**
674 * Creates a bitmap of the given contact on a selected chip.
675 *
676 * @param contact The recipient entry to pull data from.
677 * @param paint The paint to use to draw the bitmap.
678 */
Jin Caoffc01112014-12-15 16:24:37 -0800679 private Bitmap createChipBitmap(RecipientEntry contact, TextPaint paint) {
Kaikai Wangcb11fce2014-12-09 14:20:57 -0800680 paint.setColor(getDefaultChipTextColor(contact));
Jin Cao33515e72014-08-05 21:13:27 -0700681 ChipBitmapContainer bitmapContainer = createChipBitmap(contact, paint,
682 getChipBackground(contact), getDefaultChipBackgroundColor(contact));
Jin Cao35e82d42014-06-02 17:21:21 -0700683
684 if (bitmapContainer.loadIcon) {
Jin Cao809c5952014-08-08 12:28:17 -0700685 loadAvatarIcon(contact, bitmapContainer);
Jin Cao35e82d42014-06-02 17:21:21 -0700686 }
687 return bitmapContainer.bitmap;
Kevin Linb10d1c62014-01-24 12:45:00 -0800688 }
689
Jin Cao35e82d42014-06-02 17:21:21 -0700690 private ChipBitmapContainer createChipBitmap(RecipientEntry contact, TextPaint paint,
Jin Cao33515e72014-08-05 21:13:27 -0700691 Drawable overrideBackgroundDrawable, int backgroundColor) {
Jin Cao35e82d42014-06-02 17:21:21 -0700692 final ChipBitmapContainer result = new ChipBitmapContainer();
693
Kevin Linb10d1c62014-01-24 12:45:00 -0800694 Rect backgroundPadding = new Rect();
Jin Cao33515e72014-08-05 21:13:27 -0700695 if (overrideBackgroundDrawable != null) {
696 overrideBackgroundDrawable.getPadding(backgroundPadding);
697 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800698
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700699 // Ellipsize the text so that it takes AT MOST the entire width of the
700 // autocomplete text entry area. Make sure to leave space for padding
701 // on the sides.
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700702 int height = (int) mChipHeight;
Kevin Linb10d1c62014-01-24 12:45:00 -0800703 // 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 -0700704 // the chip. Don't include iconWidth for invalid contacts.
705 int iconWidth = contact.isValid() ?
706 height - backgroundPadding.top - backgroundPadding.bottom : 0;
Mindy Pereira6ed7ded2011-10-14 16:31:31 -0700707 float[] widths = new float[1];
708 paint.getTextWidths(" ", widths);
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700709 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
Kevin Lin9b398e32014-02-26 12:29:10 -0800710 calculateAvailableWidth() - iconWidth - widths[0] - backgroundPadding.left
Jin Cao33515e72014-08-05 21:13:27 -0700711 - backgroundPadding.right);
Kevin Linb10d1c62014-01-24 12:45:00 -0800712 int textWidth = (int) paint.measureText(ellipsizedText, 0, ellipsizedText.length());
713
Jin Cao33515e72014-08-05 21:13:27 -0700714 // Chip start padding is the same as the end padding if there is no contact image.
715 final int startPadding = contact.isValid() ? mChipTextStartPadding : mChipTextEndPadding;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700716 // Make sure there is a minimum chip width so the user can ALWAYS
717 // tap a chip without difficulty.
Jin Cao33515e72014-08-05 21:13:27 -0700718 int width = Math.max(iconWidth * 2, textWidth + startPadding + mChipTextEndPadding
Jin Cao58d541d2014-07-29 16:23:03 -0700719 + iconWidth + backgroundPadding.left + backgroundPadding.right);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700720
721 // Create the background of the chip.
Jin Cao35e82d42014-06-02 17:21:21 -0700722 result.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
723 final Canvas canvas = new Canvas(result.bitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700724
Jin Cao33515e72014-08-05 21:13:27 -0700725 // Check if the background drawable is set via attr
726 if (overrideBackgroundDrawable != null) {
727 overrideBackgroundDrawable.setBounds(0, 0, width, height);
728 overrideBackgroundDrawable.draw(canvas);
729 } else {
730 // Draw the default chip background
Jin Cao6c2a0162014-08-17 15:00:50 -0700731 mWorkPaint.reset();
732 mWorkPaint.setColor(backgroundColor);
Jin Cao568fb222014-08-19 13:50:59 -0700733 mWorkPaint.setAntiAlias(true);
Jin Cao33515e72014-08-05 21:13:27 -0700734 final float radius = height / 2;
735 canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius,
Jin Cao6c2a0162014-08-17 15:00:50 -0700736 mWorkPaint);
Jin Cao33515e72014-08-05 21:13:27 -0700737 }
738
Kevin Linb10d1c62014-01-24 12:45:00 -0800739 // Draw the text vertically aligned
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800740 int textX = shouldPositionAvatarOnRight() ?
Jin Cao58d541d2014-07-29 16:23:03 -0700741 mChipTextEndPadding + backgroundPadding.left :
742 width - backgroundPadding.right - mChipTextEndPadding - textWidth;
Kevin Linb10d1c62014-01-24 12:45:00 -0800743 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(),
Scott Kennedy15259d52014-07-09 17:28:47 -0700744 textX, getTextYOffset(height), paint);
Jin Cao35e82d42014-06-02 17:21:21 -0700745
746 // Set the variables that are needed to draw the icon bitmap once it's loaded
747 int iconX = shouldPositionAvatarOnRight() ? width - backgroundPadding.right - iconWidth :
748 backgroundPadding.left;
749 result.left = iconX;
750 result.top = backgroundPadding.top;
751 result.right = iconX + iconWidth;
752 result.bottom = height - backgroundPadding.bottom;
753
754 return result;
755 }
756
757 /**
758 * Helper function that draws the loaded icon bitmap into the chips bitmap
759 */
Jin Cao809c5952014-08-08 12:28:17 -0700760 private void drawIcon(ChipBitmapContainer bitMapResult, Bitmap icon) {
Jin Cao35e82d42014-06-02 17:21:21 -0700761 final Canvas canvas = new Canvas(bitMapResult.bitmap);
762 final RectF src = new RectF(0, 0, icon.getWidth(), icon.getHeight());
763 final RectF dst = new RectF(bitMapResult.left, bitMapResult.top, bitMapResult.right,
764 bitMapResult.bottom);
Jin Cao809c5952014-08-08 12:28:17 -0700765 drawIconOnCanvas(icon, canvas, src, dst);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700766 }
767
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700768 /**
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800769 * Returns true if the avatar should be positioned at the right edge of the chip.
770 * Takes into account both the set avatar position (start or end) as well as whether
771 * the layout direction is LTR or RTL.
772 */
773 private boolean shouldPositionAvatarOnRight() {
Jin Caoffc01112014-12-15 16:24:37 -0800774 final boolean isRtl = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 &&
775 getLayoutDirection() == LAYOUT_DIRECTION_RTL;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800776 final boolean assignedPosition = mAvatarPosition == AVATAR_POSITION_END;
777 // If in Rtl mode, the position should be flipped.
778 return isRtl ? !assignedPosition : assignedPosition;
779 }
780
781 /**
Kevin Linb10d1c62014-01-24 12:45:00 -0800782 * Returns the avatar icon to use for this recipient entry. Returns null if we don't want to
783 * draw an icon for this recipient.
784 */
Jin Cao35e82d42014-06-02 17:21:21 -0700785 private void loadAvatarIcon(final RecipientEntry contact,
Jin Cao809c5952014-08-08 12:28:17 -0700786 final ChipBitmapContainer bitmapContainer) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800787 // Don't draw photos for recipients that have been typed in OR generated on the fly.
788 long contactId = contact.getContactId();
789 boolean drawPhotos = isPhoneQuery() ?
790 contactId != RecipientEntry.INVALID_CONTACT
791 : (contactId != RecipientEntry.INVALID_CONTACT
Jin Caobf84bd82014-07-31 10:59:27 -0700792 && contactId != RecipientEntry.GENERATED_CONTACT);
Kevin Linb10d1c62014-01-24 12:45:00 -0800793
794 if (drawPhotos) {
Jin Cao35e82d42014-06-02 17:21:21 -0700795 final byte[] origPhotoBytes = contact.getPhotoBytes();
Kevin Linb10d1c62014-01-24 12:45:00 -0800796 // There may not be a photo yet if anything but the first contact address
797 // was selected.
Jin Cao82d38852014-06-03 10:53:46 -0700798 if (origPhotoBytes == null) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800799 // TODO: cache this in the recipient entry?
Jin Cao35e82d42014-06-02 17:21:21 -0700800 getAdapter().fetchPhoto(contact, new PhotoManager.PhotoManagerCallback() {
Jin Cao52e48142014-06-04 18:01:20 -0700801 @Override
Andrew Sapperstein50429c52014-06-12 15:12:10 -0700802 public void onPhotoBytesPopulated() {
803 // Call through to the async version which will ensure
804 // proper threading.
805 onPhotoBytesAsynchronouslyPopulated();
806 }
807
808 @Override
Jin Cao52e48142014-06-04 18:01:20 -0700809 public void onPhotoBytesAsynchronouslyPopulated() {
810 final byte[] loadedPhotoBytes = contact.getPhotoBytes();
811 final Bitmap icon = BitmapFactory.decodeByteArray(loadedPhotoBytes, 0,
812 loadedPhotoBytes.length);
813 tryDrawAndInvalidate(icon);
814 }
Jin Cao0efdc532014-06-04 15:35:16 -0700815
Jin Cao52e48142014-06-04 18:01:20 -0700816 @Override
817 public void onPhotoBytesAsyncLoadFailed() {
818 // TODO: can the scaled down default photo be cached?
819 tryDrawAndInvalidate(mDefaultContactPhoto);
820 }
821
822 private void tryDrawAndInvalidate(Bitmap icon) {
Jin Cao809c5952014-08-08 12:28:17 -0700823 drawIcon(bitmapContainer, icon);
Jin Cao52e48142014-06-04 18:01:20 -0700824 // The caller might originated from a background task. However, if the
825 // background task has already completed, the view might be already drawn
826 // on the UI but the callback would happen on the background thread.
827 // So if we are on a background thread, post an invalidate call to the UI.
828 if (Looper.myLooper() == Looper.getMainLooper()) {
829 // The view might not redraw itself since it's loaded asynchronously
Jin Cao0efdc532014-06-04 15:35:16 -0700830 invalidate();
Jin Cao52e48142014-06-04 18:01:20 -0700831 } else {
832 post(new Runnable() {
833 @Override
834 public void run() {
835 invalidate();
836 }
837 });
Jin Cao0efdc532014-06-04 15:35:16 -0700838 }
Jin Cao52e48142014-06-04 18:01:20 -0700839 }
Jin Cao35e82d42014-06-02 17:21:21 -0700840 });
Kevin Linb10d1c62014-01-24 12:45:00 -0800841 } else {
Jin Cao35e82d42014-06-02 17:21:21 -0700842 final Bitmap icon = BitmapFactory.decodeByteArray(origPhotoBytes, 0,
843 origPhotoBytes.length);
Jin Cao809c5952014-08-08 12:28:17 -0700844 drawIcon(bitmapContainer, icon);
Kevin Linb10d1c62014-01-24 12:45:00 -0800845 }
846 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800847 }
848
849 /**
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700850 * Get the background drawable for a RecipientChip.
851 */
852 // Visible for testing.
mindypf30a4282012-12-03 12:16:33 -0800853 /* package */Drawable getChipBackground(RecipientEntry contact) {
854 return contact.isValid() ? mChipBackground : mInvalidChipBackground;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700855 }
856
Kaikai Wangcb11fce2014-12-09 14:20:57 -0800857 private int getDefaultChipTextColor(RecipientEntry contact) {
858 return contact.isValid() ? mUnselectedChipTextColor :
859 getResources().getColor(android.R.color.black);
860 }
861
Jin Cao33515e72014-08-05 21:13:27 -0700862 private int getDefaultChipBackgroundColor(RecipientEntry contact) {
Kaikai Wangcb11fce2014-12-09 14:20:57 -0800863 return contact.isValid() ? mUnselectedChipBackgroundColor :
864 getResources().getColor(R.color.chip_background_invalid);
Jin Cao33515e72014-08-05 21:13:27 -0700865 }
866
Kevin Linb10d1c62014-01-24 12:45:00 -0800867 /**
868 * Given a height, returns a Y offset that will draw the text in the middle of the height.
869 */
Scott Kennedy15259d52014-07-09 17:28:47 -0700870 protected float getTextYOffset(int height) {
871 return height - ((height - mTextHeight) / 2);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700872 }
873
Kevin Linb10d1c62014-01-24 12:45:00 -0800874 /**
Scott Kennedyb8985b72014-01-28 16:36:19 -0800875 * Draws the icon onto the canvas given the source rectangle of the bitmap and the destination
Kevin Linb10d1c62014-01-24 12:45:00 -0800876 * rectangle of the canvas.
877 */
Jin Cao809c5952014-08-08 12:28:17 -0700878 protected void drawIconOnCanvas(Bitmap icon, Canvas canvas, RectF src, RectF dst) {
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700879 final Matrix matrix = new Matrix();
880
881 // Draw bitmap through shader first.
882 final BitmapShader shader = new BitmapShader(icon, TileMode.CLAMP, TileMode.CLAMP);
883 matrix.reset();
884
885 // Fit bitmap to bounds.
Kevin Linb10d1c62014-01-24 12:45:00 -0800886 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700887
888 shader.setLocalMatrix(matrix);
Jin Cao809c5952014-08-08 12:28:17 -0700889 mWorkPaint.reset();
890 mWorkPaint.setShader(shader);
891 mWorkPaint.setAntiAlias(true);
892 mWorkPaint.setFilterBitmap(true);
893 mWorkPaint.setDither(true);
894 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f, mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700895
896 // Then draw the border.
897 final float borderWidth = 1f;
Jin Cao809c5952014-08-08 12:28:17 -0700898 mWorkPaint.reset();
899 mWorkPaint.setColor(Color.TRANSPARENT);
900 mWorkPaint.setStyle(Style.STROKE);
901 mWorkPaint.setStrokeWidth(borderWidth);
902 mWorkPaint.setAntiAlias(true);
Jin Caoffc01112014-12-15 16:24:37 -0800903 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f - borderWidth / 2,
904 mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700905
Jin Cao809c5952014-08-08 12:28:17 -0700906 mWorkPaint.reset();
Kevin Linb10d1c62014-01-24 12:45:00 -0800907 }
908
Jin Caoffc01112014-12-15 16:24:37 -0800909 private DrawableRecipientChip constructChipSpan(RecipientEntry contact) {
Mindy Pereiracd611952011-06-01 17:02:20 -0700910 TextPaint paint = getPaint();
911 float defaultSize = paint.getTextSize();
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700912 int defaultColor = paint.getColor();
Mindy Pereiracd611952011-06-01 17:02:20 -0700913
Jin Caoffc01112014-12-15 16:24:37 -0800914 Bitmap tmpBitmap = createChipBitmap(contact, paint);
Mindy Pereiracd611952011-06-01 17:02:20 -0700915
Mindy Pereiracd611952011-06-01 17:02:20 -0700916 // Pass the full text, un-ellipsized, to the chip.
917 Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700918 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
Jin Cao6c2a0162014-08-17 15:00:50 -0700919 VisibleRecipientChip recipientChip =
920 new VisibleRecipientChip(result, contact);
921 recipientChip.setExtraMargin(mLineSpacingExtra);
Mindy Pereiracd611952011-06-01 17:02:20 -0700922 // Return text to the original size.
923 paint.setTextSize(defaultSize);
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700924 paint.setColor(defaultColor);
Mindy Pereiracd611952011-06-01 17:02:20 -0700925 return recipientChip;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700926 }
927
Mindy Pereiraa8166902011-06-09 17:53:23 -0700928 /**
Mindy Pereira34214202011-06-09 20:05:32 -0700929 * Calculate the bottom of the line the chip will be located on using:
930 * 1) which line the chip appears on
Mindy Pereira21625f82011-06-16 18:10:58 -0700931 * 2) the height of a chip
932 * 3) padding built into the edit text view
Mindy Pereiraa8166902011-06-09 17:53:23 -0700933 */
Mindy Pereira81fd3d12011-07-06 14:40:50 -0700934 private int calculateOffsetFromBottom(int line) {
Mindy Pereira21625f82011-06-16 18:10:58 -0700935 // Line offsets start at zero.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700936 int actualLine = getLineCount() - (line + 1);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700937 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
938 + getDropDownVerticalOffset();
Mindy Pereiraf621a602011-05-31 10:09:35 -0700939 }
940
Mindy Pereiraa8166902011-06-09 17:53:23 -0700941 /**
Jin Cao6fc1fee2014-07-29 17:56:44 -0700942 * Calculate the offset from bottom of the EditText to top of the provided line.
943 */
944 private int calculateOffsetFromBottomToTop(int line) {
945 return -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math
946 .abs(getLineCount() - line)) + getPaddingBottom());
947 }
948
949 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -0700950 * Get the max amount of space a chip can take up. The formula takes into
951 * account the width of the EditTextView, any view padding, and padding
952 * that will be added to the chip.
953 */
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800954 private float calculateAvailableWidth() {
Jin Cao58d541d2014-07-29 16:23:03 -0700955 return getWidth() - getPaddingLeft() - getPaddingRight() - mChipTextStartPadding
956 - mChipTextEndPadding;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700957 }
958
Mindy Pereira52c441e2011-12-15 13:35:37 -0800959
Mindy Pereira22faaa62011-12-16 14:30:34 -0800960 private void setChipDimensions(Context context, AttributeSet attrs) {
Mindy Pereira5da02342011-12-16 14:56:27 -0800961 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
962 0);
Mindy Pereira52c441e2011-12-15 13:35:37 -0800963 Resources r = getContext().getResources();
mindyp8c474ec2012-12-14 10:58:44 -0800964
Mindy Pereira22faaa62011-12-16 14:30:34 -0800965 mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
Jin Cao33515e72014-08-05 21:13:27 -0700966 mInvalidChipBackground = a
967 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
Mindy Pereira5da02342011-12-16 14:56:27 -0800968 mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
969 if (mChipDelete == null) {
Jin Caoa21fd882014-08-10 13:07:11 -0700970 mChipDelete = r.getDrawable(R.drawable.ic_cancel_wht_24dp);
Mindy Pereira5da02342011-12-16 14:56:27 -0800971 }
Jin Cao58d541d2014-07-29 16:23:03 -0700972 mChipTextStartPadding = mChipTextEndPadding
973 = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
974 if (mChipTextStartPadding == -1) {
975 mChipTextStartPadding = mChipTextEndPadding =
976 (int) r.getDimension(R.dimen.chip_padding);
977 }
978 // xml-overrides for each individual padding
979 // TODO: add these to attr?
980 int overridePadding = (int) r.getDimension(R.dimen.chip_padding_start);
981 if (overridePadding >= 0) {
982 mChipTextStartPadding = overridePadding;
983 }
984 overridePadding = (int) r.getDimension(R.dimen.chip_padding_end);
985 if (overridePadding >= 0) {
986 mChipTextEndPadding = overridePadding;
Mindy Pereira5da02342011-12-16 14:56:27 -0800987 }
Mindy Pereira5da02342011-12-16 14:56:27 -0800988
989 mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
990
Mindy Pereira52c441e2011-12-15 13:35:37 -0800991 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
Mindy Pereira5da02342011-12-16 14:56:27 -0800992
993 mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
994 if (mChipHeight == -1) {
995 mChipHeight = r.getDimension(R.dimen.chip_height);
996 }
997 mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
998 if (mChipFontSize == -1) {
999 mChipFontSize = r.getDimension(R.dimen.chip_text_size);
1000 }
Scott Kennedyb232e5c2014-07-09 16:29:35 -07001001 mAvatarPosition =
1002 a.getInt(R.styleable.RecipientEditTextView_avatarPosition, AVATAR_POSITION_START);
Scott Kennedyb8985b72014-01-28 16:36:19 -08001003 mDisableDelete = a.getBoolean(R.styleable.RecipientEditTextView_disableDelete, false);
Kevin Linb10d1c62014-01-24 12:45:00 -08001004
mindypf30a4282012-12-03 12:16:33 -08001005 mMaxLines = r.getInteger(R.integer.chips_max_lines);
Jin Cao6c2a0162014-08-17 15:00:50 -07001006 mLineSpacingExtra = r.getDimensionPixelOffset(R.dimen.line_spacing_extra);
Kevin Linb10d1c62014-01-24 12:45:00 -08001007
Kaikai Wangcb11fce2014-12-09 14:20:57 -08001008 mUnselectedChipTextColor = a.getColor(
1009 R.styleable.RecipientEditTextView_unselectedChipTextColor,
1010 r.getColor(android.R.color.black));
1011
1012 mSelectedChipTextColor = a.getColor(
1013 R.styleable.RecipientEditTextView_selectedChipTextColor,
1014 r.getColor(android.R.color.white));
1015
1016 mUnselectedChipBackgroundColor = a.getColor(
1017 R.styleable.RecipientEditTextView_unselectedChipBackgroundColor,
1018 r.getColor(R.color.chip_background));
1019
1020 mSelectedChipBackgroundColor = a.getColor(
1021 R.styleable.RecipientEditTextView_selectedChipBackgroundColor,
1022 r.getColor(R.color.chip_background_selected));
Mindy Pereiraef798002012-05-02 11:04:25 -07001023 a.recycle();
Mindy Pereira52c441e2011-12-15 13:35:37 -08001024 }
1025
Mindy Pereirad7192502011-09-22 08:04:45 -07001026 // Visible for testing.
1027 /* package */ void setMoreItem(TextView moreItem) {
1028 mMoreItem = moreItem;
1029 }
1030
Mindy Pereira97cb2592011-09-26 16:11:41 -07001031
1032 // Visible for testing.
1033 /* package */ void setChipBackground(Drawable chipBackground) {
1034 mChipBackground = chipBackground;
1035 }
1036
1037 // Visible for testing.
1038 /* package */ void setChipHeight(int height) {
1039 mChipHeight = height;
1040 }
1041
Kevin Linb10d1c62014-01-24 12:45:00 -08001042 public float getChipHeight() {
1043 return mChipHeight;
1044 }
1045
Mindy Pereira076d1f92011-08-08 11:53:12 -07001046 /**
1047 * Set whether to shrink the recipients field such that at most
1048 * one line of recipients chips are shown when the field loses
1049 * focus. By default, the number of displayed recipients will be
1050 * limited and a "more" chip will be shown when focus is lost.
1051 * @param shrink
1052 */
1053 public void setOnFocusListShrinkRecipients(boolean shrink) {
1054 mShouldShrink = shrink;
1055 }
1056
Mindy Pereiracd611952011-06-01 17:02:20 -07001057 @Override
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001058 public void onSizeChanged(int width, int height, int oldw, int oldh) {
1059 super.onSizeChanged(width, height, oldw, oldh);
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001060 if (width != 0 && height != 0) {
1061 if (mPendingChipsCount > 0) {
1062 postHandlePendingChips();
1063 } else {
1064 checkChipWidths();
1065 }
Mindy Pereira8005f422011-07-20 13:16:53 -07001066 }
Mindy Pereira18529312011-06-28 11:00:52 -07001067 // Try to find the scroll view parent, if it exists.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001068 if (mScrollView == null && !mTriedGettingScrollView) {
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001069 ViewParent parent = getParent();
1070 while (parent != null && !(parent instanceof ScrollView)) {
1071 parent = parent.getParent();
1072 }
1073 if (parent != null) {
1074 mScrollView = (ScrollView) parent;
1075 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001076 mTriedGettingScrollView = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001077 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001078 }
1079
Mindy Pereira2cac2312011-07-20 11:38:59 -07001080 private void postHandlePendingChips() {
1081 mHandler.removeCallbacks(mHandlePendingChips);
1082 mHandler.post(mHandlePendingChips);
1083 }
Mindy Pereira18529312011-06-28 11:00:52 -07001084
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001085 private void checkChipWidths() {
1086 // Check the widths of the associated chips.
Scott Kennedy194d4272013-03-06 22:06:45 -08001087 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001088 if (chips != null) {
1089 Rect bounds;
Scott Kennedy194d4272013-03-06 22:06:45 -08001090 for (DrawableRecipientChip chip : chips) {
mindypf30a4282012-12-03 12:16:33 -08001091 bounds = chip.getBounds();
Kevin Linc61c13f2014-02-28 15:04:40 -08001092 if (getWidth() > 0 && bounds.right - bounds.left >
1093 getWidth() - getPaddingLeft() - getPaddingRight()) {
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001094 // Need to redraw that chip.
1095 replaceChip(chip, chip.getEntry());
1096 }
1097 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001098 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001099 }
1100
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001101 // Visible for testing.
1102 /*package*/ void handlePendingChips() {
1103 if (getViewWidth() <= 0) {
Mindy Pereira8005f422011-07-20 13:16:53 -07001104 // The widget has not been sized yet.
1105 // This will be called as a result of onSizeChanged
1106 // at a later point.
1107 return;
1108 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001109 if (mPendingChipsCount <= 0) {
1110 return;
1111 }
1112
Mindy Pereira2cac2312011-07-20 11:38:59 -07001113 synchronized (mPendingChips) {
Mindy Pereira2cac2312011-07-20 11:38:59 -07001114 Editable editable = getText();
1115 // Tokenize!
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001116 if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
1117 for (int i = 0; i < mPendingChips.size(); i++) {
1118 String current = mPendingChips.get(i);
1119 int tokenStart = editable.toString().indexOf(current);
mindyp488718e2012-12-18 11:48:07 -08001120 // Always leave a space at the end between tokens.
1121 int tokenEnd = tokenStart + current.length() - 1;
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001122 if (tokenStart >= 0) {
1123 // When we have a valid token, include it with the token
1124 // to the left.
1125 if (tokenEnd < editable.length() - 2
1126 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
1127 tokenEnd++;
1128 }
mindypf30a4282012-12-03 12:16:33 -08001129 createReplacementChip(tokenStart, tokenEnd, editable, i < CHIP_LIMIT
1130 || !mShouldShrink);
Mindy Pereira2cac2312011-07-20 11:38:59 -07001131 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001132 mPendingChipsCount--;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001133 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001134 sanitizeEnd();
1135 } else {
1136 mNoChips = true;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001137 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001138
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001139 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
Mindy Pereira2cac2312011-07-20 11:38:59 -07001140 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
1141 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
1142 new RecipientReplacementTask().execute();
1143 mTemporaryRecipients = null;
1144 } else {
1145 // Create the "more" chip
1146 mIndividualReplacements = new IndividualReplacementTask();
Scott Kennedy194d4272013-03-06 22:06:45 -08001147 mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(
Mindy Pereira2cac2312011-07-20 11:38:59 -07001148 mTemporaryRecipients.subList(0, CHIP_LIMIT)));
mindyp5e60c2b2012-11-06 17:47:40 -08001149 if (mTemporaryRecipients.size() > CHIP_LIMIT) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001150 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>(
mindyp5e60c2b2012-11-06 17:47:40 -08001151 mTemporaryRecipients.subList(CHIP_LIMIT,
1152 mTemporaryRecipients.size()));
1153 } else {
1154 mTemporaryRecipients = null;
1155 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001156 createMoreChip();
1157 }
1158 } else {
1159 // There are too many recipients to look up, so just fall back
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001160 // to showing addresses for all of them.
Mindy Pereira2cac2312011-07-20 11:38:59 -07001161 mTemporaryRecipients = null;
Mindy Pereira18529312011-06-28 11:00:52 -07001162 createMoreChip();
1163 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001164 mPendingChipsCount = 0;
1165 mPendingChips.clear();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001166 }
1167 }
1168
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001169 // Visible for testing.
1170 /*package*/ int getViewWidth() {
1171 return getWidth();
1172 }
1173
Mindy Pereira3bb52162011-07-01 14:52:22 -07001174 /**
1175 * Remove any characters after the last valid chip.
1176 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001177 // Visible for testing.
1178 /*package*/ void sanitizeEnd() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001179 // Don't sanitize while we are waiting for pending chips to complete.
1180 if (mPendingChipsCount > 0) {
1181 return;
1182 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001183 // Find the last chip; eliminate any commit characters after it.
Scott Kennedy194d4272013-03-06 22:06:45 -08001184 DrawableRecipientChip[] chips = getSortedRecipients();
mindypf30a4282012-12-03 12:16:33 -08001185 Spannable spannable = getSpannable();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001186 if (chips != null && chips.length > 0) {
1187 int end;
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001188 mMoreChip = getMoreChip();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001189 if (mMoreChip != null) {
mindypf30a4282012-12-03 12:16:33 -08001190 end = spannable.getSpanEnd(mMoreChip);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001191 } else {
mindypf30a4282012-12-03 12:16:33 -08001192 end = getSpannable().getSpanEnd(getLastChip());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001193 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001194 Editable editable = getText();
1195 int length = editable.length();
1196 if (length > end) {
1197 // See what characters occur after that and eliminate them.
1198 if (Log.isLoggable(TAG, Log.DEBUG)) {
1199 Log.d(TAG, "There were extra characters after the last tokenizable entry."
1200 + editable);
1201 }
1202 editable.delete(end + 1, length);
1203 }
1204 }
1205 }
1206
1207 /**
1208 * Create a chip that represents just the email address of a recipient. At some later
1209 * point, this chip will be attached to a real contact entry, if one exists.
1210 */
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001211 // VisibleForTesting
1212 void createReplacementChip(int tokenStart, int tokenEnd, Editable editable,
mindypf30a4282012-12-03 12:16:33 -08001213 boolean visible) {
Mindy Pereira32366d42011-07-24 12:39:30 -07001214 if (alreadyHasChip(tokenStart, tokenEnd)) {
1215 // There is already a chip present at this location.
1216 // Don't recreate it.
1217 return;
1218 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07001219 String token = editable.toString().substring(tokenStart, tokenEnd);
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001220 final String trimmedToken = token.trim();
1221 int commitCharIndex = trimmedToken.lastIndexOf(COMMIT_CHAR_COMMA);
Tom Taylor41137c22013-03-26 12:22:56 -07001222 if (commitCharIndex != -1 && commitCharIndex == trimmedToken.length() - 1) {
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001223 token = trimmedToken.substring(0, trimmedToken.length() - 1);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001224 }
1225 RecipientEntry entry = createTokenizedEntry(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001226 if (entry != null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001227 DrawableRecipientChip chip = null;
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001228 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001229 if (!mNoChips) {
Jin Caoffc01112014-12-15 16:24:37 -08001230 chip = visible ? constructChipSpan(entry) : new InvisibleRecipientChip(entry);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001231 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001232 } catch (NullPointerException e) {
1233 Log.e(TAG, e.getMessage(), e);
1234 }
mindypcb76b4d2012-11-09 14:05:19 -08001235 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001236 // Add this chip to the list of entries "to replace"
1237 if (chip != null) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001238 if (mTemporaryRecipients == null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001239 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>();
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001240 }
Scott Kennedy0613ff82013-03-05 14:02:46 -08001241 chip.setOriginalText(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001242 mTemporaryRecipients.add(chip);
1243 }
Mindy Pereira18529312011-06-28 11:00:52 -07001244 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001245 }
1246
Tom Taylorabff6062012-04-17 09:04:56 -07001247 private static boolean isPhoneNumber(String number) {
1248 // TODO: replace this function with libphonenumber's isPossibleNumber (see
1249 // PhoneNumberUtil). One complication is that it requires the sender's region which
1250 // comes from the CurrentCountryIso. For now, let's just do this simple match.
1251 if (TextUtils.isEmpty(number)) {
1252 return false;
1253 }
1254
Tom Taylor4491a062012-11-15 13:57:41 -08001255 Matcher match = PHONE_PATTERN.matcher(number);
Tom Taylorabff6062012-04-17 09:04:56 -07001256 return match.matches();
1257 }
1258
Scott Kennedy983c99b2013-03-22 09:42:03 -07001259 // VisibleForTesting
1260 RecipientEntry createTokenizedEntry(final String token) {
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001261 if (TextUtils.isEmpty(token)) {
1262 return null;
1263 }
mindyp5e60c2b2012-11-06 17:47:40 -08001264 if (isPhoneQuery() && isPhoneNumber(token)) {
Tom Taylor0ba91332013-03-21 10:28:50 -07001265 return RecipientEntry.constructFakePhoneEntry(token, true);
mindyp5e60c2b2012-11-06 17:47:40 -08001266 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001267 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
mindypf30a4282012-12-03 12:16:33 -08001268 boolean isValid = isValid(token);
1269 if (isValid && tokens != null && tokens.length > 0) {
Mindy Pereiraee58f492011-08-08 13:16:46 -07001270 // If we can get a name from tokenizing, then generate an entry from
1271 // this.
Jin Caoffc01112014-12-15 16:24:37 -08001272 String display = tokens[0].getName();
Mindy Pereira01382d72011-07-15 16:52:32 -07001273 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001274 return RecipientEntry.constructGeneratedEntry(display, tokens[0].getAddress(),
1275 isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001276 } else {
1277 display = tokens[0].getAddress();
1278 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001279 return RecipientEntry.constructFakeEntry(display, isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001280 }
Mindy Pereira01382d72011-07-15 16:52:32 -07001281 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001282 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001283 // Unable to validate the token or to create a valid token from it.
1284 // Just create a chip the user can edit.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001285 String validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001286 if (mValidator != null && !isValid) {
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001287 // Try fixing up the entry using the validator.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001288 validatedToken = mValidator.fixText(token).toString();
1289 if (!TextUtils.isEmpty(validatedToken)) {
1290 if (validatedToken.contains(token)) {
mindypf30a4282012-12-03 12:16:33 -08001291 // protect against the case of a validator with a null
1292 // domain,
Mindy Pereiradbb85602011-09-16 14:02:14 -07001293 // which doesn't add a domain to the token
1294 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
1295 if (tokenized.length > 0) {
1296 validatedToken = tokenized[0].getAddress();
mindypf30a4282012-12-03 12:16:33 -08001297 isValid = true;
Mindy Pereiradbb85602011-09-16 14:02:14 -07001298 }
1299 } else {
mindypf30a4282012-12-03 12:16:33 -08001300 // We ran into a case where the token was invalid and
1301 // removed
1302 // by the validator. In this case, just use the original
1303 // token
Mindy Pereiradbb85602011-09-16 14:02:14 -07001304 // and let the user sort out the error chip.
1305 validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001306 isValid = false;
Erik184d3772011-08-04 16:07:00 -07001307 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001308 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001309 }
Mindy Pereiraee58f492011-08-08 13:16:46 -07001310 // Otherwise, fallback to just creating an editable email address chip.
mindypf30a4282012-12-03 12:16:33 -08001311 return RecipientEntry.constructFakeEntry(
1312 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid);
Mindy Pereira01382d72011-07-15 16:52:32 -07001313 }
1314
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001315 private boolean isValid(String text) {
1316 return mValidator == null ? true : mValidator.isValid(text);
1317 }
1318
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001319 private static String tokenizeAddress(String destination) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001320 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
1321 if (tokens != null && tokens.length > 0) {
1322 return tokens[0].getAddress();
1323 }
1324 return destination;
Mindy Pereira3bb52162011-07-01 14:52:22 -07001325 }
1326
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001327 @Override
Mindy Pereiracd611952011-06-01 17:02:20 -07001328 public void setTokenizer(Tokenizer tokenizer) {
1329 mTokenizer = tokenizer;
1330 super.setTokenizer(mTokenizer);
1331 }
1332
Mindy Pereiraa8166902011-06-09 17:53:23 -07001333 @Override
1334 public void setValidator(Validator validator) {
1335 mValidator = validator;
1336 super.setValidator(validator);
1337 }
1338
1339 /**
1340 * We cannot use the default mechanism for replaceText. Instead,
1341 * we override onItemClickListener so we can get all the associated
1342 * contact information including display text, address, and id.
1343 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001344 @Override
1345 protected void replaceText(CharSequence text) {
1346 return;
1347 }
1348
Mindy Pereiraa8166902011-06-09 17:53:23 -07001349 /**
1350 * Dismiss any selected chips when the back key is pressed.
1351 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001352 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001353 public boolean onKeyPreIme(int keyCode, @NonNull KeyEvent event) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001354 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) {
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001355 clearSelectedChip();
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001356 return true;
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001357 }
1358 return super.onKeyPreIme(keyCode, event);
1359 }
1360
Mindy Pereiraa8166902011-06-09 17:53:23 -07001361 /**
1362 * Monitor key presses in this view to see if the user types
1363 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
1364 * If the user has entered text that has contact matches and types
1365 * a commit key, create a chip from the topmost matching contact.
1366 * If the user has entered text that has no contact matches and types
1367 * a commit key, then create a chip from the text they have entered.
1368 */
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001369 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001370 public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001371 switch (keyCode) {
Mindy Pereira0f0df292011-06-16 20:49:51 -07001372 case KeyEvent.KEYCODE_TAB:
1373 if (event.hasNoModifiers()) {
1374 if (mSelectedChip != null) {
1375 clearSelectedChip();
1376 } else {
1377 commitDefault();
1378 }
Mindy Pereira0f0df292011-06-16 20:49:51 -07001379 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001380 break;
Mindy Pereiracd611952011-06-01 17:02:20 -07001381 }
1382 return super.onKeyUp(keyCode, event);
1383 }
1384
Mindy Pereira0f0df292011-06-16 20:49:51 -07001385 private boolean focusNext() {
1386 View next = focusSearch(View.FOCUS_DOWN);
1387 if (next != null) {
1388 next.requestFocus();
1389 return true;
1390 }
1391 return false;
1392 }
1393
Mindy Pereira34214202011-06-09 20:05:32 -07001394 /**
1395 * Create a chip from the default selection. If the popup is showing, the
Scott Kennedye4945e92014-04-21 20:17:43 -07001396 * default is the selected item (if one is selected), or the first item, in the popup
1397 * suggestions list. Otherwise, it is whatever the user had typed in. End represents where the
1398 * tokenizer should search for a token to turn into a chip.
Mindy Pereira34214202011-06-09 20:05:32 -07001399 * @return If a chip was created from a real contact.
1400 */
Mindy Pereiraa8166902011-06-09 17:53:23 -07001401 private boolean commitDefault() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001402 // If there is no tokenizer, don't try to commit.
1403 if (mTokenizer == null) {
1404 return false;
1405 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001406 Editable editable = getText();
Mindy Pereira34214202011-06-09 20:05:32 -07001407 int end = getSelectionEnd();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001408 int start = mTokenizer.findTokenStart(editable, end);
Mindy Pereira2b4ffc52011-06-20 13:20:09 -07001409
Mindy Pereira79fb4362011-06-21 14:37:07 -07001410 if (shouldCreateChip(start, end)) {
1411 int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1412 // In the middle of chip; treat this as an edit
1413 // and commit the whole token.
mindyp4f82d882012-11-08 16:30:27 -08001414 whatEnd = movePastTerminators(whatEnd);
Mindy Pereira79fb4362011-06-21 14:37:07 -07001415 if (whatEnd != getSelectionEnd()) {
1416 handleEdit(start, whatEnd);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001417 return true;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001418 }
1419 return commitChip(start, end , editable);
1420 }
1421 return false;
1422 }
1423
1424 private void commitByCharacter() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001425 // We can't possibly commit by character if we can't tokenize.
1426 if (mTokenizer == null) {
1427 return;
1428 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001429 Editable editable = getText();
1430 int end = getSelectionEnd();
1431 int start = mTokenizer.findTokenStart(editable, end);
1432 if (shouldCreateChip(start, end)) {
1433 commitChip(start, end, editable);
1434 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001435 setSelection(getText().length());
Mindy Pereira79fb4362011-06-21 14:37:07 -07001436 }
1437
1438 private boolean commitChip(int start, int end, Editable editable) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07001439 ListAdapter adapter = getAdapter();
1440 if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
Tom Taylorc7a87f02012-05-03 15:21:08 -07001441 && end == getSelectionEnd() && !isPhoneQuery()) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001442 // let's choose the selected or first entry if only the input text is NOT an email
1443 // address so we won't try to replace the user's potentially correct but
1444 // new/unencountered email input
Jin Caob3b248a2014-04-11 10:43:50 -07001445 if (!isValidEmailAddress(editable.toString().substring(start, end).trim())) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001446 final int selectedPosition = getListSelection();
1447 if (selectedPosition == -1) {
1448 // Nothing is selected; use the first item
1449 submitItemAtPosition(0);
1450 } else {
1451 submitItemAtPosition(selectedPosition);
1452 }
Jin Caob3b248a2014-04-11 10:43:50 -07001453 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001454 dismissDropDown();
1455 return true;
1456 } else {
1457 int tokenEnd = mTokenizer.findTokenEnd(editable, start);
Mindy Pereira20c9d622011-10-12 13:18:04 -07001458 if (editable.length() > tokenEnd + 1) {
1459 char charAt = editable.charAt(tokenEnd + 1);
1460 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1461 tokenEnd++;
1462 }
Mindy Pereirad7192502011-09-22 08:04:45 -07001463 }
Mindy Pereira62397a52011-10-03 13:46:43 -07001464 String text = editable.toString().substring(start, tokenEnd).trim();
Mindy Pereira79fb4362011-06-21 14:37:07 -07001465 clearComposingText();
Jin Caoffc01112014-12-15 16:24:37 -08001466 if (text.length() > 0 && !text.equals(" ")) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001467 RecipientEntry entry = createTokenizedEntry(text);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001468 if (entry != null) {
1469 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Jin Caoffc01112014-12-15 16:24:37 -08001470 CharSequence chipText = createChip(entry);
Mindy Pereiraee6d83f2011-10-03 14:25:07 -07001471 if (chipText != null && start > -1 && end > -1) {
Mindy Pereiraf177bda2011-09-15 11:23:49 -07001472 editable.replace(start, end, chipText);
1473 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001474 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07001475 // Only dismiss the dropdown if it is related to the text we
1476 // just committed.
1477 // For paste, it may not be as there are possibly multiple
1478 // tokens being added.
1479 if (end == getSelectionEnd()) {
1480 dismissDropDown();
1481 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001482 sanitizeBetween();
Mindy Pereira0f0df292011-06-16 20:49:51 -07001483 return true;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001484 }
1485 }
1486 return false;
Mindy Pereira05dbd332011-06-03 09:37:44 -07001487 }
1488
Mindy Pereira01162ce2011-09-20 12:21:55 -07001489 // Visible for testing.
1490 /* package */ void sanitizeBetween() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001491 // Don't sanitize while we are waiting for content to chipify.
1492 if (mPendingChipsCount > 0) {
1493 return;
1494 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001495 // Find the last chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08001496 DrawableRecipientChip[] recips = getSortedRecipients();
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001497 if (recips != null && recips.length > 0) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001498 DrawableRecipientChip last = recips[recips.length - 1];
1499 DrawableRecipientChip beforeLast = null;
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001500 if (recips.length > 1) {
1501 beforeLast = recips[recips.length - 2];
1502 }
1503 int startLooking = 0;
1504 int end = getSpannable().getSpanStart(last);
1505 if (beforeLast != null) {
1506 startLooking = getSpannable().getSpanEnd(beforeLast);
Mindy Pereira399bda82011-09-20 11:18:26 -07001507 Editable text = getText();
Mindy Pereira01162ce2011-09-20 12:21:55 -07001508 if (startLooking == -1 || startLooking > text.length() - 1) {
Mindy Pereira399bda82011-09-20 11:18:26 -07001509 // There is nothing after this chip.
1510 return;
1511 }
1512 if (text.charAt(startLooking) == ' ') {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001513 startLooking++;
1514 }
1515 }
Mindy Pereirae13775c2011-11-17 11:14:12 -08001516 if (startLooking >= 0 && end >= 0 && startLooking < end) {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001517 getText().delete(startLooking, end);
1518 }
1519 }
1520 }
1521
Mindy Pereira79fb4362011-06-21 14:37:07 -07001522 private boolean shouldCreateChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001523 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
Mindy Pereira32366d42011-07-24 12:39:30 -07001524 }
1525
1526 private boolean alreadyHasChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001527 if (mNoChips) {
1528 return true;
1529 }
Scott Kennedy194d4272013-03-06 22:06:45 -08001530 DrawableRecipientChip[] chips =
1531 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Jin Caoffc01112014-12-15 16:24:37 -08001532 return chips != null && chips.length > 0;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001533 }
1534
1535 private void handleEdit(int start, int end) {
Mindy Pereiraa49e7fa2011-09-13 08:01:36 -07001536 if (start == -1 || end == -1) {
1537 // This chip no longer exists in the field.
1538 dismissDropDown();
1539 return;
1540 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001541 // This is in the middle of a chip, so select out the whole chip
1542 // and commit it.
1543 Editable editable = getText();
1544 setSelection(end);
1545 String text = getText().toString().substring(start, end);
Mindy Pereirafe52b972011-09-16 11:55:57 -07001546 if (!TextUtils.isEmpty(text)) {
mindypf30a4282012-12-03 12:16:33 -08001547 RecipientEntry entry = RecipientEntry.constructFakeEntry(text, isValid(text));
Mindy Pereirafe52b972011-09-16 11:55:57 -07001548 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Jin Caoffc01112014-12-15 16:24:37 -08001549 CharSequence chipText = createChip(entry);
Mindy Pereira5cfd6fe2011-10-20 15:36:24 -07001550 int selEnd = getSelectionEnd();
1551 if (chipText != null && start > -1 && selEnd > -1) {
1552 editable.replace(start, selEnd, chipText);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001553 }
Mindy Pereirafe52b972011-09-16 11:55:57 -07001554 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001555 dismissDropDown();
Mindy Pereira64af2da2011-06-15 11:14:07 -07001556 }
1557
Mindy Pereiraa8166902011-06-09 17:53:23 -07001558 /**
1559 * If there is a selected chip, delegate the key events
1560 * to the selected chip.
1561 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001562 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001563 public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001564 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1565 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1566 mAlternatesPopup.dismiss();
1567 }
1568 removeChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001569 }
1570
Scott Kennedy2fe0cff2013-02-14 18:39:37 -08001571 switch (keyCode) {
1572 case KeyEvent.KEYCODE_ENTER:
1573 case KeyEvent.KEYCODE_DPAD_CENTER:
1574 if (event.hasNoModifiers()) {
1575 if (commitDefault()) {
1576 return true;
1577 }
1578 if (mSelectedChip != null) {
1579 clearSelectedChip();
1580 return true;
1581 } else if (focusNext()) {
1582 return true;
1583 }
1584 }
1585 break;
1586 }
1587
Mindy Pereiracd611952011-06-01 17:02:20 -07001588 return super.onKeyDown(keyCode, event);
1589 }
1590
Mindy Pereira01162ce2011-09-20 12:21:55 -07001591 // Visible for testing.
1592 /* package */ Spannable getSpannable() {
Erike33555f2011-06-21 14:20:20 -07001593 return getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001594 }
1595
Scott Kennedy194d4272013-03-06 22:06:45 -08001596 private int getChipStart(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001597 return getSpannable().getSpanStart(chip);
1598 }
1599
Scott Kennedy194d4272013-03-06 22:06:45 -08001600 private int getChipEnd(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001601 return getSpannable().getSpanEnd(chip);
1602 }
1603
Mindy Pereiracd611952011-06-01 17:02:20 -07001604 /**
1605 * Instead of filtering on the entire contents of the edit box,
1606 * this subclass method filters on the range from
1607 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1608 * if the length of that range meets or exceeds {@link #getThreshold}
1609 * and makes sure that the range is not already a Chip.
1610 */
1611 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001612 protected void performFiltering(@NonNull CharSequence text, int keyCode) {
mindyp093ecdd2012-12-14 10:40:51 -08001613 boolean isCompletedToken = isCompletedToken(text);
1614 if (enoughToFilter() && !isCompletedToken) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001615 int end = getSelectionEnd();
1616 int start = mTokenizer.findTokenStart(text, end);
1617 // If this is a RecipientChip, don't filter
1618 // on its contents.
1619 Spannable span = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001620 DrawableRecipientChip[] chips = span.getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001621 if (chips != null && chips.length > 0) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001622 dismissDropDown();
Mindy Pereiracd611952011-06-01 17:02:20 -07001623 return;
1624 }
mindyp093ecdd2012-12-14 10:40:51 -08001625 } else if (isCompletedToken) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001626 dismissDropDown();
mindyp093ecdd2012-12-14 10:40:51 -08001627 return;
Mindy Pereiracd611952011-06-01 17:02:20 -07001628 }
1629 super.performFiltering(text, keyCode);
1630 }
1631
Mindy Pereira20c9d622011-10-12 13:18:04 -07001632 // Visible for testing.
1633 /*package*/ boolean isCompletedToken(CharSequence text) {
1634 if (TextUtils.isEmpty(text)) {
1635 return false;
1636 }
1637 // Check to see if this is a completed token before filtering.
1638 int end = text.length();
1639 int start = mTokenizer.findTokenStart(text, end);
1640 String token = text.toString().substring(start, end).trim();
1641 if (!TextUtils.isEmpty(token)) {
1642 char atEnd = token.charAt(token.length() - 1);
1643 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1644 }
1645 return false;
1646 }
1647
Jin Cao49744b02014-11-06 18:40:27 -08001648 /**
1649 * Clears the selected chip if there is one (and dismissing any popups related to the selected
1650 * chip in the process).
1651 */
1652 public void clearSelectedChip() {
Mindy Pereiracd611952011-06-01 17:02:20 -07001653 if (mSelectedChip != null) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001654 unselectChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001655 mSelectedChip = null;
1656 }
Mindy Pereirab86dcd52011-06-02 13:52:30 -07001657 setCursorVisible(true);
Jin Caoffc01112014-12-15 16:24:37 -08001658 setSelection(getText().length());
Mindy Pereiracd611952011-06-01 17:02:20 -07001659 }
1660
Mindy Pereiraa8166902011-06-09 17:53:23 -07001661 /**
1662 * Monitor touch events in the RecipientEditTextView.
1663 * If the view does not have focus, any tap on the view
1664 * will just focus the view. If the view has focus, determine
1665 * if the touch target is a recipient chip. If it is and the chip
1666 * is not selected, select it and clear any other selected chips.
1667 * If it isn't, then select that chip.
1668 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001669 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001670 public boolean onTouchEvent(@NonNull MotionEvent event) {
Mindy Pereira05dbd332011-06-03 09:37:44 -07001671 if (!isFocused()) {
1672 // Ignore any chip taps until this view is focused.
1673 return super.onTouchEvent(event);
1674 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001675 boolean handled = super.onTouchEvent(event);
Mindy Pereira05dbd332011-06-03 09:37:44 -07001676 int action = event.getAction();
Mindy Pereiracd611952011-06-01 17:02:20 -07001677 boolean chipWasSelected = false;
Mindy Pereira2e905902011-09-08 16:17:04 -07001678 if (mSelectedChip == null) {
Mindy Pereira1d1ec852011-08-09 16:49:33 -07001679 mGestureDetector.onTouchEvent(event);
1680 }
Mindy Pereirabfedc1e2011-09-07 12:17:12 -07001681 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001682 float x = event.getX();
1683 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07001684 int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08001685 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereiracd611952011-06-01 17:02:20 -07001686 if (currentChip != null) {
Jin Caoffc01112014-12-15 16:24:37 -08001687 if (mSelectedChip != null && mSelectedChip != currentChip) {
1688 clearSelectedChip();
1689 selectChip(currentChip);
1690 } else if (mSelectedChip == null) {
1691 commitDefault();
1692 selectChip(currentChip);
1693 } else {
1694 onClick(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001695 }
1696 chipWasSelected = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001697 handled = true;
mindyp5e60c2b2012-11-06 17:47:40 -08001698 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07001699 chipWasSelected = true;
Mindy Pereiracd611952011-06-01 17:02:20 -07001700 }
1701 }
1702 if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1703 clearSelectedChip();
1704 }
1705 return handled;
1706 }
1707
Scott Kennedy272aae02013-04-05 17:17:24 -07001708 private void showAlternates(final DrawableRecipientChip currentChip,
Jin Cao9b166202014-08-08 13:26:14 -07001709 final ListPopupWindow alternatesPopup) {
Scott Kennedy272aae02013-04-05 17:17:24 -07001710 new AsyncTask<Void, Void, ListAdapter>() {
1711 @Override
1712 protected ListAdapter doInBackground(final Void... params) {
1713 return createAlternatesAdapter(currentChip);
1714 }
1715
Alice Yang6b7110f2013-04-26 12:50:35 -07001716 @Override
Scott Kennedy272aae02013-04-05 17:17:24 -07001717 protected void onPostExecute(final ListAdapter result) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07001718 if (!mAttachedToWindow) {
1719 return;
1720 }
Scott Kennedy272aae02013-04-05 17:17:24 -07001721 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07001722 int bottomOffset = calculateOffsetFromBottomToTop(line);
1723
Scott Kennedy272aae02013-04-05 17:17:24 -07001724 // Align the alternates popup with the left side of the View,
1725 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07001726 alternatesPopup.setAnchorView((mAlternatePopupAnchor != null) ?
1727 mAlternatePopupAnchor : RecipientEditTextView.this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07001728 alternatesPopup.setVerticalOffset(bottomOffset);
Scott Kennedy272aae02013-04-05 17:17:24 -07001729 alternatesPopup.setAdapter(result);
1730 alternatesPopup.setOnItemClickListener(mAlternatesListener);
1731 // Clear the checked item.
1732 mCheckedItem = -1;
1733 alternatesPopup.show();
1734 ListView listView = alternatesPopup.getListView();
1735 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1736 // Checked item would be -1 if the adapter has not
1737 // loaded the view that should be checked yet. The
1738 // variable will be set correctly when onCheckedItemChanged
1739 // is called in a separate thread.
1740 if (mCheckedItem != -1) {
1741 listView.setItemChecked(mCheckedItem, true);
1742 mCheckedItem = -1;
1743 }
1744 }
1745 }.execute((Void[]) null);
Mindy Pereira95a69252011-06-17 15:02:03 -07001746 }
1747
Scott Kennedy194d4272013-03-06 22:06:45 -08001748 private ListAdapter createAlternatesAdapter(DrawableRecipientChip chip) {
Scott Kennedy7a4e6772013-11-21 14:31:33 -08001749 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(),
1750 chip.getDirectoryId(), chip.getLookupKey(), chip.getDataId(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001751 getAdapter().getQueryType(), this, mDropdownChipLayouter,
1752 constructStateListDeleteDrawable());
Mindy Pereira95a69252011-06-17 15:02:03 -07001753 }
1754
Scott Kennedy194d4272013-03-06 22:06:45 -08001755 private ListAdapter createSingleAddressAdapter(DrawableRecipientChip currentChip) {
Kevin Linb10d1c62014-01-24 12:45:00 -08001756 return new SingleRecipientArrayAdapter(getContext(), currentChip.getEntry(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001757 mDropdownChipLayouter, constructStateListDeleteDrawable());
1758 }
1759
1760 private StateListDrawable constructStateListDeleteDrawable() {
1761 // Construct the StateListDrawable from deleteDrawable
1762 StateListDrawable deleteDrawable = new StateListDrawable();
Jin Caoa21fd882014-08-10 13:07:11 -07001763 if (!mDisableDelete) {
1764 deleteDrawable.addState(new int[]{android.R.attr.state_activated}, mChipDelete);
1765 }
Jin Cao4db8ccc2014-07-30 10:11:07 -07001766 deleteDrawable.addState(new int[0], null);
1767 return deleteDrawable;
Mindy Pereira01382d72011-07-15 16:52:32 -07001768 }
1769
Andy Stadleraa2afff2011-08-04 16:22:47 -07001770 @Override
Mindy Pereira95a69252011-06-17 15:02:03 -07001771 public void onCheckedItemChanged(int position) {
1772 ListView listView = mAlternatesPopup.getListView();
1773 if (listView != null && listView.getCheckedItemCount() == 0) {
1774 listView.setItemChecked(position, true);
Mindy Pereira95a69252011-06-17 15:02:03 -07001775 }
Mindy Pereira98b547f2011-09-08 09:27:39 -07001776 mCheckedItem = position;
Mindy Pereira95a69252011-06-17 15:02:03 -07001777 }
1778
Scott Kennedy1650ef62013-08-02 21:56:47 -07001779 private int putOffsetInRange(final float x, final float y) {
1780 final int offset;
1781
1782 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1783 offset = getOffsetForPosition(x, y);
1784 } else {
1785 offset = supportGetOffsetForPosition(x, y);
1786 }
1787
1788 return putOffsetInRange(offset);
1789 }
1790
Mindy Pereiracd611952011-06-01 17:02:20 -07001791 // TODO: This algorithm will need a lot of tweaking after more people have used
1792 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1793 // what comes before the finger.
1794 private int putOffsetInRange(int o) {
1795 int offset = o;
1796 Editable text = getText();
1797 int length = text.length();
1798 // Remove whitespace from end to find "real end"
1799 int realLength = length;
1800 for (int i = length - 1; i >= 0; i--) {
1801 if (text.charAt(i) == ' ') {
1802 realLength--;
1803 } else {
1804 break;
1805 }
1806 }
1807
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001808 // If the offset is beyond or at the end of the text,
1809 // leave it alone.
1810 if (offset >= realLength) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001811 return offset;
1812 }
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001813 Editable editable = getText();
Mindy Pereirab88ee452011-06-02 11:07:43 -07001814 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001815 // Keep walking backward!
1816 offset--;
1817 }
1818 return offset;
1819 }
1820
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001821 private static int findText(Editable text, int offset) {
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001822 if (text.charAt(offset) != ' ') {
1823 return offset;
1824 }
1825 return -1;
1826 }
1827
Scott Kennedy194d4272013-03-06 22:06:45 -08001828 private DrawableRecipientChip findChip(int offset) {
Jin Caoffc01112014-12-15 16:24:37 -08001829 final Spannable span = getSpannable();
1830 final DrawableRecipientChip[] chips =
1831 span.getSpans(0, span.length(), DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001832 // Find the chip that contains this offset.
Jin Caoffc01112014-12-15 16:24:37 -08001833 for (DrawableRecipientChip chip : chips) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001834 int start = getChipStart(chip);
1835 int end = getChipEnd(chip);
1836 if (offset >= start && offset <= end) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001837 return chip;
1838 }
1839 }
1840 return null;
1841 }
1842
Mindy Pereira01162ce2011-09-20 12:21:55 -07001843 // Visible for testing.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001844 // Use this method to generate text to add to the list of addresses.
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001845 /* package */String createAddressText(RecipientEntry entry) {
Mindy Pereira3ea99552011-09-19 10:50:31 -07001846 String display = entry.getDisplayName();
1847 String address = entry.getDestination();
1848 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1849 display = null;
1850 }
Tom Taylorabff6062012-04-17 09:04:56 -07001851 String trimmedDisplayText;
Tom Taylorc7a87f02012-05-03 15:21:08 -07001852 if (isPhoneQuery() && isPhoneNumber(address)) {
Tom Taylorabff6062012-04-17 09:04:56 -07001853 trimmedDisplayText = address.trim();
1854 } else {
1855 if (address != null) {
1856 // Tokenize out the address in case the address already
1857 // contained the username as well.
1858 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1859 if (tokenized != null && tokenized.length > 0) {
1860 address = tokenized[0].getAddress();
1861 }
Mindy Pereiraee48f732011-09-20 08:13:39 -07001862 }
Tom Taylorabff6062012-04-17 09:04:56 -07001863 Rfc822Token token = new Rfc822Token(display, address, null);
1864 trimmedDisplayText = token.toString().trim();
Mindy Pereirad8c15c32011-09-19 15:02:05 -07001865 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001866 int index = trimmedDisplayText.indexOf(",");
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001867 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1868 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001869 .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1870 }
1871
1872 // Visible for testing.
1873 // Use this method to generate text to display in a chip.
1874 /*package*/ String createChipDisplayText(RecipientEntry entry) {
1875 String display = entry.getDisplayName();
1876 String address = entry.getDestination();
1877 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1878 display = null;
1879 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001880 if (!TextUtils.isEmpty(display)) {
1881 return display;
1882 } else if (!TextUtils.isEmpty(address)){
1883 return address;
1884 } else {
1885 return new Rfc822Token(display, address, null).toString();
1886 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001887 }
1888
Jin Caoffc01112014-12-15 16:24:37 -08001889 private CharSequence createChip(RecipientEntry entry) {
Jin Cao4db8ccc2014-07-30 10:11:07 -07001890 final String displayText = createAddressText(entry);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001891 if (TextUtils.isEmpty(displayText)) {
1892 return null;
1893 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001894 // Always leave a blank space at the end of a chip.
Jin Cao4db8ccc2014-07-30 10:11:07 -07001895 final int textLength = displayText.length() - 1;
1896 final SpannableString chipText = new SpannableString(displayText);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001897 if (!mNoChips) {
1898 try {
Jin Caoffc01112014-12-15 16:24:37 -08001899 DrawableRecipientChip chip = constructChipSpan(entry);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001900 chipText.setSpan(chip, 0, textLength,
1901 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1902 chip.setOriginalText(chipText.toString());
1903 } catch (NullPointerException e) {
1904 Log.e(TAG, e.getMessage(), e);
1905 return null;
1906 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001907 }
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001908 onChipCreated(entry);
Mindy Pereiracd611952011-06-01 17:02:20 -07001909 return chipText;
1910 }
1911
Mindy Pereiraa8166902011-06-09 17:53:23 -07001912 /**
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001913 * A callback for subclasses to use to know when a chip was created with the
1914 * given RecipientEntry.
1915 */
1916 protected void onChipCreated(RecipientEntry entry) {}
1917
1918 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -07001919 * When an item in the suggestions list has been clicked, create a chip from the
1920 * contact information of the selected item.
1921 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001922 @Override
1923 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tom Taylor114c8932013-04-10 13:11:05 -07001924 if (position < 0) {
1925 return;
1926 }
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001927
1928 final int charactersTyped = submitItemAtPosition(position);
1929 if (charactersTyped > -1 && mRecipientEntryItemClickedListener != null) {
1930 mRecipientEntryItemClickedListener
1931 .onRecipientEntryItemClicked(charactersTyped, position);
1932 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001933 }
1934
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001935 private int submitItemAtPosition(int position) {
Scott Kennedy858e0942013-10-10 11:50:01 -07001936 RecipientEntry entry = createValidatedEntry(getAdapter().getItem(position));
Erikf7eaa5f2011-07-14 17:02:07 -07001937 if (entry == null) {
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001938 return -1;
Erikf7eaa5f2011-07-14 17:02:07 -07001939 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001940 clearComposingText();
1941
1942 int end = getSelectionEnd();
1943 int start = mTokenizer.findTokenStart(getText(), end);
1944
1945 Editable editable = getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001946 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Jin Caoffc01112014-12-15 16:24:37 -08001947 CharSequence chip = createChip(entry);
Mindy Pereira005b2e22011-11-01 10:26:58 -07001948 if (chip != null && start >= 0 && end >= 0) {
Mindy Pereirae90bfad2011-07-26 14:51:41 -07001949 editable.replace(start, end, chip);
1950 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001951 sanitizeBetween();
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001952
1953 return end - start;
Mindy Pereiracd611952011-06-01 17:02:20 -07001954 }
1955
Mindy Pereira3bb52162011-07-01 14:52:22 -07001956 private RecipientEntry createValidatedEntry(RecipientEntry item) {
1957 if (item == null) {
1958 return null;
1959 }
1960 final RecipientEntry entry;
1961 // If the display name and the address are the same, or if this is a
1962 // valid contact, but the destination is invalid, then make this a fake
1963 // recipient that is editable.
1964 String destination = item.getDestination();
mindyp5e60c2b2012-11-06 17:47:40 -08001965 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1966 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
mindypf30a4282012-12-03 12:16:33 -08001967 destination, item.isValid());
mindyp5e60c2b2012-11-06 17:47:40 -08001968 } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
Mindy Pereirab4e244a2011-10-14 11:13:29 -07001969 && (TextUtils.isEmpty(item.getDisplayName())
1970 || TextUtils.equals(item.getDisplayName(), destination)
1971 || (mValidator != null && !mValidator.isValid(destination)))) {
mindypf30a4282012-12-03 12:16:33 -08001972 entry = RecipientEntry.constructFakeEntry(destination, item.isValid());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001973 } else {
1974 entry = item;
1975 }
1976 return entry;
1977 }
1978
Mindy Pereira01162ce2011-09-20 12:21:55 -07001979 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08001980 /* package */DrawableRecipientChip[] getSortedRecipients() {
1981 DrawableRecipientChip[] recips = getSpannable()
1982 .getSpans(0, getText().length(), DrawableRecipientChip.class);
1983 ArrayList<DrawableRecipientChip> recipientsList = new ArrayList<DrawableRecipientChip>(
1984 Arrays.asList(recips));
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001985 final Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001986 Collections.sort(recipientsList, new Comparator<DrawableRecipientChip>() {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001987
1988 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08001989 public int compare(DrawableRecipientChip first, DrawableRecipientChip second) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001990 int firstStart = spannable.getSpanStart(first);
1991 int secondStart = spannable.getSpanStart(second);
1992 if (firstStart < secondStart) {
1993 return -1;
1994 } else if (firstStart > secondStart) {
1995 return 1;
1996 } else {
1997 return 0;
1998 }
1999 }
2000 });
Scott Kennedy194d4272013-03-06 22:06:45 -08002001 return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002002 }
2003
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002004 @Override
2005 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2006 return false;
2007 }
2008
2009 @Override
2010 public void onDestroyActionMode(ActionMode mode) {
2011 }
2012
2013 @Override
2014 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2015 return false;
2016 }
2017
Mindy Pereiraa8166902011-06-09 17:53:23 -07002018 /**
2019 * No chips are selectable.
2020 */
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002021 @Override
2022 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2023 return false;
2024 }
2025
Mindy Pereirad7192502011-09-22 08:04:45 -07002026 // Visible for testing.
Jin Cao6c2a0162014-08-17 15:00:50 -07002027 /* package */ReplacementDrawableSpan getMoreChip() {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002028 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
2029 MoreImageSpan.class);
2030 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
2031 }
2032
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002033 private MoreImageSpan createMoreSpan(int count) {
2034 String moreText = String.format(mMoreItem.getText().toString(), count);
Jin Cao6c2a0162014-08-17 15:00:50 -07002035 mWorkPaint.set(getPaint());
2036 mWorkPaint.setTextSize(mMoreItem.getTextSize());
2037 mWorkPaint.setColor(mMoreItem.getCurrentTextColor());
2038 final int width = (int) mWorkPaint.measureText(moreText) + mMoreItem.getPaddingLeft()
Mindy Pereira750e6e52011-07-25 11:51:30 -07002039 + mMoreItem.getPaddingRight();
Jin Cao6c2a0162014-08-17 15:00:50 -07002040 final int height = (int) mChipHeight;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002041 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2042 Canvas canvas = new Canvas(drawable);
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002043 int adjustedHeight = height;
2044 Layout layout = getLayout();
2045 if (layout != null) {
2046 adjustedHeight -= layout.getLineDescent(0);
2047 }
Jin Cao6c2a0162014-08-17 15:00:50 -07002048 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, mWorkPaint);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002049
2050 Drawable result = new BitmapDrawable(getResources(), drawable);
2051 result.setBounds(0, 0, width, height);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002052 return new MoreImageSpan(result);
2053 }
2054
2055 // Visible for testing.
2056 /*package*/ void createMoreChipPlainText() {
2057 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
2058 Editable text = getText();
2059 int start = 0;
2060 int end = start;
2061 for (int i = 0; i < CHIP_LIMIT; i++) {
2062 end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2063 start = end; // move to the next token and get its end.
2064 }
2065 // Now, count total addresses.
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002066 int tokenCount = countTokens(text);
2067 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
2068 SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
2069 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2070 text.replace(end, text.length(), chipText);
2071 mMoreChip = moreSpan;
2072 }
2073
2074 // Visible for testing.
2075 /* package */int countTokens(Editable text) {
2076 int tokenCount = 0;
2077 int start = 0;
2078 while (start < text.length()) {
2079 start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2080 tokenCount++;
2081 if (start >= text.length()) {
2082 break;
2083 }
2084 }
2085 return tokenCount;
2086 }
2087
2088 /**
2089 * Create the more chip. The more chip is text that replaces any chips that
2090 * do not fit in the pre-defined available space when the
2091 * RecipientEditTextView loses focus.
2092 */
2093 // Visible for testing.
2094 /* package */ void createMoreChip() {
2095 if (mNoChips) {
2096 createMoreChipPlainText();
2097 return;
2098 }
2099
2100 if (!mShouldShrink) {
2101 return;
2102 }
Jin Cao6c2a0162014-08-17 15:00:50 -07002103 ReplacementDrawableSpan[] tempMore = getSpannable().getSpans(0, getText().length(),
2104 MoreImageSpan.class);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002105 if (tempMore.length > 0) {
2106 getSpannable().removeSpan(tempMore[0]);
2107 }
Scott Kennedy194d4272013-03-06 22:06:45 -08002108 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002109
2110 if (recipients == null || recipients.length <= CHIP_LIMIT) {
Mindy Pereira3bb52162011-07-01 14:52:22 -07002111 mMoreChip = null;
2112 return;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002113 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002114 Spannable spannable = getSpannable();
2115 int numRecipients = recipients.length;
2116 int overage = numRecipients - CHIP_LIMIT;
2117 MoreImageSpan moreSpan = createMoreSpan(overage);
Scott Kennedy194d4272013-03-06 22:06:45 -08002118 mRemovedSpans = new ArrayList<DrawableRecipientChip>();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002119 int totalReplaceStart = 0;
2120 int totalReplaceEnd = 0;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002121 Editable text = getText();
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002122 for (int i = numRecipients - overage; i < recipients.length; i++) {
2123 mRemovedSpans.add(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002124 if (i == numRecipients - overage) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002125 totalReplaceStart = spannable.getSpanStart(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002126 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002127 if (i == recipients.length - 1) {
2128 totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002129 }
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002130 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
2131 int spanStart = spannable.getSpanStart(recipients[i]);
2132 int spanEnd = spannable.getSpanEnd(recipients[i]);
2133 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
Mindy Pereira18529312011-06-28 11:00:52 -07002134 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002135 spannable.removeSpan(recipients[i]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002136 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002137 if (totalReplaceEnd < text.length()) {
2138 totalReplaceEnd = text.length();
2139 }
Mindy Pereira18529312011-06-28 11:00:52 -07002140 int end = Math.max(totalReplaceStart, totalReplaceEnd);
2141 int start = Math.min(totalReplaceStart, totalReplaceEnd);
2142 SpannableString chipText = new SpannableString(text.subSequence(start, end));
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002143 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereira18529312011-06-28 11:00:52 -07002144 text.replace(start, end, chipText);
Mindy Pereira3bb52162011-07-01 14:52:22 -07002145 mMoreChip = moreSpan;
mindyp5e60c2b2012-11-06 17:47:40 -08002146 // If adding the +more chip goes over the limit, resize accordingly.
2147 if (!isPhoneQuery() && getLineCount() > mMaxLines) {
2148 setMaxLines(getLineCount());
2149 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002150 }
2151
Mindy Pereiraa8166902011-06-09 17:53:23 -07002152 /**
2153 * Replace the more chip, if it exists, with all of the recipient chips it had
2154 * replaced when the RecipientEditTextView gains focus.
2155 */
Mindy Pereirad7192502011-09-22 08:04:45 -07002156 // Visible for testing.
2157 /*package*/ void removeMoreChip() {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002158 if (mMoreChip != null) {
2159 Spannable span = getSpannable();
2160 span.removeSpan(mMoreChip);
2161 mMoreChip = null;
2162 // Re-add the spans that were removed.
2163 if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
2164 // Recreate each removed span.
Scott Kennedy194d4272013-03-06 22:06:45 -08002165 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereira54effe92011-09-09 09:46:38 -07002166 // Start the search for tokens after the last currently visible
2167 // chip.
Mindy Pereiraee48f732011-09-20 08:13:39 -07002168 if (recipients == null || recipients.length == 0) {
2169 return;
2170 }
Mindy Pereira54effe92011-09-09 09:46:38 -07002171 int end = span.getSpanEnd(recipients[recipients.length - 1]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002172 Editable editable = getText();
Scott Kennedy194d4272013-03-06 22:06:45 -08002173 for (DrawableRecipientChip chip : mRemovedSpans) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002174 int chipStart;
Mindy Pereira3bb52162011-07-01 14:52:22 -07002175 int chipEnd;
2176 String token;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002177 // Need to find the location of the chip, again.
2178 token = (String) chip.getOriginalText();
Mindy Pereira54effe92011-09-09 09:46:38 -07002179 // As we find the matching recipient for the remove spans,
2180 // reduce the size of the string we need to search.
2181 // That way, if there are duplicates, we always find the correct
2182 // recipient.
2183 chipStart = editable.toString().indexOf(token, end);
Mindy Pereira54effe92011-09-09 09:46:38 -07002184 end = chipEnd = Math.min(editable.length(), chipStart + token.length());
Mindy Pereira0d8b77a2011-07-08 10:26:30 -07002185 // Only set the span if we found a matching token.
2186 if (chipStart != -1) {
2187 editable.setSpan(chip, chipStart, chipEnd,
2188 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
2189 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002190 }
2191 mRemovedSpans.clear();
2192 }
2193 }
2194 }
2195
Mindy Pereiracd611952011-06-01 17:02:20 -07002196 /**
Mindy Pereira95a69252011-06-17 15:02:03 -07002197 * Show specified chip as selected. If the RecipientChip is just an email address,
2198 * selecting the chip will take the contents of the chip and place it at
2199 * the end of the RecipientEditTextView for inline editing. If the
2200 * RecipientChip is a complete contact, then selecting the chip
Jin Caoffc01112014-12-15 16:24:37 -08002201 * will show a popup window with the address in use highlighted and any other
Mindy Pereira95a69252011-06-17 15:02:03 -07002202 * alternate addresses for the contact.
2203 * @param currentChip Chip to select.
Mindy Pereiracd611952011-06-01 17:02:20 -07002204 */
Jin Caoffc01112014-12-15 16:24:37 -08002205 private void selectChip(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002206 if (shouldShowEditableText(currentChip)) {
Mindy Pereira01382d72011-07-15 16:52:32 -07002207 CharSequence text = currentChip.getValue();
2208 Editable editable = getText();
mindypf30a4282012-12-03 12:16:33 -08002209 Spannable spannable = getSpannable();
2210 int spanStart = spannable.getSpanStart(currentChip);
2211 int spanEnd = spannable.getSpanEnd(currentChip);
2212 spannable.removeSpan(currentChip);
Jin Cao15a5ebc2014-09-18 16:43:32 -07002213 // Don't need leading space if it's the only chip
2214 if (spanEnd - spanStart == editable.length() - 1) {
2215 spanEnd++;
2216 }
mindypf30a4282012-12-03 12:16:33 -08002217 editable.delete(spanStart, spanEnd);
Mindy Pereira01382d72011-07-15 16:52:32 -07002218 setCursorVisible(true);
2219 setSelection(editable.length());
mindypf30a4282012-12-03 12:16:33 -08002220 editable.append(text);
Jin Caoffc01112014-12-15 16:24:37 -08002221 mSelectedChip = constructChipSpan(
2222 RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())));
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002223 } else {
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002224 final boolean showAddress =
2225 currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT ||
2226 getAdapter().forceShowAddress();
Jin Caoffc01112014-12-15 16:24:37 -08002227 if (showAddress && mNoChips) {
2228 return;
Mindy Pereiracd611952011-06-01 17:02:20 -07002229 }
Jin Caoffc01112014-12-15 16:24:37 -08002230 mSelectedChip = currentChip;
2231 setSelection(getText().getSpanEnd(mSelectedChip));
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07002232 setCursorVisible(false);
Jin Caoffc01112014-12-15 16:24:37 -08002233
2234 if (showAddress) {
2235 showAddress(currentChip, mAddressPopup);
2236 } else {
2237 showAlternates(currentChip, mAlternatesPopup);
2238 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002239 }
2240 }
2241
Scott Kennedy194d4272013-03-06 22:06:45 -08002242 private boolean shouldShowEditableText(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002243 long contactId = currentChip.getContactId();
2244 return contactId == RecipientEntry.INVALID_CONTACT
2245 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2246 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002247
Jin Cao9b166202014-08-08 13:26:14 -07002248 private void showAddress(final DrawableRecipientChip currentChip, final ListPopupWindow popup) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07002249 if (!mAttachedToWindow) {
2250 return;
2251 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002252 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07002253 int bottomOffset = calculateOffsetFromBottomToTop(line);
Mindy Pereira01382d72011-07-15 16:52:32 -07002254 // Align the alternates popup with the left side of the View,
2255 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07002256 popup.setAnchorView((mAlternatePopupAnchor != null) ? mAlternatePopupAnchor : this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07002257 popup.setVerticalOffset(bottomOffset);
Mindy Pereira01382d72011-07-15 16:52:32 -07002258 popup.setAdapter(createSingleAddressAdapter(currentChip));
2259 popup.setOnItemClickListener(new OnItemClickListener() {
2260 @Override
2261 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2262 unselectChip(currentChip);
Mindy Pereira01382d72011-07-15 16:52:32 -07002263 }
2264 });
2265 popup.show();
2266 ListView listView = popup.getListView();
2267 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2268 listView.setItemChecked(0, true);
2269 }
2270
Mindy Pereira95a69252011-06-17 15:02:03 -07002271 /**
2272 * Remove selection from this chip. Unselecting a RecipientChip will render
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002273 * the chip without a delete icon and with an unfocused background. This is
2274 * called when the RecipientChip no longer has focus.
Mindy Pereira95a69252011-06-17 15:02:03 -07002275 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002276 private void unselectChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002277 int start = getChipStart(chip);
2278 int end = getChipEnd(chip);
2279 Editable editable = getText();
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002280 mSelectedChip = null;
Mindy Pereira95a69252011-06-17 15:02:03 -07002281 if (start == -1 || end == -1) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002282 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002283 setSelection(editable.length());
2284 commitDefault();
Mindy Pereira95a69252011-06-17 15:02:03 -07002285 } else {
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002286 getSpannable().removeSpan(chip);
Mindy Pereira95a69252011-06-17 15:02:03 -07002287 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereira04da3252011-07-06 16:09:25 -07002288 editable.removeSpan(chip);
2289 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002290 if (!mNoChips) {
Jin Caoffc01112014-12-15 16:24:37 -08002291 editable.setSpan(constructChipSpan(chip.getEntry()),
mindyp5e60c2b2012-11-06 17:47:40 -08002292 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002293 }
Mindy Pereira04da3252011-07-06 16:09:25 -07002294 } catch (NullPointerException e) {
2295 Log.e(TAG, e.getMessage(), e);
2296 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002297 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002298 setCursorVisible(true);
2299 setSelection(editable.length());
Jin Cao568fb222014-08-19 13:50:59 -07002300 dismissPopups();
Mindy Pereira95a69252011-06-17 15:02:03 -07002301 }
2302
Jin Cao4db8ccc2014-07-30 10:11:07 -07002303 @Override
2304 public void onChipDelete() {
2305 if (mSelectedChip != null) {
2306 removeChip(mSelectedChip);
Jin Cao4db8ccc2014-07-30 10:11:07 -07002307 }
Jin Cao568fb222014-08-19 13:50:59 -07002308 dismissPopups();
2309 }
2310
2311 private void dismissPopups() {
2312 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2313 mAlternatesPopup.dismiss();
2314 }
2315 if (mAddressPopup != null && mAddressPopup.isShowing()) {
2316 mAddressPopup.dismiss();
2317 }
Jin Caoffc01112014-12-15 16:24:37 -08002318 setSelection(getText().length());
Jin Cao4db8ccc2014-07-30 10:11:07 -07002319 }
2320
Mindy Pereira95a69252011-06-17 15:02:03 -07002321 /**
2322 * Remove the chip and any text associated with it from the RecipientEditTextView.
2323 */
Mindy Pereira97cb2592011-09-26 16:11:41 -07002324 // Visible for testing.
Kevin Linb10d1c62014-01-24 12:45:00 -08002325 /* package */void removeChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002326 Spannable spannable = getSpannable();
2327 int spanStart = spannable.getSpanStart(chip);
2328 int spanEnd = spannable.getSpanEnd(chip);
2329 Editable text = getText();
Mindy Pereira62397a52011-10-03 13:46:43 -07002330 int toDelete = spanEnd;
Mindy Pereira95a69252011-06-17 15:02:03 -07002331 boolean wasSelected = chip == mSelectedChip;
2332 // Clear that there is a selected chip before updating any text.
2333 if (wasSelected) {
2334 mSelectedChip = null;
2335 }
Mindy Pereira62397a52011-10-03 13:46:43 -07002336 // Always remove trailing spaces when removing a chip.
2337 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2338 toDelete++;
2339 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002340 spannable.removeSpan(chip);
Mindy Pereiraf6d4bfc2012-04-24 15:13:34 -07002341 if (spanStart >= 0 && toDelete > 0) {
2342 text.delete(spanStart, toDelete);
2343 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002344 if (wasSelected) {
2345 clearSelectedChip();
2346 }
2347 }
2348
2349 /**
2350 * Replace this currently selected chip with a new chip
2351 * that uses the contact data provided.
2352 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07002353 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002354 /*package*/ void replaceChip(DrawableRecipientChip chip, RecipientEntry entry) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002355 boolean wasSelected = chip == mSelectedChip;
2356 if (wasSelected) {
2357 mSelectedChip = null;
2358 }
2359 int start = getChipStart(chip);
2360 int end = getChipEnd(chip);
2361 getSpannable().removeSpan(chip);
2362 Editable editable = getText();
Jin Caoffc01112014-12-15 16:24:37 -08002363 CharSequence chipText = createChip(entry);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002364 if (chipText != null) {
2365 if (start == -1 || end == -1) {
2366 Log.e(TAG, "The chip to replace does not exist but should.");
2367 editable.insert(0, chipText);
2368 } else {
2369 if (!TextUtils.isEmpty(chipText)) {
2370 // There may be a space to replace with this chip's new
mindypb5afbc72012-10-03 11:57:42 -07002371 // associated space. Check for it
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002372 int toReplace = end;
2373 while (toReplace >= 0 && toReplace < editable.length()
2374 && editable.charAt(toReplace) == ' ') {
2375 toReplace++;
2376 }
2377 editable.replace(start, toReplace, chipText);
Mindy Pereira62397a52011-10-03 13:46:43 -07002378 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07002379 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002380 }
2381 setCursorVisible(true);
2382 if (wasSelected) {
2383 clearSelectedChip();
2384 }
2385 }
2386
2387 /**
2388 * Handle click events for a chip. When a selected chip receives a click
2389 * event, see if that event was in the delete icon. If so, delete it.
2390 * Otherwise, unselect the chip.
2391 */
Jin Caoa21fd882014-08-10 13:07:11 -07002392 public void onClick(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002393 if (chip.isSelected()) {
Jin Caoa21fd882014-08-10 13:07:11 -07002394 clearSelectedChip();
Mindy Pereiracd611952011-06-01 17:02:20 -07002395 }
Mindy Pereira9159cd22011-05-25 17:06:44 -07002396 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002397
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002398 private boolean chipsPending() {
2399 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2400 }
2401
Mindy Pereira883c4992011-08-04 18:01:30 -07002402 @Override
2403 public void removeTextChangedListener(TextWatcher watcher) {
2404 mTextWatcher = null;
2405 super.removeTextChangedListener(watcher);
2406 }
2407
Jin Caob3b248a2014-04-11 10:43:50 -07002408 private boolean isValidEmailAddress(String input) {
2409 return !TextUtils.isEmpty(input) && mValidator != null &&
2410 mValidator.isValid(input);
2411 }
2412
Mindy Pereira79fb4362011-06-21 14:37:07 -07002413 private class RecipientTextWatcher implements TextWatcher {
Mindy Pereira72a23392012-02-06 10:19:51 -08002414
Mindy Pereira79fb4362011-06-21 14:37:07 -07002415 @Override
2416 public void afterTextChanged(Editable s) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002417 // If the text has been set to null or empty, make sure we remove
2418 // all the spans we applied.
2419 if (TextUtils.isEmpty(s)) {
2420 // Remove all the chips spans.
2421 Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08002422 DrawableRecipientChip[] chips = spannable.getSpans(0, getText().length(),
2423 DrawableRecipientChip.class);
2424 for (DrawableRecipientChip chip : chips) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002425 spannable.removeSpan(chip);
2426 }
2427 if (mMoreChip != null) {
2428 spannable.removeSpan(mMoreChip);
2429 }
Kevin Lin41e93fb2014-02-03 17:35:29 -08002430 clearSelectedChip();
Mindy Pereira32366d42011-07-24 12:39:30 -07002431 return;
2432 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002433 // Get whether there are any recipients pending addition to the
2434 // view. If there are, don't do anything in the text watcher.
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002435 if (chipsPending()) {
Mindy Pereira79fb4362011-06-21 14:37:07 -07002436 return;
2437 }
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002438 // If the user is editing a chip, don't clear it.
mindypf30a4282012-12-03 12:16:33 -08002439 if (mSelectedChip != null) {
2440 if (!isGeneratedContact(mSelectedChip)) {
2441 setCursorVisible(true);
2442 setSelection(getText().length());
2443 clearSelectedChip();
2444 } else {
2445 return;
2446 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002447 }
2448 int length = s.length();
2449 // Make sure there is content there to parse and that it is
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002450 // not just the commit character.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002451 if (length > 1) {
mindypf30a4282012-12-03 12:16:33 -08002452 if (lastCharacterIsCommitCharacter(s)) {
2453 commitByCharacter();
2454 return;
2455 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002456 char last;
Mindy Pereira11a2adb2011-06-28 09:57:43 -07002457 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002458 int len = length() - 1;
2459 if (end != len) {
2460 last = s.charAt(end);
2461 } else {
2462 last = s.charAt(len);
2463 }
mindypf30a4282012-12-03 12:16:33 -08002464 if (last == COMMIT_CHAR_SPACE) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002465 if (!isPhoneQuery()) {
2466 // Check if this is a valid email address. If it is,
2467 // commit it.
2468 String text = getText().toString();
2469 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2470 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2471 tokenStart));
Jin Caob3b248a2014-04-11 10:43:50 -07002472 if (isValidEmailAddress(sub)) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002473 commitByCharacter();
2474 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002475 }
2476 }
2477 }
2478 }
2479
2480 @Override
2481 public void onTextChanged(CharSequence s, int start, int before, int count) {
mindypf30a4282012-12-03 12:16:33 -08002482 // The user deleted some text OR some text was replaced; check to
2483 // see if the insertion point is on a space
Mindy Pereira72a23392012-02-06 10:19:51 -08002484 // following a chip.
mindypf30a4282012-12-03 12:16:33 -08002485 if (before - count == 1) {
Mindy Pereira72a23392012-02-06 10:19:51 -08002486 // If the item deleted is a space, and the thing before the
2487 // space is a chip, delete the entire span.
2488 int selStart = getSelectionStart();
Scott Kennedy194d4272013-03-06 22:06:45 -08002489 DrawableRecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2490 DrawableRecipientChip.class);
Mindy Pereira72a23392012-02-06 10:19:51 -08002491 if (repl.length > 0) {
2492 // There is a chip there! Just remove it.
Jin Caoffc01112014-12-15 16:24:37 -08002493 DrawableRecipientChip toDelete = repl[0];
Mindy Pereira72a23392012-02-06 10:19:51 -08002494 Editable editable = getText();
2495 // Add the separator token.
Jin Caoffc01112014-12-15 16:24:37 -08002496 int deleteStart = editable.getSpanStart(toDelete);
2497 int deleteEnd = editable.getSpanEnd(toDelete) + 1;
2498 if (deleteEnd > editable.length()) {
2499 deleteEnd = editable.length();
Mindy Pereira62fce932012-02-16 15:00:30 -08002500 }
Jin Caoffc01112014-12-15 16:24:37 -08002501 editable.removeSpan(toDelete);
2502 editable.delete(deleteStart, deleteEnd);
Mindy Pereira72a23392012-02-06 10:19:51 -08002503 }
Mindy Pereira4e7d20f2012-07-16 08:09:01 -07002504 } else if (count > before) {
mindyp7e10c862012-11-27 11:13:26 -08002505 if (mSelectedChip != null
2506 && isGeneratedContact(mSelectedChip)) {
2507 if (lastCharacterIsCommitCharacter(s)) {
2508 commitByCharacter();
2509 return;
2510 }
2511 }
Mindy Pereira72a23392012-02-06 10:19:51 -08002512 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002513 }
2514
2515 @Override
2516 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002517 // Do nothing.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002518 }
2519 }
Mindy Pereira18529312011-06-28 11:00:52 -07002520
Alice Yangc1b52582013-03-04 19:54:00 -08002521 public boolean lastCharacterIsCommitCharacter(CharSequence s) {
mindypf30a4282012-12-03 12:16:33 -08002522 char last;
2523 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2524 int len = length() - 1;
2525 if (end != len) {
2526 last = s.charAt(end);
2527 } else {
2528 last = s.charAt(len);
2529 }
2530 return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON;
2531 }
2532
Scott Kennedy194d4272013-03-06 22:06:45 -08002533 public boolean isGeneratedContact(DrawableRecipientChip chip) {
mindypf30a4282012-12-03 12:16:33 -08002534 long contactId = chip.getContactId();
2535 return contactId == RecipientEntry.INVALID_CONTACT
2536 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2537 }
2538
Minh Phame51c7222011-10-12 11:33:26 -07002539 /**
2540 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2541 */
Régis Décamps219cbfb2014-06-04 14:29:54 +02002542 // Visible for testing.
2543 void handlePasteClip(ClipData clip) {
2544 if (clip == null) {
2545 // Do nothing.
2546 return;
2547 }
2548
2549 final ClipDescription clipDesc = clip.getDescription();
2550 boolean containsSupportedType = clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||
2551 clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML);
2552 if (!containsSupportedType) {
2553 return;
2554 }
2555
Minh Phame51c7222011-10-12 11:33:26 -07002556 removeTextChangedListener(mTextWatcher);
2557
Régis Décamps219cbfb2014-06-04 14:29:54 +02002558 final ClipDescription clipDescription = clip.getDescription();
2559 for (int i = 0; i < clip.getItemCount(); i++) {
2560 final String mimeType = clipDescription.getMimeType(i);
2561 final boolean supportedType = ClipDescription.MIMETYPE_TEXT_PLAIN.equals(mimeType) ||
2562 ClipDescription.MIMETYPE_TEXT_HTML.equals(mimeType);
2563 if (!supportedType) {
2564 // Only plain text and html can be pasted.
2565 continue;
2566 }
2567
2568 final CharSequence pastedItem = clip.getItemAt(i).getText();
2569 if (!TextUtils.isEmpty(pastedItem)) {
2570 final Editable editable = getText();
2571 final int start = getSelectionStart();
2572 final int end = getSelectionEnd();
2573 if (start < 0 || end < 1) {
2574 // No selection.
2575 editable.append(pastedItem);
2576 } else if (start == end) {
2577 // Insert at position.
2578 editable.insert(start, pastedItem);
2579 } else {
2580 editable.append(pastedItem, start, end);
Minh Phame51c7222011-10-12 11:33:26 -07002581 }
Régis Décamps219cbfb2014-06-04 14:29:54 +02002582 handlePasteAndReplace();
Minh Phame51c7222011-10-12 11:33:26 -07002583 }
2584 }
2585
2586 mHandler.post(mAddTextWatcher);
2587 }
2588
Mindy Pereira20c9d622011-10-12 13:18:04 -07002589 @Override
2590 public boolean onTextContextMenuItem(int id) {
2591 if (id == android.R.id.paste) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002592 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2593 Context.CLIPBOARD_SERVICE);
Minh Phame51c7222011-10-12 11:33:26 -07002594 handlePasteClip(clipboard.getPrimaryClip());
Mindy Pereira20c9d622011-10-12 13:18:04 -07002595 return true;
2596 }
2597 return super.onTextContextMenuItem(id);
2598 }
2599
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002600 private void handlePasteAndReplace() {
Scott Kennedy194d4272013-03-06 22:06:45 -08002601 ArrayList<DrawableRecipientChip> created = handlePaste();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002602 if (created != null && created.size() > 0) {
2603 // Perform reverse lookups on the pasted contacts.
2604 IndividualReplacementTask replace = new IndividualReplacementTask();
2605 replace.execute(created);
2606 }
2607 }
2608
Mindy Pereira20c9d622011-10-12 13:18:04 -07002609 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002610 /* package */ArrayList<DrawableRecipientChip> handlePaste() {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002611 String text = getText().toString();
2612 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2613 String lastAddress = text.substring(originalTokenStart);
2614 int tokenStart = originalTokenStart;
jli119X0cae8502012-10-18 12:55:47 +08002615 int prevTokenStart = 0;
Scott Kennedy194d4272013-03-06 22:06:45 -08002616 DrawableRecipientChip findChip = null;
2617 ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
Mindy Pereira20c9d622011-10-12 13:18:04 -07002618 if (tokenStart != 0) {
2619 // There are things before this!
jli119X0cae8502012-10-18 12:55:47 +08002620 while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002621 prevTokenStart = tokenStart;
2622 tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2623 findChip = findChip(tokenStart);
Tom Taylorfda01702013-01-14 16:52:25 -08002624 if (tokenStart == originalTokenStart && findChip == null) {
2625 break;
2626 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002627 }
2628 if (tokenStart != originalTokenStart) {
2629 if (findChip != null) {
2630 tokenStart = prevTokenStart;
2631 }
2632 int tokenEnd;
Scott Kennedy194d4272013-03-06 22:06:45 -08002633 DrawableRecipientChip createdChip;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002634 while (tokenStart < originalTokenStart) {
mindypb5afbc72012-10-03 11:57:42 -07002635 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2636 tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002637 commitChip(tokenStart, tokenEnd, getText());
2638 createdChip = findChip(tokenStart);
Mindy Pereirac52ea8e2012-06-04 15:24:55 -07002639 if (createdChip == null) {
2640 break;
2641 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002642 // +1 for the space at the end.
2643 tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002644 created.add(createdChip);
Mindy Pereira20c9d622011-10-12 13:18:04 -07002645 }
2646 }
2647 }
2648 // Take a look at the last token. If the token has been completed with a
2649 // commit character, create a chip.
2650 if (isCompletedToken(lastAddress)) {
2651 Editable editable = getText();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002652 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2653 commitChip(tokenStart, editable.length(), editable);
2654 created.add(findChip(tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002655 }
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002656 return created;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002657 }
2658
2659 // Visible for testing.
2660 /* package */int movePastTerminators(int tokenEnd) {
2661 if (tokenEnd >= length()) {
2662 return tokenEnd;
2663 }
2664 char atEnd = getText().toString().charAt(tokenEnd);
2665 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2666 tokenEnd++;
2667 }
2668 // This token had not only an end token character, but also a space
2669 // separating it from the next token.
2670 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2671 tokenEnd++;
2672 }
2673 return tokenEnd;
2674 }
2675
Mindy Pereira18529312011-06-28 11:00:52 -07002676 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
Scott Kennedy194d4272013-03-06 22:06:45 -08002677 private DrawableRecipientChip createFreeChip(RecipientEntry entry) {
Mindy Pereira18529312011-06-28 11:00:52 -07002678 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002679 if (mNoChips) {
2680 return null;
2681 }
Jin Caoffc01112014-12-15 16:24:37 -08002682 return constructChipSpan(entry);
Mindy Pereira18529312011-06-28 11:00:52 -07002683 } catch (NullPointerException e) {
2684 Log.e(TAG, e.getMessage(), e);
2685 return null;
2686 }
2687 }
2688
2689 @Override
Scott Kennedy78f38a02013-02-27 11:21:40 -08002690 protected void onPreExecute() {
2691 // Ensure everything is in chip-form already, so we don't have text that slowly gets
2692 // replaced
Scott Kennedy194d4272013-03-06 22:06:45 -08002693 final List<DrawableRecipientChip> originalRecipients =
2694 new ArrayList<DrawableRecipientChip>();
2695 final DrawableRecipientChip[] existingChips = getSortedRecipients();
Jin Caoffc01112014-12-15 16:24:37 -08002696 Collections.addAll(originalRecipients, existingChips);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002697 if (mRemovedSpans != null) {
2698 originalRecipients.addAll(mRemovedSpans);
2699 }
2700
Scott Kennedy194d4272013-03-06 22:06:45 -08002701 final List<DrawableRecipientChip> replacements =
2702 new ArrayList<DrawableRecipientChip>(originalRecipients.size());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002703
Scott Kennedy194d4272013-03-06 22:06:45 -08002704 for (final DrawableRecipientChip chip : originalRecipients) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002705 if (RecipientEntry.isCreatedRecipient(chip.getEntry().getContactId())
2706 && getSpannable().getSpanStart(chip) != -1) {
2707 replacements.add(createFreeChip(chip.getEntry()));
2708 } else {
2709 replacements.add(null);
2710 }
2711 }
2712
2713 processReplacements(originalRecipients, replacements);
2714 }
2715
2716 @Override
Mindy Pereira18529312011-06-28 11:00:52 -07002717 protected Void doInBackground(Void... params) {
2718 if (mIndividualReplacements != null) {
2719 mIndividualReplacements.cancel(true);
2720 }
2721 // For each chip in the list, look up the matching contact.
2722 // If there is a match, replace that chip with the matching
2723 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002724 final ArrayList<DrawableRecipientChip> recipients =
2725 new ArrayList<DrawableRecipientChip>();
2726 DrawableRecipientChip[] existingChips = getSortedRecipients();
Jin Caoffc01112014-12-15 16:24:37 -08002727 Collections.addAll(recipients, existingChips);
Mindy Pereira18529312011-06-28 11:00:52 -07002728 if (mRemovedSpans != null) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002729 recipients.addAll(mRemovedSpans);
Mindy Pereira18529312011-06-28 11:00:52 -07002730 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002731 ArrayList<String> addresses = new ArrayList<String>();
Jin Caoffc01112014-12-15 16:24:37 -08002732 for (DrawableRecipientChip chip : recipients) {
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002733 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002734 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002735 }
Mindy Pereira18529312011-06-28 11:00:52 -07002736 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002737 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002738 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002739 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002740 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002741 final ArrayList<DrawableRecipientChip> replacements =
2742 new ArrayList<DrawableRecipientChip>();
2743 for (final DrawableRecipientChip temp : recipients) {
mindyp16923ee2012-12-10 11:58:29 -08002744 RecipientEntry entry = null;
Alice Yangf0579ee2013-03-04 14:10:21 -08002745 if (temp != null && RecipientEntry.isCreatedRecipient(
2746 temp.getEntry().getContactId())
mindyp16923ee2012-12-10 11:58:29 -08002747 && getSpannable().getSpanStart(temp) != -1) {
2748 // Replace this.
2749 entry = createValidatedEntry(
2750 entries.get(tokenizeAddress(temp.getEntry()
2751 .getDestination())));
2752 }
2753 if (entry != null) {
2754 replacements.add(createFreeChip(entry));
2755 } else {
2756 replacements.add(null);
2757 }
Mindy Pereira18529312011-06-28 11:00:52 -07002758 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002759 processReplacements(recipients, replacements);
Mindy Pereira18529312011-06-28 11:00:52 -07002760 }
Scott Kennedy94fa3012013-02-15 18:22:05 -08002761
2762 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002763 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002764 final List<DrawableRecipientChip> replacements =
2765 new ArrayList<DrawableRecipientChip>(unfoundAddresses.size());
Scott Kennedy94fa3012013-02-15 18:22:05 -08002766
Scott Kennedy194d4272013-03-06 22:06:45 -08002767 for (final DrawableRecipientChip temp : recipients) {
Alice Yangad8781e2013-03-04 14:45:38 -08002768 if (temp != null && RecipientEntry.isCreatedRecipient(
2769 temp.getEntry().getContactId())
Scott Kennedy94fa3012013-02-15 18:22:05 -08002770 && getSpannable().getSpanStart(temp) != -1) {
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002771 if (unfoundAddresses.contains(
2772 temp.getEntry().getDestination())) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002773 replacements.add(createFreeChip(temp.getEntry()));
2774 } else {
2775 replacements.add(null);
2776 }
2777 } else {
2778 replacements.add(null);
2779 }
2780 }
2781
Scott Kennedy78f38a02013-02-27 11:21:40 -08002782 processReplacements(recipients, replacements);
Scott Kennedy94fa3012013-02-15 18:22:05 -08002783 }
mindyp16923ee2012-12-10 11:58:29 -08002784 });
Mindy Pereira18529312011-06-28 11:00:52 -07002785 return null;
2786 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002787
Scott Kennedy194d4272013-03-06 22:06:45 -08002788 private void processReplacements(final List<DrawableRecipientChip> recipients,
2789 final List<DrawableRecipientChip> replacements) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002790 if (replacements != null && replacements.size() > 0) {
2791 final Runnable runnable = new Runnable() {
2792 @Override
2793 public void run() {
Scott Kennedy0e128962013-04-11 10:52:08 -07002794 final Editable text = new SpannableStringBuilder(getText());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002795 int i = 0;
Scott Kennedy0e128962013-04-11 10:52:08 -07002796 for (final DrawableRecipientChip chip : recipients) {
2797 final DrawableRecipientChip replacement = replacements.get(i);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002798 if (replacement != null) {
2799 final RecipientEntry oldEntry = chip.getEntry();
2800 final RecipientEntry newEntry = replacement.getEntry();
2801 final boolean isBetter =
2802 RecipientAlternatesAdapter.getBetterRecipient(
2803 oldEntry, newEntry) == newEntry;
2804
2805 if (isBetter) {
2806 // Find the location of the chip in the text currently shown.
Scott Kennedy0e128962013-04-11 10:52:08 -07002807 final int start = text.getSpanStart(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002808 if (start != -1) {
2809 // Replacing the entirety of what the chip represented,
2810 // including the extra space dividing it from other chips.
Paul Westbrookb023f692013-04-22 12:27:35 -07002811 final int end =
2812 Math.min(text.getSpanEnd(chip) + 1, text.length());
Scott Kennedy0e128962013-04-11 10:52:08 -07002813 text.removeSpan(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002814 // Make sure we always have just 1 space at the end to
2815 // separate this chip from the next chip.
Scott Kennedy0e128962013-04-11 10:52:08 -07002816 final SpannableString displayText =
Scott Kennedy78f38a02013-02-27 11:21:40 -08002817 new SpannableString(createAddressText(
Scott Kennedy0e128962013-04-11 10:52:08 -07002818 replacement.getEntry()).trim() + " ");
Scott Kennedy78f38a02013-02-27 11:21:40 -08002819 displayText.setSpan(replacement, 0,
2820 displayText.length() - 1,
2821 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2822 // Replace the old text we found with with the new display
2823 // text, which now may also contain the display name of the
2824 // recipient.
Scott Kennedy0e128962013-04-11 10:52:08 -07002825 text.replace(start, end, displayText);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002826 replacement.setOriginalText(displayText.toString());
2827 replacements.set(i, null);
2828
2829 recipients.set(i, replacement);
2830 }
2831 }
2832 }
2833 i++;
2834 }
Scott Kennedy0e128962013-04-11 10:52:08 -07002835 setText(text);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002836 }
2837 };
2838
2839 if (Looper.myLooper() == Looper.getMainLooper()) {
2840 runnable.run();
2841 } else {
2842 mHandler.post(runnable);
2843 }
2844 }
2845 }
Mindy Pereira18529312011-06-28 11:00:52 -07002846 }
2847
Scott Kennedy78f38a02013-02-27 11:21:40 -08002848 private class IndividualReplacementTask
Scott Kennedy194d4272013-03-06 22:06:45 -08002849 extends AsyncTask<ArrayList<DrawableRecipientChip>, Void, Void> {
Mindy Pereira18529312011-06-28 11:00:52 -07002850 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08002851 protected Void doInBackground(ArrayList<DrawableRecipientChip>... params) {
Mindy Pereira18529312011-06-28 11:00:52 -07002852 // For each chip in the list, look up the matching contact.
2853 // If there is a match, replace that chip with the matching
2854 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002855 final ArrayList<DrawableRecipientChip> originalRecipients = params[0];
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002856 ArrayList<String> addresses = new ArrayList<String>();
Jin Caoffc01112014-12-15 16:24:37 -08002857 for (DrawableRecipientChip chip : originalRecipients) {
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002858 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002859 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002860 }
Mindy Pereira18529312011-06-28 11:00:52 -07002861 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002862 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002863 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002864
2865 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002866 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002867 for (final DrawableRecipientChip temp : originalRecipients) {
mindyp16923ee2012-12-10 11:58:29 -08002868 if (RecipientEntry.isCreatedRecipient(temp.getEntry()
2869 .getContactId())
2870 && getSpannable().getSpanStart(temp) != -1) {
2871 // Replace this.
Alon Albert76f1f2d2013-07-14 15:32:49 +03002872 final RecipientEntry entry = createValidatedEntry(entries
mindyp16923ee2012-12-10 11:58:29 -08002873 .get(tokenizeAddress(temp.getEntry().getDestination())
2874 .toLowerCase()));
Alon Albert76f1f2d2013-07-14 15:32:49 +03002875 if (entry != null) {
mindyp16923ee2012-12-10 11:58:29 -08002876 mHandler.post(new Runnable() {
2877 @Override
2878 public void run() {
Alon Albert76f1f2d2013-07-14 15:32:49 +03002879 replaceChip(temp, entry);
mindyp16923ee2012-12-10 11:58:29 -08002880 }
2881 });
2882 }
2883 }
Mindy Pereira18529312011-06-28 11:00:52 -07002884 }
mindyp16923ee2012-12-10 11:58:29 -08002885 }
2886
Scott Kennedy94fa3012013-02-15 18:22:05 -08002887 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002888 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002889 // No action required
2890 }
mindyp16923ee2012-12-10 11:58:29 -08002891 });
Mindy Pereira18529312011-06-28 11:00:52 -07002892 return null;
2893 }
2894 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002895
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002896
2897 /**
2898 * MoreImageSpan is a simple class created for tracking the existence of a
2899 * more chip across activity restarts/
2900 */
Jin Cao6c2a0162014-08-17 15:00:50 -07002901 private class MoreImageSpan extends ReplacementDrawableSpan {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002902 public MoreImageSpan(Drawable b) {
2903 super(b);
Jin Cao6c2a0162014-08-17 15:00:50 -07002904 setExtraMargin(mLineSpacingExtra);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002905 }
2906 }
2907
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002908 @Override
2909 public boolean onDown(MotionEvent e) {
2910 return false;
2911 }
2912
2913 @Override
2914 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2915 // Do nothing.
2916 return false;
2917 }
2918
2919 @Override
2920 public void onLongPress(MotionEvent event) {
2921 if (mSelectedChip != null) {
2922 return;
2923 }
2924 float x = event.getX();
2925 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07002926 final int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08002927 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002928 if (currentChip != null) {
Minh Phame51c7222011-10-12 11:33:26 -07002929 if (mDragEnabled) {
2930 // Start drag-and-drop for the selected chip.
2931 startDrag(currentChip);
2932 } else {
2933 // Copy the selected chip email address.
2934 showCopyDialog(currentChip.getEntry().getDestination());
2935 }
2936 }
2937 }
2938
Scott Kennedy1650ef62013-08-02 21:56:47 -07002939 // The following methods are used to provide some functionality on older versions of Android
2940 // These methods were copied out of JB MR2's TextView
2941 /////////////////////////////////////////////////
2942 private int supportGetOffsetForPosition(float x, float y) {
2943 if (getLayout() == null) return -1;
2944 final int line = supportGetLineAtCoordinate(y);
Jin Caoffc01112014-12-15 16:24:37 -08002945 return supportGetOffsetAtCoordinate(line, x);
Scott Kennedy1650ef62013-08-02 21:56:47 -07002946 }
2947
2948 private float supportConvertToLocalHorizontalCoordinate(float x) {
2949 x -= getTotalPaddingLeft();
2950 // Clamp the position to inside of the view.
2951 x = Math.max(0.0f, x);
2952 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
2953 x += getScrollX();
2954 return x;
2955 }
2956
2957 private int supportGetLineAtCoordinate(float y) {
2958 y -= getTotalPaddingLeft();
2959 // Clamp the position to inside of the view.
2960 y = Math.max(0.0f, y);
2961 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
2962 y += getScrollY();
2963 return getLayout().getLineForVertical((int) y);
2964 }
2965
2966 private int supportGetOffsetAtCoordinate(int line, float x) {
2967 x = supportConvertToLocalHorizontalCoordinate(x);
2968 return getLayout().getOffsetForHorizontal(line, x);
2969 }
2970 /////////////////////////////////////////////////
2971
Minh Phame51c7222011-10-12 11:33:26 -07002972 /**
2973 * Enables drag-and-drop for chips.
2974 */
2975 public void enableDrag() {
2976 mDragEnabled = true;
2977 }
2978
2979 /**
2980 * Starts drag-and-drop for the selected chip.
2981 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002982 private void startDrag(DrawableRecipientChip currentChip) {
Minh Phame51c7222011-10-12 11:33:26 -07002983 String address = currentChip.getEntry().getDestination();
2984 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2985
2986 // Start drag mode.
2987 startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2988
2989 // Remove the current chip, so drag-and-drop will result in a move.
2990 // TODO (phamm): consider readd this chip if it's dropped outside a target.
2991 removeChip(currentChip);
2992 }
2993
2994 /**
2995 * Handles drag event.
2996 */
2997 @Override
Jin Caoffc01112014-12-15 16:24:37 -08002998 public boolean onDragEvent(@NonNull DragEvent event) {
Minh Phame51c7222011-10-12 11:33:26 -07002999 switch (event.getAction()) {
3000 case DragEvent.ACTION_DRAG_STARTED:
3001 // Only handle plain text drag and drop.
3002 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
3003 case DragEvent.ACTION_DRAG_ENTERED:
3004 requestFocus();
3005 return true;
3006 case DragEvent.ACTION_DROP:
3007 handlePasteClip(event.getClipData());
3008 return true;
3009 }
3010 return false;
3011 }
3012
3013 /**
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07003014 * Drag shadow for a {@link DrawableRecipientChip}.
Minh Phame51c7222011-10-12 11:33:26 -07003015 */
3016 private final class RecipientChipShadow extends DragShadowBuilder {
Scott Kennedy194d4272013-03-06 22:06:45 -08003017 private final DrawableRecipientChip mChip;
Minh Phame51c7222011-10-12 11:33:26 -07003018
Scott Kennedy194d4272013-03-06 22:06:45 -08003019 public RecipientChipShadow(DrawableRecipientChip chip) {
Minh Phame51c7222011-10-12 11:33:26 -07003020 mChip = chip;
3021 }
3022
3023 @Override
Jin Caoffc01112014-12-15 16:24:37 -08003024 public void onProvideShadowMetrics(@NonNull Point shadowSize,
3025 @NonNull Point shadowTouchPoint) {
mindypf30a4282012-12-03 12:16:33 -08003026 Rect rect = mChip.getBounds();
Minh Phame51c7222011-10-12 11:33:26 -07003027 shadowSize.set(rect.width(), rect.height());
3028 shadowTouchPoint.set(rect.centerX(), rect.centerY());
3029 }
3030
3031 @Override
Jin Caoffc01112014-12-15 16:24:37 -08003032 public void onDrawShadow(@NonNull Canvas canvas) {
mindypf30a4282012-12-03 12:16:33 -08003033 mChip.draw(canvas);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003034 }
3035 }
3036
3037 private void showCopyDialog(final String address) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07003038 if (!mAttachedToWindow) {
3039 return;
3040 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003041 mCopyAddress = address;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003042 mCopyDialog.setTitle(address);
Mindy Pereira76e62e32012-02-03 15:38:50 -08003043 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003044 mCopyDialog.setCancelable(true);
3045 mCopyDialog.setCanceledOnTouchOutside(true);
Tom Taylor80f4abf2012-04-06 13:37:20 -07003046 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
3047 button.setOnClickListener(this);
3048 int btnTitleId;
Tom Taylorc7a87f02012-05-03 15:21:08 -07003049 if (isPhoneQuery()) {
Tom Taylor80f4abf2012-04-06 13:37:20 -07003050 btnTitleId = R.string.copy_number;
3051 } else {
3052 btnTitleId = R.string.copy_email;
3053 }
3054 String buttonTitle = getContext().getResources().getString(btnTitleId);
3055 button.setText(buttonTitle);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003056 mCopyDialog.setOnDismissListener(this);
3057 mCopyDialog.show();
3058 }
3059
3060 @Override
3061 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
3062 // Do nothing.
3063 return false;
3064 }
3065
3066 @Override
3067 public void onShowPress(MotionEvent e) {
3068 // Do nothing.
3069 }
3070
3071 @Override
3072 public boolean onSingleTapUp(MotionEvent e) {
3073 // Do nothing.
3074 return false;
3075 }
3076
3077 @Override
3078 public void onDismiss(DialogInterface dialog) {
3079 mCopyAddress = null;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003080 }
3081
3082 @Override
3083 public void onClick(View v) {
3084 // Copy this to the clipboard.
3085 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
3086 Context.CLIPBOARD_SERVICE);
3087 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
3088 mCopyDialog.dismiss();
3089 }
Tom Taylorc7a87f02012-05-03 15:21:08 -07003090
3091 protected boolean isPhoneQuery() {
Mindy Pereiraca522712012-06-28 11:47:48 -07003092 return getAdapter() != null
Scott Kennedy858e0942013-10-10 11:50:01 -07003093 && getAdapter().getQueryType() == BaseRecipientAdapter.QUERY_TYPE_PHONE;
3094 }
3095
3096 @Override
3097 public BaseRecipientAdapter getAdapter() {
3098 return (BaseRecipientAdapter) super.getAdapter();
Tom Taylorc7a87f02012-05-03 15:21:08 -07003099 }
Kaikai Wang972def72014-05-27 21:59:52 -07003100
3101 /**
3102 * Append a new {@link RecipientEntry} to the end of the recipient chips, leaving any
3103 * unfinished text at the end.
3104 */
3105 public void appendRecipientEntry(final RecipientEntry entry) {
3106 clearComposingText();
3107
3108 final Editable editable = getText();
3109 int chipInsertionPoint = 0;
3110
3111 // Find the end of last chip and see if there's any unchipified text.
3112 final DrawableRecipientChip[] recips = getSortedRecipients();
3113 if (recips != null && recips.length > 0) {
3114 final DrawableRecipientChip last = recips[recips.length - 1];
3115 // The chip will be inserted at the end of last chip + 1. All the unfinished text after
3116 // the insertion point will be kept untouched.
3117 chipInsertionPoint = editable.getSpanEnd(last) + 1;
3118 }
3119
Jin Caoffc01112014-12-15 16:24:37 -08003120 final CharSequence chip = createChip(entry);
Kaikai Wang972def72014-05-27 21:59:52 -07003121 if (chip != null) {
3122 editable.insert(chipInsertionPoint, chip);
3123 }
3124 }
Jin Cao35e82d42014-06-02 17:21:21 -07003125
Kaikai Wangcd980d92014-06-09 21:08:13 -07003126 /**
3127 * Remove all chips matching the given RecipientEntry.
3128 */
3129 public void removeRecipientEntry(final RecipientEntry entry) {
3130 final DrawableRecipientChip[] recips = getText()
3131 .getSpans(0, getText().length(), DrawableRecipientChip.class);
3132
3133 for (final DrawableRecipientChip recipient : recips) {
3134 final RecipientEntry existingEntry = recipient.getEntry();
3135 if (existingEntry != null && existingEntry.isValid() &&
3136 existingEntry.isSamePerson(entry)) {
3137 removeChip(recipient);
3138 }
3139 }
3140 }
3141
Jin Cao4de6a532014-08-08 11:34:10 -07003142 public void setAlternatePopupAnchor(View v) {
3143 mAlternatePopupAnchor = v;
3144 }
3145
Scott Kennedy654c9672014-12-12 14:24:17 -08003146 @Override
3147 public void setVisibility(int visibility) {
3148 super.setVisibility(visibility);
3149
3150 if (visibility != GONE && mRequiresShrinkWhenNotGone) {
3151 mRequiresShrinkWhenNotGone = false;
3152 mHandler.post(mDelayedShrink);
3153 }
3154 }
3155
Jin Cao35e82d42014-06-02 17:21:21 -07003156 private static class ChipBitmapContainer {
3157 Bitmap bitmap;
3158 // information used for positioning the loaded icon
3159 boolean loadIcon = true;
3160 float left;
3161 float top;
3162 float right;
3163 float bottom;
3164 }
Mindy Pereira18529312011-06-28 11:00:52 -07003165}