blob: 4584e585940bc726cc081dcf51ad2e9936e4b096 [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 Caob1aeb7b2014-09-01 23:48:05 -0700195 private int mCurrentSuggestionCount;
196
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800197 // VisibleForTesting
198 final ArrayList<String> mPendingChips = new ArrayList<String>();
Mindy Pereiraf97eb412011-06-24 11:26:20 -0700199
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700200 private int mPendingChipsCount = 0;
Jin Caoa21fd882014-08-10 13:07:11 -0700201 private int mCheckedItem;
Mindy Pereiraf6519d22011-11-02 13:33:18 -0700202 private boolean mNoChips = false;
Jin Caoa21fd882014-08-10 13:07:11 -0700203 private boolean mShouldShrink = true;
Scott Kennedy654c9672014-12-12 14:24:17 -0800204 private boolean mRequiresShrinkWhenNotGone = false;
Jin Cao4de6a532014-08-08 11:34:10 -0700205
Scott Kennedy20c8aa72013-03-06 22:23:59 -0800206 // VisibleForTesting
Scott Kennedy194d4272013-03-06 22:06:45 -0800207 ArrayList<DrawableRecipientChip> mTemporaryRecipients;
Mindy Pereira18529312011-06-28 11:00:52 -0700208
Scott Kennedy194d4272013-03-06 22:06:45 -0800209 private ArrayList<DrawableRecipientChip> mRemovedSpans;
Mindy Pereira3bb52162011-07-01 14:52:22 -0700210
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700211 // Chip copy fields.
212 private GestureDetector mGestureDetector;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700213 private Dialog mCopyDialog;
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700214 private String mCopyAddress;
215
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700216 // Obtain the enclosing scroll view, if it exists, so that the view can be
217 // scrolled to show the last line of chips content.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700218 private ScrollView mScrollView;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700219 private boolean mTriedGettingScrollView;
Minh Phame51c7222011-10-12 11:33:26 -0700220 private boolean mDragEnabled = false;
221
Jin Caoa21fd882014-08-10 13:07:11 -0700222 private boolean mAttachedToWindow;
Tom Taylor4491a062012-11-15 13:57:41 -0800223
Mindy Pereira79fb4362011-06-21 14:37:07 -0700224 private final Runnable mAddTextWatcher = new Runnable() {
225 @Override
226 public void run() {
227 if (mTextWatcher == null) {
228 mTextWatcher = new RecipientTextWatcher();
229 addTextChangedListener(mTextWatcher);
230 }
231 }
232 };
233
Mindy Pereira18529312011-06-28 11:00:52 -0700234 private IndividualReplacementTask mIndividualReplacements;
235
Mindy Pereira2cac2312011-07-20 11:38:59 -0700236 private Runnable mHandlePendingChips = new Runnable() {
237
238 @Override
239 public void run() {
240 handlePendingChips();
Mindy Pereira2cac2312011-07-20 11:38:59 -0700241 }
242
243 };
244
Mindy Pereirad7192502011-09-22 08:04:45 -0700245 private Runnable mDelayedShrink = new Runnable() {
246
247 @Override
248 public void run() {
249 shrink();
250 }
251
252 };
253
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700254 private RecipientEntryItemClickedListener mRecipientEntryItemClickedListener;
255
256 public interface RecipientEntryItemClickedListener {
257 /**
258 * Callback that occurs whenever an auto-complete suggestion is clicked.
259 * @param charactersTyped the number of characters typed by the user to provide the
260 * auto-complete suggestions.
261 * @param position the position in the dropdown list that the user clicked
262 */
263 void onRecipientEntryItemClicked(int charactersTyped, int position);
264 }
265
Mindy Pereira9159cd22011-05-25 17:06:44 -0700266 public RecipientEditTextView(Context context, AttributeSet attrs) {
267 super(context, attrs);
Mindy Pereira22faaa62011-12-16 14:30:34 -0800268 setChipDimensions(context, attrs);
Scott Kennedy15259d52014-07-09 17:28:47 -0700269 mTextHeight = calculateTextHeight();
Mindy Pereira95a69252011-06-17 15:02:03 -0700270 mAlternatesPopup = new ListPopupWindow(context);
Jin Cao939f5f12014-11-10 11:06:12 -0800271 setupPopupWindow(mAlternatesPopup);
Mindy Pereira01382d72011-07-15 16:52:32 -0700272 mAddressPopup = new ListPopupWindow(context);
Jin Cao939f5f12014-11-10 11:06:12 -0800273 setupPopupWindow(mAddressPopup);
Mindy Pereirabfedc1e2011-09-07 12:17:12 -0700274 mCopyDialog = new Dialog(context);
Mindy Pereira95a69252011-06-17 15:02:03 -0700275 mAlternatesListener = new OnItemClickListener() {
276 @Override
277 public void onItemClick(AdapterView<?> adapterView,View view, int position,
278 long rowId) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700279 mAlternatesPopup.setOnItemClickListener(null);
Mindy Pereira95a69252011-06-17 15:02:03 -0700280 replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
281 .getRecipientEntry(position));
282 Message delayed = Message.obtain(mHandler, DISMISS);
Mindy Pereira21cc0a22011-06-23 17:11:06 -0700283 delayed.obj = mAlternatesPopup;
Mindy Pereira95a69252011-06-17 15:02:03 -0700284 mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
285 clearComposingText();
286 }
287 };
Mindy Pereirae1bfc922011-08-16 14:00:01 -0700288 setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
Mindy Pereirab88ee452011-06-02 11:07:43 -0700289 setOnItemClickListener(this);
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700290 setCustomSelectionActionModeCallback(this);
Mindy Pereira007a76b2011-06-14 11:39:36 -0700291 mHandler = new Handler() {
292 @Override
293 public void handleMessage(Message msg) {
294 if (msg.what == DISMISS) {
Mindy Pereira95a69252011-06-17 15:02:03 -0700295 ((ListPopupWindow) msg.obj).dismiss();
Mindy Pereira007a76b2011-06-14 11:39:36 -0700296 return;
297 }
298 super.handleMessage(msg);
299 }
300 };
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700301 mTextWatcher = new RecipientTextWatcher();
302 addTextChangedListener(mTextWatcher);
Mindy Pereira1d1ec852011-08-09 16:49:33 -0700303 mGestureDetector = new GestureDetector(context, this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700304 setOnEditorActionListener(this);
Kevin Linb10d1c62014-01-24 12:45:00 -0800305
Jin Caoa20a8d02014-08-06 17:41:49 -0700306 setDropdownChipLayouter(new DropdownChipLayouter(LayoutInflater.from(context), context));
Kevin Linb10d1c62014-01-24 12:45:00 -0800307 }
308
Jin Cao939f5f12014-11-10 11:06:12 -0800309 private void setupPopupWindow(ListPopupWindow popup) {
Jin Cao939f5f12014-11-10 11:06:12 -0800310 popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
311 @Override
312 public void onDismiss() {
313 clearSelectedChip();
314 }
315 });
316 }
317
Scott Kennedy15259d52014-07-09 17:28:47 -0700318 private int calculateTextHeight() {
Scott Kennedy15259d52014-07-09 17:28:47 -0700319 final TextPaint paint = getPaint();
320
Jin Caofcaf9862014-10-08 12:15:10 -0700321 mRect.setEmpty();
Scott Kennedy15259d52014-07-09 17:28:47 -0700322 // First measure the bounds of a sample text.
323 final String textHeightSample = "a";
Jin Caofcaf9862014-10-08 12:15:10 -0700324 paint.getTextBounds(textHeightSample, 0, textHeightSample.length(), mRect);
Scott Kennedy15259d52014-07-09 17:28:47 -0700325
Jin Caofcaf9862014-10-08 12:15:10 -0700326 mRect.left = 0;
327 mRect.right = 0;
Scott Kennedy15259d52014-07-09 17:28:47 -0700328
Jin Caofcaf9862014-10-08 12:15:10 -0700329 return mRect.height();
Scott Kennedy15259d52014-07-09 17:28:47 -0700330 }
331
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -0700332 public void setDropdownChipLayouter(DropdownChipLayouter dropdownChipLayouter) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800333 mDropdownChipLayouter = dropdownChipLayouter;
Jin Caoa20a8d02014-08-06 17:41:49 -0700334 mDropdownChipLayouter.setDeleteListener(this);
Mindy Pereira93364a62012-04-27 14:17:22 -0700335 }
336
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -0700337 public void setRecipientEntryItemClickedListener(RecipientEntryItemClickedListener listener) {
338 mRecipientEntryItemClickedListener = listener;
339 }
340
Mindy Pereira93364a62012-04-27 14:17:22 -0700341 @Override
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700342 protected void onDetachedFromWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700343 super.onDetachedFromWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700344 mAttachedToWindow = false;
345 }
346
347 @Override
348 protected void onAttachedToWindow() {
Tony Mantler2b2de7c2014-03-12 11:59:31 -0700349 super.onAttachedToWindow();
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700350 mAttachedToWindow = true;
Jin Cao93d69f42014-10-07 12:27:49 -0700351
352 final int anchorId = getDropDownAnchor();
353 if (anchorId != View.NO_ID) {
354 mDropdownAnchor = getRootView().findViewById(anchorId);
355 }
Tony Mantlerfbeca0e2013-10-15 14:53:00 -0700356 }
357
358 @Override
Kevin Lin494bec82014-12-02 15:37:57 -0800359 public void setDropDownAnchor(int anchorId) {
360 super.setDropDownAnchor(anchorId);
361 if (anchorId != View.NO_ID) {
362 mDropdownAnchor = getRootView().findViewById(anchorId);
363 }
364 }
365
366 @Override
Mindy Pereira93364a62012-04-27 14:17:22 -0700367 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
368 if (action == EditorInfo.IME_ACTION_DONE) {
369 if (commitDefault()) {
370 return true;
371 }
372 if (mSelectedChip != null) {
373 clearSelectedChip();
374 return true;
375 } else if (focusNext()) {
376 return true;
377 }
378 }
379 return false;
380 }
381
382 @Override
Jin Caoffc01112014-12-15 16:24:37 -0800383 public InputConnection onCreateInputConnection(@NonNull EditorInfo outAttrs) {
Mindy Pereira93364a62012-04-27 14:17:22 -0700384 InputConnection connection = super.onCreateInputConnection(outAttrs);
385 int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
386 if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
387 // clear the existing action
388 outAttrs.imeOptions ^= imeActions;
389 // set the DONE action
390 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
391 }
392 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
393 outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
394 }
Scott Kennedy1af243f2013-01-29 23:38:43 -0800395
396 outAttrs.actionId = EditorInfo.IME_ACTION_DONE;
Kaikai Wanga5461b72014-09-18 17:38:46 -0700397
398 // Custom action labels are discouraged in L; a checkmark icon is shown in place of the
399 // custom text in this case.
Nick Kralevich8f4326a2014-10-18 07:33:30 -0700400 outAttrs.actionLabel = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? null :
Kaikai Wanga5461b72014-09-18 17:38:46 -0700401 getContext().getString(R.string.action_label);
Mindy Pereira93364a62012-04-27 14:17:22 -0700402 return connection;
Erike33555f2011-06-21 14:20:20 -0700403 }
Mindy Pereira7afe1602011-06-20 10:53:52 -0700404
Scott Kennedy194d4272013-03-06 22:06:45 -0800405 /*package*/ DrawableRecipientChip getLastChip() {
406 DrawableRecipientChip last = null;
407 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700408 if (chips != null && chips.length > 0) {
409 last = chips[chips.length - 1];
Erike33555f2011-06-21 14:20:20 -0700410 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700411 return last;
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700412 }
413
Ken Thai1248e532014-05-01 09:05:02 -0700414 /**
415 * @return The list of {@link RecipientEntry}s that have been selected by the user.
416 */
417 public List<RecipientEntry> getSelectedRecipients() {
418 DrawableRecipientChip[] chips =
419 getText().getSpans(0, getText().length(), DrawableRecipientChip.class);
Jin Caoffc01112014-12-15 16:24:37 -0800420 List<RecipientEntry> results = new ArrayList<RecipientEntry>();
Ken Thai1248e532014-05-01 09:05:02 -0700421 if (chips == null) {
422 return results;
423 }
424
425 for (DrawableRecipientChip c : chips) {
426 results.add(c.getEntry());
427 }
428
429 return results;
430 }
431
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700432 @Override
433 public void onSelectionChanged(int start, int end) {
434 // When selection changes, see if it is inside the chips area.
435 // If so, move the cursor back after the chips again.
Jin Caoffc01112014-12-15 16:24:37 -0800436 // Only exception is when we change the selection due to a selected chip.
Scott Kennedy194d4272013-03-06 22:06:45 -0800437 DrawableRecipientChip last = getLastChip();
Jin Caoffc01112014-12-15 16:24:37 -0800438 if (mSelectedChip == null && last != null && start < getSpannable().getSpanEnd(last)) {
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700439 // Grab the last chip and set the cursor to after it.
440 setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length()));
Mindy Pereirafd68ea62011-06-02 10:40:19 -0700441 }
Mindy Pereira05dbd332011-06-03 09:37:44 -0700442 super.onSelectionChanged(start, end);
443 }
444
Mindy Pereiradc04cd72011-09-16 15:42:09 -0700445 @Override
446 public void onRestoreInstanceState(Parcelable state) {
447 if (!TextUtils.isEmpty(getText())) {
448 super.onRestoreInstanceState(null);
449 } else {
450 super.onRestoreInstanceState(state);
451 }
452 }
453
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700454 @Override
Mindy Pereiradaa640c2011-10-03 14:18:30 -0700455 public Parcelable onSaveInstanceState() {
456 // If the user changes orientation while they are editing, just roll back the selection.
457 clearSelectedChip();
458 return super.onSaveInstanceState();
459 }
460
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700461 /**
462 * Convenience method: Append the specified text slice to the TextView's
463 * display buffer, upgrading it to BufferType.EDITABLE if it was
464 * not already editable. Commas are excluded as they are added automatically
465 * by the view.
466 */
467 @Override
468 public void append(CharSequence text, int start, int end) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700469 // We don't care about watching text changes while appending.
470 if (mTextWatcher != null) {
471 removeTextChangedListener(mTextWatcher);
472 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700473 super.append(text, start, end);
474 if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
mindyp01244682012-08-27 10:32:17 -0700475 String displayString = text.toString();
Scott Kennedy03e9e982013-03-04 13:26:22 -0800476
477 if (!displayString.trim().endsWith(String.valueOf(COMMIT_CHAR_COMMA))) {
478 // We have no separator, so we should add it
479 super.append(SEPARATOR, 0, SEPARATOR.length());
480 displayString += SEPARATOR;
mindyp01244682012-08-27 10:32:17 -0700481 }
Scott Kennedy03e9e982013-03-04 13:26:22 -0800482
mindyp20d7af72012-09-10 15:47:40 -0700483 if (!TextUtils.isEmpty(displayString)
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700484 && TextUtils.getTrimmedLength(displayString) > 0) {
485 mPendingChipsCount++;
Scott Kennedy03e9e982013-03-04 13:26:22 -0800486 mPendingChips.add(displayString);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700487 }
488 }
mindypabb864d2012-09-10 12:06:35 -0700489 // Put a message on the queue to make sure we ALWAYS handle pending
490 // chips.
Mindy Pereira2cac2312011-07-20 11:38:59 -0700491 if (mPendingChipsCount > 0) {
492 postHandlePendingChips();
493 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -0700494 mHandler.post(mAddTextWatcher);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700495 }
496
Mindy Pereira05dbd332011-06-03 09:37:44 -0700497 @Override
498 public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700499 super.onFocusChanged(hasFocus, direction, previous);
Mindy Pereira05dbd332011-06-03 09:37:44 -0700500 if (!hasFocus) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700501 shrink();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700502 } else {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700503 expand();
Mindy Pereira05dbd332011-06-03 09:37:44 -0700504 }
Mindy Pereira9159cd22011-05-25 17:06:44 -0700505 }
506
Alice Yang6b7110f2013-04-26 12:50:35 -0700507 @Override
Jin Caoffc01112014-12-15 16:24:37 -0800508 public <T extends ListAdapter & Filterable> void setAdapter(@NonNull T adapter) {
mindyp093ecdd2012-12-14 10:40:51 -0800509 super.setAdapter(adapter);
Kevin Linb10d1c62014-01-24 12:45:00 -0800510 BaseRecipientAdapter baseAdapter = (BaseRecipientAdapter) adapter;
511 baseAdapter.registerUpdateObserver(new BaseRecipientAdapter.EntriesUpdatedObserver() {
512 @Override
513 public void onChanged(List<RecipientEntry> entries) {
514 // Scroll the chips field to the top of the screen so
515 // that the user can see as many results as possible.
516 if (entries != null && entries.size() > 0) {
517 scrollBottomIntoView();
Jin Caob1aeb7b2014-09-01 23:48:05 -0700518 // Here the current suggestion count is still the old one since we update
519 // the count at the bottom of this function.
520 if (mCurrentSuggestionCount == 0) {
521 // Announce the new number of possible choices for accessibility.
Jin Cao04f06ea2014-09-22 14:58:28 -0700522 announceForAccessibilityCompat(getContext().getString(
Jin Caob1aeb7b2014-09-01 23:48:05 -0700523 R.string.accessbility_suggestion_dropdown_opened));
524 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800525 }
Jin Cao93d69f42014-10-07 12:27:49 -0700526
527 // Set the dropdown height to be the remaining height from the anchor to the bottom.
Jin Caofcaf9862014-10-08 12:15:10 -0700528 mDropdownAnchor.getLocationInWindow(mCoords);
529 getWindowVisibleDisplayFrame(mRect);
Jin Cao732fe3e2014-11-06 13:35:35 -0800530 setDropDownHeight(mRect.bottom - mCoords[1] - mDropdownAnchor.getHeight() -
531 getDropDownVerticalOffset());
Jin Caob1aeb7b2014-09-01 23:48:05 -0700532
533 mCurrentSuggestionCount = entries == null ? 0 : entries.size();
Kevin Linb10d1c62014-01-24 12:45:00 -0800534 }
535 });
536 baseAdapter.setDropdownChipLayouter(mDropdownChipLayouter);
mindyp093ecdd2012-12-14 10:40:51 -0800537 }
538
Jin Caoffc01112014-12-15 16:24:37 -0800539 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
Jin Cao04f06ea2014-09-22 14:58:28 -0700540 private void announceForAccessibilityCompat(String text) {
Scott Kennedy5037dea2015-01-30 12:12:13 -0800541 final AccessibilityManager accessibilityManager =
542 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
543 final boolean isAccessibilityOn = accessibilityManager.isEnabled();
544
545 if (isAccessibilityOn && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Jin Cao04f06ea2014-09-22 14:58:28 -0700546 final ViewParent parent = getParent();
547 if (parent != null) {
548 AccessibilityEvent event = AccessibilityEvent.obtain(
549 AccessibilityEvent.TYPE_ANNOUNCEMENT);
550 onInitializeAccessibilityEvent(event);
551 event.getText().add(text);
552 event.setContentDescription(null);
553 parent.requestSendAccessibilityEvent(this, event);
554 }
555 }
556 }
557
Kevin Lin53e718a2014-02-04 17:40:33 -0800558 protected void scrollBottomIntoView() {
mindyp093ecdd2012-12-14 10:40:51 -0800559 if (mScrollView != null && mShouldShrink) {
Jin Caofcaf9862014-10-08 12:15:10 -0700560 getLocationInWindow(mCoords);
mindyp093ecdd2012-12-14 10:40:51 -0800561 // Desired position shows at least 1 line of chips below the action
562 // bar. We add excess padding to make sure this is always below other
563 // content.
Jin Cao14efc572014-09-10 10:27:01 -0700564 final int height = getHeight();
Jin Caofcaf9862014-10-08 12:15:10 -0700565 final int currentPos = mCoords[1] + height;
Jin Caof6ddb752014-10-13 13:21:42 -0700566 mScrollView.getLocationInWindow(mCoords);
567 final int desiredPos = mCoords[1] + height / getLineCount();
mindyp093ecdd2012-12-14 10:40:51 -0800568 if (currentPos > desiredPos) {
569 mScrollView.scrollBy(0, currentPos - desiredPos);
570 }
571 }
572 }
573
Kevin Lin53e718a2014-02-04 17:40:33 -0800574 protected ScrollView getScrollView() {
Scott Kennedy7a4e6772013-11-21 14:31:33 -0800575 return mScrollView;
Kevin Lin53e718a2014-02-04 17:40:33 -0800576 }
577
Mindy Pereirad5d86aa2011-08-17 10:37:59 -0700578 @Override
579 public void performValidation() {
580 // Do nothing. Chips handles its own validation.
581 }
582
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700583 private void shrink() {
Mindy Pereira5c125af2011-12-13 11:04:13 -0800584 if (mTokenizer == null) {
585 return;
586 }
mindyp5e60c2b2012-11-06 17:47:40 -0800587 long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1;
588 if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT
589 && (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700590 clearSelectedChip();
591 } else {
Mindy Pereirad7192502011-09-22 08:04:45 -0700592 if (getWidth() <= 0) {
Mindy Pereirad7192502011-09-22 08:04:45 -0700593 mHandler.removeCallbacks(mDelayedShrink);
Scott Kennedy654c9672014-12-12 14:24:17 -0800594
595 if (getVisibility() == GONE) {
596 // We aren't going to have a width any time soon, so defer
597 // this until we're not GONE.
598 mRequiresShrinkWhenNotGone = true;
599 } else {
600 // We don't have the width yet which means the view hasn't been drawn yet
601 // and there is no reason to attempt to commit chips yet.
602 // This focus lost must be the result of an orientation change
603 // or an initial rendering.
604 // Re-post the shrink for later.
605 mHandler.post(mDelayedShrink);
606 }
Mindy Pereirad7192502011-09-22 08:04:45 -0700607 return;
608 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700609 // Reset any pending chips as they would have been handled
610 // when the field lost focus.
611 if (mPendingChipsCount > 0) {
Mindy Pereira2cac2312011-07-20 11:38:59 -0700612 postHandlePendingChips();
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700613 } else {
614 Editable editable = getText();
615 int end = getSelectionEnd();
616 int start = mTokenizer.findTokenStart(editable, end);
Scott Kennedy194d4272013-03-06 22:06:45 -0800617 DrawableRecipientChip[] chips =
618 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700619 if ((chips == null || chips.length == 0)) {
Mindy Pereirad7192502011-09-22 08:04:45 -0700620 Editable text = getText();
621 int whatEnd = mTokenizer.findTokenEnd(text, start);
622 // This token was already tokenized, so skip past the ending token.
Mindy Pereira448e90b2011-09-22 11:49:32 -0700623 if (whatEnd < text.length() && text.charAt(whatEnd) == ',') {
mindyp4f82d882012-11-08 16:30:27 -0800624 whatEnd = movePastTerminators(whatEnd);
Mindy Pereirad7192502011-09-22 08:04:45 -0700625 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700626 // In the middle of chip; treat this as an edit
627 // and commit the whole token.
Mindy Pereirad7192502011-09-22 08:04:45 -0700628 int selEnd = getSelectionEnd();
Mindy Pereira63372312011-11-15 15:23:07 -0800629 if (whatEnd != selEnd) {
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700630 handleEdit(start, whatEnd);
631 } else {
632 commitChip(start, end, editable);
633 }
634 }
Mindy Pereiraa74f40d2011-07-12 09:07:17 -0700635 }
Mindy Pereirae81f8a32011-07-12 16:11:43 -0700636 mHandler.post(mAddTextWatcher);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700637 }
Mindy Pereira3bb52162011-07-01 14:52:22 -0700638 createMoreChip();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700639 }
640
641 private void expand() {
mindyp374ccb22012-11-06 10:54:05 -0800642 if (mShouldShrink) {
643 setMaxLines(Integer.MAX_VALUE);
644 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700645 removeMoreChip();
646 setCursorVisible(true);
647 Editable text = getText();
648 setSelection(text != null && text.length() > 0 ? text.length() : 0);
Mindy Pereira18529312011-06-28 11:00:52 -0700649 // If there are any temporary chips, try replacing them now that the user
650 // has expanded the field.
651 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
652 new RecipientReplacementTask().execute();
653 mTemporaryRecipients = null;
654 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -0700655 }
656
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700657 private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700658 paint.setTextSize(mChipFontSize);
Mindy Pereira02a1f5f2011-06-10 11:03:07 -0700659 if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
660 Log.d(TAG, "Max width is negative: " + maxWidth);
661 }
662 return TextUtils.ellipsize(text, paint, maxWidth,
663 TextUtils.TruncateAt.END);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700664 }
665
Kevin Linb10d1c62014-01-24 12:45:00 -0800666 /**
667 * Creates a bitmap of the given contact on a selected chip.
668 *
669 * @param contact The recipient entry to pull data from.
670 * @param paint The paint to use to draw the bitmap.
671 */
Jin Caoffc01112014-12-15 16:24:37 -0800672 private Bitmap createChipBitmap(RecipientEntry contact, TextPaint paint) {
Kaikai Wangcb11fce2014-12-09 14:20:57 -0800673 paint.setColor(getDefaultChipTextColor(contact));
Jin Cao33515e72014-08-05 21:13:27 -0700674 ChipBitmapContainer bitmapContainer = createChipBitmap(contact, paint,
675 getChipBackground(contact), getDefaultChipBackgroundColor(contact));
Jin Cao35e82d42014-06-02 17:21:21 -0700676
677 if (bitmapContainer.loadIcon) {
Jin Cao809c5952014-08-08 12:28:17 -0700678 loadAvatarIcon(contact, bitmapContainer);
Jin Cao35e82d42014-06-02 17:21:21 -0700679 }
680 return bitmapContainer.bitmap;
Kevin Linb10d1c62014-01-24 12:45:00 -0800681 }
682
Jin Cao35e82d42014-06-02 17:21:21 -0700683 private ChipBitmapContainer createChipBitmap(RecipientEntry contact, TextPaint paint,
Jin Cao33515e72014-08-05 21:13:27 -0700684 Drawable overrideBackgroundDrawable, int backgroundColor) {
Jin Cao35e82d42014-06-02 17:21:21 -0700685 final ChipBitmapContainer result = new ChipBitmapContainer();
686
Kevin Linb10d1c62014-01-24 12:45:00 -0800687 Rect backgroundPadding = new Rect();
Jin Cao33515e72014-08-05 21:13:27 -0700688 if (overrideBackgroundDrawable != null) {
689 overrideBackgroundDrawable.getPadding(backgroundPadding);
690 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800691
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700692 // Ellipsize the text so that it takes AT MOST the entire width of the
693 // autocomplete text entry area. Make sure to leave space for padding
694 // on the sides.
Mindy Pereira6e8e8e82011-06-07 14:41:32 -0700695 int height = (int) mChipHeight;
Kevin Linb10d1c62014-01-24 12:45:00 -0800696 // 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 -0700697 // the chip. Don't include iconWidth for invalid contacts.
698 int iconWidth = contact.isValid() ?
699 height - backgroundPadding.top - backgroundPadding.bottom : 0;
Mindy Pereira6ed7ded2011-10-14 16:31:31 -0700700 float[] widths = new float[1];
701 paint.getTextWidths(" ", widths);
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700702 CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
Kevin Lin9b398e32014-02-26 12:29:10 -0800703 calculateAvailableWidth() - iconWidth - widths[0] - backgroundPadding.left
Jin Cao33515e72014-08-05 21:13:27 -0700704 - backgroundPadding.right);
Kevin Linb10d1c62014-01-24 12:45:00 -0800705 int textWidth = (int) paint.measureText(ellipsizedText, 0, ellipsizedText.length());
706
Jin Cao33515e72014-08-05 21:13:27 -0700707 // Chip start padding is the same as the end padding if there is no contact image.
708 final int startPadding = contact.isValid() ? mChipTextStartPadding : mChipTextEndPadding;
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700709 // Make sure there is a minimum chip width so the user can ALWAYS
710 // tap a chip without difficulty.
Jin Cao33515e72014-08-05 21:13:27 -0700711 int width = Math.max(iconWidth * 2, textWidth + startPadding + mChipTextEndPadding
Jin Cao58d541d2014-07-29 16:23:03 -0700712 + iconWidth + backgroundPadding.left + backgroundPadding.right);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700713
714 // Create the background of the chip.
Jin Cao35e82d42014-06-02 17:21:21 -0700715 result.bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
716 final Canvas canvas = new Canvas(result.bitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700717
Jin Cao33515e72014-08-05 21:13:27 -0700718 // Check if the background drawable is set via attr
719 if (overrideBackgroundDrawable != null) {
720 overrideBackgroundDrawable.setBounds(0, 0, width, height);
721 overrideBackgroundDrawable.draw(canvas);
722 } else {
723 // Draw the default chip background
Jin Cao6c2a0162014-08-17 15:00:50 -0700724 mWorkPaint.reset();
725 mWorkPaint.setColor(backgroundColor);
Jin Cao33515e72014-08-05 21:13:27 -0700726 final float radius = height / 2;
727 canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius,
Jin Cao6c2a0162014-08-17 15:00:50 -0700728 mWorkPaint);
Jin Cao33515e72014-08-05 21:13:27 -0700729 }
730
Kevin Linb10d1c62014-01-24 12:45:00 -0800731 // Draw the text vertically aligned
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800732 int textX = shouldPositionAvatarOnRight() ?
Jin Cao58d541d2014-07-29 16:23:03 -0700733 mChipTextEndPadding + backgroundPadding.left :
734 width - backgroundPadding.right - mChipTextEndPadding - textWidth;
Kevin Linb10d1c62014-01-24 12:45:00 -0800735 canvas.drawText(ellipsizedText, 0, ellipsizedText.length(),
Scott Kennedy15259d52014-07-09 17:28:47 -0700736 textX, getTextYOffset(height), paint);
Jin Cao35e82d42014-06-02 17:21:21 -0700737
738 // Set the variables that are needed to draw the icon bitmap once it's loaded
739 int iconX = shouldPositionAvatarOnRight() ? width - backgroundPadding.right - iconWidth :
740 backgroundPadding.left;
741 result.left = iconX;
742 result.top = backgroundPadding.top;
743 result.right = iconX + iconWidth;
744 result.bottom = height - backgroundPadding.bottom;
745
746 return result;
747 }
748
749 /**
750 * Helper function that draws the loaded icon bitmap into the chips bitmap
751 */
Jin Cao809c5952014-08-08 12:28:17 -0700752 private void drawIcon(ChipBitmapContainer bitMapResult, Bitmap icon) {
Jin Cao35e82d42014-06-02 17:21:21 -0700753 final Canvas canvas = new Canvas(bitMapResult.bitmap);
754 final RectF src = new RectF(0, 0, icon.getWidth(), icon.getHeight());
755 final RectF dst = new RectF(bitMapResult.left, bitMapResult.top, bitMapResult.right,
756 bitMapResult.bottom);
Jin Cao809c5952014-08-08 12:28:17 -0700757 drawIconOnCanvas(icon, canvas, src, dst);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700758 }
759
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700760 /**
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800761 * Returns true if the avatar should be positioned at the right edge of the chip.
762 * Takes into account both the set avatar position (start or end) as well as whether
763 * the layout direction is LTR or RTL.
764 */
765 private boolean shouldPositionAvatarOnRight() {
Jin Caoffc01112014-12-15 16:24:37 -0800766 final boolean isRtl = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 &&
767 getLayoutDirection() == LAYOUT_DIRECTION_RTL;
Andrew Sappersteinc0e60232014-01-24 19:03:35 -0800768 final boolean assignedPosition = mAvatarPosition == AVATAR_POSITION_END;
769 // If in Rtl mode, the position should be flipped.
770 return isRtl ? !assignedPosition : assignedPosition;
771 }
772
773 /**
Kevin Linb10d1c62014-01-24 12:45:00 -0800774 * Returns the avatar icon to use for this recipient entry. Returns null if we don't want to
775 * draw an icon for this recipient.
776 */
Jin Cao35e82d42014-06-02 17:21:21 -0700777 private void loadAvatarIcon(final RecipientEntry contact,
Jin Cao809c5952014-08-08 12:28:17 -0700778 final ChipBitmapContainer bitmapContainer) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800779 // Don't draw photos for recipients that have been typed in OR generated on the fly.
780 long contactId = contact.getContactId();
781 boolean drawPhotos = isPhoneQuery() ?
782 contactId != RecipientEntry.INVALID_CONTACT
783 : (contactId != RecipientEntry.INVALID_CONTACT
Jin Caobf84bd82014-07-31 10:59:27 -0700784 && contactId != RecipientEntry.GENERATED_CONTACT);
Kevin Linb10d1c62014-01-24 12:45:00 -0800785
786 if (drawPhotos) {
Jin Cao35e82d42014-06-02 17:21:21 -0700787 final byte[] origPhotoBytes = contact.getPhotoBytes();
Kevin Linb10d1c62014-01-24 12:45:00 -0800788 // There may not be a photo yet if anything but the first contact address
789 // was selected.
Jin Cao82d38852014-06-03 10:53:46 -0700790 if (origPhotoBytes == null) {
Kevin Linb10d1c62014-01-24 12:45:00 -0800791 // TODO: cache this in the recipient entry?
Jin Cao35e82d42014-06-02 17:21:21 -0700792 getAdapter().fetchPhoto(contact, new PhotoManager.PhotoManagerCallback() {
Jin Cao52e48142014-06-04 18:01:20 -0700793 @Override
Andrew Sapperstein50429c52014-06-12 15:12:10 -0700794 public void onPhotoBytesPopulated() {
795 // Call through to the async version which will ensure
796 // proper threading.
797 onPhotoBytesAsynchronouslyPopulated();
798 }
799
800 @Override
Jin Cao52e48142014-06-04 18:01:20 -0700801 public void onPhotoBytesAsynchronouslyPopulated() {
802 final byte[] loadedPhotoBytes = contact.getPhotoBytes();
803 final Bitmap icon = BitmapFactory.decodeByteArray(loadedPhotoBytes, 0,
804 loadedPhotoBytes.length);
805 tryDrawAndInvalidate(icon);
806 }
Jin Cao0efdc532014-06-04 15:35:16 -0700807
Jin Cao52e48142014-06-04 18:01:20 -0700808 @Override
809 public void onPhotoBytesAsyncLoadFailed() {
810 // TODO: can the scaled down default photo be cached?
811 tryDrawAndInvalidate(mDefaultContactPhoto);
812 }
813
814 private void tryDrawAndInvalidate(Bitmap icon) {
Jin Cao809c5952014-08-08 12:28:17 -0700815 drawIcon(bitmapContainer, icon);
Jin Cao52e48142014-06-04 18:01:20 -0700816 // The caller might originated from a background task. However, if the
817 // background task has already completed, the view might be already drawn
818 // on the UI but the callback would happen on the background thread.
819 // So if we are on a background thread, post an invalidate call to the UI.
820 if (Looper.myLooper() == Looper.getMainLooper()) {
821 // The view might not redraw itself since it's loaded asynchronously
Jin Cao0efdc532014-06-04 15:35:16 -0700822 invalidate();
Jin Cao52e48142014-06-04 18:01:20 -0700823 } else {
824 post(new Runnable() {
825 @Override
826 public void run() {
827 invalidate();
828 }
829 });
Jin Cao0efdc532014-06-04 15:35:16 -0700830 }
Jin Cao52e48142014-06-04 18:01:20 -0700831 }
Jin Cao35e82d42014-06-02 17:21:21 -0700832 });
Kevin Linb10d1c62014-01-24 12:45:00 -0800833 } else {
Jin Cao35e82d42014-06-02 17:21:21 -0700834 final Bitmap icon = BitmapFactory.decodeByteArray(origPhotoBytes, 0,
835 origPhotoBytes.length);
Jin Cao809c5952014-08-08 12:28:17 -0700836 drawIcon(bitmapContainer, icon);
Kevin Linb10d1c62014-01-24 12:45:00 -0800837 }
838 }
Kevin Linb10d1c62014-01-24 12:45:00 -0800839 }
840
841 /**
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700842 * Get the background drawable for a RecipientChip.
843 */
844 // Visible for testing.
mindypf30a4282012-12-03 12:16:33 -0800845 /* package */Drawable getChipBackground(RecipientEntry contact) {
846 return contact.isValid() ? mChipBackground : mInvalidChipBackground;
Mindy Pereiraaca23c42011-10-13 16:22:09 -0700847 }
848
Kaikai Wangcb11fce2014-12-09 14:20:57 -0800849 private int getDefaultChipTextColor(RecipientEntry contact) {
850 return contact.isValid() ? mUnselectedChipTextColor :
851 getResources().getColor(android.R.color.black);
852 }
853
Jin Cao33515e72014-08-05 21:13:27 -0700854 private int getDefaultChipBackgroundColor(RecipientEntry contact) {
Kaikai Wangcb11fce2014-12-09 14:20:57 -0800855 return contact.isValid() ? mUnselectedChipBackgroundColor :
856 getResources().getColor(R.color.chip_background_invalid);
Jin Cao33515e72014-08-05 21:13:27 -0700857 }
858
Kevin Linb10d1c62014-01-24 12:45:00 -0800859 /**
860 * Given a height, returns a Y offset that will draw the text in the middle of the height.
861 */
Scott Kennedy15259d52014-07-09 17:28:47 -0700862 protected float getTextYOffset(int height) {
863 return height - ((height - mTextHeight) / 2);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700864 }
865
Kevin Linb10d1c62014-01-24 12:45:00 -0800866 /**
Scott Kennedyb8985b72014-01-28 16:36:19 -0800867 * Draws the icon onto the canvas given the source rectangle of the bitmap and the destination
Kevin Linb10d1c62014-01-24 12:45:00 -0800868 * rectangle of the canvas.
869 */
Jin Cao809c5952014-08-08 12:28:17 -0700870 protected void drawIconOnCanvas(Bitmap icon, Canvas canvas, RectF src, RectF dst) {
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700871 final Matrix matrix = new Matrix();
872
873 // Draw bitmap through shader first.
874 final BitmapShader shader = new BitmapShader(icon, TileMode.CLAMP, TileMode.CLAMP);
875 matrix.reset();
876
877 // Fit bitmap to bounds.
Kevin Linb10d1c62014-01-24 12:45:00 -0800878 matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700879
880 shader.setLocalMatrix(matrix);
Jin Cao809c5952014-08-08 12:28:17 -0700881 mWorkPaint.reset();
882 mWorkPaint.setShader(shader);
883 mWorkPaint.setAntiAlias(true);
884 mWorkPaint.setFilterBitmap(true);
885 mWorkPaint.setDither(true);
886 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f, mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700887
888 // Then draw the border.
889 final float borderWidth = 1f;
Jin Cao809c5952014-08-08 12:28:17 -0700890 mWorkPaint.reset();
891 mWorkPaint.setColor(Color.TRANSPARENT);
892 mWorkPaint.setStyle(Style.STROKE);
893 mWorkPaint.setStrokeWidth(borderWidth);
894 mWorkPaint.setAntiAlias(true);
Jin Caoffc01112014-12-15 16:24:37 -0800895 canvas.drawCircle(dst.centerX(), dst.centerY(), dst.width() / 2f - borderWidth / 2,
896 mWorkPaint);
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700897
Jin Cao809c5952014-08-08 12:28:17 -0700898 mWorkPaint.reset();
Kevin Linb10d1c62014-01-24 12:45:00 -0800899 }
900
Jin Caoffc01112014-12-15 16:24:37 -0800901 private DrawableRecipientChip constructChipSpan(RecipientEntry contact) {
Mindy Pereiracd611952011-06-01 17:02:20 -0700902 TextPaint paint = getPaint();
903 float defaultSize = paint.getTextSize();
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700904 int defaultColor = paint.getColor();
Mindy Pereiracd611952011-06-01 17:02:20 -0700905
Jin Caoffc01112014-12-15 16:24:37 -0800906 Bitmap tmpBitmap = createChipBitmap(contact, paint);
Mindy Pereiracd611952011-06-01 17:02:20 -0700907
Mindy Pereiracd611952011-06-01 17:02:20 -0700908 // Pass the full text, un-ellipsized, to the chip.
909 Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
Mindy Pereira2bfe48e2011-06-03 11:44:43 -0700910 result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
Jin Cao6c2a0162014-08-17 15:00:50 -0700911 VisibleRecipientChip recipientChip =
912 new VisibleRecipientChip(result, contact);
913 recipientChip.setExtraMargin(mLineSpacingExtra);
Mindy Pereiracd611952011-06-01 17:02:20 -0700914 // Return text to the original size.
915 paint.setTextSize(defaultSize);
Mindy Pereirae50b0a12011-06-15 16:16:38 -0700916 paint.setColor(defaultColor);
Mindy Pereiracd611952011-06-01 17:02:20 -0700917 return recipientChip;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700918 }
919
Mindy Pereiraa8166902011-06-09 17:53:23 -0700920 /**
Mindy Pereira34214202011-06-09 20:05:32 -0700921 * Calculate the bottom of the line the chip will be located on using:
922 * 1) which line the chip appears on
Mindy Pereira21625f82011-06-16 18:10:58 -0700923 * 2) the height of a chip
924 * 3) padding built into the edit text view
Mindy Pereiraa8166902011-06-09 17:53:23 -0700925 */
Mindy Pereira81fd3d12011-07-06 14:40:50 -0700926 private int calculateOffsetFromBottom(int line) {
Mindy Pereira21625f82011-06-16 18:10:58 -0700927 // Line offsets start at zero.
Mindy Pereirac1fed8b2011-07-01 13:46:27 -0700928 int actualLine = getLineCount() - (line + 1);
Mindy Pereira1d37d972011-08-17 10:37:59 -0700929 return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
930 + getDropDownVerticalOffset();
Mindy Pereiraf621a602011-05-31 10:09:35 -0700931 }
932
Mindy Pereiraa8166902011-06-09 17:53:23 -0700933 /**
Jin Cao6fc1fee2014-07-29 17:56:44 -0700934 * Calculate the offset from bottom of the EditText to top of the provided line.
935 */
936 private int calculateOffsetFromBottomToTop(int line) {
937 return -(int) ((mChipHeight + (2 * mLineSpacingExtra)) * (Math
938 .abs(getLineCount() - line)) + getPaddingBottom());
939 }
940
941 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -0700942 * Get the max amount of space a chip can take up. The formula takes into
943 * account the width of the EditTextView, any view padding, and padding
944 * that will be added to the chip.
945 */
Scott Kennedyf7e202d2013-03-06 21:38:10 -0800946 private float calculateAvailableWidth() {
Jin Cao58d541d2014-07-29 16:23:03 -0700947 return getWidth() - getPaddingLeft() - getPaddingRight() - mChipTextStartPadding
948 - mChipTextEndPadding;
Mindy Pereira9159cd22011-05-25 17:06:44 -0700949 }
950
Mindy Pereira52c441e2011-12-15 13:35:37 -0800951
Mindy Pereira22faaa62011-12-16 14:30:34 -0800952 private void setChipDimensions(Context context, AttributeSet attrs) {
Mindy Pereira5da02342011-12-16 14:56:27 -0800953 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
954 0);
Mindy Pereira52c441e2011-12-15 13:35:37 -0800955 Resources r = getContext().getResources();
mindyp8c474ec2012-12-14 10:58:44 -0800956
Mindy Pereira22faaa62011-12-16 14:30:34 -0800957 mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
Jin Cao33515e72014-08-05 21:13:27 -0700958 mInvalidChipBackground = a
959 .getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
Mindy Pereira5da02342011-12-16 14:56:27 -0800960 mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
961 if (mChipDelete == null) {
Jin Caoa21fd882014-08-10 13:07:11 -0700962 mChipDelete = r.getDrawable(R.drawable.ic_cancel_wht_24dp);
Mindy Pereira5da02342011-12-16 14:56:27 -0800963 }
Jin Cao58d541d2014-07-29 16:23:03 -0700964 mChipTextStartPadding = mChipTextEndPadding
965 = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
966 if (mChipTextStartPadding == -1) {
967 mChipTextStartPadding = mChipTextEndPadding =
968 (int) r.getDimension(R.dimen.chip_padding);
969 }
970 // xml-overrides for each individual padding
971 // TODO: add these to attr?
972 int overridePadding = (int) r.getDimension(R.dimen.chip_padding_start);
973 if (overridePadding >= 0) {
974 mChipTextStartPadding = overridePadding;
975 }
976 overridePadding = (int) r.getDimension(R.dimen.chip_padding_end);
977 if (overridePadding >= 0) {
978 mChipTextEndPadding = overridePadding;
Mindy Pereira5da02342011-12-16 14:56:27 -0800979 }
Mindy Pereira5da02342011-12-16 14:56:27 -0800980
981 mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
982
Mindy Pereira52c441e2011-12-15 13:35:37 -0800983 mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
Mindy Pereira5da02342011-12-16 14:56:27 -0800984
985 mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
986 if (mChipHeight == -1) {
987 mChipHeight = r.getDimension(R.dimen.chip_height);
988 }
989 mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
990 if (mChipFontSize == -1) {
991 mChipFontSize = r.getDimension(R.dimen.chip_text_size);
992 }
Scott Kennedyb232e5c2014-07-09 16:29:35 -0700993 mAvatarPosition =
994 a.getInt(R.styleable.RecipientEditTextView_avatarPosition, AVATAR_POSITION_START);
Scott Kennedyb8985b72014-01-28 16:36:19 -0800995 mDisableDelete = a.getBoolean(R.styleable.RecipientEditTextView_disableDelete, false);
Kevin Linb10d1c62014-01-24 12:45:00 -0800996
mindypf30a4282012-12-03 12:16:33 -0800997 mMaxLines = r.getInteger(R.integer.chips_max_lines);
Jin Cao6c2a0162014-08-17 15:00:50 -0700998 mLineSpacingExtra = r.getDimensionPixelOffset(R.dimen.line_spacing_extra);
Kevin Linb10d1c62014-01-24 12:45:00 -0800999
Kaikai Wangcb11fce2014-12-09 14:20:57 -08001000 mUnselectedChipTextColor = a.getColor(
1001 R.styleable.RecipientEditTextView_unselectedChipTextColor,
1002 r.getColor(android.R.color.black));
1003
1004 mSelectedChipTextColor = a.getColor(
1005 R.styleable.RecipientEditTextView_selectedChipTextColor,
1006 r.getColor(android.R.color.white));
1007
1008 mUnselectedChipBackgroundColor = a.getColor(
1009 R.styleable.RecipientEditTextView_unselectedChipBackgroundColor,
1010 r.getColor(R.color.chip_background));
1011
1012 mSelectedChipBackgroundColor = a.getColor(
1013 R.styleable.RecipientEditTextView_selectedChipBackgroundColor,
1014 r.getColor(R.color.chip_background_selected));
Mindy Pereiraef798002012-05-02 11:04:25 -07001015 a.recycle();
Mindy Pereira52c441e2011-12-15 13:35:37 -08001016 }
1017
Mindy Pereirad7192502011-09-22 08:04:45 -07001018 // Visible for testing.
1019 /* package */ void setMoreItem(TextView moreItem) {
1020 mMoreItem = moreItem;
1021 }
1022
Mindy Pereira97cb2592011-09-26 16:11:41 -07001023
1024 // Visible for testing.
1025 /* package */ void setChipBackground(Drawable chipBackground) {
1026 mChipBackground = chipBackground;
1027 }
1028
1029 // Visible for testing.
1030 /* package */ void setChipHeight(int height) {
1031 mChipHeight = height;
1032 }
1033
Kevin Linb10d1c62014-01-24 12:45:00 -08001034 public float getChipHeight() {
1035 return mChipHeight;
1036 }
1037
Mindy Pereira076d1f92011-08-08 11:53:12 -07001038 /**
1039 * Set whether to shrink the recipients field such that at most
1040 * one line of recipients chips are shown when the field loses
1041 * focus. By default, the number of displayed recipients will be
1042 * limited and a "more" chip will be shown when focus is lost.
1043 * @param shrink
1044 */
1045 public void setOnFocusListShrinkRecipients(boolean shrink) {
1046 mShouldShrink = shrink;
1047 }
1048
Mindy Pereiracd611952011-06-01 17:02:20 -07001049 @Override
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001050 public void onSizeChanged(int width, int height, int oldw, int oldh) {
1051 super.onSizeChanged(width, height, oldw, oldh);
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001052 if (width != 0 && height != 0) {
1053 if (mPendingChipsCount > 0) {
1054 postHandlePendingChips();
1055 } else {
1056 checkChipWidths();
1057 }
Mindy Pereira8005f422011-07-20 13:16:53 -07001058 }
Mindy Pereira18529312011-06-28 11:00:52 -07001059 // Try to find the scroll view parent, if it exists.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001060 if (mScrollView == null && !mTriedGettingScrollView) {
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001061 ViewParent parent = getParent();
1062 while (parent != null && !(parent instanceof ScrollView)) {
1063 parent = parent.getParent();
1064 }
1065 if (parent != null) {
1066 mScrollView = (ScrollView) parent;
1067 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001068 mTriedGettingScrollView = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001069 }
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001070 }
1071
Mindy Pereira2cac2312011-07-20 11:38:59 -07001072 private void postHandlePendingChips() {
1073 mHandler.removeCallbacks(mHandlePendingChips);
1074 mHandler.post(mHandlePendingChips);
1075 }
Mindy Pereira18529312011-06-28 11:00:52 -07001076
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001077 private void checkChipWidths() {
1078 // Check the widths of the associated chips.
Scott Kennedy194d4272013-03-06 22:06:45 -08001079 DrawableRecipientChip[] chips = getSortedRecipients();
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001080 if (chips != null) {
1081 Rect bounds;
Scott Kennedy194d4272013-03-06 22:06:45 -08001082 for (DrawableRecipientChip chip : chips) {
mindypf30a4282012-12-03 12:16:33 -08001083 bounds = chip.getBounds();
Kevin Linc61c13f2014-02-28 15:04:40 -08001084 if (getWidth() > 0 && bounds.right - bounds.left >
1085 getWidth() - getPaddingLeft() - getPaddingRight()) {
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001086 // Need to redraw that chip.
1087 replaceChip(chip, chip.getEntry());
1088 }
1089 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001090 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001091 }
1092
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001093 // Visible for testing.
1094 /*package*/ void handlePendingChips() {
1095 if (getViewWidth() <= 0) {
Mindy Pereira8005f422011-07-20 13:16:53 -07001096 // The widget has not been sized yet.
1097 // This will be called as a result of onSizeChanged
1098 // at a later point.
1099 return;
1100 }
Mindy Pereiradb1ca652011-09-26 08:49:35 -07001101 if (mPendingChipsCount <= 0) {
1102 return;
1103 }
1104
Mindy Pereira2cac2312011-07-20 11:38:59 -07001105 synchronized (mPendingChips) {
Mindy Pereira2cac2312011-07-20 11:38:59 -07001106 Editable editable = getText();
1107 // Tokenize!
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001108 if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
1109 for (int i = 0; i < mPendingChips.size(); i++) {
1110 String current = mPendingChips.get(i);
1111 int tokenStart = editable.toString().indexOf(current);
mindyp488718e2012-12-18 11:48:07 -08001112 // Always leave a space at the end between tokens.
1113 int tokenEnd = tokenStart + current.length() - 1;
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001114 if (tokenStart >= 0) {
1115 // When we have a valid token, include it with the token
1116 // to the left.
1117 if (tokenEnd < editable.length() - 2
1118 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
1119 tokenEnd++;
1120 }
mindypf30a4282012-12-03 12:16:33 -08001121 createReplacementChip(tokenStart, tokenEnd, editable, i < CHIP_LIMIT
1122 || !mShouldShrink);
Mindy Pereira2cac2312011-07-20 11:38:59 -07001123 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001124 mPendingChipsCount--;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001125 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001126 sanitizeEnd();
1127 } else {
1128 mNoChips = true;
Mindy Pereira2cac2312011-07-20 11:38:59 -07001129 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001130
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001131 if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
Mindy Pereira2cac2312011-07-20 11:38:59 -07001132 && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
1133 if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
1134 new RecipientReplacementTask().execute();
1135 mTemporaryRecipients = null;
1136 } else {
1137 // Create the "more" chip
1138 mIndividualReplacements = new IndividualReplacementTask();
Scott Kennedy194d4272013-03-06 22:06:45 -08001139 mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(
Mindy Pereira2cac2312011-07-20 11:38:59 -07001140 mTemporaryRecipients.subList(0, CHIP_LIMIT)));
mindyp5e60c2b2012-11-06 17:47:40 -08001141 if (mTemporaryRecipients.size() > CHIP_LIMIT) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001142 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>(
mindyp5e60c2b2012-11-06 17:47:40 -08001143 mTemporaryRecipients.subList(CHIP_LIMIT,
1144 mTemporaryRecipients.size()));
1145 } else {
1146 mTemporaryRecipients = null;
1147 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001148 createMoreChip();
1149 }
1150 } else {
1151 // There are too many recipients to look up, so just fall back
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001152 // to showing addresses for all of them.
Mindy Pereira2cac2312011-07-20 11:38:59 -07001153 mTemporaryRecipients = null;
Mindy Pereira18529312011-06-28 11:00:52 -07001154 createMoreChip();
1155 }
Mindy Pereira2cac2312011-07-20 11:38:59 -07001156 mPendingChipsCount = 0;
1157 mPendingChips.clear();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001158 }
1159 }
1160
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001161 // Visible for testing.
1162 /*package*/ int getViewWidth() {
1163 return getWidth();
1164 }
1165
Mindy Pereira3bb52162011-07-01 14:52:22 -07001166 /**
1167 * Remove any characters after the last valid chip.
1168 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001169 // Visible for testing.
1170 /*package*/ void sanitizeEnd() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001171 // Don't sanitize while we are waiting for pending chips to complete.
1172 if (mPendingChipsCount > 0) {
1173 return;
1174 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001175 // Find the last chip; eliminate any commit characters after it.
Scott Kennedy194d4272013-03-06 22:06:45 -08001176 DrawableRecipientChip[] chips = getSortedRecipients();
mindypf30a4282012-12-03 12:16:33 -08001177 Spannable spannable = getSpannable();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001178 if (chips != null && chips.length > 0) {
1179 int end;
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001180 mMoreChip = getMoreChip();
Mindy Pereira3bb52162011-07-01 14:52:22 -07001181 if (mMoreChip != null) {
mindypf30a4282012-12-03 12:16:33 -08001182 end = spannable.getSpanEnd(mMoreChip);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001183 } else {
mindypf30a4282012-12-03 12:16:33 -08001184 end = getSpannable().getSpanEnd(getLastChip());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001185 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001186 Editable editable = getText();
1187 int length = editable.length();
1188 if (length > end) {
1189 // See what characters occur after that and eliminate them.
1190 if (Log.isLoggable(TAG, Log.DEBUG)) {
1191 Log.d(TAG, "There were extra characters after the last tokenizable entry."
1192 + editable);
1193 }
1194 editable.delete(end + 1, length);
1195 }
1196 }
1197 }
1198
1199 /**
1200 * Create a chip that represents just the email address of a recipient. At some later
1201 * point, this chip will be attached to a real contact entry, if one exists.
1202 */
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001203 // VisibleForTesting
1204 void createReplacementChip(int tokenStart, int tokenEnd, Editable editable,
mindypf30a4282012-12-03 12:16:33 -08001205 boolean visible) {
Mindy Pereira32366d42011-07-24 12:39:30 -07001206 if (alreadyHasChip(tokenStart, tokenEnd)) {
1207 // There is already a chip present at this location.
1208 // Don't recreate it.
1209 return;
1210 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07001211 String token = editable.toString().substring(tokenStart, tokenEnd);
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001212 final String trimmedToken = token.trim();
1213 int commitCharIndex = trimmedToken.lastIndexOf(COMMIT_CHAR_COMMA);
Tom Taylor41137c22013-03-26 12:22:56 -07001214 if (commitCharIndex != -1 && commitCharIndex == trimmedToken.length() - 1) {
Scott Kennedy20c8aa72013-03-06 22:23:59 -08001215 token = trimmedToken.substring(0, trimmedToken.length() - 1);
Mindy Pereira3bb52162011-07-01 14:52:22 -07001216 }
1217 RecipientEntry entry = createTokenizedEntry(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001218 if (entry != null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001219 DrawableRecipientChip chip = null;
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001220 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001221 if (!mNoChips) {
Jin Caoffc01112014-12-15 16:24:37 -08001222 chip = visible ? constructChipSpan(entry) : new InvisibleRecipientChip(entry);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001223 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001224 } catch (NullPointerException e) {
1225 Log.e(TAG, e.getMessage(), e);
1226 }
mindypcb76b4d2012-11-09 14:05:19 -08001227 editable.setSpan(chip, tokenStart, tokenEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001228 // Add this chip to the list of entries "to replace"
1229 if (chip != null) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001230 if (mTemporaryRecipients == null) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001231 mTemporaryRecipients = new ArrayList<DrawableRecipientChip>();
Mindy Pereiradc04cd72011-09-16 15:42:09 -07001232 }
Scott Kennedy0613ff82013-03-05 14:02:46 -08001233 chip.setOriginalText(token);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001234 mTemporaryRecipients.add(chip);
1235 }
Mindy Pereira18529312011-06-28 11:00:52 -07001236 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001237 }
1238
Tom Taylorabff6062012-04-17 09:04:56 -07001239 private static boolean isPhoneNumber(String number) {
1240 // TODO: replace this function with libphonenumber's isPossibleNumber (see
1241 // PhoneNumberUtil). One complication is that it requires the sender's region which
1242 // comes from the CurrentCountryIso. For now, let's just do this simple match.
1243 if (TextUtils.isEmpty(number)) {
1244 return false;
1245 }
1246
Tom Taylor4491a062012-11-15 13:57:41 -08001247 Matcher match = PHONE_PATTERN.matcher(number);
Tom Taylorabff6062012-04-17 09:04:56 -07001248 return match.matches();
1249 }
1250
Scott Kennedy983c99b2013-03-22 09:42:03 -07001251 // VisibleForTesting
1252 RecipientEntry createTokenizedEntry(final String token) {
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001253 if (TextUtils.isEmpty(token)) {
1254 return null;
1255 }
mindyp5e60c2b2012-11-06 17:47:40 -08001256 if (isPhoneQuery() && isPhoneNumber(token)) {
Tom Taylor0ba91332013-03-21 10:28:50 -07001257 return RecipientEntry.constructFakePhoneEntry(token, true);
mindyp5e60c2b2012-11-06 17:47:40 -08001258 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001259 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
mindypf30a4282012-12-03 12:16:33 -08001260 boolean isValid = isValid(token);
1261 if (isValid && tokens != null && tokens.length > 0) {
Mindy Pereiraee58f492011-08-08 13:16:46 -07001262 // If we can get a name from tokenizing, then generate an entry from
1263 // this.
Jin Caoffc01112014-12-15 16:24:37 -08001264 String display = tokens[0].getName();
Mindy Pereira01382d72011-07-15 16:52:32 -07001265 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001266 return RecipientEntry.constructGeneratedEntry(display, tokens[0].getAddress(),
1267 isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001268 } else {
1269 display = tokens[0].getAddress();
1270 if (!TextUtils.isEmpty(display)) {
mindypf30a4282012-12-03 12:16:33 -08001271 return RecipientEntry.constructFakeEntry(display, isValid);
Mindy Pereira401cd962011-08-09 11:29:58 -07001272 }
Mindy Pereira01382d72011-07-15 16:52:32 -07001273 }
Mindy Pereira3bb52162011-07-01 14:52:22 -07001274 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001275 // Unable to validate the token or to create a valid token from it.
1276 // Just create a chip the user can edit.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001277 String validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001278 if (mValidator != null && !isValid) {
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001279 // Try fixing up the entry using the validator.
Mindy Pereiradbb85602011-09-16 14:02:14 -07001280 validatedToken = mValidator.fixText(token).toString();
1281 if (!TextUtils.isEmpty(validatedToken)) {
1282 if (validatedToken.contains(token)) {
mindypf30a4282012-12-03 12:16:33 -08001283 // protect against the case of a validator with a null
1284 // domain,
Mindy Pereiradbb85602011-09-16 14:02:14 -07001285 // which doesn't add a domain to the token
1286 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
1287 if (tokenized.length > 0) {
1288 validatedToken = tokenized[0].getAddress();
mindypf30a4282012-12-03 12:16:33 -08001289 isValid = true;
Mindy Pereiradbb85602011-09-16 14:02:14 -07001290 }
1291 } else {
mindypf30a4282012-12-03 12:16:33 -08001292 // We ran into a case where the token was invalid and
1293 // removed
1294 // by the validator. In this case, just use the original
1295 // token
Mindy Pereiradbb85602011-09-16 14:02:14 -07001296 // and let the user sort out the error chip.
1297 validatedToken = null;
mindypf30a4282012-12-03 12:16:33 -08001298 isValid = false;
Erik184d3772011-08-04 16:07:00 -07001299 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001300 }
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001301 }
Mindy Pereiraee58f492011-08-08 13:16:46 -07001302 // Otherwise, fallback to just creating an editable email address chip.
mindypf30a4282012-12-03 12:16:33 -08001303 return RecipientEntry.constructFakeEntry(
1304 !TextUtils.isEmpty(validatedToken) ? validatedToken : token, isValid);
Mindy Pereira01382d72011-07-15 16:52:32 -07001305 }
1306
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07001307 private boolean isValid(String text) {
1308 return mValidator == null ? true : mValidator.isValid(text);
1309 }
1310
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001311 private static String tokenizeAddress(String destination) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001312 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
1313 if (tokens != null && tokens.length > 0) {
1314 return tokens[0].getAddress();
1315 }
1316 return destination;
Mindy Pereira3bb52162011-07-01 14:52:22 -07001317 }
1318
Mindy Pereira02a1f5f2011-06-10 11:03:07 -07001319 @Override
Mindy Pereiracd611952011-06-01 17:02:20 -07001320 public void setTokenizer(Tokenizer tokenizer) {
1321 mTokenizer = tokenizer;
1322 super.setTokenizer(mTokenizer);
1323 }
1324
Mindy Pereiraa8166902011-06-09 17:53:23 -07001325 @Override
1326 public void setValidator(Validator validator) {
1327 mValidator = validator;
1328 super.setValidator(validator);
1329 }
1330
1331 /**
1332 * We cannot use the default mechanism for replaceText. Instead,
1333 * we override onItemClickListener so we can get all the associated
1334 * contact information including display text, address, and id.
1335 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001336 @Override
1337 protected void replaceText(CharSequence text) {
1338 return;
1339 }
1340
Mindy Pereiraa8166902011-06-09 17:53:23 -07001341 /**
1342 * Dismiss any selected chips when the back key is pressed.
1343 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001344 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001345 public boolean onKeyPreIme(int keyCode, @NonNull KeyEvent event) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001346 if (keyCode == KeyEvent.KEYCODE_BACK && mSelectedChip != null) {
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001347 clearSelectedChip();
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001348 return true;
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001349 }
1350 return super.onKeyPreIme(keyCode, event);
1351 }
1352
Mindy Pereiraa8166902011-06-09 17:53:23 -07001353 /**
1354 * Monitor key presses in this view to see if the user types
1355 * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
1356 * If the user has entered text that has contact matches and types
1357 * a commit key, create a chip from the topmost matching contact.
1358 * If the user has entered text that has no contact matches and types
1359 * a commit key, then create a chip from the text they have entered.
1360 */
Mindy Pereira4c5fc2c2011-06-07 10:02:30 -07001361 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001362 public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001363 switch (keyCode) {
Mindy Pereira0f0df292011-06-16 20:49:51 -07001364 case KeyEvent.KEYCODE_TAB:
1365 if (event.hasNoModifiers()) {
1366 if (mSelectedChip != null) {
1367 clearSelectedChip();
1368 } else {
1369 commitDefault();
1370 }
Mindy Pereira0f0df292011-06-16 20:49:51 -07001371 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07001372 break;
Mindy Pereiracd611952011-06-01 17:02:20 -07001373 }
1374 return super.onKeyUp(keyCode, event);
1375 }
1376
Mindy Pereira0f0df292011-06-16 20:49:51 -07001377 private boolean focusNext() {
1378 View next = focusSearch(View.FOCUS_DOWN);
1379 if (next != null) {
1380 next.requestFocus();
1381 return true;
1382 }
1383 return false;
1384 }
1385
Mindy Pereira34214202011-06-09 20:05:32 -07001386 /**
1387 * Create a chip from the default selection. If the popup is showing, the
Scott Kennedye4945e92014-04-21 20:17:43 -07001388 * default is the selected item (if one is selected), or the first item, in the popup
1389 * suggestions list. Otherwise, it is whatever the user had typed in. End represents where the
1390 * tokenizer should search for a token to turn into a chip.
Mindy Pereira34214202011-06-09 20:05:32 -07001391 * @return If a chip was created from a real contact.
1392 */
Mindy Pereiraa8166902011-06-09 17:53:23 -07001393 private boolean commitDefault() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001394 // If there is no tokenizer, don't try to commit.
1395 if (mTokenizer == null) {
1396 return false;
1397 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001398 Editable editable = getText();
Mindy Pereira34214202011-06-09 20:05:32 -07001399 int end = getSelectionEnd();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001400 int start = mTokenizer.findTokenStart(editable, end);
Mindy Pereira2b4ffc52011-06-20 13:20:09 -07001401
Mindy Pereira79fb4362011-06-21 14:37:07 -07001402 if (shouldCreateChip(start, end)) {
1403 int whatEnd = mTokenizer.findTokenEnd(getText(), start);
1404 // In the middle of chip; treat this as an edit
1405 // and commit the whole token.
mindyp4f82d882012-11-08 16:30:27 -08001406 whatEnd = movePastTerminators(whatEnd);
Mindy Pereira79fb4362011-06-21 14:37:07 -07001407 if (whatEnd != getSelectionEnd()) {
1408 handleEdit(start, whatEnd);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001409 return true;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001410 }
1411 return commitChip(start, end , editable);
1412 }
1413 return false;
1414 }
1415
1416 private void commitByCharacter() {
Mindy Pereira60d96dc2012-04-27 09:15:48 -07001417 // We can't possibly commit by character if we can't tokenize.
1418 if (mTokenizer == null) {
1419 return;
1420 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001421 Editable editable = getText();
1422 int end = getSelectionEnd();
1423 int start = mTokenizer.findTokenStart(editable, end);
1424 if (shouldCreateChip(start, end)) {
1425 commitChip(start, end, editable);
1426 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001427 setSelection(getText().length());
Mindy Pereira79fb4362011-06-21 14:37:07 -07001428 }
1429
1430 private boolean commitChip(int start, int end, Editable editable) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07001431 ListAdapter adapter = getAdapter();
1432 if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
Tom Taylorc7a87f02012-05-03 15:21:08 -07001433 && end == getSelectionEnd() && !isPhoneQuery()) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001434 // let's choose the selected or first entry if only the input text is NOT an email
1435 // address so we won't try to replace the user's potentially correct but
1436 // new/unencountered email input
Jin Caob3b248a2014-04-11 10:43:50 -07001437 if (!isValidEmailAddress(editable.toString().substring(start, end).trim())) {
Scott Kennedye4945e92014-04-21 20:17:43 -07001438 final int selectedPosition = getListSelection();
1439 if (selectedPosition == -1) {
1440 // Nothing is selected; use the first item
1441 submitItemAtPosition(0);
1442 } else {
1443 submitItemAtPosition(selectedPosition);
1444 }
Jin Caob3b248a2014-04-11 10:43:50 -07001445 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001446 dismissDropDown();
1447 return true;
1448 } else {
1449 int tokenEnd = mTokenizer.findTokenEnd(editable, start);
Mindy Pereira20c9d622011-10-12 13:18:04 -07001450 if (editable.length() > tokenEnd + 1) {
1451 char charAt = editable.charAt(tokenEnd + 1);
1452 if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
1453 tokenEnd++;
1454 }
Mindy Pereirad7192502011-09-22 08:04:45 -07001455 }
Mindy Pereira62397a52011-10-03 13:46:43 -07001456 String text = editable.toString().substring(start, tokenEnd).trim();
Mindy Pereira79fb4362011-06-21 14:37:07 -07001457 clearComposingText();
Jin Caoffc01112014-12-15 16:24:37 -08001458 if (text.length() > 0 && !text.equals(" ")) {
Mindy Pereira01382d72011-07-15 16:52:32 -07001459 RecipientEntry entry = createTokenizedEntry(text);
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001460 if (entry != null) {
1461 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Jin Caoffc01112014-12-15 16:24:37 -08001462 CharSequence chipText = createChip(entry);
Mindy Pereiraee6d83f2011-10-03 14:25:07 -07001463 if (chipText != null && start > -1 && end > -1) {
Mindy Pereiraf177bda2011-09-15 11:23:49 -07001464 editable.replace(start, end, chipText);
1465 }
Mindy Pereiraba5642a2011-07-28 13:04:33 -07001466 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07001467 // Only dismiss the dropdown if it is related to the text we
1468 // just committed.
1469 // For paste, it may not be as there are possibly multiple
1470 // tokens being added.
1471 if (end == getSelectionEnd()) {
1472 dismissDropDown();
1473 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001474 sanitizeBetween();
Mindy Pereira0f0df292011-06-16 20:49:51 -07001475 return true;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001476 }
1477 }
1478 return false;
Mindy Pereira05dbd332011-06-03 09:37:44 -07001479 }
1480
Mindy Pereira01162ce2011-09-20 12:21:55 -07001481 // Visible for testing.
1482 /* package */ void sanitizeBetween() {
Mindy Pereira3c42baf2012-01-10 13:20:17 -08001483 // Don't sanitize while we are waiting for content to chipify.
1484 if (mPendingChipsCount > 0) {
1485 return;
1486 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001487 // Find the last chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08001488 DrawableRecipientChip[] recips = getSortedRecipients();
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001489 if (recips != null && recips.length > 0) {
Scott Kennedy194d4272013-03-06 22:06:45 -08001490 DrawableRecipientChip last = recips[recips.length - 1];
1491 DrawableRecipientChip beforeLast = null;
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001492 if (recips.length > 1) {
1493 beforeLast = recips[recips.length - 2];
1494 }
1495 int startLooking = 0;
1496 int end = getSpannable().getSpanStart(last);
1497 if (beforeLast != null) {
1498 startLooking = getSpannable().getSpanEnd(beforeLast);
Mindy Pereira399bda82011-09-20 11:18:26 -07001499 Editable text = getText();
Mindy Pereira01162ce2011-09-20 12:21:55 -07001500 if (startLooking == -1 || startLooking > text.length() - 1) {
Mindy Pereira399bda82011-09-20 11:18:26 -07001501 // There is nothing after this chip.
1502 return;
1503 }
1504 if (text.charAt(startLooking) == ' ') {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001505 startLooking++;
1506 }
1507 }
Mindy Pereirae13775c2011-11-17 11:14:12 -08001508 if (startLooking >= 0 && end >= 0 && startLooking < end) {
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001509 getText().delete(startLooking, end);
1510 }
1511 }
1512 }
1513
Mindy Pereira79fb4362011-06-21 14:37:07 -07001514 private boolean shouldCreateChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001515 return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
Mindy Pereira32366d42011-07-24 12:39:30 -07001516 }
1517
1518 private boolean alreadyHasChip(int start, int end) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001519 if (mNoChips) {
1520 return true;
1521 }
Scott Kennedy194d4272013-03-06 22:06:45 -08001522 DrawableRecipientChip[] chips =
1523 getSpannable().getSpans(start, end, DrawableRecipientChip.class);
Jin Caoffc01112014-12-15 16:24:37 -08001524 return chips != null && chips.length > 0;
Mindy Pereira79fb4362011-06-21 14:37:07 -07001525 }
1526
1527 private void handleEdit(int start, int end) {
Mindy Pereiraa49e7fa2011-09-13 08:01:36 -07001528 if (start == -1 || end == -1) {
1529 // This chip no longer exists in the field.
1530 dismissDropDown();
1531 return;
1532 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07001533 // This is in the middle of a chip, so select out the whole chip
1534 // and commit it.
1535 Editable editable = getText();
1536 setSelection(end);
1537 String text = getText().toString().substring(start, end);
Mindy Pereirafe52b972011-09-16 11:55:57 -07001538 if (!TextUtils.isEmpty(text)) {
mindypf30a4282012-12-03 12:16:33 -08001539 RecipientEntry entry = RecipientEntry.constructFakeEntry(text, isValid(text));
Mindy Pereirafe52b972011-09-16 11:55:57 -07001540 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Jin Caoffc01112014-12-15 16:24:37 -08001541 CharSequence chipText = createChip(entry);
Mindy Pereira5cfd6fe2011-10-20 15:36:24 -07001542 int selEnd = getSelectionEnd();
1543 if (chipText != null && start > -1 && selEnd > -1) {
1544 editable.replace(start, selEnd, chipText);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001545 }
Mindy Pereirafe52b972011-09-16 11:55:57 -07001546 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07001547 dismissDropDown();
Mindy Pereira64af2da2011-06-15 11:14:07 -07001548 }
1549
Mindy Pereiraa8166902011-06-09 17:53:23 -07001550 /**
1551 * If there is a selected chip, delegate the key events
1552 * to the selected chip.
1553 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001554 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001555 public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001556 if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
1557 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
1558 mAlternatesPopup.dismiss();
1559 }
1560 removeChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001561 }
1562
Scott Kennedy2fe0cff2013-02-14 18:39:37 -08001563 switch (keyCode) {
1564 case KeyEvent.KEYCODE_ENTER:
1565 case KeyEvent.KEYCODE_DPAD_CENTER:
1566 if (event.hasNoModifiers()) {
1567 if (commitDefault()) {
1568 return true;
1569 }
1570 if (mSelectedChip != null) {
1571 clearSelectedChip();
1572 return true;
1573 } else if (focusNext()) {
1574 return true;
1575 }
1576 }
1577 break;
1578 }
1579
Mindy Pereiracd611952011-06-01 17:02:20 -07001580 return super.onKeyDown(keyCode, event);
1581 }
1582
Mindy Pereira01162ce2011-09-20 12:21:55 -07001583 // Visible for testing.
1584 /* package */ Spannable getSpannable() {
Erike33555f2011-06-21 14:20:20 -07001585 return getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001586 }
1587
Scott Kennedy194d4272013-03-06 22:06:45 -08001588 private int getChipStart(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001589 return getSpannable().getSpanStart(chip);
1590 }
1591
Scott Kennedy194d4272013-03-06 22:06:45 -08001592 private int getChipEnd(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001593 return getSpannable().getSpanEnd(chip);
1594 }
1595
Mindy Pereiracd611952011-06-01 17:02:20 -07001596 /**
1597 * Instead of filtering on the entire contents of the edit box,
1598 * this subclass method filters on the range from
1599 * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
1600 * if the length of that range meets or exceeds {@link #getThreshold}
1601 * and makes sure that the range is not already a Chip.
1602 */
1603 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001604 protected void performFiltering(@NonNull CharSequence text, int keyCode) {
mindyp093ecdd2012-12-14 10:40:51 -08001605 boolean isCompletedToken = isCompletedToken(text);
1606 if (enoughToFilter() && !isCompletedToken) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001607 int end = getSelectionEnd();
1608 int start = mTokenizer.findTokenStart(text, end);
1609 // If this is a RecipientChip, don't filter
1610 // on its contents.
1611 Spannable span = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001612 DrawableRecipientChip[] chips = span.getSpans(start, end, DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001613 if (chips != null && chips.length > 0) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001614 dismissDropDown();
Mindy Pereiracd611952011-06-01 17:02:20 -07001615 return;
1616 }
mindyp093ecdd2012-12-14 10:40:51 -08001617 } else if (isCompletedToken) {
Kevin Lin41e93fb2014-02-03 17:35:29 -08001618 dismissDropDown();
mindyp093ecdd2012-12-14 10:40:51 -08001619 return;
Mindy Pereiracd611952011-06-01 17:02:20 -07001620 }
1621 super.performFiltering(text, keyCode);
1622 }
1623
Mindy Pereira20c9d622011-10-12 13:18:04 -07001624 // Visible for testing.
1625 /*package*/ boolean isCompletedToken(CharSequence text) {
1626 if (TextUtils.isEmpty(text)) {
1627 return false;
1628 }
1629 // Check to see if this is a completed token before filtering.
1630 int end = text.length();
1631 int start = mTokenizer.findTokenStart(text, end);
1632 String token = text.toString().substring(start, end).trim();
1633 if (!TextUtils.isEmpty(token)) {
1634 char atEnd = token.charAt(token.length() - 1);
1635 return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
1636 }
1637 return false;
1638 }
1639
Jin Cao49744b02014-11-06 18:40:27 -08001640 /**
1641 * Clears the selected chip if there is one (and dismissing any popups related to the selected
1642 * chip in the process).
1643 */
1644 public void clearSelectedChip() {
Mindy Pereiracd611952011-06-01 17:02:20 -07001645 if (mSelectedChip != null) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001646 unselectChip(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001647 mSelectedChip = null;
1648 }
Mindy Pereirab86dcd52011-06-02 13:52:30 -07001649 setCursorVisible(true);
Jin Caoffc01112014-12-15 16:24:37 -08001650 setSelection(getText().length());
Mindy Pereiracd611952011-06-01 17:02:20 -07001651 }
1652
Mindy Pereiraa8166902011-06-09 17:53:23 -07001653 /**
1654 * Monitor touch events in the RecipientEditTextView.
1655 * If the view does not have focus, any tap on the view
1656 * will just focus the view. If the view has focus, determine
1657 * if the touch target is a recipient chip. If it is and the chip
1658 * is not selected, select it and clear any other selected chips.
1659 * If it isn't, then select that chip.
1660 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001661 @Override
Jin Caoffc01112014-12-15 16:24:37 -08001662 public boolean onTouchEvent(@NonNull MotionEvent event) {
Mindy Pereira05dbd332011-06-03 09:37:44 -07001663 if (!isFocused()) {
1664 // Ignore any chip taps until this view is focused.
1665 return super.onTouchEvent(event);
1666 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001667 boolean handled = super.onTouchEvent(event);
Mindy Pereira05dbd332011-06-03 09:37:44 -07001668 int action = event.getAction();
Mindy Pereiracd611952011-06-01 17:02:20 -07001669 boolean chipWasSelected = false;
Mindy Pereira2e905902011-09-08 16:17:04 -07001670 if (mSelectedChip == null) {
Mindy Pereira1d1ec852011-08-09 16:49:33 -07001671 mGestureDetector.onTouchEvent(event);
1672 }
Mindy Pereirabfedc1e2011-09-07 12:17:12 -07001673 if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001674 float x = event.getX();
1675 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07001676 int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08001677 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereiracd611952011-06-01 17:02:20 -07001678 if (currentChip != null) {
Jin Caoffc01112014-12-15 16:24:37 -08001679 if (mSelectedChip != null && mSelectedChip != currentChip) {
1680 clearSelectedChip();
1681 selectChip(currentChip);
1682 } else if (mSelectedChip == null) {
1683 commitDefault();
1684 selectChip(currentChip);
1685 } else {
1686 onClick(mSelectedChip);
Mindy Pereiracd611952011-06-01 17:02:20 -07001687 }
1688 chipWasSelected = true;
Mindy Pereirac1fed8b2011-07-01 13:46:27 -07001689 handled = true;
mindyp5e60c2b2012-11-06 17:47:40 -08001690 } else if (mSelectedChip != null && shouldShowEditableText(mSelectedChip)) {
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07001691 chipWasSelected = true;
Mindy Pereiracd611952011-06-01 17:02:20 -07001692 }
1693 }
1694 if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
1695 clearSelectedChip();
1696 }
1697 return handled;
1698 }
1699
Scott Kennedy272aae02013-04-05 17:17:24 -07001700 private void showAlternates(final DrawableRecipientChip currentChip,
Jin Cao9b166202014-08-08 13:26:14 -07001701 final ListPopupWindow alternatesPopup) {
Scott Kennedy272aae02013-04-05 17:17:24 -07001702 new AsyncTask<Void, Void, ListAdapter>() {
1703 @Override
1704 protected ListAdapter doInBackground(final Void... params) {
1705 return createAlternatesAdapter(currentChip);
1706 }
1707
Alice Yang6b7110f2013-04-26 12:50:35 -07001708 @Override
Scott Kennedy272aae02013-04-05 17:17:24 -07001709 protected void onPostExecute(final ListAdapter result) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07001710 if (!mAttachedToWindow) {
1711 return;
1712 }
Scott Kennedy272aae02013-04-05 17:17:24 -07001713 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07001714 int bottomOffset = calculateOffsetFromBottomToTop(line);
1715
Scott Kennedy272aae02013-04-05 17:17:24 -07001716 // Align the alternates popup with the left side of the View,
1717 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07001718 alternatesPopup.setAnchorView((mAlternatePopupAnchor != null) ?
1719 mAlternatePopupAnchor : RecipientEditTextView.this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07001720 alternatesPopup.setVerticalOffset(bottomOffset);
Scott Kennedy272aae02013-04-05 17:17:24 -07001721 alternatesPopup.setAdapter(result);
1722 alternatesPopup.setOnItemClickListener(mAlternatesListener);
1723 // Clear the checked item.
1724 mCheckedItem = -1;
1725 alternatesPopup.show();
1726 ListView listView = alternatesPopup.getListView();
1727 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
1728 // Checked item would be -1 if the adapter has not
1729 // loaded the view that should be checked yet. The
1730 // variable will be set correctly when onCheckedItemChanged
1731 // is called in a separate thread.
1732 if (mCheckedItem != -1) {
1733 listView.setItemChecked(mCheckedItem, true);
1734 mCheckedItem = -1;
1735 }
1736 }
1737 }.execute((Void[]) null);
Mindy Pereira95a69252011-06-17 15:02:03 -07001738 }
1739
Scott Kennedy194d4272013-03-06 22:06:45 -08001740 private ListAdapter createAlternatesAdapter(DrawableRecipientChip chip) {
Scott Kennedy7a4e6772013-11-21 14:31:33 -08001741 return new RecipientAlternatesAdapter(getContext(), chip.getContactId(),
1742 chip.getDirectoryId(), chip.getLookupKey(), chip.getDataId(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001743 getAdapter().getQueryType(), this, mDropdownChipLayouter,
1744 constructStateListDeleteDrawable());
Mindy Pereira95a69252011-06-17 15:02:03 -07001745 }
1746
Scott Kennedy194d4272013-03-06 22:06:45 -08001747 private ListAdapter createSingleAddressAdapter(DrawableRecipientChip currentChip) {
Kevin Linb10d1c62014-01-24 12:45:00 -08001748 return new SingleRecipientArrayAdapter(getContext(), currentChip.getEntry(),
Jin Cao4db8ccc2014-07-30 10:11:07 -07001749 mDropdownChipLayouter, constructStateListDeleteDrawable());
1750 }
1751
1752 private StateListDrawable constructStateListDeleteDrawable() {
1753 // Construct the StateListDrawable from deleteDrawable
1754 StateListDrawable deleteDrawable = new StateListDrawable();
Jin Caoa21fd882014-08-10 13:07:11 -07001755 if (!mDisableDelete) {
1756 deleteDrawable.addState(new int[]{android.R.attr.state_activated}, mChipDelete);
1757 }
Jin Cao4db8ccc2014-07-30 10:11:07 -07001758 deleteDrawable.addState(new int[0], null);
1759 return deleteDrawable;
Mindy Pereira01382d72011-07-15 16:52:32 -07001760 }
1761
Andy Stadleraa2afff2011-08-04 16:22:47 -07001762 @Override
Mindy Pereira95a69252011-06-17 15:02:03 -07001763 public void onCheckedItemChanged(int position) {
1764 ListView listView = mAlternatesPopup.getListView();
1765 if (listView != null && listView.getCheckedItemCount() == 0) {
1766 listView.setItemChecked(position, true);
Mindy Pereira95a69252011-06-17 15:02:03 -07001767 }
Mindy Pereira98b547f2011-09-08 09:27:39 -07001768 mCheckedItem = position;
Mindy Pereira95a69252011-06-17 15:02:03 -07001769 }
1770
Scott Kennedy1650ef62013-08-02 21:56:47 -07001771 private int putOffsetInRange(final float x, final float y) {
1772 final int offset;
1773
1774 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1775 offset = getOffsetForPosition(x, y);
1776 } else {
1777 offset = supportGetOffsetForPosition(x, y);
1778 }
1779
1780 return putOffsetInRange(offset);
1781 }
1782
Mindy Pereiracd611952011-06-01 17:02:20 -07001783 // TODO: This algorithm will need a lot of tweaking after more people have used
1784 // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
1785 // what comes before the finger.
1786 private int putOffsetInRange(int o) {
1787 int offset = o;
1788 Editable text = getText();
1789 int length = text.length();
1790 // Remove whitespace from end to find "real end"
1791 int realLength = length;
1792 for (int i = length - 1; i >= 0; i--) {
1793 if (text.charAt(i) == ' ') {
1794 realLength--;
1795 } else {
1796 break;
1797 }
1798 }
1799
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001800 // If the offset is beyond or at the end of the text,
1801 // leave it alone.
1802 if (offset >= realLength) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001803 return offset;
1804 }
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001805 Editable editable = getText();
Mindy Pereirab88ee452011-06-02 11:07:43 -07001806 while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001807 // Keep walking backward!
1808 offset--;
1809 }
1810 return offset;
1811 }
1812
Scott Kennedyf7e202d2013-03-06 21:38:10 -08001813 private static int findText(Editable text, int offset) {
Mindy Pereirafd68ea62011-06-02 10:40:19 -07001814 if (text.charAt(offset) != ' ') {
1815 return offset;
1816 }
1817 return -1;
1818 }
1819
Scott Kennedy194d4272013-03-06 22:06:45 -08001820 private DrawableRecipientChip findChip(int offset) {
Jin Caoffc01112014-12-15 16:24:37 -08001821 final Spannable span = getSpannable();
1822 final DrawableRecipientChip[] chips =
1823 span.getSpans(0, span.length(), DrawableRecipientChip.class);
Mindy Pereiracd611952011-06-01 17:02:20 -07001824 // Find the chip that contains this offset.
Jin Caoffc01112014-12-15 16:24:37 -08001825 for (DrawableRecipientChip chip : chips) {
Mindy Pereira95a69252011-06-17 15:02:03 -07001826 int start = getChipStart(chip);
1827 int end = getChipEnd(chip);
1828 if (offset >= start && offset <= end) {
Mindy Pereiracd611952011-06-01 17:02:20 -07001829 return chip;
1830 }
1831 }
1832 return null;
1833 }
1834
Mindy Pereira01162ce2011-09-20 12:21:55 -07001835 // Visible for testing.
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001836 // Use this method to generate text to add to the list of addresses.
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001837 /* package */String createAddressText(RecipientEntry entry) {
Mindy Pereira3ea99552011-09-19 10:50:31 -07001838 String display = entry.getDisplayName();
1839 String address = entry.getDestination();
1840 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1841 display = null;
1842 }
Tom Taylorabff6062012-04-17 09:04:56 -07001843 String trimmedDisplayText;
Tom Taylorc7a87f02012-05-03 15:21:08 -07001844 if (isPhoneQuery() && isPhoneNumber(address)) {
Tom Taylorabff6062012-04-17 09:04:56 -07001845 trimmedDisplayText = address.trim();
1846 } else {
1847 if (address != null) {
1848 // Tokenize out the address in case the address already
1849 // contained the username as well.
1850 Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
1851 if (tokenized != null && tokenized.length > 0) {
1852 address = tokenized[0].getAddress();
1853 }
Mindy Pereiraee48f732011-09-20 08:13:39 -07001854 }
Tom Taylorabff6062012-04-17 09:04:56 -07001855 Rfc822Token token = new Rfc822Token(display, address, null);
1856 trimmedDisplayText = token.toString().trim();
Mindy Pereirad8c15c32011-09-19 15:02:05 -07001857 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001858 int index = trimmedDisplayText.indexOf(",");
Mindy Pereira32aff5f2012-01-11 14:35:12 -08001859 return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
1860 && index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001861 .terminateToken(trimmedDisplayText) : trimmedDisplayText;
1862 }
1863
1864 // Visible for testing.
1865 // Use this method to generate text to display in a chip.
1866 /*package*/ String createChipDisplayText(RecipientEntry entry) {
1867 String display = entry.getDisplayName();
1868 String address = entry.getDestination();
1869 if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
1870 display = null;
1871 }
Mindy Pereiraaca23c42011-10-13 16:22:09 -07001872 if (!TextUtils.isEmpty(display)) {
1873 return display;
1874 } else if (!TextUtils.isEmpty(address)){
1875 return address;
1876 } else {
1877 return new Rfc822Token(display, address, null).toString();
1878 }
Mindy Pereira3ea99552011-09-19 10:50:31 -07001879 }
1880
Jin Caoffc01112014-12-15 16:24:37 -08001881 private CharSequence createChip(RecipientEntry entry) {
Jin Cao4db8ccc2014-07-30 10:11:07 -07001882 final String displayText = createAddressText(entry);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07001883 if (TextUtils.isEmpty(displayText)) {
1884 return null;
1885 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001886 // Always leave a blank space at the end of a chip.
Jin Cao4db8ccc2014-07-30 10:11:07 -07001887 final int textLength = displayText.length() - 1;
1888 final SpannableString chipText = new SpannableString(displayText);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001889 if (!mNoChips) {
1890 try {
Jin Caoffc01112014-12-15 16:24:37 -08001891 DrawableRecipientChip chip = constructChipSpan(entry);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07001892 chipText.setSpan(chip, 0, textLength,
1893 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1894 chip.setOriginalText(chipText.toString());
1895 } catch (NullPointerException e) {
1896 Log.e(TAG, e.getMessage(), e);
1897 return null;
1898 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001899 }
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001900 onChipCreated(entry);
Mindy Pereiracd611952011-06-01 17:02:20 -07001901 return chipText;
1902 }
1903
Mindy Pereiraa8166902011-06-09 17:53:23 -07001904 /**
Kevin Lin3e05cfa2014-06-05 12:27:17 -07001905 * A callback for subclasses to use to know when a chip was created with the
1906 * given RecipientEntry.
1907 */
1908 protected void onChipCreated(RecipientEntry entry) {}
1909
1910 /**
Mindy Pereiraa8166902011-06-09 17:53:23 -07001911 * When an item in the suggestions list has been clicked, create a chip from the
1912 * contact information of the selected item.
1913 */
Mindy Pereiracd611952011-06-01 17:02:20 -07001914 @Override
1915 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tom Taylor114c8932013-04-10 13:11:05 -07001916 if (position < 0) {
1917 return;
1918 }
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001919
1920 final int charactersTyped = submitItemAtPosition(position);
1921 if (charactersTyped > -1 && mRecipientEntryItemClickedListener != null) {
1922 mRecipientEntryItemClickedListener
1923 .onRecipientEntryItemClicked(charactersTyped, position);
1924 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001925 }
1926
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001927 private int submitItemAtPosition(int position) {
Scott Kennedy858e0942013-10-10 11:50:01 -07001928 RecipientEntry entry = createValidatedEntry(getAdapter().getItem(position));
Erikf7eaa5f2011-07-14 17:02:07 -07001929 if (entry == null) {
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001930 return -1;
Erikf7eaa5f2011-07-14 17:02:07 -07001931 }
Mindy Pereiracd611952011-06-01 17:02:20 -07001932 clearComposingText();
1933
1934 int end = getSelectionEnd();
1935 int start = mTokenizer.findTokenStart(getText(), end);
1936
1937 Editable editable = getText();
Mindy Pereiracd611952011-06-01 17:02:20 -07001938 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Jin Caoffc01112014-12-15 16:24:37 -08001939 CharSequence chip = createChip(entry);
Mindy Pereira005b2e22011-11-01 10:26:58 -07001940 if (chip != null && start >= 0 && end >= 0) {
Mindy Pereirae90bfad2011-07-26 14:51:41 -07001941 editable.replace(start, end, chip);
1942 }
Mindy Pereira5df0aa82011-09-19 16:29:03 -07001943 sanitizeBetween();
Andrew Sapperstein0f2b1742014-05-14 15:03:40 -07001944
1945 return end - start;
Mindy Pereiracd611952011-06-01 17:02:20 -07001946 }
1947
Mindy Pereira3bb52162011-07-01 14:52:22 -07001948 private RecipientEntry createValidatedEntry(RecipientEntry item) {
1949 if (item == null) {
1950 return null;
1951 }
1952 final RecipientEntry entry;
1953 // If the display name and the address are the same, or if this is a
1954 // valid contact, but the destination is invalid, then make this a fake
1955 // recipient that is editable.
1956 String destination = item.getDestination();
mindyp5e60c2b2012-11-06 17:47:40 -08001957 if (!isPhoneQuery() && item.getContactId() == RecipientEntry.GENERATED_CONTACT) {
1958 entry = RecipientEntry.constructGeneratedEntry(item.getDisplayName(),
mindypf30a4282012-12-03 12:16:33 -08001959 destination, item.isValid());
mindyp5e60c2b2012-11-06 17:47:40 -08001960 } else if (RecipientEntry.isCreatedRecipient(item.getContactId())
Mindy Pereirab4e244a2011-10-14 11:13:29 -07001961 && (TextUtils.isEmpty(item.getDisplayName())
1962 || TextUtils.equals(item.getDisplayName(), destination)
1963 || (mValidator != null && !mValidator.isValid(destination)))) {
mindypf30a4282012-12-03 12:16:33 -08001964 entry = RecipientEntry.constructFakeEntry(destination, item.isValid());
Mindy Pereira3bb52162011-07-01 14:52:22 -07001965 } else {
1966 entry = item;
1967 }
1968 return entry;
1969 }
1970
Mindy Pereira01162ce2011-09-20 12:21:55 -07001971 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08001972 /* package */DrawableRecipientChip[] getSortedRecipients() {
1973 DrawableRecipientChip[] recips = getSpannable()
1974 .getSpans(0, getText().length(), DrawableRecipientChip.class);
1975 ArrayList<DrawableRecipientChip> recipientsList = new ArrayList<DrawableRecipientChip>(
1976 Arrays.asList(recips));
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001977 final Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08001978 Collections.sort(recipientsList, new Comparator<DrawableRecipientChip>() {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001979
1980 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08001981 public int compare(DrawableRecipientChip first, DrawableRecipientChip second) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001982 int firstStart = spannable.getSpanStart(first);
1983 int secondStart = spannable.getSpanStart(second);
1984 if (firstStart < secondStart) {
1985 return -1;
1986 } else if (firstStart > secondStart) {
1987 return 1;
1988 } else {
1989 return 0;
1990 }
1991 }
1992 });
Scott Kennedy194d4272013-03-06 22:06:45 -08001993 return recipientsList.toArray(new DrawableRecipientChip[recipientsList.size()]);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07001994 }
1995
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07001996 @Override
1997 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
1998 return false;
1999 }
2000
2001 @Override
2002 public void onDestroyActionMode(ActionMode mode) {
2003 }
2004
2005 @Override
2006 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2007 return false;
2008 }
2009
Mindy Pereiraa8166902011-06-09 17:53:23 -07002010 /**
2011 * No chips are selectable.
2012 */
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002013 @Override
2014 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2015 return false;
2016 }
2017
Mindy Pereirad7192502011-09-22 08:04:45 -07002018 // Visible for testing.
Jin Cao6c2a0162014-08-17 15:00:50 -07002019 /* package */ReplacementDrawableSpan getMoreChip() {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002020 MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
2021 MoreImageSpan.class);
2022 return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
2023 }
2024
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002025 private MoreImageSpan createMoreSpan(int count) {
2026 String moreText = String.format(mMoreItem.getText().toString(), count);
Jin Cao6c2a0162014-08-17 15:00:50 -07002027 mWorkPaint.set(getPaint());
2028 mWorkPaint.setTextSize(mMoreItem.getTextSize());
2029 mWorkPaint.setColor(mMoreItem.getCurrentTextColor());
2030 final int width = (int) mWorkPaint.measureText(moreText) + mMoreItem.getPaddingLeft()
Mindy Pereira750e6e52011-07-25 11:51:30 -07002031 + mMoreItem.getPaddingRight();
Jin Cao6c2a0162014-08-17 15:00:50 -07002032 final int height = (int) mChipHeight;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002033 Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2034 Canvas canvas = new Canvas(drawable);
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002035 int adjustedHeight = height;
2036 Layout layout = getLayout();
2037 if (layout != null) {
2038 adjustedHeight -= layout.getLineDescent(0);
2039 }
Jin Cao6c2a0162014-08-17 15:00:50 -07002040 canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, mWorkPaint);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002041
2042 Drawable result = new BitmapDrawable(getResources(), drawable);
2043 result.setBounds(0, 0, width, height);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002044 return new MoreImageSpan(result);
2045 }
2046
2047 // Visible for testing.
2048 /*package*/ void createMoreChipPlainText() {
2049 // Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
2050 Editable text = getText();
2051 int start = 0;
2052 int end = start;
2053 for (int i = 0; i < CHIP_LIMIT; i++) {
2054 end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2055 start = end; // move to the next token and get its end.
2056 }
2057 // Now, count total addresses.
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002058 int tokenCount = countTokens(text);
2059 MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
2060 SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
2061 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2062 text.replace(end, text.length(), chipText);
2063 mMoreChip = moreSpan;
2064 }
2065
2066 // Visible for testing.
2067 /* package */int countTokens(Editable text) {
2068 int tokenCount = 0;
2069 int start = 0;
2070 while (start < text.length()) {
2071 start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
2072 tokenCount++;
2073 if (start >= text.length()) {
2074 break;
2075 }
2076 }
2077 return tokenCount;
2078 }
2079
2080 /**
2081 * Create the more chip. The more chip is text that replaces any chips that
2082 * do not fit in the pre-defined available space when the
2083 * RecipientEditTextView loses focus.
2084 */
2085 // Visible for testing.
2086 /* package */ void createMoreChip() {
2087 if (mNoChips) {
2088 createMoreChipPlainText();
2089 return;
2090 }
2091
2092 if (!mShouldShrink) {
2093 return;
2094 }
Jin Cao6c2a0162014-08-17 15:00:50 -07002095 ReplacementDrawableSpan[] tempMore = getSpannable().getSpans(0, getText().length(),
2096 MoreImageSpan.class);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002097 if (tempMore.length > 0) {
2098 getSpannable().removeSpan(tempMore[0]);
2099 }
Scott Kennedy194d4272013-03-06 22:06:45 -08002100 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002101
2102 if (recipients == null || recipients.length <= CHIP_LIMIT) {
Mindy Pereira3bb52162011-07-01 14:52:22 -07002103 mMoreChip = null;
2104 return;
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002105 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002106 Spannable spannable = getSpannable();
2107 int numRecipients = recipients.length;
2108 int overage = numRecipients - CHIP_LIMIT;
2109 MoreImageSpan moreSpan = createMoreSpan(overage);
Scott Kennedy194d4272013-03-06 22:06:45 -08002110 mRemovedSpans = new ArrayList<DrawableRecipientChip>();
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002111 int totalReplaceStart = 0;
2112 int totalReplaceEnd = 0;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002113 Editable text = getText();
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002114 for (int i = numRecipients - overage; i < recipients.length; i++) {
2115 mRemovedSpans.add(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002116 if (i == numRecipients - overage) {
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002117 totalReplaceStart = spannable.getSpanStart(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002118 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002119 if (i == recipients.length - 1) {
2120 totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
Mindy Pereira364e7cf2011-06-07 11:17:36 -07002121 }
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002122 if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
2123 int spanStart = spannable.getSpanStart(recipients[i]);
2124 int spanEnd = spannable.getSpanEnd(recipients[i]);
2125 recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
Mindy Pereira18529312011-06-28 11:00:52 -07002126 }
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002127 spannable.removeSpan(recipients[i]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002128 }
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002129 if (totalReplaceEnd < text.length()) {
2130 totalReplaceEnd = text.length();
2131 }
Mindy Pereira18529312011-06-28 11:00:52 -07002132 int end = Math.max(totalReplaceStart, totalReplaceEnd);
2133 int start = Math.min(totalReplaceStart, totalReplaceEnd);
2134 SpannableString chipText = new SpannableString(text.subSequence(start, end));
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002135 chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereira18529312011-06-28 11:00:52 -07002136 text.replace(start, end, chipText);
Mindy Pereira3bb52162011-07-01 14:52:22 -07002137 mMoreChip = moreSpan;
mindyp5e60c2b2012-11-06 17:47:40 -08002138 // If adding the +more chip goes over the limit, resize accordingly.
2139 if (!isPhoneQuery() && getLineCount() > mMaxLines) {
2140 setMaxLines(getLineCount());
2141 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002142 }
2143
Mindy Pereiraa8166902011-06-09 17:53:23 -07002144 /**
2145 * Replace the more chip, if it exists, with all of the recipient chips it had
2146 * replaced when the RecipientEditTextView gains focus.
2147 */
Mindy Pereirad7192502011-09-22 08:04:45 -07002148 // Visible for testing.
2149 /*package*/ void removeMoreChip() {
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002150 if (mMoreChip != null) {
2151 Spannable span = getSpannable();
2152 span.removeSpan(mMoreChip);
2153 mMoreChip = null;
2154 // Re-add the spans that were removed.
2155 if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
2156 // Recreate each removed span.
Scott Kennedy194d4272013-03-06 22:06:45 -08002157 DrawableRecipientChip[] recipients = getSortedRecipients();
Mindy Pereira54effe92011-09-09 09:46:38 -07002158 // Start the search for tokens after the last currently visible
2159 // chip.
Mindy Pereiraee48f732011-09-20 08:13:39 -07002160 if (recipients == null || recipients.length == 0) {
2161 return;
2162 }
Mindy Pereira54effe92011-09-09 09:46:38 -07002163 int end = span.getSpanEnd(recipients[recipients.length - 1]);
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002164 Editable editable = getText();
Scott Kennedy194d4272013-03-06 22:06:45 -08002165 for (DrawableRecipientChip chip : mRemovedSpans) {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002166 int chipStart;
Mindy Pereira3bb52162011-07-01 14:52:22 -07002167 int chipEnd;
2168 String token;
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002169 // Need to find the location of the chip, again.
2170 token = (String) chip.getOriginalText();
Mindy Pereira54effe92011-09-09 09:46:38 -07002171 // As we find the matching recipient for the remove spans,
2172 // reduce the size of the string we need to search.
2173 // That way, if there are duplicates, we always find the correct
2174 // recipient.
2175 chipStart = editable.toString().indexOf(token, end);
Mindy Pereira54effe92011-09-09 09:46:38 -07002176 end = chipEnd = Math.min(editable.length(), chipStart + token.length());
Mindy Pereira0d8b77a2011-07-08 10:26:30 -07002177 // Only set the span if we found a matching token.
2178 if (chipStart != -1) {
2179 editable.setSpan(chip, chipStart, chipEnd,
2180 Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
2181 }
Mindy Pereira12cf3fc2011-06-06 11:08:17 -07002182 }
2183 mRemovedSpans.clear();
2184 }
2185 }
2186 }
2187
Mindy Pereiracd611952011-06-01 17:02:20 -07002188 /**
Mindy Pereira95a69252011-06-17 15:02:03 -07002189 * Show specified chip as selected. If the RecipientChip is just an email address,
2190 * selecting the chip will take the contents of the chip and place it at
2191 * the end of the RecipientEditTextView for inline editing. If the
2192 * RecipientChip is a complete contact, then selecting the chip
Jin Caoffc01112014-12-15 16:24:37 -08002193 * will show a popup window with the address in use highlighted and any other
Mindy Pereira95a69252011-06-17 15:02:03 -07002194 * alternate addresses for the contact.
2195 * @param currentChip Chip to select.
Mindy Pereiracd611952011-06-01 17:02:20 -07002196 */
Jin Caoffc01112014-12-15 16:24:37 -08002197 private void selectChip(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002198 if (shouldShowEditableText(currentChip)) {
Mindy Pereira01382d72011-07-15 16:52:32 -07002199 CharSequence text = currentChip.getValue();
2200 Editable editable = getText();
mindypf30a4282012-12-03 12:16:33 -08002201 Spannable spannable = getSpannable();
2202 int spanStart = spannable.getSpanStart(currentChip);
2203 int spanEnd = spannable.getSpanEnd(currentChip);
2204 spannable.removeSpan(currentChip);
Jin Cao15a5ebc2014-09-18 16:43:32 -07002205 // Don't need leading space if it's the only chip
2206 if (spanEnd - spanStart == editable.length() - 1) {
2207 spanEnd++;
2208 }
mindypf30a4282012-12-03 12:16:33 -08002209 editable.delete(spanStart, spanEnd);
Mindy Pereira01382d72011-07-15 16:52:32 -07002210 setCursorVisible(true);
2211 setSelection(editable.length());
mindypf30a4282012-12-03 12:16:33 -08002212 editable.append(text);
Jin Caoffc01112014-12-15 16:24:37 -08002213 mSelectedChip = constructChipSpan(
2214 RecipientEntry.constructFakeEntry((String) text, isValid(text.toString())));
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002215 } else {
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002216 final boolean showAddress =
2217 currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT ||
2218 getAdapter().forceShowAddress();
Jin Caoffc01112014-12-15 16:24:37 -08002219 if (showAddress && mNoChips) {
2220 return;
Mindy Pereiracd611952011-06-01 17:02:20 -07002221 }
Jin Caoffc01112014-12-15 16:24:37 -08002222 mSelectedChip = currentChip;
2223 setSelection(getText().getSpanEnd(mSelectedChip));
Mindy Pereira4e18d8b2011-07-25 11:08:41 -07002224 setCursorVisible(false);
Jin Caoffc01112014-12-15 16:24:37 -08002225
2226 if (showAddress) {
2227 showAddress(currentChip, mAddressPopup);
2228 } else {
2229 showAlternates(currentChip, mAlternatesPopup);
2230 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002231 }
2232 }
2233
Scott Kennedy194d4272013-03-06 22:06:45 -08002234 private boolean shouldShowEditableText(DrawableRecipientChip currentChip) {
mindyp5e60c2b2012-11-06 17:47:40 -08002235 long contactId = currentChip.getContactId();
2236 return contactId == RecipientEntry.INVALID_CONTACT
2237 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2238 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002239
Jin Cao9b166202014-08-08 13:26:14 -07002240 private void showAddress(final DrawableRecipientChip currentChip, final ListPopupWindow popup) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07002241 if (!mAttachedToWindow) {
2242 return;
2243 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002244 int line = getLayout().getLineForOffset(getChipStart(currentChip));
Jin Cao6fc1fee2014-07-29 17:56:44 -07002245 int bottomOffset = calculateOffsetFromBottomToTop(line);
Mindy Pereira01382d72011-07-15 16:52:32 -07002246 // Align the alternates popup with the left side of the View,
2247 // regardless of the position of the chip tapped.
Jin Cao4de6a532014-08-08 11:34:10 -07002248 popup.setAnchorView((mAlternatePopupAnchor != null) ? mAlternatePopupAnchor : this);
Jin Cao6fc1fee2014-07-29 17:56:44 -07002249 popup.setVerticalOffset(bottomOffset);
Mindy Pereira01382d72011-07-15 16:52:32 -07002250 popup.setAdapter(createSingleAddressAdapter(currentChip));
2251 popup.setOnItemClickListener(new OnItemClickListener() {
2252 @Override
2253 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
2254 unselectChip(currentChip);
2255 popup.dismiss();
2256 }
2257 });
2258 popup.show();
2259 ListView listView = popup.getListView();
2260 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
2261 listView.setItemChecked(0, true);
2262 }
2263
Mindy Pereira95a69252011-06-17 15:02:03 -07002264 /**
2265 * Remove selection from this chip. Unselecting a RecipientChip will render
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002266 * the chip without a delete icon and with an unfocused background. This is
2267 * called when the RecipientChip no longer has focus.
Mindy Pereira95a69252011-06-17 15:02:03 -07002268 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002269 private void unselectChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002270 int start = getChipStart(chip);
2271 int end = getChipEnd(chip);
2272 Editable editable = getText();
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002273 mSelectedChip = null;
Mindy Pereira95a69252011-06-17 15:02:03 -07002274 if (start == -1 || end == -1) {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002275 Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002276 setSelection(editable.length());
2277 commitDefault();
Mindy Pereira95a69252011-06-17 15:02:03 -07002278 } else {
Mindy Pereirae82e61f2011-06-21 14:29:56 -07002279 getSpannable().removeSpan(chip);
Mindy Pereira95a69252011-06-17 15:02:03 -07002280 QwertyKeyListener.markAsReplaced(editable, start, end, "");
Mindy Pereira04da3252011-07-06 16:09:25 -07002281 editable.removeSpan(chip);
2282 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002283 if (!mNoChips) {
Jin Caoffc01112014-12-15 16:24:37 -08002284 editable.setSpan(constructChipSpan(chip.getEntry()),
mindyp5e60c2b2012-11-06 17:47:40 -08002285 start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002286 }
Mindy Pereira04da3252011-07-06 16:09:25 -07002287 } catch (NullPointerException e) {
2288 Log.e(TAG, e.getMessage(), e);
2289 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002290 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002291 setCursorVisible(true);
2292 setSelection(editable.length());
2293 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2294 mAlternatesPopup.dismiss();
2295 }
2296 }
2297
Jin Cao4db8ccc2014-07-30 10:11:07 -07002298 @Override
2299 public void onChipDelete() {
2300 if (mSelectedChip != null) {
2301 removeChip(mSelectedChip);
Jin Cao4db8ccc2014-07-30 10:11:07 -07002302 }
Jin Cao568fb222014-08-19 13:50:59 -07002303 dismissPopups();
2304 }
2305
2306 private void dismissPopups() {
2307 if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
2308 mAlternatesPopup.dismiss();
2309 }
2310 if (mAddressPopup != null && mAddressPopup.isShowing()) {
2311 mAddressPopup.dismiss();
2312 }
Jin Caoffc01112014-12-15 16:24:37 -08002313 setSelection(getText().length());
Jin Cao4db8ccc2014-07-30 10:11:07 -07002314 }
2315
Mindy Pereira95a69252011-06-17 15:02:03 -07002316 /**
2317 * Remove the chip and any text associated with it from the RecipientEditTextView.
2318 */
Mindy Pereira97cb2592011-09-26 16:11:41 -07002319 // Visible for testing.
Kevin Linb10d1c62014-01-24 12:45:00 -08002320 /* package */void removeChip(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002321 Spannable spannable = getSpannable();
2322 int spanStart = spannable.getSpanStart(chip);
2323 int spanEnd = spannable.getSpanEnd(chip);
2324 Editable text = getText();
Mindy Pereira62397a52011-10-03 13:46:43 -07002325 int toDelete = spanEnd;
Mindy Pereira95a69252011-06-17 15:02:03 -07002326 boolean wasSelected = chip == mSelectedChip;
2327 // Clear that there is a selected chip before updating any text.
2328 if (wasSelected) {
2329 mSelectedChip = null;
2330 }
Mindy Pereira62397a52011-10-03 13:46:43 -07002331 // Always remove trailing spaces when removing a chip.
2332 while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
2333 toDelete++;
2334 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002335 spannable.removeSpan(chip);
Mindy Pereiraf6d4bfc2012-04-24 15:13:34 -07002336 if (spanStart >= 0 && toDelete > 0) {
2337 text.delete(spanStart, toDelete);
2338 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002339 if (wasSelected) {
2340 clearSelectedChip();
2341 }
2342 }
2343
2344 /**
2345 * Replace this currently selected chip with a new chip
2346 * that uses the contact data provided.
2347 */
Mindy Pereiraaca23c42011-10-13 16:22:09 -07002348 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002349 /*package*/ void replaceChip(DrawableRecipientChip chip, RecipientEntry entry) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002350 boolean wasSelected = chip == mSelectedChip;
2351 if (wasSelected) {
2352 mSelectedChip = null;
2353 }
2354 int start = getChipStart(chip);
2355 int end = getChipEnd(chip);
2356 getSpannable().removeSpan(chip);
2357 Editable editable = getText();
Jin Caoffc01112014-12-15 16:24:37 -08002358 CharSequence chipText = createChip(entry);
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002359 if (chipText != null) {
2360 if (start == -1 || end == -1) {
2361 Log.e(TAG, "The chip to replace does not exist but should.");
2362 editable.insert(0, chipText);
2363 } else {
2364 if (!TextUtils.isEmpty(chipText)) {
2365 // There may be a space to replace with this chip's new
mindypb5afbc72012-10-03 11:57:42 -07002366 // associated space. Check for it
Mindy Pereira2d7709d2011-10-05 13:24:43 -07002367 int toReplace = end;
2368 while (toReplace >= 0 && toReplace < editable.length()
2369 && editable.charAt(toReplace) == ' ') {
2370 toReplace++;
2371 }
2372 editable.replace(start, toReplace, chipText);
Mindy Pereira62397a52011-10-03 13:46:43 -07002373 }
Mindy Pereira7ebb40f2011-07-06 17:21:14 -07002374 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002375 }
2376 setCursorVisible(true);
2377 if (wasSelected) {
2378 clearSelectedChip();
2379 }
2380 }
2381
2382 /**
2383 * Handle click events for a chip. When a selected chip receives a click
2384 * event, see if that event was in the delete icon. If so, delete it.
2385 * Otherwise, unselect the chip.
2386 */
Jin Caoa21fd882014-08-10 13:07:11 -07002387 public void onClick(DrawableRecipientChip chip) {
Mindy Pereira95a69252011-06-17 15:02:03 -07002388 if (chip.isSelected()) {
Jin Caoa21fd882014-08-10 13:07:11 -07002389 clearSelectedChip();
Mindy Pereiracd611952011-06-01 17:02:20 -07002390 }
Mindy Pereira9159cd22011-05-25 17:06:44 -07002391 }
Mindy Pereira95a69252011-06-17 15:02:03 -07002392
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002393 private boolean chipsPending() {
2394 return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
2395 }
2396
Mindy Pereira883c4992011-08-04 18:01:30 -07002397 @Override
2398 public void removeTextChangedListener(TextWatcher watcher) {
2399 mTextWatcher = null;
2400 super.removeTextChangedListener(watcher);
2401 }
2402
Jin Caob3b248a2014-04-11 10:43:50 -07002403 private boolean isValidEmailAddress(String input) {
2404 return !TextUtils.isEmpty(input) && mValidator != null &&
2405 mValidator.isValid(input);
2406 }
2407
Mindy Pereira79fb4362011-06-21 14:37:07 -07002408 private class RecipientTextWatcher implements TextWatcher {
Mindy Pereira72a23392012-02-06 10:19:51 -08002409
Mindy Pereira79fb4362011-06-21 14:37:07 -07002410 @Override
2411 public void afterTextChanged(Editable s) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002412 // If the text has been set to null or empty, make sure we remove
2413 // all the spans we applied.
2414 if (TextUtils.isEmpty(s)) {
2415 // Remove all the chips spans.
2416 Spannable spannable = getSpannable();
Scott Kennedy194d4272013-03-06 22:06:45 -08002417 DrawableRecipientChip[] chips = spannable.getSpans(0, getText().length(),
2418 DrawableRecipientChip.class);
2419 for (DrawableRecipientChip chip : chips) {
Mindy Pereira32366d42011-07-24 12:39:30 -07002420 spannable.removeSpan(chip);
2421 }
2422 if (mMoreChip != null) {
2423 spannable.removeSpan(mMoreChip);
2424 }
Kevin Lin41e93fb2014-02-03 17:35:29 -08002425 clearSelectedChip();
Mindy Pereira32366d42011-07-24 12:39:30 -07002426 return;
2427 }
Mindy Pereira01382d72011-07-15 16:52:32 -07002428 // Get whether there are any recipients pending addition to the
2429 // view. If there are, don't do anything in the text watcher.
Mindy Pereira21cc0a22011-06-23 17:11:06 -07002430 if (chipsPending()) {
Mindy Pereira79fb4362011-06-21 14:37:07 -07002431 return;
2432 }
Mindy Pereirac0a34ab2011-09-13 15:17:39 -07002433 // If the user is editing a chip, don't clear it.
mindypf30a4282012-12-03 12:16:33 -08002434 if (mSelectedChip != null) {
2435 if (!isGeneratedContact(mSelectedChip)) {
2436 setCursorVisible(true);
2437 setSelection(getText().length());
2438 clearSelectedChip();
2439 } else {
2440 return;
2441 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002442 }
2443 int length = s.length();
2444 // Make sure there is content there to parse and that it is
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002445 // not just the commit character.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002446 if (length > 1) {
mindypf30a4282012-12-03 12:16:33 -08002447 if (lastCharacterIsCommitCharacter(s)) {
2448 commitByCharacter();
2449 return;
2450 }
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002451 char last;
Mindy Pereira11a2adb2011-06-28 09:57:43 -07002452 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
Mindy Pereiraab5a9642011-06-23 17:23:22 -07002453 int len = length() - 1;
2454 if (end != len) {
2455 last = s.charAt(end);
2456 } else {
2457 last = s.charAt(len);
2458 }
mindypf30a4282012-12-03 12:16:33 -08002459 if (last == COMMIT_CHAR_SPACE) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002460 if (!isPhoneQuery()) {
2461 // Check if this is a valid email address. If it is,
2462 // commit it.
2463 String text = getText().toString();
2464 int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2465 String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
2466 tokenStart));
Jin Caob3b248a2014-04-11 10:43:50 -07002467 if (isValidEmailAddress(sub)) {
Tom Taylor4afc73e2012-05-04 10:21:17 -07002468 commitByCharacter();
2469 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002470 }
2471 }
2472 }
2473 }
2474
2475 @Override
2476 public void onTextChanged(CharSequence s, int start, int before, int count) {
mindypf30a4282012-12-03 12:16:33 -08002477 // The user deleted some text OR some text was replaced; check to
2478 // see if the insertion point is on a space
Mindy Pereira72a23392012-02-06 10:19:51 -08002479 // following a chip.
mindypf30a4282012-12-03 12:16:33 -08002480 if (before - count == 1) {
Mindy Pereira72a23392012-02-06 10:19:51 -08002481 // If the item deleted is a space, and the thing before the
2482 // space is a chip, delete the entire span.
2483 int selStart = getSelectionStart();
Scott Kennedy194d4272013-03-06 22:06:45 -08002484 DrawableRecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
2485 DrawableRecipientChip.class);
Mindy Pereira72a23392012-02-06 10:19:51 -08002486 if (repl.length > 0) {
2487 // There is a chip there! Just remove it.
Jin Caoffc01112014-12-15 16:24:37 -08002488 DrawableRecipientChip toDelete = repl[0];
Mindy Pereira72a23392012-02-06 10:19:51 -08002489 Editable editable = getText();
2490 // Add the separator token.
Jin Caoffc01112014-12-15 16:24:37 -08002491 int deleteStart = editable.getSpanStart(toDelete);
2492 int deleteEnd = editable.getSpanEnd(toDelete) + 1;
2493 if (deleteEnd > editable.length()) {
2494 deleteEnd = editable.length();
Mindy Pereira62fce932012-02-16 15:00:30 -08002495 }
Jin Caoffc01112014-12-15 16:24:37 -08002496 editable.removeSpan(toDelete);
2497 editable.delete(deleteStart, deleteEnd);
Mindy Pereira72a23392012-02-06 10:19:51 -08002498 }
Mindy Pereira4e7d20f2012-07-16 08:09:01 -07002499 } else if (count > before) {
mindyp7e10c862012-11-27 11:13:26 -08002500 if (mSelectedChip != null
2501 && isGeneratedContact(mSelectedChip)) {
2502 if (lastCharacterIsCommitCharacter(s)) {
2503 commitByCharacter();
2504 return;
2505 }
2506 }
Mindy Pereira72a23392012-02-06 10:19:51 -08002507 }
Mindy Pereira79fb4362011-06-21 14:37:07 -07002508 }
2509
2510 @Override
2511 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Mindy Pereiradc04cd72011-09-16 15:42:09 -07002512 // Do nothing.
Mindy Pereira79fb4362011-06-21 14:37:07 -07002513 }
2514 }
Mindy Pereira18529312011-06-28 11:00:52 -07002515
Alice Yangc1b52582013-03-04 19:54:00 -08002516 public boolean lastCharacterIsCommitCharacter(CharSequence s) {
mindypf30a4282012-12-03 12:16:33 -08002517 char last;
2518 int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
2519 int len = length() - 1;
2520 if (end != len) {
2521 last = s.charAt(end);
2522 } else {
2523 last = s.charAt(len);
2524 }
2525 return last == COMMIT_CHAR_COMMA || last == COMMIT_CHAR_SEMICOLON;
2526 }
2527
Scott Kennedy194d4272013-03-06 22:06:45 -08002528 public boolean isGeneratedContact(DrawableRecipientChip chip) {
mindypf30a4282012-12-03 12:16:33 -08002529 long contactId = chip.getContactId();
2530 return contactId == RecipientEntry.INVALID_CONTACT
2531 || (!isPhoneQuery() && contactId == RecipientEntry.GENERATED_CONTACT);
2532 }
2533
Minh Phame51c7222011-10-12 11:33:26 -07002534 /**
2535 * Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
2536 */
Régis Décamps219cbfb2014-06-04 14:29:54 +02002537 // Visible for testing.
2538 void handlePasteClip(ClipData clip) {
2539 if (clip == null) {
2540 // Do nothing.
2541 return;
2542 }
2543
2544 final ClipDescription clipDesc = clip.getDescription();
2545 boolean containsSupportedType = clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ||
2546 clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML);
2547 if (!containsSupportedType) {
2548 return;
2549 }
2550
Minh Phame51c7222011-10-12 11:33:26 -07002551 removeTextChangedListener(mTextWatcher);
2552
Régis Décamps219cbfb2014-06-04 14:29:54 +02002553 final ClipDescription clipDescription = clip.getDescription();
2554 for (int i = 0; i < clip.getItemCount(); i++) {
2555 final String mimeType = clipDescription.getMimeType(i);
2556 final boolean supportedType = ClipDescription.MIMETYPE_TEXT_PLAIN.equals(mimeType) ||
2557 ClipDescription.MIMETYPE_TEXT_HTML.equals(mimeType);
2558 if (!supportedType) {
2559 // Only plain text and html can be pasted.
2560 continue;
2561 }
2562
2563 final CharSequence pastedItem = clip.getItemAt(i).getText();
2564 if (!TextUtils.isEmpty(pastedItem)) {
2565 final Editable editable = getText();
2566 final int start = getSelectionStart();
2567 final int end = getSelectionEnd();
2568 if (start < 0 || end < 1) {
2569 // No selection.
2570 editable.append(pastedItem);
2571 } else if (start == end) {
2572 // Insert at position.
2573 editable.insert(start, pastedItem);
2574 } else {
2575 editable.append(pastedItem, start, end);
Minh Phame51c7222011-10-12 11:33:26 -07002576 }
Régis Décamps219cbfb2014-06-04 14:29:54 +02002577 handlePasteAndReplace();
Minh Phame51c7222011-10-12 11:33:26 -07002578 }
2579 }
2580
2581 mHandler.post(mAddTextWatcher);
2582 }
2583
Mindy Pereira20c9d622011-10-12 13:18:04 -07002584 @Override
2585 public boolean onTextContextMenuItem(int id) {
2586 if (id == android.R.id.paste) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002587 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
2588 Context.CLIPBOARD_SERVICE);
Minh Phame51c7222011-10-12 11:33:26 -07002589 handlePasteClip(clipboard.getPrimaryClip());
Mindy Pereira20c9d622011-10-12 13:18:04 -07002590 return true;
2591 }
2592 return super.onTextContextMenuItem(id);
2593 }
2594
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002595 private void handlePasteAndReplace() {
Scott Kennedy194d4272013-03-06 22:06:45 -08002596 ArrayList<DrawableRecipientChip> created = handlePaste();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002597 if (created != null && created.size() > 0) {
2598 // Perform reverse lookups on the pasted contacts.
2599 IndividualReplacementTask replace = new IndividualReplacementTask();
2600 replace.execute(created);
2601 }
2602 }
2603
Mindy Pereira20c9d622011-10-12 13:18:04 -07002604 // Visible for testing.
Scott Kennedy194d4272013-03-06 22:06:45 -08002605 /* package */ArrayList<DrawableRecipientChip> handlePaste() {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002606 String text = getText().toString();
2607 int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
2608 String lastAddress = text.substring(originalTokenStart);
2609 int tokenStart = originalTokenStart;
jli119X0cae8502012-10-18 12:55:47 +08002610 int prevTokenStart = 0;
Scott Kennedy194d4272013-03-06 22:06:45 -08002611 DrawableRecipientChip findChip = null;
2612 ArrayList<DrawableRecipientChip> created = new ArrayList<DrawableRecipientChip>();
Mindy Pereira20c9d622011-10-12 13:18:04 -07002613 if (tokenStart != 0) {
2614 // There are things before this!
jli119X0cae8502012-10-18 12:55:47 +08002615 while (tokenStart != 0 && findChip == null && tokenStart != prevTokenStart) {
Mindy Pereira20c9d622011-10-12 13:18:04 -07002616 prevTokenStart = tokenStart;
2617 tokenStart = mTokenizer.findTokenStart(text, tokenStart);
2618 findChip = findChip(tokenStart);
Tom Taylorfda01702013-01-14 16:52:25 -08002619 if (tokenStart == originalTokenStart && findChip == null) {
2620 break;
2621 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002622 }
2623 if (tokenStart != originalTokenStart) {
2624 if (findChip != null) {
2625 tokenStart = prevTokenStart;
2626 }
2627 int tokenEnd;
Scott Kennedy194d4272013-03-06 22:06:45 -08002628 DrawableRecipientChip createdChip;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002629 while (tokenStart < originalTokenStart) {
mindypb5afbc72012-10-03 11:57:42 -07002630 tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(getText().toString(),
2631 tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002632 commitChip(tokenStart, tokenEnd, getText());
2633 createdChip = findChip(tokenStart);
Mindy Pereirac52ea8e2012-06-04 15:24:55 -07002634 if (createdChip == null) {
2635 break;
2636 }
Mindy Pereira20c9d622011-10-12 13:18:04 -07002637 // +1 for the space at the end.
2638 tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002639 created.add(createdChip);
Mindy Pereira20c9d622011-10-12 13:18:04 -07002640 }
2641 }
2642 }
2643 // Take a look at the last token. If the token has been completed with a
2644 // commit character, create a chip.
2645 if (isCompletedToken(lastAddress)) {
2646 Editable editable = getText();
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002647 tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
2648 commitChip(tokenStart, editable.length(), editable);
2649 created.add(findChip(tokenStart));
Mindy Pereira20c9d622011-10-12 13:18:04 -07002650 }
Mindy Pereirab4e244a2011-10-14 11:13:29 -07002651 return created;
Mindy Pereira20c9d622011-10-12 13:18:04 -07002652 }
2653
2654 // Visible for testing.
2655 /* package */int movePastTerminators(int tokenEnd) {
2656 if (tokenEnd >= length()) {
2657 return tokenEnd;
2658 }
2659 char atEnd = getText().toString().charAt(tokenEnd);
2660 if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
2661 tokenEnd++;
2662 }
2663 // This token had not only an end token character, but also a space
2664 // separating it from the next token.
2665 if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
2666 tokenEnd++;
2667 }
2668 return tokenEnd;
2669 }
2670
Mindy Pereira18529312011-06-28 11:00:52 -07002671 private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
Scott Kennedy194d4272013-03-06 22:06:45 -08002672 private DrawableRecipientChip createFreeChip(RecipientEntry entry) {
Mindy Pereira18529312011-06-28 11:00:52 -07002673 try {
Mindy Pereiraf6519d22011-11-02 13:33:18 -07002674 if (mNoChips) {
2675 return null;
2676 }
Jin Caoffc01112014-12-15 16:24:37 -08002677 return constructChipSpan(entry);
Mindy Pereira18529312011-06-28 11:00:52 -07002678 } catch (NullPointerException e) {
2679 Log.e(TAG, e.getMessage(), e);
2680 return null;
2681 }
2682 }
2683
2684 @Override
Scott Kennedy78f38a02013-02-27 11:21:40 -08002685 protected void onPreExecute() {
2686 // Ensure everything is in chip-form already, so we don't have text that slowly gets
2687 // replaced
Scott Kennedy194d4272013-03-06 22:06:45 -08002688 final List<DrawableRecipientChip> originalRecipients =
2689 new ArrayList<DrawableRecipientChip>();
2690 final DrawableRecipientChip[] existingChips = getSortedRecipients();
Jin Caoffc01112014-12-15 16:24:37 -08002691 Collections.addAll(originalRecipients, existingChips);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002692 if (mRemovedSpans != null) {
2693 originalRecipients.addAll(mRemovedSpans);
2694 }
2695
Scott Kennedy194d4272013-03-06 22:06:45 -08002696 final List<DrawableRecipientChip> replacements =
2697 new ArrayList<DrawableRecipientChip>(originalRecipients.size());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002698
Scott Kennedy194d4272013-03-06 22:06:45 -08002699 for (final DrawableRecipientChip chip : originalRecipients) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002700 if (RecipientEntry.isCreatedRecipient(chip.getEntry().getContactId())
2701 && getSpannable().getSpanStart(chip) != -1) {
2702 replacements.add(createFreeChip(chip.getEntry()));
2703 } else {
2704 replacements.add(null);
2705 }
2706 }
2707
2708 processReplacements(originalRecipients, replacements);
2709 }
2710
2711 @Override
Mindy Pereira18529312011-06-28 11:00:52 -07002712 protected Void doInBackground(Void... params) {
2713 if (mIndividualReplacements != null) {
2714 mIndividualReplacements.cancel(true);
2715 }
2716 // For each chip in the list, look up the matching contact.
2717 // If there is a match, replace that chip with the matching
2718 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002719 final ArrayList<DrawableRecipientChip> recipients =
2720 new ArrayList<DrawableRecipientChip>();
2721 DrawableRecipientChip[] existingChips = getSortedRecipients();
Jin Caoffc01112014-12-15 16:24:37 -08002722 Collections.addAll(recipients, existingChips);
Mindy Pereira18529312011-06-28 11:00:52 -07002723 if (mRemovedSpans != null) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002724 recipients.addAll(mRemovedSpans);
Mindy Pereira18529312011-06-28 11:00:52 -07002725 }
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002726 ArrayList<String> addresses = new ArrayList<String>();
Jin Caoffc01112014-12-15 16:24:37 -08002727 for (DrawableRecipientChip chip : recipients) {
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002728 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002729 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002730 }
Mindy Pereira18529312011-06-28 11:00:52 -07002731 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002732 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002733 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002734 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002735 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002736 final ArrayList<DrawableRecipientChip> replacements =
2737 new ArrayList<DrawableRecipientChip>();
2738 for (final DrawableRecipientChip temp : recipients) {
mindyp16923ee2012-12-10 11:58:29 -08002739 RecipientEntry entry = null;
Alice Yangf0579ee2013-03-04 14:10:21 -08002740 if (temp != null && RecipientEntry.isCreatedRecipient(
2741 temp.getEntry().getContactId())
mindyp16923ee2012-12-10 11:58:29 -08002742 && getSpannable().getSpanStart(temp) != -1) {
2743 // Replace this.
2744 entry = createValidatedEntry(
2745 entries.get(tokenizeAddress(temp.getEntry()
2746 .getDestination())));
2747 }
2748 if (entry != null) {
2749 replacements.add(createFreeChip(entry));
2750 } else {
2751 replacements.add(null);
2752 }
Mindy Pereira18529312011-06-28 11:00:52 -07002753 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002754 processReplacements(recipients, replacements);
Mindy Pereira18529312011-06-28 11:00:52 -07002755 }
Scott Kennedy94fa3012013-02-15 18:22:05 -08002756
2757 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002758 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002759 final List<DrawableRecipientChip> replacements =
2760 new ArrayList<DrawableRecipientChip>(unfoundAddresses.size());
Scott Kennedy94fa3012013-02-15 18:22:05 -08002761
Scott Kennedy194d4272013-03-06 22:06:45 -08002762 for (final DrawableRecipientChip temp : recipients) {
Alice Yangad8781e2013-03-04 14:45:38 -08002763 if (temp != null && RecipientEntry.isCreatedRecipient(
2764 temp.getEntry().getContactId())
Scott Kennedy94fa3012013-02-15 18:22:05 -08002765 && getSpannable().getSpanStart(temp) != -1) {
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002766 if (unfoundAddresses.contains(
2767 temp.getEntry().getDestination())) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002768 replacements.add(createFreeChip(temp.getEntry()));
2769 } else {
2770 replacements.add(null);
2771 }
2772 } else {
2773 replacements.add(null);
2774 }
2775 }
2776
Scott Kennedy78f38a02013-02-27 11:21:40 -08002777 processReplacements(recipients, replacements);
Scott Kennedy94fa3012013-02-15 18:22:05 -08002778 }
mindyp16923ee2012-12-10 11:58:29 -08002779 });
Mindy Pereira18529312011-06-28 11:00:52 -07002780 return null;
2781 }
Scott Kennedy78f38a02013-02-27 11:21:40 -08002782
Scott Kennedy194d4272013-03-06 22:06:45 -08002783 private void processReplacements(final List<DrawableRecipientChip> recipients,
2784 final List<DrawableRecipientChip> replacements) {
Scott Kennedy78f38a02013-02-27 11:21:40 -08002785 if (replacements != null && replacements.size() > 0) {
2786 final Runnable runnable = new Runnable() {
2787 @Override
2788 public void run() {
Scott Kennedy0e128962013-04-11 10:52:08 -07002789 final Editable text = new SpannableStringBuilder(getText());
Scott Kennedy78f38a02013-02-27 11:21:40 -08002790 int i = 0;
Scott Kennedy0e128962013-04-11 10:52:08 -07002791 for (final DrawableRecipientChip chip : recipients) {
2792 final DrawableRecipientChip replacement = replacements.get(i);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002793 if (replacement != null) {
2794 final RecipientEntry oldEntry = chip.getEntry();
2795 final RecipientEntry newEntry = replacement.getEntry();
2796 final boolean isBetter =
2797 RecipientAlternatesAdapter.getBetterRecipient(
2798 oldEntry, newEntry) == newEntry;
2799
2800 if (isBetter) {
2801 // Find the location of the chip in the text currently shown.
Scott Kennedy0e128962013-04-11 10:52:08 -07002802 final int start = text.getSpanStart(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002803 if (start != -1) {
2804 // Replacing the entirety of what the chip represented,
2805 // including the extra space dividing it from other chips.
Paul Westbrookb023f692013-04-22 12:27:35 -07002806 final int end =
2807 Math.min(text.getSpanEnd(chip) + 1, text.length());
Scott Kennedy0e128962013-04-11 10:52:08 -07002808 text.removeSpan(chip);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002809 // Make sure we always have just 1 space at the end to
2810 // separate this chip from the next chip.
Scott Kennedy0e128962013-04-11 10:52:08 -07002811 final SpannableString displayText =
Scott Kennedy78f38a02013-02-27 11:21:40 -08002812 new SpannableString(createAddressText(
Scott Kennedy0e128962013-04-11 10:52:08 -07002813 replacement.getEntry()).trim() + " ");
Scott Kennedy78f38a02013-02-27 11:21:40 -08002814 displayText.setSpan(replacement, 0,
2815 displayText.length() - 1,
2816 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
2817 // Replace the old text we found with with the new display
2818 // text, which now may also contain the display name of the
2819 // recipient.
Scott Kennedy0e128962013-04-11 10:52:08 -07002820 text.replace(start, end, displayText);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002821 replacement.setOriginalText(displayText.toString());
2822 replacements.set(i, null);
2823
2824 recipients.set(i, replacement);
2825 }
2826 }
2827 }
2828 i++;
2829 }
Scott Kennedy0e128962013-04-11 10:52:08 -07002830 setText(text);
Scott Kennedy78f38a02013-02-27 11:21:40 -08002831 }
2832 };
2833
2834 if (Looper.myLooper() == Looper.getMainLooper()) {
2835 runnable.run();
2836 } else {
2837 mHandler.post(runnable);
2838 }
2839 }
2840 }
Mindy Pereira18529312011-06-28 11:00:52 -07002841 }
2842
Scott Kennedy78f38a02013-02-27 11:21:40 -08002843 private class IndividualReplacementTask
Scott Kennedy194d4272013-03-06 22:06:45 -08002844 extends AsyncTask<ArrayList<DrawableRecipientChip>, Void, Void> {
Mindy Pereira18529312011-06-28 11:00:52 -07002845 @Override
Scott Kennedy194d4272013-03-06 22:06:45 -08002846 protected Void doInBackground(ArrayList<DrawableRecipientChip>... params) {
Mindy Pereira18529312011-06-28 11:00:52 -07002847 // For each chip in the list, look up the matching contact.
2848 // If there is a match, replace that chip with the matching
2849 // chip.
Scott Kennedy194d4272013-03-06 22:06:45 -08002850 final ArrayList<DrawableRecipientChip> originalRecipients = params[0];
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002851 ArrayList<String> addresses = new ArrayList<String>();
Jin Caoffc01112014-12-15 16:24:37 -08002852 for (DrawableRecipientChip chip : originalRecipients) {
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002853 if (chip != null) {
Mindy Pereira03cfe3e2012-05-24 13:21:59 -07002854 addresses.add(createAddressText(chip.getEntry()));
Mindy Pereiraf07e8b22011-12-06 16:48:29 -08002855 }
Mindy Pereira18529312011-06-28 11:00:52 -07002856 }
Scott Kennedy7a4e6772013-11-21 14:31:33 -08002857 final BaseRecipientAdapter adapter = getAdapter();
Andrew Sapperstein8af0d3b2014-05-02 15:23:19 -07002858 adapter.getMatchingRecipients(addresses, new RecipientMatchCallback() {
mindyp16923ee2012-12-10 11:58:29 -08002859
2860 @Override
Scott Kennedy94fa3012013-02-15 18:22:05 -08002861 public void matchesFound(Map<String, RecipientEntry> entries) {
Scott Kennedy194d4272013-03-06 22:06:45 -08002862 for (final DrawableRecipientChip temp : originalRecipients) {
mindyp16923ee2012-12-10 11:58:29 -08002863 if (RecipientEntry.isCreatedRecipient(temp.getEntry()
2864 .getContactId())
2865 && getSpannable().getSpanStart(temp) != -1) {
2866 // Replace this.
Alon Albert76f1f2d2013-07-14 15:32:49 +03002867 final RecipientEntry entry = createValidatedEntry(entries
mindyp16923ee2012-12-10 11:58:29 -08002868 .get(tokenizeAddress(temp.getEntry().getDestination())
2869 .toLowerCase()));
Alon Albert76f1f2d2013-07-14 15:32:49 +03002870 if (entry != null) {
mindyp16923ee2012-12-10 11:58:29 -08002871 mHandler.post(new Runnable() {
2872 @Override
2873 public void run() {
Alon Albert76f1f2d2013-07-14 15:32:49 +03002874 replaceChip(temp, entry);
mindyp16923ee2012-12-10 11:58:29 -08002875 }
2876 });
2877 }
2878 }
Mindy Pereira18529312011-06-28 11:00:52 -07002879 }
mindyp16923ee2012-12-10 11:58:29 -08002880 }
2881
Scott Kennedy94fa3012013-02-15 18:22:05 -08002882 @Override
Scott Kennedyf7e202d2013-03-06 21:38:10 -08002883 public void matchesNotFound(final Set<String> unfoundAddresses) {
Scott Kennedy94fa3012013-02-15 18:22:05 -08002884 // No action required
2885 }
mindyp16923ee2012-12-10 11:58:29 -08002886 });
Mindy Pereira18529312011-06-28 11:00:52 -07002887 return null;
2888 }
2889 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002890
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002891
2892 /**
2893 * MoreImageSpan is a simple class created for tracking the existence of a
2894 * more chip across activity restarts/
2895 */
Jin Cao6c2a0162014-08-17 15:00:50 -07002896 private class MoreImageSpan extends ReplacementDrawableSpan {
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002897 public MoreImageSpan(Drawable b) {
2898 super(b);
Jin Cao6c2a0162014-08-17 15:00:50 -07002899 setExtraMargin(mLineSpacingExtra);
Mindy Pereirae1bfc922011-08-16 14:00:01 -07002900 }
2901 }
2902
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002903 @Override
2904 public boolean onDown(MotionEvent e) {
2905 return false;
2906 }
2907
2908 @Override
2909 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
2910 // Do nothing.
2911 return false;
2912 }
2913
2914 @Override
2915 public void onLongPress(MotionEvent event) {
2916 if (mSelectedChip != null) {
2917 return;
2918 }
2919 float x = event.getX();
2920 float y = event.getY();
Scott Kennedy1650ef62013-08-02 21:56:47 -07002921 final int offset = putOffsetInRange(x, y);
Scott Kennedy194d4272013-03-06 22:06:45 -08002922 DrawableRecipientChip currentChip = findChip(offset);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07002923 if (currentChip != null) {
Minh Phame51c7222011-10-12 11:33:26 -07002924 if (mDragEnabled) {
2925 // Start drag-and-drop for the selected chip.
2926 startDrag(currentChip);
2927 } else {
2928 // Copy the selected chip email address.
2929 showCopyDialog(currentChip.getEntry().getDestination());
2930 }
2931 }
2932 }
2933
Scott Kennedy1650ef62013-08-02 21:56:47 -07002934 // The following methods are used to provide some functionality on older versions of Android
2935 // These methods were copied out of JB MR2's TextView
2936 /////////////////////////////////////////////////
2937 private int supportGetOffsetForPosition(float x, float y) {
2938 if (getLayout() == null) return -1;
2939 final int line = supportGetLineAtCoordinate(y);
Jin Caoffc01112014-12-15 16:24:37 -08002940 return supportGetOffsetAtCoordinate(line, x);
Scott Kennedy1650ef62013-08-02 21:56:47 -07002941 }
2942
2943 private float supportConvertToLocalHorizontalCoordinate(float x) {
2944 x -= getTotalPaddingLeft();
2945 // Clamp the position to inside of the view.
2946 x = Math.max(0.0f, x);
2947 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x);
2948 x += getScrollX();
2949 return x;
2950 }
2951
2952 private int supportGetLineAtCoordinate(float y) {
2953 y -= getTotalPaddingLeft();
2954 // Clamp the position to inside of the view.
2955 y = Math.max(0.0f, y);
2956 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y);
2957 y += getScrollY();
2958 return getLayout().getLineForVertical((int) y);
2959 }
2960
2961 private int supportGetOffsetAtCoordinate(int line, float x) {
2962 x = supportConvertToLocalHorizontalCoordinate(x);
2963 return getLayout().getOffsetForHorizontal(line, x);
2964 }
2965 /////////////////////////////////////////////////
2966
Minh Phame51c7222011-10-12 11:33:26 -07002967 /**
2968 * Enables drag-and-drop for chips.
2969 */
2970 public void enableDrag() {
2971 mDragEnabled = true;
2972 }
2973
2974 /**
2975 * Starts drag-and-drop for the selected chip.
2976 */
Scott Kennedy194d4272013-03-06 22:06:45 -08002977 private void startDrag(DrawableRecipientChip currentChip) {
Minh Phame51c7222011-10-12 11:33:26 -07002978 String address = currentChip.getEntry().getDestination();
2979 ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
2980
2981 // Start drag mode.
2982 startDrag(data, new RecipientChipShadow(currentChip), null, 0);
2983
2984 // Remove the current chip, so drag-and-drop will result in a move.
2985 // TODO (phamm): consider readd this chip if it's dropped outside a target.
2986 removeChip(currentChip);
2987 }
2988
2989 /**
2990 * Handles drag event.
2991 */
2992 @Override
Jin Caoffc01112014-12-15 16:24:37 -08002993 public boolean onDragEvent(@NonNull DragEvent event) {
Minh Phame51c7222011-10-12 11:33:26 -07002994 switch (event.getAction()) {
2995 case DragEvent.ACTION_DRAG_STARTED:
2996 // Only handle plain text drag and drop.
2997 return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
2998 case DragEvent.ACTION_DRAG_ENTERED:
2999 requestFocus();
3000 return true;
3001 case DragEvent.ACTION_DROP:
3002 handlePasteClip(event.getClipData());
3003 return true;
3004 }
3005 return false;
3006 }
3007
3008 /**
Andrew Sapperstein1db635b2014-04-29 13:07:57 -07003009 * Drag shadow for a {@link DrawableRecipientChip}.
Minh Phame51c7222011-10-12 11:33:26 -07003010 */
3011 private final class RecipientChipShadow extends DragShadowBuilder {
Scott Kennedy194d4272013-03-06 22:06:45 -08003012 private final DrawableRecipientChip mChip;
Minh Phame51c7222011-10-12 11:33:26 -07003013
Scott Kennedy194d4272013-03-06 22:06:45 -08003014 public RecipientChipShadow(DrawableRecipientChip chip) {
Minh Phame51c7222011-10-12 11:33:26 -07003015 mChip = chip;
3016 }
3017
3018 @Override
Jin Caoffc01112014-12-15 16:24:37 -08003019 public void onProvideShadowMetrics(@NonNull Point shadowSize,
3020 @NonNull Point shadowTouchPoint) {
mindypf30a4282012-12-03 12:16:33 -08003021 Rect rect = mChip.getBounds();
Minh Phame51c7222011-10-12 11:33:26 -07003022 shadowSize.set(rect.width(), rect.height());
3023 shadowTouchPoint.set(rect.centerX(), rect.centerY());
3024 }
3025
3026 @Override
Jin Caoffc01112014-12-15 16:24:37 -08003027 public void onDrawShadow(@NonNull Canvas canvas) {
mindypf30a4282012-12-03 12:16:33 -08003028 mChip.draw(canvas);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003029 }
3030 }
3031
3032 private void showCopyDialog(final String address) {
Tony Mantlerfbeca0e2013-10-15 14:53:00 -07003033 if (!mAttachedToWindow) {
3034 return;
3035 }
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003036 mCopyAddress = address;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003037 mCopyDialog.setTitle(address);
Mindy Pereira76e62e32012-02-03 15:38:50 -08003038 mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003039 mCopyDialog.setCancelable(true);
3040 mCopyDialog.setCanceledOnTouchOutside(true);
Tom Taylor80f4abf2012-04-06 13:37:20 -07003041 Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
3042 button.setOnClickListener(this);
3043 int btnTitleId;
Tom Taylorc7a87f02012-05-03 15:21:08 -07003044 if (isPhoneQuery()) {
Tom Taylor80f4abf2012-04-06 13:37:20 -07003045 btnTitleId = R.string.copy_number;
3046 } else {
3047 btnTitleId = R.string.copy_email;
3048 }
3049 String buttonTitle = getContext().getResources().getString(btnTitleId);
3050 button.setText(buttonTitle);
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003051 mCopyDialog.setOnDismissListener(this);
3052 mCopyDialog.show();
3053 }
3054
3055 @Override
3056 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
3057 // Do nothing.
3058 return false;
3059 }
3060
3061 @Override
3062 public void onShowPress(MotionEvent e) {
3063 // Do nothing.
3064 }
3065
3066 @Override
3067 public boolean onSingleTapUp(MotionEvent e) {
3068 // Do nothing.
3069 return false;
3070 }
3071
3072 @Override
3073 public void onDismiss(DialogInterface dialog) {
3074 mCopyAddress = null;
Mindy Pereira1d1ec852011-08-09 16:49:33 -07003075 }
3076
3077 @Override
3078 public void onClick(View v) {
3079 // Copy this to the clipboard.
3080 ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
3081 Context.CLIPBOARD_SERVICE);
3082 clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
3083 mCopyDialog.dismiss();
3084 }
Tom Taylorc7a87f02012-05-03 15:21:08 -07003085
3086 protected boolean isPhoneQuery() {
Mindy Pereiraca522712012-06-28 11:47:48 -07003087 return getAdapter() != null
Scott Kennedy858e0942013-10-10 11:50:01 -07003088 && getAdapter().getQueryType() == BaseRecipientAdapter.QUERY_TYPE_PHONE;
3089 }
3090
3091 @Override
3092 public BaseRecipientAdapter getAdapter() {
3093 return (BaseRecipientAdapter) super.getAdapter();
Tom Taylorc7a87f02012-05-03 15:21:08 -07003094 }
Kaikai Wang972def72014-05-27 21:59:52 -07003095
3096 /**
3097 * Append a new {@link RecipientEntry} to the end of the recipient chips, leaving any
3098 * unfinished text at the end.
3099 */
3100 public void appendRecipientEntry(final RecipientEntry entry) {
3101 clearComposingText();
3102
3103 final Editable editable = getText();
3104 int chipInsertionPoint = 0;
3105
3106 // Find the end of last chip and see if there's any unchipified text.
3107 final DrawableRecipientChip[] recips = getSortedRecipients();
3108 if (recips != null && recips.length > 0) {
3109 final DrawableRecipientChip last = recips[recips.length - 1];
3110 // The chip will be inserted at the end of last chip + 1. All the unfinished text after
3111 // the insertion point will be kept untouched.
3112 chipInsertionPoint = editable.getSpanEnd(last) + 1;
3113 }
3114
Jin Caoffc01112014-12-15 16:24:37 -08003115 final CharSequence chip = createChip(entry);
Kaikai Wang972def72014-05-27 21:59:52 -07003116 if (chip != null) {
3117 editable.insert(chipInsertionPoint, chip);
3118 }
3119 }
Jin Cao35e82d42014-06-02 17:21:21 -07003120
Kaikai Wangcd980d92014-06-09 21:08:13 -07003121 /**
3122 * Remove all chips matching the given RecipientEntry.
3123 */
3124 public void removeRecipientEntry(final RecipientEntry entry) {
3125 final DrawableRecipientChip[] recips = getText()
3126 .getSpans(0, getText().length(), DrawableRecipientChip.class);
3127
3128 for (final DrawableRecipientChip recipient : recips) {
3129 final RecipientEntry existingEntry = recipient.getEntry();
3130 if (existingEntry != null && existingEntry.isValid() &&
3131 existingEntry.isSamePerson(entry)) {
3132 removeChip(recipient);
3133 }
3134 }
3135 }
3136
Jin Cao4de6a532014-08-08 11:34:10 -07003137 public void setAlternatePopupAnchor(View v) {
3138 mAlternatePopupAnchor = v;
3139 }
3140
Scott Kennedy654c9672014-12-12 14:24:17 -08003141 @Override
3142 public void setVisibility(int visibility) {
3143 super.setVisibility(visibility);
3144
3145 if (visibility != GONE && mRequiresShrinkWhenNotGone) {
3146 mRequiresShrinkWhenNotGone = false;
3147 mHandler.post(mDelayedShrink);
3148 }
3149 }
3150
Jin Cao35e82d42014-06-02 17:21:21 -07003151 private static class ChipBitmapContainer {
3152 Bitmap bitmap;
3153 // information used for positioning the loaded icon
3154 boolean loadIcon = true;
3155 float left;
3156 float top;
3157 float right;
3158 float bottom;
3159 }
Mindy Pereira18529312011-06-28 11:00:52 -07003160}