summaryrefslogtreecommitdiffstatshomepage
path: root/tableview.go
blob: e879c911c94d6eb94b95a95d254332a23a2bb95a (plain) (blame)
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
// Copyright 2011 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build windows

package walk

import (
	"encoding/json"
	"fmt"
	"reflect"
	"syscall"
	"time"
	"unsafe"

	"github.com/lxn/win"
)

const tableViewWindowClass = "WireGuard UI - TableView"

var (
	white                       = win.COLORREF(RGB(255, 255, 255))
	checkmark                   = string([]byte{0xE2, 0x9C, 0x94})
	tableViewFrozenLVWndProcPtr uintptr
	tableViewNormalLVWndProcPtr uintptr
	tableViewHdrWndProcPtr      uintptr
)

func init() {
	AppendToWalkInit(func() {
		MustRegisterWindowClass(tableViewWindowClass)
		tableViewFrozenLVWndProcPtr = syscall.NewCallback(tableViewFrozenLVWndProc)
		tableViewNormalLVWndProcPtr = syscall.NewCallback(tableViewNormalLVWndProc)
		tableViewHdrWndProcPtr = syscall.NewCallback(tableViewHdrWndProc)
	})
}

const (
	tableViewCurrentIndexChangedTimerId = 1 + iota
	tableViewSelectedIndexesChangedTimerId
)

type TableViewCfg struct {
	Style              uint32
	CustomHeaderHeight int // in native pixels?
	CustomRowHeight    int // in native pixels?
}

// TableView is a model based widget for record centric, tabular data.
//
// TableView is implemented as a virtual mode list view to support quite large
// amounts of data.
type TableView struct {
	WidgetBase
	hwndFrozenLV                       win.HWND
	hwndFrozenHdr                      win.HWND
	frozenLVOrigWndProcPtr             uintptr
	frozenHdrOrigWndProcPtr            uintptr
	hwndNormalLV                       win.HWND
	hwndNormalHdr                      win.HWND
	normalLVOrigWndProcPtr             uintptr
	normalHdrOrigWndProcPtr            uintptr
	state                              *tableViewState
	columns                            *TableViewColumnList
	model                              TableModel
	providedModel                      interface{}
	itemChecker                        ItemChecker
	imageProvider                      ImageProvider
	styler                             CellStyler
	style                              CellStyle
	itemFont                           *Font
	hIml                               win.HIMAGELIST
	usingSysIml                        bool
	imageUintptr2Index                 map[uintptr]int32
	filePath2IconIndex                 map[string]int32
	rowsResetHandlerHandle             int
	rowChangedHandlerHandle            int
	rowsChangedHandlerHandle           int
	rowsInsertedHandlerHandle          int
	rowsRemovedHandlerHandle           int
	sortChangedHandlerHandle           int
	selectedIndexes                    []int
	prevIndex                          int
	currentIndex                       int
	itemIndexOfLastMouseButtonDown     int
	hwndItemChanged                    win.HWND
	currentIndexChangedPublisher       EventPublisher
	selectedIndexesChangedPublisher    EventPublisher
	itemActivatedPublisher             EventPublisher
	columnClickedPublisher             IntEventPublisher
	columnsOrderableChangedPublisher   EventPublisher
	columnsSizableChangedPublisher     EventPublisher
	itemCountChangedPublisher          EventPublisher
	publishNextSelClear                bool
	inSetSelectedIndexes               bool
	lastColumnStretched                bool
	persistent                         bool
	itemStateChangedEventDelay         int
	themeNormalBGColor                 Color
	themeNormalTextColor               Color
	themeSelectedBGColor               Color
	themeSelectedTextColor             Color
	themeSelectedNotFocusedBGColor     Color
	itemBGColor                        Color
	itemTextColor                      Color
	alternatingRowBGColor              Color
	alternatingRowTextColor            Color
	alternatingRowBG                   bool
	delayedCurrentIndexChangedCanceled bool
	sortedColumnIndex                  int
	sortOrder                          SortOrder
	formActivatingHandle               int
	customHeaderHeight                 int // in native pixels?
	customRowHeight                    int // in native pixels?
	dpiOfPrevStretchLastColumn         int
	scrolling                          bool
	inSetCurrentIndex                  bool
	inMouseEvent                       bool
	hasFrozenColumn                    bool
	busyStretchingLastColumn           bool
	focused                            bool
	ignoreNowhere                      bool
	updateLVSizesNeedsSpecialCare      bool
	scrollbarOrientation               Orientation
	currentItemChangedPublisher        EventPublisher
	currentItemID                      interface{}
	restoringCurrentItemOnReset        bool
}

// NewTableView creates and returns a *TableView as child of the specified
// Container.
func NewTableView(parent Container) (*TableView, error) {
	return NewTableViewWithStyle(parent, win.LVS_SHOWSELALWAYS)
}

// NewTableViewWithStyle creates and returns a *TableView as child of the specified
// Container and with the provided additional style bits set.
func NewTableViewWithStyle(parent Container, style uint32) (*TableView, error) {
	return NewTableViewWithCfg(parent, &TableViewCfg{Style: style})
}

// NewTableViewWithCfg creates and returns a *TableView as child of the specified
// Container and with the provided additional configuration.
func NewTableViewWithCfg(parent Container, cfg *TableViewCfg) (*TableView, error) {
	tv := &TableView{
		imageUintptr2Index:          make(map[uintptr]int32),
		filePath2IconIndex:          make(map[string]int32),
		formActivatingHandle:        -1,
		customHeaderHeight:          cfg.CustomHeaderHeight,
		customRowHeight:             cfg.CustomRowHeight,
		scrollbarOrientation:        Horizontal | Vertical,
		restoringCurrentItemOnReset: true,
	}

	tv.columns = newTableViewColumnList(tv)

	if err := InitWidget(
		tv,
		parent,
		tableViewWindowClass,
		win.WS_BORDER|win.WS_VISIBLE,
		win.WS_EX_CONTROLPARENT); err != nil {
		return nil, err
	}

	succeeded := false
	defer func() {
		if !succeeded {
			tv.Dispose()
		}
	}()

	var rowHeightStyle uint32
	if cfg.CustomRowHeight > 0 {
		rowHeightStyle = win.LVS_OWNERDRAWFIXED
	}

	if tv.hwndFrozenLV = win.CreateWindowEx(
		0,
		syscall.StringToUTF16Ptr("SysListView32"),
		nil,
		win.WS_CHILD|win.WS_CLIPSIBLINGS|win.WS_TABSTOP|win.WS_VISIBLE|win.LVS_OWNERDATA|win.LVS_REPORT|cfg.Style|rowHeightStyle,
		win.CW_USEDEFAULT,
		win.CW_USEDEFAULT,
		win.CW_USEDEFAULT,
		win.CW_USEDEFAULT,
		tv.hWnd,
		0,
		0,
		nil,
	); tv.hwndFrozenLV == 0 {
		return nil, newError("creating frozen lv failed")
	}

	tv.frozenLVOrigWndProcPtr = win.SetWindowLongPtr(tv.hwndFrozenLV, win.GWLP_WNDPROC, tableViewFrozenLVWndProcPtr)
	if tv.frozenLVOrigWndProcPtr == 0 {
		return nil, lastError("SetWindowLongPtr")
	}

	tv.hwndFrozenHdr = win.HWND(win.SendMessage(tv.hwndFrozenLV, win.LVM_GETHEADER, 0, 0))
	tv.frozenHdrOrigWndProcPtr = win.SetWindowLongPtr(tv.hwndFrozenHdr, win.GWLP_WNDPROC, tableViewHdrWndProcPtr)
	if tv.frozenHdrOrigWndProcPtr == 0 {
		return nil, lastError("SetWindowLongPtr")
	}

	if tv.hwndNormalLV = win.CreateWindowEx(
		0,
		syscall.StringToUTF16Ptr("SysListView32"),
		nil,
		win.WS_CHILD|win.WS_CLIPSIBLINGS|win.WS_TABSTOP|win.WS_VISIBLE|win.LVS_OWNERDATA|win.LVS_REPORT|cfg.Style|rowHeightStyle,
		win.CW_USEDEFAULT,
		win.CW_USEDEFAULT,
		win.CW_USEDEFAULT,
		win.CW_USEDEFAULT,
		tv.hWnd,
		0,
		0,
		nil,
	); tv.hwndNormalLV == 0 {
		return nil, newError("creating normal lv failed")
	}

	tv.normalLVOrigWndProcPtr = win.SetWindowLongPtr(tv.hwndNormalLV, win.GWLP_WNDPROC, tableViewNormalLVWndProcPtr)
	if tv.normalLVOrigWndProcPtr == 0 {
		return nil, lastError("SetWindowLongPtr")
	}

	tv.hwndNormalHdr = win.HWND(win.SendMessage(tv.hwndNormalLV, win.LVM_GETHEADER, 0, 0))
	tv.normalHdrOrigWndProcPtr = win.SetWindowLongPtr(tv.hwndNormalHdr, win.GWLP_WNDPROC, tableViewHdrWndProcPtr)
	if tv.normalHdrOrigWndProcPtr == 0 {
		return nil, lastError("SetWindowLongPtr")
	}

	tv.SetPersistent(true)

	exStyle := win.SendMessage(tv.hwndFrozenLV, win.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
	exStyle |= win.LVS_EX_DOUBLEBUFFER | win.LVS_EX_FULLROWSELECT | win.LVS_EX_HEADERDRAGDROP | win.LVS_EX_LABELTIP | win.LVS_EX_SUBITEMIMAGES
	win.SendMessage(tv.hwndFrozenLV, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle)
	win.SendMessage(tv.hwndNormalLV, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle)

	if hr := win.SetWindowTheme(tv.hwndFrozenLV, syscall.StringToUTF16Ptr("Explorer"), nil); win.FAILED(hr) {
		return nil, errorFromHRESULT("SetWindowTheme", hr)
	}
	if hr := win.SetWindowTheme(tv.hwndNormalLV, syscall.StringToUTF16Ptr("Explorer"), nil); win.FAILED(hr) {
		return nil, errorFromHRESULT("SetWindowTheme", hr)
	}

	win.SendMessage(tv.hwndFrozenLV, win.WM_CHANGEUISTATE, uintptr(win.MAKELONG(win.UIS_SET, win.UISF_HIDEFOCUS)), 0)
	win.SendMessage(tv.hwndNormalLV, win.WM_CHANGEUISTATE, uintptr(win.MAKELONG(win.UIS_SET, win.UISF_HIDEFOCUS)), 0)

	tv.group.toolTip.addTool(tv.hwndFrozenHdr, false)
	tv.group.toolTip.addTool(tv.hwndNormalHdr, false)

	tv.applyFont(parent.Font())

	tv.style.dpi = tv.DPI()
	tv.ApplySysColors()

	tv.currentIndex = -1

	tv.GraphicsEffects().Add(InteractionEffect)
	tv.GraphicsEffects().Add(FocusEffect)

	tv.MustRegisterProperty("ColumnsOrderable", NewBoolProperty(
		func() bool {
			return tv.ColumnsOrderable()
		},
		func(b bool) error {
			tv.SetColumnsOrderable(b)
			return nil
		},
		tv.columnsOrderableChangedPublisher.Event()))

	tv.MustRegisterProperty("ColumnsSizable", NewBoolProperty(
		func() bool {
			return tv.ColumnsSizable()
		},
		func(b bool) error {
			return tv.SetColumnsSizable(b)
		},
		tv.columnsSizableChangedPublisher.Event()))

	tv.MustRegisterProperty("CurrentIndex", NewProperty(
		func() interface{} {
			return tv.CurrentIndex()
		},
		func(v interface{}) error {
			return tv.SetCurrentIndex(assertIntOr(v, -1))
		},
		tv.CurrentIndexChanged()))

	tv.MustRegisterProperty("CurrentItem", NewReadOnlyProperty(
		func() interface{} {
			if i := tv.CurrentIndex(); i > -1 {
				if rm, ok := tv.providedModel.(reflectModel); ok {
					return reflect.ValueOf(rm.Items()).Index(i).Interface()
				}
			}

			return nil
		},
		tv.CurrentIndexChanged()))

	tv.MustRegisterProperty("HasCurrentItem", NewReadOnlyBoolProperty(
		func() bool {
			return tv.CurrentIndex() != -1
		},
		tv.CurrentIndexChanged()))

	tv.MustRegisterProperty("ItemCount", NewReadOnlyProperty(
		func() interface{} {
			if tv.model == nil {
				return 0
			}
			return tv.model.RowCount()
		},
		tv.itemCountChangedPublisher.Event()))

	tv.MustRegisterProperty("SelectedCount", NewReadOnlyProperty(
		func() interface{} {
			return len(tv.selectedIndexes)
		},
		tv.SelectedIndexesChanged()))

	succeeded = true

	return tv, nil
}

func (tv *TableView) asTableView() *TableView {
	return tv
}

// Dispose releases the operating system resources, associated with the
// *TableView.
func (tv *TableView) Dispose() {
	tv.columns.unsetColumnsTV()

	tv.disposeImageListAndCaches()

	if tv.hWnd != 0 {
		if !win.KillTimer(tv.hWnd, tableViewCurrentIndexChangedTimerId) {
			lastError("KillTimer")
		}
		if !win.KillTimer(tv.hWnd, tableViewSelectedIndexesChangedTimerId) {
			lastError("KillTimer")
		}
	}

	if tv.hwndFrozenLV != 0 {
		tv.group.toolTip.removeTool(tv.hwndFrozenHdr)
		win.DestroyWindow(tv.hwndFrozenLV)
		tv.hwndFrozenLV = 0
	}

	if tv.hwndNormalLV != 0 {
		tv.group.toolTip.removeTool(tv.hwndNormalHdr)
		win.DestroyWindow(tv.hwndNormalLV)
		tv.hwndNormalLV = 0
	}

	if tv.formActivatingHandle > -1 {
		if form := tv.Form(); form != nil {
			form.Activating().Detach(tv.formActivatingHandle)
		}
		tv.formActivatingHandle = -1
	}

	tv.WidgetBase.Dispose()
}

func (tv *TableView) applyEnabled(enabled bool) {
	tv.WidgetBase.applyEnabled(enabled)

	win.EnableWindow(tv.hwndFrozenLV, enabled)
	win.EnableWindow(tv.hwndNormalLV, enabled)
}

func (tv *TableView) applyFont(font *Font) {
	if tv.customHeaderHeight > 0 || tv.customRowHeight > 0 {
		return
	}

	tv.WidgetBase.applyFont(font)

	hFont := uintptr(font.handleForDPI(tv.DPI()))

	win.SendMessage(tv.hwndFrozenLV, win.WM_SETFONT, hFont, 0)
	win.SendMessage(tv.hwndNormalLV, win.WM_SETFONT, hFont, 0)
}

func (tv *TableView) ApplyDPI(dpi int) {
	tv.style.dpi = dpi
	if tv.style.canvas != nil {
		tv.style.canvas.dpi = dpi
	}

	tv.WidgetBase.ApplyDPI(dpi)

	for _, column := range tv.columns.items {
		column.update()
	}

	if tv.hIml != 0 {
		tv.disposeImageListAndCaches()

		if bmp, err := NewBitmapForDPI(SizeFrom96DPI(Size{16, 16}, dpi), dpi); err == nil {
			tv.applyImageListForImage(bmp)
			bmp.Dispose()
		}
	}
}

func (tv *TableView) ApplySysColors() {
	tv.WidgetBase.ApplySysColors()

	// As some combinations of property and state may be invalid for any theme,
	// we set some defaults here.
	tv.themeNormalBGColor = Color(win.GetSysColor(win.COLOR_WINDOW))
	tv.themeNormalTextColor = Color(win.GetSysColor(win.COLOR_WINDOWTEXT))
	tv.themeSelectedBGColor = tv.themeNormalBGColor
	tv.themeSelectedTextColor = tv.themeNormalTextColor
	tv.themeSelectedNotFocusedBGColor = tv.themeNormalBGColor
	tv.alternatingRowBGColor = Color(win.GetSysColor(win.COLOR_BTNFACE))
	tv.alternatingRowTextColor = Color(win.GetSysColor(win.COLOR_BTNTEXT))

	type item struct {
		stateID    int32
		propertyID int32
		color      *Color
	}

	getThemeColor := func(theme win.HTHEME, partId int32, items []item) {
		for _, item := range items {
			var c win.COLORREF
			if result := win.GetThemeColor(theme, partId, item.stateID, item.propertyID, &c); !win.FAILED(result) {
				(*item.color) = Color(c)
			}
		}
	}

	if hThemeListView := win.OpenThemeData(tv.hwndNormalLV, syscall.StringToUTF16Ptr("Listview")); hThemeListView != 0 {
		defer win.CloseThemeData(hThemeListView)

		getThemeColor(hThemeListView, win.LVP_LISTITEM, []item{
			{win.LISS_NORMAL, win.TMT_FILLCOLOR, &tv.themeNormalBGColor},
			{win.LISS_NORMAL, win.TMT_TEXTCOLOR, &tv.themeNormalTextColor},
			{win.LISS_SELECTED, win.TMT_FILLCOLOR, &tv.themeSelectedBGColor},
			{win.LISS_SELECTED, win.TMT_TEXTCOLOR, &tv.themeSelectedTextColor},
			{win.LISS_SELECTEDNOTFOCUS, win.TMT_FILLCOLOR, &tv.themeSelectedNotFocusedBGColor},
		})
	} else {
		// The others already have been retrieved above.
		tv.themeSelectedBGColor = Color(win.GetSysColor(win.COLOR_HIGHLIGHT))
		tv.themeSelectedTextColor = Color(win.GetSysColor(win.COLOR_HIGHLIGHTTEXT))
		tv.themeSelectedNotFocusedBGColor = Color(win.GetSysColor(win.COLOR_BTNFACE))
	}

	if hThemeButton := win.OpenThemeData(tv.hwndNormalLV, syscall.StringToUTF16Ptr("BUTTON")); hThemeButton != 0 {
		defer win.CloseThemeData(hThemeButton)

		getThemeColor(hThemeButton, win.BP_PUSHBUTTON, []item{
			{win.PBS_NORMAL, win.TMT_FILLCOLOR, &tv.alternatingRowBGColor},
			{win.PBS_NORMAL, win.TMT_TEXTCOLOR, &tv.alternatingRowTextColor},
		})
	}

	win.SendMessage(tv.hwndNormalLV, win.LVM_SETBKCOLOR, 0, uintptr(tv.themeNormalBGColor))
	win.SendMessage(tv.hwndFrozenLV, win.LVM_SETBKCOLOR, 0, uintptr(tv.themeNormalBGColor))
}

// ColumnsOrderable returns if the user can reorder columns by dragging and
// dropping column headers.
func (tv *TableView) ColumnsOrderable() bool {
	exStyle := win.SendMessage(tv.hwndNormalLV, win.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
	return exStyle&win.LVS_EX_HEADERDRAGDROP > 0
}

// SetColumnsOrderable sets if the user can reorder columns by dragging and
// dropping column headers.
func (tv *TableView) SetColumnsOrderable(enabled bool) {
	var hwnd win.HWND
	if tv.hasFrozenColumn {
		hwnd = tv.hwndFrozenLV
	} else {
		hwnd = tv.hwndNormalLV
	}

	exStyle := win.SendMessage(hwnd, win.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
	if enabled {
		exStyle |= win.LVS_EX_HEADERDRAGDROP
	} else {
		exStyle &^= win.LVS_EX_HEADERDRAGDROP
	}
	win.SendMessage(tv.hwndFrozenLV, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle)
	win.SendMessage(tv.hwndNormalLV, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle)

	tv.columnsOrderableChangedPublisher.Publish()
}

// ColumnsSizable returns if the user can change column widths by dragging
// dividers in the header.
func (tv *TableView) ColumnsSizable() bool {
	style := win.GetWindowLong(tv.hwndNormalHdr, win.GWL_STYLE)

	return style&win.HDS_NOSIZING == 0
}

// SetColumnsSizable sets if the user can change column widths by dragging
// dividers in the header.
func (tv *TableView) SetColumnsSizable(b bool) error {
	updateStyle := func(headerHWnd win.HWND) error {
		style := win.GetWindowLong(headerHWnd, win.GWL_STYLE)

		if b {
			style &^= win.HDS_NOSIZING
		} else {
			style |= win.HDS_NOSIZING
		}

		if 0 == win.SetWindowLong(headerHWnd, win.GWL_STYLE, style) {
			return lastError("SetWindowLong(GWL_STYLE)")
		}

		return nil
	}

	if err := updateStyle(tv.hwndFrozenHdr); err != nil {
		return err
	}
	if err := updateStyle(tv.hwndNormalHdr); err != nil {
		return err
	}

	tv.columnsSizableChangedPublisher.Publish()

	return nil
}

// ContextMenuLocation returns selected item position in screen coordinates in native pixels.
func (tv *TableView) ContextMenuLocation() Point {
	idx := win.SendMessage(tv.hwndNormalLV, win.LVM_GETSELECTIONMARK, 0, 0)
	rc := win.RECT{Left: win.LVIR_BOUNDS}
	if 0 == win.SendMessage(tv.hwndNormalLV, win.LVM_GETITEMRECT, idx, uintptr(unsafe.Pointer(&rc))) {
		return tv.WidgetBase.ContextMenuLocation()
	}
	var pt win.POINT
	if tv.RightToLeftReading() {
		pt.X = rc.Right
	} else {
		pt.X = rc.Left
	}
	pt.X = rc.Bottom
	windowTrimToClientBounds(tv.hwndNormalLV, &pt)
	win.ClientToScreen(tv.hwndNormalLV, &pt)
	return pointPixelsFromPOINT(pt)
}

// SortableByHeaderClick returns if the user can change sorting by clicking the header.
func (tv *TableView) SortableByHeaderClick() bool {
	return !hasWindowLongBits(tv.hwndFrozenLV, win.GWL_STYLE, win.LVS_NOSORTHEADER) ||
		!hasWindowLongBits(tv.hwndNormalLV, win.GWL_STYLE, win.LVS_NOSORTHEADER)
}

// HeaderHidden returns whether the column header is hidden.
func (tv *TableView) HeaderHidden() bool {
	style := win.GetWindowLong(tv.hwndNormalLV, win.GWL_STYLE)

	return style&win.LVS_NOCOLUMNHEADER != 0
}

// SetHeaderHidden sets whether the column header is hidden.
func (tv *TableView) SetHeaderHidden(hidden bool) error {
	if err := ensureWindowLongBits(tv.hwndFrozenLV, win.GWL_STYLE, win.LVS_NOCOLUMNHEADER, hidden); err != nil {
		return err
	}

	return ensureWindowLongBits(tv.hwndNormalLV, win.GWL_STYLE, win.LVS_NOCOLUMNHEADER, hidden)
}

// AlternatingRowBG returns the alternating row background.
func (tv *TableView) AlternatingRowBG() bool {
	return tv.alternatingRowBG
}

// SetAlternatingRowBG sets the alternating row background.
func (tv *TableView) SetAlternatingRowBG(enabled bool) {
	tv.alternatingRowBG = enabled

	tv.Invalidate()
}

// Gridlines returns if the rows are separated by grid lines.
func (tv *TableView) Gridlines() bool {
	exStyle := win.SendMessage(tv.hwndNormalLV, win.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
	return exStyle&win.LVS_EX_GRIDLINES > 0
}

// SetGridlines sets if the rows are separated by grid lines.
func (tv *TableView) SetGridlines(enabled bool) {
	var hwnd win.HWND
	if tv.hasFrozenColumn {
		hwnd = tv.hwndFrozenLV
	} else {
		hwnd = tv.hwndNormalLV
	}

	exStyle := win.SendMessage(hwnd, win.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
	if enabled {
		exStyle |= win.LVS_EX_GRIDLINES
	} else {
		exStyle &^= win.LVS_EX_GRIDLINES
	}
	win.SendMessage(tv.hwndFrozenLV, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle)
	win.SendMessage(tv.hwndNormalLV, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle)
}

// Columns returns the list of columns.
func (tv *TableView) Columns() *TableViewColumnList {
	return tv.columns
}

// VisibleColumnsInDisplayOrder returns a slice of visible columns in display
// order.
func (tv *TableView) VisibleColumnsInDisplayOrder() []*TableViewColumn {
	visibleCols := tv.visibleColumns()
	indices := make([]int32, len(visibleCols))

	frozenCount := tv.visibleFrozenColumnCount()
	normalCount := len(visibleCols) - frozenCount

	if frozenCount > 0 {
		if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_GETCOLUMNORDERARRAY, uintptr(frozenCount), uintptr(unsafe.Pointer(&indices[0]))) {
			newError("LVM_GETCOLUMNORDERARRAY")
			return nil
		}
	}
	if normalCount > 0 {
		if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_GETCOLUMNORDERARRAY, uintptr(normalCount), uintptr(unsafe.Pointer(&indices[frozenCount]))) {
			newError("LVM_GETCOLUMNORDERARRAY")
			return nil
		}
	}

	orderedCols := make([]*TableViewColumn, len(visibleCols))

	for i, j := range indices {
		if i >= frozenCount {
			j += int32(frozenCount)
		}
		orderedCols[i] = visibleCols[j]
	}

	return orderedCols
}

// RowsPerPage returns the number of fully visible rows.
func (tv *TableView) RowsPerPage() int {
	return int(win.SendMessage(tv.hwndNormalLV, win.LVM_GETCOUNTPERPAGE, 0, 0))
}

func (tv *TableView) Invalidate() error {
	win.InvalidateRect(tv.hwndFrozenLV, nil, true)
	win.InvalidateRect(tv.hwndNormalLV, nil, true)

	return tv.WidgetBase.Invalidate()
}

func (tv *TableView) redrawItems() {
	first := win.SendMessage(tv.hwndNormalLV, win.LVM_GETTOPINDEX, 0, 0)
	last := first + win.SendMessage(tv.hwndNormalLV, win.LVM_GETCOUNTPERPAGE, 0, 0) + 1
	win.SendMessage(tv.hwndFrozenLV, win.LVM_REDRAWITEMS, first, last)
	win.SendMessage(tv.hwndNormalLV, win.LVM_REDRAWITEMS, first, last)
}

// UpdateItem ensures the item at index will be redrawn.
//
// If the model supports sorting, it will be resorted.
func (tv *TableView) UpdateItem(index int) error {
	if s, ok := tv.model.(Sorter); ok {
		if err := s.Sort(s.SortedColumn(), s.SortOrder()); err != nil {
			return err
		}
	} else {
		if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_UPDATE, uintptr(index), 0) {
			return newError("LVM_UPDATE")
		}
		if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_UPDATE, uintptr(index), 0) {
			return newError("LVM_UPDATE")
		}
	}

	return nil
}

func (tv *TableView) attachModel() {
	restoreCurrentItemOrFallbackToFirst := func(ip IDProvider) {
		if tv.itemStateChangedEventDelay == 0 {
			defer tv.currentItemChangedPublisher.Publish()
		} else {
			if 0 == win.SetTimer(
				tv.hWnd,
				tableViewCurrentIndexChangedTimerId,
				uint32(tv.itemStateChangedEventDelay),
				0,
			) {
				lastError("SetTimer")
			}
		}

		count := tv.model.RowCount()
		for i := 0; i < count; i++ {
			if ip.ID(i) == tv.currentItemID {
				tv.SetCurrentIndex(i)
				return
			}
		}

		tv.SetCurrentIndex(0)
	}

	tv.rowsResetHandlerHandle = tv.model.RowsReset().Attach(func() {
		tv.setItemCount()

		if ip, ok := tv.providedModel.(IDProvider); ok && tv.restoringCurrentItemOnReset {
			if _, ok := tv.model.(Sorter); !ok {
				restoreCurrentItemOrFallbackToFirst(ip)
			}
		} else {
			tv.SetCurrentIndex(-1)
		}

		tv.itemCountChangedPublisher.Publish()
	})

	tv.rowChangedHandlerHandle = tv.model.RowChanged().Attach(func(row int) {
		tv.UpdateItem(row)
	})

	tv.rowsChangedHandlerHandle = tv.model.RowsChanged().Attach(func(from, to int) {
		if s, ok := tv.model.(Sorter); ok {
			s.Sort(s.SortedColumn(), s.SortOrder())
		} else {
			first, last := uintptr(from), uintptr(to)
			win.SendMessage(tv.hwndFrozenLV, win.LVM_REDRAWITEMS, first, last)
			win.SendMessage(tv.hwndNormalLV, win.LVM_REDRAWITEMS, first, last)
		}
	})

	tv.rowsInsertedHandlerHandle = tv.model.RowsInserted().Attach(func(from, to int) {
		i := tv.currentIndex

		tv.setItemCount()

		if from <= i {
			i += 1 + to - from

			tv.SetCurrentIndex(i)
		}

		tv.itemCountChangedPublisher.Publish()
	})

	tv.rowsRemovedHandlerHandle = tv.model.RowsRemoved().Attach(func(from, to int) {
		i := tv.currentIndex

		tv.setItemCount()

		index := i

		if from <= i && i <= to {
			index = -1
		} else if from < i {
			index -= 1 + to - from
		}

		if index != i {
			tv.SetCurrentIndex(index)
		}

		tv.itemCountChangedPublisher.Publish()
	})

	if sorter, ok := tv.model.(Sorter); ok {
		tv.sortChangedHandlerHandle = sorter.SortChanged().Attach(func() {
			if ip, ok := tv.providedModel.(IDProvider); ok && tv.restoringCurrentItemOnReset {
				restoreCurrentItemOrFallbackToFirst(ip)
			}

			col := sorter.SortedColumn()
			tv.setSortIcon(col, sorter.SortOrder())

			tv.redrawItems()
		})
	}
}

func (tv *TableView) detachModel() {
	tv.model.RowsReset().Detach(tv.rowsResetHandlerHandle)
	tv.model.RowChanged().Detach(tv.rowChangedHandlerHandle)
	tv.model.RowsInserted().Detach(tv.rowsInsertedHandlerHandle)
	tv.model.RowsRemoved().Detach(tv.rowsRemovedHandlerHandle)
	if sorter, ok := tv.model.(Sorter); ok {
		sorter.SortChanged().Detach(tv.sortChangedHandlerHandle)
	}
}

// ItemCountChanged returns the event that is published when the number of items
// in the model of the TableView changed.
func (tv *TableView) ItemCountChanged() *Event {
	return tv.itemCountChangedPublisher.Event()
}

// Model returns the model of the TableView.
func (tv *TableView) Model() interface{} {
	return tv.providedModel
}

// SetModel sets the model of the TableView.
//
// It is required that mdl either implements walk.TableModel,
// walk.ReflectTableModel or be a slice of pointers to struct or a
// []map[string]interface{}. A walk.TableModel implementation must also
// implement walk.Sorter to support sorting, all other options get sorting for
// free. To support item check boxes and icons, mdl must implement
// walk.ItemChecker and walk.ImageProvider, respectively. On-demand model
// population for a walk.ReflectTableModel or slice requires mdl to implement
// walk.Populator.
func (tv *TableView) SetModel(mdl interface{}) error {
	model, ok := mdl.(TableModel)
	if !ok && mdl != nil {
		var err error
		if model, err = newReflectTableModel(mdl); err != nil {
			if model, err = newMapTableModel(mdl); err != nil {
				return err
			}
		}
	}

	tv.SetSuspended(true)
	defer tv.SetSuspended(false)

	if tv.model != nil {
		tv.detachModel()

		tv.disposeImageListAndCaches()
	}

	oldProvidedModelStyler, _ := tv.providedModel.(CellStyler)
	if styler, ok := mdl.(CellStyler); ok || tv.styler == oldProvidedModelStyler {
		tv.styler = styler
	}

	tv.providedModel = mdl
	tv.model = model

	tv.itemChecker, _ = model.(ItemChecker)
	tv.imageProvider, _ = model.(ImageProvider)

	if model != nil {
		tv.attachModel()

		if dms, ok := model.(dataMembersSetter); ok {
			// FIXME: This depends on columns to be initialized before
			// calling this method.
			dataMembers := make([]string, len(tv.columns.items))

			for i, col := range tv.columns.items {
				dataMembers[i] = col.DataMemberEffective()
			}

			dms.setDataMembers(dataMembers)
		}

		if lfs, ok := model.(lessFuncsSetter); ok {
			lessFuncs := make([]func(i, j int) bool, tv.columns.Len())
			for i, c := range tv.columns.items {
				lessFuncs[i] = c.lessFunc
			}
			lfs.setLessFuncs(lessFuncs)
		}

		if sorter, ok := tv.model.(Sorter); ok {
			if tv.sortedColumnIndex >= tv.visibleColumnCount() {
				tv.sortedColumnIndex = maxi(-1, mini(0, tv.visibleColumnCount()-1))
				tv.sortOrder = SortAscending
			}

			sorter.Sort(tv.sortedColumnIndex, tv.sortOrder)
		}
	}

	tv.SetCurrentIndex(-1)

	tv.setItemCount()

	tv.itemCountChangedPublisher.Publish()

	return nil
}

// TableModel returns the TableModel of the TableView.
func (tv *TableView) TableModel() TableModel {
	return tv.model
}

// ItemChecker returns the ItemChecker of the TableView.
func (tv *TableView) ItemChecker() ItemChecker {
	return tv.itemChecker
}

// SetItemChecker sets the ItemChecker of the TableView.
func (tv *TableView) SetItemChecker(itemChecker ItemChecker) {
	tv.itemChecker = itemChecker
}

// CellStyler returns the CellStyler of the TableView.
func (tv *TableView) CellStyler() CellStyler {
	return tv.styler
}

// SetCellStyler sets the CellStyler of the TableView.
func (tv *TableView) SetCellStyler(styler CellStyler) {
	tv.styler = styler
}

func (tv *TableView) setItemCount() error {
	var count int

	if tv.model != nil {
		count = tv.model.RowCount()
	}

	if 0 == win.SendMessage(tv.hwndFrozenLV, win.LVM_SETITEMCOUNT, uintptr(count), win.LVSICF_NOINVALIDATEALL|win.LVSICF_NOSCROLL) {
		return newError("SendMessage(LVM_SETITEMCOUNT)")
	}
	if 0 == win.SendMessage(tv.hwndNormalLV, win.LVM_SETITEMCOUNT, uintptr(count), win.LVSICF_NOINVALIDATEALL|win.LVSICF_NOSCROLL) {
		return newError("SendMessage(LVM_SETITEMCOUNT)")
	}

	return nil
}

// CheckBoxes returns if the *TableView has check boxes.
func (tv *TableView) CheckBoxes() bool {
	var hwnd win.HWND
	if tv.hasFrozenColumn {
		hwnd = tv.hwndFrozenLV
	} else {
		hwnd = tv.hwndNormalLV
	}

	return win.SendMessage(hwnd, win.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)&win.LVS_EX_CHECKBOXES > 0
}

// SetCheckBoxes sets if the *TableView has check boxes.
func (tv *TableView) SetCheckBoxes(checkBoxes bool) {
	var hwnd, hwndOther win.HWND
	if tv.hasFrozenColumn {
		hwnd, hwndOther = tv.hwndFrozenLV, tv.hwndNormalLV
	} else {
		hwnd, hwndOther = tv.hwndNormalLV, tv.hwndFrozenLV
	}

	exStyle := win.SendMessage(hwnd, win.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0)
	oldStyle := exStyle
	if checkBoxes {
		exStyle |= win.LVS_EX_CHECKBOXES
	} else {
		exStyle &^= win.LVS_EX_CHECKBOXES
	}
	if exStyle != oldStyle {
		win.SendMessage(hwnd, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle)
	}

	win.SendMessage(hwndOther, win.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, exStyle&^win.LVS_EX_CHECKBOXES)

	mask := win.SendMessage(hwnd, win.LVM_GETCALLBACKMASK, 0, 0)

	if checkBoxes {
		mask |= win.LVIS_STATEIMAGEMASK
	} else {
		mask &^= win.LVIS_STATEIMAGEMASK
	}

	if win.FALSE == win.SendMessage(hwnd, win.LVM_SETCALLBACKMASK, mask, 0) {
		newError("SendMessage(LVM_SETCALLBACKMASK)")
	}
}

func (tv *TableView) fromLVColIdx(frozen bool, index int32) int {
	var idx int32

	for i, tvc := range tv.columns.items {
		if frozen == tvc.frozen && tvc.visible {
			if idx == index {
				return i
			}

			idx++
		}
	}

	return -1
}

func (tv *TableView) toLVColIdx(index int) int32 {
	var idx int32

	for i, tvc := range tv.columns.items {
		if tvc.visible {
			if i == index {
				return idx
			}

			idx++
		}
	}

	return -1
}

func (tv *TableView) visibleFrozenColumnCount() int {
	var count int

	for _, tvc := range tv.columns.items {
		if tvc.frozen && tvc.visible {
			count++
		}
	}

	return count
}

func (tv *TableView) visibleColumnCount() int {
	var count int

	for _, tvc := range tv.columns.items {
		if tvc.visible {
			count++
		}
	}

	return count
}

func (tv *TableView) visibleColumns() []*TableViewColumn {
	var cols []*TableViewColumn

	for _, tvc := range tv.columns.items {
		if tvc.visible {
			cols = append(cols, tvc)
		}
	}

	return cols
}

/*func (tv *TableView) selectedColumnIndex() int {
	return tv.fromLVColIdx(tv.SendMessage(LVM_GETSELECTEDCOLUMN, 0, 0))
}*/

// func (tv *TableView) setSelectedColumnIndex(index int) {
// 	tv.SendMessage(win.LVM_SETSELECTEDCOLUMN, uintptr(tv.toLVColIdx(index)), 0)
// }

func (tv *TableView) setSortIcon(index int, order SortOrder) error {
	idx := int(tv.toLVColIdx(index))

	frozenCount := tv.visibleFrozenColumnCount()

	for i, col := range tv.visibleColumns() {
		item := win.HDITEM{
			Mask: win.HDI_FORMAT,
		}

		var headerHwnd win.HWND
		var offset int
		if col.frozen {
			headerHwnd = tv.hwndFrozenHdr
		} else {
			headerHwnd = tv.hwndNormalHdr
			offset = -frozenCount
		}

		iPtr := uintptr(offset + i)
		itemPtr := uintptr(unsafe.Pointer(&item))

		if win.SendMessage(headerHwnd, win.HDM_GETITEM, iPtr, itemPtr) == 0 {
			return newError("SendMessage(HDM_GETITEM)")
		}

		if i == idx {
			switch order {
			case SortAscending:
				item.Fmt &^= win.HDF_SORTDOWN
				item.Fmt |= win.HDF_SORTUP

			case SortDescending:
				item.Fmt &^= win.HDF_SORTUP
				item.Fmt |= win.HDF_SORTDOWN
			}
		} else {
			item.Fmt &^= win.HDF_SORTDOWN | win.HDF_SORTUP
		}

		if win.SendMessage(headerHwnd, win.HDM_SETITEM, iPtr, itemPtr) == 0 {
			return newError("SendMessage(HDM_SETITEM)")
		}
	}

	return nil
}

// ColumnClicked returns the event that is published after a column header was
// clicked.
func (tv *TableView) ColumnClicked() *IntEvent {
	return tv.columnClickedPublisher.Event()
}

// ItemActivated returns the event that is published after an item was
// activated.
//
// An item is activated when it is double clicked or the enter key is pressed
// when the item is selected.
func (tv *TableView) ItemActivated() *Event {
	return tv.itemActivatedPublisher.Event()
}

// RestoringCurrentItemOnReset returns whether the TableView after its model
// has been reset should attempt to restore CurrentIndex to the item that was
// current before the reset.
//
// For this to work, the model must implement the IDProvider interface.
func (tv *TableView) RestoringCurrentItemOnReset() bool {
	return tv.restoringCurrentItemOnReset
}

// SetRestoringCurrentItemOnReset sets whether the TableView after its model
// has been reset should attempt to restore CurrentIndex to the item that was
// current before the reset.
//
// For this to work, the model must implement the IDProvider interface.
func (tv *TableView) SetRestoringCurrentItemOnReset(restoring bool) {
	tv.restoringCurrentItemOnReset = restoring
}

// CurrentItemChanged returns the event that is published after the current
// item has changed.
//
// For this to work, the model must implement the IDProvider interface.
func (tv *TableView) CurrentItemChanged() *Event {
	return tv.currentItemChangedPublisher.Event()
}

// CurrentIndex returns the index of the current item, or -1 if there is no
// current item.
func (tv *TableView) CurrentIndex() int {
	return tv.currentIndex
}

// SetCurrentIndex sets the index of the current item.
//
// Call this with a value of -1 to have no current item.
func (tv *TableView) SetCurrentIndex(index int) error {
	if tv.inSetCurrentIndex {
		return nil
	}
	tv.inSetCurrentIndex = true
	defer func() {
		tv.inSetCurrentIndex = false
	}()

	var lvi win.LVITEM

	lvi.StateMask = win.LVIS_FOCUSED | win.LVIS_SELECTED

	if tv.MultiSelection() {
		if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_SETITEMSTATE, ^uintptr(0), uintptr(unsafe.Pointer(&lvi))) {
			return newError("SendMessage(LVM_SETITEMSTATE)")
		}
		if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_SETITEMSTATE, ^uintptr(0), uintptr(unsafe.Pointer(&lvi))) {
			return newError("SendMessage(LVM_SETITEMSTATE)")
		}
	}

	if index > -1 {
		lvi.State = win.LVIS_FOCUSED | win.LVIS_SELECTED
	}

	if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_SETITEMSTATE, uintptr(index), uintptr(unsafe.Pointer(&lvi))) {
		return newError("SendMessage(LVM_SETITEMSTATE)")
	}
	if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_SETITEMSTATE, uintptr(index), uintptr(unsafe.Pointer(&lvi))) {
		return newError("SendMessage(LVM_SETITEMSTATE)")
	}

	if index > -1 {
		if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_ENSUREVISIBLE, uintptr(index), uintptr(0)) {
			return newError("SendMessage(LVM_ENSUREVISIBLE)")
		}
		// Windows bug? Sometimes a second LVM_ENSUREVISIBLE is required.
		if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_ENSUREVISIBLE, uintptr(index), uintptr(0)) {
			return newError("SendMessage(LVM_ENSUREVISIBLE)")
		}
		if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_ENSUREVISIBLE, uintptr(index), uintptr(0)) {
			return newError("SendMessage(LVM_ENSUREVISIBLE)")
		}
		// Windows bug? Sometimes a second LVM_ENSUREVISIBLE is required.
		if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_ENSUREVISIBLE, uintptr(index), uintptr(0)) {
			return newError("SendMessage(LVM_ENSUREVISIBLE)")
		}

		if ip, ok := tv.providedModel.(IDProvider); ok && tv.restoringCurrentItemOnReset {
			if id := ip.ID(index); id != tv.currentItemID {
				tv.currentItemID = id
				if tv.itemStateChangedEventDelay == 0 {
					defer tv.currentItemChangedPublisher.Publish()
				}
			}
		}
	} else {
		tv.currentItemID = nil
		if tv.itemStateChangedEventDelay == 0 {
			defer tv.currentItemChangedPublisher.Publish()
		}
	}

	tv.currentIndex = index

	if index == -1 || tv.itemStateChangedEventDelay == 0 {
		tv.currentIndexChangedPublisher.Publish()
	}

	if tv.MultiSelection() {
		tv.updateSelectedIndexes()
	}

	return nil
}

// CurrentIndexChanged is the event that is published after CurrentIndex has
// changed.
func (tv *TableView) CurrentIndexChanged() *Event {
	return tv.currentIndexChangedPublisher.Event()
}

// IndexAt returns the item index at coordinates x, y of the
// TableView or -1, if that point is not inside any item.
func (tv *TableView) IndexAt(x, y int) int {
	var hti win.LVHITTESTINFO

	var rc win.RECT
	if !win.GetWindowRect(tv.hwndFrozenLV, &rc) {
		return -1
	}

	var hwnd win.HWND
	if x < int(rc.Right-rc.Left) {
		hwnd = tv.hwndFrozenLV
	} else {
		hwnd = tv.hwndNormalLV
	}

	hti.Pt.X = int32(x)
	hti.Pt.Y = int32(y)

	win.SendMessage(hwnd, win.LVM_HITTEST, 0, uintptr(unsafe.Pointer(&hti)))

	return int(hti.IItem)
}

// ItemVisible returns whether the item at position index is visible.
func (tv *TableView) ItemVisible(index int) bool {
	return 0 != win.SendMessage(tv.hwndNormalLV, win.LVM_ISITEMVISIBLE, uintptr(index), 0)
}

// EnsureItemVisible ensures the item at position index is visible, scrolling if necessary.
func (tv *TableView) EnsureItemVisible(index int) {
	win.SendMessage(tv.hwndNormalLV, win.LVM_ENSUREVISIBLE, uintptr(index), 0)
}

// SelectionHiddenWithoutFocus returns whether selection indicators are hidden
// when the TableView does not have the keyboard input focus.
func (tv *TableView) SelectionHiddenWithoutFocus() bool {
	style := uint(win.GetWindowLong(tv.hwndNormalLV, win.GWL_STYLE))
	if style == 0 {
		lastError("GetWindowLong")
		return false
	}

	return style&win.LVS_SHOWSELALWAYS == 0
}

// SetSelectionHiddenWithoutFocus sets whether selection indicators are visible when the TableView does not have the keyboard input focus.
func (tv *TableView) SetSelectionHiddenWithoutFocus(hidden bool) error {
	if err := ensureWindowLongBits(tv.hwndFrozenLV, win.GWL_STYLE, win.LVS_SHOWSELALWAYS, !hidden); err != nil {
		return err
	}

	return ensureWindowLongBits(tv.hwndNormalLV, win.GWL_STYLE, win.LVS_SHOWSELALWAYS, !hidden)
}

// MultiSelection returns whether multiple items can be selected at once.
//
// By default only a single item can be selected at once.
func (tv *TableView) MultiSelection() bool {
	style := uint(win.GetWindowLong(tv.hwndNormalLV, win.GWL_STYLE))
	if style == 0 {
		lastError("GetWindowLong")
		return false
	}

	return style&win.LVS_SINGLESEL == 0
}

// SetMultiSelection sets whether multiple items can be selected at once.
func (tv *TableView) SetMultiSelection(multiSel bool) error {
	if err := ensureWindowLongBits(tv.hwndFrozenLV, win.GWL_STYLE, win.LVS_SINGLESEL, !multiSel); err != nil {
		return err
	}

	return ensureWindowLongBits(tv.hwndNormalLV, win.GWL_STYLE, win.LVS_SINGLESEL, !multiSel)
}

// SelectedIndexes returns the indexes of the currently selected items.
func (tv *TableView) SelectedIndexes() []int {
	indexes := make([]int, len(tv.selectedIndexes))

	for i, j := range tv.selectedIndexes {
		indexes[i] = j
	}

	return indexes
}

// SetSelectedIndexes sets the indexes of the currently selected items.
func (tv *TableView) SetSelectedIndexes(indexes []int) error {
	tv.inSetSelectedIndexes = true
	defer func() {
		tv.inSetSelectedIndexes = false
		tv.publishSelectedIndexesChanged()
	}()

	lvi := &win.LVITEM{StateMask: win.LVIS_FOCUSED | win.LVIS_SELECTED}
	lp := uintptr(unsafe.Pointer(lvi))

	if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_SETITEMSTATE, ^uintptr(0), lp) {
		return newError("SendMessage(LVM_SETITEMSTATE)")
	}
	if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_SETITEMSTATE, ^uintptr(0), lp) {
		return newError("SendMessage(LVM_SETITEMSTATE)")
	}

	selectAll := false
	lvi.State = win.LVIS_FOCUSED | win.LVIS_SELECTED
	for _, i := range indexes {
		val := uintptr(i)
		if i == -1 {
			selectAll = true
			val = ^uintptr(0)
		}
		if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_SETITEMSTATE, val, lp) && i != -1 {
			return newError("SendMessage(LVM_SETITEMSTATE)")
		}
		if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_SETITEMSTATE, val, lp) && i != -1 {
			return newError("SendMessage(LVM_SETITEMSTATE)")
		}
	}

	if !selectAll {
		idxs := make([]int, len(indexes))

		for i, j := range indexes {
			idxs[i] = j
		}

		tv.selectedIndexes = idxs
	} else {
		count := int(win.SendMessage(tv.hwndNormalLV, win.LVM_GETSELECTEDCOUNT, 0, 0))
		idxs := make([]int, count)
		for i := range idxs {
			idxs[i] = i
		}
		tv.selectedIndexes = idxs
	}

	return nil
}

func (tv *TableView) updateSelectedIndexes() {
	count := int(win.SendMessage(tv.hwndNormalLV, win.LVM_GETSELECTEDCOUNT, 0, 0))
	indexes := make([]int, count)

	j := -1
	for i := 0; i < count; i++ {
		j = int(win.SendMessage(tv.hwndNormalLV, win.LVM_GETNEXTITEM, uintptr(j), win.LVNI_SELECTED))
		indexes[i] = j
	}

	changed := len(indexes) != len(tv.selectedIndexes)
	if !changed {
		for i := 0; i < len(indexes); i++ {
			if indexes[i] != tv.selectedIndexes[i] {
				changed = true
				break
			}
		}
	}

	if changed {
		tv.selectedIndexes = indexes
		tv.publishSelectedIndexesChanged()
	}
}

func (tv *TableView) copySelectedIndexes(hwndTo, hwndFrom win.HWND) error {
	count := int(win.SendMessage(hwndFrom, win.LVM_GETSELECTEDCOUNT, 0, 0))

	lvi := &win.LVITEM{StateMask: win.LVIS_FOCUSED | win.LVIS_SELECTED}
	lp := uintptr(unsafe.Pointer(lvi))

	if win.FALSE == win.SendMessage(hwndTo, win.LVM_SETITEMSTATE, ^uintptr(0), lp) {
		return newError("SendMessage(LVM_SETITEMSTATE)")
	}

	lvi.StateMask = win.LVIS_SELECTED
	lvi.State = win.LVIS_SELECTED

	j := -1
	for i := 0; i < count; i++ {
		j = int(win.SendMessage(hwndFrom, win.LVM_GETNEXTITEM, uintptr(j), win.LVNI_SELECTED))

		if win.FALSE == win.SendMessage(hwndTo, win.LVM_SETITEMSTATE, uintptr(j), lp) {
			return newError("SendMessage(LVM_SETITEMSTATE)")
		}
	}

	return nil
}

// ItemStateChangedEventDelay returns the delay in milliseconds, between the
// moment the state of an item in the *TableView changes and the moment the
// associated event is published.
//
// By default there is no delay.
func (tv *TableView) ItemStateChangedEventDelay() int {
	return tv.itemStateChangedEventDelay
}

// SetItemStateChangedEventDelay sets the delay in milliseconds, between the
// moment the state of an item in the *TableView changes and the moment the
// associated event is published.
//
// An example where this may be useful is a master-details scenario. If the
// master TableView is configured to delay the event, you can avoid pointless
// updates of the details TableView, if the user uses arrow keys to rapidly
// navigate the master view.
func (tv *TableView) SetItemStateChangedEventDelay(delay int) {
	tv.itemStateChangedEventDelay = delay
}

// SelectedIndexesChanged returns the event that is published when the list of
// selected item indexes changed.
func (tv *TableView) SelectedIndexesChanged() *Event {
	return tv.selectedIndexesChangedPublisher.Event()
}

func (tv *TableView) publishSelectedIndexesChanged() {
	if tv.itemStateChangedEventDelay > 0 {
		if 0 == win.SetTimer(
			tv.hWnd,
			tableViewSelectedIndexesChangedTimerId,
			uint32(tv.itemStateChangedEventDelay),
			0) {

			lastError("SetTimer")
		}
	} else {
		tv.selectedIndexesChangedPublisher.Publish()
	}
}

// LastColumnStretched returns if the last column should take up all remaining
// horizontal space of the *TableView.
func (tv *TableView) LastColumnStretched() bool {
	return tv.lastColumnStretched
}

// SetLastColumnStretched sets if the last column should take up all remaining
// horizontal space of the *TableView.
//
// The effect of setting this is persistent.
func (tv *TableView) SetLastColumnStretched(value bool) error {
	if value {
		if err := tv.StretchLastColumn(); err != nil {
			return err
		}
	}

	tv.lastColumnStretched = value

	return nil
}

// StretchLastColumn makes the last column take up all remaining horizontal
// space of the *TableView.
//
// The effect of this is not persistent.
func (tv *TableView) StretchLastColumn() error {
	colCount := tv.visibleColumnCount()
	if colCount == 0 {
		return nil
	}

	var hwnd win.HWND
	frozenColCount := tv.visibleFrozenColumnCount()
	if colCount-frozenColCount == 0 {
		hwnd = tv.hwndFrozenLV
		colCount = frozenColCount
	} else {
		hwnd = tv.hwndNormalLV
		colCount -= frozenColCount
	}

	var lp uintptr
	if tv.scrollbarOrientation&Horizontal != 0 {
		lp = win.LVSCW_AUTOSIZE_USEHEADER
	} else {
		width := tv.ClientBoundsPixels().Width

		lastIndexInLV := -1
		var lastIndexInLVWidth int

		for _, tvc := range tv.columns.items {
			var offset int
			if !tvc.Frozen() {
				offset = frozenColCount
			}

			colWidth := tv.IntFrom96DPI(tvc.Width())
			width -= colWidth

			if index := int32(offset) + tvc.indexInListView(); int(index) > lastIndexInLV {
				lastIndexInLV = int(index)
				lastIndexInLVWidth = colWidth
			}
		}

		width += lastIndexInLVWidth

		if hasWindowLongBits(tv.hwndNormalLV, win.GWL_STYLE, win.WS_VSCROLL) {
			width -= int(win.GetSystemMetricsForDpi(win.SM_CXVSCROLL, uint32(tv.DPI())))
		}

		lp = uintptr(maxi(0, width))
	}

	if lp > 0 {
		if 0 == win.SendMessage(hwnd, win.LVM_SETCOLUMNWIDTH, uintptr(colCount-1), lp) {
			return newError("LVM_SETCOLUMNWIDTH failed")
		}

		if dpi := tv.DPI(); dpi != tv.dpiOfPrevStretchLastColumn {
			tv.dpiOfPrevStretchLastColumn = dpi

			tv.Invalidate()
		}
	}

	return nil
}

// Persistent returns if the *TableView should persist its UI state, like column
// widths. See *App.Settings for details.
func (tv *TableView) Persistent() bool {
	return tv.persistent
}

// SetPersistent sets if the *TableView should persist its UI state, like column
// widths. See *App.Settings for details.
func (tv *TableView) SetPersistent(value bool) {
	tv.persistent = value
}

// IgnoreNowhere returns if the *TableView should ignore left mouse clicks in the
// empty space. It forbids the user from unselecting the current index, or when
// multi selection is enabled, disables click drag selection.
func (tv *TableView) IgnoreNowhere() bool {
	return tv.ignoreNowhere
}

// IgnoreNowhere sets if the *TableView should ignore left mouse clicks in the
// empty space. It forbids the user from unselecting the current index, or when
// multi selection is enabled, disables click drag selection.
func (tv *TableView) SetIgnoreNowhere(value bool) {
	tv.ignoreNowhere = value
}

type tableViewState struct {
	SortColumnName     string
	SortOrder          SortOrder
	ColumnDisplayOrder []string
	Columns            []*tableViewColumnState
}

type tableViewColumnState struct {
	Name         string
	Title        string
	Width        int
	Visible      bool
	Frozen       bool
	LastSeenDate string
}

// SaveState writes the UI state of the *TableView to the settings.
func (tv *TableView) SaveState() error {
	if tv.columns.Len() == 0 {
		return nil
	}

	if tv.state == nil {
		tv.state = new(tableViewState)
	}

	tvs := tv.state

	tvs.SortColumnName = tv.columns.items[tv.sortedColumnIndex].name
	tvs.SortOrder = tv.sortOrder

	// tvs.Columns = make([]tableViewColumnState, tv.columns.Len())

	for _, tvc := range tv.columns.items {
		var tvcs *tableViewColumnState
		for _, cur := range tvs.Columns {
			if cur.Name == tvc.name {
				tvcs = cur
				break
			}
		}

		// tvcs := &tvs.Columns[i]

		if tvcs == nil {
			tvs.Columns = append(tvs.Columns, new(tableViewColumnState))
			tvcs = tvs.Columns[len(tvs.Columns)-1]
		}

		tvcs.Name = tvc.name
		tvcs.Title = tvc.titleOverride
		tvcs.Width = tvc.Width()
		tvcs.Visible = tvc.Visible()
		tvcs.Frozen = tvc.Frozen()
		tvcs.LastSeenDate = time.Now().Format("2006-01-02")
	}

	visibleCols := tv.visibleColumns()
	frozenCount := tv.visibleFrozenColumnCount()
	normalCount := len(visibleCols) - frozenCount
	indices := make([]int32, len(visibleCols))
	var lp uintptr
	if frozenCount > 0 {
		lp = uintptr(unsafe.Pointer(&indices[0]))

		if 0 == win.SendMessage(tv.hwndFrozenLV, win.LVM_GETCOLUMNORDERARRAY, uintptr(frozenCount), lp) {
			return newError("LVM_GETCOLUMNORDERARRAY")
		}
	}
	if normalCount > 0 {
		lp = uintptr(unsafe.Pointer(&indices[frozenCount]))

		if 0 == win.SendMessage(tv.hwndNormalLV, win.LVM_GETCOLUMNORDERARRAY, uintptr(normalCount), lp) {
			return newError("LVM_GETCOLUMNORDERARRAY")
		}
	}

	tvs.ColumnDisplayOrder = make([]string, len(visibleCols))
	for i, j := range indices {
		if i >= frozenCount {
			j += int32(frozenCount)
		}
		tvs.ColumnDisplayOrder[i] = visibleCols[j].name
	}

	state, err := json.Marshal(tvs)
	if err != nil {
		return err
	}

	return tv.WriteState(string(state))
}

// RestoreState restores the UI state of the *TableView from the settings.
func (tv *TableView) RestoreState() error {
	state, err := tv.ReadState()
	if err != nil {
		return err
	}
	if state == "" {
		return nil
	}

	tv.SetSuspended(true)
	defer tv.SetSuspended(false)

	if tv.state == nil {
		tv.state = new(tableViewState)
	}

	tvs := tv.state

	if err := json.Unmarshal(([]byte)(state), tvs); err != nil {
		return err
	}

	name2tvc := make(map[string]*TableViewColumn)

	for _, tvc := range tv.columns.items {
		name2tvc[tvc.name] = tvc
	}

	name2tvcs := make(map[string]*tableViewColumnState)

	tvcsRetained := make([]*tableViewColumnState, 0, len(tvs.Columns))
	for _, tvcs := range tvs.Columns {
		if tvcs.LastSeenDate != "" {
			if lastSeen, err := time.Parse("2006-02-01", tvcs.LastSeenDate); err != nil {
				tvcs.LastSeenDate = ""
			} else if name2tvc[tvcs.Name] == nil && lastSeen.Add(time.Hour*24*90).Before(time.Now()) {
				continue
			}
		}
		tvcsRetained = append(tvcsRetained, tvcs)

		name2tvcs[tvcs.Name] = tvcsRetained[len(tvcsRetained)-1]

		if tvc := name2tvc[tvcs.Name]; tvc != nil {
			if err := tvc.SetFrozen(tvcs.Frozen); err != nil {
				return err
			}
			var visible bool
			for _, name := range tvs.ColumnDisplayOrder {
				if name == tvc.name {
					visible = true
					break
				}
			}
			if err := tvc.SetVisible(tvc.visible && (visible || tvcs.Visible)); err != nil {
				return err
			}
			if err := tvc.SetTitleOverride(tvcs.Title); err != nil {
				return err
			}
			if err := tvc.SetWidth(tvcs.Width); err != nil {
				return err
			}
		}
	}
	tvs.Columns = tvcsRetained

	visibleCount := tv.visibleColumnCount()
	frozenCount := tv.visibleFrozenColumnCount()
	normalCount := visibleCount - frozenCount

	indices := make([]int32, visibleCount)

	knownNames := make(map[string]struct{})

	displayOrder := make([]string, 0, visibleCount)
	for _, name := range tvs.ColumnDisplayOrder {
		knownNames[name] = struct{}{}
		if tvc, ok := name2tvc[name]; ok && tvc.visible {
			displayOrder = append(displayOrder, name)
		}
	}
	for _, tvc := range tv.visibleColumns() {
		if _, ok := knownNames[tvc.name]; !ok {
			displayOrder = append(displayOrder, tvc.name)
		}
	}

	for i, tvc := range tv.visibleColumns() {
		for j, name := range displayOrder {
			if tvc.name == name && j < visibleCount {
				idx := i
				if j >= frozenCount {
					idx -= frozenCount
				}
				indices[j] = int32(idx)
				break
			}
		}
	}

	var lp uintptr
	if frozenCount > 0 {
		lp = uintptr(unsafe.Pointer(&indices[0]))

		if 0 == win.SendMessage(tv.hwndFrozenLV, win.LVM_SETCOLUMNORDERARRAY, uintptr(frozenCount), lp) {
			return newError("LVM_SETCOLUMNORDERARRAY")
		}
	}
	if normalCount > 0 {
		lp = uintptr(unsafe.Pointer(&indices[frozenCount]))

		if 0 == win.SendMessage(tv.hwndNormalLV, win.LVM_SETCOLUMNORDERARRAY, uintptr(normalCount), lp) {
			return newError("LVM_SETCOLUMNORDERARRAY")
		}
	}

	for i, c := range tvs.Columns {
		if c.Name == tvs.SortColumnName && i < visibleCount {
			tv.sortedColumnIndex = i
			tv.sortOrder = tvs.SortOrder
			break
		}
	}

	if sorter, ok := tv.model.(Sorter); ok {
		if !sorter.ColumnSortable(tv.sortedColumnIndex) {
			for i := range tvs.Columns {
				if sorter.ColumnSortable(i) {
					tv.sortedColumnIndex = i
					break
				}
			}
		}

		sorter.Sort(tv.sortedColumnIndex, tvs.SortOrder)
	}

	return nil
}

func (tv *TableView) toggleItemChecked(index int) error {
	checked := tv.itemChecker.Checked(index)

	if err := tv.itemChecker.SetChecked(index, !checked); err != nil {
		return wrapError(err)
	}

	if win.FALSE == win.SendMessage(tv.hwndFrozenLV, win.LVM_UPDATE, uintptr(index), 0) {
		return newError("SendMessage(LVM_UPDATE)")
	}
	if win.FALSE == win.SendMessage(tv.hwndNormalLV, win.LVM_UPDATE, uintptr(index), 0) {
		return newError("SendMessage(LVM_UPDATE)")
	}

	return nil
}

func (tv *TableView) applyImageListForImage(image interface{}) {
	tv.hIml, tv.usingSysIml, _ = imageListForImage(image, tv.DPI())

	tv.applyImageList()

	tv.imageUintptr2Index = make(map[uintptr]int32)
	tv.filePath2IconIndex = make(map[string]int32)
}

func (tv *TableView) applyImageList() {
	win.SendMessage(tv.hwndFrozenLV, win.LVM_SETIMAGELIST, win.LVSIL_SMALL, uintptr(tv.hIml))
	win.SendMessage(tv.hwndNormalLV, win.LVM_SETIMAGELIST, win.LVSIL_SMALL, uintptr(tv.hIml))
}

func (tv *TableView) disposeImageListAndCaches() {
	if tv.hIml != 0 && !tv.usingSysIml {
		win.SendMessage(tv.hwndFrozenLV, win.LVM_SETIMAGELIST, win.LVSIL_SMALL, 0)
		win.SendMessage(tv.hwndNormalLV, win.LVM_SETIMAGELIST, win.LVSIL_SMALL, 0)

		win.ImageList_Destroy(tv.hIml)
	}
	tv.hIml = 0

	tv.imageUintptr2Index = nil
	tv.filePath2IconIndex = nil
}

func (tv *TableView) Focused() bool {
	focused := win.GetFocus()

	return focused == tv.hwndFrozenLV || focused == tv.hwndNormalLV
}

func (tv *TableView) maybePublishFocusChanged(hwnd win.HWND, msg uint32, wp uintptr) {
	focused := msg == win.WM_SETFOCUS

	if focused != tv.focused && wp != uintptr(tv.hwndFrozenLV) && wp != uintptr(tv.hwndNormalLV) {
		tv.focused = focused
		tv.focusedChangedPublisher.Publish()
	}
}

func tableViewFrozenLVWndProc(hwnd win.HWND, msg uint32, wp, lp uintptr) uintptr {
	tv := (*TableView)(unsafe.Pointer(windowFromHandle(win.GetParent(hwnd)).AsWindowBase()))

	switch msg {
	case win.WM_NCCALCSIZE:
		ensureWindowLongBits(hwnd, win.GWL_STYLE, win.WS_HSCROLL|win.WS_VSCROLL, false)

	case win.WM_SETFOCUS:
		win.SetFocus(tv.hwndNormalLV)
		tv.maybePublishFocusChanged(hwnd, msg, wp)

	case win.WM_KILLFOCUS:
		tv.maybePublishFocusChanged(hwnd, msg, wp)

	case win.WM_MOUSEWHEEL:
		tableViewNormalLVWndProc(tv.hwndNormalLV, msg, wp, lp)
	}

	return tv.lvWndProc(tv.frozenLVOrigWndProcPtr, hwnd, msg, wp, lp)
}

func tableViewNormalLVWndProc(hwnd win.HWND, msg uint32, wp, lp uintptr) uintptr {
	tv := (*TableView)(unsafe.Pointer(windowFromHandle(win.GetParent(hwnd)).AsWindowBase()))

	switch msg {
	case win.WM_LBUTTONDOWN, win.WM_RBUTTONDOWN:
		win.SetFocus(tv.hwndFrozenLV)

	case win.WM_SETFOCUS:
		tv.invalidateBorderInParent()
		tv.maybePublishFocusChanged(hwnd, msg, wp)

	case win.WM_KILLFOCUS:
		win.SendMessage(tv.hwndFrozenLV, msg, wp, lp)
		tv.WndProc(tv.hWnd, msg, wp, lp)
		tv.maybePublishFocusChanged(hwnd, msg, wp)
	}

	result := tv.lvWndProc(tv.normalLVOrigWndProcPtr, hwnd, msg, wp, lp)

	var off uint32 = win.WS_HSCROLL | win.WS_VSCROLL
	if tv.scrollbarOrientation&Horizontal != 0 {
		off &^= win.WS_HSCROLL
	}
	if tv.scrollbarOrientation&Vertical != 0 {
		off &^= win.WS_VSCROLL
	}
	if off != 0 {
		ensureWindowLongBits(hwnd, win.GWL_STYLE, off, false)
	}

	return result
}

func (tv *TableView) lvWndProc(origWndProcPtr uintptr, hwnd win.HWND, msg uint32, wp, lp uintptr) uintptr {
	var hwndOther win.HWND
	if hwnd == tv.hwndFrozenLV {
		hwndOther = tv.hwndNormalLV
	} else {
		hwndOther = tv.hwndFrozenLV
	}

	var maybeStretchLastColumn bool

	switch msg {
	case win.WM_ERASEBKGND:
		maybeStretchLastColumn = true

	case win.WM_WINDOWPOSCHANGED:
		wp := (*win.WINDOWPOS)(unsafe.Pointer(lp))

		if wp.Flags&win.SWP_NOSIZE != 0 {
			break
		}

		maybeStretchLastColumn = int(wp.Cx) < tv.WidthPixels()

	case win.WM_GETDLGCODE:
		if wp == win.VK_RETURN {
			return win.DLGC_WANTALLKEYS
		}

	case win.WM_LBUTTONDOWN, win.WM_RBUTTONDOWN, win.WM_LBUTTONDBLCLK, win.WM_RBUTTONDBLCLK:
		var hti win.LVHITTESTINFO
		hti.Pt = win.POINT{win.GET_X_LPARAM(lp), win.GET_Y_LPARAM(lp)}
		win.SendMessage(hwnd, win.LVM_HITTEST, 0, uintptr(unsafe.Pointer(&hti)))

		tv.itemIndexOfLastMouseButtonDown = int(hti.IItem)

		if hti.Flags == win.LVHT_NOWHERE {
			if tv.MultiSelection() {
				tv.publishNextSelClear = true
			} else {
				if tv.CheckBoxes() {
					if tv.currentIndex > -1 {
						tv.SetCurrentIndex(-1)
					}
				} else {
					// We keep the current item, if in single item selection mode without check boxes.
					win.SetFocus(tv.hwndFrozenLV)
					return 0
				}
			}

			if tv.IgnoreNowhere() {
				return 0
			}
		}

		switch msg {
		case win.WM_LBUTTONDOWN, win.WM_RBUTTONDOWN:
			if hti.Flags == win.LVHT_ONITEMSTATEICON &&
				tv.itemChecker != nil &&
				tv.CheckBoxes() {

				tv.toggleItemChecked(int(hti.IItem))
			}

		case win.WM_LBUTTONDBLCLK, win.WM_RBUTTONDBLCLK:
			if tv.currentIndex != tv.prevIndex && tv.itemStateChangedEventDelay > 0 {
				tv.prevIndex = tv.currentIndex
				tv.currentIndexChangedPublisher.Publish()
				tv.currentItemChangedPublisher.Publish()
			}
		}

	case win.WM_LBUTTONUP, win.WM_RBUTTONUP:
		tv.itemIndexOfLastMouseButtonDown = -1

	case win.WM_MOUSEMOVE, win.WM_MOUSELEAVE:
		if tv.inMouseEvent {
			break
		}
		tv.inMouseEvent = true
		defer func() {
			tv.inMouseEvent = false
		}()

		if msg == win.WM_MOUSEMOVE {
			y := int(win.GET_Y_LPARAM(lp))
			lp = uintptr(win.MAKELONG(0, uint16(y)))
		}

		win.SendMessage(hwndOther, msg, wp, lp)

	case win.WM_KEYDOWN:
		if wp == win.VK_SPACE &&
			tv.currentIndex > -1 &&
			tv.itemChecker != nil &&
			tv.CheckBoxes() {

			tv.toggleItemChecked(tv.currentIndex)
		}

		tv.handleKeyDown(wp, lp)

	case win.WM_KEYUP:
		tv.handleKeyUp(wp, lp)

	case win.WM_NOTIFY:
		nmh := ((*win.NMHDR)(unsafe.Pointer(lp)))
		switch nmh.HwndFrom {
		case tv.hwndFrozenHdr, tv.hwndNormalHdr:
			if nmh.Code == win.NM_CUSTOMDRAW {
				return tableViewHdrWndProc(nmh.HwndFrom, msg, wp, lp)
			}
		}

		switch nmh.Code {
		case win.LVN_GETDISPINFO:
			di := (*win.NMLVDISPINFO)(unsafe.Pointer(lp))

			row := int(di.Item.IItem)
			col := tv.fromLVColIdx(hwnd == tv.hwndFrozenLV, di.Item.ISubItem)
			if col == -1 {
				break
			}

			if di.Item.Mask&win.LVIF_TEXT > 0 {
				value := tv.model.Value(row, col)
				var text string
				if format := tv.columns.items[col].formatFunc; format != nil {
					text = format(value)
				} else {
					switch val := value.(type) {
					case string:
						text = val

					case float32:
						prec := tv.columns.items[col].precision
						if prec == 0 {
							prec = 2
						}
						text = FormatFloatGrouped(float64(val), prec)

					case float64:
						prec := tv.columns.items[col].precision
						if prec == 0 {
							prec = 2
						}
						text = FormatFloatGrouped(val, prec)

					case time.Time:
						if val.Year() > 1601 {
							text = val.Format(tv.columns.items[col].format)
						}

					case bool:
						if val {
							text = checkmark
						}

					default:
						text = fmt.Sprintf(tv.columns.items[col].format, val)
					}
				}

				utf16 := syscall.StringToUTF16(text)
				buf := (*[264]uint16)(unsafe.Pointer(di.Item.PszText))
				max := mini(len(utf16), int(di.Item.CchTextMax))
				copy((*buf)[:], utf16[:max])
				(*buf)[max-1] = 0
			}

			if (tv.imageProvider != nil || tv.styler != nil) && di.Item.Mask&win.LVIF_IMAGE > 0 {
				var image interface{}
				if di.Item.ISubItem == 0 {
					if ip := tv.imageProvider; ip != nil && image == nil {
						image = ip.Image(row)
					}
				}
				if styler := tv.styler; styler != nil && image == nil {
					tv.style.row = row
					tv.style.col = col
					tv.style.bounds = Rectangle{}
					tv.style.dpi = tv.DPI()
					tv.style.Image = nil

					styler.StyleCell(&tv.style)

					image = tv.style.Image
				}

				if image != nil {
					if tv.hIml == 0 {
						tv.applyImageListForImage(image)
					}

					di.Item.IImage = imageIndexMaybeAdd(
						image,
						tv.hIml,
						tv.usingSysIml,
						tv.imageUintptr2Index,
						tv.filePath2IconIndex,
						tv.DPI())
				}
			}

			if di.Item.ISubItem == 0 && di.Item.StateMask&win.LVIS_STATEIMAGEMASK > 0 &&
				tv.itemChecker != nil {
				checked := tv.itemChecker.Checked(row)

				if checked {
					di.Item.State = 0x2000
				} else {
					di.Item.State = 0x1000
				}
			}

		case win.NM_CUSTOMDRAW:
			nmlvcd := (*win.NMLVCUSTOMDRAW)(unsafe.Pointer(lp))

			if nmlvcd.IIconPhase == 0 {
				row := int(nmlvcd.Nmcd.DwItemSpec)
				col := tv.fromLVColIdx(hwnd == tv.hwndFrozenLV, nmlvcd.ISubItem)
				if col == -1 {
					break
				}

				applyCellStyle := func() int {
					if tv.styler != nil {
						dpi := tv.DPI()

						tv.style.row = row
						tv.style.col = col
						tv.style.bounds = rectangleFromRECT(nmlvcd.Nmcd.Rc)
						tv.style.dpi = dpi
						tv.style.hdc = nmlvcd.Nmcd.Hdc
						tv.style.BackgroundColor = tv.itemBGColor
						tv.style.TextColor = tv.itemTextColor
						tv.style.Font = nil
						tv.style.Image = nil

						tv.styler.StyleCell(&tv.style)

						defer func() {
							tv.style.bounds = Rectangle{}
							if tv.style.canvas != nil {
								tv.style.canvas.Dispose()
								tv.style.canvas = nil
							}
							tv.style.hdc = 0
						}()

						if tv.style.canvas != nil {
							return win.CDRF_SKIPDEFAULT
						}

						nmlvcd.ClrTextBk = win.COLORREF(tv.style.BackgroundColor)
						nmlvcd.ClrText = win.COLORREF(tv.style.TextColor)

						font := tv.style.Font
						if font == nil {
							font = tv.Font()
						}
						win.SelectObject(nmlvcd.Nmcd.Hdc, win.HGDIOBJ(font.handleForDPI(dpi)))
					}

					return 0
				}

				switch nmlvcd.Nmcd.DwDrawStage {
				case win.CDDS_PREPAINT:
					return win.CDRF_NOTIFYITEMDRAW

				case win.CDDS_ITEMPREPAINT:
					var selected bool
					if itemState := win.SendMessage(hwnd, win.LVM_GETITEMSTATE, nmlvcd.Nmcd.DwItemSpec, win.LVIS_SELECTED); itemState&win.LVIS_SELECTED != 0 {
						selected = true

						tv.itemBGColor = tv.themeSelectedBGColor
						tv.itemTextColor = tv.themeSelectedTextColor
					} else {
						tv.itemBGColor = tv.themeNormalBGColor
						tv.itemTextColor = tv.themeNormalTextColor
					}

					if !selected && tv.alternatingRowBG && row%2 == 1 {
						tv.itemBGColor = tv.alternatingRowBGColor
						tv.itemTextColor = tv.alternatingRowTextColor
					}

					tv.style.BackgroundColor = tv.itemBGColor
					tv.style.TextColor = tv.itemTextColor

					if tv.styler != nil {
						tv.style.row = row
						tv.style.col = -1
						tv.style.bounds = rectangleFromRECT(nmlvcd.Nmcd.Rc)
						tv.style.dpi = tv.DPI()
						tv.style.hdc = 0
						tv.style.Font = nil
						tv.style.Image = nil

						tv.styler.StyleCell(&tv.style)

						tv.itemFont = tv.style.Font
					}

					if selected {
						tv.style.BackgroundColor = tv.itemBGColor
						tv.style.TextColor = tv.itemTextColor
					} else {
						tv.itemBGColor = tv.style.BackgroundColor
						tv.itemTextColor = tv.style.TextColor
					}

					if tv.style.BackgroundColor != tv.themeNormalBGColor {
						var color Color
						if selected && !tv.Focused() {
							color = tv.themeSelectedNotFocusedBGColor
						} else {
							color = tv.style.BackgroundColor
						}

						if brush, _ := NewSolidColorBrush(color); brush != nil {
							defer brush.Dispose()

							canvas, _ := newCanvasFromHDC(nmlvcd.Nmcd.Hdc)
							canvas.FillRectanglePixels(brush, rectangleFromRECT(nmlvcd.Nmcd.Rc))
						}
					}

					nmlvcd.ClrText = win.COLORREF(tv.style.TextColor)
					nmlvcd.ClrTextBk = win.COLORREF(tv.style.BackgroundColor)

					return win.CDRF_NOTIFYSUBITEMDRAW

				case win.CDDS_ITEMPREPAINT | win.CDDS_SUBITEM:
					if tv.itemFont != nil {
						win.SelectObject(nmlvcd.Nmcd.Hdc, win.HGDIOBJ(tv.itemFont.handleForDPI(tv.DPI())))
					}

					if applyCellStyle() == win.CDRF_SKIPDEFAULT && win.IsAppThemed() {
						return win.CDRF_SKIPDEFAULT
					}

					return win.CDRF_NEWFONT | win.CDRF_SKIPPOSTPAINT | win.CDRF_NOTIFYPOSTPAINT

				case win.CDDS_ITEMPOSTPAINT | win.CDDS_SUBITEM:
					if applyCellStyle() == win.CDRF_SKIPDEFAULT {
						return win.CDRF_SKIPDEFAULT
					}

					return win.CDRF_NEWFONT | win.CDRF_SKIPPOSTPAINT
				}

				return win.CDRF_SKIPPOSTPAINT
			}

			return win.CDRF_SKIPPOSTPAINT

		case win.LVN_BEGINSCROLL:
			if tv.scrolling {
				break
			}
			tv.scrolling = true
			defer func() {
				tv.scrolling = false
			}()

			var rc win.RECT
			win.SendMessage(hwnd, win.LVM_GETITEMRECT, 0, uintptr(unsafe.Pointer(&rc)))

			nmlvs := (*win.NMLVSCROLL)(unsafe.Pointer(lp))
			win.SendMessage(hwndOther, win.LVM_SCROLL, 0, uintptr(nmlvs.Dy*(rc.Bottom-rc.Top)))

		case win.LVN_COLUMNCLICK:
			nmlv := (*win.NMLISTVIEW)(unsafe.Pointer(lp))

			col := tv.fromLVColIdx(hwnd == tv.hwndFrozenLV, nmlv.ISubItem)

			if sorter, ok := tv.model.(Sorter); ok && sorter.ColumnSortable(col) {
				prevCol := sorter.SortedColumn()
				var order SortOrder
				if col != prevCol || sorter.SortOrder() == SortDescending {
					order = SortAscending
				} else {
					order = SortDescending
				}
				tv.sortedColumnIndex = col
				tv.sortOrder = order
				sorter.Sort(col, order)
			}

			tv.columnClickedPublisher.Publish(col)

		case win.LVN_ITEMCHANGED:
			nmlv := (*win.NMLISTVIEW)(unsafe.Pointer(lp))

			if tv.hwndItemChanged != 0 && tv.hwndItemChanged != hwnd {
				break
			}
			tv.hwndItemChanged = hwnd
			defer func() {
				tv.hwndItemChanged = 0
			}()

			tv.copySelectedIndexes(hwndOther, hwnd)

			if nmlv.IItem == -1 && !tv.publishNextSelClear {
				break
			}
			tv.publishNextSelClear = false

			selectedNow := nmlv.UNewState&win.LVIS_SELECTED > 0
			selectedBefore := nmlv.UOldState&win.LVIS_SELECTED > 0
			if tv.itemIndexOfLastMouseButtonDown != -1 && selectedNow && !selectedBefore && ModifiersDown()&(ModControl|ModShift) == 0 {
				tv.prevIndex = tv.currentIndex
				tv.currentIndex = int(nmlv.IItem)
				if tv.itemStateChangedEventDelay > 0 {
					tv.delayedCurrentIndexChangedCanceled = false
					if 0 == win.SetTimer(
						tv.hWnd,
						tableViewCurrentIndexChangedTimerId,
						uint32(tv.itemStateChangedEventDelay),
						0) {

						lastError("SetTimer")
					}

					tv.SetCurrentIndex(int(nmlv.IItem))
				} else {
					tv.SetCurrentIndex(int(nmlv.IItem))
				}
			}

			if selectedNow != selectedBefore {
				if !tv.inSetSelectedIndexes && tv.MultiSelection() {
					tv.updateSelectedIndexes()
				}
			}

		case win.LVN_ODSTATECHANGED:
			if tv.hwndItemChanged != 0 && tv.hwndItemChanged != hwnd {
				break
			}
			tv.hwndItemChanged = hwnd
			defer func() {
				tv.hwndItemChanged = 0
			}()

			tv.copySelectedIndexes(hwndOther, hwnd)

			tv.updateSelectedIndexes()

		case win.LVN_ITEMACTIVATE:
			nmia := (*win.NMITEMACTIVATE)(unsafe.Pointer(lp))

			if tv.itemStateChangedEventDelay > 0 {
				tv.delayedCurrentIndexChangedCanceled = true
			}

			if int(nmia.IItem) != tv.currentIndex {
				tv.SetCurrentIndex(int(nmia.IItem))
				tv.currentIndexChangedPublisher.Publish()
				tv.currentItemChangedPublisher.Publish()
			}

			tv.itemActivatedPublisher.Publish()

		case win.HDN_ITEMCHANGING:
			tv.updateLVSizes()
		}

	case win.WM_UPDATEUISTATE:
		switch win.LOWORD(uint32(wp)) {
		case win.UIS_SET:
			wp |= win.UISF_HIDEFOCUS << 16

		case win.UIS_CLEAR, win.UIS_INITIALIZE:
			wp &^= ^uintptr(win.UISF_HIDEFOCUS << 16)
		}
	}

	lpFixed := lp
	fixXInLP := func() {
		// fmt.Printf("hwnd == tv.hwndNormalLV: %t, tv.hasFrozenColumn: %t\n", hwnd == tv.hwndNormalLV, tv.hasFrozenColumn)
		if hwnd == tv.hwndNormalLV && tv.hasFrozenColumn {
			var rc win.RECT
			if win.GetWindowRect(tv.hwndFrozenLV, &rc) {
				x := int(win.GET_X_LPARAM(lp)) + int(rc.Right-rc.Left)
				y := int(win.GET_Y_LPARAM(lp))

				lpFixed = uintptr(win.MAKELONG(uint16(x), uint16(y)))
			}
		}
	}

	switch msg {
	case win.WM_LBUTTONDOWN, win.WM_MBUTTONDOWN, win.WM_RBUTTONDOWN:
		fixXInLP()
		tv.publishMouseEvent(&tv.mouseDownPublisher, msg, wp, lpFixed)

	case win.WM_LBUTTONUP, win.WM_MBUTTONUP, win.WM_RBUTTONUP:
		fixXInLP()
		tv.publishMouseEvent(&tv.mouseUpPublisher, msg, wp, lpFixed)

	case win.WM_MOUSEMOVE:
		fixXInLP()
		tv.publishMouseEvent(&tv.mouseMovePublisher, msg, wp, lpFixed)

	case win.WM_MOUSEWHEEL:
		fixXInLP()
		tv.publishMouseWheelEvent(&tv.mouseWheelPublisher, wp, lpFixed)
	}

	if maybeStretchLastColumn {
		if tv.lastColumnStretched && !tv.busyStretchingLastColumn {
			if normalVisColCount := tv.visibleColumnCount() - tv.visibleFrozenColumnCount(); normalVisColCount == 0 || normalVisColCount > 0 == (hwnd == tv.hwndNormalLV) {
				tv.busyStretchingLastColumn = true
				defer func() {
					tv.busyStretchingLastColumn = false
				}()
				tv.StretchLastColumn()
			}
		}

		if msg == win.WM_ERASEBKGND {
			return 1
		}
	}

	return win.CallWindowProc(origWndProcPtr, hwnd, msg, wp, lp)
}

func tableViewHdrWndProc(hwnd win.HWND, msg uint32, wp, lp uintptr) uintptr {
	tv := (*TableView)(unsafe.Pointer(windowFromHandle(win.GetParent(win.GetParent(hwnd))).AsWindowBase()))

	var origWndProcPtr uintptr
	if hwnd == tv.hwndFrozenHdr {
		origWndProcPtr = tv.frozenHdrOrigWndProcPtr
	} else {
		origWndProcPtr = tv.normalHdrOrigWndProcPtr
	}

	switch msg {
	case win.WM_NOTIFY:
		switch ((*win.NMHDR)(unsafe.Pointer(lp))).Code {
		case win.NM_CUSTOMDRAW:
			if tv.customHeaderHeight == 0 {
				break
			}

			nmcd := (*win.NMCUSTOMDRAW)(unsafe.Pointer(lp))

			switch nmcd.DwDrawStage {
			case win.CDDS_PREPAINT:
				return win.CDRF_NOTIFYITEMDRAW

			case win.CDDS_ITEMPREPAINT:
				return win.CDRF_NOTIFYPOSTPAINT

			case win.CDDS_ITEMPOSTPAINT:
				col := tv.fromLVColIdx(hwnd == tv.hwndFrozenHdr, int32(nmcd.DwItemSpec))
				if tv.styler != nil && col > -1 {
					tv.style.row = -1
					tv.style.col = col
					tv.style.bounds = rectangleFromRECT(nmcd.Rc)
					tv.style.dpi = tv.DPI()
					tv.style.hdc = nmcd.Hdc
					tv.style.TextColor = tv.themeNormalTextColor
					tv.style.Font = nil

					tv.styler.StyleCell(&tv.style)

					defer func() {
						tv.style.bounds = Rectangle{}
						if tv.style.canvas != nil {
							tv.style.canvas.Dispose()
							tv.style.canvas = nil
						}
						tv.style.hdc = 0
					}()
				}

				return win.CDRF_DODEFAULT
			}

			return win.CDRF_DODEFAULT
		}

	case win.HDM_LAYOUT:
		if tv.customHeaderHeight == 0 {
			break
		}

		result := win.CallWindowProc(origWndProcPtr, hwnd, msg, wp, lp)

		hdl := (*win.HDLAYOUT)(unsafe.Pointer(lp))
		hdl.Prc.Top = int32(tv.customHeaderHeight)
		hdl.Pwpos.Cy = int32(tv.customHeaderHeight)

		return result

	case win.WM_MOUSEMOVE, win.WM_LBUTTONDOWN, win.WM_LBUTTONUP, win.WM_MBUTTONDOWN, win.WM_MBUTTONUP, win.WM_RBUTTONDOWN, win.WM_RBUTTONUP:
		hti := win.HDHITTESTINFO{Pt: win.POINT{int32(win.GET_X_LPARAM(lp)), int32(win.GET_Y_LPARAM(lp))}}
		win.SendMessage(hwnd, win.HDM_HITTEST, 0, uintptr(unsafe.Pointer(&hti)))
		if hti.IItem == -1 {
			tv.group.toolTip.setText(hwnd, "")
			break
		}

		col := tv.fromLVColIdx(hwnd == tv.hwndFrozenHdr, hti.IItem)
		text := tv.columns.At(col).TitleEffective()

		var rc win.RECT
		if 0 == win.SendMessage(hwnd, win.HDM_GETITEMRECT, uintptr(hti.IItem), uintptr(unsafe.Pointer(&rc))) {
			tv.group.toolTip.setText(hwnd, "")
			break
		}

		size := calculateTextSize(text, tv.Font(), tv.DPI(), 0, hwnd)
		if size.Width <= rectangleFromRECT(rc).Width-int(win.SendMessage(hwnd, win.HDM_GETBITMAPMARGIN, 0, 0)) {
			tv.group.toolTip.setText(hwnd, "")
			break
		}

		if tv.group.toolTip.text(hwnd) == text {
			break
		}

		tv.group.toolTip.setText(hwnd, text)

		m := win.MSG{
			HWnd:    hwnd,
			Message: msg,
			WParam:  wp,
			LParam:  lp,
			Pt:      hti.Pt,
		}

		tv.group.toolTip.SendMessage(win.TTM_RELAYEVENT, 0, uintptr(unsafe.Pointer(&m)))
	}

	return win.CallWindowProc(origWndProcPtr, hwnd, msg, wp, lp)
}

func (tv *TableView) WndProc(hwnd win.HWND, msg uint32, wp, lp uintptr) uintptr {
	switch msg {
	case win.WM_NOTIFY:
		nmh := (*win.NMHDR)(unsafe.Pointer(lp))
		switch nmh.HwndFrom {
		case tv.hwndFrozenLV:
			return tableViewFrozenLVWndProc(nmh.HwndFrom, msg, wp, lp)

		case tv.hwndNormalLV:
			return tableViewNormalLVWndProc(nmh.HwndFrom, msg, wp, lp)
		}

	case win.WM_WINDOWPOSCHANGED:
		wp := (*win.WINDOWPOS)(unsafe.Pointer(lp))

		if wp.Flags&win.SWP_NOSIZE != 0 {
			break
		}

		if tv.formActivatingHandle == -1 {
			if form := tv.Form(); form != nil {
				tv.formActivatingHandle = form.Activating().Attach(func() {
					if tv.hwndNormalLV == win.GetFocus() {
						win.SetFocus(tv.hwndFrozenLV)
					}
				})
			}
		}

		tv.updateLVSizes()

		// FIXME: The InvalidateRect and redrawItems calls below prevent
		// painting glitches on resize. Though this seems to work reasonably
		// well, in the long run we would like to find the root cause of this
		// issue and come up with a better fix.
		dpi := uint32(tv.DPI())
		var rc win.RECT

		vsbWidth := win.GetSystemMetricsForDpi(win.SM_CXVSCROLL, dpi)
		rc = win.RECT{wp.Cx - vsbWidth - 1, 0, wp.Cx, wp.Cy}
		win.InvalidateRect(tv.hWnd, &rc, true)

		hsbHeight := win.GetSystemMetricsForDpi(win.SM_CYHSCROLL, dpi)
		rc = win.RECT{0, wp.Cy - hsbHeight - 1, wp.Cx, wp.Cy}
		win.InvalidateRect(tv.hWnd, &rc, true)

		tv.redrawItems()

	case win.WM_TIMER:
		if !win.KillTimer(tv.hWnd, wp) {
			lastError("KillTimer")
		}

		switch wp {
		case tableViewCurrentIndexChangedTimerId:
			if !tv.delayedCurrentIndexChangedCanceled {
				tv.currentIndexChangedPublisher.Publish()
				tv.currentItemChangedPublisher.Publish()
			}

		case tableViewSelectedIndexesChangedTimerId:
			tv.selectedIndexesChangedPublisher.Publish()
		}

	case win.WM_MEASUREITEM:
		mis := (*win.MEASUREITEMSTRUCT)(unsafe.Pointer(lp))
		mis.ItemHeight = uint32(tv.customRowHeight)

		ensureWindowLongBits(tv.hwndFrozenLV, win.GWL_STYLE, win.LVS_OWNERDRAWFIXED, false)
		ensureWindowLongBits(tv.hwndNormalLV, win.GWL_STYLE, win.LVS_OWNERDRAWFIXED, false)

	case win.WM_SETFOCUS:
		win.SetFocus(tv.hwndFrozenLV)

	case win.WM_DESTROY:
		// As we subclass all windows of system classes, we prevented the
		// clean-up code in the WM_NCDESTROY handlers of some windows from
		// being called. To fix this, we restore the original window
		// procedures here.
		if tv.frozenHdrOrigWndProcPtr != 0 {
			win.SetWindowLongPtr(tv.hwndFrozenHdr, win.GWLP_WNDPROC, tv.frozenHdrOrigWndProcPtr)
		}
		if tv.frozenLVOrigWndProcPtr != 0 {
			win.SetWindowLongPtr(tv.hwndFrozenLV, win.GWLP_WNDPROC, tv.frozenLVOrigWndProcPtr)
		}
		if tv.normalHdrOrigWndProcPtr != 0 {
			win.SetWindowLongPtr(tv.hwndNormalHdr, win.GWLP_WNDPROC, tv.normalHdrOrigWndProcPtr)
		}
		if tv.normalLVOrigWndProcPtr != 0 {
			win.SetWindowLongPtr(tv.hwndNormalLV, win.GWLP_WNDPROC, tv.normalLVOrigWndProcPtr)
		}
	}

	return tv.WidgetBase.WndProc(hwnd, msg, wp, lp)
}

func (tv *TableView) updateLVSizes() {
	tv.updateLVSizesWithSpecialCare(false)
}

func (tv *TableView) updateLVSizesWithSpecialCare(needSpecialCare bool) {
	var width int
	for i := tv.columns.Len() - 1; i >= 0; i-- {
		if col := tv.columns.At(i); col.frozen && col.visible {
			width += col.Width()
		}
	}

	dpi := tv.DPI()
	widthPixels := IntFrom96DPI(width, dpi)

	cb := tv.ClientBoundsPixels()

	win.MoveWindow(tv.hwndNormalLV, int32(widthPixels), 0, int32(cb.Width-widthPixels), int32(cb.Height), true)

	var sbh int
	if hasWindowLongBits(tv.hwndNormalLV, win.GWL_STYLE, win.WS_HSCROLL) {
		sbh = int(win.GetSystemMetricsForDpi(win.SM_CYHSCROLL, uint32(dpi)))
	}

	win.MoveWindow(tv.hwndFrozenLV, 0, 0, int32(widthPixels), int32(cb.Height-sbh), true)

	if needSpecialCare {
		tv.updateLVSizesNeedsSpecialCare = true
	}

	if tv.updateLVSizesNeedsSpecialCare {
		win.ShowWindow(tv.hwndNormalLV, win.SW_HIDE)
		win.ShowWindow(tv.hwndNormalLV, win.SW_SHOW)
	}

	if !needSpecialCare {
		tv.updateLVSizesNeedsSpecialCare = false
	}
}

func (*TableView) CreateLayoutItem(ctx *LayoutContext) LayoutItem {
	return NewGreedyLayoutItem()
}

func (tv *TableView) SetScrollbarOrientation(orientation Orientation) {
	tv.scrollbarOrientation = orientation
}

func (tv *TableView) ScrollbarOrientation() Orientation {
	return tv.scrollbarOrientation
}