File: customlistview.inc

package info (click to toggle)
lazarus 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 275,760 kB
  • sloc: pascal: 2,341,904; xml: 509,420; makefile: 348,726; cpp: 93,608; sh: 3,387; java: 609; perl: 297; sql: 222; ansic: 137
file content (1901 lines) | stat: -rw-r--r-- 57,883 bytes parent folder | download
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
{%MainUnit ../comctrls.pp}
{
 *****************************************************************************
  This file is part of the Lazarus Component Library (LCL)

  See the file COPYING.modifiedLGPL.txt, included in this distribution,
  for details about the license.
 *****************************************************************************
}

{ TIconOptions }

procedure TIconOptions.SetArrangement(Value: TIconArrangement);
begin
  if FArrangement <> Value then
  begin
    FArrangement := Value;
    if FListView.HandleAllocated then
      TWSCustomListViewClass(FListView.WidgetSetClass).SetIconArrangement(FListView, Arrangement);
  end;
end;

function TIconOptions.GetAutoArrange: Boolean;
begin
  Result := FListView.GetProperty(Ord(lvpAutoArrange));
end;

function TIconOptions.GetWrapText: Boolean;
begin
  Result := FListView.GetProperty(Ord(lvpWrapText));
end;

procedure TIconOptions.SetAutoArrange(Value: Boolean);
begin
  FListView.SetProperty(Ord(lvpAutoArrange), Value);
end;

procedure TIconOptions.SetWrapText(Value: Boolean);
begin
  FListView.SetProperty(Ord(lvpWrapText), Value);
end;

procedure TIconOptions.AssignTo(Dest: TPersistent);
var
  DestOptions: TIconOptions absolute Dest;
begin
  if Dest is TIconOptions then
  begin
    DestOptions.Arrangement := Arrangement;
    DestOptions.AutoArrange := AutoArrange;
    DestOptions.WrapText := WrapText;
  end
  else
    inherited AssignTo(Dest);
end;

function TIconOptions.GetOwner: TPersistent;
begin
  Result := FListView;
end;

constructor TIconOptions.Create(AOwner: TCustomListView);
begin
  inherited Create;
  FListView := AOwner;
  FArrangement := iaTop;
end;

{ TCustomListViewEditor }

procedure TCustomListViewEditor.ListViewEditorKeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
  if (Shift = []) and Visible then
  begin
    if Key = VK_ESCAPE then
    begin
      Key := 0;
      FItem := nil;
      Visible := False;
      Parent.SetFocus;
    end else
    if Key = VK_RETURN then
    begin
      Key := 0;
      Parent.SetFocus;
    end;
  end;
end;

procedure TCustomListViewEditor.DoExit;
begin
  TCustomListView(Parent).HideEditor;
  inherited DoExit;
end;

constructor TCustomListViewEditor.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FItem := nil;
  OnKeyDown := @ListViewEditorKeyDown;
end;

{------------------------------------------------------------------------------
   TCustomListView Constructor
------------------------------------------------------------------------------}
constructor TCustomListView.Create(AOwner: TComponent);
var
  lvil: TListViewImageList;
begin
  inherited Create(AOwner);
  ControlStyle := ControlStyle - [csCaptureMouse];
  FAutoSort := True;
  FAutoWidthLastColumn := False;
  FSortDirection := sdAscending;
  FIconOptions := TIconOptions.Create(Self);
  FColumns := TListColumns.Create(Self);
  FListItems := CreateListItems;
  BorderStyle := bsSingle;
  FScrollBars := ssBoth;
  FCompStyle := csListView;
  FViewStyle := vsList;
  FSortType := stNone;
  FSortColumn := -1;

  for lvil := Low(TListViewImageList) to High(TListViewImageList) do
  begin
    FImageChangeLinks[lvil] := TChangeLink.Create;
    FImageChangeLinks[lvil].OnChange := @ImageChanged;
    FImageChangeLinks[lvil].OnDestroyResolutionHandle := @ImageResolutionHandleDestroyed;
  end;
  FHoverTime := -1;
  TabStop := true;
  with GetControlClassDefaultSize do
    SetInitialBounds(0, 0, CX, CY);
  ParentColor := False;
  Color := {$ifdef UseCLDefault}clDefault{$else}clWindow{$endif};
  FCanvas := TControlCanvas.Create;
  TControlCanvas(FCanvas).Control := Self;
  FProperties := [lvpColumnClick, lvpHideSelection, lvpShowColumnHeaders, lvpToolTips, lvpWrapText];
  
  FOwnerDataItem := TOwnerDataListItem.Create(FListItems);
  FEditor := TCustomListViewEditor.Create(Self);
  FEditor.ControlStyle := FEditor.ControlStyle + [csNoDesignVisible, csNoDesignSelectable];
  FEditor.AutoSize := False;
  FEditor.Visible := False;
  FEditor.Parent := Self;
end;

{------------------------------------------------------------------------------
   TCustomListView CustomDraw
------------------------------------------------------------------------------}
function TCustomListView.CustomDraw(const ARect: TRect; AStage: TCustomDrawStage): Boolean;
begin
  Result := True;
  if Assigned(FOnCustomDraw) and (AStage = cdPrePaint)
  then FOnCustomDraw(Self, ARect, Result);

  if Assigned(FOnAdvancedCustomDraw)
  then FOnAdvancedCustomDraw(Self, ARect, AStage, Result)
end;

{------------------------------------------------------------------------------}
{   TCustomListView CustomDrawItem                                             }
{------------------------------------------------------------------------------}
function TCustomListView.CustomDrawItem(AItem: TListItem; AState: TCustomDrawState; AStage: TCustomDrawStage): Boolean;
begin
  Result := True;
  if Assigned(FOnCustomDrawItem) and (AStage = cdPrePaint)
  then FOnCustomDrawItem(Self, AItem, AState, Result);
  
  if Assigned(FOnAdvancedCustomDrawItem)
  then FOnAdvancedCustomDrawItem(Self, AItem, AState, AStage, Result);
end;

{------------------------------------------------------------------------------}
{   TCustomListView CustomDrawSubItem                                          }
{------------------------------------------------------------------------------}
function TCustomListView.CustomDrawSubItem(AItem: TListItem; ASubItem: Integer; AState: TCustomDrawState; AStage: TCustomDrawStage): Boolean;
begin
  Result := True;
  if Assigned(FOnCustomDrawSubItem) and (AStage = cdPrePaint)
  then FOnCustomDrawSubItem(Self, AItem, ASubItem, AState, Result);
  
  if Assigned(FOnAdvancedCustomDrawSubItem)
  then FOnAdvancedCustomDrawSubItem(Self, AItem, ASubItem, AState, AStage, Result);

end;

{------------------------------------------------------------------------------}
{   TCustomListView Change                                                     }
{------------------------------------------------------------------------------}
procedure TCustomListView.Change(AItem: TListItem; AChange: Integer);
var
  ItemChange: TItemChange;
begin
  case AChange of
    LVIF_TEXT: ItemChange := ctText;
    LVIF_IMAGE: ItemChange := ctImage;
    LVIF_STATE: ItemChange := ctState;
  else
    Exit;
  end;
  if Assigned(FOnChange)
  then FOnChange(Self, AItem, ItemChange);
end;

function TCustomListView.CanChange(AItem: TListItem; AChange: Integer): Boolean;
var
  ItemChange: TItemChange;
begin
  Result := True;
  case AChange of
    LVIF_TEXT: ItemChange := ctText;
    LVIF_IMAGE: ItemChange := ctImage;
    LVIF_STATE: ItemChange := ctState;
  else
    Exit;
  end;
  if Assigned(FOnChanging) then
    FOnChanging(Self, AItem, ItemChange, Result);
end;

{------------------------------------------------------------------------------}
{   TCustomListView ColClick                                                   }
{------------------------------------------------------------------------------}
procedure TCustomListView.ColClick(AColumn: TListColumn);
const
  DirToIndicator : array [TSortDirection] of TSortIndicator = (siAscending, siDescending);
var
  i: Integer;
begin
  if IsEditing then
  begin
    if FEditor.Focused then
    begin
      SetFocus;
      HideEditor;
    end;
  end;
  if Assigned(FOnColumnClick) and ColumnClick then FOnColumnClick(Self, AColumn);
  // we set autosort after FOnColumnClick, maybe programmer want to
  // stop autosorting after some special column is clicked.
  if FAutoSort then
  begin
    if SortType <> stNone then
    begin
      if AColumn.Index <> SortColumn then begin
        if FAutoSortIndicator then
          for i:=0 to Columns.Count-1 do
            if (i <> AColumn.Index) and (Columns[i].SortIndicator <> siNone) then
              Columns[i].SortIndicator := siNone;

        SortColumn := AColumn.Index;
        SortDirection := sdAscending;
        if FAutoSortIndicator then AColumn.SortIndicator := siAscending;
      end
      else
      begin
        // with same column we are changing only direction
        if SortDirection = sdAscending then
          SortDirection := sdDescending
        else
          SortDirection := sdAscending;
        if FAutoSortIndicator then AColumn.SortIndicator := DirToIndicator[SortDirection];
      end;
    end;
  end;
end;

{------------------------------------------------------------------------------}
{   TCustomListView CNNotify                                                   }
{------------------------------------------------------------------------------}
procedure TCustomListView.CNNotify(var AMessage: TLMNotify);
var
  nm: PNMListView;
  Item: TListItem;
  n: Integer;
  oldSelected: TListItem;
  AllowChange: Boolean;
begin
  nm := PNMListView(AMessage.NMHdr);
  // ignore any notifications while initializing items
  if (nm^.iItem >= Items.Count) or
     not (OwnerData or (lisfWSItemsCreated in FListItems.Flags)) then Exit;
  //remark: NMHdr^.code is normally unhanged by the win32 interface, so the others
  //        maps there codes to the of win32
  case AMessage.NMHdr^.code of 
//  HDN_TRACK:
//  NM_CUSTOMDRAW:
      // Custom Drawing is handled direct from the interfaces by IntfCustomDraw
//  LVN_BEGINDRAG:
    LVN_DELETEITEM: begin
      Item := FListItems[nm^.iItem];
      if FSelected = Item then
        InvalidateSelected;
      if Item = nil then Exit; //? nm^.iItem > Items.Count ?
      Exclude(Item.FFlags, lifCreated);
      if not (lifDestroying in Item.FFlags)
      then Item.Delete;
    end;
    LVN_DELETEALLITEMS: begin
      InvalidateSelected;
      for n := FListItems.Count - 1 downto 0 do
      begin
        Item := FListItems[n];
        Exclude(Item.FFlags, lifCreated);
        if not (lifDestroying in Item.FFlags)
        then Item.Delete;
      end;
    end;
//    LVN_GETDISPINFO:
//    LVN_ODCACHEHINT:
//    LVN_ODFINDITEM:     implemented in win32 widgetset
//    LVN_ITEMCHANGING:   implemented in win32 widgetset
//    LVN_ODSTATECHANGED:
//    LVN_BEGINLABELEDIT: implemented via TCustomListViewEditor
//    LVN_ENDLABELEDIT:   implemented via TCustomListViewEditor
    LVN_COLUMNCLICK:
    begin
      ColClick(Columns[nm^.iSubItem]);
    end;
    LVN_INSERTITEM: begin
      // don't call insert yet,
      // there is no solution available when we have inserted the item first
      // see delete
      // besides... who's inserting items
    end;

    LVN_ITEMCHANGING: begin
      //Currently implemented in win32 widgeset only
      //in response CanChange should be called and the result of that function most likely
      //should be handled at WS level (if at all possible for non-windows)
    end;

LVN_ITEMCHANGED:
    begin
      if nm^.iItem < 0 then
        Item := nil
      else
        Item := Items[nm^.iItem];
      //DebugLn('TCustomListView.CNNotify Count=',dbgs(Items.Count),' nm^.iItem=',dbgs(nm^.iItem),' destroying=',dbgs(lifDestroying in Item.FFlags));
      if (Item <> nil) and (not OwnerData) and (lifDestroying in Item.FFlags) then
      begin
        if Item=FFocused then
          FFocused:=nil;
        if Item=FSelected then
          InvalidateSelected;
      end else
      begin
        if (nm^.uChanged = LVIF_STATE) then
        begin
          // checkbox
          if Checkboxes then
            DoItemChecked(Item);
                
          // end editing
          if (IsEditing and OwnerData) then
           if (nm^.iItem = -1) And (FSelectedIdx<>-1) then
             if TWSCustomListViewClass(WidgetSetClass).MustHideEditor(self, FSelectedIdx) then
               HideEditor;
           
          // focus
          if (nm^.uOldState and LVIS_FOCUSED) <> (nm^.uNewState and LVIS_FOCUSED) then
          begin
            // focus state changed
            if (nm^.uNewState and LVIS_FOCUSED) = 0 then
            begin
              if FFocused = Item then
                FFocused := nil;
            end
            else
              FFocused := Item;
          end;
          // select
          if (((nm^.uOldState and LVIS_SELECTED) <> (nm^.uNewState and LVIS_SELECTED)))
          or (not (lffSelectedValid in FFlags) and (nm^.uNewState and LVIS_SELECTED <> 0)) then
          begin
            oldSelected := FSelected;
            if MultiSelect and OwnerData then
              UpdateMultiSelList(Item, nm^.uNewState and LVIS_SELECTED <> 0);

            // select state changed
            if (nm^.uNewState and LVIS_SELECTED) = 0 then
            begin
              if not OwnerData then
              begin
                if FSelected = Item then
                  InvalidateSelected
              end else
              begin
                if (nm^.iItem < 0) or (nm^.iItem = FSelectedIdx) then
                  if not MultiSelect then
                    InvalidateSelected;
                Item := oldSelected;
              end;
            end else
            begin
              FSelected := Item;
              Include(FFlags,lffSelectedValid);
              if OwnerData then
                FSelectedIdx:=nm^.iItem;
              //DebugLn('TCustomListView.CNNotify FSelected=',dbgs(FSelected));
            end;
            Change(Item, nm^.uChanged);
            DoSelectItem(Item, (nm^.uNewState and LVIS_SELECTED) <> 0);
          end;
        end
        else
          Change(Item, nm^.uChanged);
      end;
    end;
//    LVN_GETINFOTIP:
//    NM_CLICK:
//    NM_RCLICK:
  end;
end;

procedure TCustomListView.DrawItem(AItem: TListItem; ARect: TRect;
  AState: TOwnerDrawState);
begin
  if Assigned(FOnDrawItem) then FOnDrawItem(Self, AItem, ARect, AState)
  else
  begin
    FCanvas.FillRect(ARect);
    FCanvas.TextOut(ARect.Left + 2, ARect.Top, AItem.Caption);
  end;
end;

procedure TCustomListView.CNDrawItem(var Message: TLMDrawListItem);
var
  State: TOwnerDrawState;
  SaveIndex: Integer;
begin
  if Assigned(FCanvas) then
  begin
    with Message.DrawListItemStruct^ do
    begin
      State := ItemState;
      SaveIndex := SaveDC(DC);
      FCanvas.Lock;
      try
        FCanvas.Handle := DC;
        FCanvas.Font := Font;
        FCanvas.Brush := Brush;
        if itemID = DWORD(-1) then
          FCanvas.FillRect(Area)
        else
          DrawItem(Items[itemID], Area, State);
      finally
        FCanvas.Handle := 0;
        FCanvas.Unlock;
        RestoreDC(DC, SaveIndex);
      end;
    end;
    Message.Result := 1;
  end;
end;

procedure TCustomListView.InvalidateSelected;
begin
  FSelected:=nil;
  FSelectedIdx := -1;
  Exclude(FFlags,lffSelectedValid);
end;

procedure TCustomListView.HideEditor;
var
  S: String;
begin
  S := FEditor.Text;
  if FEditor.Item <> nil then
  begin
    if MultiSelect and OwnerData then
      DoEndEdit(Items[FSelectedIdx], S)
    else
      DoEndEdit(FEditor.Item, S);
  end;
  FEditor.Item := nil;
  FEditor.Visible := False;
  FEditor.SetBounds(0, 0, 0, 0);
end;

procedure TCustomListView.ShowEditor;
var
  Item: TListItem;
  R: TRect;
  TempHeight: Integer;
  S: String;
begin
  if (ItemIndex >= 0) and (ItemIndex < Items.Count) then
    Item := Items[ItemIndex]
  else
    Item := nil;
  HideEditor;
  if Item = nil then
    exit;
  if not CanEdit(Item) then
    exit;

  R := Item.DisplayRect(drLabel);
  if LCLIntf.IsRectEmpty(R) then
    exit;
  S := Item.Caption;
  if S = '' then
    S := 'H';
  TempHeight := Canvas.TextHeight(S);
  if TempHeight >= R.Bottom - R.Top then
    TempHeight := TempHeight - (R.Bottom - R.Top) + 4 {border above and below text}
  else
    TempHeight := 0;
  with R do
    FEditor.SetBounds(Left, Top, Right - Left, (Bottom - Top) + TempHeight);
  FEditor.Item := Item;
  FEditor.Text := Item.Caption;
  FEditor.Visible := True;
  FEditor.SetFocus;
end;

procedure TCustomListView.WMHScroll(var message: TLMHScroll);
begin
  if IsEditing then
  begin
    if FEditor.Focused then
      SetFocus
    else
      HideEditor;
  end;
end;

procedure TCustomListView.WMVScroll(var message: TLMVScroll);
begin
  if IsEditing then
  begin
    if FEditor.Focused then
      SetFocus
    else
      HideEditor;
  end;
end;

{------------------------------------------------------------------------------}
{   TCustomListView IsCustomDrawn                                              }
{------------------------------------------------------------------------------}
function TCustomListView.IsCustomDrawn(ATarget: TCustomDrawTarget; AStage: TCustomDrawStage): Boolean;
begin
  case ATarget of
    dtControl: Result := Assigned(FOnAdvancedCustomDraw)
                      or Assigned(FOnAdvancedCustomDrawItem)
                      or Assigned(FOnAdvancedCustomDrawSubItem);
    dtItem:    Result := Assigned(FOnAdvancedCustomDrawItem)
                      or Assigned(FOnAdvancedCustomDrawSubItem);
    dtSubItem: Result := Assigned(FOnAdvancedCustomDrawSubItem);
  end;
  
  if Result then exit;

  // check the normal events only in the prepaint stage
  if AStage <> cdPrePaint then Exit;

  case ATarget of
    dtControl: Result := Assigned(FOnCustomDraw)
                      or Assigned(FOnCustomDrawItem)
                      or Assigned(FOnCustomDrawSubItem);
    dtItem:    Result := Assigned(FOnCustomDrawItem)
                      or Assigned(FOnCustomDrawSubItem);
    dtSubItem: Result := Assigned(FOnCustomDrawSubItem);
  end;
end;

{------------------------------------------------------------------------------}
{   TCustomListView InitializeWnd                                              }
{------------------------------------------------------------------------------}
procedure TCustomListView.InitializeWnd;
var
  LVC: TWSCustomListViewClass;
  lvil: TListViewImageList;
begin
  inherited InitializeWnd;
  
  LVC := TWSCustomListViewClass(WidgetSetClass);

  // set the style first
  LVC.SetViewStyle(Self, FViewStyle);
  
  // add columns
  FColumns.WSCreateColumns;
  
  // set imagelists and item depending properties
  for lvil := Low(TListViewImageList) to High(TListViewImageList) do
  begin
    if FImages[lvil] <> nil
    then LVC.SetImageList(Self, lvil, FImages[lvil].ResolutionForPPI[FImagesWidth[lvil], Font.PixelsPerInch, 1].Resolution); // to-do: support scaling factor
  end;
  LVC.SetScrollBars(Self, FScrollBars);
  LVC.SetViewOrigin(Self, FViewOriginCache) ;
  LVC.SetProperties(Self, FProperties);
  LVC.SetSort(Self, FSortType, FSortColumn, FSortDirection);

  // add items
  if not OwnerData then 
  begin
    FListItems.WSCreateItems;
    // set other properties
    LVC.SetAllocBy(Self, FAllocBy);
  end 
  else 
  begin
    LVC.SetOwnerData(Self, True);
    LVC.SetItemsCount(Self, FListItems.Count);
  end;
  
  LVC.SetDefaultItemHeight(Self, FDefaultItemHeight);
  LVC.SetHotTrackStyles(Self, FHotTrackStyles);
  LVC.SetHoverTime(Self, FHoverTime);

  if FSelected <> nil 
  then LVC.ItemSetState(Self, FSelected.Index, FSelected, lisSelected, True);
  if FFocused <> nil
  then LVC.ItemSetState(Self, FFocused.Index, FFocused, lisFocused, True);
end;

{------------------------------------------------------------------------------}
{   TCustomListView DoDeletion                                                 }
{------------------------------------------------------------------------------}
procedure TCustomListView.DoDeletion(AItem: TListItem);
begin
  if not (TMethod(@Self.Delete).Code = Pointer(@TCustomListView.Delete)) then
    //There is an override for Delete, so use that for Delphi compatibility. Issue #0038263
    Delete(AItem)
  else
  //if you change the code below, make sure to change it in TCustomListView.Delete as well
  if {not (csDestroying in ComponentState) and} Assigned(FOnDeletion) then
    FOnDeletion(Self, AItem);
end;

{------------------------------------------------------------------------------}
{   TCustomListView Delete                                                     }
{------------------------------------------------------------------------------}
procedure TCustomListView.Delete(AItem : TListItem);
begin
  {
    In Delphi Delete is called in reaction to Items.Delete, but
    if you call it directly it will also do the actual deletion and then call the OnDeletion handler
    In that case we simply call Items.Delete and this will then call Delete again and in the second run
    we call the OnDeletion handler.
    Not 100% Delphi compatible, but more compatible then it was before. (BB)
  }
  //debugln(['TCustomListView.Delete: (lifDestroying in AItem.FFlags)=',(lifDestroying in AItem.FFlags)]);
  if not (lifDestroying in AItem.FFlags) then
  begin
    AItem.Delete;
    Exit;
  end;
  if {not (csDestroying in ComponentState) and} Assigned(FOnDeletion) then
    FOnDeletion(Self, AItem);
end;

{------------------------------------------------------------------------------}
{   TCustomListView DoInsert                                                   }
{------------------------------------------------------------------------------}
procedure TCustomListView.DoInsert(AItem: TListItem);
begin
  if not (TMethod(@Self.InsertItem).Code = Pointer(@TCUstomListView.InsertItem)) then
    //There is an override for InsertItem, so use that for Delphi compatibility. Issue #0038263
    InsertItem(AItem)
  else
    //if you change the code below, make sure to change it in TCustomListView.Delete as well
    if Assigned(FOnInsert) then FOnInsert(Self, AItem);
end;

{------------------------------------------------------------------------------}
{   TCustomListView InsertItem                                                 }
{------------------------------------------------------------------------------}
procedure TCustomListView.InsertItem(AItem : TListItem);
begin
  if Assigned(FOnInsert) then FOnInsert(Self, AItem);
end;

{------------------------------------------------------------------------------}
{   TCustomListView DoItemChecked                                              }
{------------------------------------------------------------------------------}
procedure TCustomListView.DoItemChecked(AItem: TListItem);
var
  B: Boolean;
begin
  if (not HandleAllocated) or (csLoading in ComponentState) then exit;
  B := TWSCustomListViewClass(WidgetSetClass).ItemGetChecked(Self,
    AItem.Index, AItem);
  if B <> AItem.GetCheckedInternal then
  begin
    AItem.Checked := B;
    if Assigned(FOnItemChecked) then
      FOnItemChecked(Self, AItem);
  end;
end;

{------------------------------------------------------------------------------}
{   TCustomListView DoSelectItem                                               }
{------------------------------------------------------------------------------}
procedure TCustomListView.DoSelectItem(AItem: TListItem; ASelected: Boolean);
begin
  if Assigned(AItem) then
    AItem.Selected:=ASelected;
  if Assigned(FOnSelectItem) and
    ([lffItemsMoving, lffItemsSorting] * FFlags = []) then
      FOnSelectItem(Self, AItem, ASelected);
end;

procedure TCustomListView.DoAutoAdjustLayout(
  const AMode: TLayoutAdjustmentPolicy; const AXProportion, AYProportion: Double
  );
var
  i: Integer;
  C: TListColumn;
  L: TListViewImageList;
begin
  inherited;

  if AMode in [lapAutoAdjustWithoutHorizontalScrolling, lapAutoAdjustForDPI] then
  begin
    for i := ColumnCount - 1 downto 0 do
    begin
      C := Column[i];
      C.MaxWidth := Round(C.MaxWidth * AXProportion);
      C.MinWidth := Round(C.MinWidth * AXProportion);
      C.Width := Round(C.Width * AXProportion);
    end;

    for L in TListViewImageList do
      SetImageListWS(L);
  end;
end;

procedure TCustomListView.DoSetBounds(ALeft, ATop, AWidth, AHeight: integer);
begin
  inherited DoSetBounds(ALeft, ATop, AWidth, AHeight);
  if AutoWidthLastColumn then
    ResizeLastColumn;
end;

procedure TCustomListView.DoEndEdit(AItem: TListItem; const AValue: String);
var
  S: string;
begin
  if not (TMethod(@Self.Edit).Code = Pointer(@TCustomListView.Edit)) then
    //There is an override for Edit, so use that for Delphi compatibility. Issue #0038263
    Edit(AItem)
  else
  begin
    //if you change the code below, make sure to change it in TCustomListView.Edit as well
    S := AValue;
    if Assigned(FOnEdited) then
      FOnEdited(Self, AItem, S);
    if AItem <> nil then
      AItem.Caption := S;
  end;
end;

procedure TCustomListView.Edit(AItem: TListItem);
var
  S: String;
begin
  //debugln(['TCustomListView.Edit: FEditor.Text=',FEditor.Text]);
  S := FEditor.Text;
  if Assigned(FOnEdited) then
    FOnEdited(Self, AItem, S);
  if AItem <> nil then
    AItem.Caption := S;
end;

{------------------------------------------------------------------------------}
{   TCustomListView ItemDeleted                                                }
{------------------------------------------------------------------------------}
procedure TCustomListView.ItemDeleted(const AItem: TListItem);  //called by TListItems
begin
  //DebugLn('TCustomListView.ItemDeleted ',dbgs(AItem),' FSelected=',dbgs(FSelected));
  if FSelected = AItem then InvalidateSelected;
  if FFocused = AItem then FFocused := nil;
  DoDeletion(AItem);
end;

{------------------------------------------------------------------------------}
{   TCustomListView ItemInserted                                               }
{------------------------------------------------------------------------------}
procedure TCustomListView.ItemInserted(const AItem: TListItem);
begin
  if csDestroying in Componentstate then Exit;
  DoInsert(AItem);
end;

class procedure TCustomListView.WSRegisterClass;
begin
  RegisterPropertyToSkip(Self, 'ItemIndex', 'Property streamed in older Lazarus revision', '');
  RegisterPropertyToSkip(Self, 'BevelKind', 'VCL compatibility property', '');
  RegisterPropertyToSkip(TListItem, 'OverlayIndex', 'VCL compatibility property', '');
  inherited WSRegisterClass;
  RegisterCustomListView;
end;

class function TCustomListView.GetControlClassDefaultSize: TSize;
begin
  Result.CX := 250;
  Result.CY := 150;
end;

{------------------------------------------------------------------------------}
{   TCustomListView SetItems                                                   }
{------------------------------------------------------------------------------}
procedure TCustomListView.SetItems(const AValue : TListItems);
begin
end;

{------------------------------------------------------------------------------}
{   TCustomListView SetItemVisible                                             }
{------------------------------------------------------------------------------}
procedure TCustomListView.SetItemVisible(const AValue : TListItem;
                                                     const APartialOK: Boolean);
begin
  if (not HandleAllocated) or (csLoading in ComponentState) then exit;
  TWSCustomListViewClass(WidgetSetClass).ItemShow(
                                        Self, AValue.Index, AValue, APartialOK);
end;



function TCustomListView.IntfCustomDraw(ATarget: TCustomDrawTarget; AStage: TCustomDrawStage; AItem, ASubItem: Integer; AState: TCustomDrawState; const ARect: PRect): TCustomDrawResult;
begin
  Result := [];
  
  // in the prepaint stage, return the notifications we want
  if AStage = cdPrePaint
  then begin
    case ATarget of
      dtControl: begin
        if IsCustomDrawn(dtItem, cdPrePaint) or IsCustomDrawn(dtItem, cdPreErase)
        then Include(Result, cdrNotifyItemDraw);

        if IsCustomDrawn(dtItem, cdPostPaint)
        then Include(Result, cdrNotifyPostPaint);

        if IsCustomDrawn(dtItem, cdPostErase)
        then Include(Result, cdrNotifyPostErase);

        if IsCustomDrawn(dtSubItem, cdPrePaint)
        then Include(Result, cdrNotifySubitemDraw);
      end;
      dtItem: begin
        if IsCustomDrawn(dtItem, cdPostPaint)
        then Include(Result, cdrNotifyPostPaint);

        if IsCustomDrawn(dtItem, cdPostErase)
        then Include(Result, cdrNotifyPostErase);

        if IsCustomDrawn(dtSubItem, cdPrePaint)
        then Include(Result, cdrNotifySubitemDraw);
      end;
      dtSubItem: begin
        if IsCustomDrawn(dtSubItem, cdPostPaint)
        then Include(Result, cdrNotifyPostPaint);

        if IsCustomDrawn(dtSubItem, cdPostErase)
        then Include(Result, cdrNotifyPostErase);
      end;
    end;
  end;

  if not IsCustomDrawn(ATarget, AStage) then Exit;


  case ATarget of
    dtControl: if CustomDraw(ARect^, AStage) then Exit;
    dtItem:    if CustomDrawItem(Items[AItem], AState, AStage) then Exit;
    dtSubItem: if CustomDrawSubItem(Items[AItem], ASubItem, AState, AStage) then Exit;
  end;

  // if we are here, a custom step returned false, so no default drawing
  if AStage = cdPrePaint
  then Result := [cdrSkipDefault];
end;

function TCustomListView.GetUpdateCount: Integer;
begin
  Result := FUpdateCount;
end;

procedure TCustomListView.DoGetOwnerData(Item: TListItem); 
begin
  if Assigned(OnData) then OnData(Self, Item);
end;

function TCustomListView.DoOwnerDataHint(AStartIndex, AEndIndex: Integer
  ): Boolean;
begin
  Result := Assigned(FOnDataHint);
  if Result then
    FOnDataHint(Self, AStartIndex, AEndIndex);
end;

function TCustomListView.DoOwnerDataStateChange(AStartIndex,
  AEndIndex: Integer; AOldState, ANewState: TListItemStates): Boolean;
begin
  Result := Assigned(FOnDataStateChange);
  if Result then
    FOnDataStateChange(Self, AStartIndex, AEndIndex, AOldState, ANewState);
end;

function TCustomListView.DoOwnerDataFind(AFind: TItemFind; const AFindString: string;
  const AFindPosition: TPoint; AFindData: Pointer; AStartIndex: Integer;
  ADirection: TSearchDirection; AWrap: Boolean): Integer;
begin
  Result := -1;
  if Assigned(FOnDataFind) then
    FOnDataFind(Self, AFind, AFindString, AFindPosition, AFindData, AStartIndex,
      ADirection, AWrap, Result);
end;

procedure TCustomListView.QueuedShowEditor(Data: PtrInt);
begin
  if fShowEditorQueued and IsVisible then
  begin
    fShowEditorQueued:=false;
    ShowEditor;
  end;
end;

procedure TCustomListView.DblClick;
begin
  inherited DblClick;
  if not ReadOnly and Assigned(FEditor) then
    ShowEditorQueued:=true;
end;

procedure TCustomListView.KeyDown(var Key: Word; Shift: TShiftState);
begin
  if not ReadOnly and (Key = VK_F2) and (Shift = []) then
  begin
    ShowEditor;
    Key := 0;
  end else
    inherited KeyDown(Key, Shift);
end;

{------------------------------------------------------------------------------}
{   TCustomListView SetColumns                                                 }
{------------------------------------------------------------------------------}
procedure TCustomListView.SetColumns(const AValue: TListColumns);
begin
  if AValue=FColumns then exit;
  BeginUpdate;
  FColumns.Assign(AValue);
  EndUpdate;
  if ([csDesigning,csLoading,csReading]*ComponentState=[csDesigning]) then
    OwnerFormDesignerModified(Self);
end;


{------------------------------------------------------------------------------}
{   TCustomListView SetViewOrigin                                              }
{------------------------------------------------------------------------------}
procedure TCustomListView.SetViewOrigin(AValue: TPoint);
begin
  if AValue.X < 0 then AValue.X := 0;
  if AValue.Y < 0 then AValue.Y := 0;
  if HandleAllocated
  then begin
    TWSCustomListViewClass(WidgetSetClass).SetViewOrigin(Self, AValue);
  end
  else begin
    FViewOriginCache := AValue;
  end;
end;

{------------------------------------------------------------------------------}
{   TCustomListView SetViewStyle                                               }
{------------------------------------------------------------------------------}
procedure TCustomListView.SetViewStyle(const Avalue: TViewStyle);
begin
  if FViewStyle = AValue then Exit;
  FViewStyle := AValue;
  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).SetViewStyle(Self, AValue);
end;

{------------------------------------------------------------------------------}
{   TCustomListView SetSortType                                                }
{------------------------------------------------------------------------------}
procedure TCustomListView.SetSortType(const AValue: TSortType);
begin
  if FSortType = AValue then Exit;
  FSortType := AValue;
  Sort;
end;

{------------------------------------------------------------------------------}
{   TCustomListView SetSortColumn                                              }
{------------------------------------------------------------------------------}
procedure TCustomListView.SetSortColumn(const AValue : Integer);
begin
  if FSortColumn = AValue then Exit;
  FSortColumn := AValue;
  Sort;
end;

procedure TCustomListView.SetSortDirection(const AValue: TSortDirection);
begin
  if FSortDirection=AValue then exit;
  FSortDirection:=AValue;
  Sort;
end;

function _CompareListViewItems_CustomSort(Item1, Item2: Pointer): Integer;
var
  ListView: TCustomListView;
begin
  Result := 0;
  ListView := TListItem(Item1).Owner.Owner;

  if Assigned(ListView.FCustomSort_Func) then
    Result := ListView.FCustomSort_Func(TListItem(Item1), TListItem(Item2), ListView.FCustomSort_Param)
  else
  if Assigned(ListView.FOnCompare) then
    ListView.FOnCompare(ListView, TListItem(Item1), TListItem(Item2), 0, Result);
end;

function _CompareListViewItems(Item1, Item2: Pointer): Integer;
var
  Str1: String;
  Str2: String;
  ListView: TCustomListView;
begin
  Result := 0;
  ListView := TListItem(Item1).Owner.Owner;
  if Assigned(ListView.FOnCompare) then
    ListView.FOnCompare(ListView, TListItem(Item1), TListItem(Item2),0 ,Result)
  else
  begin
    if ListView.SortType in [stData] then
      Result := CompareValue(PtrUInt(TListItem(Item1).Data), PtrUInt(TListItem(Item2).Data))
    else
    begin
      if ListView.FSortColumn = 0 then
      begin
        Str1 := TListItem(Item1).Caption;
        Str2 := TListItem(Item2).Caption;
      end else
      begin
        if ListView.FSortColumn <= TListItem(Item1).SubItems.Count then
          Str1 := TListItem(Item1).SubItems.Strings[ListView.FSortColumn-1]
        else
          Str1 := '';
        if ListView.FSortColumn <= TListItem(Item2).SubItems.Count then
          Str2 := TListItem(Item2).SubItems.Strings[ListView.FSortColumn-1]
        else
          Str2 := '';
      end;
      Result := AnsiCompareText(Str1, Str2);
    end;
    if ListView.SortDirection = sdDescending then
      Result := -Result;
  end;
end;

{------------------------------------------------------------------------------}
{   TCustomListView Sort                                                       }
{------------------------------------------------------------------------------}
procedure TCustomListView.Sort;
begin
  if FSortType = stNone then exit;
  if (FSortColumn < 0) or (FSortColumn >= ColumnCount) then exit;
  SortWithParams(@_CompareListViewItems);
end;

function TCustomListView.CustomSort(ASortProc: TLVCompare; AOptionalParam: PtrInt): Boolean;
begin
  Result := Assigned(ASortProc) or Assigned(FOnCompare);
  if Result then
  begin
    FCustomSort_Func := ASortProc;
    FCustomSort_Param := AOptionalParam;
    SortWithParams(@_CompareListViewItems_CustomSort);
  end;
end;

procedure TCustomListView.SortWithParams(ACompareFunc: TListSortCompare);
var
  FSavedSelection: TFPList;
  FSavedFocused: TListItem;
  FSavedChecked: TFPList;
  FSavedCheckItem: TListItem;
  i: Integer;
  AItemIndex: Integer;
begin
  if FListItems.Count < 2 then exit;
  if lffPreparingSorting in FFlags then exit;

  if HandleAllocated then
  begin
    Include(FFlags, lffItemsSorting);
    FSavedSelection := TFPList.Create;
    FSavedChecked := nil;
    try
      if (ItemIndex >= 0) then
        FSavedFocused := Items[ItemIndex]
      else
        FSavedFocused := nil;
      if Assigned(Selected) then
      begin
        FSavedSelection.Add(Selected);
        if MultiSelect then
          for i := 0 to Items.Count-1 do
            if Items[i].Selected and (Items[i] <> Selected) then
              FSavedSelection.Add(Items[i]);
      end;
      if Checkboxes and (TWSCustomListViewClass(WidgetSetClass).RestoreItemCheckedAfterSort(Self))
        and Items.WSUpdateAllowed
        and not OwnerData then
      begin
        FSavedChecked := TFPList.Create;
        for i := 0 to Items.Count - 1 do
          if Items[i].Checked then
            FSavedChecked.Add(Items[i]);
      end;

      Items.FCacheIndex := -1;
      Items.FCacheItem := nil;

      FListItems.FItems.Sort(ACompareFunc);
      TWSCustomListViewClass(WidgetSetClass).SetSort(Self, FSortType,
        FSortColumn, FSortDirection);

      if (FSavedSelection.Count > 0) or Assigned(FSavedFocused) then
      begin
        Selected := nil; // unselect all

        if FSavedFocused <> nil then
          TWSCustomListViewClass(WidgetSetClass).ItemSetState(Self,
            FSavedFocused.Index, FSavedFocused, lisFocused, True);

        for i := FSavedSelection.Count - 1 downto 0 do
        begin
          AItemIndex := Items.IndexOf(TListItem(FSavedSelection.Items[i]));
          if AItemIndex <> -1 then
            TWSCustomListViewClass(WidgetSetClass).ItemSetState(Self,
              AItemIndex, Items[AItemIndex], lisSelected, True);
        end;
      end;

      if FSavedChecked <> nil then
      begin
        for i := 0 to FSavedChecked.Count - 1 do
        begin
          FSavedCheckItem := TListItem( FSavedChecked[i] );
          // todo: this is inefficient, because FSavedCheckItem.Index must be called again
          TWSCustomListViewClass(WidgetSetClass).ItemSetChecked(Self,
            FSavedCheckItem.Index, FSavedCheckItem, True);
        end;
        FSavedChecked.Free;
      end;
    finally
      FreeThenNil(FSavedSelection);
      Exclude(FFlags, lffItemsSorting);
    end;
  end else
    FListItems.FItems.Sort(ACompareFunc);
end;

{------------------------------------------------------------------------------}
{   TCustomListView Destructor                                                 }
{------------------------------------------------------------------------------}
destructor TCustomListView.Destroy;
var
  lvil: TListViewImageList;
begin
  Application.RemoveAsyncCalls(Self);
  // Better destroy the wincontrol (=widget) first. So wo don't have to delete
  // all items/columns and we won't get notifications for each.
  FreeAndNil(FCanvas);
  inherited Destroy;
  FreeAndNil(FColumns);
  for lvil := Low(TListViewImageList) to High(TListViewImageList) do
    FreeAndNil(FImageChangeLinks[lvil]);
  FreeAndNil(FOwnerDataItem);
  FreeAndNil(FListItems);
  FreeAndNil(FIconOptions);
end;

procedure TCustomListView.AddItem(Item: string; AObject: TObject);
var
  AItem: TListItem;
begin
  AItem := Items.Add;
  AItem.Caption := Item;
  AItem.Data := AObject;
end;

function TCustomListView.AlphaSort: Boolean;
begin
  Result := False;
  Include(FFlags, lffPreparingSorting);
  // always reset direction, so sort triggers later !
  SortDirection := sdDescending;
  SortType := stText;
  SortColumn := 0;
  Exclude(FFlags, lffPreparingSorting);
  // now trigger sort when all rules are applied
  SortDirection := sdAscending;
  Result := True;
end;

{------------------------------------------------------------------------------
   TCustomListView DestroyWnd
   Params: None
   Result: none

   Frees the canvas
 ------------------------------------------------------------------------------}
procedure TCustomListView.DestroyWnd; 
begin
  if FCanvas<>nil then
    TControlCanvas(FCanvas).FreeHandle;
  inherited DestroyWnd;
end;

procedure TCustomListView.BeginAutoDrag;
begin
  BeginDrag(False);
end;

function TCustomListView.CreateListItem: TListItem;
var
  AItemClass: TListItemClass;
begin
  AItemClass := TListItem;
  if Assigned(OnCreateItemClass) then
    OnCreateItemClass(Self, AItemClass);
  Result := AItemClass.Create(Items);
end;

function TCustomListView.CreateListItems: TListItems;
begin
  Result := TListItems.Create(Self);
end;

{------------------------------------------------------------------------------
   TCustomListView BeginUpdate
   Params: None
   Result: none

   Increases the update count. Use this procedure before any big change, so that
   the interface will not show any single step.
 ------------------------------------------------------------------------------}
procedure TCustomListView.BeginUpdate;
begin
  Inc(FUpdateCount);
  Include(FFlags, lffPreparingSorting);
  if (FUpdateCount = 1) and HandleAllocated
  then TWSCustomListViewClass(WidgetSetClass).BeginUpdate(Self);
end;

function TCustomListView.CanEdit(Item: TListItem): Boolean;
begin
  Result := True;
  if Assigned(FOnEditing) then
    FOnEditing(Self, Item, Result);
end;

procedure TCustomListView.Clear;
begin
  FListItems.Clear;
end;

{------------------------------------------------------------------------------}
{   TCustomListView EndUpdate                                               }
{------------------------------------------------------------------------------}
procedure TCustomListView.EndUpdate;
begin
  if FUpdateCount <= 0
  then LazTracer.RaiseGDBException('TCustomListView.EndUpdate FUpdateCount=0');
  
  Dec(FUpdateCount);
  if FUpdateCount=0 then Exclude(FFlags, lffPreparingSorting);
  if (FUpdateCount = 0) and HandleAllocated
  then TWSCustomListViewClass(WidgetSetClass).EndUpdate(Self);
end;

procedure TCustomListView.Repaint;
begin
  if OwnerData then
    // the last cached item might be left updated, because OnData isn't called!
    FOwnerDataItem.SetDataIndex(-1);
  inherited Repaint;
end;

procedure TCustomListView.FinalizeWnd;
begin
  FShowEditorQueued:=false;
  // store origin
  FViewOriginCache := TWSCustomListViewClass(WidgetSetClass).GetViewOrigin(Self);
  if not OwnerData then
    FListItems.DoFinalizeWnd;
  Columns.DoFinalizeWnd;
  inherited FinalizeWnd;
end;

function TCustomListView.FindCaption(StartIndex: Integer; Value: string;
  Partial, Inclusive, Wrap: Boolean; PartStart: Boolean = True): TListItem;
begin
  Result := FListItems.FindCaption(StartIndex, Value, Partial, Inclusive, Wrap, PartStart);
end;

function TCustomListView.FindData(StartIndex: Integer; Value: Pointer;
  Inclusive, Wrap: Boolean): TListItem;
begin
  Result := FListItems.FindData(StartIndex, Value, Inclusive, Wrap);
end;

function TCustomListView.GetBoundingRect: TRect;
begin
  if not HandleAllocated
  then Result := Rect(0,0,0,0)
  else Result := TWSCustomListViewClass(WidgetSetClass).GetBoundingRect(Self);
end;

function TCustomListView.GetColumnCount: Integer;
begin
  Result := FColumns.Count;
end;

function TCustomListView.GetColumnFromIndex(AIndex: Integer): TListColumn;
begin
  Result := FColumns[AIndex];
end;

function TCustomListView.GetDropTarget: TListItem;
var
  idx: Integer;
begin
  if not HandleAllocated
  then idx := -1
  else idx := TWSCustomListViewClass(WidgetSetClass).GetDropTarget(Self);
  if idx = -1
  then Result := nil
  else Result := FListItems[idx];
end;

function TCustomListView.GetFocused: TListItem;
begin
  Result := FFocused;
end;

function TCustomListView.GetImageList(const ALvilOrd: Integer): TCustomImageList;
begin
  Result := FImages[TListViewImageList(ALvilOrd)];
end;

function TCustomListView.GetImageListWidth(const ALvilOrd: Integer): Integer;
begin
  Result := FImagesWidth[TListViewImageList(ALvilOrd)];
end;

function TCustomListView.GetHoverTime: Integer;
begin
  if HandleAllocated
  then Result := TWSCustomListViewClass(WidgetSetClass).GetHoverTime(Self)
  else Result := FHoverTime;
end;

function TCustomListView.GetItemIndex: Integer;
begin
  Result := -1;
  if not OwnerData then begin
    if Selected = nil then Exit;
    Result := Selected.Index
  end else
    Result := FSelectedIdx;
end;

function TCustomListView.GetHitTestInfoAt(X, Y: Integer): THitTests;
begin
  Result := [];
  if HandleAllocated then
    Result := TWSCustomListViewClass(WidgetSetClass).GetHitTestInfoAt( Self, X, Y );
end;

function TCustomListView.GetItemAt(x, y: integer): TListItem;
var 
  Item: Integer;
begin      
  Result := nil; 
  if HandleAllocated
  then begin
    Item := TWSCustomListViewClass(WidgetSetClass).GetItemAt(Self,x,y);
    if Item <> -1 
    then Result := Items[Item];
  end;
end;

function TCustomListView.GetNearestItem(APoint: TPoint;
  Direction: TSearchDirection): TListItem;
var
  AItem: TListItem;
  AIndex: Integer;
begin
  Result := nil;
  AItem := GetItemAt(APoint.x, APoint.y);
  if Assigned(AItem) then
  begin
    AIndex := AItem.Index;
    case Direction of
      sdAbove: if AIndex - 1 >= 0 then Result := Items[AIndex - 1];
      sdBelow: if AIndex - 1 < Items.Count then
        Result := Items[AIndex + 1];
    end;
  end;
end;

function TCustomListView.GetNextItem(StartItem: TListItem;
  Direction: TSearchDirection; States: TListItemStates): TListItem;
begin
  Result := nil;
  if HandleAllocated then
     Result := TWSCustomListViewClass(WidgetSetClass).GetNextItem(Self, StartItem, Direction, States);
end;

procedure TCustomListView.ClearSelection;
begin
  Self.BeginUpdate;
  if MultiSelect then
  begin
    if HandleAllocated then
      TWSCustomListViewClass(WidgetSetClass).SelectAll(Self, False);
    Items.ClearSelection;
  end else
  if (ItemIndex >= 0) and (ItemIndex < Items.Count) then
    Items.Item[ItemIndex].Selected := False;
  Self.EndUpdate;
end;

procedure TCustomListView.SelectAll;
begin
  if not MultiSelect then
    exit;
  Self.BeginUpdate;
  if HandleAllocated then
    TWSCustomListViewClass(WidgetSetClass).SelectAll(Self, True);
  Items.SelectAll;
  Self.EndUpdate;
end;

function TCustomListView.IsEditing: Boolean;
begin
  Result := Assigned(Self.FEditor) and FEditor.Visible;
end;

function TCustomListView.GetProperty(const ALvpOrd: Integer): Boolean;
begin
  Result := (TListViewProperty(ALvpOrd) in FProperties);
end;

function TCustomListView.GetSelCount: Integer;
var
  i: integer;
begin
  if HandleAllocated
  then Result := TWSCustomListViewClass(WidgetSetClass).GetSelCount(Self)
  else
  begin
    Result := 0;
    for i := 0 to Items.Count - 1 do
      if Items[i].Selected then
        inc(Result);
  end;
end;

{------------------------------------------------------------------------------
   TCustomListView GetSelection
------------------------------------------------------------------------------}
function TCustomListView.GetSelection: TListItem;
var
  i: Integer;
begin
  if OwnerData and not MultiSelect then
  begin
    if FSelectedIdx>=0 then begin
      FOwnerDataItem.SetDataIndex(FSelectedIdx);
      Result:=FOwnerDataItem;
    end else
      Result:=nil;
  end
  else begin
    { according to Delphi docs we always must return first selected item,
      not the last selected one see issue #16773 }
    if not (lffSelectedValid in FFlags) or MultiSelect then
    begin
      if MultiSelect and OwnerData then
      begin
        FSelected := GetFirstSelected;
        if FSelected <> nil then FSelectedIdx := FSelected.Index else FSelectedIdx := -1;
      end else
      begin
        FSelected := nil;
        if (not FOwnerData) or (FSelectedIdx >= 0) then
        begin
          if MultiSelect and FOwnerData and (FSelectedIdx >= 0) then
            FSelected := Items[FSelectedIdx]
          else
            for i := 0 to Items.Count - 1 do
            begin
              if Items[i].Selected then
              begin
                FSelected := Items[i];
                break;
              end;
            end;
        end;
      end;
      Include(FFlags, lffSelectedValid);
    end;
    Result := FSelected;
  end;
end;

function TCustomListView.GetTopItem: TListItem;
var
  idx: Integer;
begin
  if ViewStyle in [vsSmallIcon, vsIcon]
  then idx := -1
  else idx := TWSCustomListViewClass(WidgetSetClass).GetTopItem(Self);
  if idx = -1
  then Result := nil
  else Result := FListItems[idx];
end;

{------------------------------------------------------------------------------}
{   TCustomListView GetViewOrigin                                              }
{------------------------------------------------------------------------------}
function TCustomListView.GetViewOrigin: TPoint;
begin
  if HandleAllocated
  then begin
    Result := TWSCustomListViewClass(WidgetSetClass).GetViewOrigin(Self);
  end
  else begin
    Result := FViewOriginCache;
  end;
end;


function TCustomListView.GetVisibleRowCount: Integer;
begin
  if ViewStyle in [vsReport, vsList]
  then Result := TWSCustomListViewClass(WidgetSetClass).GetVisibleRowCount(Self)
  else Result := 0;
end;

procedure TCustomListView.SetAllocBy(const AValue: Integer);
begin
  if FAllocBy = AValue then Exit;
  FAllocBy := AValue;
  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).SetAllocBy(Self, AValue);
end;

procedure TCustomListView.ResizeLastColumn;
var
  i: Integer;
  LastVisibleColumn: Integer;
  Accu: Integer;
  W: Integer;
  NewWidth: Integer;
begin
  if not (ViewStyle in [vsList, vsReport]) or (ColumnCount = 0) then
    exit;
  LastVisibleColumn := -1;

  // find last visible column
  for i := ColumnCount - 1 downto 0 do
  begin
    if Column[i].Visible then
    begin
      LastVisibleColumn := i;
      break;
    end;
  end;

  // calculate size and apply it only if it's > 0
  if LastVisibleColumn >= 0 then
  begin
    //TODO: gtk2 doesnt return correct ClientWidth. win32 and qt works ok.
    W := ClientWidth - (BorderWidth * 2);
    Accu := 0;
    for i := 0 to LastVisibleColumn - 1 do
    begin
      if Column[i].Visible then
        Accu := Accu + Column[i].Width;
    end;
    NewWidth := W - Accu;
    if NewWidth > 0 then
    begin
      // now set AutoSize and MinWidth/MaxWidth to 0
      Column[LastVisibleColumn].AutoSize := False;
      Column[LastVisibleColumn].MinWidth := 0;
      Column[LastVisibleColumn].MaxWidth := 0;
      Column[LastVisibleColumn].Width := NewWidth;
    end;
  end;
end;

procedure TCustomListView.SetAutoWidthLastColumn(AValue: Boolean);
begin
  if FAutoWidthLastColumn=AValue then Exit;
  FAutoWidthLastColumn:=AValue;
  if FAutoWidthLastColumn then
    ResizeLastColumn;
end;

procedure TCustomListView.SetDefaultItemHeight(AValue: Integer);
begin
  if AValue <=0 then AValue := 20;
  if AValue = FDefaultItemHeight then Exit;
  FDefaultItemHeight := AValue;
  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).SetDefaultItemHeight(Self, AValue);
end;

procedure TCustomListView.SetDropTarget(const AValue: TListItem);
begin
  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).ItemSetState(Self, AValue.Index, AValue, lisDropTarget, True);
end;

procedure TCustomListView.SetFocused(const AValue: TListItem);
begin
  if FFocused = AValue then exit;
  FFocused := AValue;
  if not HandleAllocated then
    Exit;
  if FFocused <> nil then
    TWSCustomListViewClass(WidgetSetClass).ItemSetState(Self, FFocused.Index, FFocused, lisFocused, True);
end;

procedure TCustomListView.SetHotTrackStyles(const AValue: TListHotTrackStyles);
begin
  if FHotTrackStyles = AValue then Exit;
  FHotTrackStyles := AValue;
  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).SetHotTrackStyles(Self, AValue);
end;

procedure TCustomListView.SetHoverTime(const AValue: Integer);
begin
  if FHoverTime = AValue then Exit;
  FHoverTime := AValue;
  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).SetHoverTime(Self, FHoverTime);
end;

procedure TCustomListView.SetIconOptions(const AValue: TIconOptions);
begin
  FIconOptions.Assign(AValue);
end;

procedure TCustomListView.SetImageList(const ALvilOrd: Integer; const AValue: TCustomImageList);
var
  lvil: TListViewImageList;
begin
  lvil := TListViewImageList(ALvilOrd);

  if FImages[lvil] = AValue then Exit;

  if FImages[lvil] <> nil
  then FImages[lvil].UnregisterChanges(FImageChangeLinks[lvil]);

  FImages[lvil] := AValue;

  if FImages[lvil] <> nil
  then begin
    FImages[lvil].RegisterChanges(FImageChangeLinks[lvil]);
    FImages[lvil].FreeNotification(self);
  end;

  SetImageListWS(lvil);
end;

procedure TCustomListView.SetImageListAsync(Data: PtrInt);
begin
  SetImageListWS(TListViewImageList(Data));
end;

procedure TCustomListView.SetImageListWidth(const ALvilOrd: Integer;
  const AValue: Integer);
var
  lvil: TListViewImageList;
begin
  lvil := TListViewImageList(ALvilOrd);

  if FImagesWidth[lvil] = AValue then Exit;

  FImagesWidth[lvil] := AValue;

  SetImageListWS(lvil);
end;

procedure TCustomListView.SetImageListWS(const ALvil: TListViewImageList);
var
  R: TCustomImageListResolution;
begin
  if not HandleAllocated then
    Exit;
  if FImages[ALvil]<>nil then
    R := FImages[ALvil].ResolutionForPPI[FImagesWidth[ALvil], Font.PixelsPerInch, 1].Resolution // to-do: support scaling factor
  else
    R := nil;
  TWSCustomListViewClass(WidgetSetClass).SetImageList(Self, ALvil, R)
end;

procedure TCustomListView.SetItemIndex(const AValue: Integer);
begin
  if (AValue < -1) or (AValue >= Items.Count) then
    raise Exception.CreateFmt(rsListIndexExceedsBounds,[AValue]);

  if AValue = -1 then
    Selected := nil
  else
  begin
    // trigger ws selection update, it'll update Selected too
    if OwnerData then
    begin
      // clean selection when itemindex is changed. issue #19825
      if MultiSelect then
        Selected := nil;
      FSelectedIdx := AValue;
      Items.Item[AValue].Selected := True;
    end else
      Selected := Items.Item[AValue];
  end;
end;

{------------------------------------------------------------------------------
   TCustomListView SetSelection
------------------------------------------------------------------------------}
procedure TCustomListView.SetSelection(const AValue: TListItem);
var
  i: integer;
begin
  if (AValue<>nil) and (AValue.ListView<>Self) then
    raise Exception.Create('Item does not belong to this listview');
  if (not FOwnerData) and (FSelected = AValue) then Exit;
  //DebugLn('TCustomListView.SetSelection FSelected=',dbgs(FSelected));
  if AValue = nil then
  begin
    if MultiSelect then
    begin
      BeginUpdate;
      try
        for i:=0 to Items.Count-1 do
          with Items[i] do
            if Selected then
              Selected:=False;
      finally
        EndUpdate;
      end;
    end else
    if FSelected <> nil then
      FSelected.Selected := False;
    FSelected := nil;
    Include(FFlags,lffSelectedValid);
  end else
  begin
    FSelected := AValue;
    if HandleAllocated then
      TWSCustomListViewClass(WidgetSetClass).ItemSetState(Self, FSelected.Index,
          FSelected, lisSelected, True);
  end;
end;

procedure TCustomListView.SetShowEditorQueued(AValue: boolean);
begin
  if FShowEditorQueued=AValue then Exit;
  FShowEditorQueued:=AValue;
  if FShowEditorQueued then
    Application.QueueAsyncCall(@QueuedShowEditor,0);
end;

procedure TCustomListView.SetOwnerData(const AValue: Boolean);
begin
  if FOwnerData=AValue then exit;
  FOwnerData:=AValue;
  FOwnerDataItem.SetOwner(nil);
  Items.Free;
  if AValue then
  begin
    FSelectedIdx := -1;
    FListItems := TOwnerDataListItems.Create(Self);
  end
  else
    FListItems := CreateListItems;

  if HandleAllocated then 
    TWSCustomListViewClass(WidgetSetClass).SetOwnerData(Self, AValue);
  FOwnerDataItem.SetOwner(FListItems);
end;

procedure TCustomListView.SetProperty(const ALvpOrd: Integer;
  const AIsSet: Boolean);
var
  AProp: TListViewProperty;
begin
  AProp := TListViewProperty(ALvpOrd);
  if (AProp in FProperties) = AIsSet then Exit;

  if AIsSet
  then Include(FProperties, AProp)
  else Exclude(FProperties, AProp);

  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).SetProperty(Self, AProp, AIsSet);
end;

procedure TCustomListView.ImageChanged(Sender : TObject);
begin
  if csDestroying in ComponentState Then Exit;
// TODO: move Imagelist to interface, image changes can be update there
//  if FUpdateCount>0 then
//    Include(FStates,lvUpdateNeeded)
//  else begin
//    //image changed so redraw it all....
//    UpdateProperties;
//  end;
end;

procedure TCustomListView.ImageResolutionHandleDestroyed(
  Sender: TCustomImageList; AWidth: Integer; AReferenceHandle: TLCLHandle);
var
  lvil: TListViewImageList;
begin
  if not HandleAllocated then
    Exit;

  for lvil in TListViewImageList do
    if Sender = FImages[lvil] then
    begin
      TWSCustomListViewClass(WidgetSetClass).SetImageList(Self, lvil, nil);
      Application.QueueAsyncCall(@SetImageListAsync, Ord(lvil));
    end;
end;

procedure TCustomListView.Loaded;
begin
  // create interface columns if needed
  if HandleAllocated then
    FColumns.WSCreateColumns;
  inherited Loaded;
end;

procedure TCustomListView.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited Notification(AComponent, Operation);
  if Operation = opRemove then begin
    if AComponent = LargeImages then LargeImages := nil;
    if AComponent = SmallImages then SmallImages := nil;
    if AComponent = StateImages then StateImages := nil;
  end;
end;

procedure TCustomListView.SetScrollBars(const AValue: TScrollStyle);
begin
  if (FScrollBars = AValue) then exit;
  FScrollBars := AValue;
  if not HandleAllocated then Exit;
  TWSCustomListViewClass(WidgetSetClass).SetScrollBars(Self, AValue);
  UpdateScrollBars;
end;

procedure TCustomListView.UpdateScrollbars;
begin
  // this needs to be done in the widgetset
  DebugLn('TODO: TCustomListView.UpdateScrollbars');
  exit;

  if not HandleAllocated then exit;
end;

// Multi-selection
procedure TCustomListView.InitMultiSelList(AEnable: Boolean);
begin
  TWSCustomListViewClass(WidgetSetClass).InitMultiSelList(Self, AEnable);
end;

procedure TCustomListView.UpdateMultiSelList(AItem: TListItem; Add: Boolean);
begin
  TWSCustomListViewClass(WidgetSetClass).UpdateMultiSelList(Self, AItem, Add);
end;

function TCustomListView.GetFirstSelected: TListItem;
begin
  Result := TWSCustomListViewClass(WidgetSetClass).GetFirstSelected(Self);
end;