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
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
|
/*
* Copyright 2000-2018 Vaadin Ltd.
*
* 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.vaadin.ui;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
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.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.vaadin.data.BeanPropertySet;
import com.vaadin.data.Binder;
import com.vaadin.data.Binder.Binding;
import com.vaadin.data.HasDataProvider;
import com.vaadin.data.HasValue;
import com.vaadin.data.PropertyDefinition;
import com.vaadin.data.PropertySet;
import com.vaadin.data.ValueProvider;
import com.vaadin.data.provider.CallbackDataProvider;
import com.vaadin.data.provider.DataCommunicator;
import com.vaadin.data.provider.DataGenerator;
import com.vaadin.data.provider.DataProvider;
import com.vaadin.data.provider.GridSortOrder;
import com.vaadin.data.provider.GridSortOrderBuilder;
import com.vaadin.data.provider.InMemoryDataProvider;
import com.vaadin.data.provider.Query;
import com.vaadin.data.provider.QuerySortOrder;
import com.vaadin.event.ConnectorEvent;
import com.vaadin.event.ContextClickEvent;
import com.vaadin.event.HasUserOriginated;
import com.vaadin.event.SortEvent;
import com.vaadin.event.SortEvent.SortListener;
import com.vaadin.event.SortEvent.SortNotifier;
import com.vaadin.event.selection.MultiSelectionListener;
import com.vaadin.event.selection.SelectionListener;
import com.vaadin.event.selection.SingleSelectionListener;
import com.vaadin.server.AbstractExtension;
import com.vaadin.server.EncodeResult;
import com.vaadin.server.Extension;
import com.vaadin.server.JsonCodec;
import com.vaadin.server.SerializableComparator;
import com.vaadin.server.SerializableSupplier;
import com.vaadin.server.Setter;
import com.vaadin.server.VaadinServiceClassLoaderUtil;
import com.vaadin.shared.Connector;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.Registration;
import com.vaadin.shared.data.DataCommunicatorConstants;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.shared.ui.grid.AbstractGridExtensionState;
import com.vaadin.shared.ui.grid.ColumnResizeMode;
import com.vaadin.shared.ui.grid.ColumnState;
import com.vaadin.shared.ui.grid.DetailsManagerState;
import com.vaadin.shared.ui.grid.GridClientRpc;
import com.vaadin.shared.ui.grid.GridConstants;
import com.vaadin.shared.ui.grid.GridConstants.Section;
import com.vaadin.shared.ui.grid.GridServerRpc;
import com.vaadin.shared.ui.grid.GridState;
import com.vaadin.shared.ui.grid.GridStaticCellType;
import com.vaadin.shared.ui.grid.HeightMode;
import com.vaadin.shared.ui.grid.ScrollDestination;
import com.vaadin.shared.ui.grid.SectionState;
import com.vaadin.ui.components.grid.ColumnReorderListener;
import com.vaadin.ui.components.grid.ColumnResizeListener;
import com.vaadin.ui.components.grid.ColumnVisibilityChangeListener;
import com.vaadin.ui.components.grid.DetailsGenerator;
import com.vaadin.ui.components.grid.Editor;
import com.vaadin.ui.components.grid.EditorImpl;
import com.vaadin.ui.components.grid.Footer;
import com.vaadin.ui.components.grid.FooterRow;
import com.vaadin.ui.components.grid.GridSelectionModel;
import com.vaadin.ui.components.grid.Header;
import com.vaadin.ui.components.grid.Header.Row;
import com.vaadin.ui.components.grid.HeaderCell;
import com.vaadin.ui.components.grid.HeaderRow;
import com.vaadin.ui.components.grid.ItemClickListener;
import com.vaadin.ui.components.grid.MultiSelectionModel;
import com.vaadin.ui.components.grid.MultiSelectionModelImpl;
import com.vaadin.ui.components.grid.NoSelectionModel;
import com.vaadin.ui.components.grid.SingleSelectionModel;
import com.vaadin.ui.components.grid.SingleSelectionModelImpl;
import com.vaadin.ui.components.grid.SortOrderProvider;
import com.vaadin.ui.declarative.DesignAttributeHandler;
import com.vaadin.ui.declarative.DesignContext;
import com.vaadin.ui.declarative.DesignException;
import com.vaadin.ui.declarative.DesignFormatter;
import com.vaadin.ui.renderers.AbstractRenderer;
import com.vaadin.ui.renderers.ComponentRenderer;
import com.vaadin.ui.renderers.HtmlRenderer;
import com.vaadin.ui.renderers.Renderer;
import com.vaadin.ui.renderers.TextRenderer;
import com.vaadin.util.ReflectTools;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
/**
* A grid component for displaying tabular data.
*
* @author Vaadin Ltd
* @since 8.0
*
* @param <T>
* the grid bean type
*/
public class Grid<T> extends AbstractListing<T> implements HasComponents,
HasDataProvider<T>, SortNotifier<GridSortOrder<T>> {
private static final String DECLARATIVE_DATA_ITEM_TYPE = "data-item-type";
/**
* A callback method for fetching items. The callback is provided with a
* list of sort orders, offset index and limit.
*
* @param <T>
* the grid bean type
*/
@FunctionalInterface
public interface FetchItemsCallback<T> extends Serializable {
/**
* Returns a stream of items ordered by given sort orders, limiting the
* results with given offset and limit.
* <p>
* This method is called after the size of the data set is asked from a
* related size callback. The offset and limit are promised to be within
* the size of the data set.
*
* @param sortOrder
* a list of sort orders
* @param offset
* the first index to fetch
* @param limit
* the fetched item count
* @return stream of items
*/
public Stream<T> fetchItems(List<QuerySortOrder> sortOrder, int offset,
int limit);
}
@Deprecated
private static final Method COLUMN_REORDER_METHOD = ReflectTools.findMethod(
ColumnReorderListener.class, "columnReorder",
ColumnReorderEvent.class);
private static final Method SORT_ORDER_CHANGE_METHOD = ReflectTools
.findMethod(SortListener.class, "sort", SortEvent.class);
@Deprecated
private static final Method COLUMN_RESIZE_METHOD = ReflectTools.findMethod(
ColumnResizeListener.class, "columnResize",
ColumnResizeEvent.class);
@Deprecated
private static final Method ITEM_CLICK_METHOD = ReflectTools
.findMethod(ItemClickListener.class, "itemClick", ItemClick.class);
@Deprecated
private static final Method COLUMN_VISIBILITY_METHOD = ReflectTools
.findMethod(ColumnVisibilityChangeListener.class,
"columnVisibilityChanged",
ColumnVisibilityChangeEvent.class);
/**
* Selection mode representing the built-in selection models in grid.
* <p>
* These enums can be used in {@link Grid#setSelectionMode(SelectionMode)}
* to easily switch between the build-in selection models.
*
* @see Grid#setSelectionMode(SelectionMode)
* @see Grid#setSelectionModel(GridSelectionModel)
*/
public enum SelectionMode {
/**
* Single selection mode that maps to build-in
* {@link SingleSelectionModel}.
*
* @see SingleSelectionModelImpl
*/
SINGLE {
@Override
protected <T> GridSelectionModel<T> createModel() {
return new SingleSelectionModelImpl<>();
}
},
/**
* Multiselection mode that maps to build-in {@link MultiSelectionModel}
* .
*
* @see MultiSelectionModelImpl
*/
MULTI {
@Override
protected <T> GridSelectionModel<T> createModel() {
return new MultiSelectionModelImpl<>();
}
},
/**
* Selection model that doesn't allow selection.
*
* @see NoSelectionModel
*/
NONE {
@Override
protected <T> GridSelectionModel<T> createModel() {
return new NoSelectionModel<>();
}
};
/**
* Creates the selection model to use with this enum.
*
* @param <T>
* the type of items in the grid
* @return the selection model
*/
protected abstract <T> GridSelectionModel<T> createModel();
}
/**
* An event that is fired when the columns are reordered.
*/
public static class ColumnReorderEvent extends Component.Event
implements HasUserOriginated {
private final boolean userOriginated;
/**
*
* @param source
* the grid where the event originated from
* @param userOriginated
* <code>true</code> if event is a result of user
* interaction, <code>false</code> if from API call
*/
public ColumnReorderEvent(Grid source, boolean userOriginated) {
super(source);
this.userOriginated = userOriginated;
}
/**
* Returns <code>true</code> if the column reorder was done by the user,
* <code>false</code> if not and it was triggered by server side code.
*
* @return <code>true</code> if event is a result of user interaction
*/
@Override
public boolean isUserOriginated() {
return userOriginated;
}
}
/**
* An event that is fired when a column is resized, either programmatically
* or by the user.
*/
public static class ColumnResizeEvent extends Component.Event
implements HasUserOriginated {
private final Column<?, ?> column;
private final boolean userOriginated;
/**
*
* @param source
* the grid where the event originated from
* @param userOriginated
* <code>true</code> if event is a result of user
* interaction, <code>false</code> if from API call
*/
public ColumnResizeEvent(Grid<?> source, Column<?, ?> column,
boolean userOriginated) {
super(source);
this.column = column;
this.userOriginated = userOriginated;
}
/**
* Returns the column that was resized.
*
* @return the resized column.
*/
public Column<?, ?> getColumn() {
return column;
}
/**
* Returns <code>true</code> if the column resize was done by the user,
* <code>false</code> if not and it was triggered by server side code.
*
* @return <code>true</code> if event is a result of user interaction
*/
@Override
public boolean isUserOriginated() {
return userOriginated;
}
}
/**
* An event fired when an item in the Grid has been clicked.
*
* @param <T>
* the grid bean type
*/
public static class ItemClick<T> extends ConnectorEvent {
private final T item;
private final Column<T, ?> column;
private final MouseEventDetails mouseEventDetails;
private final int rowIndex;
/**
* Creates a new {@code ItemClick} event containing the given item and
* Column originating from the given Grid.
*
*/
public ItemClick(Grid<T> source, Column<T, ?> column, T item,
MouseEventDetails mouseEventDetails, int rowIndex) {
super(source);
this.column = column;
this.item = item;
this.mouseEventDetails = mouseEventDetails;
this.rowIndex = rowIndex;
}
/**
* Returns the clicked item.
*
* @return the clicked item
*/
public T getItem() {
return item;
}
/**
* Returns the clicked column.
*
* @return the clicked column
*/
public Column<T, ?> getColumn() {
return column;
}
/**
* Returns the source Grid.
*
* @return the grid
*/
@Override
public Grid<T> getSource() {
return (Grid<T>) super.getSource();
}
/**
* Returns the mouse event details.
*
* @return the mouse event details
*/
public MouseEventDetails getMouseEventDetails() {
return mouseEventDetails;
}
/**
* Returns the clicked rowIndex.
*
* @return the clicked rowIndex
*/
public int getRowIndex() {
return rowIndex;
}
}
/**
* ContextClickEvent for the Grid Component.
*
* <p>
* Usage:
*
* <pre>
* grid.addContextClickListener(event -> Notification.show(
* ((GridContextClickEvent<Person>) event).getItem() + " Clicked"));
* </pre>
*
* @param <T>
* the grid bean type
*/
public static class GridContextClickEvent<T> extends ContextClickEvent {
private final T item;
private final int rowIndex;
private final Column<T, ?> column;
private final Section section;
/**
* Creates a new context click event.
*
* @param source
* the grid where the context click occurred
* @param mouseEventDetails
* details about mouse position
* @param section
* the section of the grid which was clicked
* @param rowIndex
* the index of the row which was clicked
* @param item
* the item which was clicked
* @param column
* the column which was clicked
*/
public GridContextClickEvent(Grid<T> source,
MouseEventDetails mouseEventDetails, Section section,
int rowIndex, T item, Column<T, ?> column) {
super(source, mouseEventDetails);
this.item = item;
this.section = section;
this.column = column;
this.rowIndex = rowIndex;
}
/**
* Returns the item of context clicked row.
*
* @return item of clicked row; <code>null</code> if header or footer
*/
public T getItem() {
return item;
}
/**
* Returns the clicked column.
*
* @return the clicked column
*/
public Column<T, ?> getColumn() {
return column;
}
/**
* Return the clicked section of Grid.
*
* @return section of grid
*/
public Section getSection() {
return section;
}
/**
* Returns the clicked row index.
* <p>
* Header and Footer rows for index can be fetched with
* {@link Grid#getHeaderRow(int)} and {@link Grid#getFooterRow(int)}.
*
* @return row index in section
*/
public int getRowIndex() {
return rowIndex;
}
@Override
public Grid<T> getComponent() {
return (Grid<T>) super.getComponent();
}
}
/**
* An event that is fired when a column's visibility changes.
*
* @since 7.5.0
*/
public static class ColumnVisibilityChangeEvent extends Component.Event
implements HasUserOriginated {
private final Column<?, ?> column;
private final boolean userOriginated;
private final boolean hidden;
/**
* Constructor for a column visibility change event.
*
* @param source
* the grid from which this event originates
* @param column
* the column that changed its visibility
* @param hidden
* <code>true</code> if the column was hidden,
* <code>false</code> if it became visible
* @param isUserOriginated
* <code>true</code> if the event was triggered by an UI
* interaction
*/
public ColumnVisibilityChangeEvent(Grid<?> source, Column<?, ?> column,
boolean hidden, boolean isUserOriginated) {
super(source);
this.column = column;
this.hidden = hidden;
userOriginated = isUserOriginated;
}
/**
* Gets the column that became hidden or visible.
*
* @return the column that became hidden or visible.
* @see Column#isHidden()
*/
public Column<?, ?> getColumn() {
return column;
}
/**
* Was the column set hidden or visible.
*
* @return <code>true</code> if the column was hidden <code>false</code>
* if it was set visible
*/
public boolean isHidden() {
return hidden;
}
@Override
public boolean isUserOriginated() {
return userOriginated;
}
}
/**
* A helper base class for creating extensions for the Grid component.
*
* @param <T>
*/
public abstract static class AbstractGridExtension<T>
extends AbstractListingExtension<T> {
@Override
public void extend(AbstractListing<T> grid) {
if (!(grid instanceof Grid)) {
throw new IllegalArgumentException(
getClass().getSimpleName() + " can only extend Grid");
}
super.extend(grid);
}
/**
* Adds given component to the connector hierarchy of Grid.
*
* @param c
* the component to add
*/
protected void addComponentToGrid(Component c) {
getParent().addExtensionComponent(c);
}
/**
* Removes given component from the connector hierarchy of Grid.
*
* @param c
* the component to remove
*/
protected void removeComponentFromGrid(Component c) {
getParent().removeExtensionComponent(c);
}
@Override
public Grid<T> getParent() {
return (Grid<T>) super.getParent();
}
@Override
protected AbstractGridExtensionState getState() {
return (AbstractGridExtensionState) super.getState();
}
@Override
protected AbstractGridExtensionState getState(boolean markAsDirty) {
return (AbstractGridExtensionState) super.getState(markAsDirty);
}
protected String getInternalIdForColumn(Column<T, ?> column) {
return getParent().getInternalIdForColumn(column);
}
}
private final class GridServerRpcImpl implements GridServerRpc {
@Override
public void sort(String[] columnInternalIds, SortDirection[] directions,
boolean isUserOriginated) {
assert columnInternalIds.length == directions.length : "Column and sort direction counts don't match.";
List<GridSortOrder<T>> list = new ArrayList<>(directions.length);
for (int i = 0; i < columnInternalIds.length; ++i) {
Column<T, ?> column = columnKeys.get(columnInternalIds[i]);
list.add(new GridSortOrder<>(column, directions[i]));
}
setSortOrder(list, isUserOriginated);
}
@Override
public void itemClick(String rowKey, String columnInternalId,
MouseEventDetails details, int rowIndex) {
Column<T, ?> column = getColumnByInternalId(columnInternalId);
T item = getDataCommunicator().getKeyMapper().get(rowKey);
fireEvent(new ItemClick<>(Grid.this, column, item, details, rowIndex));
}
@Override
public void contextClick(int rowIndex, String rowKey,
String columnInternalId, Section section,
MouseEventDetails details) {
T item = null;
if (rowKey != null) {
item = getDataCommunicator().getKeyMapper().get(rowKey);
}
fireEvent(new GridContextClickEvent<>(Grid.this, details, section,
rowIndex, item, getColumnByInternalId(columnInternalId)));
}
@Override
public void columnsReordered(List<String> newColumnOrder,
List<String> oldColumnOrder) {
final String diffStateKey = "columnOrder";
ConnectorTracker connectorTracker = getUI().getConnectorTracker();
JsonObject diffState = connectorTracker.getDiffState(Grid.this);
// discard the change if the columns have been reordered from
// the server side, as the server side is always right
if (getState(false).columnOrder.equals(oldColumnOrder)) {
// Don't mark as dirty since client has the state already
getState(false).columnOrder = newColumnOrder;
// write changes to diffState so that possible reverting the
// column order is sent to client
assert diffState
.hasKey(diffStateKey) : "Field name has changed";
Type type = null;
try {
type = getState(false).getClass().getField(diffStateKey)
.getGenericType();
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
EncodeResult encodeResult = JsonCodec.encode(
getState(false).columnOrder, diffState, type,
connectorTracker);
diffState.put(diffStateKey, encodeResult.getEncodedValue());
fireColumnReorderEvent(true);
} else {
// make sure the client is reverted to the order that the
// server thinks it is
diffState.remove(diffStateKey);
markAsDirty();
}
}
@Override
public void columnVisibilityChanged(String internalId, boolean hidden) {
Column<T, ?> column = getColumnByInternalId(internalId);
if (column.isHidden() != hidden) {
column.setHidden(hidden);
fireColumnVisibilityChangeEvent(column, hidden, true);
}
}
@Override
public void columnResized(String internalId, double pixels) {
final Column<T, ?> column = getColumnByInternalId(internalId);
if (column != null && column.isResizable()) {
column.getState().width = pixels;
fireColumnResizeEvent(column, true);
}
}
}
/**
* Class for managing visible details rows.
*
* @param <T>
* the grid bean type
*/
public static class DetailsManager<T> extends AbstractGridExtension<T> {
private final Set<T> visibleDetails = new HashSet<>();
private final Map<T, Component> components = new HashMap<>();
private DetailsGenerator<T> generator;
/**
* Sets the details component generator.
*
* @param generator
* the generator for details components
*/
public void setDetailsGenerator(DetailsGenerator<T> generator) {
if (this.generator != generator) {
removeAllComponents();
}
this.generator = generator;
visibleDetails.forEach(this::refresh);
}
@Override
public void remove() {
removeAllComponents();
super.remove();
}
private void removeAllComponents() {
// Clean up old components
components.values().forEach(this::removeComponentFromGrid);
components.clear();
}
@Override
public void generateData(T item, JsonObject jsonObject) {
if (generator == null || !visibleDetails.contains(item)) {
return;
}
if (!components.containsKey(item)) {
Component detailsComponent = generator.apply(item);
Objects.requireNonNull(detailsComponent,
"Details generator can't create null components");
if (detailsComponent.getParent() != null) {
throw new IllegalStateException(
"Details component was already attached");
}
addComponentToGrid(detailsComponent);
components.put(item, detailsComponent);
}
jsonObject.put(GridState.JSONKEY_DETAILS_VISIBLE,
components.get(item).getConnectorId());
}
@Override
public void destroyData(T item) {
// No clean up needed. Components are removed when hiding details
// and/or changing details generator
}
/**
* Sets the visibility of details component for given item.
*
* @param item
* the item to show details for
* @param visible
* {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public void setDetailsVisible(T item, boolean visible) {
boolean refresh = false;
if (!visible) {
refresh = visibleDetails.remove(item);
if (components.containsKey(item)) {
removeComponentFromGrid(components.remove(item));
}
} else {
refresh = visibleDetails.add(item);
}
if (refresh) {
refresh(item);
}
}
/**
* Returns the visibility of details component for given item.
*
* @param item
* the item to show details for
*
* @return {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public boolean isDetailsVisible(T item) {
return visibleDetails.contains(item);
}
@Override
public Grid<T> getParent() {
return super.getParent();
}
@Override
protected DetailsManagerState getState() {
return (DetailsManagerState) super.getState();
}
@Override
protected DetailsManagerState getState(boolean markAsDirty) {
return (DetailsManagerState) super.getState(markAsDirty);
}
}
/**
* This extension manages the configuration and data communication for a
* Column inside of a Grid component.
*
* @param <T>
* the grid bean type
* @param <V>
* the column value type
*/
public static class Column<T, V> extends AbstractExtension {
private final ValueProvider<T, V> valueProvider;
private ValueProvider<V, ?> presentationProvider;
private SortOrderProvider sortOrderProvider = direction -> {
String id = getId();
if (id == null) {
return Stream.empty();
}
return Stream.of(new QuerySortOrder(id, direction));
};
private boolean sortable = true;
private SerializableComparator<T> comparator;
private StyleGenerator<T> styleGenerator = item -> null;
private DescriptionGenerator<T> descriptionGenerator;
private DataGenerator<T> dataGenerator = new DataGenerator<T>() {
@Override
public void generateData(T item, JsonObject jsonObject) {
ColumnState state = getState(false);
String communicationId = getConnectorId();
assert communicationId != null : "No communication ID set for column "
+ state.caption;
JsonObject obj = getDataObject(jsonObject,
DataCommunicatorConstants.DATA);
obj.put(communicationId, generateRendererValue(item,
presentationProvider, state.renderer));
String style = styleGenerator.apply(item);
if (style != null && !style.isEmpty()) {
JsonObject styleObj = getDataObject(jsonObject,
GridState.JSONKEY_CELLSTYLES);
styleObj.put(communicationId, style);
}
if (descriptionGenerator != null) {
String description = descriptionGenerator.apply(item);
if (description != null && !description.isEmpty()) {
JsonObject descriptionObj = getDataObject(jsonObject,
GridState.JSONKEY_CELLDESCRIPTION);
descriptionObj.put(communicationId, description);
}
}
}
@Override
public void destroyData(T item) {
removeComponent(getGrid().getDataProvider().getId(item));
}
@Override
public void destroyAllData() {
// Make a defensive copy of keys, as the map gets cleared when
// removing components.
new HashSet<>(activeComponents.keySet())
.forEach(component -> removeComponent(component));
}
};
private Binding<T, ?> editorBinding;
private Map<Object, Component> activeComponents = new HashMap<>();
private String userId;
/**
* Constructs a new Column configuration with given renderer and value
* provider.
*
* @param valueProvider
* the function to get values from items, not
* <code>null</code>
* @param renderer
* the value renderer, not <code>null</code>
*/
protected Column(ValueProvider<T, V> valueProvider,
Renderer<? super V> renderer) {
this(valueProvider, ValueProvider.identity(), renderer);
}
/**
* Constructs a new Column configuration with given renderer and value
* provider.
* <p>
* For a more complete explanation on presentation provider, see
* {@link #setRenderer(ValueProvider, Renderer)}.
*
* @param valueProvider
* the function to get values from items, not
* <code>null</code>
* @param presentationProvider
* the function to get presentations from the value of this
* column, not <code>null</code>. For more details, see
* {@link #setRenderer(ValueProvider, Renderer)}
* @param renderer
* the presentation renderer, not <code>null</code>
* @param <P>
* the presentation type
*
* @since 8.1
*/
protected <P> Column(ValueProvider<T, V> valueProvider,
ValueProvider<V, P> presentationProvider,
Renderer<? super P> renderer) {
Objects.requireNonNull(valueProvider,
"Value provider can't be null");
Objects.requireNonNull(presentationProvider,
"Presentation provider can't be null");
Objects.requireNonNull(renderer, "Renderer can't be null");
ColumnState state = getState();
this.valueProvider = valueProvider;
this.presentationProvider = presentationProvider;
state.renderer = renderer;
state.caption = "";
// Add the renderer as a child extension of this extension, thus
// ensuring the renderer will be unregistered when this column is
// removed
addExtension(renderer);
Class<? super P> valueType = renderer.getPresentationType();
if (Comparable.class.isAssignableFrom(valueType)) {
comparator = (a, b) -> compareComparables(
valueProvider.apply(a), valueProvider.apply(b));
} else if (Number.class.isAssignableFrom(valueType)) {
/*
* Value type will be Number whenever using NumberRenderer.
* Provide explicit comparison support in this case even though
* Number itself isn't Comparable.
*/
comparator = (a, b) -> compareNumbers(
(Number) valueProvider.apply(a),
(Number) valueProvider.apply(b));
} else {
comparator = (a, b) -> compareMaybeComparables(
valueProvider.apply(a), valueProvider.apply(b));
}
}
private static int compareMaybeComparables(Object a, Object b) {
if (hasCommonComparableBaseType(a, b)) {
return compareComparables(a, b);
}
return compareComparables(Objects.toString(a, ""),
Objects.toString(b, ""));
}
private static boolean hasCommonComparableBaseType(Object a, Object b) {
if (a instanceof Comparable<?> && b instanceof Comparable<?>) {
Class<?> aClass = a.getClass();
Class<?> bClass = b.getClass();
if (aClass == bClass) {
return true;
}
Class<?> baseType = ReflectTools.findCommonBaseType(aClass,
bClass);
if (Comparable.class.isAssignableFrom(baseType)) {
return true;
}
}
if ((a == null && b instanceof Comparable<?>)
|| (b == null && a instanceof Comparable<?>)) {
return true;
}
return false;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static int compareComparables(Object a, Object b) {
return ((Comparator) Comparator
.nullsLast(Comparator.naturalOrder())).compare(a, b);
}
@SuppressWarnings("unchecked")
private static int compareNumbers(Number a, Number b) {
Number valueA = a != null ? a : Double.POSITIVE_INFINITY;
Number valueB = b != null ? b : Double.POSITIVE_INFINITY;
// Most Number implementations are Comparable
if (valueA instanceof Comparable
&& valueA.getClass().isInstance(valueB)) {
return ((Comparable<Number>) valueA).compareTo(valueB);
}
if (valueA.equals(valueB)) {
return 0;
}
// Fall back to comparing based on potentially truncated values
int compare = Long.compare(valueA.longValue(), valueB.longValue());
if (compare == 0) {
// This might still produce 0 even though the values are not
// equals, but there's nothing more we can do about that
compare = Double.compare(valueA.doubleValue(),
valueB.doubleValue());
}
return compare;
}
@SuppressWarnings("unchecked")
private <P> JsonValue generateRendererValue(T item,
ValueProvider<V, P> presentationProvider, Connector renderer) {
P presentationValue = presentationProvider
.apply(valueProvider.apply(item));
// Make Grid track components.
if (renderer instanceof ComponentRenderer
&& presentationValue instanceof Component) {
addComponent(getGrid().getDataProvider().getId(item),
(Component) presentationValue);
}
return ((Renderer<P>) renderer).encode(presentationValue);
}
private void addComponent(Object item, Component component) {
if (activeComponents.containsKey(item)) {
if (activeComponents.get(item).equals(component)) {
// Reusing old component
return;
}
removeComponent(item);
}
activeComponents.put(item, component);
getGrid().addExtensionComponent(component);
}
private void removeComponent(Object item) {
Component component = activeComponents.remove(item);
if (component != null) {
getGrid().removeExtensionComponent(component);
}
}
/**
* Gets a data object with the given key from the given JsonObject. If
* there is no object with the key, this method creates a new
* JsonObject.
*
* @param jsonObject
* the json object
* @param key
* the key where the desired data object is stored
* @return data object for the given key
*/
private JsonObject getDataObject(JsonObject jsonObject, String key) {
if (!jsonObject.hasKey(key)) {
jsonObject.put(key, Json.createObject());
}
return jsonObject.getObject(key);
}
@Override
protected ColumnState getState() {
return getState(true);
}
@Override
protected ColumnState getState(boolean markAsDirty) {
return (ColumnState) super.getState(markAsDirty);
}
/**
* This method extends the given Grid with this Column.
*
* @param grid
* the grid to extend
*/
private void extend(Grid<T> grid) {
super.extend(grid);
}
/**
* Returns the identifier used with this Column in communication.
*
* @return the identifier string
*/
private String getInternalId() {
return getState(false).internalId;
}
/**
* Sets the identifier to use with this Column in communication.
*
* @param id
* the identifier string
*/
private void setInternalId(String id) {
Objects.requireNonNull(id, "Communication ID can't be null");
getState().internalId = id;
}
/**
* Returns the user-defined identifier for this column.
*
* @return the identifier string
*/
public String getId() {
return userId;
}
/**
* Sets the user-defined identifier to map this column. The identifier
* can be used for example in {@link Grid#getColumn(String)}.
* <p>
* The id is also used as the {@link #setSortProperty(String...) backend
* sort property} for this column if no sort property or sort order
* provider has been set for this column.
*
* @see #setSortProperty(String...)
* @see #setSortOrderProvider(SortOrderProvider)
*
* @param id
* the identifier string
* @return this column
*/
public Column<T, V> setId(String id) {
Objects.requireNonNull(id, "Column identifier cannot be null");
if (userId != null) {
throw new IllegalStateException(
"Column identifier cannot be changed");
}
userId = id;
getGrid().setColumnId(id, this);
updateSortable();
return this;
}
private void updateSortable() {
boolean inMemory = getGrid().getDataProvider().isInMemory();
boolean hasSortOrder = getSortOrder(SortDirection.ASCENDING)
.count() != 0;
getState().sortable = this.sortable && (inMemory || hasSortOrder);
}
/**
* Gets the function used to produce the value for data in this column
* based on the row item.
*
* @return the value provider function
*
* @since 8.0.3
*/
public ValueProvider<T, V> getValueProvider() {
return valueProvider;
}
/**
* Sets whether the user can sort this column or not. Whether the column
* is actually sortable after {@code setSortable(true)} depends on the
* {@link DataProvider} and the defined sort order for this column. When
* using an {@link InMemoryDataProvider} sorting can be automatic.
*
* @param sortable
* {@code true} to enable sorting for this column;
* {@code false} to disable it
* @return this column
*/
public Column<T, V> setSortable(boolean sortable) {
if (this.sortable != sortable) {
this.sortable = sortable;
updateSortable();
}
return this;
}
/**
* Gets whether sorting is enabled for this column.
*
* @return {@code true} if the sorting is enabled for this column;
* {@code false} if not
*/
public boolean isSortable() {
return sortable;
}
/**
* Gets whether the user can actually sort this column.
*
* @return {@code true} if the column can be sorted by the user;
* {@code false} if not
*
* @since 8.3.2
*/
public boolean isSortableByUser() {
return getState(false).sortable;
}
/**
* Sets the header aria-label for this column.
*
* @param caption
* the header aria-label, null removes the aria-label from
* this column
*
* @return this column
*
* @since 8.2
*/
public Column<T, V> setAssistiveCaption(String caption) {
if (Objects.equals(caption, getAssistiveCaption())) {
return this;
}
getState().assistiveCaption = caption;
return this;
}
/**
* Gets the header caption for this column.
*
* @return header caption
*
* @since 8.2
*/
public String getAssistiveCaption() {
return getState(false).assistiveCaption;
}
/**
* Sets the header caption for this column.
*
* @param caption
* the header caption, not null
*
* @return this column
*/
public Column<T, V> setCaption(String caption) {
Objects.requireNonNull(caption, "Header caption can't be null");
if (caption.equals(getState(false).caption)) {
return this;
}
getState().caption = caption;
HeaderRow row = getGrid().getDefaultHeaderRow();
if (row != null) {
row.getCell(this).setText(caption);
}
return this;
}
/**
* Gets the header caption for this column.
*
* @return header caption
*/
public String getCaption() {
return getState(false).caption;
}
/**
* Sets a comparator to use with in-memory sorting with this column.
* Sorting with a back-end is done using
* {@link Column#setSortProperty(String...)}.
*
* @param comparator
* the comparator to use when sorting data in this column
* @return this column
*/
public Column<T, V> setComparator(
SerializableComparator<T> comparator) {
Objects.requireNonNull(comparator, "Comparator can't be null");
this.comparator = comparator;
return this;
}
/**
* Gets the comparator to use with in-memory sorting for this column
* when sorting in the given direction.
*
* @param sortDirection
* the direction this column is sorted by
* @return comparator for this column
*/
public SerializableComparator<T> getComparator(
SortDirection sortDirection) {
Objects.requireNonNull(comparator,
"No comparator defined for sorted column.");
boolean reverse = sortDirection != SortDirection.ASCENDING;
return reverse ? (t1, t2) -> comparator.reversed().compare(t1, t2)
: comparator;
}
/**
* Sets strings describing back end properties to be used when sorting
* this column.
* <p>
* By default, the {@link #setId(String) column id} will be used as the
* sort property.
*
* @param properties
* the array of strings describing backend properties
* @return this column
*/
public Column<T, V> setSortProperty(String... properties) {
Objects.requireNonNull(properties, "Sort properties can't be null");
sortOrderProvider = dir -> Arrays.stream(properties)
.map(s -> new QuerySortOrder(s, dir));
return this;
}
/**
* Sets the sort orders when sorting this column. The sort order
* provider is a function which provides {@link QuerySortOrder} objects
* to describe how to sort by this column.
* <p>
* By default, the {@link #setId(String) column id} will be used as the
* sort property.
*
* @param provider
* the function to use when generating sort orders with the
* given direction
* @return this column
*/
public Column<T, V> setSortOrderProvider(SortOrderProvider provider) {
Objects.requireNonNull(provider,
"Sort order provider can't be null");
sortOrderProvider = provider;
return this;
}
/**
* Gets the sort orders to use with back-end sorting for this column
* when sorting in the given direction.
*
* @see #setSortProperty(String...)
* @see #setId(String)
* @see #setSortOrderProvider(SortOrderProvider)
*
* @param direction
* the sorting direction
* @return stream of sort orders
*/
public Stream<QuerySortOrder> getSortOrder(SortDirection direction) {
return sortOrderProvider.apply(direction);
}
/**
* Sets the style generator that is used for generating class names for
* cells in this column. Returning null from the generator results in no
* custom style name being set.
*
* @param cellStyleGenerator
* the cell style generator to set, not null
* @return this column
* @throws NullPointerException
* if {@code cellStyleGenerator} is {@code null}
*/
public Column<T, V> setStyleGenerator(
StyleGenerator<T> cellStyleGenerator) {
Objects.requireNonNull(cellStyleGenerator,
"Cell style generator must not be null");
this.styleGenerator = cellStyleGenerator;
getGrid().getDataCommunicator().reset();
return this;
}
/**
* Gets the style generator that is used for generating styles for
* cells.
*
* @return the cell style generator
*/
public StyleGenerator<T> getStyleGenerator() {
return styleGenerator;
}
/**
* Sets the description generator that is used for generating
* descriptions for cells in this column. This method uses the
* {@link ContentMode#PREFORMATTED} content mode.
*
* @see #setDescriptionGenerator(DescriptionGenerator, ContentMode)
*
* @param cellDescriptionGenerator
* the cell description generator to set, or {@code null} to
* remove a previously set generator
* @return this column
*/
public Column<T, V> setDescriptionGenerator(
DescriptionGenerator<T> cellDescriptionGenerator) {
return setDescriptionGenerator(cellDescriptionGenerator,
ContentMode.PREFORMATTED);
}
/**
* Sets the description generator that is used for generating
* descriptions for cells in this column. This method uses the given
* content mode.
*
* @see #setDescriptionGenerator(DescriptionGenerator)
*
* @param cellDescriptionGenerator
* the cell description generator to set, or {@code null} to
* remove a previously set generator
* @param tooltipContentMode
* the content mode for tooltips
* @return this column
*
* @since 8.2
*/
public Column<T, V> setDescriptionGenerator(
DescriptionGenerator<T> cellDescriptionGenerator,
ContentMode tooltipContentMode) {
this.descriptionGenerator = cellDescriptionGenerator;
getState().tooltipContentMode = tooltipContentMode;
getGrid().getDataCommunicator().reset();
return this;
}
/**
* Gets the description generator that is used for generating
* descriptions for cells.
*
* @return the cell description generator, or <code>null</code> if no
* generator is set
*/
public DescriptionGenerator<T> getDescriptionGenerator() {
return descriptionGenerator;
}
/**
* Sets the ratio with which the column expands.
* <p>
* By default, all columns expand equally (treated as if all of them had
* an expand ratio of 1). Once at least one column gets a defined expand
* ratio, the implicit expand ratio is removed, and only the defined
* expand ratios are taken into account.
* <p>
* If a column has a defined width ({@link #setWidth(double)}), it
* overrides this method's effects.
* <p>
* <em>Example:</em> A grid with three columns, with expand ratios 0, 1
* and 2, respectively. The column with a <strong>ratio of 0 is exactly
* as wide as its contents requires</strong>. The column with a ratio of
* 1 is as wide as it needs, <strong>plus a third of any excess
* space</strong>, because we have 3 parts total, and this column
* reserves only one of those. The column with a ratio of 2, is as wide
* as it needs to be, <strong>plus two thirds</strong> of the excess
* width.
*
* @param expandRatio
* the expand ratio of this column. {@code 0} to not have it
* expand at all. A negative number to clear the expand
* value.
* @throws IllegalStateException
* if the column is no longer attached to any grid
* @see #setWidth(double)
*/
public Column<T, V> setExpandRatio(int expandRatio)
throws IllegalStateException {
checkColumnIsAttached();
if (expandRatio != getExpandRatio()) {
getState().expandRatio = expandRatio;
getGrid().markAsDirty();
}
return this;
}
/**
* Returns the column's expand ratio.
*
* @return the column's expand ratio
* @see #setExpandRatio(int)
*/
public int getExpandRatio() {
return getState(false).expandRatio;
}
/**
* Clears the expand ratio for this column.
* <p>
* Equal to calling {@link #setExpandRatio(int) setExpandRatio(-1)}
*
* @throws IllegalStateException
* if the column is no longer attached to any grid
*/
public Column<T, V> clearExpandRatio() throws IllegalStateException {
return setExpandRatio(-1);
}
/**
* Returns the width (in pixels). By default a column is 100px wide.
*
* @return the width in pixels of the column
* @throws IllegalStateException
* if the column is no longer attached to any grid
*/
public double getWidth() throws IllegalStateException {
checkColumnIsAttached();
return getState(false).width;
}
/**
* Sets the width (in pixels).
* <p>
* This overrides any configuration set by any of
* {@link #setExpandRatio(int)}, {@link #setMinimumWidth(double)} or
* {@link #setMaximumWidth(double)}.
*
* @param pixelWidth
* the new pixel width of the column
* @return the column itself
*
* @throws IllegalStateException
* if the column is no longer attached to any grid
* @throws IllegalArgumentException
* thrown if pixel width is less than zero
*/
public Column<T, V> setWidth(double pixelWidth)
throws IllegalStateException, IllegalArgumentException {
checkColumnIsAttached();
if (pixelWidth < 0) {
throw new IllegalArgumentException(
"Pixel width should be greated than 0 (in " + toString()
+ ")");
}
if (pixelWidth != getWidth()) {
getState().width = pixelWidth;
getGrid().markAsDirty();
getGrid().fireColumnResizeEvent(this, false);
}
return this;
}
/**
* Returns whether this column has an undefined width.
*
* @since 7.6
* @return whether the width is undefined
* @throws IllegalStateException
* if the column is no longer attached to any grid
*/
public boolean isWidthUndefined() {
checkColumnIsAttached();
return getState(false).width < 0;
}
/**
* Marks the column width as undefined. An undefined width means the
* grid is free to resize the column based on the cell contents and
* available space in the grid.
*
* @return the column itself
*/
public Column<T, V> setWidthUndefined() {
checkColumnIsAttached();
if (!isWidthUndefined()) {
getState().width = -1;
getGrid().markAsDirty();
getGrid().fireColumnResizeEvent(this, false);
}
return this;
}
/**
* Sets the minimum width for this column.
* <p>
* This defines the minimum guaranteed pixel width of the column
* <em>when it is set to expand</em>.
*
* @param pixels
* the minimum width for the column
* @throws IllegalStateException
* if the column is no longer attached to any grid
* @see #setExpandRatio(int)
* @return the column itself
*/
public Column<T, V> setMinimumWidth(double pixels)
throws IllegalStateException {
checkColumnIsAttached();
final double maxwidth = getMaximumWidth();
if (pixels >= 0 && pixels > maxwidth && maxwidth >= 0) {
throw new IllegalArgumentException("New minimum width ("
+ pixels + ") was greater than maximum width ("
+ maxwidth + ")");
}
getState().minWidth = pixels;
getGrid().markAsDirty();
return this;
}
/**
* Return the minimum width for this column.
*
* @return the minimum width for this column
* @see #setMinimumWidth(double)
*/
public double getMinimumWidth() {
return getState(false).minWidth;
}
/**
* Sets whether the width of the contents in the column should be
* considered minimum width for this column.
* <p>
* If this is set to <code>true</code> (default for backwards
* compatibility), then a column will not shrink to smaller than the
* width required to show the contents available when calculating the
* widths (only the widths of the initially rendered rows are
* considered).
* <p>
* If this is set to <code>false</code> and the column has been set to
* expand using #setExpandRatio(int), then the contents of the column
* will be ignored when calculating the width, and the column will thus
* shrink down to the minimum width defined by #setMinimumWidth(double)
* if necessary.
*
* @param minimumWidthFromContent
* <code>true</code> to reserve space for all contents,
* <code>false</code> to allow the column to shrink smaller
* than the contents
* @return the column itself
* @throws IllegalStateException
* if the column is no longer attached to any grid
* @see #setMinimumWidth(double)
* @since 8.1
*/
public Column<T, V> setMinimumWidthFromContent(
boolean minimumWidthFromContent) throws IllegalStateException {
checkColumnIsAttached();
if (isMinimumWidthFromContent() != minimumWidthFromContent) {
getState().minimumWidthFromContent = minimumWidthFromContent;
getGrid().markAsDirty();
}
return this;
}
/**
* Gets whether the width of the contents in the column should be
* considered minimum width for this column.
*
* @return <code>true</code> to reserve space for all contents,
* <code>false</code> to allow the column to shrink smaller than
* the contents
* @see #setMinimumWidthFromContent(boolean)
* @since 8.1
*/
public boolean isMinimumWidthFromContent() {
return getState(false).minimumWidthFromContent;
}
/**
* Sets the maximum width for this column.
* <p>
* This defines the maximum allowed pixel width of the column <em>when
* it is set to expand</em>.
*
* @param pixels
* the maximum width
* @throws IllegalStateException
* if the column is no longer attached to any grid
* @see #setExpandRatio(int)
*/
public Column<T, V> setMaximumWidth(double pixels) {
checkColumnIsAttached();
final double minwidth = getMinimumWidth();
if (pixels >= 0 && pixels < minwidth && minwidth >= 0) {
throw new IllegalArgumentException("New maximum width ("
+ pixels + ") was less than minimum width (" + minwidth
+ ")");
}
getState().maxWidth = pixels;
getGrid().markAsDirty();
return this;
}
/**
* Returns the maximum width for this column.
*
* @return the maximum width for this column
* @see #setMaximumWidth(double)
*/
public double getMaximumWidth() {
return getState(false).maxWidth;
}
/**
* Sets whether this column can be resized by the user.
*
* @since 7.6
* @param resizable
* {@code true} if this column should be resizable,
* {@code false} otherwise
* @throws IllegalStateException
* if the column is no longer attached to any grid
*/
public Column<T, V> setResizable(boolean resizable) {
checkColumnIsAttached();
if (resizable != isResizable()) {
getState().resizable = resizable;
getGrid().markAsDirty();
}
return this;
}
/**
* Gets the caption of the hiding toggle for this column.
*
* @since 7.5.0
* @see #setHidingToggleCaption(String)
* @return the caption for the hiding toggle for this column
*/
public String getHidingToggleCaption() {
return getState(false).hidingToggleCaption;
}
/**
* Sets the caption of the hiding toggle for this column. Shown in the
* toggle for this column in the grid's sidebar when the column is
* {@link #isHidable() hidable}.
* <p>
* The default value is <code>null</code>, and in that case the column's
* {@link #getCaption() header caption} is used.
* <p>
* <em>NOTE:</em> setting this to empty string might cause the hiding
* toggle to not render correctly.
*
* @since 7.5.0
* @param hidingToggleCaption
* the text to show in the column hiding toggle
* @return the column itself
*/
public Column<T, V> setHidingToggleCaption(String hidingToggleCaption) {
if (hidingToggleCaption != getHidingToggleCaption()) {
getState().hidingToggleCaption = hidingToggleCaption;
}
return this;
}
/**
* Hides or shows the column. By default columns are visible before
* explicitly hiding them.
*
* @since 7.5.0
* @param hidden
* <code>true</code> to hide the column, <code>false</code>
* to show
* @return this column
* @throws IllegalStateException
* if the column is no longer attached to any grid
*/
public Column<T, V> setHidden(boolean hidden) {
checkColumnIsAttached();
if (hidden != isHidden()) {
getState().hidden = hidden;
getGrid().fireColumnVisibilityChangeEvent(this, hidden, false);
}
return this;
}
/**
* Returns whether this column is hidden. Default is {@code false}.
*
* @since 7.5.0
* @return <code>true</code> if the column is currently hidden,
* <code>false</code> otherwise
*/
public boolean isHidden() {
return getState(false).hidden;
}
/**
* Sets whether this column can be hidden by the user. Hidable columns
* can be hidden and shown via the sidebar menu.
*
* @since 7.5.0
* @param hidable
* <code>true</code> if the column may be hidable by the user
* via UI interaction
* @return this column
*/
public Column<T, V> setHidable(boolean hidable) {
if (hidable != isHidable()) {
getState().hidable = hidable;
}
return this;
}
/**
* Returns whether this column can be hidden by the user. Default is
* {@code false}.
* <p>
* <em>Note:</em> the column can be programmatically hidden using
* {@link #setHidden(boolean)} regardless of the returned value.
*
* @since 7.5.0
* @return <code>true</code> if the user can hide the column,
* <code>false</code> if not
*/
public boolean isHidable() {
return getState(false).hidable;
}
/**
* Returns whether this column can be resized by the user. Default is
* {@code true}.
* <p>
* <em>Note:</em> the column can be programmatically resized using
* {@link #setWidth(double)} and {@link #setWidthUndefined()} regardless
* of the returned value.
*
* @since 7.6
* @return {@code true} if this column is resizable, {@code false}
* otherwise
*/
public boolean isResizable() {
return getState(false).resizable;
}
/**
* Sets whether this Column has a component displayed in Editor or not.
* A column can only be editable if an editor component or binding has
* been set.
*
* @param editable
* {@code true} if column is editable; {@code false} if not
* @return this column
*
* @see #setEditorComponent(HasValue, Setter)
* @see #setEditorBinding(Binding)
*/
public Column<T, V> setEditable(boolean editable) {
Objects.requireNonNull(editorBinding,
"Column has no editor binding or component defined");
getState().editable = editable;
return this;
}
/**
* Gets whether this Column has a component displayed in Editor or not.
*
* @return {@code true} if the column displays an editor component;
* {@code false} if not
*/
public boolean isEditable() {
return getState(false).editable;
}
/**
* Sets an editor binding for this column. The {@link Binding} is used
* when a row is in editor mode to define how to populate an editor
* component based on the edited row and how to update an item based on
* the value in the editor component.
* <p>
* To create a binding to use with a column, define a binding for the
* editor binder (<code>grid.getEditor().getBinder()</code>) using e.g.
* {@link Binder#forField(HasValue)}. You can also use
* {@link #setEditorComponent(HasValue, Setter)} if no validator or
* converter is needed for the binding.
* <p>
* The {@link HasValue} that the binding is defined to use must be a
* {@link Component}.
*
* @param binding
* the binding to use for this column
* @return this column
*
* @see #setEditorComponent(HasValue, Setter)
* @see Binding
* @see Grid#getEditor()
* @see Editor#getBinder()
*/
public Column<T, V> setEditorBinding(Binding<T, ?> binding) {
Objects.requireNonNull(binding, "null is not a valid editor field");
if (!(binding.getField() instanceof Component)) {
throw new IllegalArgumentException(
"Binding target must be a component.");
}
this.editorBinding = binding;
return setEditable(true);
}
/**
* Gets the binder binding that is currently used for this column.
*
* @return the used binder binding, or <code>null</code> if no binding
* is configured
*
* @see #setEditorBinding(Binding)
*/
public Binding<T, ?> getEditorBinding() {
return editorBinding;
}
/**
* Sets a component and setter to use for editing values of this column
* in the editor row. This is a shorthand for use in simple cases where
* no validator or converter is needed. Use
* {@link #setEditorBinding(Binding)} to support more complex cases.
* <p>
* <strong>Note:</strong> The same component cannot be used for multiple
* columns.
*
* @param editorComponent
* the editor component
* @param setter
* a setter that stores the component value in the row item
* @return this column
*
* @see #setEditorBinding(Binding)
* @see Grid#getEditor()
* @see Binder#bind(HasValue, ValueProvider, Setter)
*/
public <C extends HasValue<V> & Component> Column<T, V> setEditorComponent(
C editorComponent, Setter<T, V> setter) {
Objects.requireNonNull(editorComponent,
"Editor component cannot be null");
Objects.requireNonNull(setter, "Setter cannot be null");
Binding<T, V> binding = getGrid().getEditor().getBinder()
.bind(editorComponent, valueProvider::apply, setter);
return setEditorBinding(binding);
}
/**
* Sets a component to use for editing values of this columns in the
* editor row. This method can only be used if the column has an
* {@link #setId(String) id} and the {@link Grid} has been created using
* {@link Grid#Grid(Class)} or some other way that allows finding
* properties based on property names.
* <p>
* This is a shorthand for use in simple cases where no validator or
* converter is needed. Use {@link #setEditorBinding(Binding)} to
* support more complex cases.
* <p>
* <strong>Note:</strong> The same component cannot be used for multiple
* columns.
*
* @param editorComponent
* the editor component
* @return this column
*
* @see #setEditorBinding(Binding)
* @see Grid#getEditor()
* @see Binder#bind(HasValue, String)
* @see Grid#Grid(Class)
*/
public <F, C extends HasValue<F> & Component> Column<T, V> setEditorComponent(
C editorComponent) {
Objects.requireNonNull(editorComponent,
"Editor component cannot be null");
String propertyName = getId();
if (propertyName == null) {
throw new IllegalStateException(
"setEditorComponent without a setter can only be used if the column has an id. "
+ "Use another setEditorComponent(Component, Setter) or setEditorBinding(Binding) instead.");
}
Binding<T, F> binding = getGrid().getEditor().getBinder()
.bind(editorComponent, propertyName);
return setEditorBinding(binding);
}
/**
* Sets the Renderer for this Column. Setting the renderer will cause
* all currently available row data to be recreated and sent to the
* client.
*
* @param renderer
* the new renderer
* @return this column
*
* @since 8.0.3
*/
public Column<T, V> setRenderer(Renderer<? super V> renderer) {
return setRenderer(ValueProvider.identity(), renderer);
}
/**
* Sets the Renderer for this Column. Setting the renderer will cause
* all currently available row data to be recreated and sent to the
* client.
* <p>
* The presentation provider is a method that takes the value of this
* column on a single row, and maps that to a value that the renderer
* accepts. This feature can be used for storing a complex value in a
* column for editing, but providing a simplified presentation for the
* user when not editing.
*
* @param presentationProvider
* the function to get presentations from the value of this
* column, not {@code null}
* @param renderer
* the new renderer, not {@code null}
*
* @param <P>
* the presentation type
*
* @return this column
*
* @since 8.1
*/
public <P> Column<T, V> setRenderer(
ValueProvider<V, P> presentationProvider,
Renderer<? super P> renderer) {
Objects.requireNonNull(renderer, "Renderer can not be null");
Objects.requireNonNull(presentationProvider,
"Presentation provider can not be null");
// Remove old renderer
Connector oldRenderer = getState().renderer;
if (oldRenderer instanceof Extension) {
removeExtension((Extension) oldRenderer);
}
// Set new renderer
getState().renderer = renderer;
addExtension(renderer);
this.presentationProvider = presentationProvider;
// Trigger redraw
getGrid().getDataCommunicator().reset();
return this;
}
/**
* Gets the Renderer for this Column.
*
* @return the renderer
* @since 8.1
*/
public Renderer<?> getRenderer() {
return (Renderer<?>) getState().renderer;
}
/**
* Sets whether Grid should handle events in this Column from Components
* and Widgets rendered by certain Renderers. By default the events are
* not handled.
* <p>
* <strong>Note:</strong> Enabling this feature will for example select
* a row when a component is clicked. For example in the case of a
* {@link ComboBox} or {@link TextField} it might be problematic as the
* component gets re-rendered and might lose focus.
*
* @param handleWidgetEvents
* {@code true} to handle events; {@code false} to not
* @return this column
* @since 8.3
*/
public Column<T, V> setHandleWidgetEvents(boolean handleWidgetEvents) {
getState().handleWidgetEvents = handleWidgetEvents;
return this;
}
/**
* Gets whether Grid is handling the events in this Column from
* Component and Widgets.
*
* @see #setHandleWidgetEvents(boolean)
*
* @return {@code true} if handling events; {@code false} if not
* @since 8.3
*/
public boolean isHandleWidgetEvents() {
return getState(false).handleWidgetEvents;
}
/**
* Gets the grid that this column belongs to.
*
* @return the grid that this column belongs to, or <code>null</code> if
* this column has not yet been associated with any grid
*/
@SuppressWarnings("unchecked")
protected Grid<T> getGrid() {
return (Grid<T>) getParent();
}
/**
* Checks if column is attached and throws an
* {@link IllegalStateException} if it is not.
*
* @throws IllegalStateException
* if the column is no longer attached to any grid
*/
protected void checkColumnIsAttached() throws IllegalStateException {
if (getGrid() == null) {
throw new IllegalStateException(
"Column is no longer attached to a grid.");
}
}
/**
* Writes the design attributes for this column into given element.
*
* @since 7.5.0
*
* @param element
* Element to write attributes into
*
* @param designContext
* the design context
*/
protected void writeDesign(Element element,
DesignContext designContext) {
Attributes attributes = element.attributes();
ColumnState defaultState = new ColumnState();
if (getId() == null) {
setId("column" + getGrid().getColumns().indexOf(this));
}
DesignAttributeHandler.writeAttribute("column-id", attributes,
getId(), null, String.class, designContext);
// Sortable is a special attribute that depends on the data
// provider.
DesignAttributeHandler.writeAttribute("sortable", attributes,
isSortable(), null, boolean.class, designContext);
DesignAttributeHandler.writeAttribute("editable", attributes,
isEditable(), defaultState.editable, boolean.class,
designContext);
DesignAttributeHandler.writeAttribute("resizable", attributes,
isResizable(), defaultState.resizable, boolean.class,
designContext);
DesignAttributeHandler.writeAttribute("hidable", attributes,
isHidable(), defaultState.hidable, boolean.class,
designContext);
DesignAttributeHandler.writeAttribute("hidden", attributes,
isHidden(), defaultState.hidden, boolean.class,
designContext);
DesignAttributeHandler.writeAttribute("hiding-toggle-caption",
attributes, getHidingToggleCaption(),
defaultState.hidingToggleCaption, String.class,
designContext);
DesignAttributeHandler.writeAttribute("width", attributes,
getWidth(), defaultState.width, Double.class,
designContext);
DesignAttributeHandler.writeAttribute("min-width", attributes,
getMinimumWidth(), defaultState.minWidth, Double.class,
designContext);
DesignAttributeHandler.writeAttribute("max-width", attributes,
getMaximumWidth(), defaultState.maxWidth, Double.class,
designContext);
DesignAttributeHandler.writeAttribute("expand", attributes,
getExpandRatio(), defaultState.expandRatio, Integer.class,
designContext);
}
/**
* Reads the design attributes for this column from given element.
*
* @since 7.5.0
* @param design
* Element to read attributes from
* @param designContext
* the design context
*/
@SuppressWarnings("unchecked")
protected void readDesign(Element design, DesignContext designContext) {
Attributes attributes = design.attributes();
if (design.hasAttr("sortable")) {
setSortable(DesignAttributeHandler.readAttribute("sortable",
attributes, boolean.class));
} else {
setSortable(false);
}
if (design.hasAttr("editable")) {
/*
* This is a fake editor just to have something (otherwise
* "setEditable" throws an exception.
*
* Let's use TextField here because we support only Strings as
* inline data type. It will work incorrectly for other types
* but we don't support them anyway.
*/
setEditorComponent((HasValue<V> & Component) new TextField(),
(item, value) -> {
// Ignore user value since we don't know the setter
});
setEditable(DesignAttributeHandler.readAttribute("editable",
attributes, boolean.class));
}
if (design.hasAttr("resizable")) {
setResizable(DesignAttributeHandler.readAttribute("resizable",
attributes, boolean.class));
}
if (design.hasAttr("hidable")) {
setHidable(DesignAttributeHandler.readAttribute("hidable",
attributes, boolean.class));
}
if (design.hasAttr("hidden")) {
setHidden(DesignAttributeHandler.readAttribute("hidden",
attributes, boolean.class));
}
if (design.hasAttr("hiding-toggle-caption")) {
setHidingToggleCaption(DesignAttributeHandler.readAttribute(
"hiding-toggle-caption", attributes, String.class));
}
if (design.hasAttr("assistive-caption")) {
setAssistiveCaption(DesignAttributeHandler.readAttribute(
"assistive-caption", attributes, String.class));
}
// Read size info where necessary.
if (design.hasAttr("width")) {
setWidth(DesignAttributeHandler.readAttribute("width",
attributes, Double.class));
}
if (design.hasAttr("min-width")) {
setMinimumWidth(DesignAttributeHandler
.readAttribute("min-width", attributes, Double.class));
}
if (design.hasAttr("max-width")) {
setMaximumWidth(DesignAttributeHandler
.readAttribute("max-width", attributes, Double.class));
}
if (design.hasAttr("expand")) {
if (design.attr("expand").isEmpty()) {
setExpandRatio(1);
} else {
setExpandRatio(DesignAttributeHandler.readAttribute(
"expand", attributes, Integer.class));
}
}
}
/**
* Gets the DataGenerator for this Column.
*
* @return data generator
*/
private DataGenerator<T> getDataGenerator() {
return dataGenerator;
}
}
private class HeaderImpl extends Header {
@Override
protected Grid<T> getGrid() {
return Grid.this;
}
@Override
protected SectionState getState(boolean markAsDirty) {
return Grid.this.getState(markAsDirty).header;
}
@Override
protected Column<?, ?> getColumnByInternalId(String internalId) {
return getGrid().getColumnByInternalId(internalId);
}
@Override
@SuppressWarnings("unchecked")
protected String getInternalIdForColumn(Column<?, ?> column) {
return getGrid().getInternalIdForColumn((Column<T, ?>) column);
}
};
private class FooterImpl extends Footer {
@Override
protected Grid<T> getGrid() {
return Grid.this;
}
@Override
protected SectionState getState(boolean markAsDirty) {
return Grid.this.getState(markAsDirty).footer;
}
@Override
protected Column<?, ?> getColumnByInternalId(String internalId) {
return getGrid().getColumnByInternalId(internalId);
}
@Override
@SuppressWarnings("unchecked")
protected String getInternalIdForColumn(Column<?, ?> column) {
return getGrid().getInternalIdForColumn((Column<T, ?>) column);
}
};
private final Set<Column<T, ?>> columnSet = new LinkedHashSet<>();
private final Map<String, Column<T, ?>> columnKeys = new HashMap<>();
private final Map<String, Column<T, ?>> columnIds = new HashMap<>();
private final List<GridSortOrder<T>> sortOrder = new ArrayList<>();
private final DetailsManager<T> detailsManager;
private final Set<Component> extensionComponents = new HashSet<>();
private StyleGenerator<T> styleGenerator = item -> null;
private DescriptionGenerator<T> descriptionGenerator;
private final Header header = new HeaderImpl();
private final Footer footer = new FooterImpl();
private int counter = 0;
private GridSelectionModel<T> selectionModel;
private Editor<T> editor;
private PropertySet<T> propertySet;
private Class<T> beanType = null;
/**
* Creates a new grid without support for creating columns based on property
* names. Use an alternative constructor, such as {@link Grid#Grid(Class)},
* to create a grid that automatically sets up columns based on the type of
* presented data.
*
* @see #Grid(Class)
* @see #withPropertySet(PropertySet)
*/
public Grid() {
this(new DataCommunicator<>());
}
/**
* Creates a new grid that uses reflection based on the provided bean type
* to automatically set up an initial set of columns. All columns will be
* configured using the same {@link Object#toString()} renderer that is used
* by {@link #addColumn(ValueProvider)}.
*
* @param beanType
* the bean type to use, not <code>null</code>
* @see #Grid()
* @see #withPropertySet(PropertySet)
*/
public Grid(Class<T> beanType) {
this(beanType, new DataCommunicator<>());
}
/**
* Creates a new grid that uses custom data communicator and provided bean
* type
*
* It uses reflection of the provided bean type to automatically set up an
* initial set of columns. All columns will be configured using the same
* {@link Object#toString()} renderer that is used by
* {@link #addColumn(ValueProvider)}.
*
* @param beanType
* the bean type to use, not <code>null</code>
* @param dataCommunicator
* the data communicator to use, not<code>null</code>
* @since 8.0.7
*/
protected Grid(Class<T> beanType, DataCommunicator<T> dataCommunicator) {
this(BeanPropertySet.get(beanType), dataCommunicator);
this.beanType = beanType;
}
/**
* Creates a new grid with the given data communicator and without support
* for creating columns based on property names.
*
* @param dataCommunicator
* the custom data communicator to set
* @see #Grid()
* @see #Grid(PropertySet, DataCommunicator)
* @since 8.0.7
*/
protected Grid(DataCommunicator<T> dataCommunicator) {
this(new PropertySet<T>() {
@Override
public Stream<PropertyDefinition<T, ?>> getProperties() {
// No columns configured by default
return Stream.empty();
}
@Override
public Optional<PropertyDefinition<T, ?>> getProperty(String name) {
throw new IllegalStateException(
"A Grid created without a bean type class literal or a custom property set"
+ " doesn't support finding properties by name.");
}
}, dataCommunicator);
}
/**
* Creates a grid using a custom {@link PropertySet} implementation for
* configuring the initial columns and resolving property names for
* {@link #addColumn(String)} and
* {@link Column#setEditorComponent(HasValue)}.
*
* @see #withPropertySet(PropertySet)
*
* @param propertySet
* the property set implementation to use, not <code>null</code>.
*/
protected Grid(PropertySet<T> propertySet) {
this(propertySet, new DataCommunicator<>());
}
/**
* Creates a grid using a custom {@link PropertySet} implementation and
* custom data communicator.
* <p>
* Property set is used for configuring the initial columns and resolving
* property names for {@link #addColumn(String)} and
* {@link Column#setEditorComponent(HasValue)}.
*
* @see #withPropertySet(PropertySet)
*
* @param propertySet
* the property set implementation to use, not <code>null</code>.
* @param dataCommunicator
* the data communicator to use, not<code>null</code>
* @since 8.0.7
*/
protected Grid(PropertySet<T> propertySet,
DataCommunicator<T> dataCommunicator) {
super(dataCommunicator);
registerRpc(new GridServerRpcImpl());
setDefaultHeaderRow(appendHeaderRow());
setSelectionModel(new SingleSelectionModelImpl<>());
detailsManager = new DetailsManager<>();
addExtension(detailsManager);
addDataGenerator(detailsManager);
addDataGenerator((item, json) -> {
String styleName = styleGenerator.apply(item);
if (styleName != null && !styleName.isEmpty()) {
json.put(GridState.JSONKEY_ROWSTYLE, styleName);
}
if (descriptionGenerator != null) {
String description = descriptionGenerator.apply(item);
if (description != null && !description.isEmpty()) {
json.put(GridState.JSONKEY_ROWDESCRIPTION, description);
}
}
});
setPropertySet(propertySet);
// Automatically add columns for all available properties
propertySet.getProperties().map(PropertyDefinition::getName)
.forEach(this::addColumn);
}
/**
* Sets the property set to use for this grid. Does not create or update
* columns in any way but will delete and re-create the editor.
* <p>
* This is only meant to be called from constructors and readDesign, at a
* stage where it does not matter if you throw away the editor.
*
* @param propertySet
* the property set to use
*
* @since 8.0.3
*/
protected void setPropertySet(PropertySet<T> propertySet) {
Objects.requireNonNull(propertySet, "propertySet cannot be null");
this.propertySet = propertySet;
if (editor instanceof Extension) {
removeExtension((Extension) editor);
}
editor = createEditor();
if (editor instanceof Extension) {
addExtension((Extension) editor);
}
}
/**
* Returns the property set used by this grid.
*
* @return propertySet
* the property set to return
* @since
*/
protected PropertySet<T> getPropertySet() {
return propertySet;
}
/**
* Creates a grid using a custom {@link PropertySet} implementation for
* creating a default set of columns and for resolving property names with
* {@link #addColumn(String)} and
* {@link Column#setEditorComponent(HasValue)}.
* <p>
* This functionality is provided as static method instead of as a public
* constructor in order to make it possible to use a custom property set
* without creating a subclass while still leaving the public constructors
* focused on the common use cases.
*
* @see Grid#Grid()
* @see Grid#Grid(Class)
*
* @param propertySet
* the property set implementation to use, not <code>null</code>.
* @return a new grid using the provided property set, not <code>null</code>
*/
public static <BEAN> Grid<BEAN> withPropertySet(
PropertySet<BEAN> propertySet) {
return new Grid<>(propertySet);
}
/**
* Creates a new {@code Grid} using the given caption.
*
* @param caption
* the caption of the grid
*/
public Grid(String caption) {
this();
setCaption(caption);
}
/**
* Creates a new {@code Grid} using the given caption and
* {@code DataProvider}.
*
* @param caption
* the caption of the grid
* @param dataProvider
* the data provider, not {@code null}
*/
public Grid(String caption, DataProvider<T, ?> dataProvider) {
this(caption);
setDataProvider(dataProvider);
}
/**
* Creates a new {@code Grid} using the given {@code DataProvider}.
*
* @param dataProvider
* the data provider, not {@code null}
*/
public Grid(DataProvider<T, ?> dataProvider) {
this();
setDataProvider(dataProvider);
}
/**
* Creates a new {@code Grid} using the given caption and collection of
* items.
*
* @param caption
* the caption of the grid
* @param items
* the data items to use, not {@çode null}
*/
public Grid(String caption, Collection<T> items) {
this(caption, DataProvider.ofCollection(items));
}
/**
* Gets the bean type used by this grid.
* <p>
* The bean type is used to automatically set up a column added using a
* property name.
*
* @return the used bean type or <code>null</code> if no bean type has been
* defined
*
* @since 8.0.3
*/
public Class<T> getBeanType() {
return beanType;
}
public <V> void fireColumnVisibilityChangeEvent(Column<T, V> column,
boolean hidden, boolean userOriginated) {
fireEvent(new ColumnVisibilityChangeEvent(this, column, hidden,
userOriginated));
}
/**
* Adds a new column with the given property name. The column will use a
* {@link TextRenderer}. The value is converted to a String using
* {@link Object#toString()}. The property name will be used as the
* {@link Column#getId() column id} and the {@link Column#getCaption()
* column caption} will be set based on the property definition.
* <p>
* This method can only be used for a <code>Grid</code> created using
* {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
* <p>
* You can add columns for nested properties with dot notation, eg.
* <code>"property.nestedProperty"</code>
*
* @param propertyName
* the property name of the new column, not <code>null</code>
* @return the newly added column, not <code>null</code>
*/
public Column<T, ?> addColumn(String propertyName) {
return addColumn(propertyName, new TextRenderer());
}
/**
* Adds a new column with the given property name and renderer. The property
* name will be used as the {@link Column#getId() column id} and the
* {@link Column#getCaption() column caption} will be set based on the
* property definition.
* <p>
* This method can only be used for a <code>Grid</code> created using
* {@link Grid#Grid(Class)} or {@link #withPropertySet(PropertySet)}.
* <p>
* You can add columns for nested properties with dot notation, eg.
* <code>"property.nestedProperty"</code>
*
*
* @param propertyName
* the property name of the new column, not <code>null</code>
* @param renderer
* the renderer to use, not <code>null</code>
* @return the newly added column, not <code>null</code>
*/
public Column<T, ?> addColumn(String propertyName,
AbstractRenderer<? super T, ?> renderer) {
Objects.requireNonNull(propertyName, "Property name cannot be null");
Objects.requireNonNull(renderer, "Renderer cannot be null");
if (getColumn(propertyName) != null) {
throw new IllegalStateException(
"There is already a column for " + propertyName);
}
PropertyDefinition<T, ?> definition = propertySet
.getProperty(propertyName)
.orElseThrow(() -> new IllegalArgumentException(
"Could not resolve property name " + propertyName
+ " from " + propertySet));
if (!renderer.getPresentationType()
.isAssignableFrom(definition.getType())) {
throw new IllegalArgumentException(
renderer + " cannot be used with a property of type "
+ definition.getType().getName());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
Column<T, ?> column = addColumn(definition.getGetter(),
(AbstractRenderer) renderer).setId(definition.getName())
.setCaption(definition.getCaption());
return column;
}
/**
* Adds a new text column to this {@link Grid} with a value provider. The
* column will use a {@link TextRenderer}. The value is converted to a
* String using {@link Object#toString()}. In-memory sorting will use the
* natural ordering of elements if they are mutually comparable and
* otherwise fall back to comparing the string representations of the
* values.
*
* @param valueProvider
* the value provider
*
* @return the new column
*/
public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider) {
return addColumn(valueProvider, new TextRenderer());
}
/**
* Adds a new column to this {@link Grid} with typed renderer and value
* provider.
*
* @param valueProvider
* the value provider
* @param renderer
* the column value renderer
* @param <V>
* the column value type
*
* @return the new column
*
* @see AbstractRenderer
*/
public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
AbstractRenderer<? super T, ? super V> renderer) {
return addColumn(valueProvider, ValueProvider.identity(), renderer);
}
/**
* Adds a new column to this {@link Grid} with value provider and
* presentation provider.
* <p>
* <strong>Note:</strong> The presentation type for this method is set to be
* String. To use any custom renderer with the presentation provider, use
* {@link #addColumn(ValueProvider, ValueProvider, AbstractRenderer)}.
*
* @param valueProvider
* the value provider
* @param presentationProvider
* the value presentation provider
* @param <V>
* the column value type
*
* @see #addColumn(ValueProvider, ValueProvider, AbstractRenderer)
*
* @return the new column
* @since 8.1
*/
public <V> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
ValueProvider<V, String> presentationProvider) {
return addColumn(valueProvider, presentationProvider,
new TextRenderer());
}
/**
* Adds a new column to this {@link Grid} with value provider, presentation
* provider and typed renderer.
*
* <p>
* The presentation provider is a method that takes the value from the value
* provider, and maps that to a value that the renderer accepts. This
* feature can be used for storing a complex value in a column for editing,
* but providing a simplified presentation for the user when not editing.
*
* @param valueProvider
* the value provider
* @param presentationProvider
* the value presentation provider
* @param renderer
* the column value renderer
* @param <V>
* the column value type
* @param <P>
* the column presentation type
*
* @return the new column
*
* @see AbstractRenderer
* @since 8.1
*/
public <V, P> Column<T, V> addColumn(ValueProvider<T, V> valueProvider,
ValueProvider<V, P> presentationProvider,
AbstractRenderer<? super T, ? super P> renderer) {
String generatedIdentifier = getGeneratedIdentifier();
Column<T, V> column = createColumn(valueProvider, presentationProvider,
renderer);
addColumn(generatedIdentifier, column);
return column;
}
/**
* Adds a column that shows components.
* <p>
* This is a shorthand for {@link #addColum()} with a
* {@link ComponentRenderer}.
*
* @param componentProvider
* a value provider that will return a component for the given
* item
* @return the new column
* @param <V>
* the column value type, extends component
* @since 8.1
*/
public <V extends Component> Column<T, V> addComponentColumn(
ValueProvider<T, V> componentProvider) {
return addColumn(componentProvider, new ComponentRenderer());
}
/**
* Creates a column instance from a value provider, presentation provider
* and a renderer.
*
* @param valueProvider
* the value provider
* @param presentationProvider
* the presentation provider
* @param renderer
* the renderer
* @return a new column instance
* @param <V>
* the column value type
* @param <P>
* the column presentation type
*
* @since 8.1
*/
protected <V, P> Column<T, V> createColumn(
ValueProvider<T, V> valueProvider,
ValueProvider<V, P> presentationProvider,
AbstractRenderer<? super T, ? super P> renderer) {
return new Column<>(valueProvider, presentationProvider, renderer);
}
private void addColumn(String identifier, Column<T, ?> column) {
if (getColumns().contains(column)) {
return;
}
column.extend(this);
columnSet.add(column);
columnKeys.put(identifier, column);
column.setInternalId(identifier);
addDataGenerator(column.getDataGenerator());
getState().columnOrder.add(identifier);
getHeader().addColumn(identifier);
getFooter().addColumn(identifier);
if (getDefaultHeaderRow() != null) {
getDefaultHeaderRow().getCell(column).setText(column.getCaption());
}
column.updateSortable();
}
/**
* Removes the given column from this {@link Grid}.
*
* @param column
* the column to remove
*
* @throws IllegalArgumentException
* if the column is not a valid one
*/
public void removeColumn(Column<T, ?> column) {
if (columnSet.remove(column)) {
String columnId = column.getInternalId();
int displayIndex = getState(false).columnOrder.indexOf(columnId);
assert displayIndex != -1 : "Tried to remove a column which is not included in columnOrder. This should not be possible as all columns should be in columnOrder.";
columnKeys.remove(columnId);
columnIds.remove(column.getId());
column.remove();
removeDataGenerator(column.getDataGenerator());
getHeader().removeColumn(columnId);
getFooter().removeColumn(columnId);
getState(true).columnOrder.remove(columnId);
if (displayIndex < getFrozenColumnCount()) {
setFrozenColumnCount(getFrozenColumnCount() - 1);
}
} else {
throw new IllegalArgumentException("Column with id "
+ column.getId() + " cannot be removed from the grid");
}
}
/**
* Removes the column with the given column id.
*
* @see #removeColumn(Column)
* @see Column#setId(String)
*
* @param columnId
* the id of the column to remove, not <code>null</code>
*/
public void removeColumn(String columnId) {
removeColumn(getColumnOrThrow(columnId));
}
/**
* Removes all columns from this Grid.
*
* @since 8.0.2
*/
public void removeAllColumns() {
for (Column<T, ?> column : getColumns()) {
removeColumn(column);
}
}
/**
* Requests that the column widths should be recalculated.
* <p>
* In most cases Grid will know when column widths need to be recalculated
* but this method can be used to force recalculation in situations when
* grid does not recalculate automatically.
*
* @since 8.1.1
*/
public void recalculateColumnWidths() {
getRpcProxy(GridClientRpc.class).recalculateColumnWidths();
}
/**
* Sets the details component generator.
*
* @param generator
* the generator for details components
*/
public void setDetailsGenerator(DetailsGenerator<T> generator) {
this.detailsManager.setDetailsGenerator(generator);
}
/**
* Sets the visibility of details component for given item.
*
* @param item
* the item to show details for
* @param visible
* {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public void setDetailsVisible(T item, boolean visible) {
detailsManager.setDetailsVisible(item, visible);
}
/**
* Returns the visibility of details component for given item.
*
* @param item
* the item to show details for
*
* @return {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public boolean isDetailsVisible(T item) {
return detailsManager.isDetailsVisible(item);
}
/**
* Gets an unmodifiable collection of all columns currently in this
* {@link Grid}.
*
* @return unmodifiable collection of columns
*/
public List<Column<T, ?>> getColumns() {
return Collections.unmodifiableList(getState(false).columnOrder.stream()
.map(columnKeys::get).collect(Collectors.toList()));
}
/**
* Gets a {@link Column} of this grid by its identifying string.
*
* @see Column#setId(String)
*
* @param columnId
* the identifier of the column to get
* @return the column corresponding to the given column identifier, or
* <code>null</code> if there is no such column
*/
public Column<T, ?> getColumn(String columnId) {
return columnIds.get(columnId);
}
private Column<T, ?> getColumnOrThrow(String columnId) {
Objects.requireNonNull(columnId, "Column id cannot be null");
Column<T, ?> column = getColumn(columnId);
if (column == null) {
throw new IllegalStateException(
"There is no column with the id " + columnId);
}
return column;
}
/**
* {@inheritDoc}
* <p>
* Note that the order of the returned components it not specified.
*/
@Override
public Iterator<Component> iterator() {
Set<Component> componentSet = new LinkedHashSet<>(extensionComponents);
Header header = getHeader();
for (int i = 0; i < header.getRowCount(); ++i) {
HeaderRow row = header.getRow(i);
componentSet.addAll(row.getComponents());
}
Footer footer = getFooter();
for (int i = 0; i < footer.getRowCount(); ++i) {
FooterRow row = footer.getRow(i);
componentSet.addAll(row.getComponents());
}
return Collections.unmodifiableSet(componentSet).iterator();
}
/**
* Sets the number of frozen columns in this grid. Setting the count to 0
* means that no data columns will be frozen, but the built-in selection
* checkbox column will still be frozen if it's in use. Setting the count to
* -1 will also disable the selection column.
* <p>
* <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
* columns} in the count.
* <p>
* The default value is 0.
*
* @param numberOfColumns
* the number of columns that should be frozen
*
* @throws IllegalArgumentException
* if the column count is less than -1 or greater than the
* number of visible columns
*/
public void setFrozenColumnCount(int numberOfColumns) {
if (numberOfColumns < -1 || numberOfColumns > columnSet.size()) {
throw new IllegalArgumentException(
"count must be between -1 and the current number of columns ("
+ columnSet.size() + "): " + numberOfColumns);
}
getState().frozenColumnCount = numberOfColumns;
}
/**
* Gets the number of frozen columns in this grid. 0 means that no data
* columns will be frozen, but the built-in selection checkbox column will
* still be frozen if it's in use. -1 means that not even the selection
* column is frozen.
* <p>
* <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
* columns} in the count.
*
* @see #setFrozenColumnCount(int)
*
* @return the number of frozen columns
*/
public int getFrozenColumnCount() {
return getState(false).frozenColumnCount;
}
/**
* Sets the number of rows that should be visible in Grid's body. This
* method will set the height mode to be {@link HeightMode#ROW}.
*
* @param rows
* The height in terms of number of rows displayed in Grid's
* body. If Grid doesn't contain enough rows, white space is
* displayed instead.
* @throws IllegalArgumentException
* if {@code rows} is zero or less
* @throws IllegalArgumentException
* if {@code rows} is {@link Double#isInfinite(double) infinite}
* @throws IllegalArgumentException
* if {@code rows} is {@link Double#isNaN(double) NaN}
*/
public void setHeightByRows(double rows) {
if (rows <= 0.0d) {
throw new IllegalArgumentException(
"More than zero rows must be shown.");
}
if (Double.isInfinite(rows)) {
throw new IllegalArgumentException(
"Grid doesn't support infinite heights");
}
if (Double.isNaN(rows)) {
throw new IllegalArgumentException("NaN is not a valid row count");
}
getState().heightMode = HeightMode.ROW;
getState().heightByRows = rows;
}
/**
* Gets the amount of rows in Grid's body that are shown, while
* {@link #getHeightMode()} is {@link HeightMode#ROW}.
*
* @return the amount of rows that are being shown in Grid's body
* @see #setHeightByRows(double)
*/
public double getHeightByRows() {
return getState(false).heightByRows;
}
/**
* {@inheritDoc}
* <p>
* <em>Note:</em> This method will set the height mode to be
* {@link HeightMode#CSS}.
*
* @see #setHeightMode(HeightMode)
*/
@Override
public void setHeight(float height, Unit unit) {
getState().heightMode = HeightMode.CSS;
super.setHeight(height, unit);
}
/**
* Defines the mode in which the Grid widget's height is calculated.
* <p>
* If {@link HeightMode#CSS} is given, Grid will respect the values given
* via a {@code setHeight}-method, and behave as a traditional Component.
* <p>
* If {@link HeightMode#ROW} is given, Grid will make sure that the body
* will display as many rows as {@link #getHeightByRows()} defines.
* <em>Note:</em> If headers/footers are inserted or removed, the widget
* will resize itself to still display the required amount of rows in its
* body. It also takes the horizontal scrollbar into account.
*
* @param heightMode
* the mode in to which Grid should be set
*/
public void setHeightMode(HeightMode heightMode) {
/*
* This method is a workaround for the fact that Vaadin re-applies
* widget dimensions (height/width) on each state change event. The
* original design was to have setHeight and setHeightByRow be equals,
* and whichever was called the latest was considered in effect.
*
* But, because of Vaadin always calling setHeight on the widget, this
* approach doesn't work.
*/
getState().heightMode = heightMode;
}
/**
* Returns the current {@link HeightMode} the Grid is in.
* <p>
* Defaults to {@link HeightMode#CSS}.
*
* @return the current HeightMode
*/
public HeightMode getHeightMode() {
return getState(false).heightMode;
}
/**
* Sets the height of body, header and footer rows. If -1 (default), the row
* height is calculated based on the theme for an empty row before the Grid
* is displayed.
* <p>
* Note that all header, body and footer rows get the same height if
* explicitly set. In automatic mode, each section is calculated separately
* based on an empty row of that type.
*
* @see #setBodyRowHeight(double)
* @see #setHeaderRowHeight(double)
* @see #setFooterRowHeight(double)
*
* @param rowHeight
* The height of a row in pixels or -1 for automatic calculation
*/
public void setRowHeight(double rowHeight) {
setBodyRowHeight(rowHeight);
setHeaderRowHeight(rowHeight);
setFooterRowHeight(rowHeight);
}
/**
* Sets the height of a body row. If -1 (default), the row height is
* calculated based on the theme for an empty row before the Grid is
* displayed.
*
* @param rowHeight
* The height of a row in pixels or -1 for automatic calculation
* @since 8.2
*/
public void setBodyRowHeight(double rowHeight) {
getState().bodyRowHeight = rowHeight;
}
/**
* Sets the height of a header row. If -1 (default), the row height is
* calculated based on the theme for an empty row before the Grid is
* displayed.
*
* @param rowHeight
* The height of a row in pixels or -1 for automatic calculation
* @since 8.2
*/
public void setHeaderRowHeight(double rowHeight) {
getState().headerRowHeight = rowHeight;
}
/**
* Sets the height of a footer row. If -1 (default), the row height is
* calculated based on the theme for an empty row before the Grid is
* displayed.
*
* @param rowHeight
* The height of a row in pixels or -1 for automatic calculation
* @since 8.2
*/
public void setFooterRowHeight(double rowHeight) {
getState().footerRowHeight = rowHeight;
}
/**
* Returns the current body row height.-1 if row height is in automatic
* calculation mode.
*
* @see #getBodyRowHeight()
* @see #getHeaderRowHeight()
* @see #getFooterRowHeight()
*
* @return body row height
* @deprecated replaced by three separate row height controls
*/
@Deprecated
public double getRowHeight() {
return getBodyRowHeight();
}
/**
* Returns the current body row height. -1 if row height is in automatic
* calculation mode.
*
* @return body row height
* @since 8.2
*/
public double getBodyRowHeight() {
return getState(false).bodyRowHeight;
}
/**
* Returns the current header row height. -1 if row height is in automatic
* calculation mode.
*
* @return header row height
* @since 8.2
*/
public double getHeaderRowHeight() {
return getState(false).headerRowHeight;
}
/**
* Returns the current footer row height. -1 if row height is in automatic
* calculation mode.
*
* @return footer row height
* @since 8.2
*/
public double getFooterRowHeight() {
return getState(false).footerRowHeight;
}
/**
* Sets the style generator that is used for generating class names for rows
* in this grid. Returning null from the generator results in no custom
* style name being set.
*
* @see StyleGenerator
*
* @param styleGenerator
* the row style generator to set, not null
* @throws NullPointerException
* if {@code styleGenerator} is {@code null}
*/
public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
Objects.requireNonNull(styleGenerator,
"Style generator must not be null");
this.styleGenerator = styleGenerator;
getDataCommunicator().reset();
}
/**
* Gets the style generator that is used for generating class names for
* rows.
*
* @see StyleGenerator
*
* @return the row style generator
*/
public StyleGenerator<T> getStyleGenerator() {
return styleGenerator;
}
/**
* Sets the description generator that is used for generating descriptions
* for rows. This method uses the {@link ContentMode#PREFORMATTED} content
* mode.
*
* @see #setDescriptionGenerator(DescriptionGenerator, ContentMode)
*
* @param descriptionGenerator
* the row description generator to set, or <code>null</code> to
* remove a previously set generator
*/
public void setDescriptionGenerator(
DescriptionGenerator<T> descriptionGenerator) {
setDescriptionGenerator(descriptionGenerator, ContentMode.PREFORMATTED);
}
/**
* Sets the description generator that is used for generating descriptions
* for rows. This method uses the given content mode.
*
* @see #setDescriptionGenerator(DescriptionGenerator)
*
* @param descriptionGenerator
* the row description generator to set, or {@code null} to
* remove a previously set generator
* @param contentMode
* the content mode for row tooltips
*
* @since 8.2
*/
public void setDescriptionGenerator(
DescriptionGenerator<T> descriptionGenerator,
ContentMode contentMode) {
Objects.requireNonNull(contentMode, "contentMode cannot be null");
this.descriptionGenerator = descriptionGenerator;
getState().rowDescriptionContentMode = contentMode;
getDataCommunicator().reset();
}
/**
* Gets the description generator that is used for generating descriptions
* for rows.
*
* @return the row description generator, or <code>null</code> if no
* generator is set
*/
public DescriptionGenerator<T> getDescriptionGenerator() {
return descriptionGenerator;
}
//
// HEADER AND FOOTER
//
/**
* Returns the header row at the given index.
*
* @param index
* the index of the row, where the topmost row has index zero
* @return the header row at the index
* @throws IndexOutOfBoundsException
* if {@code rowIndex < 0 || rowIndex >= getHeaderRowCount()}
*/
public HeaderRow getHeaderRow(int index) {
return getHeader().getRow(index);
}
/**
* Gets the number of rows in the header section.
*
* @return the number of header rows
*/
public int getHeaderRowCount() {
return header.getRowCount();
}
/**
* Inserts a new row at the given position to the header section. Shifts the
* row currently at that position and any subsequent rows down (adds one to
* their indices). Inserting at {@link #getHeaderRowCount()} appends the row
* at the bottom of the header.
*
* @param index
* the index at which to insert the row, where the topmost row
* has index zero
* @return the inserted header row
*
* @throws IndexOutOfBoundsException
* if {@code rowIndex < 0 || rowIndex > getHeaderRowCount()}
*
* @see #appendHeaderRow()
* @see #prependHeaderRow()
* @see #removeHeaderRow(HeaderRow)
* @see #removeHeaderRow(int)
*/
public HeaderRow addHeaderRowAt(int index) {
return getHeader().addRowAt(index);
}
/**
* Adds a new row at the bottom of the header section.
*
* @return the appended header row
*
* @see #prependHeaderRow()
* @see #addHeaderRowAt(int)
* @see #removeHeaderRow(HeaderRow)
* @see #removeHeaderRow(int)
*/
public HeaderRow appendHeaderRow() {
return addHeaderRowAt(getHeaderRowCount());
}
/**
* Adds a new row at the top of the header section.
*
* @return the prepended header row
*
* @see #appendHeaderRow()
* @see #addHeaderRowAt(int)
* @see #removeHeaderRow(HeaderRow)
* @see #removeHeaderRow(int)
*/
public HeaderRow prependHeaderRow() {
return addHeaderRowAt(0);
}
/**
* Removes the given row from the header section. Removing a default row
* sets the Grid to have no default row.
*
* @param row
* the header row to be removed, not null
*
* @throws IllegalArgumentException
* if the header does not contain the row
*
* @see #removeHeaderRow(int)
* @see #addHeaderRowAt(int)
* @see #appendHeaderRow()
* @see #prependHeaderRow()
*/
public void removeHeaderRow(HeaderRow row) {
getHeader().removeRow(row);
}
/**
* Removes the row at the given position from the header section.
*
* @param index
* the index of the row to remove, where the topmost row has
* index zero
*
* @throws IndexOutOfBoundsException
* if {@code index < 0 || index >= getHeaderRowCount()}
*
* @see #removeHeaderRow(HeaderRow)
* @see #addHeaderRowAt(int)
* @see #appendHeaderRow()
* @see #prependHeaderRow()
*/
public void removeHeaderRow(int index) {
getHeader().removeRow(index);
}
/**
* Sets the visibility of the Header in this Grid.
*
* @param headerVisible
* {@code true} if visible; {@code false} if not
*
* @since 8.1.1
*/
public void setHeaderVisible(boolean headerVisible) {
getHeader().setVisible(headerVisible);
}
/**
* Gets the visibility of the Header in this Grid.
*
* @return {@code true} if visible; {@code false} if not
*
* @since 8.1.1
*/
public boolean isHeaderVisible() {
return getHeader().isVisible();
}
/**
* Returns the current default row of the header.
*
* @return the default row or null if no default row set
*
* @see #setDefaultHeaderRow(HeaderRow)
*/
public HeaderRow getDefaultHeaderRow() {
return header.getDefaultRow();
}
/**
* Sets the default row of the header. The default row is a special header
* row that displays column captions and sort indicators. By default Grid
* has a single row which is also the default row. When a header row is set
* as the default row, any existing cell content is replaced by the column
* captions.
*
* @param row
* the new default row, or null for no default row
*
* @throws IllegalArgumentException
* if the header does not contain the row
*/
public void setDefaultHeaderRow(HeaderRow row) {
header.setDefaultRow((Row) row);
}
/**
* Returns the header section of this grid. The default header contains a
* single row, set as the {@linkplain #setDefaultHeaderRow(HeaderRow)
* default row}.
*
* @return the header section
*/
protected Header getHeader() {
return header;
}
/**
* Returns the footer row at the given index.
*
* @param index
* the index of the row, where the topmost row has index zero
* @return the footer row at the index
* @throws IndexOutOfBoundsException
* if {@code rowIndex < 0 || rowIndex >= getFooterRowCount()}
*/
public FooterRow getFooterRow(int index) {
return getFooter().getRow(index);
}
/**
* Gets the number of rows in the footer section.
*
* @return the number of footer rows
*/
public int getFooterRowCount() {
return getFooter().getRowCount();
}
/**
* Inserts a new row at the given position to the footer section. Shifts the
* row currently at that position and any subsequent rows down (adds one to
* their indices). Inserting at {@link #getFooterRowCount()} appends the row
* at the bottom of the footer.
*
* @param index
* the index at which to insert the row, where the topmost row
* has index zero
* @return the inserted footer row
*
* @throws IndexOutOfBoundsException
* if {@code rowIndex < 0 || rowIndex > getFooterRowCount()}
*
* @see #appendFooterRow()
* @see #prependFooterRow()
* @see #removeFooterRow(FooterRow)
* @see #removeFooterRow(int)
*/
public FooterRow addFooterRowAt(int index) {
return getFooter().addRowAt(index);
}
/**
* Adds a new row at the bottom of the footer section.
*
* @return the appended footer row
*
* @see #prependFooterRow()
* @see #addFooterRowAt(int)
* @see #removeFooterRow(FooterRow)
* @see #removeFooterRow(int)
*/
public FooterRow appendFooterRow() {
return addFooterRowAt(getFooterRowCount());
}
/**
* Adds a new row at the top of the footer section.
*
* @return the prepended footer row
*
* @see #appendFooterRow()
* @see #addFooterRowAt(int)
* @see #removeFooterRow(FooterRow)
* @see #removeFooterRow(int)
*/
public FooterRow prependFooterRow() {
return addFooterRowAt(0);
}
/**
* Removes the given row from the footer section. Removing a default row
* sets the Grid to have no default row.
*
* @param row
* the footer row to be removed, not null
*
* @throws IllegalArgumentException
* if the footer does not contain the row
*
* @see #removeFooterRow(int)
* @see #addFooterRowAt(int)
* @see #appendFooterRow()
* @see #prependFooterRow()
*/
public void removeFooterRow(FooterRow row) {
getFooter().removeRow(row);
}
/**
* Removes the row at the given position from the footer section.
*
* @param index
* the index of the row to remove, where the topmost row has
* index zero
*
* @throws IndexOutOfBoundsException
* if {@code index < 0 || index >= getFooterRowCount()}
*
* @see #removeFooterRow(FooterRow)
* @see #addFooterRowAt(int)
* @see #appendFooterRow()
* @see #prependFooterRow()
*/
public void removeFooterRow(int index) {
getFooter().removeRow(index);
}
/**
* Sets the visibility of the Footer in this Grid.
*
* @param footerVisible
* {@code true} if visible; {@code false} if not
*
* @since 8.1.1
*/
public void setFooterVisible(boolean footerVisible) {
getFooter().setVisible(footerVisible);
}
/**
* Gets the visibility of the Footer in this Grid.
*
* @return {@code true} if visible; {@code false} if not
*
* @since 8.1.1
*/
public boolean isFooterVisible() {
return getFooter().isVisible();
}
/**
* Returns the footer section of this grid.
*
* @return the footer section
*/
protected Footer getFooter() {
return footer;
}
/**
* Registers a new column reorder listener.
*
* @param listener
* the listener to register, not null
* @return a registration for the listener
*/
public Registration addColumnReorderListener(
ColumnReorderListener listener) {
return addListener(ColumnReorderEvent.class, listener,
COLUMN_REORDER_METHOD);
}
/**
* Registers a new column resize listener.
*
* @param listener
* the listener to register, not null
* @return a registration for the listener
*/
public Registration addColumnResizeListener(ColumnResizeListener listener) {
return addListener(ColumnResizeEvent.class, listener,
COLUMN_RESIZE_METHOD);
}
/**
* Adds an item click listener. The listener is called when an item of this
* {@code Grid} is clicked.
*
* @param listener
* the item click listener, not null
* @return a registration for the listener
* @see #addContextClickListener
*/
public Registration addItemClickListener(
ItemClickListener<? super T> listener) {
return addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClick.class,
listener, ITEM_CLICK_METHOD);
}
/**
* Adds a context click listener that gets notified when a context click
* happens.
*
* @param listener
* the context click listener to add, not null actual event
* provided to the listener is {@link GridContextClickEvent}
* @return a registration object for removing the listener
*
* @since 8.1
* @see #addItemClickListener
* @see Registration
*/
@Override
public Registration addContextClickListener(
ContextClickEvent.ContextClickListener listener) {
return super.addContextClickListener(listener);
}
/**
* Registers a new column visibility change listener.
*
* @param listener
* the listener to register, not null
* @return a registration for the listener
*/
public Registration addColumnVisibilityChangeListener(
ColumnVisibilityChangeListener listener) {
return addListener(ColumnVisibilityChangeEvent.class, listener,
COLUMN_VISIBILITY_METHOD);
}
/**
* Returns whether column reordering is allowed. Default value is
* <code>false</code>.
*
* @return true if reordering is allowed
*/
public boolean isColumnReorderingAllowed() {
return getState(false).columnReorderingAllowed;
}
/**
* Sets whether or not column reordering is allowed. Default value is
* <code>false</code>.
*
* @param columnReorderingAllowed
* specifies whether column reordering is allowed
*/
public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
if (isColumnReorderingAllowed() != columnReorderingAllowed) {
getState().columnReorderingAllowed = columnReorderingAllowed;
}
}
/**
* Sets the columns and their order based on their column ids. Columns
* currently in this grid that are not present in the list of column ids are
* removed. This includes any column that has no id. Similarly, any new
* column in columns will be added to this grid. New columns can only be
* added for a <code>Grid</code> created using {@link Grid#Grid(Class)} or
* {@link #withPropertySet(PropertySet)}.
*
*
* @param columnIds
* the column ids to set
*
* @see Column#setId(String)
*/
public void setColumns(String... columnIds) {
// Must extract to an explicitly typed variable because otherwise javac
// cannot determine which overload of setColumnOrder to use
Column<T, ?>[] newColumnOrder = Stream.of(columnIds)
.map((Function<String, Column<T, ?>>) id -> {
Column<T, ?> column = getColumn(id);
if (column == null) {
column = addColumn(id);
}
return column;
}).toArray(Column[]::new);
setColumnOrder(newColumnOrder);
// The columns to remove are now at the end of the column list
getColumns().stream().skip(columnIds.length)
.forEach(this::removeColumn);
}
private String getGeneratedIdentifier() {
String columnId = "" + counter;
counter++;
return columnId;
}
/**
* Sets a new column order for the grid. All columns which are not ordered
* here will remain in the order they were before as the last columns of
* grid.
*
* @param columns
* the columns in the order they should be
*/
public void setColumnOrder(Column<T, ?>... columns) {
setColumnOrder(Stream.of(columns));
}
private void setColumnOrder(Stream<Column<T, ?>> columns) {
List<String> columnOrder = new ArrayList<>();
columns.forEach(column -> {
if (columnSet.contains(column)) {
columnOrder.add(column.getInternalId());
} else {
throw new IllegalStateException(
"setColumnOrder should not be called "
+ "with columns that are not in the grid.");
}
});
List<String> stateColumnOrder = getState().columnOrder;
if (stateColumnOrder.size() != columnOrder.size()) {
stateColumnOrder.removeAll(columnOrder);
columnOrder.addAll(stateColumnOrder);
}
getState().columnOrder = columnOrder;
fireColumnReorderEvent(false);
}
/**
* Sets a new column order for the grid based on their column ids. All
* columns which are not ordered here will remain in the order they were
* before as the last columns of grid.
*
* @param columnIds
* the column ids in the order they should be
*
* @see Column#setId(String)
*/
public void setColumnOrder(String... columnIds) {
setColumnOrder(Stream.of(columnIds).map(this::getColumnOrThrow));
}
/**
* Returns the selection model for this grid.
*
* @return the selection model, not null
*/
public GridSelectionModel<T> getSelectionModel() {
assert selectionModel != null : "No selection model set by "
+ getClass().getName() + " constructor";
return selectionModel;
}
/**
* Use this grid as a single select in {@link Binder}.
* <p>
* Throws {@link IllegalStateException} if the grid is not using a
* {@link SingleSelectionModel}.
*
* @return the single select wrapper that can be used in binder
* @throws IllegalStateException
* if not using a single selection model
*/
public SingleSelect<T> asSingleSelect() {
GridSelectionModel<T> model = getSelectionModel();
if (!(model instanceof SingleSelectionModel)) {
throw new IllegalStateException(
"Grid is not in single select mode, it needs to be explicitly set to such with setSelectionModel(SingleSelectionModel) before being able to use single selection features.");
}
return ((SingleSelectionModel<T>) model).asSingleSelect();
}
public Editor<T> getEditor() {
return editor;
}
/**
* User this grid as a multiselect in {@link Binder}.
* <p>
* Throws {@link IllegalStateException} if the grid is not using a
* {@link MultiSelectionModel}.
*
* @return the multiselect wrapper that can be used in binder
* @throws IllegalStateException
* if not using a multiselection model
*/
public MultiSelect<T> asMultiSelect() {
GridSelectionModel<T> model = getSelectionModel();
if (!(model instanceof MultiSelectionModel)) {
throw new IllegalStateException(
"Grid is not in multiselect mode, it needs to be explicitly set to such with setSelectionModel(MultiSelectionModel) before being able to use multiselection features.");
}
return ((MultiSelectionModel<T>) model).asMultiSelect();
}
/**
* Sets the selection model for the grid.
* <p>
* This method is for setting a custom selection model, and is
* {@code protected} because {@link #setSelectionMode(SelectionMode)} should
* be used for easy switching between built-in selection models.
* <p>
* The default selection model is {@link SingleSelectionModelImpl}.
* <p>
* To use a custom selection model, you can e.g. extend the grid call this
* method with your custom selection model.
*
* @param model
* the selection model to use, not {@code null}
*
* @see #setSelectionMode(SelectionMode)
*/
@SuppressWarnings("unchecked")
protected void setSelectionModel(GridSelectionModel<T> model) {
Objects.requireNonNull(model, "selection model cannot be null");
if (selectionModel != null) { // null when called from constructor
selectionModel.remove();
}
selectionModel = model;
if (selectionModel instanceof AbstractListingExtension) {
((AbstractListingExtension<T>) selectionModel).extend(this);
} else {
addExtension(selectionModel);
}
}
/**
* Sets the grid's selection mode.
* <p>
* The built-in selection models are:
* <ul>
* <li>{@link SelectionMode#SINGLE} -> {@link SingleSelectionModelImpl},
* <b>the default model</b></li>
* <li>{@link SelectionMode#MULTI} -> {@link MultiSelectionModelImpl}, with
* checkboxes in the first column for selection</li>
* <li>{@link SelectionMode#NONE} -> {@link NoSelectionModel}, preventing
* selection</li>
* </ul>
* <p>
* To use your custom selection model, you can use
* {@link #setSelectionModel(GridSelectionModel)}, see existing selection
* model implementations for example.
*
* @param selectionMode
* the selection mode to switch to, not {@code null}
* @return the used selection model
*
* @see SelectionMode
* @see GridSelectionModel
* @see #setSelectionModel(GridSelectionModel)
*/
public GridSelectionModel<T> setSelectionMode(SelectionMode selectionMode) {
Objects.requireNonNull(selectionMode, "Selection mode cannot be null.");
GridSelectionModel<T> model = selectionMode.createModel();
setSelectionModel(model);
return model;
}
/**
* This method is a shorthand that delegates to the currently set selection
* model.
*
* @see #getSelectionModel()
* @see GridSelectionModel
*/
public Set<T> getSelectedItems() {
return getSelectionModel().getSelectedItems();
}
/**
* This method is a shorthand that delegates to the currently set selection
* model.
*
* @see #getSelectionModel()
* @see GridSelectionModel
*/
public void select(T item) {
getSelectionModel().select(item);
}
/**
* This method is a shorthand that delegates to the currently set selection
* model.
*
* @see #getSelectionModel()
* @see GridSelectionModel
*/
public void deselect(T item) {
getSelectionModel().deselect(item);
}
/**
* This method is a shorthand that delegates to the currently set selection
* model.
*
* @see #getSelectionModel()
* @see GridSelectionModel
*/
public void deselectAll() {
getSelectionModel().deselectAll();
}
/**
* Adds a selection listener to the current selection model.
* <p>
* <em>NOTE:</em> If selection mode is switched with
* {@link #setSelectionMode(SelectionMode)}, then this listener is not
* triggered anymore when selection changes!
* <p>
* This is a shorthand for
* {@code grid.getSelectionModel().addSelectionListener()}. To get more
* detailed selection events, use {@link #getSelectionModel()} and either
* {@link SingleSelectionModel#addSingleSelectionListener(SingleSelectionListener)}
* or
* {@link MultiSelectionModel#addMultiSelectionListener(MultiSelectionListener)}
* depending on the used selection mode.
*
* @param listener
* the listener to add
* @return a registration handle to remove the listener
* @throws UnsupportedOperationException
* if selection has been disabled with
* {@link SelectionMode#NONE}
*/
public Registration addSelectionListener(SelectionListener<T> listener)
throws UnsupportedOperationException {
return getSelectionModel().addSelectionListener(listener);
}
/**
* Sort this Grid in ascending order by a specified column.
*
* @param column
* a column to sort against
*
*/
public void sort(Column<T, ?> column) {
sort(column, SortDirection.ASCENDING);
}
/**
* Sort this Grid in user-specified direction by a column.
*
* @param column
* a column to sort against
* @param direction
* a sort order value (ascending/descending)
*
*/
public void sort(Column<T, ?> column, SortDirection direction) {
setSortOrder(Collections
.singletonList(new GridSortOrder<>(column, direction)));
}
/**
* Sort this Grid in ascending order by a specified column defined by id.
*
* @param columnId
* the id of the column to sort against
*
* @see Column#setId(String)
*/
public void sort(String columnId) {
sort(columnId, SortDirection.ASCENDING);
}
/**
* Sort this Grid in a user-specified direction by a column defined by id.
*
* @param columnId
* the id of the column to sort against
* @param direction
* a sort order value (ascending/descending)
*
* @see Column#setId(String)
*/
public void sort(String columnId, SortDirection direction) {
sort(getColumnOrThrow(columnId), direction);
}
/**
* Clear the current sort order, and re-sort the grid.
*/
public void clearSortOrder() {
sortOrder.clear();
sort(false);
}
/**
* Sets the sort order to use.
*
* @param order
* a sort order list.
*
* @throws IllegalArgumentException
* if order is null
*/
public void setSortOrder(List<GridSortOrder<T>> order) {
setSortOrder(order, false);
}
/**
* Sets the sort order to use, given a {@link GridSortOrderBuilder}.
* Shorthand for {@code setSortOrder(builder.build())}.
*
* @see GridSortOrderBuilder
*
* @param builder
* the sort builder to retrieve the sort order from
* @throws NullPointerException
* if builder is null
*/
public void setSortOrder(GridSortOrderBuilder<T> builder) {
Objects.requireNonNull(builder, "Sort builder cannot be null");
setSortOrder(builder.build());
}
/**
* Adds a sort order change listener that gets notified when the sort order
* changes.
*
* @param listener
* the sort order change listener to add
*/
@Override
public Registration addSortListener(
SortListener<GridSortOrder<T>> listener) {
return addListener(SortEvent.class, listener, SORT_ORDER_CHANGE_METHOD);
}
/**
* Get the current sort order list.
*
* @return a sort order list
*/
public List<GridSortOrder<T>> getSortOrder() {
return Collections.unmodifiableList(sortOrder);
}
/**
* Scrolls to a certain item, using {@link ScrollDestination#ANY}.
* <p>
* If the item has an open details row, its size will also be taken into
* account.
*
* @param row
* zero based index of the item to scroll to in the current view.
* @throws IllegalArgumentException
* if the provided row is outside the item range
*/
public void scrollTo(int row) throws IllegalArgumentException {
scrollTo(row, ScrollDestination.ANY);
}
/**
* Scrolls to a certain item, using user-specified scroll destination.
* <p>
* If the item has an open details row, its size will also be taken into
* account.
*
* @param row
* zero based index of the item to scroll to in the current view.
* @param destination
* value specifying desired position of scrolled-to row, not
* {@code null}
* @throws IllegalArgumentException
* if the provided row is outside the item range
*/
public void scrollTo(int row, ScrollDestination destination) {
Objects.requireNonNull(destination,
"ScrollDestination can not be null");
if (row > getDataCommunicator().getDataProviderSize()) {
throw new IllegalArgumentException("Row outside dataProvider size");
}
getRpcProxy(GridClientRpc.class).scrollToRow(row, destination);
}
/**
* Scrolls to the beginning of the first data row.
*/
public void scrollToStart() {
getRpcProxy(GridClientRpc.class).scrollToStart();
}
/**
* Scrolls to the end of the last data row.
*/
public void scrollToEnd() {
getRpcProxy(GridClientRpc.class).scrollToEnd();
}
@Override
protected GridState getState() {
return getState(true);
}
@Override
protected GridState getState(boolean markAsDirty) {
return (GridState) super.getState(markAsDirty);
}
/**
* Sets the column resize mode to use. The default mode is
* {@link ColumnResizeMode#ANIMATED}.
*
* @param mode
* a ColumnResizeMode value
* @since 7.7.5
*/
public void setColumnResizeMode(ColumnResizeMode mode) {
getState().columnResizeMode = mode;
}
/**
* Returns the current column resize mode. The default mode is
* {@link ColumnResizeMode#ANIMATED}.
*
* @return a ColumnResizeMode value
* @since 7.7.5
*/
public ColumnResizeMode getColumnResizeMode() {
return getState(false).columnResizeMode;
}
/**
* Creates a new Editor instance. Can be overridden to create a custom
* Editor. If the Editor is a {@link AbstractGridExtension}, it will be
* automatically added to {@link DataCommunicator}.
*
* @return editor
*/
protected Editor<T> createEditor() {
return new EditorImpl<>(propertySet);
}
private void addExtensionComponent(Component c) {
if (extensionComponents.add(c)) {
c.setParent(this);
markAsDirty();
}
}
private void removeExtensionComponent(Component c) {
if (extensionComponents.remove(c)) {
c.setParent(null);
markAsDirty();
}
}
private void fireColumnReorderEvent(boolean userOriginated) {
fireEvent(new ColumnReorderEvent(this, userOriginated));
}
private void fireColumnResizeEvent(Column<?, ?> column,
boolean userOriginated) {
fireEvent(new ColumnResizeEvent(this, column, userOriginated));
}
@Override
protected void readItems(Element design, DesignContext context) {
// Grid handles reading of items in Grid#readData
}
@Override
public DataProvider<T, ?> getDataProvider() {
return internalGetDataProvider();
}
@Override
public void setDataProvider(DataProvider<T, ?> dataProvider) {
internalSetDataProvider(dataProvider);
}
/**
* Sets a CallbackDataProvider using the given fetch items callback and a
* size callback.
* <p>
* This method is a shorthand for making a {@link CallbackDataProvider} that
* handles a partial {@link Query} object.
*
* @param fetchItems
* a callback for fetching items
* @param sizeCallback
* a callback for getting the count of items
*
* @see CallbackDataProvider
* @see #setDataProvider(DataProvider)
*/
public void setDataProvider(FetchItemsCallback<T> fetchItems,
SerializableSupplier<Integer> sizeCallback) {
internalSetDataProvider(
new CallbackDataProvider<>(
q -> fetchItems.fetchItems(q.getSortOrders(),
q.getOffset(), q.getLimit()),
q -> sizeCallback.get()));
}
@Override
protected void doReadDesign(Element design, DesignContext context) {
Attributes attrs = design.attributes();
if (design.hasAttr(DECLARATIVE_DATA_ITEM_TYPE)) {
String itemType = design.attr(DECLARATIVE_DATA_ITEM_TYPE);
setBeanType(itemType);
}
if (attrs.hasKey("selection-mode")) {
setSelectionMode(DesignAttributeHandler.readAttribute(
"selection-mode", attrs, SelectionMode.class));
}
Attributes attr = design.attributes();
if (attr.hasKey("selection-allowed")) {
setReadOnly(DesignAttributeHandler
.readAttribute("selection-allowed", attr, Boolean.class));
}
if (attrs.hasKey("rows")) {
setHeightByRows(DesignAttributeHandler.readAttribute("rows", attrs,
double.class));
}
readStructure(design, context);
// Read frozen columns after columns are read.
if (attrs.hasKey("frozen-columns")) {
setFrozenColumnCount(DesignAttributeHandler
.readAttribute("frozen-columns", attrs, int.class));
}
}
/**
* Sets the bean type to use for property mapping.
* <p>
* This method is responsible also for setting or updating the property set
* so that it matches the given bean type.
* <p>
* Protected mostly for Designer needs, typically should not be overridden
* or even called.
*
* @param beanTypeClassName
* the fully qualified class name of the bean type
*
* @since 8.0.3
*/
@SuppressWarnings("unchecked")
protected void setBeanType(String beanTypeClassName) {
setBeanType((Class<T>) resolveClass(beanTypeClassName));
}
/**
* Sets the bean type to use for property mapping.
* <p>
* This method is responsible also for setting or updating the property set
* so that it matches the given bean type.
* <p>
* Protected mostly for Designer needs, typically should not be overridden
* or even called.
*
* @param beanType
* the bean type class
*
* @since 8.0.3
*/
protected void setBeanType(Class<T> beanType) {
this.beanType = beanType;
setPropertySet(BeanPropertySet.get(beanType));
}
private Class<?> resolveClass(String qualifiedClassName) {
try {
Class<?> resolvedClass = Class.forName(qualifiedClassName, true,
VaadinServiceClassLoaderUtil.findDefaultClassLoader());
return resolvedClass;
} catch (ClassNotFoundException | SecurityException e) {
throw new IllegalArgumentException(
"Unable to find class " + qualifiedClassName, e);
}
}
@Override
protected void doWriteDesign(Element design, DesignContext designContext) {
Attributes attr = design.attributes();
if (this.beanType != null) {
design.attr(DECLARATIVE_DATA_ITEM_TYPE,
this.beanType.getCanonicalName());
}
DesignAttributeHandler.writeAttribute("selection-allowed", attr,
isReadOnly(), false, Boolean.class, designContext);
Attributes attrs = design.attributes();
Grid<?> defaultInstance = designContext.getDefaultInstance(this);
DesignAttributeHandler.writeAttribute("frozen-columns", attrs,
getFrozenColumnCount(), defaultInstance.getFrozenColumnCount(),
int.class, designContext);
if (HeightMode.ROW.equals(getHeightMode())) {
DesignAttributeHandler.writeAttribute("rows", attrs,
getHeightByRows(), defaultInstance.getHeightByRows(),
double.class, designContext);
}
SelectionMode mode = getSelectionMode();
if (mode != null) {
DesignAttributeHandler.writeAttribute("selection-mode", attrs, mode,
SelectionMode.SINGLE, SelectionMode.class, designContext);
}
writeStructure(design, designContext);
}
@Override
protected T deserializeDeclarativeRepresentation(String item) {
if (item == null) {
return super.deserializeDeclarativeRepresentation(
UUID.randomUUID().toString());
}
return super.deserializeDeclarativeRepresentation(new String(item));
}
@Override
protected boolean isReadOnly() {
SelectionMode selectionMode = getSelectionMode();
if (SelectionMode.SINGLE.equals(selectionMode)) {
return asSingleSelect().isReadOnly();
}
if (SelectionMode.MULTI.equals(selectionMode)) {
return asMultiSelect().isReadOnly();
}
return false;
}
@Override
protected void setReadOnly(boolean readOnly) {
SelectionMode selectionMode = getSelectionMode();
if (SelectionMode.SINGLE.equals(selectionMode)) {
asSingleSelect().setReadOnly(readOnly);
} else if (SelectionMode.MULTI.equals(selectionMode)) {
asMultiSelect().setReadOnly(readOnly);
}
}
private void readStructure(Element design, DesignContext context) {
if (design.children().isEmpty()) {
return;
}
if (design.children().size() > 1
|| !design.child(0).tagName().equals("table")) {
throw new DesignException(
"Grid needs to have a table element as its only child");
}
Element table = design.child(0);
Elements colgroups = table.getElementsByTag("colgroup");
if (colgroups.size() != 1) {
throw new DesignException(
"Table element in declarative Grid needs to have a"
+ " colgroup defining the columns used in Grid");
}
List<DeclarativeValueProvider<T>> providers = new ArrayList<>();
for (Element col : colgroups.get(0).getElementsByTag("col")) {
String id = DesignAttributeHandler.readAttribute("column-id",
col.attributes(), null, String.class);
// If there is a property with a matching name available,
// map to that
Optional<PropertyDefinition<T, ?>> property = propertySet
.getProperties().filter(p -> p.getName().equals(id))
.findFirst();
Column<T, ?> column;
if (property.isPresent()) {
column = addColumn(id);
} else {
DeclarativeValueProvider<T> provider = new DeclarativeValueProvider<>();
column = createColumn(provider, ValueProvider.identity(),
new HtmlRenderer());
addColumn(getGeneratedIdentifier(), column);
if (id != null) {
column.setId(id);
}
providers.add(provider);
}
column.readDesign(col, context);
}
for (Element child : table.children()) {
if (child.tagName().equals("thead")) {
getHeader().readDesign(child, context);
} else if (child.tagName().equals("tbody")) {
readData(child, providers);
} else if (child.tagName().equals("tfoot")) {
getFooter().readDesign(child, context);
}
}
// Sync default header captions to column captions
if (getDefaultHeaderRow() != null) {
for (Column<T, ?> c : getColumns()) {
HeaderCell headerCell = getDefaultHeaderRow().getCell(c);
if (headerCell.getCellType() == GridStaticCellType.TEXT) {
c.setCaption(headerCell.getText());
}
}
}
}
/**
* Reads the declarative representation of a grid's data from the given
* element and stores it in the given {@link DeclarativeValueProvider}s.
* Each member in the list of value providers corresponds to a column in the
* grid.
*
* @since 8.1
*
* @param body
* the element to read data from
* @param providers
* list of {@link DeclarativeValueProvider}s to store the data of
* each column to
*/
protected void readData(Element body,
List<DeclarativeValueProvider<T>> providers) {
getSelectionModel().deselectAll();
List<T> items = new ArrayList<>();
List<T> selectedItems = new ArrayList<>();
for (Element row : body.children()) {
T item = deserializeDeclarativeRepresentation(row.attr("item"));
items.add(item);
if (row.hasAttr("selected")) {
selectedItems.add(item);
}
Elements cells = row.children();
int i = 0;
for (Element cell : cells) {
providers.get(i).addValue(item, cell.html());
i++;
}
}
setItems(items);
selectedItems.forEach(getSelectionModel()::select);
}
private void writeStructure(Element design, DesignContext designContext) {
if (getColumns().isEmpty()) {
return;
}
Element tableElement = design.appendElement("table");
Element colGroup = tableElement.appendElement("colgroup");
getColumns().forEach(column -> column
.writeDesign(colGroup.appendElement("col"), designContext));
// Always write thead. Reads correctly when there no header rows
getHeader().writeDesign(tableElement.appendElement("thead"),
designContext);
if (designContext.shouldWriteData(this)) {
Element bodyElement = tableElement.appendElement("tbody");
writeData(bodyElement, designContext);
}
if (getFooter().getRowCount() > 0) {
getFooter().writeDesign(tableElement.appendElement("tfoot"),
designContext);
}
}
/**
* Writes the data contained in this grid. Used when serializing a grid to
* its declarative representation, if
* {@link DesignContext#shouldWriteData(Component)} returns {@code true} for
* the grid that is being written.
*
* @since 8.1
*
* @param body
* the body element to write the declarative representation of
* data to
* @param designContext
* the design context
*
* @since 8.1
*/
protected void writeData(Element body, DesignContext designContext) {
getDataProvider().fetch(new Query<>())
.forEach(item -> writeRow(body, item, designContext));
}
private void writeRow(Element container, T item, DesignContext context) {
Element tableRow = container.appendElement("tr");
tableRow.attr("item", serializeDeclarativeRepresentation(item));
if (getSelectionModel().isSelected(item)) {
tableRow.attr("selected", true);
}
for (Column<T, ?> column : getColumns()) {
Object value = column.valueProvider.apply(item);
tableRow.appendElement("td")
.append(Optional.ofNullable(value).map(Object::toString)
.map(DesignFormatter::encodeForTextNode)
.orElse(""));
}
}
private SelectionMode getSelectionMode() {
GridSelectionModel<T> selectionModel = getSelectionModel();
SelectionMode mode = null;
if (selectionModel.getClass().equals(SingleSelectionModelImpl.class)) {
mode = SelectionMode.SINGLE;
} else if (selectionModel.getClass()
.equals(MultiSelectionModelImpl.class)) {
mode = SelectionMode.MULTI;
} else if (selectionModel.getClass().equals(NoSelectionModel.class)) {
mode = SelectionMode.NONE;
}
return mode;
}
/**
* Sets a user-defined identifier for given column.
*
* @see Column#setId(String)
*
* @param column
* the column
* @param id
* the user-defined identifier
*/
protected void setColumnId(String id, Column<T, ?> column) {
if (columnIds.containsKey(id)) {
throw new IllegalArgumentException("Duplicate ID for columns");
}
columnIds.put(id, column);
}
@Override
protected Collection<String> getCustomAttributes() {
Collection<String> result = super.getCustomAttributes();
// "rename" for frozen column count
result.add("frozen-column-count");
result.add("frozen-columns");
// "rename" for height-mode
result.add("height-by-rows");
result.add("rows");
// add a selection-mode attribute
result.add("selection-mode");
return result;
}
/**
* Returns a column identified by its internal id. This id should not be
* confused with the user-defined identifier.
*
* @param columnId
* the internal id of column
* @return column identified by internal id
*/
protected Column<T, ?> getColumnByInternalId(String columnId) {
return columnKeys.get(columnId);
}
/**
* Returns the internal id for given column. This id should not be confused
* with the user-defined identifier.
*
* @param column
* the column
* @return internal id of given column
*/
protected String getInternalIdForColumn(Column<T, ?> column) {
return column.getInternalId();
}
private void setSortOrder(List<GridSortOrder<T>> order,
boolean userOriginated) {
Objects.requireNonNull(order, "Sort order list cannot be null");
// Update client state to display sort order.
List<String> sortColumns = new ArrayList<>();
List<SortDirection> directions = new ArrayList<>();
order.stream().forEach(sortOrder -> {
sortColumns.add(sortOrder.getSorted().getInternalId());
directions.add(sortOrder.getDirection());
});
getState().sortColumns = sortColumns.toArray(new String[0]);
getState().sortDirs = directions.toArray(new SortDirection[0]);
sortOrder.clear();
if (order.isEmpty()) {
// Grid is not sorted anymore.
getDataCommunicator().setBackEndSorting(Collections.emptyList());
getDataCommunicator().setInMemorySorting(null);
fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
userOriginated));
return;
}
sortOrder.addAll(order);
sort(userOriginated);
}
private void sort(boolean userOriginated) {
// Set sort orders
// In-memory comparator
getDataCommunicator().setInMemorySorting(createSortingComparator());
// Back-end sort properties
List<QuerySortOrder> sortProperties = new ArrayList<>();
sortOrder.stream().map(
order -> order.getSorted().getSortOrder(order.getDirection()))
.forEach(s -> s.forEach(sortProperties::add));
getDataCommunicator().setBackEndSorting(sortProperties);
// Close grid editor if it's open.
if (getEditor().isOpen()) {
getEditor().cancel();
}
fireEvent(new SortEvent<>(this, new ArrayList<>(sortOrder),
userOriginated));
}
/**
* Creates a comparator for grid to sort rows.
*
* @return the comparator based on column sorting information.
*/
protected SerializableComparator<T> createSortingComparator() {
/*
* thenComparing is defined to return a serializable comparator as long
* as both original comparators are also serializable
*/
BinaryOperator<SerializableComparator<T>> operator = (comparator1,
comparator2) -> comparator1.thenComparing(comparator2)::compare;
return sortOrder.stream().map(
order -> order.getSorted().getComparator(order.getDirection()))
.reduce((x, y) -> 0, operator);
}
@Override
protected void internalSetDataProvider(DataProvider<T, ?> dataProvider) {
super.internalSetDataProvider(dataProvider);
for (Column<T, ?> column : getColumns()) {
column.updateSortable();
}
}
@Override
public void setVisible(boolean visible) {
if (getEditor().isOpen() && !visible) {
getEditor().cancel();
}
super.setVisible(visible);
}
@Override
public void detach() {
if (getEditor().isOpen()) {
getEditor().cancel();
}
super.detach();
}
}
|