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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
|
/*
* 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.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.text.Editable;
import android.text.InputType;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
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.Patterns;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.DragEvent;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewParent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
/**
* 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,
PopupWindow.OnDismissListener, 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 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 int mChipPadding;
private Tokenizer mTokenizer;
private Validator mValidator;
private RecipientChip mSelectedChip;
private int mAlternatesLayout;
private Bitmap mDefaultContactPhoto;
private ImageSpan mMoreChip;
private TextView mMoreItem;
private final ArrayList<String> mPendingChips = new ArrayList<String>();
private Handler mHandler;
private int mPendingChipsCount = 0;
private boolean mNoChips = false;
private ListPopupWindow mAlternatesPopup;
private ListPopupWindow mAddressPopup;
private ArrayList<RecipientChip> mTemporaryRecipients;
private ArrayList<RecipientChip> 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;
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();
}
};
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);
mAlternatesPopup.setOnDismissListener(this);
mAddressPopup = new ListPopupWindow(context);
mAddressPopup.setOnDismissListener(this);
mCopyDialog = new Dialog(context);
mAlternatesListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView,View view, int position,
long rowId) {
mAlternatesPopup.setOnItemClickListener(null);
setEnabled(true);
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);
}
@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;
}
return connection;
}
/*package*/ RecipientChip getLastChip() {
RecipientChip last = null;
RecipientChip[] 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.
RecipientChip 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) {
final String displayString = text.toString();
int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA);
if (seperatorPos != 0 && !TextUtils.isEmpty(displayString)
&& TextUtils.getTrimmedLength(displayString) > 0) {
mPendingChipsCount++;
mPendingChips.add(text.toString());
}
}
// 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();
}
}
@Override
public void performValidation() {
// Do nothing. Chips handles its own validation.
}
private void shrink() {
if (mTokenizer == null) {
return;
}
if (mSelectedChip != null
&& mSelectedChip.getEntry().getContactId() != RecipientEntry.INVALID_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);
RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.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++;
}
// 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() {
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);
}
private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
// 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;
int deleteWidth = height;
float[] widths = new float[1];
paint.getTextWidths(" ", widths);
CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
calculateAvailableWidth(true) - deleteWidth - widths[0]);
// Make sure there is a minimum chip width so the user can ALWAYS
// tap a chip without difficulty.
int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
ellipsizedText.length()))
+ (mChipPadding * 2) + deleteWidth);
// Create the background of the chip.
Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(tmpBitmap);
if (mChipBackgroundPressed != null) {
mChipBackgroundPressed.setBounds(0, 0, width, height);
mChipBackgroundPressed.draw(canvas);
paint.setColor(sSelectedTextColor);
// Vertically center the text in the chip.
canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
getTextYOffset((String) ellipsizedText, paint, height), paint);
// Make the delete a square.
Rect backgroundPadding = new Rect();
mChipBackgroundPressed.getPadding(backgroundPadding);
mChipDelete.setBounds(width - deleteWidth + backgroundPadding.left,
0 + backgroundPadding.top,
width - backgroundPadding.right,
height - backgroundPadding.bottom);
mChipDelete.draw(canvas);
} else {
Log.w(TAG, "Unable to draw a background for the chips as it was never set");
}
return tmpBitmap;
}
private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) {
// 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;
int iconWidth = height;
float[] widths = new float[1];
paint.getTextWidths(" ", widths);
CharSequence ellipsizedText = ellipsizeText(createChipDisplayText(contact), paint,
calculateAvailableWidth(false) - iconWidth - widths[0]);
// Make sure there is a minimum chip width so the user can ALWAYS
// tap a chip without difficulty.
int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0,
ellipsizedText.length()))
+ (mChipPadding * 2) + iconWidth);
// Create the background of the chip.
Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(tmpBitmap);
Drawable background = getChipBackground(contact);
if (background != null) {
background.setBounds(0, 0, width, height);
background.draw(canvas);
// Don't draw photos for recipients that have been typed in.
if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) {
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?
((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact
.getPhotoThumbnailUri());
photoBytes = contact.getPhotoBytes();
}
Bitmap photo;
if (photoBytes != null) {
photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
} else {
// TODO: can the scaled down default photo be cached?
photo = mDefaultContactPhoto;
}
// Draw the photo on the left side.
if (photo != null) {
RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight());
Rect backgroundPadding = new Rect();
mChipBackground.getPadding(backgroundPadding);
RectF dst = new RectF(width - iconWidth + backgroundPadding.left,
0 + backgroundPadding.top,
width - backgroundPadding.right,
height - backgroundPadding.bottom);
Matrix matrix = new Matrix();
matrix.setRectToRect(src, dst, Matrix.ScaleToFit.FILL);
canvas.drawBitmap(photo, matrix, paint);
}
} else {
// Don't leave any space for the icon. It isn't being drawn.
iconWidth = 0;
}
paint.setColor(getContext().getResources().getColor(android.R.color.black));
// Vertically center the text in the chip.
canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding,
getTextYOffset((String)ellipsizedText, paint, height), paint);
} else {
Log.w(TAG, "Unable to draw a background for the chips as it was never set");
}
return tmpBitmap;
}
/**
* Get the background drawable for a RecipientChip.
*/
// Visible for testing.
/*package*/ Drawable getChipBackground(RecipientEntry contact) {
return (mValidator != null && mValidator.isValid(contact.getDestination())) ?
mChipBackground : mInvalidChipBackground;
}
private 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();
}
private RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed)
throws NullPointerException {
if (mChipBackground == null) {
throw new NullPointerException(
"Unable to render any chips as setChipDimensions was not called.");
}
Layout layout = getLayout();
TextPaint paint = getPaint();
float defaultSize = paint.getTextSize();
int defaultColor = paint.getColor();
Bitmap tmpBitmap;
if (pressed) {
tmpBitmap = createSelectedChip(contact, paint, layout);
} else {
tmpBitmap = createUnselectedChip(contact, paint, layout);
}
// Pass the full text, un-ellipsized, to the chip.
Drawable result = new BitmapDrawable(getResources(), tmpBitmap);
result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight());
RecipientChip recipientChip = new RecipientChip(result, contact, offset);
// Return text to the original size.
paint.setTextSize(defaultSize);
paint.setColor(defaultColor);
return recipientChip;
}
/**
* 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(boolean pressed) {
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);
}
mAlternatesLayout = a.getResourceId(R.styleable.RecipientEditTextView_chipAlternatesLayout,
-1);
if (mAlternatesLayout == -1) {
mAlternatesLayout = R.layout.chips_alternate_item;
}
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);
}
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;
}
/**
* 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.
RecipientChip[] chips = getSortedRecipients();
if (chips != null) {
Rect bounds;
for (RecipientChip chip : chips) {
bounds = chip.getDrawable().getBounds();
if (getWidth() > 0 && bounds.right - bounds.left > getWidth()) {
// 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);
int tokenEnd = tokenStart + current.length();
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);
}
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<RecipientChip>(
mTemporaryRecipients.subList(0, CHIP_LIMIT)));
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.
RecipientChip[] chips = getSortedRecipients();
if (chips != null && chips.length > 0) {
int end;
ImageSpan lastSpan;
mMoreChip = getMoreChip();
if (mMoreChip != null) {
lastSpan = mMoreChip;
} else {
lastSpan = getLastChip();
}
end = getSpannable().getSpanEnd(lastSpan);
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);
}
}
}
/**
* Create a chip that represents just the email address of a recipient. At some later
* point, this chip will be attached to a real contact entry, if one exists.
*/
private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) {
if (alreadyHasChip(tokenStart, tokenEnd)) {
// There is already a chip present at this location.
// Don't recreate it.
return;
}
String token = editable.toString().substring(tokenStart, tokenEnd);
int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA);
if (commitCharIndex == token.length() - 1) {
token = token.substring(0, token.length() - 1);
}
RecipientEntry entry = createTokenizedEntry(token);
if (entry != null) {
String destText = createAddressText(entry);
// Always leave a blank space at the end of a chip.
int textLength = destText.length() - 1;
SpannableString chipText = new SpannableString(destText);
int end = getSelectionEnd();
int start = mTokenizer != null ? mTokenizer.findTokenStart(getText(), end) : 0;
RecipientChip chip = null;
try {
if (!mNoChips) {
chip = constructChipSpan(entry, start, false);
chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage(), e);
}
editable.replace(tokenStart, tokenEnd, chipText);
// Add this chip to the list of entries "to replace"
if (chip != null) {
if (mTemporaryRecipients == null) {
mTemporaryRecipients = new ArrayList<RecipientChip>();
}
chip.setOriginalText(chipText.toString());
mTemporaryRecipients.add(chip);
}
}
}
private static boolean isPhoneNumber(String number) {
// TODO: replace this function with libphonenumber's isPossibleNumber (see
// PhoneNumberUtil). One complication is that it requires the sender's region which
// comes from the CurrentCountryIso. For now, let's just do this simple match.
if (TextUtils.isEmpty(number)) {
return false;
}
Matcher match = Patterns.PHONE.matcher(number);
return match.matches();
}
private RecipientEntry createTokenizedEntry(String token) {
if (TextUtils.isEmpty(token)) {
return null;
}
if (((BaseRecipientAdapter)getAdapter()).getQueryType() ==
BaseRecipientAdapter.QUERY_TYPE_PHONE && isPhoneNumber(token)) {
return RecipientEntry
.constructFakeEntry(token);
}
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token);
String display = null;
if (isValid(token) && tokens != null && tokens.length > 0) {
// If we can get a name from tokenizing, then generate an entry from
// this.
display = tokens[0].getName();
if (!TextUtils.isEmpty(display)) {
return RecipientEntry.constructGeneratedEntry(display, token);
} else {
display = tokens[0].getAddress();
if (!TextUtils.isEmpty(display)) {
return RecipientEntry.constructFakeEntry(display);
}
}
}
// Unable to validate the token or to create a valid token from it.
// Just create a chip the user can edit.
String validatedToken = null;
if (mValidator != null && !mValidator.isValid(token)) {
// Try fixing up the entry using the validator.
validatedToken = mValidator.fixText(token).toString();
if (!TextUtils.isEmpty(validatedToken)) {
if (validatedToken.contains(token)) {
// protect against the case of a validator with a null domain,
// which doesn't add a domain to the token
Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(validatedToken);
if (tokenized.length > 0) {
validatedToken = tokenized[0].getAddress();
}
} else {
// We ran into a case where the token was invalid and removed
// by the validator. In this case, just use the original token
// and let the user sort out the error chip.
validatedToken = null;
}
}
}
// Otherwise, fallback to just creating an editable email address chip.
return RecipientEntry
.constructFakeEntry(!TextUtils.isEmpty(validatedToken) ? validatedToken : token);
}
private boolean isValid(String text) {
return mValidator == null ? true : mValidator.isValid(text);
}
private String tokenizeAddress(String destination) {
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination);
if (tokens != null && tokens.length > 0) {
return tokens[0].getAddress();
}
return destination;
}
@Override
public void setTokenizer(Tokenizer tokenizer) {
mTokenizer = tokenizer;
super.setTokenizer(mTokenizer);
}
@Override
public void setValidator(Validator validator) {
mValidator = validator;
super.setValidator(validator);
}
/**
* We cannot use the default mechanism for replaceText. Instead,
* we override onItemClickListener so we can get all the associated
* contact information including display text, address, and id.
*/
@Override
protected void replaceText(CharSequence text) {
return;
}
/**
* Dismiss any selected chips when the back key is pressed.
*/
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
clearSelectedChip();
}
return super.onKeyPreIme(keyCode, event);
}
/**
* Monitor key presses in this view to see if the user types
* any commit keys, which consist of ENTER, TAB, or DPAD_CENTER.
* If the user has entered text that has contact matches and types
* a commit key, create a chip from the topmost matching contact.
* If the user has entered text that has no contact matches and types
* a commit key, then create a chip from the text they have entered.
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_DPAD_CENTER:
if (event.hasNoModifiers()) {
if (commitDefault()) {
return true;
}
if (mSelectedChip != null) {
clearSelectedChip();
return true;
} else if (focusNext()) {
return true;
}
}
break;
case KeyEvent.KEYCODE_TAB:
if (event.hasNoModifiers()) {
if (mSelectedChip != null) {
clearSelectedChip();
} else {
commitDefault();
}
if (focusNext()) {
return true;
}
}
}
return super.onKeyUp(keyCode, event);
}
private boolean focusNext() {
View next = focusSearch(View.FOCUS_DOWN);
if (next != null) {
next.requestFocus();
return true;
}
return false;
}
/**
* Create a chip from the default selection. If the popup is showing, the
* default is the first item in the popup suggestions list. Otherwise, it is
* whatever the user had typed in. End represents where the the tokenizer
* should search for a token to turn into a chip.
* @return If a chip was created from a real contact.
*/
private boolean commitDefault() {
// If there is no tokenizer, don't try to commit.
if (mTokenizer == null) {
return false;
}
Editable editable = getText();
int end = getSelectionEnd();
int start = mTokenizer.findTokenStart(editable, end);
if (shouldCreateChip(start, end)) {
int whatEnd = mTokenizer.findTokenEnd(getText(), start);
// In the middle of chip; treat this as an edit
// and commit the whole token.
if (whatEnd != getSelectionEnd()) {
handleEdit(start, whatEnd);
return true;
}
return commitChip(start, end , editable);
}
return false;
}
private void commitByCharacter() {
// We can't possibly commit by character if we can't tokenize.
if (mTokenizer == null) {
return;
}
Editable editable = getText();
int end = getSelectionEnd();
int start = mTokenizer.findTokenStart(editable, end);
if (shouldCreateChip(start, end)) {
commitChip(start, end, editable);
}
setSelection(getText().length());
}
private boolean commitChip(int start, int end, Editable editable) {
ListAdapter adapter = getAdapter();
if (adapter != null && adapter.getCount() > 0 && enoughToFilter()
&& end == getSelectionEnd()) {
// choose the first entry.
submitItemAtPosition(0);
dismissDropDown();
return true;
} else {
int tokenEnd = mTokenizer.findTokenEnd(editable, start);
if (editable.length() > tokenEnd + 1) {
char charAt = editable.charAt(tokenEnd + 1);
if (charAt == COMMIT_CHAR_COMMA || charAt == COMMIT_CHAR_SEMICOLON) {
tokenEnd++;
}
}
String text = editable.toString().substring(start, tokenEnd).trim();
clearComposingText();
if (text != null && text.length() > 0 && !text.equals(" ")) {
RecipientEntry entry = createTokenizedEntry(text);
if (entry != null) {
QwertyKeyListener.markAsReplaced(editable, start, end, "");
CharSequence chipText = createChip(entry, false);
if (chipText != null && start > -1 && end > -1) {
editable.replace(start, end, chipText);
}
}
// Only dismiss the dropdown if it is related to the text we
// just committed.
// For paste, it may not be as there are possibly multiple
// tokens being added.
if (end == getSelectionEnd()) {
dismissDropDown();
}
sanitizeBetween();
return true;
}
}
return false;
}
// Visible for testing.
/* package */ void sanitizeBetween() {
// Don't sanitize while we are waiting for content to chipify.
if (mPendingChipsCount > 0) {
return;
}
// Find the last chip.
RecipientChip[] recips = getSortedRecipients();
if (recips != null && recips.length > 0) {
RecipientChip last = recips[recips.length - 1];
RecipientChip beforeLast = null;
if (recips.length > 1) {
beforeLast = recips[recips.length - 2];
}
int startLooking = 0;
int end = getSpannable().getSpanStart(last);
if (beforeLast != null) {
startLooking = getSpannable().getSpanEnd(beforeLast);
Editable text = getText();
if (startLooking == -1 || startLooking > text.length() - 1) {
// There is nothing after this chip.
return;
}
if (text.charAt(startLooking) == ' ') {
startLooking++;
}
}
if (startLooking >= 0 && end >= 0 && startLooking < end) {
getText().delete(startLooking, end);
}
}
}
private boolean shouldCreateChip(int start, int end) {
return !mNoChips && hasFocus() && enoughToFilter() && !alreadyHasChip(start, end);
}
private boolean alreadyHasChip(int start, int end) {
if (mNoChips) {
return true;
}
RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class);
if ((chips == null || chips.length == 0)) {
return false;
}
return true;
}
private void handleEdit(int start, int end) {
if (start == -1 || end == -1) {
// This chip no longer exists in the field.
dismissDropDown();
return;
}
// This is in the middle of a chip, so select out the whole chip
// and commit it.
Editable editable = getText();
setSelection(end);
String text = getText().toString().substring(start, end);
if (!TextUtils.isEmpty(text)) {
RecipientEntry entry = RecipientEntry.constructFakeEntry(text);
QwertyKeyListener.markAsReplaced(editable, start, end, "");
CharSequence chipText = createChip(entry, false);
int selEnd = getSelectionEnd();
if (chipText != null && start > -1 && selEnd > -1) {
editable.replace(start, selEnd, chipText);
}
}
dismissDropDown();
}
/**
* If there is a selected chip, delegate the key events
* to the selected chip.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) {
if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
mAlternatesPopup.dismiss();
}
removeChip(mSelectedChip);
}
if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) {
return true;
}
return super.onKeyDown(keyCode, event);
}
// Visible for testing.
/* package */ Spannable getSpannable() {
return getText();
}
private int getChipStart(RecipientChip chip) {
return getSpannable().getSpanStart(chip);
}
private int getChipEnd(RecipientChip chip) {
return getSpannable().getSpanEnd(chip);
}
/**
* Instead of filtering on the entire contents of the edit box,
* this subclass method filters on the range from
* {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd}
* if the length of that range meets or exceeds {@link #getThreshold}
* and makes sure that the range is not already a Chip.
*/
@Override
protected void performFiltering(CharSequence text, int keyCode) {
if (enoughToFilter() && !isCompletedToken(text)) {
int end = getSelectionEnd();
int start = mTokenizer.findTokenStart(text, end);
// If this is a RecipientChip, don't filter
// on its contents.
Spannable span = getSpannable();
RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class);
if (chips != null && chips.length > 0) {
return;
}
}
super.performFiltering(text, keyCode);
}
// Visible for testing.
/*package*/ boolean isCompletedToken(CharSequence text) {
if (TextUtils.isEmpty(text)) {
return false;
}
// Check to see if this is a completed token before filtering.
int end = text.length();
int start = mTokenizer.findTokenStart(text, end);
String token = text.toString().substring(start, end).trim();
if (!TextUtils.isEmpty(token)) {
char atEnd = token.charAt(token.length() - 1);
return atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON;
}
return false;
}
private void clearSelectedChip() {
if (mSelectedChip != null) {
unselectChip(mSelectedChip);
mSelectedChip = null;
}
setCursorVisible(true);
}
/**
* Monitor touch events in the RecipientEditTextView.
* If the view does not have focus, any tap on the view
* will just focus the view. If the view has focus, determine
* if the touch target is a recipient chip. If it is and the chip
* is not selected, select it and clear any other selected chips.
* If it isn't, then select that chip.
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isFocused()) {
// Ignore any chip taps until this view is focused.
return super.onTouchEvent(event);
}
boolean handled = super.onTouchEvent(event);
int action = event.getAction();
boolean chipWasSelected = false;
if (mSelectedChip == null) {
mGestureDetector.onTouchEvent(event);
}
if (mCopyAddress == null && action == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
int offset = putOffsetInRange(getOffsetForPosition(x, y));
RecipientChip currentChip = findChip(offset);
if (currentChip != null) {
if (action == MotionEvent.ACTION_UP) {
if (mSelectedChip != null && mSelectedChip != currentChip) {
clearSelectedChip();
mSelectedChip = selectChip(currentChip);
} else if (mSelectedChip == null) {
setSelection(getText().length());
commitDefault();
mSelectedChip = selectChip(currentChip);
} else {
onClick(mSelectedChip, offset, x, y);
}
}
chipWasSelected = true;
handled = true;
} else if (mSelectedChip != null
&& mSelectedChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
chipWasSelected = true;
}
}
if (action == MotionEvent.ACTION_UP && !chipWasSelected) {
clearSelectedChip();
}
return handled;
}
private void scrollLineIntoView(int line) {
if (mScrollView != null) {
mScrollView.scrollBy(0, calculateOffsetFromBottom(line));
}
}
private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup,
int width, Context context) {
int line = getLayout().getLineForOffset(getChipStart(currentChip));
int bottom = calculateOffsetFromBottom(line);
// Align the alternates popup with the left side of the View,
// regardless of the position of the chip tapped.
alternatesPopup.setWidth(width);
setEnabled(false);
alternatesPopup.setAnchorView(this);
alternatesPopup.setVerticalOffset(bottom);
alternatesPopup.setAdapter(createAlternatesAdapter(currentChip));
alternatesPopup.setOnItemClickListener(mAlternatesListener);
// Clear the checked item.
mCheckedItem = -1;
alternatesPopup.show();
ListView listView = alternatesPopup.getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Checked item would be -1 if the adapter has not
// loaded the view that should be checked yet. The
// variable will be set correctly when onCheckedItemChanged
// is called in a separate thread.
if (mCheckedItem != -1) {
listView.setItemChecked(mCheckedItem, true);
mCheckedItem = -1;
}
}
// Dismiss listener for alterns and single address popup.
@Override
public void onDismiss() {
setEnabled(true);
}
private ListAdapter createAlternatesAdapter(RecipientChip chip) {
return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(),
mAlternatesLayout, ((BaseRecipientAdapter)getAdapter()).getQueryType(), this);
}
private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) {
return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip
.getEntry());
}
@Override
public void onCheckedItemChanged(int position) {
ListView listView = mAlternatesPopup.getListView();
if (listView != null && listView.getCheckedItemCount() == 0) {
listView.setItemChecked(position, true);
}
mCheckedItem = position;
}
// TODO: This algorithm will need a lot of tweaking after more people have used
// the chips ui. This attempts to be "forgiving" to fat finger touches by favoring
// what comes before the finger.
private int putOffsetInRange(int o) {
int offset = o;
Editable text = getText();
int length = text.length();
// Remove whitespace from end to find "real end"
int realLength = length;
for (int i = length - 1; i >= 0; i--) {
if (text.charAt(i) == ' ') {
realLength--;
} else {
break;
}
}
// If the offset is beyond or at the end of the text,
// leave it alone.
if (offset >= realLength) {
return offset;
}
Editable editable = getText();
while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) {
// Keep walking backward!
offset--;
}
return offset;
}
private int findText(Editable text, int offset) {
if (text.charAt(offset) != ' ') {
return offset;
}
return -1;
}
private RecipientChip findChip(int offset) {
RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class);
// Find the chip that contains this offset.
for (int i = 0; i < chips.length; i++) {
RecipientChip chip = chips[i];
int start = getChipStart(chip);
int end = getChipEnd(chip);
if (offset >= start && offset <= end) {
return chip;
}
}
return null;
}
// Visible for testing.
// Use this method to generate text to add to the list of addresses.
/* package */String createAddressText(RecipientEntry entry) {
String display = entry.getDisplayName();
String address = entry.getDestination();
if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
display = null;
}
String trimmedDisplayText;
if (((BaseRecipientAdapter)getAdapter()).getQueryType() ==
BaseRecipientAdapter.QUERY_TYPE_PHONE && isPhoneNumber(address)) {
trimmedDisplayText = address.trim();
} else {
if (address != null) {
// Tokenize out the address in case the address already
// contained the username as well.
Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
if (tokenized != null && tokenized.length > 0) {
address = tokenized[0].getAddress();
}
}
Rfc822Token token = new Rfc822Token(display, address, null);
trimmedDisplayText = token.toString().trim();
}
int index = trimmedDisplayText.indexOf(",");
return mTokenizer != null && !TextUtils.isEmpty(trimmedDisplayText)
&& index < trimmedDisplayText.length() - 1 ? (String) mTokenizer
.terminateToken(trimmedDisplayText) : trimmedDisplayText;
}
// Visible for testing.
// Use this method to generate text to display in a chip.
/*package*/ String createChipDisplayText(RecipientEntry entry) {
String display = entry.getDisplayName();
String address = entry.getDestination();
if (TextUtils.isEmpty(display) || TextUtils.equals(display, address)) {
display = null;
}
if (address != null && !(((BaseRecipientAdapter)getAdapter()).getQueryType() ==
BaseRecipientAdapter.QUERY_TYPE_PHONE && isPhoneNumber(address))) {
// Tokenize out the address in case the address already
// contained the username as well.
Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(address);
if (tokenized != null && tokenized.length > 0) {
address = tokenized[0].getAddress();
}
}
if (!TextUtils.isEmpty(display)) {
return display;
} else if (!TextUtils.isEmpty(address)){
return address;
} else {
return new Rfc822Token(display, address, null).toString();
}
}
private CharSequence createChip(RecipientEntry entry, boolean pressed) {
String displayText = createAddressText(entry);
if (TextUtils.isEmpty(displayText)) {
return null;
}
SpannableString chipText = null;
// Always leave a blank space at the end of a chip.
int end = getSelectionEnd();
int start = mTokenizer.findTokenStart(getText(), end);
int textLength = displayText.length()-1;
chipText = new SpannableString(displayText);
if (!mNoChips) {
try {
RecipientChip chip = constructChipSpan(entry, start, pressed);
chipText.setSpan(chip, 0, textLength,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
chip.setOriginalText(chipText.toString());
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage(), e);
return null;
}
}
return chipText;
}
/**
* When an item in the suggestions list has been clicked, create a chip from the
* contact information of the selected item.
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
submitItemAtPosition(position);
}
private void submitItemAtPosition(int position) {
RecipientEntry entry = createValidatedEntry(
(RecipientEntry)getAdapter().getItem(position));
if (entry == null) {
return;
}
clearComposingText();
int end = getSelectionEnd();
int start = mTokenizer.findTokenStart(getText(), end);
Editable editable = getText();
QwertyKeyListener.markAsReplaced(editable, start, end, "");
CharSequence chip = createChip(entry, false);
if (chip != null && start >= 0 && end >= 0) {
editable.replace(start, end, chip);
}
sanitizeBetween();
}
private RecipientEntry createValidatedEntry(RecipientEntry item) {
if (item == null) {
return null;
}
final RecipientEntry entry;
// If the display name and the address are the same, or if this is a
// valid contact, but the destination is invalid, then make this a fake
// recipient that is editable.
String destination = item.getDestination();
if (RecipientEntry.isCreatedRecipient(item.getContactId())
&& (TextUtils.isEmpty(item.getDisplayName())
|| TextUtils.equals(item.getDisplayName(), destination)
|| (mValidator != null && !mValidator.isValid(destination)))) {
entry = RecipientEntry.constructFakeEntry(destination);
} else {
entry = item;
}
return entry;
}
/** Returns a collection of contact Id for each chip inside this View. */
/* package */ Collection<Long> getContactIds() {
final Set<Long> result = new HashSet<Long>();
RecipientChip[] chips = getSortedRecipients();
if (chips != null) {
for (RecipientChip chip : chips) {
result.add(chip.getContactId());
}
}
return result;
}
/** Returns a collection of data Id for each chip inside this View. May be null. */
/* package */ Collection<Long> getDataIds() {
final Set<Long> result = new HashSet<Long>();
RecipientChip [] chips = getSortedRecipients();
if (chips != null) {
for (RecipientChip chip : chips) {
result.add(chip.getDataId());
}
}
return result;
}
// Visible for testing.
/* package */RecipientChip[] getSortedRecipients() {
RecipientChip[] recips = getSpannable()
.getSpans(0, getText().length(), RecipientChip.class);
ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays
.asList(recips));
final Spannable spannable = getSpannable();
Collections.sort(recipientsList, new Comparator<RecipientChip>() {
@Override
public int compare(RecipientChip first, RecipientChip second) {
int firstStart = spannable.getSpanStart(first);
int secondStart = spannable.getSpanStart(second);
if (firstStart < secondStart) {
return -1;
} else if (firstStart > secondStart) {
return 1;
} else {
return 0;
}
}
});
return recipientsList.toArray(new RecipientChip[recipientsList.size()]);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
/**
* No chips are selectable.
*/
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
// Visible for testing.
/* package */ImageSpan getMoreChip() {
MoreImageSpan[] moreSpans = getSpannable().getSpans(0, getText().length(),
MoreImageSpan.class);
return moreSpans != null && moreSpans.length > 0 ? moreSpans[0] : null;
}
private MoreImageSpan createMoreSpan(int count) {
String moreText = String.format(mMoreItem.getText().toString(), count);
TextPaint morePaint = new TextPaint(getPaint());
morePaint.setTextSize(mMoreItem.getTextSize());
morePaint.setColor(mMoreItem.getCurrentTextColor());
int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft()
+ mMoreItem.getPaddingRight();
int height = getLineHeight();
Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(drawable);
int adjustedHeight = height;
Layout layout = getLayout();
if (layout != null) {
adjustedHeight -= layout.getLineDescent(0);
}
canvas.drawText(moreText, 0, moreText.length(), 0, adjustedHeight, morePaint);
Drawable result = new BitmapDrawable(getResources(), drawable);
result.setBounds(0, 0, width, height);
return new MoreImageSpan(result);
}
// Visible for testing.
/*package*/ void createMoreChipPlainText() {
// Take the first <= CHIP_LIMIT addresses and get to the end of the second one.
Editable text = getText();
int start = 0;
int end = start;
for (int i = 0; i < CHIP_LIMIT; i++) {
end = movePastTerminators(mTokenizer.findTokenEnd(text, start));
start = end; // move to the next token and get its end.
}
// Now, count total addresses.
start = 0;
int tokenCount = countTokens(text);
MoreImageSpan moreSpan = createMoreSpan(tokenCount - CHIP_LIMIT);
SpannableString chipText = new SpannableString(text.subSequence(end, text.length()));
chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.replace(end, text.length(), chipText);
mMoreChip = moreSpan;
}
// Visible for testing.
/* package */int countTokens(Editable text) {
int tokenCount = 0;
int start = 0;
while (start < text.length()) {
start = movePastTerminators(mTokenizer.findTokenEnd(text, start));
tokenCount++;
if (start >= text.length()) {
break;
}
}
return tokenCount;
}
/**
* Create the more chip. The more chip is text that replaces any chips that
* do not fit in the pre-defined available space when the
* RecipientEditTextView loses focus.
*/
// Visible for testing.
/* package */ void createMoreChip() {
if (mNoChips) {
createMoreChipPlainText();
return;
}
if (!mShouldShrink) {
return;
}
ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class);
if (tempMore.length > 0) {
getSpannable().removeSpan(tempMore[0]);
}
RecipientChip[] recipients = getSortedRecipients();
if (recipients == null || recipients.length <= CHIP_LIMIT) {
mMoreChip = null;
return;
}
Spannable spannable = getSpannable();
int numRecipients = recipients.length;
int overage = numRecipients - CHIP_LIMIT;
MoreImageSpan moreSpan = createMoreSpan(overage);
mRemovedSpans = new ArrayList<RecipientChip>();
int totalReplaceStart = 0;
int totalReplaceEnd = 0;
Editable text = getText();
for (int i = numRecipients - overage; i < recipients.length; i++) {
mRemovedSpans.add(recipients[i]);
if (i == numRecipients - overage) {
totalReplaceStart = spannable.getSpanStart(recipients[i]);
}
if (i == recipients.length - 1) {
totalReplaceEnd = spannable.getSpanEnd(recipients[i]);
}
if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) {
int spanStart = spannable.getSpanStart(recipients[i]);
int spanEnd = spannable.getSpanEnd(recipients[i]);
recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd));
}
spannable.removeSpan(recipients[i]);
}
if (totalReplaceEnd < text.length()) {
totalReplaceEnd = text.length();
}
int end = Math.max(totalReplaceStart, totalReplaceEnd);
int start = Math.min(totalReplaceStart, totalReplaceEnd);
SpannableString chipText = new SpannableString(text.subSequence(start, end));
chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text.replace(start, end, chipText);
mMoreChip = moreSpan;
}
/**
* Replace the more chip, if it exists, with all of the recipient chips it had
* replaced when the RecipientEditTextView gains focus.
*/
// Visible for testing.
/*package*/ void removeMoreChip() {
if (mMoreChip != null) {
Spannable span = getSpannable();
span.removeSpan(mMoreChip);
mMoreChip = null;
// Re-add the spans that were removed.
if (mRemovedSpans != null && mRemovedSpans.size() > 0) {
// Recreate each removed span.
RecipientChip[] recipients = getSortedRecipients();
// Start the search for tokens after the last currently visible
// chip.
if (recipients == null || recipients.length == 0) {
return;
}
int end = span.getSpanEnd(recipients[recipients.length - 1]);
Editable editable = getText();
for (RecipientChip chip : mRemovedSpans) {
int chipStart;
int chipEnd;
String token;
// Need to find the location of the chip, again.
token = (String) chip.getOriginalText();
// As we find the matching recipient for the remove spans,
// reduce the size of the string we need to search.
// That way, if there are duplicates, we always find the correct
// recipient.
chipStart = editable.toString().indexOf(token, end);
end = chipEnd = Math.min(editable.length(), chipStart + token.length());
// Only set the span if we found a matching token.
if (chipStart != -1) {
editable.setSpan(chip, chipStart, chipEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
mRemovedSpans.clear();
}
}
}
/**
* Show specified chip as selected. If the RecipientChip is just an email address,
* selecting the chip will take the contents of the chip and place it at
* the end of the RecipientEditTextView for inline editing. If the
* RecipientChip is a complete contact, then selecting the chip
* will change the background color of the chip, show the delete icon,
* and a popup window with the address in use highlighted and any other
* alternate addresses for the contact.
* @param currentChip Chip to select.
* @return A RecipientChip in the selected state or null if the chip
* just contained an email address.
*/
private RecipientChip selectChip(RecipientChip currentChip) {
if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) {
CharSequence text = currentChip.getValue();
Editable editable = getText();
removeChip(currentChip);
editable.append(text);
setCursorVisible(true);
setSelection(editable.length());
return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1);
} else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) {
int start = getChipStart(currentChip);
int end = getChipEnd(currentChip);
getSpannable().removeSpan(currentChip);
RecipientChip newChip;
try {
if (mNoChips) {
return null;
}
newChip = constructChipSpan(currentChip.getEntry(), start, true);
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage(), e);
return null;
}
Editable editable = getText();
QwertyKeyListener.markAsReplaced(editable, start, end, "");
if (start == -1 || end == -1) {
Log.d(TAG, "The chip being selected no longer exists but should.");
} else {
editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
newChip.setSelected(true);
if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
}
showAddress(newChip, mAddressPopup, getWidth(), getContext());
setCursorVisible(false);
return newChip;
} else {
int start = getChipStart(currentChip);
int end = getChipEnd(currentChip);
getSpannable().removeSpan(currentChip);
RecipientChip newChip;
try {
newChip = constructChipSpan(currentChip.getEntry(), start, true);
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage(), e);
return null;
}
Editable editable = getText();
QwertyKeyListener.markAsReplaced(editable, start, end, "");
if (start == -1 || end == -1) {
Log.d(TAG, "The chip being selected no longer exists but should.");
} else {
editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
newChip.setSelected(true);
if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) {
scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip)));
}
showAlternates(newChip, mAlternatesPopup, getWidth(), getContext());
setCursorVisible(false);
return newChip;
}
}
private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup,
int width, Context context) {
int line = getLayout().getLineForOffset(getChipStart(currentChip));
int bottom = calculateOffsetFromBottom(line);
// Align the alternates popup with the left side of the View,
// regardless of the position of the chip tapped.
setEnabled(false);
popup.setWidth(width);
popup.setAnchorView(this);
popup.setVerticalOffset(bottom);
popup.setAdapter(createSingleAddressAdapter(currentChip));
popup.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
unselectChip(currentChip);
popup.dismiss();
}
});
popup.show();
ListView listView = popup.getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setItemChecked(0, true);
}
/**
* Remove selection from this chip. Unselecting a RecipientChip will render
* the chip without a delete icon and with an unfocused background. This is
* called when the RecipientChip no longer has focus.
*/
private void unselectChip(RecipientChip chip) {
int start = getChipStart(chip);
int end = getChipEnd(chip);
Editable editable = getText();
mSelectedChip = null;
if (start == -1 || end == -1) {
Log.w(TAG, "The chip doesn't exist or may be a chip a user was editing");
setSelection(editable.length());
commitDefault();
} else {
getSpannable().removeSpan(chip);
QwertyKeyListener.markAsReplaced(editable, start, end, "");
editable.removeSpan(chip);
try {
if (!mNoChips) {
editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage(), e);
}
}
setCursorVisible(true);
setSelection(editable.length());
if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) {
mAlternatesPopup.dismiss();
}
}
/**
* Return whether a touch event was inside the delete target of
* a selected chip. It is in the delete target if:
* 1) the x and y points of the event are within the
* delete assset.
* 2) the point tapped would have caused a cursor to appear
* right after the selected chip.
* @return boolean
*/
private boolean isInDelete(RecipientChip chip, int offset, float x, float y) {
// Figure out the bounds of this chip and whether or not
// the user clicked in the X portion.
return chip.isSelected() && offset == getChipEnd(chip);
}
/**
* Remove the chip and any text associated with it from the RecipientEditTextView.
*/
// Visible for testing.
/*pacakge*/ void removeChip(RecipientChip chip) {
Spannable spannable = getSpannable();
int spanStart = spannable.getSpanStart(chip);
int spanEnd = spannable.getSpanEnd(chip);
Editable text = getText();
int toDelete = spanEnd;
boolean wasSelected = chip == mSelectedChip;
// Clear that there is a selected chip before updating any text.
if (wasSelected) {
mSelectedChip = null;
}
// Always remove trailing spaces when removing a chip.
while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') {
toDelete++;
}
spannable.removeSpan(chip);
if (spanStart >= 0 && toDelete > 0) {
text.delete(spanStart, toDelete);
}
if (wasSelected) {
clearSelectedChip();
}
}
/**
* Replace this currently selected chip with a new chip
* that uses the contact data provided.
*/
// Visible for testing.
/*package*/ void replaceChip(RecipientChip chip, RecipientEntry entry) {
boolean wasSelected = chip == mSelectedChip;
if (wasSelected) {
mSelectedChip = null;
}
int start = getChipStart(chip);
int end = getChipEnd(chip);
getSpannable().removeSpan(chip);
Editable editable = getText();
CharSequence chipText = createChip(entry, false);
if (chipText != null) {
if (start == -1 || end == -1) {
Log.e(TAG, "The chip to replace does not exist but should.");
editable.insert(0, chipText);
} else {
if (!TextUtils.isEmpty(chipText)) {
// There may be a space to replace with this chip's new
// associated
// space. Check for it
int toReplace = end;
while (toReplace >= 0 && toReplace < editable.length()
&& editable.charAt(toReplace) == ' ') {
toReplace++;
}
editable.replace(start, toReplace, chipText);
}
}
}
setCursorVisible(true);
if (wasSelected) {
clearSelectedChip();
}
}
/**
* Handle click events for a chip. When a selected chip receives a click
* event, see if that event was in the delete icon. If so, delete it.
* Otherwise, unselect the chip.
*/
public void onClick(RecipientChip chip, int offset, float x, float y) {
if (chip.isSelected()) {
if (isInDelete(chip, offset, x, y)) {
removeChip(chip);
} else {
clearSelectedChip();
}
}
}
private boolean chipsPending() {
return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0);
}
@Override
public void removeTextChangedListener(TextWatcher watcher) {
mTextWatcher = null;
super.removeTextChangedListener(watcher);
}
private class RecipientTextWatcher implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
// If the text has been set to null or empty, make sure we remove
// all the spans we applied.
if (TextUtils.isEmpty(s)) {
// Remove all the chips spans.
Spannable spannable = getSpannable();
RecipientChip[] chips = spannable.getSpans(0, getText().length(),
RecipientChip.class);
for (RecipientChip chip : chips) {
spannable.removeSpan(chip);
}
if (mMoreChip != null) {
spannable.removeSpan(mMoreChip);
}
return;
}
// Get whether there are any recipients pending addition to the
// view. If there are, don't do anything in the text watcher.
if (chipsPending()) {
return;
}
// If the user is editing a chip, don't clear it.
if (mSelectedChip != null
&& mSelectedChip.getContactId() != RecipientEntry.INVALID_CONTACT) {
setCursorVisible(true);
setSelection(getText().length());
clearSelectedChip();
}
int length = s.length();
// Make sure there is content there to parse and that it is
// not just the commit character.
if (length > 1) {
char last;
int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1;
int len = length() - 1;
if (end != len) {
last = s.charAt(end);
} else {
last = s.charAt(len);
}
if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) {
commitByCharacter();
} else if (last == COMMIT_CHAR_SPACE) {
// Check if this is a valid email address. If it is,
// commit it.
String text = getText().toString();
int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text,
tokenStart));
if (!TextUtils.isEmpty(sub) && mValidator != null && mValidator.isValid(sub)) {
commitByCharacter();
}
}
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// This is a delete; check to see if the insertion point is on a space
// following a chip.
if (before > count) {
// If the item deleted is a space, and the thing before the
// space is a chip, delete the entire span.
int selStart = getSelectionStart();
RecipientChip[] repl = getSpannable().getSpans(selStart, selStart,
RecipientChip.class);
if (repl.length > 0) {
// There is a chip there! Just remove it.
Editable editable = getText();
// Add the separator token.
int tokenStart = mTokenizer.findTokenStart(editable, selStart);
int tokenEnd = mTokenizer.findTokenEnd(editable, tokenStart);
tokenEnd = tokenEnd + 1;
if (tokenEnd > editable.length()) {
tokenEnd = editable.length();
}
editable.delete(tokenStart, tokenEnd);
getSpannable().removeSpan(repl[0]);
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing.
}
}
/**
* Handles pasting a {@link ClipData} to this {@link RecipientEditTextView}.
*/
private void handlePasteClip(ClipData clip) {
removeTextChangedListener(mTextWatcher);
if (clip != null && clip.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)){
for (int i = 0; i < clip.getItemCount(); i++) {
CharSequence paste = clip.getItemAt(i).getText();
if (paste != null) {
int start = getSelectionStart();
int end = getSelectionEnd();
Editable editable = getText();
if (start >= 0 && end >= 0 && start != end) {
editable.append(paste, start, end);
} else {
editable.insert(end, paste);
}
handlePasteAndReplace();
}
}
}
mHandler.post(mAddTextWatcher);
}
@Override
public boolean onTextContextMenuItem(int id) {
if (id == android.R.id.paste) {
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
Context.CLIPBOARD_SERVICE);
handlePasteClip(clipboard.getPrimaryClip());
return true;
}
return super.onTextContextMenuItem(id);
}
private void handlePasteAndReplace() {
ArrayList<RecipientChip> created = handlePaste();
if (created != null && created.size() > 0) {
// Perform reverse lookups on the pasted contacts.
IndividualReplacementTask replace = new IndividualReplacementTask();
replace.execute(created);
}
}
// Visible for testing.
/* package */ArrayList<RecipientChip> handlePaste() {
String text = getText().toString();
int originalTokenStart = mTokenizer.findTokenStart(text, getSelectionEnd());
String lastAddress = text.substring(originalTokenStart);
int tokenStart = originalTokenStart;
int prevTokenStart = tokenStart;
RecipientChip findChip = null;
ArrayList<RecipientChip> created = new ArrayList<RecipientChip>();
if (tokenStart != 0) {
// There are things before this!
while (tokenStart != 0 && findChip == null) {
prevTokenStart = tokenStart;
tokenStart = mTokenizer.findTokenStart(text, tokenStart);
findChip = findChip(tokenStart);
}
if (tokenStart != originalTokenStart) {
if (findChip != null) {
tokenStart = prevTokenStart;
}
int tokenEnd;
RecipientChip createdChip;
while (tokenStart < originalTokenStart) {
tokenEnd = movePastTerminators(mTokenizer.findTokenEnd(text, tokenStart));
commitChip(tokenStart, tokenEnd, getText());
createdChip = findChip(tokenStart);
// +1 for the space at the end.
tokenStart = getSpannable().getSpanEnd(createdChip) + 1;
created.add(createdChip);
}
}
}
// Take a look at the last token. If the token has been completed with a
// commit character, create a chip.
if (isCompletedToken(lastAddress)) {
Editable editable = getText();
tokenStart = editable.toString().indexOf(lastAddress, originalTokenStart);
commitChip(tokenStart, editable.length(), editable);
created.add(findChip(tokenStart));
}
return created;
}
// Visible for testing.
/* package */int movePastTerminators(int tokenEnd) {
if (tokenEnd >= length()) {
return tokenEnd;
}
char atEnd = getText().toString().charAt(tokenEnd);
if (atEnd == COMMIT_CHAR_COMMA || atEnd == COMMIT_CHAR_SEMICOLON) {
tokenEnd++;
}
// This token had not only an end token character, but also a space
// separating it from the next token.
if (tokenEnd < length() && getText().toString().charAt(tokenEnd) == ' ') {
tokenEnd++;
}
return tokenEnd;
}
private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> {
private RecipientChip createFreeChip(RecipientEntry entry) {
try {
if (mNoChips) {
return null;
}
return constructChipSpan(entry, -1, false);
} catch (NullPointerException e) {
Log.e(TAG, e.getMessage(), e);
return null;
}
}
@Override
protected Void doInBackground(Void... params) {
if (mIndividualReplacements != null) {
mIndividualReplacements.cancel(true);
}
// For each chip in the list, look up the matching contact.
// If there is a match, replace that chip with the matching
// chip.
final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>();
RecipientChip[] existingChips = getSortedRecipients();
for (int i = 0; i < existingChips.length; i++) {
originalRecipients.add(existingChips[i]);
}
if (mRemovedSpans != null) {
originalRecipients.addAll(mRemovedSpans);
}
String[] addresses = new String[originalRecipients.size()];
RecipientChip chip;
for (int i = 0; i < originalRecipients.size(); i++) {
chip = originalRecipients.get(i);
if (chip != null) {
addresses[i] = createAddressText(chip.getEntry());
}
}
HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
.getMatchingRecipients(getContext(), addresses);
final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>();
for (final RecipientChip temp : originalRecipients) {
RecipientEntry entry = null;
if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
&& getSpannable().getSpanStart(temp) != -1) {
// Replace this.
entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry()
.getDestination())));
}
if (entry != null) {
replacements.add(createFreeChip(entry));
} else {
replacements.add(temp);
}
}
if (replacements != null && replacements.size() > 0) {
mHandler.post(new Runnable() {
@Override
public void run() {
SpannableStringBuilder text = new SpannableStringBuilder(getText()
.toString());
Editable oldText = getText();
int start, end;
int i = 0;
for (RecipientChip chip : originalRecipients) {
start = oldText.getSpanStart(chip);
if (start != -1) {
end = oldText.getSpanEnd(chip);
oldText.removeSpan(chip);
// Leave a spot for the space!
RecipientChip replacement = replacements.get(i);
text.setSpan(replacement, start, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
replacement.setOriginalText(text.toString().substring(start, end));
}
i++;
}
originalRecipients.clear();
setText(text);
}
});
}
return null;
}
}
private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> {
@SuppressWarnings("unchecked")
@Override
protected Void doInBackground(Object... params) {
// For each chip in the list, look up the matching contact.
// If there is a match, replace that chip with the matching
// chip.
final ArrayList<RecipientChip> originalRecipients =
(ArrayList<RecipientChip>) params[0];
String[] addresses = new String[originalRecipients.size()];
RecipientChip chip;
for (int i = 0; i < originalRecipients.size(); i++) {
chip = originalRecipients.get(i);
if (chip != null) {
addresses[i] = createAddressText(chip.getEntry());
}
}
HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter
.getMatchingRecipients(getContext(), addresses);
for (final RecipientChip temp : originalRecipients) {
if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId())
&& getSpannable().getSpanStart(temp) != -1) {
// Replace this.
final RecipientEntry entry = createValidatedEntry(entries
.get(tokenizeAddress(temp.getEntry().getDestination()).toLowerCase()));
if (entry != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
replaceChip(temp, entry);
}
});
}
}
}
return null;
}
}
/**
* MoreImageSpan is a simple class created for tracking the existence of a
* more chip across activity restarts/
*/
private class MoreImageSpan extends ImageSpan {
public MoreImageSpan(Drawable b) {
super(b);
}
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// Do nothing.
return false;
}
@Override
public void onLongPress(MotionEvent event) {
if (mSelectedChip != null) {
return;
}
float x = event.getX();
float y = event.getY();
int offset = putOffsetInRange(getOffsetForPosition(x, y));
RecipientChip currentChip = findChip(offset);
if (currentChip != null) {
if (mDragEnabled) {
// Start drag-and-drop for the selected chip.
startDrag(currentChip);
} else {
// Copy the selected chip email address.
showCopyDialog(currentChip.getEntry().getDestination());
}
}
}
/**
* Enables drag-and-drop for chips.
*/
public void enableDrag() {
mDragEnabled = true;
}
/**
* Starts drag-and-drop for the selected chip.
*/
private void startDrag(RecipientChip currentChip) {
String address = currentChip.getEntry().getDestination();
ClipData data = ClipData.newPlainText(address, address + COMMIT_CHAR_COMMA);
// Start drag mode.
startDrag(data, new RecipientChipShadow(currentChip), null, 0);
// Remove the current chip, so drag-and-drop will result in a move.
// TODO (phamm): consider readd this chip if it's dropped outside a target.
removeChip(currentChip);
}
/**
* Handles drag event.
*/
@Override
public boolean onDragEvent(DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// Only handle plain text drag and drop.
return event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN);
case DragEvent.ACTION_DRAG_ENTERED:
requestFocus();
return true;
case DragEvent.ACTION_DROP:
handlePasteClip(event.getClipData());
return true;
}
return false;
}
/**
* Drag shadow for a {@link RecipientChip}.
*/
private final class RecipientChipShadow extends DragShadowBuilder {
private final RecipientChip mChip;
public RecipientChipShadow(RecipientChip chip) {
mChip = chip;
}
@Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
Rect rect = mChip.getDrawable().getBounds();
shadowSize.set(rect.width(), rect.height());
shadowTouchPoint.set(rect.centerX(), rect.centerY());
}
@Override
public void onDrawShadow(Canvas canvas) {
mChip.getDrawable().draw(canvas);
}
}
private void showCopyDialog(final String address) {
mCopyAddress = address;
mCopyDialog.setTitle(address);
mCopyDialog.setContentView(R.layout.copy_chip_dialog_layout);
mCopyDialog.setCancelable(true);
mCopyDialog.setCanceledOnTouchOutside(true);
Button button = (Button)mCopyDialog.findViewById(android.R.id.button1);
button.setOnClickListener(this);
int btnTitleId;
if (((BaseRecipientAdapter)getAdapter()).getQueryType() ==
BaseRecipientAdapter.QUERY_TYPE_PHONE) {
btnTitleId = R.string.copy_number;
} else {
btnTitleId = R.string.copy_email;
}
String buttonTitle = getContext().getResources().getString(btnTitleId);
button.setText(buttonTitle);
mCopyDialog.setOnDismissListener(this);
mCopyDialog.show();
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// Do nothing.
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// Do nothing.
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// Do nothing.
return false;
}
@Override
public void onDismiss(DialogInterface dialog) {
mCopyAddress = null;
}
@Override
public void onClick(View v) {
// Copy this to the clipboard.
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(
Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress));
mCopyDialog.dismiss();
}
}
|