/
RecipientEditTextView.java
3015 lines (2728 loc) · 116 KB
/
RecipientEditTextView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ex.chips;
import android.app.Dialog;
import android.content.*;
import android.content.ClipboardManager;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.*;
import android.text.*;
import android.text.method.QwertyKeyListener;
import android.text.style.ImageSpan;
import android.text.util.Rfc822Token;
import android.text.util.Rfc822Tokenizer;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.*;
import android.view.ActionMode.Callback;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.android.ex.chips.RecipientAlternatesAdapter.RecipientMatchCallback;
import com.android.ex.chips.recipientchip.DrawableRecipientChip;
import com.android.ex.chips.recipientchip.InvisibleRecipientChip;
import com.android.ex.chips.recipientchip.VisibleRecipientChip;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* RecipientEditTextView is an auto complete text view for use with applications
* that use the new Chips UI for addressing a message to recipients.
*/
public class RecipientEditTextView extends MultiAutoCompleteTextView implements
OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener,
GestureDetector.OnGestureListener, OnDismissListener, OnClickListener,
TextView.OnEditorActionListener {
private static final char COMMIT_CHAR_COMMA = ',';
private static final char COMMIT_CHAR_SEMICOLON = ';';
private static final char COMMIT_CHAR_SPACE = ' ';
private static final String SEPARATOR = String.valueOf(COMMIT_CHAR_COMMA)
+ String.valueOf(COMMIT_CHAR_SPACE);
private static final String TAG = "RecipientEditTextView";
private static int DISMISS = "dismiss".hashCode();
private static final long DISMISS_DELAY = 300;
// TODO: get correct number/ algorithm from with UX.
// Visible for testing.
/*package*/ static final int CHIP_LIMIT = 2;
private static final int MAX_CHIPS_PARSED = 50;
private static int sSelectedTextColor = -1;
// Resources for displaying chips.
private Drawable mChipBackground = null;
private Drawable mChipDelete = null;
private Drawable mInvalidChipBackground;
private Drawable mChipBackgroundPressed;
private float mChipHeight;
private float mChipFontSize;
private float mLineSpacingExtra;
private int mChipPadding;
/**
* Enumerator for avatar position. See attr.xml for more details.
* 0 for end, 1 for start.
*/
private int mAvatarPosition;
private static final int AVATAR_POSITION_END = 0;
private static final int AVATAR_POSITION_START = 1;
/**
* Enumerator for image span alignment. See attr.xml for more details.
* 0 for bottom, 1 for baseline.
*/
private int mImageSpanAlignment;
private static final int IMAGE_SPAN_ALIGNMENT_BOTTOM = 0;
private static final int IMAGE_SPAN_ALIGNMENT_BASELINE = 1;
private boolean mDisableDelete;
private Tokenizer mTokenizer;
private Validator mValidator;
private DrawableRecipientChip mSelectedChip;
private Bitmap mDefaultContactPhoto;
private ImageSpan mMoreChip;
private TextView mMoreItem;
// VisibleForTesting
final ArrayList<String> mPendingChips = new ArrayList<String>();
private Handler mHandler;
private int mPendingChipsCount = 0;
private boolean mNoChips = false;
private ListPopupWindow mAlternatesPopup;
private ListPopupWindow mAddressPopup;
// VisibleForTesting
ArrayList<DrawableRecipientChip> mTemporaryRecipients;
private ArrayList<DrawableRecipientChip> mRemovedSpans;
private boolean mShouldShrink = true;
// Chip copy fields.
private GestureDetector mGestureDetector;
private Dialog mCopyDialog;
private String mCopyAddress;
/**
* Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a
* selected chip.
*/
private OnItemClickListener mAlternatesListener;
private int mCheckedItem;
private TextWatcher mTextWatcher;
// Obtain the enclosing scroll view, if it exists, so that the view can be
// scrolled to show the last line of chips content.
private ScrollView mScrollView;
private boolean mTriedGettingScrollView;
private boolean mDragEnabled = false;
// This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
// parens, so numbers such as "1 (425) 222-2342" match.
private static final Pattern PHONE_PATTERN
= Pattern.compile( // sdd = space, dot, or dash
"(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
+ "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?" // 1(<digits>)<sdd>*
+ "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
private final Runnable mAddTextWatcher = new Runnable() {
@Override
public void run() {
if (mTextWatcher == null) {
mTextWatcher = new RecipientTextWatcher();
addTextChangedListener(mTextWatcher);
}
}
};
private IndividualReplacementTask mIndividualReplacements;
private Runnable mHandlePendingChips = new Runnable() {
@Override
public void run() {
handlePendingChips();
}
};
private Runnable mDelayedShrink = new Runnable() {
@Override
public void run() {
shrink();
}
};
private int mMaxLines;
private static int sExcessTopPadding = -1;
private int mActionBarHeight;
private boolean mAttachedToWindow;
private DropdownChipLayouter mDropdownChipLayouter;
private boolean mDismissPopupOnClick = true;
private ItemSelectedListener itemSelectedListener;
public RecipientEditTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setChipDimensions(context, attrs);
if (sSelectedTextColor == -1) {
sSelectedTextColor = context.getResources().getColor(android.R.color.white);
}
mAlternatesPopup = new ListPopupWindow(context);
mAddressPopup = new ListPopupWindow(context);
mCopyDialog = new Dialog(context);
mAlternatesListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView,View view, int position,
long rowId) {
mAlternatesPopup.setOnItemClickListener(null);
replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter())
.getRecipientEntry(position));
Message delayed = Message.obtain(mHandler, DISMISS);
delayed.obj = mAlternatesPopup;
mHandler.sendMessageDelayed(delayed, DISMISS_DELAY);
clearComposingText();
}
};
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
setOnItemClickListener(this);
setCustomSelectionActionModeCallback(this);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == DISMISS) {
((ListPopupWindow) msg.obj).dismiss();
return;
}
super.handleMessage(msg);
}
};
mTextWatcher = new RecipientTextWatcher();
addTextChangedListener(mTextWatcher);
mGestureDetector = new GestureDetector(context, this);
setOnEditorActionListener(this);
setDropdownChipLayouter(new DropdownChipLayouter(LayoutInflater.from(context), context));
}
protected void setDropdownChipLayouter(DropdownChipLayouter dropdownChipLayouter) {
mDropdownChipLayouter = dropdownChipLayouter;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mAttachedToWindow = false;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mAttachedToWindow = true;
}
@Override
public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
if (action == EditorInfo.IME_ACTION_DONE) {
if (commitDefault()) {
return true;
}
if (mSelectedChip != null) {
clearSelectedChip();
return true;
} else if (focusNext()) {
return true;
}
}
return false;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
InputConnection connection = super.onCreateInputConnection(outAttrs);
int imeActions = outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION;
if ((imeActions&EditorInfo.IME_ACTION_DONE) != 0) {
// clear the existing action
outAttrs.imeOptions ^= imeActions;
// set the DONE action
outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE;
}
if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NO_ENTER_ACTION) != 0) {
outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
}
outAttrs.actionId = EditorInfo.IME_ACTION_DONE;
outAttrs.actionLabel = getContext().getString(R.string.done);
return connection;
}
/*package*/ DrawableRecipientChip getLastChip() {
DrawableRecipientChip last = null;
DrawableRecipientChip[] chips = getSortedRecipients();
if (chips != null && chips.length > 0) {
last = chips[chips.length - 1];
}
return last;
}
@Override
public void onSelectionChanged(int start, int end) {
// When selection changes, see if it is inside the chips area.
// If so, move the cursor back after the chips again.
DrawableRecipientChip last = getLastChip();
if (last != null && start < getSpannable().getSpanEnd(last)) {
// Grab the last chip and set the cursor to after it.
setSelection(Math.min(getSpannable().getSpanEnd(last) + 1, getText().length()));
}
super.onSelectionChanged(start, end);
}
@Override
public void onRestoreInstanceState(Parcelable state) {
if (!TextUtils.isEmpty(getText())) {
super.onRestoreInstanceState(null);
} else {
super.onRestoreInstanceState(state);
}
}
@Override
public Parcelable onSaveInstanceState() {
// If the user changes orientation while they are editing, just roll back the selection.
clearSelectedChip();
return super.onSaveInstanceState();
}
/**
* Convenience method: Append the specified text slice to the TextView's
* display buffer, upgrading it to BufferType.EDITABLE if it was
* not already editable. Commas are excluded as they are added automatically
* by the view.
*/
@Override
public void append(CharSequence text, int start, int end) {
// We don't care about watching text changes while appending.
if (mTextWatcher != null) {
removeTextChangedListener(mTextWatcher);
}
super.append(text, start, end);
if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) {
String displayString = text.toString();
if (!displayString.trim().endsWith(String.valueOf(COMMIT_CHAR_COMMA))) {
// We have no separator, so we should add it
super.append(SEPARATOR, 0, SEPARATOR.length());
displayString += SEPARATOR;
}
if (!TextUtils.isEmpty(displayString)
&& TextUtils.getTrimmedLength(displayString) > 0) {
mPendingChipsCount++;
mPendingChips.add(displayString);
}
}
// Put a message on the queue to make sure we ALWAYS handle pending
// chips.
if (mPendingChipsCount > 0) {
postHandlePendingChips();
}
mHandler.post(mAddTextWatcher);
}
@Override
public void onFocusChanged(boolean hasFocus, int direction, Rect previous) {
super.onFocusChanged(hasFocus, direction, previous);
if (!hasFocus) {
shrink();
} else {
expand();
}
}
private int getExcessTopPadding() {
if (sExcessTopPadding == -1) {
sExcessTopPadding = (int) (mChipHeight + mLineSpacingExtra);
}
return sExcessTopPadding;
}
@Override
public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
super.setAdapter(adapter);
BaseRecipientAdapter baseAdapter = (BaseRecipientAdapter) adapter;
baseAdapter.registerUpdateObserver(new BaseRecipientAdapter.EntriesUpdatedObserver() {
@Override
public void onChanged(List<RecipientEntry> entries) {
// Scroll the chips field to the top of the screen so
// that the user can see as many results as possible.
if (entries != null && entries.size() > 0) {
scrollBottomIntoView();
}
}
});
baseAdapter.setDropdownChipLayouter(mDropdownChipLayouter);
}
protected void scrollBottomIntoView() {
if (mScrollView != null && mShouldShrink) {
int[] location = new int[2];
getLocationOnScreen(location);
int height = getHeight();
int currentPos = location[1] + height;
// Desired position shows at least 1 line of chips below the action
// bar. We add excess padding to make sure this is always below other
// content.
int desiredPos = (int) mChipHeight + mActionBarHeight + getExcessTopPadding();
if (currentPos > desiredPos) {
mScrollView.scrollBy(0, currentPos - desiredPos);
}
}
}
protected ScrollView getScrollView() {
return mScrollView;
}
@Override
public void performValidation() {
// Do nothing. Chips handles its own validation.
}
private void shrink() {
if (mTokenizer == null) {
return;
}
long contactId = mSelectedChip != null ? mSelectedChip.getEntry().getContactId() : -1;
if (mSelectedChip != null && contactId != RecipientEntry.INVALID_CONTACT
&& (!isPhoneQuery() && contactId != RecipientEntry.GENERATED_CONTACT)) {
clearSelectedChip();
} else {
if (getWidth() <= 0) {
// We don't have the width yet which means the view hasn't been drawn yet
// and there is no reason to attempt to commit chips yet.
// This focus lost must be the result of an orientation change
// or an initial rendering.
// Re-post the shrink for later.
mHandler.removeCallbacks(mDelayedShrink);
mHandler.post(mDelayedShrink);
return;
}
// Reset any pending chips as they would have been handled
// when the field lost focus.
if (mPendingChipsCount > 0) {
postHandlePendingChips();
} else {
Editable editable = getText();
int end = getSelectionEnd();
int start = mTokenizer.findTokenStart(editable, end);
DrawableRecipientChip[] chips =
getSpannable().getSpans(start, end, DrawableRecipientChip.class);
if ((chips == null || chips.length == 0)) {
Editable text = getText();
int whatEnd = mTokenizer.findTokenEnd(text, start);
// This token was already tokenized, so skip past the ending token.
if (whatEnd < text.length() && text.charAt(whatEnd) == ',') {
whatEnd = movePastTerminators(whatEnd);
}
// In the middle of chip; treat this as an edit
// and commit the whole token.
int selEnd = getSelectionEnd();
if (whatEnd != selEnd) {
handleEdit(start, whatEnd);
} else {
commitChip(start, end, editable);
}
}
}
mHandler.post(mAddTextWatcher);
}
createMoreChip();
}
private void expand() {
if (mShouldShrink) {
setMaxLines(Integer.MAX_VALUE);
}
removeMoreChip();
setCursorVisible(true);
Editable text = getText();
setSelection(text != null && text.length() > 0 ? text.length() : 0);
// If there are any temporary chips, try replacing them now that the user
// has expanded the field.
if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) {
new RecipientReplacementTask().execute();
mTemporaryRecipients = null;
}
}
private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) {
paint.setTextSize(mChipFontSize);
if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Max width is negative: " + maxWidth);
}
return TextUtils.ellipsize(text, paint, maxWidth,
TextUtils.TruncateAt.END);
}
/**
* Creates a bitmap of the given contact on a selected chip.
*
* @param contact The recipient entry to pull data from.
* @param paint The paint to use to draw the bitmap.
*/
private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint) {
paint.setColor(sSelectedTextColor);
Bitmap photo;
if (mDisableDelete) {
// Show the avatar instead if we don't want to delete
photo = getAvatarIcon(contact);
} else {
photo = ((BitmapDrawable) mChipDelete).getBitmap();
}
return createChipBitmap(contact, paint, photo, mChipBackgroundPressed);
}
/**
* Creates a bitmap of the given contact on a selected chip.
*
* @param contact The recipient entry to pull data from.
* @param paint The paint to use to draw the bitmap.
*/
// TODO: Is leaveBlankIconSpacer obsolete now that we have left and right attributes?
private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint,
boolean leaveBlankIconSpacer) {
Drawable background = getChipBackground(contact);
Bitmap photo = getAvatarIcon(contact);
paint.setColor(getContext().getResources().getColor(android.R.color.black));
return createChipBitmap(contact, paint, photo, background);
}
private Bitmap createChipBitmap(RecipientEntry contact, TextPaint paint, Bitmap icon,
Drawable background) {
if (background == null) {
Log.w(TAG, "Unable to draw a background for the chips as it was never set");
return Bitmap.createBitmap(
(int) mChipHeight * 2, (int) mChipHeight, Bitmap.Config.ARGB_8888);
}
Rect backgroundPadding = new Rect();
background.getPadding(backgroundPadding);
// Ellipsize the text so that it takes AT MOST the entire width of the
// autocomplete text entry area. Make sure to leave space for padding
// on the sides.
int height = (int) mChipHeight + getResources().getDimensionPixelSize(R.dimen.extra_chip_height);
// Since the icon is a square, it's width is equal to the maximum height it can be inside
// the chip.
int iconWidth = height - backgroundPadding.top - backgroundPadding.bottom;
float[] widths = new float[1];
paint.getTextWidths(" ", widths);
CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
calculateAvailableWidth() - iconWidth - widths[0] - backgroundPadding.left
- backgroundPadding.right);
int textWidth = (int) paint.measureText(ellipsizedText, 0, ellipsizedText.length());
// Make sure there is a minimum chip width so the user can ALWAYS
// tap a chip without difficulty.
int width = Math.max(iconWidth * 2, textWidth + (mChipPadding * 2) + iconWidth
+ backgroundPadding.left + backgroundPadding.right);
// Create the background of the chip.
Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(tmpBitmap);
// Draw the background drawable
background.setBounds(height/2, 0, width, height);
background.draw(canvas);
// Draw the text vertically aligned
int textX = shouldPositionAvatarOnRight() ?
mChipPadding + backgroundPadding.left :
width - backgroundPadding.right - mChipPadding - textWidth;
paint.setColor(0xFF5C5C5C);
paint.setAntiAlias(true);
canvas.drawText(ellipsizedText, 0, ellipsizedText.length(),
textX, getTextYOffset(ellipsizedText.toString(), paint, height), paint);
if (icon != null) {
// Draw the icon
icon = ChipsUtil.getClip(icon);
int iconX = shouldPositionAvatarOnRight() ?
width - backgroundPadding.right - iconWidth :
backgroundPadding.left;
RectF src = new RectF(0, 0, icon.getWidth(), icon.getHeight());
RectF dst = new RectF(0, 0, height, height);
drawIconOnCanvas(icon, canvas, paint, src, dst);
}
return tmpBitmap;
}
/**
* Returns true if the avatar should be positioned at the right edge of the chip.
* Takes into account both the set avatar position (start or end) as well as whether
* the layout direction is LTR or RTL.
*/
private boolean shouldPositionAvatarOnRight() {
final boolean isRtl = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ?
getLayoutDirection() == LAYOUT_DIRECTION_RTL : false;
final boolean assignedPosition = mAvatarPosition == AVATAR_POSITION_END;
// If in Rtl mode, the position should be flipped.
return isRtl ? !assignedPosition : assignedPosition;
}
/**
* Returns the avatar icon to use for this recipient entry. Returns null if we don't want to
* draw an icon for this recipient.
*/
private Bitmap getAvatarIcon(RecipientEntry contact) {
// Don't draw photos for recipients that have been typed in OR generated on the fly.
long contactId = contact.getContactId();
boolean drawPhotos = isPhoneQuery() ?
contactId != RecipientEntry.INVALID_CONTACT
: (contactId != RecipientEntry.INVALID_CONTACT
&& (contactId != RecipientEntry.GENERATED_CONTACT &&
!TextUtils.isEmpty(contact.getDisplayName())));
if (drawPhotos) {
byte[] photoBytes = contact.getPhotoBytes();
// There may not be a photo yet if anything but the first contact address
// was selected.
if (photoBytes == null && contact.getPhotoThumbnailUri() != null) {
// TODO: cache this in the recipient entry?
getAdapter().fetchPhoto(contact, contact.getPhotoThumbnailUri(), getContext().getContentResolver());
photoBytes = contact.getPhotoBytes();
}
if (photoBytes != null) {
return BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
} else {
// TODO: can the scaled down default photo be cached?
return mDefaultContactPhoto;
}
}
return null;
}
/**
* Get the background drawable for a RecipientChip.
*/
// Visible for testing.
/* package */Drawable getChipBackground(RecipientEntry contact) {
return contact.isValid() ? mChipBackground : mInvalidChipBackground;
}
/**
* Given a height, returns a Y offset that will draw the text in the middle of the height.
*/
protected float getTextYOffset(String text, TextPaint paint, int height) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int textHeight = bounds.bottom - bounds.top ;
return height - ((height - textHeight) / 2) - (int)paint.descent()/2;
}
/**
* Draws the icon onto the canvas given the source rectangle of the bitmap and the destination
* rectangle of the canvas.
*/
protected void drawIconOnCanvas(Bitmap icon, Canvas canvas, Paint paint, RectF src, RectF dst) {
Matrix matrix = new Matrix();
matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
canvas.drawBitmap(icon, matrix, paint);
}
private DrawableRecipientChip constructChipSpan(RecipientEntry contact, boolean pressed,
boolean leaveIconSpace) throws NullPointerException {
if (mChipBackground == null) {
throw new NullPointerException(
"Unable to render any chips as setChipDimensions was not called.");
}
TextPaint paint = getPaint();
float defaultSize = paint.getTextSize();
int defaultColor = paint.getColor();
Bitmap tmpBitmap;
if (pressed) {
tmpBitmap = createSelectedChip(contact, paint);
} else {
tmpBitmap = createUnselectedChip(contact, paint, leaveIconSpace);
}
// Pass the full text, un-ellipsized, to the chip.
Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
DrawableRecipientChip recipientChip =
new VisibleRecipientChip(result, contact, getImageSpanAlignment());
// Return text to the original size.
paint.setTextSize(defaultSize);
paint.setColor(defaultColor);
return recipientChip;
}
private int getImageSpanAlignment() {
switch (mImageSpanAlignment) {
case IMAGE_SPAN_ALIGNMENT_BASELINE:
return ImageSpan.ALIGN_BASELINE;
case IMAGE_SPAN_ALIGNMENT_BOTTOM:
return ImageSpan.ALIGN_BOTTOM;
default:
return ImageSpan.ALIGN_BOTTOM;
}
}
/**
* Calculate the bottom of the line the chip will be located on using:
* 1) which line the chip appears on
* 2) the height of a chip
* 3) padding built into the edit text view
*/
private int calculateOffsetFromBottom(int line) {
// Line offsets start at zero.
int actualLine = getLineCount() - (line + 1);
return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop())
+ getDropDownVerticalOffset();
}
/**
* Get the max amount of space a chip can take up. The formula takes into
* account the width of the EditTextView, any view padding, and padding
* that will be added to the chip.
*/
private float calculateAvailableWidth() {
return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2);
}
private void setChipDimensions(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecipientEditTextView, 0,
0);
Resources r = getContext().getResources();
mChipBackground = a.getDrawable(R.styleable.RecipientEditTextView_chipBackground);
if (mChipBackground == null) {
mChipBackground = r.getDrawable(R.drawable.chip_background);
}
mChipBackgroundPressed = a
.getDrawable(R.styleable.RecipientEditTextView_chipBackgroundPressed);
if (mChipBackgroundPressed == null) {
mChipBackgroundPressed = r.getDrawable(R.drawable.chip_background_selected);
}
mChipDelete = a.getDrawable(R.styleable.RecipientEditTextView_chipDelete);
if (mChipDelete == null) {
mChipDelete = r.getDrawable(R.drawable.chip_delete);
}
mChipPadding = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipPadding, -1);
if (mChipPadding == -1) {
mChipPadding = (int) r.getDimension(R.dimen.chip_padding);
}
mDefaultContactPhoto = BitmapFactory.decodeResource(r, R.drawable.ic_contact_picture);
mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.more_item, null);
mChipHeight = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipHeight, -1);
if (mChipHeight == -1) {
mChipHeight = r.getDimension(R.dimen.chip_height);
}
mChipFontSize = a.getDimensionPixelSize(R.styleable.RecipientEditTextView_chipFontSize, -1);
if (mChipFontSize == -1) {
mChipFontSize = r.getDimension(R.dimen.chip_text_size);
}
mInvalidChipBackground = a
.getDrawable(R.styleable.RecipientEditTextView_invalidChipBackground);
if (mInvalidChipBackground == null) {
mInvalidChipBackground = r.getDrawable(R.drawable.chip_background_invalid);
}
mAvatarPosition = a.getInt(R.styleable.RecipientEditTextView_avatarPosition, 1);
mImageSpanAlignment = a.getInt(R.styleable.RecipientEditTextView_imageSpanAlignment, 0);
mDisableDelete = a.getBoolean(R.styleable.RecipientEditTextView_disableDelete, false);
mLineSpacingExtra = r.getDimension(R.dimen.line_spacing_extra);
mMaxLines = r.getInteger(R.integer.chips_max_lines);
TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources()
.getDisplayMetrics());
}
a.recycle();
}
// Visible for testing.
/* package */ void setMoreItem(TextView moreItem) {
mMoreItem = moreItem;
}
// Visible for testing.
/* package */ void setChipBackground(Drawable chipBackground) {
mChipBackground = chipBackground;
}
// Visible for testing.
/* package */ void setChipHeight(int height) {
mChipHeight = height;
}
public float getChipHeight() {
return mChipHeight;
}
/**
* Set whether to shrink the recipients field such that at most
* one line of recipients chips are shown when the field loses
* focus. By default, the number of displayed recipients will be
* limited and a "more" chip will be shown when focus is lost.
* @param shrink
*/
public void setOnFocusListShrinkRecipients(boolean shrink) {
mShouldShrink = shrink;
}
@Override
public void onSizeChanged(int width, int height, int oldw, int oldh) {
super.onSizeChanged(width, height, oldw, oldh);
if (width != 0 && height != 0) {
if (mPendingChipsCount > 0) {
postHandlePendingChips();
} else {
checkChipWidths();
}
}
// Try to find the scroll view parent, if it exists.
if (mScrollView == null && !mTriedGettingScrollView) {
ViewParent parent = getParent();
while (parent != null && !(parent instanceof ScrollView)) {
parent = parent.getParent();
}
if (parent != null) {
mScrollView = (ScrollView) parent;
}
mTriedGettingScrollView = true;
}
}
private void postHandlePendingChips() {
mHandler.removeCallbacks(mHandlePendingChips);
mHandler.post(mHandlePendingChips);
}
private void checkChipWidths() {
// Check the widths of the associated chips.
DrawableRecipientChip[] chips = getSortedRecipients();
if (chips != null) {
Rect bounds;
for (DrawableRecipientChip chip : chips) {
bounds = chip.getBounds();
if (getWidth() > 0 && bounds.right - bounds.left >
getWidth() - getPaddingLeft() - getPaddingRight()) {
// Need to redraw that chip.
replaceChip(chip, chip.getEntry());
}
}
}
}
// Visible for testing.
/*package*/ void handlePendingChips() {
if (getViewWidth() <= 0) {
// The widget has not been sized yet.
// This will be called as a result of onSizeChanged
// at a later point.
return;
}
if (mPendingChipsCount <= 0) {
return;
}
synchronized (mPendingChips) {
Editable editable = getText();
// Tokenize!
if (mPendingChipsCount <= MAX_CHIPS_PARSED) {
for (int i = 0; i < mPendingChips.size(); i++) {
String current = mPendingChips.get(i);
int tokenStart = editable.toString().indexOf(current);
// Always leave a space at the end between tokens.
int tokenEnd = tokenStart + current.length() - 1;
if (tokenStart >= 0) {
// When we have a valid token, include it with the token
// to the left.
if (tokenEnd < editable.length() - 2
&& editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) {
tokenEnd++;
}
createReplacementChip(tokenStart, tokenEnd, editable, i < CHIP_LIMIT
|| !mShouldShrink);
}
mPendingChipsCount--;
}
sanitizeEnd();
} else {
mNoChips = true;
}
if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0
&& mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) {
if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) {
new RecipientReplacementTask().execute();
mTemporaryRecipients = null;
} else {
// Create the "more" chip
mIndividualReplacements = new IndividualReplacementTask();
mIndividualReplacements.execute(new ArrayList<DrawableRecipientChip>(
mTemporaryRecipients.subList(0, CHIP_LIMIT)));
if (mTemporaryRecipients.size() > CHIP_LIMIT) {
mTemporaryRecipients = new ArrayList<DrawableRecipientChip>(
mTemporaryRecipients.subList(CHIP_LIMIT,
mTemporaryRecipients.size()));
} else {
mTemporaryRecipients = null;
}
createMoreChip();
}
} else {
// There are too many recipients to look up, so just fall back
// to showing addresses for all of them.
mTemporaryRecipients = null;
createMoreChip();
}
mPendingChipsCount = 0;
mPendingChips.clear();
}
}
// Visible for testing.
/*package*/ int getViewWidth() {
return getWidth();
}
/**
* Remove any characters after the last valid chip.
*/
// Visible for testing.
/*package*/ void sanitizeEnd() {
// Don't sanitize while we are waiting for pending chips to complete.
if (mPendingChipsCount > 0) {
return;
}
// Find the last chip; eliminate any commit characters after it.
DrawableRecipientChip[] chips = getSortedRecipients();
Spannable spannable = getSpannable();
if (chips != null && chips.length > 0) {
int end;
mMoreChip = getMoreChip();
if (mMoreChip != null) {
end = spannable.getSpanEnd(mMoreChip);
} else {
end = getSpannable().getSpanEnd(getLastChip());
}
Editable editable = getText();
int length = editable.length();
if (length > end) {
// See what characters occur after that and eliminate them.
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "There were extra characters after the last tokenizable entry."
+ editable);
}
editable.delete(end + 1, length);
}
}