File: qtobject.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 (2028 lines) | stat: -rw-r--r-- 64,104 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
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
{%MainUnit qtint.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.
 *****************************************************************************
}
//---------------------------------------------------------------

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.Create
  Params:  None
  Returns: Nothing

  Constructor for the class.
 ------------------------------------------------------------------------------}
constructor TQtWidgetSet.Create;
{$IFDEF MSWINDOWS}
var
  WStr: WideString;
{$ENDIF}
begin
  FLastWFPMousePos := Point(MaxInt, MaxInt);
  FLastWFPResult := 0;
  inherited Create;
  FIsLibraryInstance := QCoreApplication_instance() <> nil;
  if FIsLibraryInstance then
    App := QApplicationH(QCoreApplication_instance())
  else
  begin
    {$IFDEF HASX11}
    FX11Display := nil;
    {$ENDIF}
    {$IFDEF MSWINDOWS}
    //add directory plugins to the Qt paths if Qt is distributed with application under mswindows.
    WStr := 'plugins';
    QCoreApplication_addLibraryPath(@WStr);
    {$ENDIF}
    // issue #39610
    // QCoreApplication_setAttribute(QtAA_DisableHighDpiScaling, True);
    App := QApplication_Create(@argc, argv);
  end;
  QCoreApplication_setAttribute(QtAA_DontUseNativeDialogs, False);
  QGuiApplication_setHighDpiScaleFactorRoundingPolicy(QtHighDpiScaleFactorRoundingPolicy_Round);
  //QCoreApplication_setAttribute(QtAA_DontCreateNativeWidgetSiblings, True);

  {$IFDEF QtUseNativeEventLoop}
  FMainTimerID := -1;
  {$ENDIF}
  {$J+}
  QtVersionInt(QtVersionMajor, QtVersionMinor, QtVersionMicro);
  {$J-}
  FCachedMenuBarHeight := -1;
  FAppEvenFilterHook := nil;
  {$IFDEF QTUSEFOCUSCHANGEDHOOK}
  FAppFocusChangedHook := nil;
  {$ENDIF}
  FAppEventApplicationStateHook := nil;
  FPenForSetPixel := nil;
  FInGetPixel := False;

  QtGDIObjects := TQtGDIObjects.Create;
  InitStockItems;
  QtWidgetSet := Self;
  ClearCachedColors;
  FDockImage := nil;
  FDragImageLock := False;
  System.InitCriticalSection(CriticalSection);
  SavedHandlesList := TMap.Create(TMapIdType(ituPtrSize), SizeOf(TObject));
  FSocketEventMap := TMap.Create(TMapIdType(its4), SizeOf(Pointer));
  SysTrayIconsList := TFPList.Create;
  StayOnTopList := nil;
  FAppActive := False;
  {$IFDEF HASX11}
  SavedHintHandlesList := TFPList.Create;
  FMinimizedByPager := False;
  FLastMinimizeEvent := 0;
  FWindowManagerName := LowerCase(GetWindowManager);
  // metacity wm forks. marco = mint mate wm, gnome shell = gnome 3 wm
  if (FWindowManagerName = 'marco') or // issue #35782 (FWindowManagerName = 'gnome shell') or
    (UTF8Pos('mutter', FWindowManagerName) > 0) then
    FWindowManagerName := 'metacity';
  if not FIsLibraryInstance then
    FWSFrameRect := Rect(0, 0, 0, 0);
  {$ENDIF}
  {$IFDEF DARWIN}
  // do not swap meta and ctrl keys, issue #20897
  if not FIsLibraryInstance and (QtVersionMajor = 5) and (QtVersionMinor > 1) then
    QCoreApplication_setAttribute(QtAA_MacDontSwapCtrlAndMeta, True);
  {$ENDIF}
  FGlobalActions := TFPList.Create;
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.Destroy
  Params:  None
  Returns: Nothing

  Destructor for the class.
 ------------------------------------------------------------------------------}
destructor TQtWidgetSet.Destroy;
begin
  if FDockImage <> nil then
    QRubberBand_destroy(FDockImage);
  DestroyGlobalCaret;
  Clipboard.Free;
  FreeStockItems;
  FreeSysColorBrushes;
  QtDefaultPrinter.Free;
  QtWidgetSet := nil;
  
  if SavedDCList<>nil then
    SavedDCList.Free;
    
  QtDefaultContext.Free;
  QtScreenContext.Free;

  ClearCachedColors;

  if StayOnTopList <> nil then
  begin
    StayOnTopList.Free;
    StayOnTopList := nil;
  end;

  if SavedHandlesList <> nil then
  begin
    SavedHandlesList.Free;
    SavedHandlesList := nil;
  end;
  {$IFDEF HASX11}
  if SavedHintHandlesList <> nil then
  begin
    SavedHintHandlesList.Free;
    SavedHintHandlesList := nil;
  end;
  {$ENDIF}

  if SysTrayIconsList <> nil then
  begin
    SysTrayIconsList.Free;
    SysTrayIconsList := nil;
  end;

  FSocketEventMap.Free;
  FGlobalActions.Free;

  if FPenForSetPixel <> nil then
  begin
    QPen_destroy(FPenForSetPixel);
    FPenForSetPixel := nil;
  end;

  System.DoneCriticalsection(CriticalSection);

  if Assigned(QtGDIObjects) then
    FreeThenNil(QtGDIObjects);

  inherited Destroy;
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.Destroy
  Params:  None
  Returns: Nothing

  Creates a new timer and sets the callback event.
 ------------------------------------------------------------------------------}
function TQtWidgetSet.CreateTimer(Interval: integer; TimerFunc: TWSTimerProc): TLCLHandle;
var
  QtTimer: TQtTimer;
begin
  QtTimer := TQtTimer.CreateTimer(Interval, TimerFunc, App);
  
  Result := TLCLHandle(QtTimer);
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.Destroy
  Params:  None
  Returns: Nothing

  Destroys a timer.
 ------------------------------------------------------------------------------}
function TQtWidgetSet.DestroyTimer(TimerHandle: TLCLHandle): boolean;
begin
  TQtTimer(TimerHandle).Free;
  
  Result := True;
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.AppInit
  Params:  None
  Returns: Nothing

  Initializes the application
 ------------------------------------------------------------------------------}
procedure TQtWidgetSet.AppInit(var ScreenInfo: TScreenInfo);
var
  ScreenDC: HDC;
begin
  WakeMainThread := @OnWakeMainThread;

  {issue #38319 - since Qt-4.7 there's no way to set RTL over widgets}
  if Application.BidiMode = bdRightToLeft then
    QGuiApplication_setLayoutDirection(QtRightToLeft);

  {
    check whether this hook crashes on linux & darwin and why it is so
    we need this hook to catch release messages
  }
  // install global event filter
  FAppEvenFilterHook := QObject_hook_create(App);
  QObject_hook_hook_events(FAppEvenFilterHook, @EventFilter);

    // install focus change slot
  {$IFDEF QTUSEFOCUSCHANGEDHOOK}
  FAppFocusChangedHook := QApplication_hook_create(App);
  QApplication_hook_hook_focusChanged(FAppFocusChangedHook, @FocusChanged);
  {$ENDIF}

  FAppEventApplicationStateHook := QGuiApplication_hook_Create(App);
  QGuiApplication_hook_hook_applicationStateChanged(FAppEventApplicationStateHook, @AppStateChanged);

  if not FIsLibraryInstance then
  begin
    {$IF DEFINED(HAIKU) OR DEFINED(QTOPIA) OR DEFINED(QT_NO_SESSIONMANAGER)}
    FAppSessionQuit := nil;
    FAppSaveSessionRequest := nil;
    {$ELSE}
    FAppSessionQuit := QGUIApplication_hook_create(App);
    QGUIApplication_hook_hook_commitDataRequest(FAppSessionQuit, @SlotCommitDataRequest);
    FAppSaveSessionRequest := QGUIApplication_hook_create(App);
    QGUIApplication_hook_hook_saveStateRequest(FAppSaveSessionRequest, @SlotSaveDataRequest);
    {$ENDIF}
  end else
  begin
    FAppSessionQuit := nil;
    FAppSaveSessionRequest := nil;
  end;


  ScreenDC := GetDC(0);
  try
    {$IFDEF DARWIN}
    // this code is removed in r57679, and cocoa/carbon are fixed separatelly, so
    // qt/qt5 wasn't good with standard mac ppi 72. Cocoa ws uses CocoaBasePPI const.
    // issue #34625
    ScreenInfo.PixelsPerInchX := 96;
    ScreenInfo.PixelsPerInchY := 96;
	  {$ELSE}
    ScreenInfo.PixelsPerInchX := GetDeviceCaps(ScreenDC, LOGPIXELSX);
    ScreenInfo.PixelsPerInchY := GetDeviceCaps(ScreenDC, LOGPIXELSY);
	  {$ENDIF}
    ScreenInfo.ColorDepth := GetDeviceCaps(ScreenDC, BITSPIXEL);
  finally
    ReleaseDC(0, ScreenDC);
  end;

  QtDefaultPrinter;
  {$IFNDEF MSWINDOWS}
  // initialize clipboard
  ClipBoard;
  {$ENDIF}
  // initialize default app font name
  SetDefaultAppFontName;
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.AppRun
  Params:  None
  Returns: Nothing

  Enter the main message loop
 ------------------------------------------------------------------------------}
procedure TQtWidgetSet.AppRun(const ALoop: TApplicationMainLoop);
{$IFDEF QtUseNativeEventLoop}
var
  ATimer: QTimerH;
{$ENDIF}
begin
  {$IFDEF QtUseNativeEventLoop}
  if Application.Terminated then
  begin
    // application can be terminated in show event of mainform (before AppRun is called - see TApplication.Run. related to #34982)
    if Assigned(ALoop) then
      ALoop;
  end else
  begin
    FMainTimerID := -1;
    ATimer := QTimer_Create(QCoreApplication_instance());
    QTimer_setTimerType(ATimer, QtPreciseTimer);
    {$IFDEF HASX11}
    if (StyleName = 'gtk2') or (StyleName = 'gtk') then
      QTimer_setInterval(ATimer, 1)
    else
      QTimer_setInterval(ATimer, 0);
    {$ELSE}
    QTimer_setInterval(ATimer, {$IFDEF QtCocoa}5{$ELSE}1{$ENDIF});
    {$ENDIF}
    QTimer_start(ATimer);
    FMainTimerID := QTimer_timerId(ATimer);
    QApplication_exec();
  end;
  {$ELSE}
  // use LCL loop
  if Assigned(ALoop) then
    ALoop;
  {$ENDIF}
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.AppWaitMessage
  Params:  None
  Returns: Nothing

  Waits until a message arrives, processes that and returns control out of the function
  
  Utilized on Modal dialogs
 ------------------------------------------------------------------------------}
procedure TQtWidgetSet.AppWaitMessage;
begin
  QCoreApplication_processEvents(QEventLoopWaitForMoreEvents);
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.AppProcessMessages
  Params:  None
  Returns: Nothing

  Processes all messages on the quoue
 ------------------------------------------------------------------------------}
procedure TQtWidgetSet.AppProcessMessages;
begin
  QCoreApplication_processEvents(QEventLoopAllEvents);
end;

{------------------------------------------------------------------------------
  Method: TQtWidgetSet.AppTerminate
  Params:  None
  Returns: Nothing

  Implements Application.Terminate and MainForm.Close.
 ------------------------------------------------------------------------------}
procedure TQtWidgetSet.AppTerminate;
begin
  // free hooks
  if Assigned(FAppEvenFilterHook) then
    QObject_hook_destroy(FAppEvenFilterHook);
  {$IFDEF QTUSEFOCUSCHANGEDHOOK}
  if Assigned(FAppFocusChangedHook) then
    QApplication_hook_destroy(FAppFocusChangedHook);
  FAppFocusChangedHook := nil;
  {$ENDIF}
  if Assigned(FAppEventApplicationStateHook) then
    QGuiApplication_hook_Destroy(FAppEventApplicationStateHook);
  FAppEvenFilterHook := nil;
  FAppEventApplicationStateHook := nil;
  // do not quit application if we are library
  if not FIsLibraryInstance then
  begin
    {$IFNDEF HAIKU}
    if Assigned(FAppSessionQuit) then
    begin
      QGUIApplication_hook_destroy(FAppSessionQuit);
      FAppSessionQuit := nil;
    end;
    if Assigned(FAppSaveSessionRequest) then
    begin
      QGUIApplication_hook_destroy(FAppSaveSessionRequest);
      FAppSaveSessionRequest := nil;
    end;
    {$ENDIF}
    QCoreApplication_quit;
  end;
end;

procedure TQtWidgetSet.AppMinimize;
{$IFDEF HASX11}
var
  i: Integer;
  AForm: TCustomForm;
  States: QtWindowStates;
  AWidget: TQtWidget;
{$ENDIF}
begin
  if (Application.MainForm <> nil) and (Application.MainForm.HandleAllocated) then
  begin
    {$IFDEF HASX11}
    HideAllHints;
    // first minimize all designed forms
    for i := 0 to Screen.CustomFormZOrderCount-1 do
    begin
      AForm := Screen.CustomFormsZOrdered[i];
      if not AForm.HandleAllocated or Assigned(AForm.Parent) then
        continue;
      {$IFDEF DEBUGQTAPPMINIMIZE}
      DebugLn('1.MUST MINIMIZE ',dbgsName(AForm),' design ? ',dbgs(csDesigning in AForm.ComponentState),
       ' HANDLEVISIBLE ',dbgs(TQtWidget(AForm.Handle).getVisible),' FORMVISIBLE=',dbgs(AForm.Visible));
      {$ENDIF}
      AWidget := TQtWidget(AForm.Handle);
      if AWidget.getVisible and
        (csDesigning in AForm.ComponentState) then
      begin
        States := AWidget.getWindowState;
        {$IFDEF DEBUGQTAPPMINIMIZE}
        DebugLn('1.  **** TRYING TO MINIMIZE ',dbgsName(AForm),' already minimized ? ',dbgs(AWidget.isMinimized));
        {$ENDIF}
        if not AWidget.isMinimized then
          AWidget.setWindowState(States or QtWindowMinimized);
      end;
    end;
    for i := 0 to Screen.CustomFormZOrderCount-1 do
    begin
      AForm := Screen.CustomFormsZOrdered[i];
      if not AForm.HandleAllocated or Assigned(AForm.Parent) or
        (csDesigning in AForm.ComponentState) then
        continue;
      {$IFDEF DEBUGQTAPPMINIMIZE}
      DebugLn('2. MUST MINIMIZE ',dbgsName(AForm),' design ? ',dbgs(csDesigning in AForm.ComponentState),
       ' HANDLEVISIBLE ',dbgs(TQtWidget(AForm.Handle).getVisible),' FORMVISIBLE=',dbgs(AForm.Visible));
      {$ENDIF}
      AWidget := TQtWidget(AForm.Handle);
      if AWidget.getVisible and
         not (AForm.FormStyle in [fsMDIChild, fsSplash]) and
         not (AForm.BorderStyle = bsNone) then
      begin
        States := AWidget.getWindowState;
        {$IFDEF DEBUGQTAPPMINIMIZE}
        DebugLn('2.  **** TRYING TO MINIMIZE ',dbgsName(AForm),' already minimized ? ',dbgs(AWidget.isMinimized));
        {$ENDIF}
        if not AWidget.isMinimized then
          AWidget.setWindowState(States or QtWindowMinimized);
      end;
    end;
    {$ELSE}
    TQtMainWindow(Application.MainForm.Handle).ShowMinimized;
    {$ENDIF}
  end;
end;

procedure TQtWidgetSet.AppRestore;
{$IFDEF HASX11}
var
  i: Integer;
  AForm: TCustomForm;
  States: QtWindowStates;
  AWidget: TQtWidget;
{$ENDIF}
begin
  if (Application.MainForm <> nil) and (Application.MainForm.HandleAllocated) then
  begin
    {$IFDEF HASX11}
    if Screen = nil then exit;
    for i := Screen.CustomFormZOrderCount-1 downto 0 do
    begin
      AForm := Screen.CustomFormsZOrdered[i];
      if not AForm.HandleAllocated or Assigned(AForm.Parent) then
        continue;
      {$IFDEF DEBUGQTAPPMINIMIZE}
      DebugLn('MUST RESTORE ',dbgsName(AForm),' design ? ',dbgs(csDesigning in AForm.ComponentState),
       ' HANDLEVISIBLE ',dbgs(TQtWidget(AForm.Handle).getVisible),' FORMVISIBLE=',dbgs(AForm.Visible));
      {$ENDIF}
      AWidget := TQtWidget(AForm.Handle);
      if AWidget.getVisible and
        ((not (AForm.FormStyle in [fsMDIChild, fsSplash]) and
         not (AForm.BorderStyle = bsNone)) or
        (csDesigning in AForm.ComponentState)) then
      begin
        States := AWidget.getWindowState;
        {$IFDEF DEBUGQTAPPMINIMIZE}
        DebugLn('TRYING TO RESTORE ',dbgsName(AForm),' already minimized ? ',dbgs(AWidget.isMinimized));
        {$ENDIF}
        if AWidget.isMinimized then
          AWidget.setWindowState(States and not QtWindowMinimized);
      end;
    end;
    RestoreAllHints;
    {$ELSE}
    TQtMainWindow(Application.MainForm.Handle).ShowNormal;
    {$ENDIF}
  end;
end;

procedure TQtWidgetSet.AppBringToFront;
begin
  if (Application.MainForm <> nil) and
    (Application.MainForm.HandleAllocated) and
    (TQtMainWindow(Application.MainForm.Handle).getVisible) then
    TQtMainWindow(Application.MainForm.Handle).BringToFront;
end;

procedure TQtWidgetSet.AppSetIcon(const Small, Big: HICON);
var
  DoDestroyIcon: Boolean;
  Icon: QIconH;
begin
  DoDestroyIcon := Big = 0;
  if DoDestroyIcon then
    Icon := QIcon_create()
  else
    Icon := TQtIcon(Big).Handle;
  QApplication_setWindowIcon(Icon);
  if DoDestroyIcon then
    QIcon_destroy(Icon);
end;


procedure TQtWidgetSet.AppSetTitle(const ATitle: string);
begin
  //Not used. See issue #41417
end;

function TQtWidgetSet.AppRemoveStayOnTopFlags(const ASystemTopAlso: Boolean = False): Boolean;
begin
  Result := True;
  QtRemoveStayOnTop(ASystemTopAlso);
end;

function TQtWidgetSet.AppRestoreStayOnTopFlags(const ASystemTopAlso: Boolean = False): Boolean;
begin
  Result := True;
  QtRestoreStayOnTop(ASystemTopAlso);
end;

{$IFDEF HASX11}
function TQtWidgetSet.CreateDummyWidgetFrame(const ALeft, ATop, AWidth,
  AHeight: integer): boolean;
var
  ADummy: TDummyWidget;
  WM: String;
begin
  Result := False;
  WM := GetWindowManager;
  if (WM = '') or (WM = 'wayland') then
    exit;
  ADummy := TDummyWidget.Create;
  ADummy.ShowDummyWidget(ALeft, ATop, AWidth, AHeight);
  FWSFrameRect := ADummy.GetWidgetFrame;
  ADummy.Free;
  Result := not IsRectEmpty(FWSFrameRect);
end;

function TQtWidgetSet.GetDummyWidgetFrame: TRect;
begin
  Result := FWSFrameRect;
end;

function TQtWidgetSet.x11Display: PDisplay;
begin
  if FX11Display = nil then
    FX11Display := PDisplay(QGuiApplication_x11Display(QGuiApplicationH(QCoreApplication_instance())));
  Result := FX11Display;
end;
{$ENDIF}

procedure TQtWidgetSet.SetOverrideCursor(const AValue: TObject);
begin
  if AValue = nil then
    QGUIApplication_restoreOverrideCursor()
  else
  if FOverrideCursor = nil then
    QGUIApplication_setOverrideCursor(TQtCursor(AValue).Handle)
  else
    QGUIApplication_changeOverrideCursor(TQtCursor(AValue).Handle);
  FOverrideCursor := AValue;
end;

type
  TQtTempFormStyleSet = Set of TFormStyle;
const
  TQtTopForms: Array[Boolean] of TQtTempFormStyleSet = (fsAllNonSystemStayOnTop,
    fsAllStayOnTop);

procedure TQtWidgetSet.QtRemoveStayOnTop(const ASystemTopAlso: Boolean = False);
var
  i: Integer;
  AForm: TCustomForm;
  W: TQtMainWindow;
  Flags: QtWindowFlags;
begin
  if StayOnTopList = nil then
    StayOnTopList := TMap.Create(TMapIdType(ituPtrSize), SizeOf(TObject));
  for i := 0 to Screen.CustomFormZOrderCount - 1 do
  begin
    AForm := Screen.CustomFormsZOrdered[i];
    if AForm.HandleAllocated then
    begin
      W := TQtMainWindow(AForm.Handle);
      if (AForm.Parent = nil) and
        (AForm.FormStyle in TQtTopForms[ASystemTopAlso]) and W.GetVisible and
         not W.IsMdiChild and not W.IsModal and not w.isMinimized then
      begin
        Flags := W.windowFlags;
        if (Flags and QtWindowStaysOnTopHint) <> 0 then
        begin
          W.BeginUpdate;
          W.setAttribute(QtWA_ShowWithoutActivating, True);
          W.setWindowFlags(Flags and not QtWindowStaysOnTopHint);
          W.Show;
          W.EndUpdate;
          if not StayOnTopList.HasId(W) then
            StayOnTopList.Add(W, W);
        end;
      end;
    end;
  end;
end;

procedure TQtWidgetSet.QtRestoreStayOnTop(const ASystemTopAlso: Boolean = False);
var
  i: Integer;
  AForm: TCustomForm;
  W: TQtMainWindow;
  Flags: QtWindowFlags;
begin
  if StayOnTopList = nil then
    exit;
  for i := Screen.CustomFormZOrderCount - 1 downto 0 do
  begin
    AForm := Screen.CustomFormsZOrdered[i];
    if AForm.HandleAllocated then
    begin
      W := TQtMainWindow(AForm.Handle);
      if (AForm.Parent = nil) and
        (AForm.FormStyle in TQtTopForms[ASystemTopAlso]) and W.GetVisible and
        not W.IsMdiChild and not W.IsModal and not W.isMinimized then
      begin
        if StayOnTopList.HasId(W) then
        begin
          W.BeginUpdate;
          Flags := W.windowFlags;
          W.setWindowFlags(Flags or QtWindowStaysOnTopHint);
          W.Show;
          W.setAttribute(QtWA_ShowWithoutActivating, False);
          W.EndUpdate;
        end;
      end;
    end;
  end;
  StayOnTopList.Free;
  StayOnTopList := nil;
end;

procedure TQtWidgetSet.SetDefaultAppFontName;
var
  AppFont: QFontH;
begin
  FCachedMenuBarHeight := -1;
  AppFont := QFont_create();
  QApplication_font(AppFont);
  QFont_family(AppFont, @FDefaultAppFontName);
  QFont_destroy(AppFont);
end;

function TQtWidgetSet.CreateThemeServices: TThemeServices;
begin
  Result := TQtThemeServices.Create;
end;

function TQtWidgetSet.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; cdecl;
var
  AObject: TQtObject;
  W: TQtWidget;
  LCLEvent: QLCLMessageEventH;
  ASequence: QKeySequenceH;
  AKey: WideString;
  AParent: QWidgetH;
  R: TRect;
  AQtPoint: TQtPoint;
  {$IFNDEF QTUSEFOCUSCHANGEDHOOK}
  OldWidget, NewWidget: TQtWidget;
  Msg: TLMessage;
  FocusedQtWidget: QWidgetH;
  FocusedTQtWidget: TQtWidget;
  {$ENDIF}

  function IsAnyWindowActive: Boolean;
  begin
    Result := (QApplication_activeWindow() <> nil) or
      (QApplication_activeModalWidget() <> nil) or
      (QApplication_activePopupWidget() <> nil);
  end;

  function IsSystemTrayWidget: boolean;
  var
    AName: WideString;
    AWidget: QWidgetH;
    RGeom: TRect;
    AFlags: QtWindowFlags;
    i: Integer;
  begin
    Result := False;
    if QObject_isWidgetType(Sender) then
    begin
      AWidget := QWidgetH(Sender);
      QObject_objectName(Sender, @AName);
      if Copy(AName, 1, 16) = 'qtlclsystrayicon' then
      begin
        for i := 0 to SysTrayIconsList.Count - 1 do
        begin
          RGeom := TQtSystemTrayIcon(SysTrayIconsList.Items[i]).GetGeometry;
          if TQtSystemTrayIcon(SysTrayIconsList.Items[i]).SysTrayWidget = nil then
          begin
            if QApplication_widgetAt(RGeom.Left, RGeom.Top) = AWidget then
              TQtSystemTrayIcon(SysTrayIconsList.Items[i]).AttachSysTrayWidget(AWidget);
          end;
        end;
        exit(True);
      end;
      if QWidget_isWindow(AWidget) and (QWidget_parentWidget(AWidget) = nil) then
      begin
        AFlags := QWidget_windowFlags(AWidget);

        if QWidget_testAttribute(AWidget, QtWA_AlwaysShowToolTips) and
          QWidget_testAttribute(AWidget, QtWA_PaintOnScreen) and
          QWidget_testAttribute(AWidget, QtWA_NoSystemBackground) and
          not QWidget_testAttribute(AWidget, QtWA_QuitOnClose) and
          {$IFDEF HASX11}
          (AFlags and QtX11BypassWindowManagerHint = QtX11BypassWindowManagerHint) and
          {$ENDIF}
          (AFlags and QtFramelessWindowHint = QtFramelessWindowHint) then
        begin
          if HwndFromWidgetH(AWidget) = 0 then
          begin
            // we must find it by geometry, but it's innacurate since
            // qt systrayicon widget returns -1,-1 for left & top, so we
            // use QApplication_widgetAt().
            // Another problem is that QSystemTrayIcon geometry is updated
            // too late, much after QEventShow/QEventShowToParent
            // so no way to catch private QWidget until we enter
            // it by mouse.
            // For that reason we use LCLQt_RegisterSystemTrayIcon event.

            {$IFDEF DEBUGSYSTRAYICON}
            DebugLn('====****** Inherits private ? ',dbgs(QObject_inherits(AWidget, 'QSystemTrayIconSys')),
            ' mouseTracking=',dbgs(QWidget_hasMouseTracking(AWidget)));
            {$ENDIF}
            for i := 0 to SysTrayIconsList.Count - 1 do
            begin
              RGeom := TQtSystemTrayIcon(SysTrayIconsList.Items[i]).GetGeometry;
              if (QApplication_widgetAt(RGeom.Left, RGeom.Top) = AWidget) then
              begin
                AName := UTF8ToUTF16('qtlclsystrayicon_' + dbgHex(PtrUInt(AWidget)));
                QObject_setObjectName(Sender, @AName);
                TQtSystemTrayIcon(SysTrayIconsList.Items[i]).AttachSysTrayWidget(AWidget);
                {$IFDEF DEBUGSYSTRAYICON}
                DebugLn('Attached systemtrayicon[',dbgs(I),'] with geometry ',dbgs(RGeom),' dbg=',
                  dbgsName(TQtSystemTrayIcon(SysTrayIconsList.Items[i]).FTrayIcon),
                  ' position=',dbgs(TQtSystemTrayIcon(SysTrayIconsList.Items[i]).GetPosition));
                {$ENDIF}
                TQtSystemTrayIcon(SysTrayIconsList.Items[i]).UpdateSystemTrayWidget;
                Result := True;
                break;
              end;
            end;
          end;
        end;
      end;
    end;
  end;

begin
  Result := False;

  // find QSystemTrayIcon
  if ((QEvent_type(Event) = LCLQt_RegisterSystemTrayIcon) or
     (QEvent_type(Event) = QEventPaint) or
    (QEvent_type(Event) = QEventEnter)) and
    Assigned(SysTrayIconsList) and (SysTrayIconsList.Count > 0) and
    QObject_isWidgetType(Sender) and (QObject_parent(Sender) = nil) and
    QWidget_isWindow(QWidgetH(Sender)) and QWidget_isVisible(QWidgetH(Sender)) and
    (QWidget_focusPolicy(QWidgetH(Sender)) = QtNoFocus) then
  begin
    AParent := QWidgetH(Sender);
    QWidget_geometry(AParent, @R);
    if (R.Left = -1) and (R.Top = -1) and (R.Right > 0) and (R.Bottom > 0) then
    begin
      AQtPoint.x := 0;
      AQtPoint.y := 0;
      QWidget_mapToGlobal(AParent, @AQtPoint, @AQtPoint);
      {$IFDEF DEBUGSYSTRAYICON}
      DebugLn('EVENT: ',dbgs(QEvent_type(Event)),' Sender 0x',dbgHex(PtrUInt(Sender)),' geometry ',dbgs(R),' QtPt.X=',dbgs(AQtPoint.x),' QtPt.Y=',dbgs(AQtPoint.y));
      {$ENDIF}
      if (QEvent_type(Event) = LCLQt_RegisterSystemTrayIcon) then
      begin
        if IsSystemTrayWidget then
        begin
          Result := True;
          {$IFDEF DEBUGSYSTRAYICON}
          DebugLn('Found SystemTrayIcon via event ',dbgs(QEvent_type(Event)),' SYSTRAYICON 0x',dbgHex(PtrUInt(Sender)));
          {$ENDIF}
          exit;
        end;
      end else
      if ((QEvent_type(Event) = QEventPaint) and (AQtPoint.x > 0) and (AQtPoint.y > 0)) or
        (QEvent_type(Event) = QEventEnter) then
      begin
        LCLEvent := QLCLMessageEvent_create(LCLQt_RegisterSystemTrayIcon, 0, 0, 0, 0);
        QCoreApplication_postEvent(AParent, LCLEvent);
      end;
    end;
  end;

  case QEvent_type(Event) of
    {$IFDEF QtUseNativeEventLoop}
    QEventTimer:
    begin
      if QTimerEvent_timerId(QTimerEventH(Event)) = FMainTimerID then
      begin
        if Assigned(Application) and not Application.Terminated then
          Application.Idle(True);
      end;
    end;
    {$ENDIF}
    QEventShortcutOverride: // issue #22827
    begin
      QKeyEvent_text(QKeyEventH(Event), @AKey);
      if (QKeyEvent_modifiers(QKeyEventH(Event)) = QtAltModifier) and
       (AKey <> '') then
      begin
        ASequence := QKeySequence_create(QKeyEvent_modifiers(QKeyEventH(Event))
          or QKeyEvent_Key(QKeyEventH(Event)));
        try
          AParent := QWidget_parentWidget(QWidgetH(Sender));
          if AParent <> nil then
            Result := QGUIApplication_notify(App, AParent, Event);
        finally
          QKeySequence_destroy(ASequence);
        end;
      end;
    end;

    QEventApplicationFontChange: SetDefaultAppFontName;
    QEventStyleChange:
      begin
        if (Sender = QApplication_activeWindow()) or
          (Assigned(Application.MainForm) and Application.MainForm.HandleAllocated and
          (Sender = TQtWidget(Application.MainForm.Handle).Widget)) or
         (Sender = QCoreApplication_instance()) then
        begin
          if QEvent_type(Event) = QEventStyleChange then
            FCachedMenuBarHeight := -1;
          ThemeServices.IntfDoOnThemeChange;
        end;
      end;
    QEventApplicationPaletteChange:
      begin
        if Sender = App then
        begin
          ClearCachedColors;
          FreeSysColorBrushes(True);
        end;
      end;
    {$IFNDEF QTUSEFOCUSCHANGEDHOOK}
    QEventFocusIn:
    begin
      if not QObject_isWidgetType(Sender) then
        exit;
      FocusedQtWidget := QApplication_focusWidget();
      // writeln('FocusedWidget ? ',Assigned(FocusedQtWidget),' Sender ? ',QObject_isWidgetType(Sender));
      if Assigned(FocusedQtWidget) and (QWidgetH(Sender) <> FocusedQtWidget) then
      begin
        OldWidget := TQtWidget(HwndFromWidgetH(FocusedQtWidget));
        if OldWidget <> nil then
        begin
          NewWidget := TQtWidget(HwndFromWidgetH(QWidgetH(Sender)));
          Msg := Default(TLMessage);
          Msg.msg := LM_KILLFOCUS;
          Msg.wParam := PtrInt(NewWidget);
          OldWidget.DeliverMessage(Msg);
          {$IFDEF DebugQtFocus}
          writeln('OldWidget(1) deliver focus out =',DbgSName(OldWidget));
          {$ENDIF}
        end;
      end;
      NewWidget := TQtWidget(HwndFromWidgetH(QWidgetH(Sender)));
      // writeln('NewWidget=',DbgSName(NewWidget),' Ptr=',PtrUInt(NewWidget));
      Msg := Default(TLMessage);
      Msg.msg := LM_SETFOCUS;
      if Assigned(FocusedQtWidget) and (FocusedQtWidget <> QWidgetH(Sender)) then
        OldWidget := TQtWidget(HWndFromWidgetH(FocusedQtWidget))
      else
        OldWidget := nil;
      // writeln('OldWidget=',DbgSName(OldWidget),' Ptr=',PtrUInt(OldWidget));
      Msg.WParam := PtrInt(OldWidget);
      if Assigned(NewWidget) then
      begin
        {$IFDEF DebugQtFocus}
        writeln('Deliver focus IN for ',dbgsName(NewWidget));
        {$ENDIF}
        NewWidget.DeliverMessage(Msg);
      end;
    end;

    QEventFocusOut:
    begin
      if not QObject_isWidgetType(Sender) then
        exit;
      FocusedQtWidget := QWidgetH(Sender);
      OldWidget := TQtWidget(HwndFromWidgetH(FocusedQtWidget));
      if Assigned(OldWidget) then
      begin
        Msg := Default(TLMessage);
        Msg.msg := LM_KILLFOCUS;
        Msg.wParam := 0; // PtrInt(NewWidget);
        OldWidget.DeliverMessage(Msg);
        {$IFDEF DebugQtFocus}
        writeln('DELIVER focus OUT for ',dbgsName(OldWidget));
        {$ENDIF}
      end;
    end;
    {$ENDIF}
    QEventShow,
    QEventHide:
      begin
        // invalidate widgetAt cache.
        if QObject_isWidgetType(Sender) and IsValidWidgetAtCachePointer then
          InvalidateWidgetAtCache;
      end;
    LCLQt_Destroy:
      begin
        AObject := TQtObject({%H-}Pointer(QLCLMessageEvent_getWParam(QLCLMessageEventH(Event))));
        //WriteLn('Catched free for: ', PtrUInt(AObject), ' : ', AObject.ClassName);
        AObject.Free;
        Result := True;
        QEvent_Accept(Event);
      end;
    LCLQt_CheckSynchronize:
      begin
        // a thread is waiting -> synchronize
        CheckSynchronize;
      end;
  end;
end;

{$IFDEF QTUSEFOCUSCHANGEDHOOK}
procedure TQtWidgetSet.FocusChanged(aold: QWidgetH; anew: QWidgetH); cdecl;
var
  OldWidget, NewWidget: TQtWidget;
  Msg: TLMessage;
  FocusedQtWidget: QWidgetH;
  FocusedTQtWidget: TQtWidget;

  {qt is tricky about focus, we don't want to inform LCL when qt internally
  kills focus on an inactive form. eg. TTreeView->Editor enabled}
  function CheckIfActiveForm(AWidget: TQtWidget): Boolean;
  var
    AForm: TCustomForm;
    AMainWin: TQtMainWindow;
    QtEdit: IQtEdit;
  begin
    Result := True;
    if Assigned(AWidget) and Assigned(AWidget.LCLObject) then
    begin
      AMainWin := nil;
      if (csDesigning in AWidget.LCLObject.ComponentState) then
        exit;
      if TQtWidget(AWidget.LCLObject.Handle) is TQtMainWindow then
        AMainWin := TQtMainWindow(AWidget);

      if AMainWin = nil then
      begin
        AForm := GetParentForm(AWidget.LCLObject);
        if Assigned(AForm) and (AForm.HandleAllocated) then
          AMainWin := TQtMainWindow(AForm.Handle);
      end;
      Result := AMainWin <> nil;
      if not Result then
      begin
        {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
        WriteLn('TQtWidgetSet.FocusChanged: CheckIfActiveForm *** NO FORM ?!? ***');
        {$ENDIF}
        exit;
      end;

      if AMainWin.IsMdiChild then
      begin
        Result :=
          QMdiArea_activeSubWindow(QMdiSubWindow_mdiArea(QMdiSubWindowH(AMainWin.Widget))) =
            QMdiSubWindowH(AMainWin.Widget);
      end else
      begin
        Result := True; // issue #31440 QWidget_isActiveWindow(AMainWin.Widget);
      end;
      if (AMainWin <> AWidget) and not Supports(AWidget, IQtEdit, QtEdit) then
        Result := True;
    end;
  end;

  {checks when qtmdi is doing weird thing (trying to loop itself)}
  function MDIFocusFixNeeded: Boolean;
  var
    OldWin, NewWin: TCustomForm;
    // H: HWND;
  begin
    Result := False;

    if Assigned(OldWidget.LCLObject) then
      OldWin := GetParentForm(OldWidget.LCLObject)
    else
      OldWin := nil;

    if (NewWidget <> nil) and Assigned(NewWidget.LCLObject) then
      NewWin := GetParentForm(NewWidget.LCLObject)
    else
      NewWin := nil;

    Result := (OldWin <> nil) and OldWin.HandleAllocated and
      ((OldWin = NewWin) or (NewWin = nil));

    if not Result then
      exit;

    // that's real window of our => form
    Result := TQtMainWindow(OldWin.Handle).MDIChildArea <> nil;
    // Result := Result and ((NewWin = nil) or (TQtMainWindow(NewWin.Handle).MDIChildArea <> nil));
    if Result then
      Result := (OldWin = OldWidget.LCLObject) or
        ((NewWin = nil) or (NewWin = NewWidget.LCLObject));
  end;

  procedure LostFocus;
  begin
    FillChar(Msg, SizeOf(Msg), 0);
    if IsValidHandle(HWND(OldWidget)) then
    begin
      {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
      WriteLn('TQtWidgetSet.FocusChanged: KILL ', dbgsName(OldWidget.LCLObject),' W.Visible ',OldWidget.getVisible,
      ' destroying ? ',csDestroying in OldWidget.LCLObject.ComponentState,
      ' handle ?!? ',OldWidget.LCLObject.HandleAllocated);
      {$ENDIF}
      Msg.msg := LM_KILLFOCUS;
      Msg.wParam := PtrInt(NewWidget);
      if ((OldWidget is TQtMainWindow) and TQtMainWindow(OldWidget).IsMdiChild and
        Assigned(TQtMainWindow(OldWidget).LCLObject) and
        not (csDesigning in TQtMainWindow(OldWidget).LCLObject.ComponentState))
        or MDIFocusFixNeeded then
      begin
        // DO NOT TRIGGER ANYTHING, THIS IS SPURIOUS EVENT FROM MDIAREA
        //issue #29528
        if TQtMainWindow(OldWidget).IsMdiChild and (TQtMainWindow(OldWidget).LCLObject.ControlCount = 0) then
        begin
          {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
          Writeln('TQtWidgetSet.FocusChanged: *** SEND KILL FOCUS FOR MDICHILD WITH 0 CONTROLS ***');
          {$ENDIF}
          OldWidget.DeliverMessage(Msg);
        end else
        begin
          {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
          Writeln('TQtWidgetSet.FocusChanged: *** DO NOT KILL FOCUS ***');
          {$ENDIF}
        end;
      end else
        if CheckIfActiveForm(OldWidget) then
          OldWidget.DeliverMessage(Msg)
        {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
        else
          Writeln('TQtWidgetSet.FocusChanged: ***** Cannot kill focus of ',dbgsName(OldWidget.LCLObject))
        {$ENDIF}
        ;
    end;
  end;

begin
  {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
  WriteLn('> ** TQtWidgetSet.FocusChanged: old: ', dbgHex(PtrUInt(aold)), ' new: ', dbgHex(PtrUInt(anew)));
  {$ENDIF}
  if (AOld <> nil) and not QWidget_isVisible(AOld) then
    OldWidget := nil
  else
    OldWidget := GetFirstQtObjectFromWidgetH(aold);

  if (ANew <> nil) then
    NewWidget := GetFirstQtObjectFromWidgetH(anew)
  else
    NewWidget := nil;

  if OldWidget = NewWidget then
  begin
    {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
    WriteLn('TQtWidgetSet.FocusChanged: OldWidget = NewWidget ... exiting ...');
    {$ENDIF}
    Exit;
  end;

  {Applies to all TQtWidgets which have "subwidgets" created
   by CreateFrom() eg. comboBox.}
  if (OldWidget <> nil) and
     (NewWidget <> nil) and
     (OldWidget.LCLObject = NewWidget.LCLObject) then
  begin
    {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
    WriteLn('TQtWidgetSet.FocusChanged: exiting ... '+
    'OldWidget.LCLObject=NewWidget.LCLObject OBJ=',dbgsName(OldWidget.LCLObject));
    {$ENDIF}
    exit;
  end;

  if IsValidHandle(HWND(NewWidget)) and (NewWidget.getOwner <> nil) then
    NewWidget := NewWidget.getOwner;
  if IsValidHandle(HWND(OldWidget)) and (OldWidget.getOwner <> nil) then
    OldWidget := OldWidget.getOwner;

  Msg.Msg := 0; // shutup compiler

  // issue #26106
  LostFocus;

  FillChar(Msg, SizeOf(Msg), 0);

  if IsValidHandle(HWND(NewWidget)) then
  begin
    {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
    WriteLn('TQtWidgetSet.FocusChanged: SET ', dbgsName(NewWidget.LCLObject));
    {$ENDIF}
    Msg.msg := LM_SETFOCUS;
    Msg.wParam := PtrInt(OldWidget);
    if (NewWidget is TQtMainWindow) and (TQtMainWindow(NewWidget).IsMdiChild) and
      Assigned(TQtMainWindow(NewWidget).LCLObject) and
      not (csDesigning in TQtMainWindow(NewWidget).LCLObject.ComponentState) then
    begin
      // DO NOT TRIGGER ANYTHING, THIS IS SPURIOUS EVENT FROM MDIAREA
      FocusedQtWidget := QWidget_focusWidget(NewWidget.Widget);
      {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
      Writeln('TQtWidgetSet.FocusChanged: *** DO NOT SET FOCUS ***',dbgHex(PtrUInt(FocusedQtWidget)));
      {$ENDIF}
      if FocusedQtWidget <> nil then
      begin
        FocusedTQtWidget := TQtWidget(HwndFromWidgetH(FocusedQtWidget));
        if FocusedTQtWidget <> nil then
        begin
          if (FocusedTQtWidget.getOwner <> nil) then
            FocusedTQtWidget := FocusedTQtWidget.getOwner;
          if FocusedTQtWidget = NewWidget then
          begin
            {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
            writeln('TQtWidgetSet.FocusChanged: WE CANNOT FOCUS (segfault) ',dbgsName(FocusedTQtWidget.LCLObject),
            ' Active ? ',TCustomForm(NewWidget.LCLObject).Active);
            {$ENDIF}
            if Assigned(TCustomForm(NewWidget.LCLObject).ActiveControl) then
            begin
              {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
              writeln('TQtWidgetSet.FocusChanged: THIS ONE SHOULD BE FOCUSED (1) : ',dbgsName(TCustomForm(NewWidget.LCLObject).ActiveControl));
              {$ENDIF}
              if TCustomForm(NewWidget.LCLObject).ActiveControl.HandleAllocated then
              begin
                // setFocus(TCustomForm(NewWidget.LCLObject).ActiveControl.Handle);
                FocusedTQtWidget := TQtWidget(TCustomForm(NewWidget.LCLObject).ActiveControl.Handle);
                if FocusedTQtWidget <> nil then
                begin
                  if (FocusedTQtWidget.getOwner <> nil) then
                    FocusedTQtWidget := FocusedTQtWidget.getOwner;
                  // first check if we are active subwin, if not then we'll trigger qt do
                  // do correct thing
                  if TQtMainWindow(NewWidget).MDIChildArea.ActiveSubWindow <> NewWidget.Widget then
                    TQtMainWindow(NewWidget).MDIChildArea.ActivateSubWindow(QMDISubWindowH(NewWidget.Widget))
                  else
                  begin
                    // if we are already active then just inform lcl
                    Msg.msg := LM_SETFOCUS;
                    if OldWidget = FocusedTQtWidget then
                      OldWidget := nil;
                    Msg.wParam := PtrInt(OldWidget);
                    FocusedTQtWidget.DeliverMessage(Msg);
                  end;
                end;
              end else
                {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
                writeln('TQtWidgetSet.FocusChanged: BUT NO HANDLE ... CRAP: ',dbgsName(TCustomForm(NewWidget.LCLObject).ActiveControl))
                {$ENDIF}
                ;

            end else
            begin
              // issue #29528
              if TQtMainWindow(NewWidget).LCLObject.ControlCount = 0 then
              begin
                {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
                writeln('TQtWidgetSet.FocusChanged: setting focus to mdiChild with 0 controls .....');
                {$ENDIF}
                Msg.msg := LM_SETFOCUS;
                if OldWidget = NewWidget then
                  OldWidget := nil;
                Msg.wParam := PtrInt(OldWidget);
                NewWidget.DeliverMessage(Msg);
              end else
              begin
                // if this happens then qt's mdi focus is real crap
                {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
                writeln('TQtWidgetSet.FocusChanged: WE ARE COMPLETELY OUT OF MIND WHAT TO DO (1) .....');
                {$ENDIF}
              end;
            end;

          end else
          begin
            // should never happen
            {$IF DEFINED(VerboseFocus) OR DEFINED(DebugQtFocus)}
            if Assigned(TCustomForm(NewWidget.LCLObject).ActiveControl) then
              writeln('TQtWidgetSet.FocusChanged: THIS ONE SHOULD BE FOCUSED (2) : ',dbgsName(TCustomForm(NewWidget.LCLObject).ActiveControl))
            else
              writeln('TQtWidgetSet.FocusChanged: WE ARE COMPLETELY OUT OF MIND WHAT TO DO (2) .....');
            {$ENDIF}
          end;

        end;
      end;

    end else
      NewWidget.DeliverMessage(Msg);
  end;
end;
{$ENDIF}

procedure TQtWidgetSet.AppStateChanged(AState: QtApplicationState); cdecl;
begin
  if AState = QtApplicationActive then
  begin
    if not FAppActive then
    begin
      FAppActive := True;
      Application.IntfAppActivate;
    end;
  end else
  begin
    if FAppActive then
    begin
      FAppActive := False;
      Application.IntfAppDeactivate;
    end;
  end;
end;

procedure TQtWidgetSet.OnWakeMainThread(Sender: TObject);
var
  Event: QEventH;
begin
  Event := QEvent_create(LCLQt_CheckSynchronize);
  QCoreApplication_postEvent(QCoreApplication_instance(), Event, 1 {high priority});
end;

{$ifndef QT_NO_SESSIONMANAGER}
procedure TQtWidgetSet.SlotCommitDataRequest(sessionManager: QSessionManagerH);
  cdecl;
var
  ACancel: Boolean;
begin
  ACancel := False;
  {$IFDEF QTDEBUGSESSIONMANAGER}
  DebugLn('TQtWidgetSet.SlotCommitDataRequest allowInteraction ? ',dbgs(QSessionManager_allowsInteraction(sessionManager)),
    ' errorInteraction ',dbgs(QSessionManager_allowsErrorInteraction(sessionManager)),
    ' phase2 ',dbgs(QSessionManager_isPhase2(sessionManager)));
  {$ENDIF}
  {$IF NOT DEFINED(HAIKU) AND NOT DEFINED(QTOPIA)}
  // if session manager does not allow interaction, then we close app without any intf calls
  if QSessionManager_allowsInteraction(sessionManager) then
  begin
    Application.IntfQueryEndSession(ACancel);
    if ACancel then
    begin
      {$IFDEF QTDEBUGSESSIONMANAGER}
      DebugLn('*** App shutdown cancelled ...***');
      {$ENDIF}
      QSessionManager_cancel(sessionManager);
    end else
    begin
      Application.IntfEndSession;
      QGUIApplication_hook_destroy(FAppSessionQuit);
      FAppSessionQuit := nil;
      {$IFDEF QTDEBUGSESSIONMANAGER}
      DebugLn('*** App shutdown releasing sessionManager ...***');
      {$ENDIF}
      QSessionManager_release(sessionManager);
    end;
  end;
  {$ENDIF}
end;

procedure TQtWidgetSet.SlotSaveDataRequest(sessionManager: QSessionManagerH);
  cdecl;
begin
  {$IFDEF QTDEBUGSESSIONMANAGER}
  DebugLn('TQtWidgetSet.SlotSaveDataRequest ');
  {$ENDIF}
end;
{$endif}

function TQtWidgetSet.LCLPlatform: TLCLPlatform;
begin
  Result:= lpQT6;
end;

function TQtWidgetSet.GetLCLCapability(ACapability: TLCLCapability): PtrUInt;
begin
  case ACapability of
    lcEmulatedMDI,
    lcCanDrawOutsideOnPaint: Result := LCL_CAPABILITY_NO;
    lcDragDockStartOnTitleClick: Result :=
      {$ifdef MSWINDOWS} LCL_CAPABILITY_YES {$else} LCL_CAPABILITY_NO {$endif};
    lcNeedMininimizeAppWithMainForm: Result :=
      {$ifdef HASX11} LCL_CAPABILITY_YES {$else} LCL_CAPABILITY_NO {$endif};
    {when issue #20475 is fixed, then set this to LCL_CAPABILITY_YES}
    lcReceivesLMClearCutCopyPasteReliably: Result := LCL_CAPABILITY_NO;
    lcRadialGradientBrush: Result := LCL_CAPABILITY_YES;
    lcTransparentWindow: Result := LCL_CAPABILITY_YES;
    lcTextHint: Result := LCL_CAPABILITY_YES;
    lcNativeTaskDialog: Result := {$ifdef MSWINDOWS} LCL_CAPABILITY_NO {$else} LCL_CAPABILITY_YES {$endif};
    lcAllowChildControlsInNativeControls: Result := LCL_CAPABILITY_YES;
    lcAccessibilitySupport: Result := {$IFDEF QTACCESSIBILITY}LCL_CAPABILITY_YES{$ELSE}LCL_CAPABILITY_NO{$ENDIF};
  else
    Result := inherited GetLCLCapability(ACapability);
  end;
end;

function TQtWidgetSet.DCGetPixel(CanvasHandle: HDC; X, Y: integer): TGraphicsColor;
var
  Color: QColorH;
  Pixmap: QPixmapH;
  Image: QImageH;
  Widget: QWidgetH;
  Rgb: QRgb;
  AWindow: QWindowH;
begin
  Result := clNone;

  if not IsValidDC(CanvasHandle) then Exit;
  
  if (TQtDeviceContext(CanvasHandle).vImage <> nil) and
    (TQtDeviceContext(CanvasHandle).vImage.Handle <> nil) then
  begin
    Color := QColor_create(QImage_pixel(TQtDeviceContext(CanvasHandle).vImage.Handle, X, Y));
    Result := RGBToColor(QColor_red(Color), QColor_green(Color), QColor_blue(Color));
    QColor_destroy(Color);
  end else
  if (TQtDeviceContext(CanvasHandle).Widget <> nil) and (TQtDeviceContext(CanvasHandle).Parent <> nil) then
  begin
    Widget := TQtDeviceContext(CanvasHandle).Parent;
    if FInGetPixel then
      raise Exception.CreateFmt('TQtWidgetSet.DCGetPixel called recursively, probably from Paint method of QWidget %u.',[PtrUInt(Widget)]);
    FInGetPixel := true;
    try
      Pixmap:= QPixmap_create(1,1);
      Image := QImage_create(1,1, QImageFormat_ARGB32);
      AWindow := QWidget_windowHandle(Widget);
      if AWindow <> nil then
        QScreen_grabWindow(QWindow_screen(AWindow), Pixmap, QWidget_winId(Widget), X, Y, 1, 1)
      else
        QScreen_grabWindow(QGuiApplication_primaryScreen(), Pixmap, QWidget_winId(Widget), X, Y, 1, 1);
      QPixmap_toImage(PixMap, Image);
      Rgb := QImage_Pixel(Image, 0,0);
      Color := QColor_create(Rgb);
      Result := RGBToColor(QColor_red(Color), QColor_green(Color), QColor_blue(Color));
    finally
      QPixmap_destroy(Pixmap);
      QImage_destroy(Image);
      if Color <> nil then
        QColor_destroy(Color);
      FInGetPixel := false;
    end;
  end;
end;

procedure TQtWidgetSet.DCSetPixel(CanvasHandle: HDC; X, Y: integer; AColor: TGraphicsColor);
var
  Color: TQColor;
  AQColor: QColorH;
  ColorRef: TColorRef;
  Pen: QPenH;
  Painter: QPainterH;
  ADevType: Integer;
begin
  if IsValidDC(CanvasHandle) then
  begin
    // WriteLn('TQtWidgetSet.DCSetPixel X=',X,' Y=',Y, ' AColor=',dbghex(AColor),' rgb ? ',dbgHex(ColorToRGB(AColor)));
    Painter := TQtDeviceContext(CanvasHandle).Widget;
    ADevType := QPaintDevice_devType(QPaintEngine_paintDevice(QPainter_paintEngine(Painter)));
    {qt private PaintDeviceFlags 2 = QPixmap 3 = QImage. issue #29256}
    if ((ADevType = 2) or (ADevType = 3)) and
     (TQtDeviceContext(CanvasHandle).vImage <> nil) and
      (TQtDeviceContext(CanvasHandle).vImage.Handle <> nil) then
    begin
      ColorRef := TColorRef(ColorToRGB(AColor));
      QColor_fromRgb(@Color, Red(ColorRef), Green(ColorRef), Blue(ColorRef));
      AQColor := QColor_create(PQColor(@Color));
      if QImage_valid(TQtDeviceContext(CanvasHandle).vImage.Handle, X, Y) then
        QImage_setPixel(TQtDeviceContext(CanvasHandle).vImage.Handle, X, Y, QColor_rgb(AQColor));
      QColor_destroy(AQColor);
    end else
    begin
      {Save current pen.Better save copy of pen instead of
       using painter save/restore, or saved Pen in devicecontext which
       may be null. Issue #27620}
      Pen := QPen_create(QPainter_pen(Painter));
      if FPenForSetPixel = nil then
        FPenForSetPixel := QPen_Create();
      try
        ColorRef := TColorRef(ColorToRGB(AColor));
        QColor_fromRgb(@Color, Red(ColorRef), Green(ColorRef), Blue(ColorRef));
        QPen_setColor(FPenForSetPixel, PQColor(@Color));
        QPainter_setPen(Painter, FPenForSetPixel);
        QPainter_drawPoint(Painter, X,Y);
      finally
        QPainter_setPen(Painter, Pen);
        QPen_destroy(Pen);
      end;
    end;
  end;
end;

procedure TQtWidgetSet.DCRedraw(CanvasHandle: HDC);
begin
  // TODO: implement me
end;

procedure TQtWidgetSet.DCSetAntialiasing(CanvasHandle: HDC; AEnabled: Boolean);
var
  DC: TQtDeviceContext;
begin
  if IsValidDC(CanvasHandle) then
  begin
    if CanvasHandle = 1 then
      DC := QtDefaultContext
    else
      DC := TQtDeviceContext(CanvasHandle);
    DC.setRenderHint(QPainterAntialiasing, AEnabled);
  end;
end;

procedure TQtWidgetSet.SetDesigning(AComponent: TComponent);
begin

end;

{------------------------------------------------------------------------------
  Function: TQtWidgetSet.IsValidDC
  Params:   DC     -  handle to a device context (TQtDeviceContext)
  Returns:  True   -  if the DC is valid
 ------------------------------------------------------------------------------}
function TQtWidgetSet.IsValidDC(const DC: HDC): Boolean;
begin
  Result := (DC <> 0);
end;

{------------------------------------------------------------------------------
  Function: TQtWidgetSet.IsValidGDIObject
  Params:   GDIObject  -  handle to a GDI Object (TQtFont, TQtBrush, etc)
  Returns:  True       -  if the DC is valid
  
  Remark: All handles for GDI objects must be pascal objects so we can
 distinguish between them
 ------------------------------------------------------------------------------}
function TQtWidgetSet.IsValidGDIObject(const GDIObject: HGDIOBJ): Boolean;
var
  aObject: TObject;
begin
  Result := False;

  if not QtGDIObjects.IsValidGDIObject(GDIObject) then
    exit;
  
  aObject := TObject(GDIObject);
  try
    if aObject is TObject then
    begin
      Result :=
        (aObject is TQtFont) or
        (aObject is TQtBrush) or
        (aObject is TQtImage) or
        (aObject is TQtPen) or
        (aObject is TQtRegion);
    end;
  except
    // DebugLn(['TQtWidgetSet.IsValidGDIObject: Gdi object ', GDIObject, ' is not an object!']);
    raise Exception.CreateFmt('TQtWidgetSet.IsValidGDIObject: %u is not an object ',[PtrUInt(GDIObject)]);
  end;
end;

procedure TQtWidgetSet.AddHandle(AHandle: TObject);
begin
  System.EnterCriticalsection(CriticalSection);
  if not SavedHandlesList.HasId(AHandle) then
    SavedHandlesList.Add(AHandle, AHandle);
  System.LeaveCriticalsection(CriticalSection);
end;

procedure TQtWidgetSet.RemoveHandle(AHandle: TObject);
begin
  System.EnterCriticalsection(CriticalSection);
  if SavedHandlesList.HasId(AHandle) then
    SavedHandlesList.Delete(AHandle);
  System.LeaveCriticalsection(CriticalSection);
end;

function TQtWidgetSet.IsValidHandle(AHandle: HWND): Boolean;
begin
  if (AHandle = 0) then
    Exit(False);
  System.EnterCriticalsection(CriticalSection);
  Result := SavedHandlesList.HasId(TObject(AHandle));
  System.LeaveCriticalsection(CriticalSection);
end;

procedure TQtWidgetSet.RegisterSysTrayIcon(AHandle: TObject);
begin
  SysTrayIconsList.Add(AHandle);
end;

procedure TQtWidgetSet.UnRegisterSysTrayIcon(AHandle: TObject);
begin
  SysTrayIconsList.Remove(AHandle);
end;

function TQtWidgetSet.IsValidSysTrayIcon(AHandle: HWND): Boolean;
begin
  Result := SysTrayIconsList.IndexOf(TObject(AHandle)) >= 0;
end;

{$IFDEF HASX11}
procedure TQtWidgetSet.AddHintHandle(AHandle: TObject);
begin
  System.EnterCriticalsection(CriticalSection);
  if SavedHintHandlesList.IndexOf(AHandle) < 0 then
    SavedHintHandlesList.Add(AHandle);
  System.LeaveCriticalsection(CriticalSection);
end;

procedure TQtWidgetSet.RemoveHintHandle(AHandle: TObject);
var
  AIndex: Integer;
begin
  System.EnterCriticalsection(CriticalSection);
  AIndex := SavedHintHandlesList.IndexOf(AHandle);
  if AIndex >= 0 then
    SavedHintHandlesList.Delete(AIndex);
  System.LeaveCriticalsection(CriticalSection);
end;

procedure TQtWidgetSet.RemoveAllHintsHandles;
var
  i: Integer;
  AWidget: TQtHintWindow;
begin
  System.EnterCriticalsection(CriticalSection);
  try
    if not Assigned(SavedHintHandlesList) then
      exit;
    for i := SavedHintHandlesList.Count - 1 downto 0 do
    begin
      if IsValidHintHandle(TObject(SavedHintHandlesList.Items[i])) then
      begin
        AWidget := TQtHintWindow(SavedHintHandlesList.Items[i]);
        if Assigned(AWidget.LCLObject) and (AWidget.LCLObject.Parent = nil) and
          (AWidget.LCLObject is THintWindow) then
        begin
          AWidget.BeginUpdate;
          AWidget.LCLObject.Visible := False;
          AWidget.Hide;
          AWidget.EndUpdate;
          AWidget.setParent(nil);
          THintWindow(AWidget.LCLObject).ReleaseHandle;
        end;
      end;
    end;
  finally
    System.LeaveCriticalsection(CriticalSection);
  end;
end;

function TQtWidgetSet.IsValidHintHandle(AHandle: TObject): Boolean;
begin
  if (AHandle = nil) then
    Exit(False);
  System.EnterCriticalsection(CriticalSection);
  Result := SavedHintHandlesList.IndexOf(AHandle) >= 0;
  System.LeaveCriticalsection(CriticalSection);
end;

procedure TQtWidgetSet.HideAllHints;
var
  i: Integer;
  AWidget: TQtHintWindow;
begin
  System.EnterCriticalsection(CriticalSection);
  try
    Application.CancelHint;
    if not Assigned(SavedHintHandlesList) then
      exit;
    for i := SavedHintHandlesList.Count - 1 downto 0 do
    begin
      if IsValidHintHandle(TObject(SavedHintHandlesList.Items[i])) then
      begin
        AWidget := TQtHintWindow(SavedHintHandlesList.Items[i]);
        AWidget.NeedRestoreVisible := AWidget.getVisible and
          Assigned(AWidget.LCLObject) and AWidget.LCLObject.Visible;
        AWidget.Hide;
      end;
    end;
  finally
    System.LeaveCriticalsection(CriticalSection);
  end;
end;

procedure TQtWidgetSet.RestoreAllHints;
var
  i: Integer;
  AWidget: TQtHintWindow;
begin
  System.EnterCriticalsection(CriticalSection);
  try
    if not Assigned(SavedHintHandlesList) then
      exit;
    for i := SavedHintHandlesList.Count - 1 downto 0 do
    begin
      if IsValidHintHandle(TObject(SavedHintHandlesList.Items[i])) then
      begin
        AWidget := TQtHintWindow(SavedHintHandlesList.Items[i]);
        if AWidget.NeedRestoreVisible and Assigned(AWidget.LCLObject) and
          AWIdget.LCLObject.Visible then
        begin
          AWidget.NeedRestoreVisible := False;
          AWidget.Show;
        end;
      end;
    end;
  finally
    System.LeaveCriticalsection(CriticalSection);
  end;
end;

{$ENDIF}

procedure TQtWidgetSet.ClearGlobalActions;
begin
  {$IFDEF QT_DEBUG_GLOBALACTIONS}
  writeln('TQtWidgetSet.ClearGlobalActions');
  {$ENDIF}
  FGlobalActions.Clear;
end;

procedure TQtWidgetSet.AddGlobalAction(AnAction: QActionH);
begin
  {$IFDEF QT_DEBUG_GLOBALACTIONS}
  writeln('TQtWidgetSet.AddGlobalAction() AnAction ',dbgHex(PtrUInt(AnAction)));
  {$ENDIF}
  FGlobalActions.Add(AnAction);
end;

function TQtWidgetSet.ShortcutInGlobalActions(const AMnemonicText: WideString;
  out AGlobalActionIndex: Integer): Boolean;
var
  NewKey: QKeySequenceH;
  NewStr: WideString;
  CurrentKey: QKeySequenceH;
  CurrentStr: WideString;
  Action: QActionH;
  i: Integer;
begin
  {$IFDEF QT_DEBUG_GLOBALACTIONS}
  writeln('TQtWidgetSet.ShortcutInGlobalActions ',AMnemonicText);
  {$ENDIF}
  Result := False;
  AGlobalActionIndex := -1;
  NewKey := QKeySequence_create();
  try
    QKeySequence_fromString(NewKey, @AMnemonicText);
    NewStr := '';
    QKeySequence_toString(NewKey, @NewStr);

    {$IFDEF QT_DEBUG_GLOBALACTIONS}
    writeln('TQtWidgetSet.ShortcutInGlobalActions new seq=',NewStr);
    {$ENDIF}

    for i := 0 to FGlobalActions.Count - 1 do
    begin
      Action := QActionH(FGlobalActions.Items[i]);
      CurrentStr := '';
      QAction_text(Action, @CurrentStr);
      CurrentKey := QKeySequence_create();
      try
        QKeySequence_mnemonic(CurrentKey, @CurrentStr);
        if not QKeySequence_isEmpty(CurrentKey) then
        begin
          QKeySequence_toString(CurrentKey, @CurrentStr);
          {$IFDEF QT_DEBUG_GLOBALACTIONS}
          writeln('TQtWidgetSet.ShortcutInGlobalActions CurrentKey ',
            CurrentStr,' NewKey ',NewStr,' Result ? ',CurrentStr = NewStr);
          {$ENDIF}
          Result := CurrentStr = NewStr;
          AGlobalActionIndex := i;
          if Result then
            break;
        end;
      finally
        QKeySequence_destroy(CurrentKey);
      end;
    end;
  finally
    QKeySequence_destroy(NewKey);
  end;
end;

procedure TQtWidgetSet.TriggerGlobalAction(const ActionIndex: Integer);
var
  Action: QActionH;
  MainWin: TQtMainWindow;
begin
  Action := QActionH(FGlobalActions[ActionIndex]);
  if (Action <> nil) and Assigned(Application.MainForm) and
    (Application.MainForm.HandleAllocated) then
  begin
    MainWin := TQtMainWindow(Application.MainForm.Handle);
    MainWin.Activate;
    if Assigned(MainWin.MenuBar) then
      QMenuBar_setActiveAction(QMenuBarH(MainWin.MenuBar.Widget), Action);
  end;
end;

{Params: HWND
 This function is needed by cache used in TQtWidgetSet.WindowFromPoint().
 Returns: True if we are cached (FLastWFPResult).
}
function TQtWidgetSet.IsWidgetAtCache(AHandle: HWND): Boolean;
begin
  Result := AHandle = FLastWFPResult;
end;

{Params: none
 Invalidates TQtWidgetSet.WindowFromPoint() cache (FLastWFPResult).
 Returns: nothing
}
procedure TQtWidgetSet.InvalidateWidgetAtCache;
begin
  FLastWFPResult := 0;
end;

{Params: none
 Returns: True if last cached FLastWFPResult is valid otherwise False.
}
function TQtWidgetSet.IsValidWidgetAtCachePointer: Boolean;
begin
  if FLastWFPResult = 0 then
    exit(False);
  Result := IsValidHandle(FLastWFPResult);
end;

{Params: none
 Returns last cached FLastWFPMousePos
 Returns: TPoint
}
function TQtWidgetSet.GetWidgetAtCachePoint: TPoint;
begin
  Result := FLastWFPMousePos;
end;

function TQtWidgetSet.DragImageList_BeginDrag(AImage: QImageH;
  AHotSpot: TPoint): Boolean;
var
  ASize: TSize;
  APixmap: QPixmapH;
  AMask: QBitmapH;
  ABrush: QBrushH;
  APalette: QPaletteH;
begin
  if FDragImageList = nil then
  begin
    FDragImageList := QWidget_create(nil,
      QtSubWindow or QtFramelessWindowHint or
      QtWindowStaysOnTopHint {$IFDEF HASX11}or QtX11BypassWindowManagerHint{$ENDIF});

    // do not set focus and do not activate this widget
    QWidget_setFocusPolicy(FDragImageList, QtNoFocus);
    QWidget_setAttribute(FDragImageList, QtWA_ShowWithoutActivating, True);

    QImage_size(AImage, @ASize);
    QWidget_setFixedSize(FDragImageList, @ASize);
    APixmap := QPixmap_create();
    QPixmap_fromImage(APixmap, AImage);
    AMask := QBitmap_create();
    QPixmap_mask(APixmap, AMask);
    QWidget_setMask(FDragImageList, AMask);
    // issue #26464, use QPixmap instead of QImage in QBrush constructor.
    ABrush := QBrush_create(APixmap);
    APalette := QWidget_palette(FDragImageList);
    QPalette_setBrush(APalette, QPaletteWindow, ABrush);
    QBrush_destroy(ABrush);
    QBitmap_destroy(AMask);
    QPixmap_destroy(APixmap);
    
    QWidget_setAutoFillBackground(FDragImageList, True);
    
    FDragHotSpot := AHotSpot;
  end;
  Result := FDragImageList <> nil;
end;

procedure TQtWidgetSet.DragImageList_EndDrag;
begin
  if FDragImageList <> nil then
  begin
    QObject_deleteLater(FDragImageList);
    FDragImageList := nil;
  end;
end;

function TQtWidgetSet.DragImageList_DragMove(X, Y: Integer): Boolean;
begin
  Result := FDragImageList <> nil;
  if Result then
  begin
    QWidget_raise(FDragImageList);
    QWidget_move(FDragImageList, X - FDragHotSpot.X, Y - FDragHotSpot.Y);
  end;
end;

function TQtWidgetSet.DragImageList_SetVisible(NewVisible: Boolean): Boolean;
begin
  Result := FDragImageList <> nil;
  if Result then
    QWidget_setVisible(FDragImageList, NewVisible);
end;

{$IFDEF MSWINDOWS}
function TQtWidgetSet.GetWinKeyState(AKeyState: LongInt): SHORT;
begin
  Result := Windows.GetKeyState(AKeyState);
end;
{$ENDIF}

{------------------------------------------------------------------------------
  Function: CreateDefaultFont
  Params:  none
  Returns: a TQtFont object

  Creates an default font, used for initial values
 ------------------------------------------------------------------------------}
function TQtWidgetSet.CreateDefaultFont: HFONT;
var
  QtFont: TQtFont;
begin
  QtFont := TQtFont.Create(True);
  QtFont.FShared := True;
  QApplication_font(QtFont.FHandle);
  Result := HFONT(QtFont);
end;

function TQtWidgetSet.GetDefaultAppFontName: WideString;
begin
  Result := FDefaultAppFontName;
end;

procedure TQtWidgetSet.DeleteDefaultDC;
begin
  if FStockDefaultDC <> 0 then
  TQtDeviceContext(FStockDefaultDC).Free;
  FStockDefaultDC := 0;
end;

procedure TQtWidgetSet.FreeStockItems;

  procedure DeleteAndNilObject(var h: HGDIOBJ);
  begin
    if h <> 0 then
      TQtResource(h).FShared := False;
    DeleteObject(h);
    h := 0;
  end;

begin
  DeleteAndNilObject(FStockNullBrush);
  DeleteAndNilObject(FStockBlackBrush);
  DeleteAndNilObject(FStockLtGrayBrush);
  DeleteAndNilObject(FStockGrayBrush);
  DeleteAndNilObject(FStockDkGrayBrush);
  DeleteAndNilObject(FStockWhiteBrush);

  DeleteAndNilObject(FStockNullPen);
  DeleteAndNilObject(FStockBlackPen);
  DeleteAndNilObject(FStockWhitePen);

  DeleteAndNilObject(FStockSystemFont);
end;

procedure TQtWidgetSet.FreeSysColorBrushes(const AInvalidateHandlesOnly: Boolean = False);

  procedure DeleteAndNilObject(var h: HGDIOBJ);
  begin
    if h <> 0 then
    begin
      TQtResource(h).FShared := False;
      DeleteObject(h);
      h := 0;
    end;
  end;

  procedure InvalidateHandleOnly(AIndex: Integer; h: HGDIOBJ);
  begin
    if (h <> 0) and (TQtBrush(h).FHandle <> nil) then
    begin
      QBrush_destroy(TQtBrush(h).FHandle);
      TQtBrush(h).FHandle := nil;
      getSysColorBrush(AIndex);
    end;
  end;

var
  i: integer;
begin
  for i := Low(FSysColorBrushes) to High(FSysColorBrushes) do
    if AInvalidateHandlesOnly then
      InvalidateHandleOnly(i, FSysColorBrushes[i])
    else
      DeleteAndNilObject(FSysColorBrushes[i]);
end;

function TQtWidgetSet.GetQtDefaultDC: HDC;
begin
  Result := FStockDefaultDC;
end;

procedure TQtWidgetSet.SetQtDefaultDC(Handle: HDC);
begin
  FStockDefaultDC := Handle;
end;

procedure TQtWidgetSet.InitStockItems;
var
  LogBrush: TLogBrush;
  logPen : TLogPen;
begin
  FillChar(LogBrush{%H-},SizeOf(TLogBrush),0);
  LogBrush.lbStyle := BS_NULL;
  FStockNullBrush := CreateBrushIndirect(LogBrush);
  TQtBrush(FStockNullBrush).FShared := True;
  
  LogBrush.lbStyle := BS_SOLID;
  LogBrush.lbColor := $000000;
  FStockBlackBrush := CreateBrushIndirect(LogBrush);
  TQtBrush(FStockBlackBrush).FShared := True;
  
  LogBrush.lbColor := $C0C0C0;
  FStockLtGrayBrush := CreateBrushIndirect(LogBrush);
  TQtBrush(FStockLtGrayBrush).FShared := True;
  
  LogBrush.lbColor := $808080;
  FStockGrayBrush := CreateBrushIndirect(LogBrush);
  TQtBrush(FStockGrayBrush).FShared := True;
  
  LogBrush.lbColor := $404040;
  FStockDkGrayBrush := CreateBrushIndirect(LogBrush);
  TQtBrush(FStockDkGrayBrush).FShared := True;
  
  LogBrush.lbColor := $FFFFFF;
  FStockWhiteBrush := CreateBrushIndirect(LogBrush);
  TQtBrush(FStockWhiteBrush).FShared := True;

  LogPen.lopnStyle := PS_NULL;
  LogPen.lopnWidth := Point(0, 0); // create cosmetic pens
  LogPen.lopnColor := $FFFFFF;
  FStockNullPen := CreatePenIndirect(LogPen);
  TQtPen(FStockNullPen).FShared := True;
 
  LogPen.lopnStyle := PS_SOLID;
  FStockWhitePen := CreatePenIndirect(LogPen);
  TQtPen(FStockWhitePen).FShared := True;
 
  LogPen.lopnColor := $000000;
  FStockBlackPen := CreatePenIndirect(LogPen);
  TQtPen(FStockBlackPen).FShared := True;

  FStockSystemFont := 0; // styles aren't initialized yet
  
  FStockDefaultDC := 0; // app must be initialized
end;

function TQtWidgetSet.GetMenuHeight: Integer;
var
  AMenuBar: QMenuBarH;
  DummyWindow: QMainWindowH;
  DummyStr: WideString;
  Size: TSize;
begin
  {$IFDEF DARWIN}
  Exit(0);
  {$ENDIF}
  if FCachedMenuBarHeight = -1 then
  begin
    DummyWindow := QMainWindow_create(nil);
    QWidget_setVisible(DummyWindow, False);
    AMenuBar := QMenuBar_create();
    DummyStr := 'DUMMY BAR';
    QMenuBar_addMenu(AMenuBar, @DummyStr);
    QMainWindow_setMenuBar(DummyWindow, AMenuBar);
    QMenuBar_sizeHint(AMenuBar, @Size);
    QMainWindow_destroy(DummyWindow);
    FCachedMenuBarHeight := Size.cy;
  end;
  if (FCachedMenuBarHeight <= 0) then
  begin
    FCachedMenuBarHeight := 22;
  end;
  Result := FCachedMenuBarHeight;
end;

procedure TQtWidgetSet.ClearCachedColors;
var
  i: Integer;
begin
  for i := 0 to High(FCachedColors) do
  begin
    if FCachedColors[i] <> nil then
      FreeMem(FCachedColors[i]);
    FCachedColors[i] := nil;
  end;
end;

function TQtWidgetSet.GetStyleName: String;
var
  WStr: WideString;
begin
  QObject_objectName(QApplication_style, @WStr);
  Result := UTF16ToUTF8(WStr);
end;

//------------------------------------------------------------------------