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
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
|
/*
* Copyright 2011 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.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.util.ContainerOrderedWrapper;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.data.util.converter.Converter;
import com.vaadin.data.util.converter.ConverterUtil;
import com.vaadin.event.Action;
import com.vaadin.event.Action.Handler;
import com.vaadin.event.DataBoundTransferable;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.event.ItemClickEvent.ItemClickNotifier;
import com.vaadin.event.MouseEvents.ClickEvent;
import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.event.dd.DragSource;
import com.vaadin.event.dd.DropHandler;
import com.vaadin.event.dd.DropTarget;
import com.vaadin.event.dd.acceptcriteria.ServerSideCriterion;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.ui.table.TableConstants;
import com.vaadin.terminal.KeyMapper;
import com.vaadin.terminal.LegacyPaint;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.terminal.Resource;
/**
* <p>
* <code>Table</code> is used for representing data or components in a pageable
* and selectable table.
* </p>
*
* <p>
* Scalability of the Table is largely dictated by the container. A table does
* not have a limit for the number of items and is just as fast with hundreds of
* thousands of items as with just a few. The current GWT implementation with
* scrolling however limits the number of rows to around 500000, depending on
* the browser and the pixel height of rows.
* </p>
*
* <p>
* Components in a Table will not have their caption nor icon rendered.
* </p>
*
* @author Vaadin Ltd.
* @since 3.0
*/
@SuppressWarnings({ "deprecation" })
public class Table extends AbstractSelect implements Action.Container,
Container.Ordered, Container.Sortable, ItemClickNotifier, DragSource,
DropTarget, HasComponents {
private transient Logger logger = null;
/**
* Modes that Table support as drag sourse.
*/
public enum TableDragMode {
/**
* Table does not start drag and drop events. HTM5 style events started
* by browser may still happen.
*/
NONE,
/**
* Table starts drag with a one row only.
*/
ROW,
/**
* Table drags selected rows, if drag starts on a selected rows. Else it
* starts like in ROW mode. Note, that in Transferable there will still
* be only the row on which the drag started, other dragged rows need to
* be checked from the source Table.
*/
MULTIROW
}
protected static final int CELL_KEY = 0;
protected static final int CELL_HEADER = 1;
protected static final int CELL_ICON = 2;
protected static final int CELL_ITEMID = 3;
protected static final int CELL_GENERATED_ROW = 4;
protected static final int CELL_FIRSTCOL = 5;
public enum Align {
/**
* Left column alignment. <b>This is the default behaviour. </b>
*/
LEFT("b"),
/**
* Center column alignment.
*/
CENTER("c"),
/**
* Right column alignment.
*/
RIGHT("e");
private String alignment;
private Align(String alignment) {
this.alignment = alignment;
}
@Override
public String toString() {
return alignment;
}
public Align convertStringToAlign(String string) {
if (string == null) {
return null;
}
if (string.equals("b")) {
return Align.LEFT;
} else if (string.equals("c")) {
return Align.CENTER;
} else if (string.equals("e")) {
return Align.RIGHT;
} else {
return null;
}
}
}
/**
* @deprecated from 7.0, use {@link Align#LEFT} instead
*/
@Deprecated
public static final Align ALIGN_LEFT = Align.LEFT;
/**
* @deprecated from 7.0, use {@link Align#CENTER} instead
*/
@Deprecated
public static final Align ALIGN_CENTER = Align.CENTER;
/**
* @deprecated from 7.0, use {@link Align#RIGHT} instead
*/
@Deprecated
public static final Align ALIGN_RIGHT = Align.RIGHT;
public enum ColumnHeaderMode {
/**
* Column headers are hidden.
*/
HIDDEN,
/**
* Property ID:s are used as column headers.
*/
ID,
/**
* Column headers are explicitly specified with
* {@link #setColumnHeaders(String[])}.
*/
EXPLICIT,
/**
* Column headers are explicitly specified with
* {@link #setColumnHeaders(String[])}. If a header is not specified for
* a given property, its property id is used instead.
* <p>
* <b>This is the default behavior. </b>
*/
EXPLICIT_DEFAULTS_ID
}
/**
* @deprecated from 7.0, use {@link ColumnHeaderMode#HIDDEN} instead
*/
@Deprecated
public static final ColumnHeaderMode COLUMN_HEADER_MODE_HIDDEN = ColumnHeaderMode.HIDDEN;
/**
* @deprecated from 7.0, use {@link ColumnHeaderMode#ID} instead
*/
@Deprecated
public static final ColumnHeaderMode COLUMN_HEADER_MODE_ID = ColumnHeaderMode.ID;
/**
* @deprecated from 7.0, use {@link ColumnHeaderMode#EXPLICIT} instead
*/
@Deprecated
public static final ColumnHeaderMode COLUMN_HEADER_MODE_EXPLICIT = ColumnHeaderMode.EXPLICIT;
/**
* @deprecated from 7.0, use {@link ColumnHeaderMode#EXPLICIT_DEFAULTS_ID}
* instead
*/
@Deprecated
public static final ColumnHeaderMode COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID = ColumnHeaderMode.EXPLICIT_DEFAULTS_ID;
public enum RowHeaderMode {
/**
* Row caption mode: The row headers are hidden. <b>This is the default
* mode. </b>
*/
HIDDEN(null),
/**
* Row caption mode: Items Id-objects toString is used as row caption.
*/
ID(ItemCaptionMode.ID),
/**
* Row caption mode: Item-objects toString is used as row caption.
*/
ITEM(ItemCaptionMode.ITEM),
/**
* Row caption mode: Index of the item is used as item caption. The
* index mode can only be used with the containers implementing the
* {@link com.vaadin.data.Container.Indexed} interface.
*/
INDEX(ItemCaptionMode.INDEX),
/**
* Row caption mode: Item captions are explicitly specified, but if the
* caption is missing, the item id objects <code>toString()</code> is
* used instead.
*/
EXPLICIT_DEFAULTS_ID(ItemCaptionMode.EXPLICIT_DEFAULTS_ID),
/**
* Row caption mode: Item captions are explicitly specified.
*/
EXPLICIT(ItemCaptionMode.EXPLICIT),
/**
* Row caption mode: Only icons are shown, the captions are hidden.
*/
ICON_ONLY(ItemCaptionMode.ICON_ONLY),
/**
* Row caption mode: Item captions are read from property specified with
* {@link #setItemCaptionPropertyId(Object)}.
*/
PROPERTY(ItemCaptionMode.PROPERTY);
ItemCaptionMode mode;
private RowHeaderMode(ItemCaptionMode mode) {
this.mode = mode;
}
public ItemCaptionMode getItemCaptionMode() {
return mode;
}
}
/**
* @deprecated from 7.0, use {@link RowHeaderMode#HIDDEN} instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_HIDDEN = RowHeaderMode.HIDDEN;
/**
* @deprecated from 7.0, use {@link RowHeaderMode#ID} instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_ID = RowHeaderMode.ID;
/**
* @deprecated from 7.0, use {@link RowHeaderMode#ITEM} instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_ITEM = RowHeaderMode.ITEM;
/**
* @deprecated from 7.0, use {@link RowHeaderMode#INDEX} instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_INDEX = RowHeaderMode.INDEX;
/**
* @deprecated from 7.0, use {@link RowHeaderMode#EXPLICIT_DEFAULTS_ID}
* instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_EXPLICIT_DEFAULTS_ID = RowHeaderMode.EXPLICIT_DEFAULTS_ID;
/**
* @deprecated from 7.0, use {@link RowHeaderMode#EXPLICIT} instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_EXPLICIT = RowHeaderMode.EXPLICIT;
/**
* @deprecated from 7.0, use {@link RowHeaderMode#ICON_ONLY} instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_ICON_ONLY = RowHeaderMode.ICON_ONLY;
/**
* @deprecated from 7.0, use {@link RowHeaderMode#PROPERTY} instead
*/
@Deprecated
public static final RowHeaderMode ROW_HEADER_MODE_PROPERTY = RowHeaderMode.PROPERTY;
/**
* The default rate that table caches rows for smooth scrolling.
*/
private static final double CACHE_RATE_DEFAULT = 2;
private static final String ROW_HEADER_COLUMN_KEY = "0";
private static final Object ROW_HEADER_FAKE_PROPERTY_ID = new UniqueSerializable() {
};
/* Private table extensions to Select */
/**
* True if column collapsing is allowed.
*/
private boolean columnCollapsingAllowed = false;
/**
* True if reordering of columns is allowed on the client side.
*/
private boolean columnReorderingAllowed = false;
/**
* Keymapper for column ids.
*/
private final KeyMapper<Object> columnIdMap = new KeyMapper<Object>();
/**
* Holds visible column propertyIds - in order.
*/
private LinkedList<Object> visibleColumns = new LinkedList<Object>();
/**
* Holds noncollapsible columns.
*/
private HashSet<Object> noncollapsibleColumns = new HashSet<Object>();
/**
* Holds propertyIds of currently collapsed columns.
*/
private final HashSet<Object> collapsedColumns = new HashSet<Object>();
/**
* Holds headers for visible columns (by propertyId).
*/
private final HashMap<Object, String> columnHeaders = new HashMap<Object, String>();
/**
* Holds footers for visible columns (by propertyId).
*/
private final HashMap<Object, String> columnFooters = new HashMap<Object, String>();
/**
* Holds icons for visible columns (by propertyId).
*/
private final HashMap<Object, Resource> columnIcons = new HashMap<Object, Resource>();
/**
* Holds alignments for visible columns (by propertyId).
*/
private HashMap<Object, Align> columnAlignments = new HashMap<Object, Align>();
/**
* Holds column widths in pixels (Integer) or expand ratios (Float) for
* visible columns (by propertyId).
*/
private final HashMap<Object, Object> columnWidths = new HashMap<Object, Object>();
/**
* Holds column generators
*/
private final HashMap<Object, ColumnGenerator> columnGenerators = new LinkedHashMap<Object, ColumnGenerator>();
/**
* Holds value of property pageLength. 0 disables paging.
*/
private int pageLength = 15;
/**
* Id the first item on the current page.
*/
private Object currentPageFirstItemId = null;
/**
* Index of the first item on the current page.
*/
private int currentPageFirstItemIndex = 0;
/**
* Holds value of property selectable.
*/
private boolean selectable = false;
/**
* Holds value of property columnHeaderMode.
*/
private ColumnHeaderMode columnHeaderMode = ColumnHeaderMode.EXPLICIT_DEFAULTS_ID;
/**
* Holds value of property rowHeaderMode.
*/
private RowHeaderMode rowHeaderMode = RowHeaderMode.EXPLICIT_DEFAULTS_ID;
/**
* Should the Table footer be visible?
*/
private boolean columnFootersVisible = false;
/**
* Page contents buffer used in buffered mode.
*/
private Object[][] pageBuffer = null;
/**
* Set of properties listened - the list is kept to release the listeners
* later.
*/
private HashSet<Property<?>> listenedProperties = null;
/**
* Set of visible components - the is used for needsRepaint calculation.
*/
private HashSet<Component> visibleComponents = null;
/**
* List of action handlers.
*/
private LinkedList<Handler> actionHandlers = null;
/**
* Action mapper.
*/
private KeyMapper<Action> actionMapper = null;
/**
* Table cell editor factory.
*/
private TableFieldFactory fieldFactory = DefaultFieldFactory.get();
/**
* Is table editable.
*/
private boolean editable = false;
/**
* Current sorting direction.
*/
private boolean sortAscending = true;
/**
* Currently table is sorted on this propertyId.
*/
private Object sortContainerPropertyId = null;
/**
* Is table sorting by the user enabled.
*/
private boolean sortEnabled = true;
/**
* Number of rows explicitly requested by the client to be painted on next
* paint. This is -1 if no request by the client is made. Painting the
* component will automatically reset this to -1.
*/
private int reqRowsToPaint = -1;
/**
* Index of the first rows explicitly requested by the client to be painted.
* This is -1 if no request by the client is made. Painting the component
* will automatically reset this to -1.
*/
private int reqFirstRowToPaint = -1;
private int firstToBeRenderedInClient = -1;
private int lastToBeRenderedInClient = -1;
private boolean isContentRefreshesEnabled = true;
private int pageBufferFirstIndex;
private boolean containerChangeToBeRendered = false;
/**
* Table cell specific style generator
*/
private CellStyleGenerator cellStyleGenerator = null;
/**
* Table cell specific tooltip generator
*/
private ItemDescriptionGenerator itemDescriptionGenerator;
/*
* EXPERIMENTAL feature: will tell the client to re-calculate column widths
* if set to true. Currently no setter: extend to enable.
*/
protected boolean alwaysRecalculateColumnWidths = false;
private double cacheRate = CACHE_RATE_DEFAULT;
private TableDragMode dragMode = TableDragMode.NONE;
private DropHandler dropHandler;
private MultiSelectMode multiSelectMode = MultiSelectMode.DEFAULT;
private boolean rowCacheInvalidated;
private RowGenerator rowGenerator = null;
private final Map<Field<?>, Property<?>> associatedProperties = new HashMap<Field<?>, Property<?>>();
private boolean painted = false;
private HashMap<Object, Converter<String, Object>> propertyValueConverters = new HashMap<Object, Converter<String, Object>>();
/**
* Set to true if the client-side should be informed that the key mapper has
* been reset so it can avoid sending back references to keys that are no
* longer present.
*/
private boolean keyMapperReset;
/* Table constructors */
/**
* Creates a new empty table.
*/
public Table() {
setRowHeaderMode(ROW_HEADER_MODE_HIDDEN);
}
/**
* Creates a new empty table with caption.
*
* @param caption
*/
public Table(String caption) {
this();
setCaption(caption);
}
/**
* Creates a new table with caption and connect it to a Container.
*
* @param caption
* @param dataSource
*/
public Table(String caption, Container dataSource) {
this();
setCaption(caption);
setContainerDataSource(dataSource);
}
/* Table functionality */
/**
* Gets the array of visible column id:s, including generated columns.
*
* <p>
* The columns are show in the order of their appearance in this array.
* </p>
*
* @return an array of currently visible propertyIds and generated column
* ids.
*/
public Object[] getVisibleColumns() {
if (visibleColumns == null) {
return null;
}
return visibleColumns.toArray();
}
/**
* Sets the array of visible column property id:s.
*
* <p>
* The columns are show in the order of their appearance in this array.
* </p>
*
* @param visibleColumns
* the Array of shown property id:s.
*/
public void setVisibleColumns(Object[] visibleColumns) {
// Visible columns must exist
if (visibleColumns == null) {
throw new NullPointerException(
"Can not set visible columns to null value");
}
// TODO add error check that no duplicate identifiers exist
// Checks that the new visible columns contains no nulls and properties
// exist
final Collection<?> properties = getContainerPropertyIds();
for (int i = 0; i < visibleColumns.length; i++) {
if (visibleColumns[i] == null) {
throw new NullPointerException("Ids must be non-nulls");
} else if (!properties.contains(visibleColumns[i])
&& !columnGenerators.containsKey(visibleColumns[i])) {
throw new IllegalArgumentException(
"Ids must exist in the Container or as a generated column , missing id: "
+ visibleColumns[i]);
}
}
// If this is called before the constructor is finished, it might be
// uninitialized
final LinkedList<Object> newVC = new LinkedList<Object>();
for (int i = 0; i < visibleColumns.length; i++) {
newVC.add(visibleColumns[i]);
}
// Removes alignments, icons and headers from hidden columns
if (this.visibleColumns != null) {
boolean disabledHere = disableContentRefreshing();
try {
for (final Iterator<Object> i = this.visibleColumns.iterator(); i
.hasNext();) {
final Object col = i.next();
if (!newVC.contains(col)) {
setColumnHeader(col, null);
setColumnAlignment(col, (Align) null);
setColumnIcon(col, null);
}
}
} finally {
if (disabledHere) {
enableContentRefreshing(false);
}
}
}
this.visibleColumns = newVC;
// Assures visual refresh
refreshRowCache();
}
/**
* Gets the headers of the columns.
*
* <p>
* The headers match the property id:s given my the set visible column
* headers. The table must be set in either
* {@link #COLUMN_HEADER_MODE_EXPLICIT} or
* {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the
* headers. In the defaults mode any nulls in the headers array are replaced
* with id.toString().
* </p>
*
* @return the Array of column headers.
*/
public String[] getColumnHeaders() {
if (columnHeaders == null) {
return null;
}
final String[] headers = new String[visibleColumns.size()];
int i = 0;
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext(); i++) {
headers[i] = getColumnHeader(it.next());
}
return headers;
}
/**
* Sets the headers of the columns.
*
* <p>
* The headers match the property id:s given my the set visible column
* headers. The table must be set in either
* {@link #COLUMN_HEADER_MODE_EXPLICIT} or
* {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the
* headers. In the defaults mode any nulls in the headers array are replaced
* with id.toString() outputs when rendering.
* </p>
*
* @param columnHeaders
* the Array of column headers that match the
* {@link #getVisibleColumns()} method.
*/
public void setColumnHeaders(String[] columnHeaders) {
if (columnHeaders.length != visibleColumns.size()) {
throw new IllegalArgumentException(
"The length of the headers array must match the number of visible columns");
}
this.columnHeaders.clear();
int i = 0;
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext() && i < columnHeaders.length; i++) {
this.columnHeaders.put(it.next(), columnHeaders[i]);
}
requestRepaint();
}
/**
* Gets the icons of the columns.
*
* <p>
* The icons in headers match the property id:s given my the set visible
* column headers. The table must be set in either
* {@link #COLUMN_HEADER_MODE_EXPLICIT} or
* {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the headers
* with icons.
* </p>
*
* @return the Array of icons that match the {@link #getVisibleColumns()}.
*/
public Resource[] getColumnIcons() {
if (columnIcons == null) {
return null;
}
final Resource[] icons = new Resource[visibleColumns.size()];
int i = 0;
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext(); i++) {
icons[i] = columnIcons.get(it.next());
}
return icons;
}
/**
* Sets the icons of the columns.
*
* <p>
* The icons in headers match the property id:s given my the set visible
* column headers. The table must be set in either
* {@link #COLUMN_HEADER_MODE_EXPLICIT} or
* {@link #COLUMN_HEADER_MODE_EXPLICIT_DEFAULTS_ID} mode to show the headers
* with icons.
* </p>
*
* @param columnIcons
* the Array of icons that match the {@link #getVisibleColumns()}
* .
*/
public void setColumnIcons(Resource[] columnIcons) {
if (columnIcons.length != visibleColumns.size()) {
throw new IllegalArgumentException(
"The length of the icons array must match the number of visible columns");
}
this.columnIcons.clear();
int i = 0;
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext() && i < columnIcons.length; i++) {
this.columnIcons.put(it.next(), columnIcons[i]);
}
requestRepaint();
}
/**
* Gets the array of column alignments.
*
* <p>
* The items in the array must match the properties identified by
* {@link #getVisibleColumns()}. The possible values for the alignments
* include:
* <ul>
* <li>{@link Align#LEFT}: Left alignment</li>
* <li>{@link Align#CENTER}: Centered</li>
* <li>{@link Align#RIGHT}: Right alignment</li>
* </ul>
* The alignments default to {@link Align#LEFT}: any null values are
* rendered as align lefts.
* </p>
*
* @return the Column alignments array.
*/
public Align[] getColumnAlignments() {
if (columnAlignments == null) {
return null;
}
final Align[] alignments = new Align[visibleColumns.size()];
int i = 0;
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext(); i++) {
alignments[i] = getColumnAlignment(it.next());
}
return alignments;
}
/**
* Sets the column alignments.
*
* <p>
* The amount of items in the array must match the amount of properties
* identified by {@link #getVisibleColumns()}. The possible values for the
* alignments include:
* <ul>
* <li>{@link Align#LEFT}: Left alignment</li>
* <li>{@link Align#CENTER}: Centered</li>
* <li>{@link Align#RIGHT}: Right alignment</li>
* </ul>
* The alignments default to {@link Align#LEFT}
* </p>
*
* @param columnAlignments
* the Column alignments array.
*/
public void setColumnAlignments(Align... columnAlignments) {
if (columnAlignments.length != visibleColumns.size()) {
throw new IllegalArgumentException(
"The length of the alignments array must match the number of visible columns");
}
// Resets the alignments
final HashMap<Object, Align> newCA = new HashMap<Object, Align>();
int i = 0;
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext() && i < columnAlignments.length; i++) {
newCA.put(it.next(), columnAlignments[i]);
}
this.columnAlignments = newCA;
// Assures the visual refresh. No need to reset the page buffer before
// as the content has not changed, only the alignments.
refreshRenderedCells();
}
/**
* Sets columns width (in pixels). Theme may not necessary respect very
* small or very big values. Setting width to -1 (default) means that theme
* will make decision of width.
*
* <p>
* Column can either have a fixed width or expand ratio. The latter one set
* is used. See @link {@link #setColumnExpandRatio(Object, float)}.
*
* @param propertyId
* colunmns property id
* @param width
* width to be reserved for colunmns content
* @since 4.0.3
*/
public void setColumnWidth(Object propertyId, int width) {
if (propertyId == null) {
// Since propertyId is null, this is the row header. Use the magic
// id to store the width of the row header.
propertyId = ROW_HEADER_FAKE_PROPERTY_ID;
}
if (width < 0) {
columnWidths.remove(propertyId);
} else {
columnWidths.put(propertyId, Integer.valueOf(width));
}
requestRepaint();
}
/**
* Sets the column expand ratio for given column.
* <p>
* Expand ratios can be defined to customize the way how excess space is
* divided among columns. Table can have excess space if it has its width
* defined and there is horizontally more space than columns consume
* naturally. Excess space is the space that is not used by columns with
* explicit width (see {@link #setColumnWidth(Object, int)}) or with natural
* width (no width nor expand ratio).
*
* <p>
* By default (without expand ratios) the excess space is divided
* proportionally to columns natural widths.
*
* <p>
* Only expand ratios of visible columns are used in final calculations.
*
* <p>
* Column can either have a fixed width or expand ratio. The latter one set
* is used.
*
* <p>
* A column with expand ratio is considered to be minimum width by default
* (if no excess space exists). The minimum width is defined by terminal
* implementation.
*
* <p>
* If terminal implementation supports re-sizable columns the column becomes
* fixed width column if users resizes the column.
*
* @param propertyId
* columns property id
* @param expandRatio
* the expandRatio used to divide excess space for this column
*/
public void setColumnExpandRatio(Object propertyId, float expandRatio) {
if (expandRatio < 0) {
columnWidths.remove(propertyId);
} else {
columnWidths.put(propertyId, new Float(expandRatio));
}
}
public float getColumnExpandRatio(Object propertyId) {
final Object width = columnWidths.get(propertyId);
if (width == null || !(width instanceof Float)) {
return -1;
}
final Float value = (Float) width;
return value.floatValue();
}
/**
* Gets the pixel width of column
*
* @param propertyId
* @return width of column or -1 when value not set
*/
public int getColumnWidth(Object propertyId) {
if (propertyId == null) {
// Since propertyId is null, this is the row header. Use the magic
// id to retrieve the width of the row header.
propertyId = ROW_HEADER_FAKE_PROPERTY_ID;
}
final Object width = columnWidths.get(propertyId);
if (width == null || !(width instanceof Integer)) {
return -1;
}
final Integer value = (Integer) width;
return value.intValue();
}
/**
* Gets the page length.
*
* <p>
* Setting page length 0 disables paging.
* </p>
*
* @return the Length of one page.
*/
public int getPageLength() {
return pageLength;
}
/**
* Sets the page length.
*
* <p>
* Setting page length 0 disables paging. The page length defaults to 15.
* </p>
*
* <p>
* If Table has width set ({@link #setWidth(float, int)} ) the client side
* may update the page length automatically the correct value.
* </p>
*
* @param pageLength
* the length of one page.
*/
public void setPageLength(int pageLength) {
if (pageLength >= 0 && this.pageLength != pageLength) {
this.pageLength = pageLength;
// Assures the visual refresh
refreshRowCache();
}
}
/**
* This method adjusts a possible caching mechanism of table implementation.
*
* <p>
* Table component may fetch and render some rows outside visible area. With
* complex tables (for example containing layouts and components), the
* client side may become unresponsive. Setting the value lower, UI will
* become more responsive. With higher values scrolling in client will hit
* server less frequently.
*
* <p>
* The amount of cached rows will be cacheRate multiplied with pageLength (
* {@link #setPageLength(int)} both below and above visible area..
*
* @param cacheRate
* a value over 0 (fastest rendering time). Higher value will
* cache more rows on server (smoother scrolling). Default value
* is 2.
*/
public void setCacheRate(double cacheRate) {
if (cacheRate < 0) {
throw new IllegalArgumentException(
"cacheRate cannot be less than zero");
}
if (this.cacheRate != cacheRate) {
this.cacheRate = cacheRate;
requestRepaint();
}
}
/**
* @see #setCacheRate(double)
*
* @return the current cache rate value
*/
public double getCacheRate() {
return cacheRate;
}
/**
* Getter for property currentPageFirstItem.
*
* @return the Value of property currentPageFirstItem.
*/
public Object getCurrentPageFirstItemId() {
// Priorise index over id if indexes are supported
if (items instanceof Container.Indexed) {
final int index = getCurrentPageFirstItemIndex();
Object id = null;
if (index >= 0 && index < size()) {
id = getIdByIndex(index);
}
if (id != null && !id.equals(currentPageFirstItemId)) {
currentPageFirstItemId = id;
}
}
// If there is no item id at all, use the first one
if (currentPageFirstItemId == null) {
currentPageFirstItemId = firstItemId();
}
return currentPageFirstItemId;
}
protected Object getIdByIndex(int index) {
return ((Container.Indexed) items).getIdByIndex(index);
}
/**
* Setter for property currentPageFirstItemId.
*
* @param currentPageFirstItemId
* the New value of property currentPageFirstItemId.
*/
public void setCurrentPageFirstItemId(Object currentPageFirstItemId) {
// Gets the corresponding index
int index = -1;
if (items instanceof Container.Indexed) {
index = indexOfId(currentPageFirstItemId);
} else {
// If the table item container does not have index, we have to
// calculates the index by hand
Object id = firstItemId();
while (id != null && !id.equals(currentPageFirstItemId)) {
index++;
id = nextItemId(id);
}
if (id == null) {
index = -1;
}
}
// If the search for item index was successful
if (index >= 0) {
/*
* The table is not capable of displaying an item in the container
* as the first if there are not enough items following the selected
* item so the whole table (pagelength) is filled.
*/
int maxIndex = size() - pageLength;
if (maxIndex < 0) {
maxIndex = 0;
}
if (index > maxIndex) {
// Note that we pass index, not maxIndex, letting
// setCurrentPageFirstItemIndex handle the situation.
setCurrentPageFirstItemIndex(index);
return;
}
this.currentPageFirstItemId = currentPageFirstItemId;
currentPageFirstItemIndex = index;
}
// Assures the visual refresh
refreshRowCache();
}
protected int indexOfId(Object itemId) {
return ((Container.Indexed) items).indexOfId(itemId);
}
/**
* Gets the icon Resource for the specified column.
*
* @param propertyId
* the propertyId indentifying the column.
* @return the icon for the specified column; null if the column has no icon
* set, or if the column is not visible.
*/
public Resource getColumnIcon(Object propertyId) {
return columnIcons.get(propertyId);
}
/**
* Sets the icon Resource for the specified column.
* <p>
* Throws IllegalArgumentException if the specified column is not visible.
* </p>
*
* @param propertyId
* the propertyId identifying the column.
* @param icon
* the icon Resource to set.
*/
public void setColumnIcon(Object propertyId, Resource icon) {
if (icon == null) {
columnIcons.remove(propertyId);
} else {
columnIcons.put(propertyId, icon);
}
requestRepaint();
}
/**
* Gets the header for the specified column.
*
* @param propertyId
* the propertyId identifying the column.
* @return the header for the specified column if it has one.
*/
public String getColumnHeader(Object propertyId) {
if (getColumnHeaderMode() == ColumnHeaderMode.HIDDEN) {
return null;
}
String header = columnHeaders.get(propertyId);
if ((header == null && getColumnHeaderMode() == ColumnHeaderMode.EXPLICIT_DEFAULTS_ID)
|| getColumnHeaderMode() == ColumnHeaderMode.ID) {
header = propertyId.toString();
}
return header;
}
/**
* Sets the column header for the specified column;
*
* @param propertyId
* the propertyId identifying the column.
* @param header
* the header to set.
*/
public void setColumnHeader(Object propertyId, String header) {
if (header == null) {
columnHeaders.remove(propertyId);
} else {
columnHeaders.put(propertyId, header);
}
requestRepaint();
}
/**
* Gets the specified column's alignment.
*
* @param propertyId
* the propertyID identifying the column.
* @return the specified column's alignment if it as one; null otherwise.
*/
public Align getColumnAlignment(Object propertyId) {
final Align a = columnAlignments.get(propertyId);
return a == null ? Align.LEFT : a;
}
/**
* Sets the specified column's alignment.
*
* <p>
* Throws IllegalArgumentException if the alignment is not one of the
* following: {@link Align#LEFT}, {@link Align#CENTER} or
* {@link Align#RIGHT}
* </p>
*
* @param propertyId
* the propertyID identifying the column.
* @param alignment
* the desired alignment.
*/
public void setColumnAlignment(Object propertyId, Align alignment) {
if (alignment == null || alignment == Align.LEFT) {
columnAlignments.remove(propertyId);
} else {
columnAlignments.put(propertyId, alignment);
}
// Assures the visual refresh. No need to reset the page buffer before
// as the content has not changed, only the alignments.
refreshRenderedCells();
}
/**
* Checks if the specified column is collapsed.
*
* @param propertyId
* the propertyID identifying the column.
* @return true if the column is collapsed; false otherwise;
*/
public boolean isColumnCollapsed(Object propertyId) {
return collapsedColumns != null
&& collapsedColumns.contains(propertyId);
}
/**
* Sets whether the specified column is collapsed or not.
*
*
* @param propertyId
* the propertyID identifying the column.
* @param collapsed
* the desired collapsedness.
* @throws IllegalStateException
* if column collapsing is not allowed
*/
public void setColumnCollapsed(Object propertyId, boolean collapsed)
throws IllegalStateException {
if (!isColumnCollapsingAllowed()) {
throw new IllegalStateException("Column collapsing not allowed!");
}
if (collapsed && noncollapsibleColumns.contains(propertyId)) {
throw new IllegalStateException("The column is noncollapsible!");
}
if (collapsed) {
collapsedColumns.add(propertyId);
} else {
collapsedColumns.remove(propertyId);
}
// Assures the visual refresh
refreshRowCache();
}
/**
* Checks if column collapsing is allowed.
*
* @return true if columns can be collapsed; false otherwise.
*/
public boolean isColumnCollapsingAllowed() {
return columnCollapsingAllowed;
}
/**
* Sets whether column collapsing is allowed or not.
*
* @param collapsingAllowed
* specifies whether column collapsing is allowed.
*/
public void setColumnCollapsingAllowed(boolean collapsingAllowed) {
columnCollapsingAllowed = collapsingAllowed;
if (!collapsingAllowed) {
collapsedColumns.clear();
}
// Assures the visual refresh. No need to reset the page buffer before
// as the content has not changed, only the alignments.
refreshRenderedCells();
}
/**
* Sets whether the given column is collapsible. Note that collapsible
* columns can only be actually collapsed (via UI or with
* {@link #setColumnCollapsed(Object, boolean) setColumnCollapsed()}) if
* {@link #isColumnCollapsingAllowed()} is true. By default all columns are
* collapsible.
*
* @param propertyId
* the propertyID identifying the column.
* @param collapsible
* true if the column should be collapsible, false otherwise.
*/
public void setColumnCollapsible(Object propertyId, boolean collapsible) {
if (collapsible) {
noncollapsibleColumns.remove(propertyId);
} else {
noncollapsibleColumns.add(propertyId);
collapsedColumns.remove(propertyId);
}
refreshRowCache();
}
/**
* Checks if the given column is collapsible. Note that even if this method
* returns <code>true</code>, the column can only be actually collapsed (via
* UI or with {@link #setColumnCollapsed(Object, boolean)
* setColumnCollapsed()}) if {@link #isColumnCollapsingAllowed()} is also
* true.
*
* @return true if the column can be collapsed; false otherwise.
*/
public boolean isColumnCollapsible(Object propertyId) {
return !noncollapsibleColumns.contains(propertyId);
}
/**
* Checks if column reordering is allowed.
*
* @return true if columns can be reordered; false otherwise.
*/
public boolean isColumnReorderingAllowed() {
return columnReorderingAllowed;
}
/**
* Sets whether column reordering is allowed or not.
*
* @param columnReorderingAllowed
* specifies whether column reordering is allowed.
*/
public void setColumnReorderingAllowed(boolean columnReorderingAllowed) {
if (columnReorderingAllowed != this.columnReorderingAllowed) {
this.columnReorderingAllowed = columnReorderingAllowed;
requestRepaint();
}
}
/*
* Arranges visible columns according to given columnOrder. Silently ignores
* colimnId:s that are not visible columns, and keeps the internal order of
* visible columns left out of the ordering (trailing). Silently does
* nothing if columnReordering is not allowed.
*/
private void setColumnOrder(Object[] columnOrder) {
if (columnOrder == null || !isColumnReorderingAllowed()) {
return;
}
final LinkedList<Object> newOrder = new LinkedList<Object>();
for (int i = 0; i < columnOrder.length; i++) {
if (columnOrder[i] != null
&& visibleColumns.contains(columnOrder[i])) {
visibleColumns.remove(columnOrder[i]);
newOrder.add(columnOrder[i]);
}
}
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext();) {
final Object columnId = it.next();
if (!newOrder.contains(columnId)) {
newOrder.add(columnId);
}
}
visibleColumns = newOrder;
// Assure visual refresh
refreshRowCache();
}
/**
* Getter for property currentPageFirstItem.
*
* @return the Value of property currentPageFirstItem.
*/
public int getCurrentPageFirstItemIndex() {
return currentPageFirstItemIndex;
}
void setCurrentPageFirstItemIndex(int newIndex, boolean needsPageBufferReset) {
if (newIndex < 0) {
newIndex = 0;
}
/*
* minimize Container.size() calls which may be expensive. For example
* it may cause sql query.
*/
final int size = size();
/*
* The table is not capable of displaying an item in the container as
* the first if there are not enough items following the selected item
* so the whole table (pagelength) is filled.
*/
int maxIndex = size - pageLength;
if (maxIndex < 0) {
maxIndex = 0;
}
/*
* FIXME #7607 Take somehow into account the case where we want to
* scroll to the bottom so that the last row is completely visible even
* if (table height) / (row height) is not an integer. Reverted the
* original fix because of #8662 regression.
*/
if (newIndex > maxIndex) {
newIndex = maxIndex;
}
// Refresh first item id
if (items instanceof Container.Indexed) {
try {
currentPageFirstItemId = getIdByIndex(newIndex);
} catch (final IndexOutOfBoundsException e) {
currentPageFirstItemId = null;
}
currentPageFirstItemIndex = newIndex;
} else {
// For containers not supporting indexes, we must iterate the
// container forwards / backwards
// next available item forward or backward
currentPageFirstItemId = firstItemId();
// Go forwards in the middle of the list (respect borders)
while (currentPageFirstItemIndex < newIndex
&& !isLastId(currentPageFirstItemId)) {
currentPageFirstItemIndex++;
currentPageFirstItemId = nextItemId(currentPageFirstItemId);
}
// If we did hit the border
if (isLastId(currentPageFirstItemId)) {
currentPageFirstItemIndex = size - 1;
}
// Go backwards in the middle of the list (respect borders)
while (currentPageFirstItemIndex > newIndex
&& !isFirstId(currentPageFirstItemId)) {
currentPageFirstItemIndex--;
currentPageFirstItemId = prevItemId(currentPageFirstItemId);
}
// If we did hit the border
if (isFirstId(currentPageFirstItemId)) {
currentPageFirstItemIndex = 0;
}
// Go forwards once more
while (currentPageFirstItemIndex < newIndex
&& !isLastId(currentPageFirstItemId)) {
currentPageFirstItemIndex++;
currentPageFirstItemId = nextItemId(currentPageFirstItemId);
}
// If for some reason we do hit border again, override
// the user index request
if (isLastId(currentPageFirstItemId)) {
newIndex = currentPageFirstItemIndex = size - 1;
}
}
if (needsPageBufferReset) {
// Assures the visual refresh
refreshRowCache();
}
}
/**
* Setter for property currentPageFirstItem.
*
* @param newIndex
* the New value of property currentPageFirstItem.
*/
public void setCurrentPageFirstItemIndex(int newIndex) {
setCurrentPageFirstItemIndex(newIndex, true);
}
/**
* Getter for property pageBuffering.
*
* @deprecated functionality is not needed in ajax rendering model
*
* @return the Value of property pageBuffering.
*/
@Deprecated
public boolean isPageBufferingEnabled() {
return true;
}
/**
* Setter for property pageBuffering.
*
* @deprecated functionality is not needed in ajax rendering model
*
* @param pageBuffering
* the New value of property pageBuffering.
*/
@Deprecated
public void setPageBufferingEnabled(boolean pageBuffering) {
}
/**
* Getter for property selectable.
*
* <p>
* The table is not selectable by default.
* </p>
*
* @return the Value of property selectable.
*/
public boolean isSelectable() {
return selectable;
}
/**
* Setter for property selectable.
*
* <p>
* The table is not selectable by default.
* </p>
*
* @param selectable
* the New value of property selectable.
*/
public void setSelectable(boolean selectable) {
if (this.selectable != selectable) {
this.selectable = selectable;
requestRepaint();
}
}
/**
* Getter for property columnHeaderMode.
*
* @return the Value of property columnHeaderMode.
*/
public ColumnHeaderMode getColumnHeaderMode() {
return columnHeaderMode;
}
/**
* Setter for property columnHeaderMode.
*
* @param columnHeaderMode
* the New value of property columnHeaderMode.
*/
public void setColumnHeaderMode(ColumnHeaderMode columnHeaderMode) {
if (columnHeaderMode == null) {
throw new IllegalArgumentException(
"Column header mode can not be null");
}
if (columnHeaderMode != this.columnHeaderMode) {
this.columnHeaderMode = columnHeaderMode;
requestRepaint();
}
}
/**
* Refreshes the rows in the internal cache. Only if
* {@link #resetPageBuffer()} is called before this then all values are
* guaranteed to be recreated.
*/
protected void refreshRenderedCells() {
if (getParent() == null) {
return;
}
if (!isContentRefreshesEnabled) {
return;
}
// Collects the basic facts about the table page
final int pagelen = getPageLength();
int rows, totalRows;
rows = totalRows = size();
int firstIndex = Math
.min(getCurrentPageFirstItemIndex(), totalRows - 1);
if (rows > 0 && firstIndex >= 0) {
rows -= firstIndex;
}
if (pagelen > 0 && pagelen < rows) {
rows = pagelen;
}
// If "to be painted next" variables are set, use them
if (lastToBeRenderedInClient - firstToBeRenderedInClient > 0) {
rows = lastToBeRenderedInClient - firstToBeRenderedInClient + 1;
}
if (firstToBeRenderedInClient >= 0) {
if (firstToBeRenderedInClient < totalRows) {
firstIndex = firstToBeRenderedInClient;
} else {
firstIndex = totalRows - 1;
}
} else {
// initial load
// #8805 send one extra row in the beginning in case a partial
// row is shown on the UI
if (firstIndex > 0) {
firstIndex = firstIndex - 1;
rows = rows + 1;
}
firstToBeRenderedInClient = firstIndex;
}
if (totalRows > 0) {
if (rows + firstIndex > totalRows) {
rows = totalRows - firstIndex;
}
} else {
rows = 0;
}
// Saves the results to internal buffer
pageBuffer = getVisibleCellsNoCache(firstIndex, rows, true);
if (rows > 0) {
pageBufferFirstIndex = firstIndex;
}
setRowCacheInvalidated(true);
requestRepaint();
}
/**
* Requests that the Table should be repainted as soon as possible.
*
* Note that a {@code Table} does not necessarily repaint its contents when
* this method has been called. See {@link #refreshRowCache()} for forcing
* an update of the contents.
*/
@Override
public void requestRepaint() {
// Overridden only for javadoc
super.requestRepaint();
}
@Override
public void requestRepaintAll() {
super.requestRepaintAll();
// Avoid sending a partial repaint (#8714)
refreshRowCache();
}
private void removeRowsFromCacheAndFillBottom(int firstIndex, int rows) {
int totalCachedRows = pageBuffer[CELL_ITEMID].length;
int totalRows = size();
int firstIndexInPageBuffer = firstIndex - pageBufferFirstIndex;
/*
* firstIndexInPageBuffer is the first row to be removed. "rows" rows
* after that should be removed. If the page buffer does not contain
* that many rows, we only remove the rows that actually are in the page
* buffer.
*/
if (firstIndexInPageBuffer + rows > totalCachedRows) {
rows = totalCachedRows - firstIndexInPageBuffer;
}
/*
* Unregister components that will no longer be in the page buffer to
* make sure that no components leak.
*/
unregisterComponentsAndPropertiesInRows(firstIndex, rows);
/*
* The number of rows that should be in the cache after this operation
* is done (pageBuffer currently contains the expanded items).
*/
int newCachedRowCount = totalCachedRows;
if (newCachedRowCount + pageBufferFirstIndex > totalRows) {
newCachedRowCount = totalRows - pageBufferFirstIndex;
}
/*
* The index at which we should render the first row that does not come
* from the previous page buffer.
*/
int firstAppendedRowInPageBuffer = totalCachedRows - rows;
int firstAppendedRow = firstAppendedRowInPageBuffer
+ pageBufferFirstIndex;
/*
* Calculate the maximum number of new rows that we can add to the page
* buffer. Less than the rows we removed if the container does not
* contain that many items afterwards.
*/
int maxRowsToRender = (totalRows - firstAppendedRow);
int rowsToAdd = rows;
if (rowsToAdd > maxRowsToRender) {
rowsToAdd = maxRowsToRender;
}
Object[][] cells = null;
if (rowsToAdd > 0) {
cells = getVisibleCellsNoCache(firstAppendedRow, rowsToAdd, false);
}
/*
* Create the new cache buffer by copying the first rows from the old
* buffer, moving the following rows upwards and appending more rows if
* applicable.
*/
Object[][] newPageBuffer = new Object[pageBuffer.length][newCachedRowCount];
for (int i = 0; i < pageBuffer.length; i++) {
for (int row = 0; row < firstIndexInPageBuffer; row++) {
// Copy the first rows
newPageBuffer[i][row] = pageBuffer[i][row];
}
for (int row = firstIndexInPageBuffer; row < firstAppendedRowInPageBuffer; row++) {
// Move the rows that were after the expanded rows
newPageBuffer[i][row] = pageBuffer[i][row + rows];
}
for (int row = firstAppendedRowInPageBuffer; row < newCachedRowCount; row++) {
// Add the newly rendered rows. Only used if rowsToAdd > 0
// (cells != null)
newPageBuffer[i][row] = cells[i][row
- firstAppendedRowInPageBuffer];
}
}
pageBuffer = newPageBuffer;
}
private Object[][] getVisibleCellsUpdateCacheRows(int firstIndex, int rows) {
Object[][] cells = getVisibleCellsNoCache(firstIndex, rows, false);
int cacheIx = firstIndex - pageBufferFirstIndex;
// update the new rows in the cache.
int totalCachedRows = pageBuffer[CELL_ITEMID].length;
int end = Math.min(cacheIx + rows, totalCachedRows);
for (int ix = cacheIx; ix < end; ix++) {
for (int i = 0; i < pageBuffer.length; i++) {
pageBuffer[i][ix] = cells[i][ix - cacheIx];
}
}
return cells;
}
/**
* @param firstIndex
* The position where new rows should be inserted
* @param rows
* The maximum number of rows that should be inserted at position
* firstIndex. Less rows will be inserted if the page buffer is
* too small.
* @return
*/
private Object[][] getVisibleCellsInsertIntoCache(int firstIndex, int rows) {
getLogger().finest(
"Insert " + rows + " rows at index " + firstIndex
+ " to existing page buffer requested");
// Page buffer must not become larger than pageLength*cacheRate before
// or after the current page
int minPageBufferIndex = getCurrentPageFirstItemIndex()
- (int) (getPageLength() * getCacheRate());
if (minPageBufferIndex < 0) {
minPageBufferIndex = 0;
}
int maxPageBufferIndex = getCurrentPageFirstItemIndex()
+ (int) (getPageLength() * (1 + getCacheRate()));
int maxBufferSize = maxPageBufferIndex - minPageBufferIndex;
if (getPageLength() == 0) {
// If pageLength == 0 then all rows should be rendered
maxBufferSize = pageBuffer[0].length + rows;
}
/*
* Number of rows that were previously cached. This is not necessarily
* the same as pageLength if we do not have enough rows in the
* container.
*/
int currentlyCachedRowCount = pageBuffer[CELL_ITEMID].length;
/*
* firstIndexInPageBuffer is the offset in pageBuffer where the new rows
* will be inserted (firstIndex is the index in the whole table).
*
* E.g. scrolled down to row 1000: firstIndex==1010,
* pageBufferFirstIndex==1000 -> cacheIx==10
*/
int firstIndexInPageBuffer = firstIndex - pageBufferFirstIndex;
/* If rows > size available in page buffer */
if (firstIndexInPageBuffer + rows > maxBufferSize) {
rows = maxBufferSize - firstIndexInPageBuffer;
}
/*
* "rows" rows will be inserted at firstIndex. Find out how many old
* rows fall outside the new buffer so we can unregister components in
* the cache.
*/
/* All rows until the insertion point remain, always. */
int firstCacheRowToRemoveInPageBuffer = firstIndexInPageBuffer;
/*
* IF there is space remaining in the buffer after the rows have been
* inserted, we can keep more rows.
*/
int numberOfOldRowsAfterInsertedRows = maxBufferSize
- firstIndexInPageBuffer - rows;
if (numberOfOldRowsAfterInsertedRows > 0) {
firstCacheRowToRemoveInPageBuffer += numberOfOldRowsAfterInsertedRows;
}
if (firstCacheRowToRemoveInPageBuffer <= currentlyCachedRowCount) {
/*
* Unregister all components that fall beyond the cache limits after
* inserting the new rows.
*/
unregisterComponentsAndPropertiesInRows(
firstCacheRowToRemoveInPageBuffer + pageBufferFirstIndex,
currentlyCachedRowCount - firstCacheRowToRemoveInPageBuffer
+ pageBufferFirstIndex);
}
// Calculate the new cache size
int newCachedRowCount = currentlyCachedRowCount;
if (maxBufferSize == 0 || currentlyCachedRowCount < maxBufferSize) {
newCachedRowCount = currentlyCachedRowCount + rows;
if (maxBufferSize > 0 && newCachedRowCount > maxBufferSize) {
newCachedRowCount = maxBufferSize;
}
}
/* Paint the new rows into a separate buffer */
Object[][] cells = getVisibleCellsNoCache(firstIndex, rows, false);
/*
* Create the new cache buffer and fill it with the data from the old
* buffer as well as the inserted rows.
*/
Object[][] newPageBuffer = new Object[pageBuffer.length][newCachedRowCount];
for (int i = 0; i < pageBuffer.length; i++) {
for (int row = 0; row < firstIndexInPageBuffer; row++) {
// Copy the first rows
newPageBuffer[i][row] = pageBuffer[i][row];
}
for (int row = firstIndexInPageBuffer; row < firstIndexInPageBuffer
+ rows; row++) {
// Copy the newly created rows
newPageBuffer[i][row] = cells[i][row - firstIndexInPageBuffer];
}
for (int row = firstIndexInPageBuffer + rows; row < newCachedRowCount; row++) {
// Move the old rows down below the newly inserted rows
newPageBuffer[i][row] = pageBuffer[i][row - rows];
}
}
pageBuffer = newPageBuffer;
getLogger().finest(
"Page Buffer now contains "
+ pageBuffer[CELL_ITEMID].length
+ " rows ("
+ pageBufferFirstIndex
+ "-"
+ (pageBufferFirstIndex
+ pageBuffer[CELL_ITEMID].length - 1) + ")");
return cells;
}
/**
* Render rows with index "firstIndex" to "firstIndex+rows-1" to a new
* buffer.
*
* Reuses values from the current page buffer if the rows are found there.
*
* @param firstIndex
* @param rows
* @param replaceListeners
* @return
*/
private Object[][] getVisibleCellsNoCache(int firstIndex, int rows,
boolean replaceListeners) {
getLogger().finest(
"Render visible cells for rows " + firstIndex + "-"
+ (firstIndex + rows - 1));
final Object[] colids = getVisibleColumns();
final int cols = colids.length;
HashSet<Property<?>> oldListenedProperties = listenedProperties;
HashSet<Component> oldVisibleComponents = visibleComponents;
if (replaceListeners) {
// initialize the listener collections, this should only be done if
// the entire cache is refreshed (through refreshRenderedCells)
listenedProperties = new HashSet<Property<?>>();
visibleComponents = new HashSet<Component>();
}
Object[][] cells = new Object[cols + CELL_FIRSTCOL][rows];
if (rows == 0) {
unregisterPropertiesAndComponents(oldListenedProperties,
oldVisibleComponents);
return cells;
}
// Gets the first item id
Object id;
if (items instanceof Container.Indexed) {
id = getIdByIndex(firstIndex);
} else {
id = firstItemId();
for (int i = 0; i < firstIndex; i++) {
id = nextItemId(id);
}
}
final RowHeaderMode headmode = getRowHeaderMode();
final boolean[] iscomponent = new boolean[cols];
for (int i = 0; i < cols; i++) {
iscomponent[i] = columnGenerators.containsKey(colids[i])
|| Component.class.isAssignableFrom(getType(colids[i]));
}
int firstIndexNotInCache;
if (pageBuffer != null && pageBuffer[CELL_ITEMID].length > 0) {
firstIndexNotInCache = pageBufferFirstIndex
+ pageBuffer[CELL_ITEMID].length;
} else {
firstIndexNotInCache = -1;
}
// Creates the page contents
int filledRows = 0;
for (int i = 0; i < rows && id != null; i++) {
cells[CELL_ITEMID][i] = id;
cells[CELL_KEY][i] = itemIdMapper.key(id);
if (headmode != ROW_HEADER_MODE_HIDDEN) {
switch (headmode) {
case INDEX:
cells[CELL_HEADER][i] = String.valueOf(i + firstIndex + 1);
break;
default:
cells[CELL_HEADER][i] = getItemCaption(id);
}
cells[CELL_ICON][i] = getItemIcon(id);
}
GeneratedRow generatedRow = rowGenerator != null ? rowGenerator
.generateRow(this, id) : null;
cells[CELL_GENERATED_ROW][i] = generatedRow;
for (int j = 0; j < cols; j++) {
if (isColumnCollapsed(colids[j])) {
continue;
}
Property<?> p = null;
Object value = "";
boolean isGeneratedRow = generatedRow != null;
boolean isGeneratedColumn = columnGenerators
.containsKey(colids[j]);
boolean isGenerated = isGeneratedRow || isGeneratedColumn;
if (!isGenerated) {
p = getContainerProperty(id, colids[j]);
}
if (isGeneratedRow) {
if (generatedRow.isSpanColumns() && j > 0) {
value = null;
} else if (generatedRow.isSpanColumns() && j == 0
&& generatedRow.getValue() instanceof Component) {
value = generatedRow.getValue();
} else if (generatedRow.getText().length > j) {
value = generatedRow.getText()[j];
}
} else {
// check in current pageBuffer already has row
int index = firstIndex + i;
if (p != null || isGenerated) {
int indexInOldBuffer = index - pageBufferFirstIndex;
if (index < firstIndexNotInCache
&& index >= pageBufferFirstIndex
&& pageBuffer[CELL_GENERATED_ROW][indexInOldBuffer] == null
&& id.equals(pageBuffer[CELL_ITEMID][indexInOldBuffer])) {
// we already have data in our cache,
// recycle it instead of fetching it via
// getValue/getPropertyValue
value = pageBuffer[CELL_FIRSTCOL + j][indexInOldBuffer];
if (!isGeneratedColumn && iscomponent[j]
|| !(value instanceof Component)) {
listenProperty(p, oldListenedProperties);
}
} else {
if (isGeneratedColumn) {
ColumnGenerator cg = columnGenerators
.get(colids[j]);
value = cg.generateCell(this, id, colids[j]);
if (value != null
&& !(value instanceof Component)
&& !(value instanceof String)) {
// Avoid errors if a generator returns
// something
// other than a Component or a String
value = value.toString();
}
} else if (iscomponent[j]) {
value = p.getValue();
listenProperty(p, oldListenedProperties);
} else if (p != null) {
value = getPropertyValue(id, colids[j], p);
/*
* If returned value is Component (via
* fieldfactory or overridden getPropertyValue)
* we excpect it to listen property value
* changes. Otherwise if property emits value
* change events, table will start to listen
* them and refresh content when needed.
*/
if (!(value instanceof Component)) {
listenProperty(p, oldListenedProperties);
}
} else {
value = getPropertyValue(id, colids[j], null);
}
}
}
}
if (value instanceof Component) {
registerComponent((Component) value);
}
cells[CELL_FIRSTCOL + j][i] = value;
}
// Gets the next item id
if (items instanceof Container.Indexed) {
int index = firstIndex + i + 1;
if (index < size()) {
id = getIdByIndex(index);
} else {
id = null;
}
} else {
id = nextItemId(id);
}
filledRows++;
}
// Assures that all the rows of the cell-buffer are valid
if (filledRows != cells[0].length) {
final Object[][] temp = new Object[cells.length][filledRows];
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < filledRows; j++) {
temp[i][j] = cells[i][j];
}
}
cells = temp;
}
unregisterPropertiesAndComponents(oldListenedProperties,
oldVisibleComponents);
return cells;
}
protected void registerComponent(Component component) {
getLogger().finest(
"Registered " + component.getClass().getSimpleName() + ": "
+ component.getCaption());
if (component.getParent() != this) {
component.setParent(this);
}
visibleComponents.add(component);
}
private void listenProperty(Property<?> p,
HashSet<Property<?>> oldListenedProperties) {
if (p instanceof Property.ValueChangeNotifier) {
if (oldListenedProperties == null
|| !oldListenedProperties.contains(p)) {
((Property.ValueChangeNotifier) p).addListener(this);
}
/*
* register listened properties, so we can do proper cleanup to free
* memory. Essential if table has loads of data and it is used for a
* long time.
*/
listenedProperties.add(p);
}
}
/**
* @param firstIx
* Index of the first row to process. Global index, not relative
* to page buffer.
* @param count
*/
private void unregisterComponentsAndPropertiesInRows(int firstIx, int count) {
getLogger().finest(
"Unregistering components in rows " + firstIx + "-"
+ (firstIx + count - 1));
Object[] colids = getVisibleColumns();
if (pageBuffer != null && pageBuffer[CELL_ITEMID].length > 0) {
int bufSize = pageBuffer[CELL_ITEMID].length;
int ix = firstIx - pageBufferFirstIndex;
ix = ix < 0 ? 0 : ix;
if (ix < bufSize) {
count = count > bufSize - ix ? bufSize - ix : count;
for (int i = 0; i < count; i++) {
for (int c = 0; c < colids.length; c++) {
Object cellVal = pageBuffer[CELL_FIRSTCOL + c][i + ix];
if (cellVal instanceof Component
&& visibleComponents.contains(cellVal)) {
visibleComponents.remove(cellVal);
unregisterComponent((Component) cellVal);
} else {
Property<?> p = getContainerProperty(
pageBuffer[CELL_ITEMID][i + ix], colids[c]);
if (p instanceof ValueChangeNotifier
&& listenedProperties.contains(p)) {
listenedProperties.remove(p);
((ValueChangeNotifier) p).removeListener(this);
}
}
}
}
}
}
}
/**
* Helper method to remove listeners and maintain correct component
* hierarchy. Detaches properties and components if those are no more
* rendered in client.
*
* @param oldListenedProperties
* set of properties that where listened in last render
* @param oldVisibleComponents
* set of components that where attached in last render
*/
private void unregisterPropertiesAndComponents(
HashSet<Property<?>> oldListenedProperties,
HashSet<Component> oldVisibleComponents) {
if (oldVisibleComponents != null) {
for (final Iterator<Component> i = oldVisibleComponents.iterator(); i
.hasNext();) {
Component c = i.next();
if (!visibleComponents.contains(c)) {
unregisterComponent(c);
}
}
}
if (oldListenedProperties != null) {
for (final Iterator<Property<?>> i = oldListenedProperties
.iterator(); i.hasNext();) {
Property.ValueChangeNotifier o = (ValueChangeNotifier) i.next();
if (!listenedProperties.contains(o)) {
o.removeListener(this);
}
}
}
}
/**
* This method cleans up a Component that has been generated when Table is
* in editable mode. The component needs to be detached from its parent and
* if it is a field, it needs to be detached from its property data source
* in order to allow garbage collection to take care of removing the unused
* component from memory.
*
* Override this method and getPropertyValue(Object, Object, Property) with
* custom logic if you need to deal with buffered fields.
*
* @see #getPropertyValue(Object, Object, Property)
*
* @param oldVisibleComponents
* a set of components that should be unregistered.
*/
protected void unregisterComponent(Component component) {
getLogger().finest(
"Unregistered " + component.getClass().getSimpleName() + ": "
+ component.getCaption());
component.setParent(null);
/*
* Also remove property data sources to unregister listeners keeping the
* fields in memory.
*/
if (component instanceof Field) {
Field<?> field = (Field<?>) component;
Property<?> associatedProperty = associatedProperties
.remove(component);
if (associatedProperty != null
&& field.getPropertyDataSource() == associatedProperty) {
// Remove the property data source only if it's the one we
// added in getPropertyValue
field.setPropertyDataSource(null);
}
}
}
/**
* Refreshes the current page contents.
*
* @deprecated should not need to be used
*/
@Deprecated
public void refreshCurrentPage() {
}
/**
* Sets the row header mode.
* <p>
* The mode can be one of the following ones:
* <ul>
* <li>{@link #ROW_HEADER_MODE_HIDDEN}: The row captions are hidden.</li>
* <li>{@link #ROW_HEADER_MODE_ID}: Items Id-objects <code>toString()</code>
* is used as row caption.
* <li>{@link #ROW_HEADER_MODE_ITEM}: Item-objects <code>toString()</code>
* is used as row caption.
* <li>{@link #ROW_HEADER_MODE_PROPERTY}: Property set with
* {@link #setItemCaptionPropertyId(Object)} is used as row header.
* <li>{@link #ROW_HEADER_MODE_EXPLICIT_DEFAULTS_ID}: Items Id-objects
* <code>toString()</code> is used as row header. If caption is explicitly
* specified, it overrides the id-caption.
* <li>{@link #ROW_HEADER_MODE_EXPLICIT}: The row headers must be explicitly
* specified.</li>
* <li>{@link #ROW_HEADER_MODE_INDEX}: The index of the item is used as row
* caption. The index mode can only be used with the containers implementing
* <code>Container.Indexed</code> interface.</li>
* </ul>
* The default value is {@link #ROW_HEADER_MODE_HIDDEN}
* </p>
*
* @param mode
* the One of the modes listed above.
*/
public void setRowHeaderMode(RowHeaderMode mode) {
if (mode != null) {
rowHeaderMode = mode;
if (mode != RowHeaderMode.HIDDEN) {
setItemCaptionMode(mode.getItemCaptionMode());
}
// Assures the visual refresh. No need to reset the page buffer
// before
// as the content has not changed, only the alignments.
refreshRenderedCells();
}
}
/**
* Gets the row header mode.
*
* @return the Row header mode.
* @see #setRowHeaderMode(int)
*/
public RowHeaderMode getRowHeaderMode() {
return rowHeaderMode;
}
/**
* Adds the new row to table and fill the visible cells (except generated
* columns) with given values.
*
* @param cells
* the Object array that is used for filling the visible cells
* new row. The types must be settable to visible column property
* types.
* @param itemId
* the Id the new row. If null, a new id is automatically
* assigned. If given, the table cant already have a item with
* given id.
* @return Returns item id for the new row. Returns null if operation fails.
*/
public Object addItem(Object[] cells, Object itemId)
throws UnsupportedOperationException {
// remove generated columns from the list of columns being assigned
final LinkedList<Object> availableCols = new LinkedList<Object>();
for (Iterator<Object> it = visibleColumns.iterator(); it.hasNext();) {
Object id = it.next();
if (!columnGenerators.containsKey(id)) {
availableCols.add(id);
}
}
// Checks that a correct number of cells are given
if (cells.length != availableCols.size()) {
return null;
}
// Creates new item
Item item;
if (itemId == null) {
itemId = items.addItem();
if (itemId == null) {
return null;
}
item = items.getItem(itemId);
} else {
item = items.addItem(itemId);
}
if (item == null) {
return null;
}
// Fills the item properties
for (int i = 0; i < availableCols.size(); i++) {
item.getItemProperty(availableCols.get(i)).setValue(cells[i]);
}
if (!(items instanceof Container.ItemSetChangeNotifier)) {
refreshRowCache();
}
return itemId;
}
/**
* Discards and recreates the internal row cache. Call this if you make
* changes that affect the rows but the information about the changes are
* not automatically propagated to the Table.
* <p>
* Do not call this e.g. if you have updated the data model through a
* Property. These types of changes are automatically propagated to the
* Table.
* <p>
* A typical case when this is needed is if you update a generator (e.g.
* CellStyleGenerator) and want to ensure that the rows are redrawn with new
* styles.
* <p>
* <i>Note that calling this method is not cheap so avoid calling it
* unnecessarily.</i>
*
* @since 6.7.2
*/
public void refreshRowCache() {
resetPageBuffer();
refreshRenderedCells();
}
@Override
public void setContainerDataSource(Container newDataSource) {
disableContentRefreshing();
if (newDataSource == null) {
newDataSource = new IndexedContainer();
}
// Assures that the data source is ordered by making unordered
// containers ordered by wrapping them
if (newDataSource instanceof Container.Ordered) {
super.setContainerDataSource(newDataSource);
} else {
super.setContainerDataSource(new ContainerOrderedWrapper(
newDataSource));
}
// Resets page position
currentPageFirstItemId = null;
currentPageFirstItemIndex = 0;
// Resets column properties
if (collapsedColumns != null) {
collapsedColumns.clear();
}
// columnGenerators 'override' properties, don't add the same id twice
Collection<Object> col = new LinkedList<Object>();
for (Iterator<?> it = getContainerPropertyIds().iterator(); it
.hasNext();) {
Object id = it.next();
if (columnGenerators == null || !columnGenerators.containsKey(id)) {
col.add(id);
}
}
// generators added last
if (columnGenerators != null && columnGenerators.size() > 0) {
col.addAll(columnGenerators.keySet());
}
setVisibleColumns(col.toArray());
// Assure visual refresh
resetPageBuffer();
enableContentRefreshing(true);
}
/**
* Gets items ids from a range of key values
*
* @param startRowKey
* The start key
* @param endRowKey
* The end key
* @return
*/
private LinkedHashSet<Object> getItemIdsInRange(Object itemId,
final int length) {
LinkedHashSet<Object> ids = new LinkedHashSet<Object>();
for (int i = 0; i < length; i++) {
assert itemId != null; // should not be null unless client-server
// are out of sync
ids.add(itemId);
itemId = nextItemId(itemId);
}
return ids;
}
/**
* Handles selection if selection is a multiselection
*
* @param variables
* The variables
*/
private void handleSelectedItems(Map<String, Object> variables) {
final String[] ka = (String[]) variables.get("selected");
final String[] ranges = (String[]) variables.get("selectedRanges");
Set<Object> renderedButNotSelectedItemIds = getCurrentlyRenderedItemIds();
@SuppressWarnings("unchecked")
HashSet<Object> newValue = new LinkedHashSet<Object>(
(Collection<Object>) getValue());
if (variables.containsKey("clearSelections")) {
// the client side has instructed to swipe all previous selections
newValue.clear();
}
/*
* Then add (possibly some of them back) rows that are currently
* selected on the client side (the ones that the client side is aware
* of).
*/
for (int i = 0; i < ka.length; i++) {
// key to id
final Object id = itemIdMapper.get(ka[i]);
if (!isNullSelectionAllowed()
&& (id == null || id == getNullSelectionItemId())) {
// skip empty selection if nullselection is not allowed
requestRepaint();
} else if (id != null && containsId(id)) {
newValue.add(id);
renderedButNotSelectedItemIds.remove(id);
}
}
/* Add range items aka shift clicked multiselection areas */
if (ranges != null) {
for (String range : ranges) {
String[] split = range.split("-");
Object startItemId = itemIdMapper.get(split[0]);
int length = Integer.valueOf(split[1]);
LinkedHashSet<Object> itemIdsInRange = getItemIdsInRange(
startItemId, length);
newValue.addAll(itemIdsInRange);
renderedButNotSelectedItemIds.removeAll(itemIdsInRange);
}
}
/*
* finally clear all currently rendered rows (the ones that the client
* side counterpart is aware of) that the client didn't send as selected
*/
newValue.removeAll(renderedButNotSelectedItemIds);
if (!isNullSelectionAllowed() && newValue.isEmpty()) {
// empty selection not allowed, keep old value
requestRepaint();
return;
}
setValue(newValue, true);
}
private Set<Object> getCurrentlyRenderedItemIds() {
HashSet<Object> ids = new HashSet<Object>();
if (pageBuffer != null) {
for (int i = 0; i < pageBuffer[CELL_ITEMID].length; i++) {
ids.add(pageBuffer[CELL_ITEMID][i]);
}
}
return ids;
}
/* Component basics */
/**
* Invoked when the value of a variable has changed.
*
* @see com.vaadin.ui.Select#changeVariables(java.lang.Object,
* java.util.Map)
*/
@Override
public void changeVariables(Object source, Map<String, Object> variables) {
boolean clientNeedsContentRefresh = false;
handleClickEvent(variables);
handleColumnResizeEvent(variables);
handleColumnWidthUpdates(variables);
disableContentRefreshing();
if (!isSelectable() && variables.containsKey("selected")) {
// Not-selectable is a special case, AbstractSelect does not support
// TODO could be optimized.
variables = new HashMap<String, Object>(variables);
variables.remove("selected");
}
/*
* The AbstractSelect cannot handle the multiselection properly, instead
* we handle it ourself
*/
else if (isSelectable() && isMultiSelect()
&& variables.containsKey("selected")
&& multiSelectMode == MultiSelectMode.DEFAULT) {
handleSelectedItems(variables);
variables = new HashMap<String, Object>(variables);
variables.remove("selected");
}
super.changeVariables(source, variables);
// Client might update the pagelength if Table height is fixed
if (variables.containsKey("pagelength")) {
// Sets pageLength directly to avoid repaint that setter causes
pageLength = (Integer) variables.get("pagelength");
}
// Page start index
if (variables.containsKey("firstvisible")) {
final Integer value = (Integer) variables.get("firstvisible");
if (value != null) {
setCurrentPageFirstItemIndex(value.intValue(), false);
}
}
// Sets requested firstrow and rows for the next paint
if (variables.containsKey("reqfirstrow")
|| variables.containsKey("reqrows")) {
try {
firstToBeRenderedInClient = ((Integer) variables
.get("firstToBeRendered")).intValue();
lastToBeRenderedInClient = ((Integer) variables
.get("lastToBeRendered")).intValue();
} catch (Exception e) {
// FIXME: Handle exception
getLogger().log(Level.FINER,
"Could not parse the first and/or last rows.", e);
}
// respect suggested rows only if table is not otherwise updated
// (row caches emptied by other event)
if (!containerChangeToBeRendered) {
Integer value = (Integer) variables.get("reqfirstrow");
if (value != null) {
reqFirstRowToPaint = value.intValue();
}
value = (Integer) variables.get("reqrows");
if (value != null) {
reqRowsToPaint = value.intValue();
// sanity check
if (reqFirstRowToPaint + reqRowsToPaint > size()) {
reqRowsToPaint = size() - reqFirstRowToPaint;
}
}
}
getLogger().finest(
"Client wants rows " + reqFirstRowToPaint + "-"
+ (reqFirstRowToPaint + reqRowsToPaint - 1));
clientNeedsContentRefresh = true;
}
if (isSortEnabled()) {
// Sorting
boolean doSort = false;
if (variables.containsKey("sortcolumn")) {
final String colId = (String) variables.get("sortcolumn");
if (colId != null && !"".equals(colId) && !"null".equals(colId)) {
final Object id = columnIdMap.get(colId);
setSortContainerPropertyId(id, false);
doSort = true;
}
}
if (variables.containsKey("sortascending")) {
final boolean state = ((Boolean) variables.get("sortascending"))
.booleanValue();
if (state != sortAscending) {
setSortAscending(state, false);
doSort = true;
}
}
if (doSort) {
this.sort();
resetPageBuffer();
}
}
// Dynamic column hide/show and order
// Update visible columns
if (isColumnCollapsingAllowed()) {
if (variables.containsKey("collapsedcolumns")) {
try {
final Object[] ids = (Object[]) variables
.get("collapsedcolumns");
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext();) {
setColumnCollapsed(it.next(), false);
}
for (int i = 0; i < ids.length; i++) {
setColumnCollapsed(columnIdMap.get(ids[i].toString()),
true);
}
} catch (final Exception e) {
// FIXME: Handle exception
getLogger().log(Level.FINER,
"Could not determine column collapsing state", e);
}
clientNeedsContentRefresh = true;
}
}
if (isColumnReorderingAllowed()) {
if (variables.containsKey("columnorder")) {
try {
final Object[] ids = (Object[]) variables
.get("columnorder");
// need a real Object[], ids can be a String[]
final Object[] idsTemp = new Object[ids.length];
for (int i = 0; i < ids.length; i++) {
idsTemp[i] = columnIdMap.get(ids[i].toString());
}
setColumnOrder(idsTemp);
if (hasListeners(ColumnReorderEvent.class)) {
fireEvent(new ColumnReorderEvent(this));
}
} catch (final Exception e) {
// FIXME: Handle exception
getLogger().log(Level.FINER,
"Could not determine column reordering state", e);
}
clientNeedsContentRefresh = true;
}
}
enableContentRefreshing(clientNeedsContentRefresh);
// Actions
if (variables.containsKey("action")) {
final StringTokenizer st = new StringTokenizer(
(String) variables.get("action"), ",");
if (st.countTokens() == 2) {
final Object itemId = itemIdMapper.get(st.nextToken());
final Action action = actionMapper.get(st.nextToken());
if (action != null && (itemId == null || containsId(itemId))
&& actionHandlers != null) {
for (Handler ah : actionHandlers) {
ah.handleAction(action, this, itemId);
}
}
}
}
}
/**
* Handles click event
*
* @param variables
*/
private void handleClickEvent(Map<String, Object> variables) {
// Item click event
if (variables.containsKey("clickEvent")) {
String key = (String) variables.get("clickedKey");
Object itemId = itemIdMapper.get(key);
Object propertyId = null;
String colkey = (String) variables.get("clickedColKey");
// click is not necessary on a property
if (colkey != null) {
propertyId = columnIdMap.get(colkey);
}
MouseEventDetails evt = MouseEventDetails
.deSerialize((String) variables.get("clickEvent"));
Item item = getItem(itemId);
if (item != null) {
fireEvent(new ItemClickEvent(this, item, itemId, propertyId,
evt));
}
}
// Header click event
else if (variables.containsKey("headerClickEvent")) {
MouseEventDetails details = MouseEventDetails
.deSerialize((String) variables.get("headerClickEvent"));
Object cid = variables.get("headerClickCID");
Object propertyId = null;
if (cid != null) {
propertyId = columnIdMap.get(cid.toString());
}
fireEvent(new HeaderClickEvent(this, propertyId, details));
}
// Footer click event
else if (variables.containsKey("footerClickEvent")) {
MouseEventDetails details = MouseEventDetails
.deSerialize((String) variables.get("footerClickEvent"));
Object cid = variables.get("footerClickCID");
Object propertyId = null;
if (cid != null) {
propertyId = columnIdMap.get(cid.toString());
}
fireEvent(new FooterClickEvent(this, propertyId, details));
}
}
/**
* Handles the column resize event sent by the client.
*
* @param variables
*/
private void handleColumnResizeEvent(Map<String, Object> variables) {
if (variables.containsKey("columnResizeEventColumn")) {
Object cid = variables.get("columnResizeEventColumn");
Object propertyId = null;
if (cid != null) {
propertyId = columnIdMap.get(cid.toString());
Object prev = variables.get("columnResizeEventPrev");
int previousWidth = -1;
if (prev != null) {
previousWidth = Integer.valueOf(prev.toString());
}
Object curr = variables.get("columnResizeEventCurr");
int currentWidth = -1;
if (curr != null) {
currentWidth = Integer.valueOf(curr.toString());
}
fireColumnResizeEvent(propertyId, previousWidth, currentWidth);
}
}
}
private void fireColumnResizeEvent(Object propertyId, int previousWidth,
int currentWidth) {
/*
* Update the sizes on the server side. If a column previously had a
* expand ratio and the user resized the column then the expand ratio
* will be turned into a static pixel size.
*/
setColumnWidth(propertyId, currentWidth);
fireEvent(new ColumnResizeEvent(this, propertyId, previousWidth,
currentWidth));
}
private void handleColumnWidthUpdates(Map<String, Object> variables) {
if (variables.containsKey("columnWidthUpdates")) {
String[] events = (String[]) variables.get("columnWidthUpdates");
for (String str : events) {
String[] eventDetails = str.split(":");
Object propertyId = columnIdMap.get(eventDetails[0]);
if (propertyId == null) {
propertyId = ROW_HEADER_FAKE_PROPERTY_ID;
}
int width = Integer.valueOf(eventDetails[1]);
setColumnWidth(propertyId, width);
}
}
}
/**
* Go to mode where content updates are not done. This is due we want to
* bypass expensive content for some reason (like when we know we may have
* other content changes on their way).
*
* @return true if content refresh flag was enabled prior this call
*/
protected boolean disableContentRefreshing() {
boolean wasDisabled = isContentRefreshesEnabled;
isContentRefreshesEnabled = false;
return wasDisabled;
}
/**
* Go to mode where content content refreshing has effect.
*
* @param refreshContent
* true if content refresh needs to be done
*/
protected void enableContentRefreshing(boolean refreshContent) {
isContentRefreshesEnabled = true;
if (refreshContent) {
refreshRenderedCells();
// Ensure that client gets a response
requestRepaint();
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.AbstractSelect#paintContent(com.vaadin.
* terminal.PaintTarget)
*/
@Override
public void paintContent(PaintTarget target) throws PaintException {
/*
* Body actions - Actions which has the target null and can be invoked
* by right clicking on the table body.
*/
final Set<Action> actionSet = findAndPaintBodyActions(target);
final Object[][] cells = getVisibleCells();
int rows = findNumRowsToPaint(target, cells);
int total = size();
if (shouldHideNullSelectionItem()) {
total--;
rows--;
}
// Table attributes
paintTableAttributes(target, rows, total);
paintVisibleColumnOrder(target);
// Rows
if (isPartialRowUpdate() && painted && !target.isFullRepaint()) {
paintPartialRowUpdate(target, actionSet);
/*
* Send the page buffer indexes to ensure that the client side stays
* in sync. Otherwise we _might_ have the situation where the client
* side discards too few or too many rows, causing out of sync
* issues.
*
* This could probably be done for full repaints also to simplify
* the client side.
*/
int pageBufferLastIndex = pageBufferFirstIndex
+ pageBuffer[CELL_ITEMID].length - 1;
target.addAttribute(TableConstants.ATTRIBUTE_PAGEBUFFER_FIRST,
pageBufferFirstIndex);
target.addAttribute(TableConstants.ATTRIBUTE_PAGEBUFFER_LAST,
pageBufferLastIndex);
} else if (target.isFullRepaint() || isRowCacheInvalidated()) {
paintRows(target, cells, actionSet);
setRowCacheInvalidated(false);
}
paintSorting(target);
resetVariablesAndPageBuffer(target);
// Actions
paintActions(target, actionSet);
paintColumnOrder(target);
// Available columns
paintAvailableColumns(target);
paintVisibleColumns(target);
if (keyMapperReset) {
keyMapperReset = false;
target.addAttribute(TableConstants.ATTRIBUTE_KEY_MAPPER_RESET, true);
}
if (dropHandler != null) {
dropHandler.getAcceptCriterion().paint(target);
}
painted = true;
}
private void setRowCacheInvalidated(boolean invalidated) {
rowCacheInvalidated = invalidated;
}
protected boolean isRowCacheInvalidated() {
return rowCacheInvalidated;
}
private void paintPartialRowUpdate(PaintTarget target, Set<Action> actionSet)
throws PaintException {
paintPartialRowUpdates(target, actionSet);
paintPartialRowAdditions(target, actionSet);
}
private void paintPartialRowUpdates(PaintTarget target,
Set<Action> actionSet) throws PaintException {
final boolean[] iscomponent = findCellsWithComponents();
int firstIx = getFirstUpdatedItemIndex();
int count = getUpdatedRowCount();
target.startTag("urows");
target.addAttribute("firsturowix", firstIx);
target.addAttribute("numurows", count);
// Partial row updates bypass the normal caching mechanism.
Object[][] cells = getVisibleCellsUpdateCacheRows(firstIx, count);
for (int indexInRowbuffer = 0; indexInRowbuffer < count; indexInRowbuffer++) {
final Object itemId = cells[CELL_ITEMID][indexInRowbuffer];
if (shouldHideNullSelectionItem()) {
// Remove null selection item if null selection is not allowed
continue;
}
paintRow(target, cells, isEditable(), actionSet, iscomponent,
indexInRowbuffer, itemId);
}
target.endTag("urows");
}
private void paintPartialRowAdditions(PaintTarget target,
Set<Action> actionSet) throws PaintException {
final boolean[] iscomponent = findCellsWithComponents();
int firstIx = getFirstAddedItemIndex();
int count = getAddedRowCount();
target.startTag("prows");
if (!shouldHideAddedRows()) {
getLogger().finest(
"Paint rows for add. Index: " + firstIx + ", count: "
+ count + ".");
// Partial row additions bypass the normal caching mechanism.
Object[][] cells = getVisibleCellsInsertIntoCache(firstIx, count);
if (cells[0].length < count) {
// delete the rows below, since they will fall beyond the cache
// page.
target.addAttribute("delbelow", true);
count = cells[0].length;
}
for (int indexInRowbuffer = 0; indexInRowbuffer < count; indexInRowbuffer++) {
final Object itemId = cells[CELL_ITEMID][indexInRowbuffer];
if (shouldHideNullSelectionItem()) {
// Remove null selection item if null selection is not
// allowed
continue;
}
paintRow(target, cells, isEditable(), actionSet, iscomponent,
indexInRowbuffer, itemId);
}
} else {
getLogger().finest(
"Paint rows for remove. Index: " + firstIx + ", count: "
+ count + ".");
removeRowsFromCacheAndFillBottom(firstIx, count);
target.addAttribute("hide", true);
}
target.addAttribute("firstprowix", firstIx);
target.addAttribute("numprows", count);
target.endTag("prows");
}
/**
* Subclass and override this to enable partial row updates and additions,
* which bypass the normal caching mechanism. This is useful for e.g.
* TreeTable.
*
* @return true if this update is a partial row update, false if not. For
* plain Table it is always false.
*/
protected boolean isPartialRowUpdate() {
return false;
}
/**
* Subclass and override this to enable partial row additions, bypassing the
* normal caching mechanism. This is useful for e.g. TreeTable, where
* expanding a node should only fetch and add the items inside of that node.
*
* @return The index of the first added item. For plain Table it is always
* 0.
*/
protected int getFirstAddedItemIndex() {
return 0;
}
/**
* Subclass and override this to enable partial row additions, bypassing the
* normal caching mechanism. This is useful for e.g. TreeTable, where
* expanding a node should only fetch and add the items inside of that node.
*
* @return the number of rows to be added, starting at the index returned by
* {@link #getFirstAddedItemIndex()}. For plain Table it is always
* 0.
*/
protected int getAddedRowCount() {
return 0;
}
/**
* Subclass and override this to enable removing of rows, bypassing the
* normal caching and lazy loading mechanism. This is useful for e.g.
* TreeTable, when you need to hide certain rows as a node is collapsed.
*
* This should return true if the rows pointed to by
* {@link #getFirstAddedItemIndex()} and {@link #getAddedRowCount()} should
* be hidden instead of added.
*
* @return whether the rows to add (see {@link #getFirstAddedItemIndex()}
* and {@link #getAddedRowCount()}) should be added or hidden. For
* plain Table it is always false.
*/
protected boolean shouldHideAddedRows() {
return false;
}
/**
* Subclass and override this to enable partial row updates, bypassing the
* normal caching and lazy loading mechanism. This is useful for updating
* the state of certain rows, e.g. in the TreeTable the collapsed state of a
* single node is updated using this mechanism.
*
* @return the index of the first item to be updated. For plain Table it is
* always 0.
*/
protected int getFirstUpdatedItemIndex() {
return 0;
}
/**
* Subclass and override this to enable partial row updates, bypassing the
* normal caching and lazy loading mechanism. This is useful for updating
* the state of certain rows, e.g. in the TreeTable the collapsed state of a
* single node is updated using this mechanism.
*
* @return the number of rows to update, starting at the index returned by
* {@link #getFirstUpdatedItemIndex()}. For plain table it is always
* 0.
*/
protected int getUpdatedRowCount() {
return 0;
}
private void paintTableAttributes(PaintTarget target, int rows, int total)
throws PaintException {
paintTabIndex(target);
paintDragMode(target);
paintSelectMode(target);
if (cacheRate != CACHE_RATE_DEFAULT) {
target.addAttribute("cr", cacheRate);
}
target.addAttribute("cols", getVisibleColumns().length);
target.addAttribute("rows", rows);
target.addAttribute("firstrow",
(reqFirstRowToPaint >= 0 ? reqFirstRowToPaint
: firstToBeRenderedInClient));
target.addAttribute("totalrows", total);
if (getPageLength() != 0) {
target.addAttribute("pagelength", getPageLength());
}
if (areColumnHeadersEnabled()) {
target.addAttribute("colheaders", true);
}
if (rowHeadersAreEnabled()) {
target.addAttribute("rowheaders", true);
}
target.addAttribute("colfooters", columnFootersVisible);
// The cursors are only shown on pageable table
if (getCurrentPageFirstItemIndex() != 0 || getPageLength() > 0) {
target.addVariable(this, "firstvisible",
getCurrentPageFirstItemIndex());
}
}
/**
* Resets and paints "to be painted next" variables. Also reset pageBuffer
*/
private void resetVariablesAndPageBuffer(PaintTarget target)
throws PaintException {
reqFirstRowToPaint = -1;
reqRowsToPaint = -1;
containerChangeToBeRendered = false;
target.addVariable(this, "reqrows", reqRowsToPaint);
target.addVariable(this, "reqfirstrow", reqFirstRowToPaint);
}
private boolean areColumnHeadersEnabled() {
return getColumnHeaderMode() != ColumnHeaderMode.HIDDEN;
}
private void paintVisibleColumns(PaintTarget target) throws PaintException {
target.startTag("visiblecolumns");
if (rowHeadersAreEnabled()) {
target.startTag("column");
target.addAttribute("cid", ROW_HEADER_COLUMN_KEY);
paintColumnWidth(target, ROW_HEADER_FAKE_PROPERTY_ID);
target.endTag("column");
}
final Collection<?> sortables = getSortableContainerPropertyIds();
for (Object colId : visibleColumns) {
if (colId != null) {
target.startTag("column");
target.addAttribute("cid", columnIdMap.key(colId));
final String head = getColumnHeader(colId);
target.addAttribute("caption", (head != null ? head : ""));
final String foot = getColumnFooter(colId);
target.addAttribute("fcaption", (foot != null ? foot : ""));
if (isColumnCollapsed(colId)) {
target.addAttribute("collapsed", true);
}
if (areColumnHeadersEnabled()) {
if (getColumnIcon(colId) != null) {
target.addAttribute("icon", getColumnIcon(colId));
}
if (sortables.contains(colId)) {
target.addAttribute("sortable", true);
}
}
if (!Align.LEFT.equals(getColumnAlignment(colId))) {
target.addAttribute("align", getColumnAlignment(colId)
.toString());
}
paintColumnWidth(target, colId);
target.endTag("column");
}
}
target.endTag("visiblecolumns");
}
private void paintAvailableColumns(PaintTarget target)
throws PaintException {
if (columnCollapsingAllowed) {
final HashSet<Object> collapsedCols = new HashSet<Object>();
for (Object colId : visibleColumns) {
if (isColumnCollapsed(colId)) {
collapsedCols.add(colId);
}
}
final String[] collapsedKeys = new String[collapsedCols.size()];
int nextColumn = 0;
for (Object colId : visibleColumns) {
if (isColumnCollapsed(colId)) {
collapsedKeys[nextColumn++] = columnIdMap.key(colId);
}
}
target.addVariable(this, "collapsedcolumns", collapsedKeys);
final String[] noncollapsibleKeys = new String[noncollapsibleColumns
.size()];
nextColumn = 0;
for (Object colId : noncollapsibleColumns) {
noncollapsibleKeys[nextColumn++] = columnIdMap.key(colId);
}
target.addVariable(this, "noncollapsiblecolumns",
noncollapsibleKeys);
}
}
private void paintActions(PaintTarget target, final Set<Action> actionSet)
throws PaintException {
if (!actionSet.isEmpty()) {
target.addVariable(this, "action", "");
target.startTag("actions");
for (Action a : actionSet) {
target.startTag("action");
if (a.getCaption() != null) {
target.addAttribute("caption", a.getCaption());
}
if (a.getIcon() != null) {
target.addAttribute("icon", a.getIcon());
}
target.addAttribute("key", actionMapper.key(a));
target.endTag("action");
}
target.endTag("actions");
}
}
private void paintColumnOrder(PaintTarget target) throws PaintException {
if (columnReorderingAllowed) {
final String[] colorder = new String[visibleColumns.size()];
int i = 0;
for (Object colId : visibleColumns) {
colorder[i++] = columnIdMap.key(colId);
}
target.addVariable(this, "columnorder", colorder);
}
}
private void paintSorting(PaintTarget target) throws PaintException {
// Sorting
if (getContainerDataSource() instanceof Container.Sortable) {
target.addVariable(this, "sortcolumn",
columnIdMap.key(sortContainerPropertyId));
target.addVariable(this, "sortascending", sortAscending);
}
}
private void paintRows(PaintTarget target, final Object[][] cells,
final Set<Action> actionSet) throws PaintException {
final boolean[] iscomponent = findCellsWithComponents();
target.startTag("rows");
// cells array contains all that are supposed to be visible on client,
// but we'll start from the one requested by client
int start = 0;
if (reqFirstRowToPaint != -1 && firstToBeRenderedInClient != -1) {
start = reqFirstRowToPaint - firstToBeRenderedInClient;
}
int end = cells[0].length;
if (reqRowsToPaint != -1) {
end = start + reqRowsToPaint;
}
// sanity check
if (lastToBeRenderedInClient != -1 && lastToBeRenderedInClient < end) {
end = lastToBeRenderedInClient + 1;
}
if (start > cells[CELL_ITEMID].length || start < 0) {
start = 0;
}
if (end > cells[CELL_ITEMID].length) {
end = cells[CELL_ITEMID].length;
}
for (int indexInRowbuffer = start; indexInRowbuffer < end; indexInRowbuffer++) {
final Object itemId = cells[CELL_ITEMID][indexInRowbuffer];
if (shouldHideNullSelectionItem()) {
// Remove null selection item if null selection is not allowed
continue;
}
paintRow(target, cells, isEditable(), actionSet, iscomponent,
indexInRowbuffer, itemId);
}
target.endTag("rows");
}
private boolean[] findCellsWithComponents() {
final boolean[] isComponent = new boolean[visibleColumns.size()];
int ix = 0;
for (Object columnId : visibleColumns) {
if (columnGenerators.containsKey(columnId)) {
isComponent[ix++] = true;
} else {
final Class<?> colType = getType(columnId);
isComponent[ix++] = colType != null
&& Component.class.isAssignableFrom(colType);
}
}
return isComponent;
}
private void paintVisibleColumnOrder(PaintTarget target) {
// Visible column order
final ArrayList<String> visibleColOrder = new ArrayList<String>();
for (Object columnId : visibleColumns) {
if (!isColumnCollapsed(columnId)) {
visibleColOrder.add(columnIdMap.key(columnId));
}
}
target.addAttribute("vcolorder", visibleColOrder.toArray());
}
private Set<Action> findAndPaintBodyActions(PaintTarget target) {
Set<Action> actionSet = new LinkedHashSet<Action>();
if (actionHandlers != null) {
final ArrayList<String> keys = new ArrayList<String>();
for (Handler ah : actionHandlers) {
// Getting actions for the null item, which in this case means
// the body item
final Action[] actions = ah.getActions(null, this);
if (actions != null) {
for (Action action : actions) {
actionSet.add(action);
keys.add(actionMapper.key(action));
}
}
}
target.addAttribute("alb", keys.toArray());
}
return actionSet;
}
private boolean shouldHideNullSelectionItem() {
return !isNullSelectionAllowed() && getNullSelectionItemId() != null
&& containsId(getNullSelectionItemId());
}
private int findNumRowsToPaint(PaintTarget target, final Object[][] cells)
throws PaintException {
int rows;
if (reqRowsToPaint >= 0) {
rows = reqRowsToPaint;
} else {
rows = cells[0].length;
if (alwaysRecalculateColumnWidths) {
// TODO experimental feature for now: tell the client to
// recalculate column widths.
// We'll only do this for paints that do not originate from
// table scroll/cache requests (i.e when reqRowsToPaint<0)
target.addAttribute("recalcWidths", true);
}
}
return rows;
}
private void paintSelectMode(PaintTarget target) throws PaintException {
if (multiSelectMode != MultiSelectMode.DEFAULT) {
target.addAttribute("multiselectmode", multiSelectMode.ordinal());
}
if (isSelectable()) {
target.addAttribute("selectmode", (isMultiSelect() ? "multi"
: "single"));
} else {
target.addAttribute("selectmode", "none");
}
if (!isNullSelectionAllowed()) {
target.addAttribute("nsa", false);
}
// selection support
// The select variable is only enabled if selectable
if (isSelectable()) {
target.addVariable(this, "selected", findSelectedKeys());
}
}
private String[] findSelectedKeys() {
LinkedList<String> selectedKeys = new LinkedList<String>();
if (isMultiSelect()) {
HashSet<?> sel = new HashSet<Object>((Set<?>) getValue());
Collection<?> vids = getVisibleItemIds();
for (Iterator<?> it = vids.iterator(); it.hasNext();) {
Object id = it.next();
if (sel.contains(id)) {
selectedKeys.add(itemIdMapper.key(id));
}
}
} else {
Object value = getValue();
if (value == null) {
value = getNullSelectionItemId();
}
if (value != null) {
selectedKeys.add(itemIdMapper.key(value));
}
}
return selectedKeys.toArray(new String[selectedKeys.size()]);
}
private void paintDragMode(PaintTarget target) throws PaintException {
if (dragMode != TableDragMode.NONE) {
target.addAttribute("dragmode", dragMode.ordinal());
}
}
private void paintTabIndex(PaintTarget target) throws PaintException {
// The tab ordering number
if (getTabIndex() > 0) {
target.addAttribute("tabindex", getTabIndex());
}
}
private void paintColumnWidth(PaintTarget target, final Object columnId)
throws PaintException {
if (columnWidths.containsKey(columnId)) {
if (getColumnWidth(columnId) > -1) {
target.addAttribute("width",
String.valueOf(getColumnWidth(columnId)));
} else {
target.addAttribute("er", getColumnExpandRatio(columnId));
}
}
}
private boolean rowHeadersAreEnabled() {
return getRowHeaderMode() != ROW_HEADER_MODE_HIDDEN;
}
private void paintRow(PaintTarget target, final Object[][] cells,
final boolean iseditable, final Set<Action> actionSet,
final boolean[] iscomponent, int indexInRowbuffer,
final Object itemId) throws PaintException {
target.startTag("tr");
paintRowAttributes(target, cells, actionSet, indexInRowbuffer, itemId);
// cells
int currentColumn = 0;
for (final Iterator<Object> it = visibleColumns.iterator(); it
.hasNext(); currentColumn++) {
final Object columnId = it.next();
if (columnId == null || isColumnCollapsed(columnId)) {
continue;
}
/*
* For each cell, if a cellStyleGenerator is specified, get the
* specific style for the cell. If there is any, add it to the
* target.
*/
if (cellStyleGenerator != null) {
String cellStyle = cellStyleGenerator
.getStyle(itemId, columnId);
if (cellStyle != null && !cellStyle.equals("")) {
target.addAttribute("style-" + columnIdMap.key(columnId),
cellStyle);
}
}
if ((iscomponent[currentColumn] || iseditable || cells[CELL_GENERATED_ROW][indexInRowbuffer] != null)
&& Component.class.isInstance(cells[CELL_FIRSTCOL
+ currentColumn][indexInRowbuffer])) {
final Component c = (Component) cells[CELL_FIRSTCOL
+ currentColumn][indexInRowbuffer];
if (c == null) {
target.addText("");
paintCellTooltips(target, itemId, columnId);
} else {
LegacyPaint.paint(c, target);
}
} else {
target.addText((String) cells[CELL_FIRSTCOL + currentColumn][indexInRowbuffer]);
paintCellTooltips(target, itemId, columnId);
}
}
target.endTag("tr");
}
private void paintCellTooltips(PaintTarget target, Object itemId,
Object columnId) throws PaintException {
if (itemDescriptionGenerator != null) {
String itemDescription = itemDescriptionGenerator
.generateDescription(this, itemId, columnId);
if (itemDescription != null && !itemDescription.equals("")) {
target.addAttribute("descr-" + columnIdMap.key(columnId),
itemDescription);
}
}
}
private void paintRowTooltips(PaintTarget target, Object itemId)
throws PaintException {
if (itemDescriptionGenerator != null) {
String rowDescription = itemDescriptionGenerator
.generateDescription(this, itemId, null);
if (rowDescription != null && !rowDescription.equals("")) {
target.addAttribute("rowdescr", rowDescription);
}
}
}
private void paintRowAttributes(PaintTarget target, final Object[][] cells,
final Set<Action> actionSet, int indexInRowbuffer,
final Object itemId) throws PaintException {
// tr attributes
paintRowIcon(target, cells, indexInRowbuffer);
paintRowHeader(target, cells, indexInRowbuffer);
paintGeneratedRowInfo(target, cells, indexInRowbuffer);
target.addAttribute("key",
Integer.parseInt(cells[CELL_KEY][indexInRowbuffer].toString()));
if (isSelected(itemId)) {
target.addAttribute("selected", true);
}
// Actions
if (actionHandlers != null) {
final ArrayList<String> keys = new ArrayList<String>();
for (Handler ah : actionHandlers) {
final Action[] aa = ah.getActions(itemId, this);
if (aa != null) {
for (int ai = 0; ai < aa.length; ai++) {
final String key = actionMapper.key(aa[ai]);
actionSet.add(aa[ai]);
keys.add(key);
}
}
}
target.addAttribute("al", keys.toArray());
}
/*
* For each row, if a cellStyleGenerator is specified, get the specific
* style for the cell, using null as propertyId. If there is any, add it
* to the target.
*/
if (cellStyleGenerator != null) {
String rowStyle = cellStyleGenerator.getStyle(itemId, null);
if (rowStyle != null && !rowStyle.equals("")) {
target.addAttribute("rowstyle", rowStyle);
}
}
paintRowTooltips(target, itemId);
paintRowAttributes(target, itemId);
}
private void paintGeneratedRowInfo(PaintTarget target, Object[][] cells,
int indexInRowBuffer) throws PaintException {
GeneratedRow generatedRow = (GeneratedRow) cells[CELL_GENERATED_ROW][indexInRowBuffer];
if (generatedRow != null) {
target.addAttribute("gen_html", generatedRow.isHtmlContentAllowed());
target.addAttribute("gen_span", generatedRow.isSpanColumns());
target.addAttribute("gen_widget",
generatedRow.getValue() instanceof Component);
}
}
protected void paintRowHeader(PaintTarget target, Object[][] cells,
int indexInRowbuffer) throws PaintException {
if (rowHeadersAreEnabled()) {
if (cells[CELL_HEADER][indexInRowbuffer] != null) {
target.addAttribute("caption",
(String) cells[CELL_HEADER][indexInRowbuffer]);
}
}
}
protected void paintRowIcon(PaintTarget target, final Object[][] cells,
int indexInRowbuffer) throws PaintException {
if (rowHeadersAreEnabled()
&& cells[CELL_ICON][indexInRowbuffer] != null) {
target.addAttribute("icon",
(Resource) cells[CELL_ICON][indexInRowbuffer]);
}
}
/**
* A method where extended Table implementations may add their custom
* attributes for rows.
*
* @param target
* @param itemId
*/
protected void paintRowAttributes(PaintTarget target, Object itemId)
throws PaintException {
}
/**
* Gets the cached visible table contents.
*
* @return the cached visible table contents.
*/
private Object[][] getVisibleCells() {
if (pageBuffer == null) {
refreshRenderedCells();
}
return pageBuffer;
}
/**
* Gets the value of property.
*
* By default if the table is editable the fieldFactory is used to create
* editors for table cells. Otherwise formatPropertyValue is used to format
* the value representation.
*
* @param rowId
* the Id of the row (same as item Id).
* @param colId
* the Id of the column.
* @param property
* the Property to be presented.
* @return Object Either formatted value or Component for field.
* @see #setTableFieldFactory(TableFieldFactory)
*/
protected Object getPropertyValue(Object rowId, Object colId,
Property property) {
if (isEditable() && fieldFactory != null) {
final Field<?> f = fieldFactory.createField(
getContainerDataSource(), rowId, colId, this);
if (f != null) {
// Remember that we have made this association so we can remove
// it when the component is removed
associatedProperties.put(f, property);
bindPropertyToField(rowId, colId, property, f);
return f;
}
}
return formatPropertyValue(rowId, colId, property);
}
/**
* Binds an item property to a field generated by TableFieldFactory. The
* default behavior is to bind property straight to Field. If
* Property.Viewer type property (e.g. PropertyFormatter) is already set for
* field, the property is bound to that Property.Viewer.
*
* @param rowId
* @param colId
* @param property
* @param field
* @since 6.7.3
*/
protected void bindPropertyToField(Object rowId, Object colId,
Property property, Field field) {
// check if field has a property that is Viewer set. In that case we
// expect developer has e.g. PropertyFormatter that he wishes to use and
// assign the property to the Viewer instead.
boolean hasFilterProperty = field.getPropertyDataSource() != null
&& (field.getPropertyDataSource() instanceof Property.Viewer);
if (hasFilterProperty) {
((Property.Viewer) field.getPropertyDataSource())
.setPropertyDataSource(property);
} else {
field.setPropertyDataSource(property);
}
}
/**
* Formats table cell property values. By default the property.toString()
* and return a empty string for null properties.
*
* @param rowId
* the Id of the row (same as item Id).
* @param colId
* the Id of the column.
* @param property
* the Property to be formatted.
* @return the String representation of property and its value.
* @since 3.1
*/
protected String formatPropertyValue(Object rowId, Object colId,
Property<?> property) {
if (property == null) {
return "";
}
Converter<String, Object> converter = null;
if (hasConverter(colId)) {
converter = getConverter(colId);
} else {
ConverterUtil.getConverter(String.class, property.getType(),
getApplication());
}
Object value = property.getValue();
if (converter != null) {
return converter.convertToPresentation(value, getLocale());
}
return (null != value) ? value.toString() : "";
}
/* Action container */
/**
* Registers a new action handler for this container
*
* @see com.vaadin.event.Action.Container#addActionHandler(Action.Handler)
*/
@Override
public void addActionHandler(Action.Handler actionHandler) {
if (actionHandler != null) {
if (actionHandlers == null) {
actionHandlers = new LinkedList<Handler>();
actionMapper = new KeyMapper<Action>();
}
if (!actionHandlers.contains(actionHandler)) {
actionHandlers.add(actionHandler);
// Assures the visual refresh. No need to reset the page buffer
// before as the content has not changed, only the action
// handlers.
refreshRenderedCells();
}
}
}
/**
* Removes a previously registered action handler for the contents of this
* container.
*
* @see com.vaadin.event.Action.Container#removeActionHandler(Action.Handler)
*/
@Override
public void removeActionHandler(Action.Handler actionHandler) {
if (actionHandlers != null && actionHandlers.contains(actionHandler)) {
actionHandlers.remove(actionHandler);
if (actionHandlers.isEmpty()) {
actionHandlers = null;
actionMapper = null;
}
// Assures the visual refresh. No need to reset the page buffer
// before as the content has not changed, only the action
// handlers.
refreshRenderedCells();
}
}
/**
* Removes all action handlers
*/
public void removeAllActionHandlers() {
actionHandlers = null;
actionMapper = null;
// Assures the visual refresh. No need to reset the page buffer
// before as the content has not changed, only the action
// handlers.
refreshRenderedCells();
}
/* Property value change listening support */
/**
* Notifies this listener that the Property's value has changed.
*
* Also listens changes in rendered items to refresh content area.
*
* @see com.vaadin.data.Property.ValueChangeListener#valueChange(Property.ValueChangeEvent)
*/
@Override
public void valueChange(Property.ValueChangeEvent event) {
if (event.getProperty() == this
|| event.getProperty() == getPropertyDataSource()) {
super.valueChange(event);
} else {
refreshRowCache();
containerChangeToBeRendered = true;
}
requestRepaint();
}
/**
* Clears the current page buffer. Call this before
* {@link #refreshRenderedCells()} to ensure that all content is updated
* from the properties.
*/
protected void resetPageBuffer() {
firstToBeRenderedInClient = -1;
lastToBeRenderedInClient = -1;
reqFirstRowToPaint = -1;
reqRowsToPaint = -1;
pageBuffer = null;
}
/**
* Notifies the component that it is connected to an application.
*
* @see com.vaadin.ui.Component#attach()
*/
@Override
public void attach() {
super.attach();
refreshRenderedCells();
}
/**
* Notifies the component that it is detached from the application
*
* @see com.vaadin.ui.Component#detach()
*/
@Override
public void detach() {
super.detach();
}
/**
* Removes all Items from the Container.
*
* @see com.vaadin.data.Container#removeAllItems()
*/
@Override
public boolean removeAllItems() {
currentPageFirstItemId = null;
currentPageFirstItemIndex = 0;
return super.removeAllItems();
}
/**
* Removes the Item identified by <code>ItemId</code> from the Container.
*
* @see com.vaadin.data.Container#removeItem(Object)
*/
@Override
public boolean removeItem(Object itemId) {
final Object nextItemId = nextItemId(itemId);
final boolean ret = super.removeItem(itemId);
if (ret && (itemId != null) && (itemId.equals(currentPageFirstItemId))) {
currentPageFirstItemId = nextItemId;
}
if (!(items instanceof Container.ItemSetChangeNotifier)) {
refreshRowCache();
}
return ret;
}
/**
* Removes a Property specified by the given Property ID from the Container.
*
* @see com.vaadin.data.Container#removeContainerProperty(Object)
*/
@Override
public boolean removeContainerProperty(Object propertyId)
throws UnsupportedOperationException {
// If a visible property is removed, remove the corresponding column
visibleColumns.remove(propertyId);
columnAlignments.remove(propertyId);
columnIcons.remove(propertyId);
columnHeaders.remove(propertyId);
columnFooters.remove(propertyId);
return super.removeContainerProperty(propertyId);
}
/**
* Adds a new property to the table and show it as a visible column.
*
* @param propertyId
* the Id of the proprty.
* @param type
* the class of the property.
* @param defaultValue
* the default value given for all existing items.
* @see com.vaadin.data.Container#addContainerProperty(Object, Class,
* Object)
*/
@Override
public boolean addContainerProperty(Object propertyId, Class<?> type,
Object defaultValue) throws UnsupportedOperationException {
boolean visibleColAdded = false;
if (!visibleColumns.contains(propertyId)) {
visibleColumns.add(propertyId);
visibleColAdded = true;
}
if (!super.addContainerProperty(propertyId, type, defaultValue)) {
if (visibleColAdded) {
visibleColumns.remove(propertyId);
}
return false;
}
if (!(items instanceof Container.PropertySetChangeNotifier)) {
refreshRowCache();
}
return true;
}
/**
* Adds a new property to the table and show it as a visible column.
*
* @param propertyId
* the Id of the proprty
* @param type
* the class of the property
* @param defaultValue
* the default value given for all existing items
* @param columnHeader
* the Explicit header of the column. If explicit header is not
* needed, this should be set null.
* @param columnIcon
* the Icon of the column. If icon is not needed, this should be
* set null.
* @param columnAlignment
* the Alignment of the column. Null implies align left.
* @throws UnsupportedOperationException
* if the operation is not supported.
* @see com.vaadin.data.Container#addContainerProperty(Object, Class,
* Object)
*/
public boolean addContainerProperty(Object propertyId, Class<?> type,
Object defaultValue, String columnHeader, Resource columnIcon,
Align columnAlignment) throws UnsupportedOperationException {
if (!this.addContainerProperty(propertyId, type, defaultValue)) {
return false;
}
setColumnAlignment(propertyId, columnAlignment);
setColumnHeader(propertyId, columnHeader);
setColumnIcon(propertyId, columnIcon);
return true;
}
/**
* Adds a generated column to the Table.
* <p>
* A generated column is a column that exists only in the Table, not as a
* property in the underlying Container. It shows up just as a regular
* column.
* </p>
* <p>
* A generated column will override a property with the same id, so that the
* generated column is shown instead of the column representing the
* property. Note that getContainerProperty() will still get the real
* property.
* </p>
* <p>
* Table will not listen to value change events from properties overridden
* by generated columns. If the content of your generated column depends on
* properties that are not directly visible in the table, attach value
* change listener to update the content on all depended properties.
* Otherwise your UI might not get updated as expected.
* </p>
* <p>
* Also note that getVisibleColumns() will return the generated columns,
* while getContainerPropertyIds() will not.
* </p>
*
* @param id
* the id of the column to be added
* @param generatedColumn
* the {@link ColumnGenerator} to use for this column
*/
public void addGeneratedColumn(Object id, ColumnGenerator generatedColumn) {
if (generatedColumn == null) {
throw new IllegalArgumentException(
"Can not add null as a GeneratedColumn");
}
if (columnGenerators.containsKey(id)) {
throw new IllegalArgumentException(
"Can not add the same GeneratedColumn twice, id:" + id);
} else {
columnGenerators.put(id, generatedColumn);
/*
* add to visible column list unless already there (overriding
* column from DS)
*/
if (!visibleColumns.contains(id)) {
visibleColumns.add(id);
}
refreshRowCache();
}
}
/**
* Returns the ColumnGenerator used to generate the given column.
*
* @param columnId
* The id of the generated column
* @return The ColumnGenerator used for the given columnId or null.
*/
public ColumnGenerator getColumnGenerator(Object columnId)
throws IllegalArgumentException {
return columnGenerators.get(columnId);
}
/**
* Removes a generated column previously added with addGeneratedColumn.
*
* @param columnId
* id of the generated column to remove
* @return true if the column could be removed (existed in the Table)
*/
public boolean removeGeneratedColumn(Object columnId) {
if (columnGenerators.containsKey(columnId)) {
columnGenerators.remove(columnId);
// remove column from visibleColumns list unless it exists in
// container (generator previously overrode this column)
if (!items.getContainerPropertyIds().contains(columnId)) {
visibleColumns.remove(columnId);
}
refreshRowCache();
return true;
} else {
return false;
}
}
/**
* Returns item identifiers of the items which are currently rendered on the
* client.
* <p>
* Note, that some due to historical reasons the name of the method is bit
* misleading. Some items may be partly or totally out of the viewport of
* the table's scrollable area. Actually detecting rows which can be
* actually seen by the end user may be problematic due to the client server
* architecture. Using {@link #getCurrentPageFirstItemId()} combined with
* {@link #getPageLength()} may produce good enough estimates in some
* situations.
*
* @see com.vaadin.ui.Select#getVisibleItemIds()
*/
@Override
public Collection<?> getVisibleItemIds() {
final LinkedList<Object> visible = new LinkedList<Object>();
final Object[][] cells = getVisibleCells();
// may be null if the table has not been rendered yet (e.g. not attached
// to a layout)
if (null != cells) {
for (int i = 0; i < cells[CELL_ITEMID].length; i++) {
visible.add(cells[CELL_ITEMID][i]);
}
}
return visible;
}
/**
* Container datasource item set change. Table must flush its buffers on
* change.
*
* @see com.vaadin.data.Container.ItemSetChangeListener#containerItemSetChange(com.vaadin.data.Container.ItemSetChangeEvent)
*/
@Override
public void containerItemSetChange(Container.ItemSetChangeEvent event) {
super.containerItemSetChange(event);
// super method clears the key map, must inform client about this to
// avoid getting invalid keys back (#8584)
keyMapperReset = true;
// ensure that page still has first item in page, ignore buffer refresh
// (forced in this method)
setCurrentPageFirstItemIndex(getCurrentPageFirstItemIndex(), false);
refreshRowCache();
}
/**
* Container datasource property set change. Table must flush its buffers on
* change.
*
* @see com.vaadin.data.Container.PropertySetChangeListener#containerPropertySetChange(com.vaadin.data.Container.PropertySetChangeEvent)
*/
@Override
public void containerPropertySetChange(
Container.PropertySetChangeEvent event) {
disableContentRefreshing();
super.containerPropertySetChange(event);
// sanitetize visibleColumns. note that we are not adding previously
// non-existing properties as columns
Collection<?> containerPropertyIds = getContainerDataSource()
.getContainerPropertyIds();
LinkedList<Object> newVisibleColumns = new LinkedList<Object>(
visibleColumns);
for (Iterator<Object> iterator = newVisibleColumns.iterator(); iterator
.hasNext();) {
Object id = iterator.next();
if (!(containerPropertyIds.contains(id) || columnGenerators
.containsKey(id))) {
iterator.remove();
}
}
setVisibleColumns(newVisibleColumns.toArray());
// same for collapsed columns
for (Iterator<Object> iterator = collapsedColumns.iterator(); iterator
.hasNext();) {
Object id = iterator.next();
if (!(containerPropertyIds.contains(id) || columnGenerators
.containsKey(id))) {
iterator.remove();
}
}
resetPageBuffer();
enableContentRefreshing(true);
}
/**
* Adding new items is not supported.
*
* @throws UnsupportedOperationException
* if set to true.
* @see com.vaadin.ui.Select#setNewItemsAllowed(boolean)
*/
@Override
public void setNewItemsAllowed(boolean allowNewOptions)
throws UnsupportedOperationException {
if (allowNewOptions) {
throw new UnsupportedOperationException();
}
}
/**
* Gets the ID of the Item following the Item that corresponds to itemId.
*
* @see com.vaadin.data.Container.Ordered#nextItemId(java.lang.Object)
*/
@Override
public Object nextItemId(Object itemId) {
return ((Container.Ordered) items).nextItemId(itemId);
}
/**
* Gets the ID of the Item preceding the Item that corresponds to the
* itemId.
*
* @see com.vaadin.data.Container.Ordered#prevItemId(java.lang.Object)
*/
@Override
public Object prevItemId(Object itemId) {
return ((Container.Ordered) items).prevItemId(itemId);
}
/**
* Gets the ID of the first Item in the Container.
*
* @see com.vaadin.data.Container.Ordered#firstItemId()
*/
@Override
public Object firstItemId() {
return ((Container.Ordered) items).firstItemId();
}
/**
* Gets the ID of the last Item in the Container.
*
* @see com.vaadin.data.Container.Ordered#lastItemId()
*/
@Override
public Object lastItemId() {
return ((Container.Ordered) items).lastItemId();
}
/**
* Tests if the Item corresponding to the given Item ID is the first Item in
* the Container.
*
* @see com.vaadin.data.Container.Ordered#isFirstId(java.lang.Object)
*/
@Override
public boolean isFirstId(Object itemId) {
return ((Container.Ordered) items).isFirstId(itemId);
}
/**
* Tests if the Item corresponding to the given Item ID is the last Item in
* the Container.
*
* @see com.vaadin.data.Container.Ordered#isLastId(java.lang.Object)
*/
@Override
public boolean isLastId(Object itemId) {
return ((Container.Ordered) items).isLastId(itemId);
}
/**
* Adds new item after the given item.
*
* @see com.vaadin.data.Container.Ordered#addItemAfter(java.lang.Object)
*/
@Override
public Object addItemAfter(Object previousItemId)
throws UnsupportedOperationException {
Object itemId = ((Container.Ordered) items)
.addItemAfter(previousItemId);
if (!(items instanceof Container.ItemSetChangeNotifier)) {
refreshRowCache();
}
return itemId;
}
/**
* Adds new item after the given item.
*
* @see com.vaadin.data.Container.Ordered#addItemAfter(java.lang.Object,
* java.lang.Object)
*/
@Override
public Item addItemAfter(Object previousItemId, Object newItemId)
throws UnsupportedOperationException {
Item item = ((Container.Ordered) items).addItemAfter(previousItemId,
newItemId);
if (!(items instanceof Container.ItemSetChangeNotifier)) {
refreshRowCache();
}
return item;
}
/**
* Sets the TableFieldFactory that is used to create editor for table cells.
*
* The TableFieldFactory is only used if the Table is editable. By default
* the DefaultFieldFactory is used.
*
* @param fieldFactory
* the field factory to set.
* @see #isEditable
* @see DefaultFieldFactory
*/
public void setTableFieldFactory(TableFieldFactory fieldFactory) {
this.fieldFactory = fieldFactory;
// Assure visual refresh
refreshRowCache();
}
/**
* Gets the TableFieldFactory that is used to create editor for table cells.
*
* The FieldFactory is only used if the Table is editable.
*
* @return TableFieldFactory used to create the Field instances.
* @see #isEditable
*/
public TableFieldFactory getTableFieldFactory() {
return fieldFactory;
}
/**
* Is table editable.
*
* If table is editable a editor of type Field is created for each table
* cell. The assigned FieldFactory is used to create the instances.
*
* To provide custom editors for table cells create a class implementins the
* FieldFactory interface, and assign it to table, and set the editable
* property to true.
*
* @return true if table is editable, false oterwise.
* @see Field
* @see FieldFactory
*
*/
public boolean isEditable() {
return editable;
}
/**
* Sets the editable property.
*
* If table is editable a editor of type Field is created for each table
* cell. The assigned FieldFactory is used to create the instances.
*
* To provide custom editors for table cells create a class implementins the
* FieldFactory interface, and assign it to table, and set the editable
* property to true.
*
* @param editable
* true if table should be editable by user.
* @see Field
* @see FieldFactory
*
*/
public void setEditable(boolean editable) {
this.editable = editable;
// Assure visual refresh
refreshRowCache();
}
/**
* Sorts the table.
*
* @throws UnsupportedOperationException
* if the container data source does not implement
* Container.Sortable
* @see com.vaadin.data.Container.Sortable#sort(java.lang.Object[],
* boolean[])
*
*/
@Override
public void sort(Object[] propertyId, boolean[] ascending)
throws UnsupportedOperationException {
final Container c = getContainerDataSource();
if (c instanceof Container.Sortable) {
final int pageIndex = getCurrentPageFirstItemIndex();
((Container.Sortable) c).sort(propertyId, ascending);
setCurrentPageFirstItemIndex(pageIndex);
refreshRowCache();
} else if (c != null) {
throw new UnsupportedOperationException(
"Underlying Data does not allow sorting");
}
}
/**
* Sorts the table by currently selected sorting column.
*
* @throws UnsupportedOperationException
* if the container data source does not implement
* Container.Sortable
*/
public void sort() {
if (getSortContainerPropertyId() == null) {
return;
}
sort(new Object[] { sortContainerPropertyId },
new boolean[] { sortAscending });
}
/**
* Gets the container property IDs, which can be used to sort the item.
* <p>
* Note that the {@link #isSortEnabled()} state affects what this method
* returns. Disabling sorting causes this method to always return an empty
* collection.
* </p>
*
* @see com.vaadin.data.Container.Sortable#getSortableContainerPropertyIds()
*/
@Override
public Collection<?> getSortableContainerPropertyIds() {
final Container c = getContainerDataSource();
if (c instanceof Container.Sortable && isSortEnabled()) {
return ((Container.Sortable) c).getSortableContainerPropertyIds();
} else {
return Collections.EMPTY_LIST;
}
}
/**
* Gets the currently sorted column property ID.
*
* @return the Container property id of the currently sorted column.
*/
public Object getSortContainerPropertyId() {
return sortContainerPropertyId;
}
/**
* Sets the currently sorted column property id.
*
* @param propertyId
* the Container property id of the currently sorted column.
*/
public void setSortContainerPropertyId(Object propertyId) {
setSortContainerPropertyId(propertyId, true);
}
/**
* Internal method to set currently sorted column property id. With doSort
* flag actual sorting may be bypassed.
*
* @param propertyId
* @param doSort
*/
private void setSortContainerPropertyId(Object propertyId, boolean doSort) {
if ((sortContainerPropertyId != null && !sortContainerPropertyId
.equals(propertyId))
|| (sortContainerPropertyId == null && propertyId != null)) {
sortContainerPropertyId = propertyId;
if (doSort) {
sort();
// Assures the visual refresh. This should not be necessary as
// sort() calls refreshRowCache
refreshRenderedCells();
}
}
}
/**
* Is the table currently sorted in ascending order.
*
* @return <code>true</code> if ascending, <code>false</code> if descending.
*/
public boolean isSortAscending() {
return sortAscending;
}
/**
* Sets the table in ascending order.
*
* @param ascending
* <code>true</code> if ascending, <code>false</code> if
* descending.
*/
public void setSortAscending(boolean ascending) {
setSortAscending(ascending, true);
}
/**
* Internal method to set sort ascending. With doSort flag actual sort can
* be bypassed.
*
* @param ascending
* @param doSort
*/
private void setSortAscending(boolean ascending, boolean doSort) {
if (sortAscending != ascending) {
sortAscending = ascending;
if (doSort) {
sort();
// Assures the visual refresh. This should not be necessary as
// sort() calls refreshRowCache
refreshRenderedCells();
}
}
}
/**
* Is sorting disabled altogether.
*
* True iff no sortable columns are given even in the case where data source
* would support this.
*
* @return True iff sorting is disabled.
* @deprecated Use {@link #isSortEnabled()} instead
*/
@Deprecated
public boolean isSortDisabled() {
return !isSortEnabled();
}
/**
* Checks if sorting is enabled.
*
* @return true if sorting by the user is allowed, false otherwise
*/
public boolean isSortEnabled() {
return sortEnabled;
}
/**
* Disables the sorting by the user altogether.
*
* @param sortDisabled
* True iff sorting is disabled.
* @deprecated Use {@link #setSortEnabled(boolean)} instead
*/
@Deprecated
public void setSortDisabled(boolean sortDisabled) {
setSortEnabled(!sortDisabled);
}
/**
* Enables or disables sorting.
* <p>
* Setting this to false disallows sorting by the user. It is still possible
* to call {@link #sort()}.
* </p>
*
* @param sortEnabled
* true to allow the user to sort the table, false to disallow it
*/
public void setSortEnabled(boolean sortEnabled) {
if (this.sortEnabled != sortEnabled) {
this.sortEnabled = sortEnabled;
requestRepaint();
}
}
/**
* Used to create "generated columns"; columns that exist only in the Table,
* not in the underlying Container. Implement this interface and pass it to
* Table.addGeneratedColumn along with an id for the column to be generated.
*
*/
public interface ColumnGenerator extends Serializable {
/**
* Called by Table when a cell in a generated column needs to be
* generated.
*
* @param source
* the source Table
* @param itemId
* the itemId (aka rowId) for the of the cell to be generated
* @param columnId
* the id for the generated column (as specified in
* addGeneratedColumn)
* @return A {@link Component} that should be rendered in the cell or a
* {@link String} that should be displayed in the cell. Other
* return values are not supported.
*/
public abstract Object generateCell(Table source, Object itemId,
Object columnId);
}
/**
* Set cell style generator for Table.
*
* @param cellStyleGenerator
* New cell style generator or null to remove generator.
*/
public void setCellStyleGenerator(CellStyleGenerator cellStyleGenerator) {
this.cellStyleGenerator = cellStyleGenerator;
// Assures the visual refresh. No need to reset the page buffer
// before as the content has not changed, only the style generators
refreshRenderedCells();
}
/**
* Get the current cell style generator.
*
*/
public CellStyleGenerator getCellStyleGenerator() {
return cellStyleGenerator;
}
/**
* Allow to define specific style on cells (and rows) contents. Implements
* this interface and pass it to Table.setCellStyleGenerator. Row styles are
* generated when porpertyId is null. The CSS class name that will be added
* to the cell content is <tt>v-table-cell-content-[style name]</tt>, and
* the row style will be <tt>v-table-row-[style name]</tt>.
*/
public interface CellStyleGenerator extends Serializable {
/**
* Called by Table when a cell (and row) is painted.
*
* @param itemId
* The itemId of the painted cell
* @param propertyId
* The propertyId of the cell, null when getting row style
* @return The style name to add to this cell or row. (the CSS class
* name will be v-table-cell-content-[style name], or
* v-table-row-[style name] for rows)
*/
public abstract String getStyle(Object itemId, Object propertyId);
}
@Override
public void addListener(ItemClickListener listener) {
addListener(TableConstants.ITEM_CLICK_EVENT_ID, ItemClickEvent.class,
listener, ItemClickEvent.ITEM_CLICK_METHOD);
}
@Override
public void removeListener(ItemClickListener listener) {
removeListener(TableConstants.ITEM_CLICK_EVENT_ID,
ItemClickEvent.class, listener);
}
// Identical to AbstractCompoenentContainer.setEnabled();
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (getParent() != null && !getParent().isEnabled()) {
// some ancestor still disabled, don't update children
return;
} else {
requestRepaintAll();
}
}
/**
* Sets the drag start mode of the Table. Drag start mode controls how Table
* behaves as a drag source.
*
* @param newDragMode
*/
public void setDragMode(TableDragMode newDragMode) {
dragMode = newDragMode;
requestRepaint();
}
/**
* @return the current start mode of the Table. Drag start mode controls how
* Table behaves as a drag source.
*/
public TableDragMode getDragMode() {
return dragMode;
}
/**
* Concrete implementation of {@link DataBoundTransferable} for data
* transferred from a table.
*
* @see {@link DataBoundTransferable}.
*
* @since 6.3
*/
public class TableTransferable extends DataBoundTransferable {
protected TableTransferable(Map<String, Object> rawVariables) {
super(Table.this, rawVariables);
Object object = rawVariables.get("itemId");
if (object != null) {
setData("itemId", itemIdMapper.get((String) object));
}
object = rawVariables.get("propertyId");
if (object != null) {
setData("propertyId", columnIdMap.get((String) object));
}
}
@Override
public Object getItemId() {
return getData("itemId");
}
@Override
public Object getPropertyId() {
return getData("propertyId");
}
@Override
public Table getSourceComponent() {
return (Table) super.getSourceComponent();
}
}
@Override
public TableTransferable getTransferable(Map<String, Object> rawVariables) {
TableTransferable transferable = new TableTransferable(rawVariables);
return transferable;
}
@Override
public DropHandler getDropHandler() {
return dropHandler;
}
public void setDropHandler(DropHandler dropHandler) {
this.dropHandler = dropHandler;
}
@Override
public AbstractSelectTargetDetails translateDropTargetDetails(
Map<String, Object> clientVariables) {
return new AbstractSelectTargetDetails(clientVariables);
}
/**
* Sets the behavior of how the multi-select mode should behave when the
* table is both selectable and in multi-select mode.
* <p>
* Note, that on some clients the mode may not be respected. E.g. on touch
* based devices CTRL/SHIFT base selection method is invalid, so touch based
* browsers always use the {@link MultiSelectMode#SIMPLE}.
*
* @param mode
* The select mode of the table
*/
public void setMultiSelectMode(MultiSelectMode mode) {
multiSelectMode = mode;
requestRepaint();
}
/**
* Returns the select mode in which multi-select is used.
*
* @return The multi select mode
*/
public MultiSelectMode getMultiSelectMode() {
return multiSelectMode;
}
/**
* Lazy loading accept criterion for Table. Accepted target rows are loaded
* from server once per drag and drop operation. Developer must override one
* method that decides on which rows the currently dragged data can be
* dropped.
*
* <p>
* Initially pretty much no data is sent to client. On first required
* criterion check (per drag request) the client side data structure is
* initialized from server and no subsequent requests requests are needed
* during that drag and drop operation.
*/
public static abstract class TableDropCriterion extends ServerSideCriterion {
private Table table;
private Set<Object> allowedItemIds;
/*
* (non-Javadoc)
*
* @see
* com.vaadin.event.dd.acceptcriteria.ServerSideCriterion#getIdentifier
* ()
*/
@Override
protected String getIdentifier() {
return TableDropCriterion.class.getCanonicalName();
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.event.dd.acceptcriteria.AcceptCriterion#accepts(com.vaadin
* .event.dd.DragAndDropEvent)
*/
@Override
@SuppressWarnings("unchecked")
public boolean accept(DragAndDropEvent dragEvent) {
AbstractSelectTargetDetails dropTargetData = (AbstractSelectTargetDetails) dragEvent
.getTargetDetails();
table = (Table) dragEvent.getTargetDetails().getTarget();
Collection<?> visibleItemIds = table.getVisibleItemIds();
allowedItemIds = getAllowedItemIds(dragEvent, table,
(Collection<Object>) visibleItemIds);
return allowedItemIds.contains(dropTargetData.getItemIdOver());
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.event.dd.acceptcriteria.AcceptCriterion#paintResponse(
* com.vaadin.terminal.PaintTarget)
*/
@Override
public void paintResponse(PaintTarget target) throws PaintException {
/*
* send allowed nodes to client so subsequent requests can be
* avoided
*/
Object[] array = allowedItemIds.toArray();
for (int i = 0; i < array.length; i++) {
String key = table.itemIdMapper.key(array[i]);
array[i] = key;
}
target.addAttribute("allowedIds", array);
}
/**
* @param dragEvent
* @param table
* the table for which the allowed item identifiers are
* defined
* @param visibleItemIds
* the list of currently rendered item identifiers, accepted
* item id's need to be detected only for these visible items
* @return the set of identifiers for items on which the dragEvent will
* be accepted
*/
protected abstract Set<Object> getAllowedItemIds(
DragAndDropEvent dragEvent, Table table,
Collection<Object> visibleItemIds);
}
/**
* Click event fired when clicking on the Table headers. The event includes
* a reference the the Table the event originated from, the property id of
* the column which header was pressed and details about the mouse event
* itself.
*/
public static class HeaderClickEvent extends ClickEvent {
public static final Method HEADER_CLICK_METHOD;
static {
try {
// Set the header click method
HEADER_CLICK_METHOD = HeaderClickListener.class
.getDeclaredMethod("headerClick",
new Class[] { HeaderClickEvent.class });
} catch (final java.lang.NoSuchMethodException e) {
// This should never happen
throw new java.lang.RuntimeException(e);
}
}
// The property id of the column which header was pressed
private final Object columnPropertyId;
public HeaderClickEvent(Component source, Object propertyId,
MouseEventDetails details) {
super(source, details);
columnPropertyId = propertyId;
}
/**
* Gets the property id of the column which header was pressed
*
* @return The column propety id
*/
public Object getPropertyId() {
return columnPropertyId;
}
}
/**
* Click event fired when clicking on the Table footers. The event includes
* a reference the the Table the event originated from, the property id of
* the column which header was pressed and details about the mouse event
* itself.
*/
public static class FooterClickEvent extends ClickEvent {
public static final Method FOOTER_CLICK_METHOD;
static {
try {
// Set the header click method
FOOTER_CLICK_METHOD = FooterClickListener.class
.getDeclaredMethod("footerClick",
new Class[] { FooterClickEvent.class });
} catch (final java.lang.NoSuchMethodException e) {
// This should never happen
throw new java.lang.RuntimeException(e);
}
}
// The property id of the column which header was pressed
private final Object columnPropertyId;
/**
* Constructor
*
* @param source
* The source of the component
* @param propertyId
* The propertyId of the column
* @param details
* The mouse details of the click
*/
public FooterClickEvent(Component source, Object propertyId,
MouseEventDetails details) {
super(source, details);
columnPropertyId = propertyId;
}
/**
* Gets the property id of the column which header was pressed
*
* @return The column propety id
*/
public Object getPropertyId() {
return columnPropertyId;
}
}
/**
* Interface for the listener for column header mouse click events. The
* headerClick method is called when the user presses a header column cell.
*/
public interface HeaderClickListener extends Serializable {
/**
* Called when a user clicks a header column cell
*
* @param event
* The event which contains information about the column and
* the mouse click event
*/
public void headerClick(HeaderClickEvent event);
}
/**
* Interface for the listener for column footer mouse click events. The
* footerClick method is called when the user presses a footer column cell.
*/
public interface FooterClickListener extends Serializable {
/**
* Called when a user clicks a footer column cell
*
* @param event
* The event which contains information about the column and
* the mouse click event
*/
public void footerClick(FooterClickEvent event);
}
/**
* Adds a header click listener which handles the click events when the user
* clicks on a column header cell in the Table.
* <p>
* The listener will receive events which contain information about which
* column was clicked and some details about the mouse event.
* </p>
*
* @param listener
* The handler which should handle the header click events.
*/
public void addListener(HeaderClickListener listener) {
addListener(TableConstants.HEADER_CLICK_EVENT_ID,
HeaderClickEvent.class, listener,
HeaderClickEvent.HEADER_CLICK_METHOD);
}
/**
* Removes a header click listener
*
* @param listener
* The listener to remove.
*/
public void removeListener(HeaderClickListener listener) {
removeListener(TableConstants.HEADER_CLICK_EVENT_ID,
HeaderClickEvent.class, listener);
}
/**
* Adds a footer click listener which handles the click events when the user
* clicks on a column footer cell in the Table.
* <p>
* The listener will receive events which contain information about which
* column was clicked and some details about the mouse event.
* </p>
*
* @param listener
* The handler which should handle the footer click events.
*/
public void addListener(FooterClickListener listener) {
addListener(TableConstants.FOOTER_CLICK_EVENT_ID,
FooterClickEvent.class, listener,
FooterClickEvent.FOOTER_CLICK_METHOD);
}
/**
* Removes a footer click listener
*
* @param listener
* The listener to remove.
*/
public void removeListener(FooterClickListener listener) {
removeListener(TableConstants.FOOTER_CLICK_EVENT_ID,
FooterClickEvent.class, listener);
}
/**
* Gets the footer caption beneath the rows
*
* @param propertyId
* The propertyId of the column *
* @return The caption of the footer or NULL if not set
*/
public String getColumnFooter(Object propertyId) {
return columnFooters.get(propertyId);
}
/**
* Sets the column footer caption. The column footer caption is the text
* displayed beneath the column if footers have been set visible.
*
* @param propertyId
* The properyId of the column
*
* @param footer
* The caption of the footer
*/
public void setColumnFooter(Object propertyId, String footer) {
if (footer == null) {
columnFooters.remove(propertyId);
} else {
columnFooters.put(propertyId, footer);
}
requestRepaint();
}
/**
* Sets the footer visible in the bottom of the table.
* <p>
* The footer can be used to add column related data like sums to the bottom
* of the Table using setColumnFooter(Object propertyId, String footer).
* </p>
*
* @param visible
* Should the footer be visible
*/
public void setFooterVisible(boolean visible) {
if (visible != columnFootersVisible) {
columnFootersVisible = visible;
requestRepaint();
}
}
/**
* Is the footer currently visible?
*
* @return Returns true if visible else false
*/
public boolean isFooterVisible() {
return columnFootersVisible;
}
/**
* This event is fired when a column is resized. The event contains the
* columns property id which was fired, the previous width of the column and
* the width of the column after the resize.
*/
public static class ColumnResizeEvent extends Component.Event {
public static final Method COLUMN_RESIZE_METHOD;
static {
try {
COLUMN_RESIZE_METHOD = ColumnResizeListener.class
.getDeclaredMethod("columnResize",
new Class[] { ColumnResizeEvent.class });
} catch (final java.lang.NoSuchMethodException e) {
// This should never happen
throw new java.lang.RuntimeException(e);
}
}
private final int previousWidth;
private final int currentWidth;
private final Object columnPropertyId;
/**
* Constructor
*
* @param source
* The source of the event
* @param propertyId
* The columns property id
* @param previous
* The width in pixels of the column before the resize event
* @param current
* The width in pixels of the column after the resize event
*/
public ColumnResizeEvent(Component source, Object propertyId,
int previous, int current) {
super(source);
previousWidth = previous;
currentWidth = current;
columnPropertyId = propertyId;
}
/**
* Get the column property id of the column that was resized.
*
* @return The column property id
*/
public Object getPropertyId() {
return columnPropertyId;
}
/**
* Get the width in pixels of the column before the resize event
*
* @return Width in pixels
*/
public int getPreviousWidth() {
return previousWidth;
}
/**
* Get the width in pixels of the column after the resize event
*
* @return Width in pixels
*/
public int getCurrentWidth() {
return currentWidth;
}
}
/**
* Interface for listening to column resize events.
*/
public interface ColumnResizeListener extends Serializable {
/**
* This method is triggered when the column has been resized
*
* @param event
* The event which contains the column property id, the
* previous width of the column and the current width of the
* column
*/
public void columnResize(ColumnResizeEvent event);
}
/**
* Adds a column resize listener to the Table. A column resize listener is
* called when a user resizes a columns width.
*
* @param listener
* The listener to attach to the Table
*/
public void addListener(ColumnResizeListener listener) {
addListener(TableConstants.COLUMN_RESIZE_EVENT_ID,
ColumnResizeEvent.class, listener,
ColumnResizeEvent.COLUMN_RESIZE_METHOD);
}
/**
* Removes a column resize listener from the Table.
*
* @param listener
* The listener to remove
*/
public void removeListener(ColumnResizeListener listener) {
removeListener(TableConstants.COLUMN_RESIZE_EVENT_ID,
ColumnResizeEvent.class, listener);
}
/**
* This event is fired when a columns are reordered by the end user user.
*/
public static class ColumnReorderEvent extends Component.Event {
public static final Method METHOD;
static {
try {
METHOD = ColumnReorderListener.class.getDeclaredMethod(
"columnReorder",
new Class[] { ColumnReorderEvent.class });
} catch (final java.lang.NoSuchMethodException e) {
// This should never happen
throw new java.lang.RuntimeException(e);
}
}
/**
* Constructor
*
* @param source
* The source of the event
*/
public ColumnReorderEvent(Component source) {
super(source);
}
}
/**
* Interface for listening to column reorder events.
*/
public interface ColumnReorderListener extends Serializable {
/**
* This method is triggered when the column has been reordered
*
* @param event
*/
public void columnReorder(ColumnReorderEvent event);
}
/**
* Adds a column reorder listener to the Table. A column reorder listener is
* called when a user reorders columns.
*
* @param listener
* The listener to attach to the Table
*/
public void addListener(ColumnReorderListener listener) {
addListener(TableConstants.COLUMN_REORDER_EVENT_ID,
ColumnReorderEvent.class, listener, ColumnReorderEvent.METHOD);
}
/**
* Removes a column reorder listener from the Table.
*
* @param listener
* The listener to remove
*/
public void removeListener(ColumnReorderListener listener) {
removeListener(TableConstants.COLUMN_REORDER_EVENT_ID,
ColumnReorderEvent.class, listener);
}
/**
* Set the item description generator which generates tooltips for cells and
* rows in the Table
*
* @param generator
* The generator to use or null to disable
*/
public void setItemDescriptionGenerator(ItemDescriptionGenerator generator) {
if (generator != itemDescriptionGenerator) {
itemDescriptionGenerator = generator;
// Assures the visual refresh. No need to reset the page buffer
// before as the content has not changed, only the descriptions
refreshRenderedCells();
}
}
/**
* Get the item description generator which generates tooltips for cells and
* rows in the Table.
*/
public ItemDescriptionGenerator getItemDescriptionGenerator() {
return itemDescriptionGenerator;
}
/**
* Row generators can be used to replace certain items in a table with a
* generated string. The generator is called each time the table is
* rendered, which means that new strings can be generated each time.
*
* Row generators can be used for e.g. summary rows or grouping of items.
*/
public interface RowGenerator extends Serializable {
/**
* Called for every row that is painted in the Table. Returning a
* GeneratedRow object will cause the row to be painted based on the
* contents of the GeneratedRow. A generated row is by default styled
* similarly to a header or footer row.
* <p>
* The GeneratedRow data object contains the text that should be
* rendered in the row. The itemId in the container thus works only as a
* placeholder.
* <p>
* If GeneratedRow.setSpanColumns(true) is used, there will be one
* String spanning all columns (use setText("Spanning text")). Otherwise
* you can define one String per visible column.
* <p>
* If GeneratedRow.setRenderAsHtml(true) is used, the strings can
* contain HTML markup, otherwise all strings will be rendered as text
* (the default).
* <p>
* A "v-table-generated-row" CSS class is added to all generated rows.
* For custom styling of a generated row you can combine a RowGenerator
* with a CellStyleGenerator.
* <p>
*
* @param table
* The Table that is being painted
* @param itemId
* The itemId for the row
* @return A GeneratedRow describing how the row should be painted or
* null to paint the row with the contents from the container
*/
public GeneratedRow generateRow(Table table, Object itemId);
}
public static class GeneratedRow implements Serializable {
private boolean htmlContentAllowed = false;
private boolean spanColumns = false;
private String[] text = null;
/**
* Creates a new generated row. If only one string is passed in, columns
* are automatically spanned.
*
* @param text
*/
public GeneratedRow(String... text) {
setHtmlContentAllowed(false);
setSpanColumns(text == null || text.length == 1);
setText(text);
}
/**
* Pass one String if spanColumns is used, one String for each visible
* column otherwise
*/
public void setText(String... text) {
if (text == null || (text.length == 1 && text[0] == null)) {
text = new String[] { "" };
}
this.text = text;
}
protected String[] getText() {
return text;
}
protected Object getValue() {
return getText();
}
protected boolean isHtmlContentAllowed() {
return htmlContentAllowed;
}
/**
* If set to true, all strings passed to {@link #setText(String...)}
* will be rendered as HTML.
*
* @param htmlContentAllowed
*/
public void setHtmlContentAllowed(boolean htmlContentAllowed) {
this.htmlContentAllowed = htmlContentAllowed;
}
protected boolean isSpanColumns() {
return spanColumns;
}
/**
* If set to true, only one string will be rendered, spanning the entire
* row.
*
* @param spanColumns
*/
public void setSpanColumns(boolean spanColumns) {
this.spanColumns = spanColumns;
}
}
/**
* Assigns a row generator to the table. The row generator will be able to
* replace rows in the table when it is rendered.
*
* @param generator
* the new row generator
*/
public void setRowGenerator(RowGenerator generator) {
rowGenerator = generator;
refreshRowCache();
}
/**
* @return the current row generator
*/
public RowGenerator getRowGenerator() {
return rowGenerator;
}
/**
* Sets a converter for a property id.
* <p>
* The converter is used to format the the data for the given property id
* before displaying it in the table.
* </p>
*
* @param propertyId
* The propertyId to format using the converter
* @param converter
* The converter to use for the property id
*/
public void setConverter(Object propertyId, Converter<String, ?> converter) {
if (!getContainerPropertyIds().contains(propertyId)) {
throw new IllegalArgumentException("PropertyId " + propertyId
+ " must be in the container");
}
// FIXME: This check should be here but primitive types like Boolean
// formatter for boolean property must be handled
// if (!converter.getSourceType().isAssignableFrom(getType(propertyId)))
// {
// throw new IllegalArgumentException("Property type ("
// + getType(propertyId)
// + ") must match converter source type ("
// + converter.getSourceType() + ")");
// }
propertyValueConverters.put(propertyId,
(Converter<String, Object>) converter);
refreshRowCache();
}
/**
* Checks if there is a converter set explicitly for the given property id.
*
* @param propertyId
* The propertyId to check
* @return true if a converter has been set for the property id, false
* otherwise
*/
protected boolean hasConverter(Object propertyId) {
return propertyValueConverters.containsKey(propertyId);
}
/**
* Returns the converter used to format the given propertyId.
*
* @param propertyId
* The propertyId to check
* @return The converter used to format the propertyId or null if no
* converter has been set
*/
public Converter<String, Object> getConverter(Object propertyId) {
return propertyValueConverters.get(propertyId);
}
@Override
public void setVisible(boolean visible) {
if (visible) {
// We need to ensure that the rows are sent to the client when the
// Table is made visible if it has been rendered as invisible.
setRowCacheInvalidated(true);
}
super.setVisible(visible);
}
@Override
public Iterator<Component> iterator() {
return getComponentIterator();
}
@Override
public Iterator<Component> getComponentIterator() {
if (visibleComponents == null) {
Collection<Component> empty = Collections.emptyList();
return empty.iterator();
}
return visibleComponents.iterator();
}
@Override
public boolean isComponentVisible(Component childComponent) {
return true;
}
private final Logger getLogger() {
if (logger == null) {
logger = Logger.getLogger(Table.class.getName());
}
return logger;
}
}
|