winit-kora 0.30.13

Cross-platform window creation library. (Playtron's Kora fork of winit)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
//! The state of the window, which is shared with the event-loop.

use std::num::NonZeroU32;
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;

use ahash::HashSet;
use tracing::{info, warn};

use sctk::reexports::client::backend::ObjectId;
use sctk::reexports::client::protocol::wl_seat::WlSeat;
use sctk::reexports::client::protocol::wl_shm::WlShm;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{Connection, Proxy, QueueHandle};
use sctk::reexports::csd_frame::{
    DecorationsFrame, FrameAction, FrameClick, ResizeEdge, WindowState as XdgWindowState,
};
use sctk::globals::GlobalData;
use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1::WpFractionalScaleV1;
use sctk::reexports::protocols::wp::keyboard_shortcuts_inhibit::zv1::client::zwp_keyboard_shortcuts_inhibit_manager_v1::ZwpKeyboardShortcutsInhibitManagerV1;
use sctk::reexports::protocols::wp::keyboard_shortcuts_inhibit::zv1::client::zwp_keyboard_shortcuts_inhibitor_v1::ZwpKeyboardShortcutsInhibitorV1;
use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::ZwpTextInputV3;
use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport;
use sctk::reexports::protocols::xdg::shell::client::xdg_toplevel::ResizeEdge as XdgResizeEdge;

use sctk::compositor::{CompositorState, Region, SurfaceData, SurfaceDataExt};
use sctk::seat::pointer::{PointerDataExt, ThemedPointer};
use sctk::shell::xdg::window::{DecorationMode, Window, WindowConfigure};
use sctk::shell::xdg::XdgSurface;
use sctk::shell::WaylandSurface;
use sctk::shm::slot::SlotPool;
use sctk::shm::Shm;
use sctk::subcompositor::SubcompositorState;
use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur;

use crate::cursor::CustomCursor as RootCustomCursor;
use crate::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Size};
use crate::error::{ExternalError, NotSupportedError};
use crate::platform::wayland::ImeSurroundingText;
use crate::platform_impl::wayland::logical_to_physical_rounded;
use crate::platform_impl::wayland::types::background_effect::{
    BackgroundEffect, BackgroundEffectManager,
};
use crate::platform_impl::wayland::types::cosmic_animated_resize::{
    AnimatedResizeController, CosmicAnimatedResizeManager,
};
use crate::platform_impl::wayland::types::cosmic_backdrop_color::{
    BackdropColorController, CosmicBackdropColorManager,
};
use crate::platform_impl::wayland::types::cosmic_corner_radius::{
    CornerRadiusController, CosmicCornerRadiusManager,
};
use crate::platform_impl::wayland::types::cosmic_special_action::{
    CosmicSpecialActionManager, SpecialActionEvent, SpecialActionReceiver,
};
use crate::platform_impl::wayland::types::cosmic_surface_embed::{
    CosmicSurfaceEmbedManager, EmbeddedSurface,
};
use crate::platform_impl::wayland::types::cursor::{CustomCursor, SelectedCursor};
use crate::platform_impl::wayland::types::kwin_blur::KWinBlurManager;
use crate::platform_impl::wayland::types::wayland_dnd::{SharedDndOfferState, WaylandDndManager};
use crate::platform_impl::wayland::types::xdg_foreign::ImportedToplevel;
use crate::platform_impl::{PlatformCustomCursor, WindowId};
use crate::window::{CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme};

use crate::platform_impl::wayland::seat::{
    PointerConstraintsState, SurroundingChange, SurroundingText, WinitPointerData,
    WinitPointerDataExt, ZwpTextInputV3Ext,
};
use crate::platform_impl::wayland::state::{WindowCompositorUpdate, WinitState};

#[cfg(feature = "sctk-adwaita")]
pub type WinitFrame = sctk_adwaita::AdwaitaFrame<WinitState>;
#[cfg(not(feature = "sctk-adwaita"))]
pub type WinitFrame = sctk::shell::xdg::fallback_frame::FallbackFrame<WinitState>;

// Minimum window inner size.
const MIN_WINDOW_SIZE: LogicalSize<u32> = LogicalSize::new(2, 1);

/// The state of the window which is being updated from the [`WinitState`].
pub struct WindowState {
    /// A change of the `suspended` state the last configure brought, not yet reported.
    occluded: Option<bool>,
    identity: Option<crate::platform_impl::wayland::types::kora_toplevel_identity::IdentityHandle>,
    app_commands:
        Option<crate::platform_impl::wayland::types::kora_app_commands::AppCommandsHandle>,
    /// Seat and serial of the latest key press while focused, for requests that
    /// must name the input that caused them.
    last_key_press: Option<(WlSeat, u32)>,
    /// The connection to Wayland server.
    pub connection: Connection,

    /// The `Shm` to set cursor.
    pub shm: WlShm,

    // A shared pool where to allocate custom cursors.
    custom_cursor_pool: Arc<Mutex<SlotPool>>,

    /// The last received configure.
    pub last_configure: Option<WindowConfigure>,

    /// The pointers observed on the window.
    pub pointers: Vec<Weak<ThemedPointer<WinitPointerData>>>,

    selected_cursor: SelectedCursor,

    /// Whether the cursor is visible.
    pub cursor_visible: bool,

    /// Pointer constraints to lock/confine pointer.
    pub pointer_constraints: Option<Arc<PointerConstraintsState>>,

    /// Queue handle.
    pub queue_handle: QueueHandle<WinitState>,

    /// Theme variant.
    theme: Option<Theme>,

    /// The current window title.
    title: String,

    /// Whether the frame is resizable.
    resizable: bool,

    // NOTE: we can't use simple counter, since it's racy when seat getting destroyed and new
    // is created, since add/removed stuff could be delivered a bit out of order.
    /// Seats that has keyboard focus on that window.
    seat_focus: HashSet<ObjectId>,

    /// The scale factor of the window.
    scale_factor: f64,

    /// Whether the window is transparent.
    transparent: bool,

    /// The state of the compositor to create WlRegions.
    compositor: Arc<CompositorState>,

    /// The current cursor grabbing mode.
    cursor_grab_mode: GrabState,

    /// Whether the IME input is allowed for that window.
    ime_allowed: bool,

    /// The current IME purpose.
    ime_purpose: ImePurpose,

    /// The IME cursor area, resent whenever a text input is enabled.
    ime_cursor_area: Option<(i32, i32, i32, i32)>,

    /// The focused field's surrounding text, as last sent to the text inputs.
    ime_surrounding: Option<SurroundingText>,

    /// Whether an input method commit is what last changed the focused field.
    ime_committed: bool,

    /// The text inputs observed on the window.
    text_inputs: Vec<ZwpTextInputV3>,

    /// Keyboard-shortcuts-inhibit manager + seat captured at creation, and the
    /// active inhibitor while the app is capturing keys.
    keyboard_shortcuts_inhibit_manager: Option<ZwpKeyboardShortcutsInhibitManagerV1>,
    keyboard_shortcuts_inhibit_seat: Option<WlSeat>,
    keyboard_shortcuts_inhibitor: Option<ZwpKeyboardShortcutsInhibitorV1>,

    /// The inner size of the window, as in without client side decorations.
    size: LogicalSize<u32>,

    /// Whether the CSD fail to create, so we don't try to create them on each iteration.
    csd_fails: bool,

    /// Whether we should decorate the frame.
    decorate: bool,

    /// Min size.
    min_inner_size: LogicalSize<u32>,
    max_inner_size: Option<LogicalSize<u32>>,

    /// The size of the window when no states were applied to it. The primary use for it
    /// is to fallback to original window size, before it was maximized, if the compositor
    /// sends `None` for the new size in the configure.
    stateless_size: LogicalSize<u32>,

    /// Initial window size provided by the user. Removed on the first
    /// configure.
    initial_size: Option<Size>,

    /// The state of the frame callback.
    frame_callback_state: FrameCallbackState,

    viewport: Option<WpViewport>,
    fractional_scale: Option<WpFractionalScaleV1>,
    blur: Option<OrgKdeKwinBlur>,
    blur_manager: Option<KWinBlurManager>,
    /// The standard background-effect equivalent of `blur`. Compositors
    /// commonly implement only one of the two protocols, so both are set and
    /// whichever the compositor understands takes effect.
    background_effect: Option<BackgroundEffect>,
    background_effect_manager: Option<BackgroundEffectManager>,

    /// COSMIC animated resize manager.
    animated_resize_manager: Option<CosmicAnimatedResizeManager>,
    /// Active animated resize controller for this window.
    animated_resize_controller: Option<AnimatedResizeController>,

    /// COSMIC corner radius manager.
    corner_radius_manager: Option<CosmicCornerRadiusManager>,
    /// Routes the device's special key here while this surface is focused.
    special_action_manager: Option<CosmicSpecialActionManager>,
    /// Live registration, once the window has asked for one.
    special_action_receiver: Option<SpecialActionReceiver>,
    /// Active corner radius controller for this window.
    corner_radius_controller: Option<CornerRadiusController>,

    /// COSMIC backdrop color manager.
    backdrop_color_manager: Option<CosmicBackdropColorManager>,
    /// Active backdrop color controller for this window.
    backdrop_color_controller: Option<BackdropColorController>,

    /// COSMIC exclusive mode manager.
    /// Active exclusive mode controller for this window.

    /// COSMIC surface embed manager.
    surface_embed_manager: Option<CosmicSurfaceEmbedManager>,
    /// Active embedded surfaces in this window (keyed by a client-provided ID).
    embedded_surfaces: std::collections::HashMap<u64, EmbeddedSurface>,
    /// Next embed ID for tracking.
    next_embed_id: u64,

    /// xdg-foreign import that parents this window to a foreign toplevel.
    /// Kept alive for the window's lifetime; dropping it removes the parent
    /// relationship in the compositor.
    xdg_imported_parent: Option<ImportedToplevel>,

    /// Wayland DnD manager (cloned from WinitState).
    dnd_manager: Option<WaylandDndManager>,
    /// Per-seat data devices for DnD (cloned from WinitState).
    dnd_data_devices: Vec<sctk::reexports::client::protocol::wl_data_device::WlDataDevice>,
    /// Shared DnD offer state (shared with WinitState).
    dnd_shared_offer: std::sync::Arc<std::sync::Mutex<SharedDndOfferState>>,
    /// The icon surface + backing buffer for the current drag.
    /// Both must stay alive while the drag is active.
    dnd_icon:
        Option<(sctk::reexports::client::protocol::wl_surface::WlSurface, sctk::shm::slot::Buffer)>,

    /// Whether the client side decorations have pending move operations.
    ///
    /// The value is the serial of the event triggered moved.
    has_pending_move: Option<u32>,

    /// Seat + serial of the most recent `wl_touch.down` on this surface.
    ///
    /// `xdg_toplevel.move`/`resize` require the serial of an input event with
    /// an active implicit grab. A touchscreen produces no pointer button serial,
    /// so an interactive move/resize started from a touch gesture must use the
    /// touch-down serial instead — otherwise the request is ignored and the
    /// window never moves.
    last_touch_down: Option<(WlSeat, u32)>,

    /// The underlying SCTK window.
    pub window: Window,

    // NOTE: The spec says that destroying parent(`window` in our case), will unmap the
    // subsurfaces. Thus to achieve atomic unmap of the client, drop the decorations
    // frame after the `window` is dropped. To achieve that we rely on rust's struct
    // field drop order guarantees.
    /// The window frame, which is created from the configure request.
    frame: Option<WinitFrame>,
}

impl WindowState {
    /// Create new window state.
    pub fn new(
        connection: Connection,
        queue_handle: &QueueHandle<WinitState>,
        winit_state: &WinitState,
        initial_size: Size,
        window: Window,
        theme: Option<Theme>,
    ) -> Self {
        let compositor = winit_state.compositor_state.clone();
        let pointer_constraints = winit_state.pointer_constraints.clone();
        let viewport = winit_state
            .viewporter_state
            .as_ref()
            .map(|state| state.get_viewport(window.wl_surface(), queue_handle));
        let fractional_scale = winit_state
            .fractional_scaling_manager
            .as_ref()
            .map(|fsm| fsm.fractional_scaling(window.wl_surface(), queue_handle));

        Self {
            identity: winit_state
                .identity_manager
                .as_ref()
                .map(|manager| manager.get_identity(window.xdg_toplevel(), queue_handle)),
            app_commands: winit_state
                .app_commands_manager
                .as_ref()
                .map(|manager| manager.get_commands(window.xdg_toplevel(), queue_handle)),
            last_key_press: None,
            blur: None,
            blur_manager: winit_state.kwin_blur_manager.clone(),
            background_effect: None,
            background_effect_manager: winit_state.background_effect_manager.clone(),
            animated_resize_manager: winit_state.animated_resize_manager.clone(),
            animated_resize_controller: None,
            corner_radius_manager: winit_state.corner_radius_manager.clone(),
            corner_radius_controller: None,
            special_action_manager: winit_state.special_action_manager.clone(),
            special_action_receiver: None,
            backdrop_color_manager: winit_state.backdrop_color_manager.clone(),
            backdrop_color_controller: None,
            surface_embed_manager: winit_state.surface_embed_manager.clone(),
            embedded_surfaces: std::collections::HashMap::new(),
            next_embed_id: 1,
            xdg_imported_parent: None,
            dnd_manager: winit_state.dnd_manager.clone(),
            dnd_data_devices: winit_state.dnd_data_devices.clone(),
            dnd_shared_offer: winit_state.dnd_session.shared_offer.clone(),
            dnd_icon: None,
            compositor,
            connection,
            csd_fails: false,
            cursor_grab_mode: GrabState::new(),
            selected_cursor: Default::default(),
            cursor_visible: true,
            decorate: true,
            fractional_scale,
            frame: None,
            frame_callback_state: FrameCallbackState::None,
            seat_focus: Default::default(),
            has_pending_move: None,
            last_touch_down: None,
            ime_allowed: false,
            ime_purpose: ImePurpose::Normal,
            ime_cursor_area: None,
            ime_surrounding: None,
            ime_committed: false,
            last_configure: None,
            occluded: None,
            max_inner_size: None,
            min_inner_size: MIN_WINDOW_SIZE,
            pointer_constraints,
            pointers: Default::default(),
            queue_handle: queue_handle.clone(),
            resizable: true,
            scale_factor: 1.,
            shm: winit_state.shm.wl_shm().clone(),
            custom_cursor_pool: winit_state.custom_cursor_pool.clone(),
            size: initial_size.to_logical(1.),
            stateless_size: initial_size.to_logical(1.),
            initial_size: Some(initial_size),
            text_inputs: Vec::new(),
            keyboard_shortcuts_inhibit_manager: winit_state
                .keyboard_shortcuts_inhibit_state
                .as_ref()
                .map(|s| s.manager()),
            keyboard_shortcuts_inhibit_seat: winit_state.seat_state.seats().next(),
            keyboard_shortcuts_inhibitor: None,
            theme,
            title: String::default(),
            transparent: false,
            viewport,
            window,
        }
    }

    /// Apply closure on the given pointer.
    fn apply_on_pointer<F: FnMut(&ThemedPointer<WinitPointerData>, &WinitPointerData)>(
        &self,
        mut callback: F,
    ) {
        self.pointers.iter().filter_map(Weak::upgrade).for_each(|pointer| {
            let data = pointer.pointer().winit_data();
            callback(pointer.as_ref(), data);
        })
    }

    /// Get the current state of the frame callback.
    pub fn frame_callback_state(&self) -> FrameCallbackState {
        self.frame_callback_state
    }

    /// The frame callback was received, but not yet sent to the user.
    pub fn frame_callback_received(&mut self) {
        self.frame_callback_state = FrameCallbackState::Received;
    }

    /// Reset the frame callbacks state.
    pub fn frame_callback_reset(&mut self) {
        self.frame_callback_state = FrameCallbackState::None;
    }

    /// Request a frame callback if we don't have one for this window in flight.
    pub fn request_frame_callback(&mut self) {
        let surface = self.window.wl_surface();
        match self.frame_callback_state {
            FrameCallbackState::None | FrameCallbackState::Received => {
                self.frame_callback_state = FrameCallbackState::Requested;
                surface.frame(&self.queue_handle, surface.clone());
            },
            FrameCallbackState::Requested => (),
        }
    }

    pub fn configure(
        &mut self,
        configure: WindowConfigure,
        shm: &Shm,
        subcompositor: &Option<Arc<SubcompositorState>>,
    ) -> bool {
        // NOTE: when using fractional scaling or wl_compositor@v6 the scaling
        // should be delivered before the first configure, thus apply it to
        // properly scale the physical sizes provided by the users.
        if let Some(initial_size) = self.initial_size.take() {
            self.size = initial_size.to_logical(self.scale_factor());
            self.stateless_size = self.size;
        }

        if let Some(subcompositor) = subcompositor.as_ref().filter(|_| {
            configure.decoration_mode == DecorationMode::Client
                && self.frame.is_none()
                && !self.csd_fails
        }) {
            match WinitFrame::new(
                &self.window,
                shm,
                #[cfg(feature = "sctk-adwaita")]
                self.compositor.clone(),
                subcompositor.clone(),
                self.queue_handle.clone(),
                #[cfg(feature = "sctk-adwaita")]
                into_sctk_adwaita_config(self.theme),
            ) {
                Ok(mut frame) => {
                    frame.set_title(&self.title);
                    frame.set_scaling_factor(self.scale_factor);
                    // Hide the frame if we were asked to not decorate.
                    frame.set_hidden(!self.decorate);
                    self.frame = Some(frame);
                },
                Err(err) => {
                    warn!("Failed to create client side decorations frame: {err}");
                    self.csd_fails = true;
                },
            }
        } else if configure.decoration_mode == DecorationMode::Server {
            // Drop the frame for server side decorations to save resources.
            self.frame = None;
        }

        let stateless = Self::is_stateless(&configure);

        tracing::trace!(
            "configure: stateless={}, configure.new_size={:?}, current_size={:?}, \
             stateless_size={:?}",
            stateless,
            configure.new_size,
            self.size,
            self.stateless_size
        );

        let (mut new_size, constrain) = if let Some(frame) = self.frame.as_mut() {
            // Configure the window states.
            frame.update_state(configure.state);

            match configure.new_size {
                (Some(width), Some(height)) => {
                    let (width, height) = frame.subtract_borders(width, height);
                    let width = width.map(|w| w.get()).unwrap_or(1);
                    let height = height.map(|h| h.get()).unwrap_or(1);
                    ((width, height).into(), false)
                },
                (..) if stateless => (self.stateless_size, true),
                _ => (self.size, true),
            }
        } else {
            match configure.new_size {
                (Some(width), Some(height)) => ((width.get(), height.get()).into(), false),
                _ if stateless => (self.stateless_size, true),
                _ => (self.size, true),
            }
        };

        tracing::debug!("configure: chosen new_size={:?}, constrain={}", new_size, constrain);

        // Apply configure bounds only when compositor let the user decide what size to pick.
        if constrain {
            let bounds = self.inner_size_bounds(&configure);
            new_size.width =
                bounds.0.map(|bound_w| new_size.width.min(bound_w.get())).unwrap_or(new_size.width);
            new_size.height = bounds
                .1
                .map(|bound_h| new_size.height.min(bound_h.get()))
                .unwrap_or(new_size.height);
        }

        let new_state = configure.state;
        let old_state = self.last_configure.as_ref().map(|configure| configure.state);

        // The compositor suspends a window nobody can see: minimized, or on a hidden workspace.
        let suspended = new_state.contains(XdgWindowState::SUSPENDED);
        if old_state.map_or(suspended, |old| old.contains(XdgWindowState::SUSPENDED) != suspended) {
            self.occluded = Some(suspended);
        }

        let state_change_requires_resize = old_state
            .map(|old_state| {
                !old_state
                    .symmetric_difference(new_state)
                    .difference(XdgWindowState::ACTIVATED | XdgWindowState::SUSPENDED)
                    .is_empty()
            })
            // NOTE: `None` is present for the initial configure, thus we must always resize.
            .unwrap_or(true);

        // NOTE: Set the configure before doing a resize, since we query it during it.
        self.last_configure = Some(configure);

        if state_change_requires_resize || new_size != self.inner_size() {
            self.resize(new_size);
            true
        } else {
            false
        }
    }

    /// Take the occlusion change to report as `WindowEvent::Occluded`, if any.
    pub fn take_occluded(&mut self) -> Option<bool> {
        self.occluded.take()
    }

    /// Compute the bounds for the inner size of the surface.
    fn inner_size_bounds(
        &self,
        configure: &WindowConfigure,
    ) -> (Option<NonZeroU32>, Option<NonZeroU32>) {
        let configure_bounds = match configure.suggested_bounds {
            Some((width, height)) => (NonZeroU32::new(width), NonZeroU32::new(height)),
            None => (None, None),
        };

        if let Some(frame) = self.frame.as_ref() {
            let (width, height) = frame.subtract_borders(
                configure_bounds.0.unwrap_or(NonZeroU32::new(1).unwrap()),
                configure_bounds.1.unwrap_or(NonZeroU32::new(1).unwrap()),
            );
            (configure_bounds.0.and(width), configure_bounds.1.and(height))
        } else {
            configure_bounds
        }
    }

    #[inline]
    fn is_stateless(configure: &WindowConfigure) -> bool {
        !(configure.is_maximized() || configure.is_fullscreen() || configure.is_tiled())
    }

    /// Start interacting drag resize.
    /// Record the seat and serial of the latest `wl_touch.down` on this surface
    /// so a touch-initiated interactive move/resize can pass a valid grab serial
    /// to the compositor (see [`Self::last_touch_down`]).
    pub fn set_last_touch_down(&mut self, seat: WlSeat, serial: u32) {
        self.last_touch_down = Some((seat, serial));
    }

    pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> {
        let xdg_toplevel = self.window.xdg_toplevel();

        // Prefer a pointer button serial; on a touchscreen there is none, so
        // fall back to the latest touch-down serial.
        let mut resized = false;
        self.apply_on_pointer(|_, data| {
            let serial = data.latest_button_serial();
            if serial != 0 {
                let seat = data.seat();
                xdg_toplevel.resize(seat, serial, direction.into());
                resized = true;
            }
        });
        if !resized {
            if let Some((seat, serial)) = &self.last_touch_down {
                xdg_toplevel.resize(seat, *serial, direction.into());
            }
        }

        Ok(())
    }

    /// Start the window drag.
    pub fn drag_window(&self) -> Result<(), ExternalError> {
        let xdg_toplevel = self.window.xdg_toplevel();
        // Prefer a pointer button serial; on a touchscreen there is none, so
        // fall back to the latest touch-down serial.
        let mut moved = false;
        self.apply_on_pointer(|_, data| {
            let serial = data.latest_button_serial();
            if serial != 0 {
                let seat = data.seat();
                xdg_toplevel._move(seat, serial);
                moved = true;
            }
        });
        if !moved {
            if let Some((seat, serial)) = &self.last_touch_down {
                xdg_toplevel._move(seat, *serial);
            }
        }

        Ok(())
    }

    /// Tells whether the window should be closed.
    #[allow(clippy::too_many_arguments)]
    pub fn frame_click(
        &mut self,
        click: FrameClick,
        pressed: bool,
        seat: &WlSeat,
        serial: u32,
        timestamp: Duration,
        window_id: WindowId,
        updates: &mut Vec<WindowCompositorUpdate>,
    ) -> Option<bool> {
        match self.frame.as_mut()?.on_click(timestamp, click, pressed)? {
            FrameAction::Minimize => self.window.set_minimized(),
            FrameAction::Maximize => self.window.set_maximized(),
            FrameAction::UnMaximize => self.window.unset_maximized(),
            FrameAction::Close => WinitState::queue_close(updates, window_id),
            FrameAction::Move => self.has_pending_move = Some(serial),
            FrameAction::Resize(edge) => {
                let edge = match edge {
                    ResizeEdge::None => XdgResizeEdge::None,
                    ResizeEdge::Top => XdgResizeEdge::Top,
                    ResizeEdge::Bottom => XdgResizeEdge::Bottom,
                    ResizeEdge::Left => XdgResizeEdge::Left,
                    ResizeEdge::TopLeft => XdgResizeEdge::TopLeft,
                    ResizeEdge::BottomLeft => XdgResizeEdge::BottomLeft,
                    ResizeEdge::Right => XdgResizeEdge::Right,
                    ResizeEdge::TopRight => XdgResizeEdge::TopRight,
                    ResizeEdge::BottomRight => XdgResizeEdge::BottomRight,
                    _ => return None,
                };
                self.window.resize(seat, serial, edge);
            },
            FrameAction::ShowMenu(x, y) => self.window.show_window_menu(seat, serial, (x, y)),
            _ => (),
        };

        Some(false)
    }

    pub fn frame_point_left(&mut self) {
        if let Some(frame) = self.frame.as_mut() {
            frame.click_point_left();
        }
    }

    // Move the point over decorations.
    pub fn frame_point_moved(
        &mut self,
        seat: &WlSeat,
        surface: &WlSurface,
        timestamp: Duration,
        x: f64,
        y: f64,
    ) -> Option<CursorIcon> {
        // Take the serial if we had any, so it doesn't stick around.
        let serial = self.has_pending_move.take();

        if let Some(frame) = self.frame.as_mut() {
            let cursor = frame.click_point_moved(timestamp, &surface.id(), x, y);
            // If we have a cursor change, that means that cursor is over the decorations,
            // so try to apply move.
            if let Some(serial) = cursor.is_some().then_some(serial).flatten() {
                self.window.move_(seat, serial);
                None
            } else {
                cursor
            }
        } else {
            None
        }
    }

    /// Get the stored resizable state.
    #[inline]
    pub fn resizable(&self) -> bool {
        self.resizable
    }

    /// Set the resizable state on the window.
    ///
    /// Returns `true` when the state was applied.
    #[inline]
    pub fn set_resizable(&mut self, resizable: bool) -> bool {
        if self.resizable == resizable {
            return false;
        }

        self.resizable = resizable;
        if resizable {
            // Restore min/max sizes of the window.
            self.reload_min_max_hints();
        } else {
            self.set_min_inner_size(Some(self.size));
            self.set_max_inner_size(Some(self.size));
        }

        // Reload the state on the frame as well.
        if let Some(frame) = self.frame.as_mut() {
            frame.set_resizable(resizable);
        }

        true
    }

    /// Whether the window is focused by any seat.
    #[inline]
    pub fn has_focus(&self) -> bool {
        !self.seat_focus.is_empty()
    }

    /// Whether the IME is allowed.
    #[inline]
    pub fn ime_allowed(&self) -> bool {
        self.ime_allowed
    }

    /// Get the size of the window.
    #[inline]
    pub fn inner_size(&self) -> LogicalSize<u32> {
        self.size
    }

    /// Whether the window received initial configure event from the compositor.
    #[inline]
    pub fn is_configured(&self) -> bool {
        self.last_configure.is_some()
    }

    #[inline]
    pub fn is_decorated(&mut self) -> bool {
        let csd = self
            .last_configure
            .as_ref()
            .map(|configure| configure.decoration_mode == DecorationMode::Client)
            .unwrap_or(false);
        if let Some(frame) = csd.then_some(self.frame.as_ref()).flatten() {
            !frame.is_hidden()
        } else {
            // Server side decorations.
            true
        }
    }

    /// Get the outer size of the window.
    #[inline]
    pub fn outer_size(&self) -> LogicalSize<u32> {
        self.frame
            .as_ref()
            .map(|frame| frame.add_borders(self.size.width, self.size.height).into())
            .unwrap_or(self.size)
    }

    /// Register pointer on the top-level.
    pub fn pointer_entered(&mut self, added: Weak<ThemedPointer<WinitPointerData>>) {
        self.pointers.push(added);
        self.reload_cursor_style();

        let mode = self.cursor_grab_mode.user_grab_mode;
        let _ = self.set_cursor_grab_inner(mode);
    }

    /// Pointer has left the top-level.
    pub fn pointer_left(&mut self, removed: Weak<ThemedPointer<WinitPointerData>>) {
        let mut new_pointers = Vec::new();
        for pointer in self.pointers.drain(..) {
            if let Some(pointer) = pointer.upgrade() {
                if pointer.pointer() != removed.upgrade().unwrap().pointer() {
                    new_pointers.push(Arc::downgrade(&pointer));
                }
            }
        }

        self.pointers = new_pointers;
    }

    /// Refresh the decorations frame if it's present returning whether the client should redraw.
    pub fn refresh_frame(&mut self) -> bool {
        if let Some(frame) = self.frame.as_mut() {
            if !frame.is_hidden() && frame.is_dirty() {
                return frame.draw();
            }
        }

        false
    }

    /// Reload the cursor style on the given window.
    pub fn reload_cursor_style(&mut self) {
        if self.cursor_visible {
            match &self.selected_cursor {
                SelectedCursor::Named(icon) => self.set_cursor(*icon),
                SelectedCursor::Custom(cursor) => self.apply_custom_cursor(cursor),
            }
        } else {
            self.set_cursor_visible(self.cursor_visible);
        }
    }

    /// Reissue the transparency hint to the compositor.
    pub fn reload_transparency_hint(&self) {
        let surface = self.window.wl_surface();

        if self.transparent {
            surface.set_opaque_region(None);
        } else if let Ok(region) = Region::new(&*self.compositor) {
            region.add(0, 0, i32::MAX, i32::MAX);
            surface.set_opaque_region(Some(region.wl_region()));
        } else {
            warn!("Failed to mark window opaque.");
        }
    }

    /// Reissue the background-effect blur region to the compositor.
    ///
    /// The protocol has no whole-surface mode, so the region has to be resent
    /// whenever the surface changes size or it would stay sized to the old
    /// window. The KDE blur protocol tracks the surface on its own and needs
    /// none of this.
    pub fn reload_blur_region(&self) {
        let Some(effect) = self.background_effect.as_ref() else {
            return;
        };

        if let Ok(region) = Region::new(&*self.compositor) {
            region.add(0, 0, self.size.width as i32, self.size.height as i32);
            effect.set_blur_region(Some(region.wl_region()));
        } else {
            warn!("Failed to set blur region.");
        }
    }

    /// Try to resize the window when the user can do so.
    pub fn request_inner_size(&mut self, inner_size: Size) -> PhysicalSize<u32> {
        let logical_size = inner_size.to_logical(self.scale_factor());
        let is_stateless = self.last_configure.as_ref().map(Self::is_stateless).unwrap_or(true);

        tracing::trace!(
            "request_inner_size: inner_size={:?}, logical_size={:?}, is_stateless={}, \
             current_stateless_size={:?}",
            inner_size,
            logical_size,
            is_stateless,
            self.stateless_size
        );

        if is_stateless {
            // Window is floating/normal - resize immediately
            tracing::trace!("request_inner_size: window is stateless, calling resize()");
            self.resize(logical_size);
        } else {
            // Window is maximized/fullscreen/tiled - store as the restore size
            // so when unmaximized it will restore to this size
            tracing::trace!(
                "request_inner_size: window is NOT stateless (maximized/tiled), storing {:?} as \
                 stateless_size for restore",
                logical_size
            );
            self.stateless_size = logical_size;

            // Send the resize hint to the compositor via animated_resize protocol
            // The compositor will update the restore geometry for when window is unmaximized
            self.request_animated_resize(logical_size.width as i32, logical_size.height as i32, 0);
        }
        logical_to_physical_rounded(self.inner_size(), self.scale_factor())
    }

    /// Resize the window to the new inner size.
    fn resize(&mut self, inner_size: LogicalSize<u32>) {
        tracing::debug!("resize: old_size={:?} -> new_size={:?}", self.size, inner_size,);
        self.size = inner_size;

        // Update the stateless size.
        if Some(true) == self.last_configure.as_ref().map(Self::is_stateless) {
            self.stateless_size = inner_size;
        }

        // Update the inner frame.
        let ((x, y), outer_size) = if let Some(frame) = self.frame.as_mut() {
            // Resize only visible frame.
            if !frame.is_hidden() {
                frame.resize(
                    NonZeroU32::new(self.size.width).unwrap(),
                    NonZeroU32::new(self.size.height).unwrap(),
                );
            }

            (frame.location(), frame.add_borders(self.size.width, self.size.height).into())
        } else {
            ((0, 0), self.size)
        };

        // Reload the hint.
        self.reload_transparency_hint();
        self.reload_blur_region();

        // Set the window geometry.
        tracing::debug!(
            "resize: set_window_geometry({}, {}, {}, {})",
            x,
            y,
            outer_size.width,
            outer_size.height,
        );
        self.window.xdg_surface().set_window_geometry(
            x,
            y,
            outer_size.width as i32,
            outer_size.height as i32,
        );

        // Update the target viewport, this is used if and only if fractional scaling is in use.
        if let Some(viewport) = self.viewport.as_ref() {
            tracing::debug!(
                "resize: set_viewport_destination({}, {})",
                self.size.width,
                self.size.height
            );
            // Set inner size without the borders.
            viewport.set_destination(self.size.width as _, self.size.height as _);
        }
    }

    /// Get the scale factor of the window.
    #[inline]
    pub fn scale_factor(&self) -> f64 {
        self.scale_factor
    }

    /// Set the cursor icon.
    pub fn set_cursor(&mut self, cursor_icon: CursorIcon) {
        self.selected_cursor = SelectedCursor::Named(cursor_icon);

        if !self.cursor_visible {
            return;
        }

        self.apply_on_pointer(|pointer, _| {
            if pointer.set_cursor(&self.connection, cursor_icon).is_err() {
                warn!("Failed to set cursor to {:?}", cursor_icon);
            }
        })
    }

    /// Set the custom cursor icon.
    pub(crate) fn set_custom_cursor(&mut self, cursor: RootCustomCursor) {
        let cursor = match cursor {
            RootCustomCursor { inner: PlatformCustomCursor::Wayland(cursor) } => cursor.0,
            #[cfg(x11_platform)]
            RootCustomCursor { inner: PlatformCustomCursor::X(_) } => {
                tracing::error!("passed a X11 cursor to Wayland backend");
                return;
            },
        };

        let cursor = {
            let mut pool = self.custom_cursor_pool.lock().unwrap();
            CustomCursor::new(&mut pool, &cursor)
        };

        if self.cursor_visible {
            self.apply_custom_cursor(&cursor);
        }

        self.selected_cursor = SelectedCursor::Custom(cursor);
    }

    fn apply_custom_cursor(&self, cursor: &CustomCursor) {
        self.apply_on_pointer(|pointer, data| {
            let surface = pointer.surface();

            let scale = if let Some(viewport) = data.viewport() {
                let scale = self.scale_factor();
                let size = PhysicalSize::new(cursor.w, cursor.h).to_logical(scale);
                viewport.set_destination(size.width, size.height);
                scale
            } else {
                let scale = surface.data::<SurfaceData>().unwrap().surface_data().scale_factor();
                surface.set_buffer_scale(scale);
                scale as f64
            };

            surface.attach(Some(cursor.buffer.wl_buffer()), 0, 0);
            if surface.version() >= 4 {
                surface.damage_buffer(0, 0, cursor.w, cursor.h);
            } else {
                let size = PhysicalSize::new(cursor.w, cursor.h).to_logical(scale);
                surface.damage(0, 0, size.width, size.height);
            }
            surface.commit();

            let serial = pointer
                .pointer()
                .data::<WinitPointerData>()
                .and_then(|data| data.pointer_data().latest_enter_serial())
                .unwrap();

            let hotspot =
                PhysicalPosition::new(cursor.hotspot_x, cursor.hotspot_y).to_logical(scale);
            pointer.pointer().set_cursor(serial, Some(surface), hotspot.x, hotspot.y);
        });
    }

    /// Set maximum inner window size.
    pub fn set_min_inner_size(&mut self, size: Option<LogicalSize<u32>>) {
        // Ensure that the window has the right minimum size.
        let mut size = size.unwrap_or(MIN_WINDOW_SIZE);
        size.width = size.width.max(MIN_WINDOW_SIZE.width);
        size.height = size.height.max(MIN_WINDOW_SIZE.height);

        // Add the borders.
        let size = self
            .frame
            .as_ref()
            .map(|frame| frame.add_borders(size.width, size.height).into())
            .unwrap_or(size);

        self.min_inner_size = size;
        self.window.set_min_size(Some(size.into()));
    }

    /// Set maximum inner window size.
    pub fn set_max_inner_size(&mut self, size: Option<LogicalSize<u32>>) {
        let size = size.map(|size| {
            self.frame
                .as_ref()
                .map(|frame| frame.add_borders(size.width, size.height).into())
                .unwrap_or(size)
        });

        self.max_inner_size = size;
        self.window.set_max_size(size.map(Into::into));
    }

    /// Set the CSD theme.
    pub fn set_theme(&mut self, theme: Option<Theme>) {
        self.theme = theme;
        #[cfg(feature = "sctk-adwaita")]
        if let Some(frame) = self.frame.as_mut() {
            frame.set_config(into_sctk_adwaita_config(theme))
        }
    }

    /// The current theme for CSD decorations.
    #[inline]
    pub fn theme(&self) -> Option<Theme> {
        self.theme
    }

    /// Set the cursor grabbing state on the top-level.
    pub fn set_cursor_grab(&mut self, mode: CursorGrabMode) -> Result<(), ExternalError> {
        if self.cursor_grab_mode.user_grab_mode == mode {
            return Ok(());
        }

        self.set_cursor_grab_inner(mode)?;
        // Update user grab on success.
        self.cursor_grab_mode.user_grab_mode = mode;
        Ok(())
    }

    /// Reload the hints for minimum and maximum sizes.
    pub fn reload_min_max_hints(&mut self) {
        self.set_min_inner_size(Some(self.min_inner_size));
        self.set_max_inner_size(self.max_inner_size);
    }

    /// Set the grabbing state on the surface.
    fn set_cursor_grab_inner(&mut self, mode: CursorGrabMode) -> Result<(), ExternalError> {
        let pointer_constraints = match self.pointer_constraints.as_ref() {
            Some(pointer_constraints) => pointer_constraints,
            None if mode == CursorGrabMode::None => return Ok(()),
            None => return Err(ExternalError::NotSupported(NotSupportedError::new())),
        };

        let mut unset_old = false;
        match self.cursor_grab_mode.current_grab_mode {
            CursorGrabMode::None => unset_old = true,
            CursorGrabMode::Confined => self.apply_on_pointer(|_, data| {
                data.unconfine_pointer();
                unset_old = true;
            }),
            CursorGrabMode::Locked => {
                self.apply_on_pointer(|_, data| {
                    data.unlock_pointer();
                    unset_old = true;
                });
            },
        }

        // In case we haven't unset the old mode, it means that we don't have a cursor above
        // the window, thus just wait for it to re-appear.
        if !unset_old {
            return Ok(());
        }

        let mut set_mode = false;
        let surface = self.window.wl_surface();
        match mode {
            CursorGrabMode::Locked => self.apply_on_pointer(|pointer, data| {
                let pointer = pointer.pointer();
                data.lock_pointer(pointer_constraints, surface, pointer, &self.queue_handle);
                set_mode = true;
            }),
            CursorGrabMode::Confined => self.apply_on_pointer(|pointer, data| {
                let pointer = pointer.pointer();
                data.confine_pointer(pointer_constraints, surface, pointer, &self.queue_handle);
                set_mode = true;
            }),
            CursorGrabMode::None => {
                // Current lock/confine was already removed.
                set_mode = true;
            },
        }

        // Replace the current grab mode after we've ensure that it got updated.
        if set_mode {
            self.cursor_grab_mode.current_grab_mode = mode;
        }

        Ok(())
    }

    pub fn show_window_menu(&self, position: LogicalPosition<u32>) {
        // TODO(kchibisov) handle touch serials.
        self.apply_on_pointer(|_, data| {
            let serial = data.latest_button_serial();
            let seat = data.seat();
            self.window.show_window_menu(seat, serial, position.into());
        });
    }

    /// Set the position of the cursor.
    pub fn set_cursor_position(&self, position: LogicalPosition<f64>) -> Result<(), ExternalError> {
        if self.pointer_constraints.is_none() {
            return Err(ExternalError::NotSupported(NotSupportedError::new()));
        }

        // Position can be set only for locked cursor.
        if self.cursor_grab_mode.current_grab_mode != CursorGrabMode::Locked {
            return Err(ExternalError::Os(os_error!(crate::platform_impl::OsError::Misc(
                "cursor position can be set only for locked cursor."
            ))));
        }

        self.apply_on_pointer(|_, data| {
            data.set_locked_cursor_position(position.x, position.y);
        });

        Ok(())
    }

    /// Set the visibility state of the cursor.
    pub fn set_cursor_visible(&mut self, cursor_visible: bool) {
        self.cursor_visible = cursor_visible;

        if self.cursor_visible {
            match &self.selected_cursor {
                SelectedCursor::Named(icon) => self.set_cursor(*icon),
                SelectedCursor::Custom(cursor) => self.apply_custom_cursor(cursor),
            }
        } else {
            for pointer in self.pointers.iter().filter_map(|pointer| pointer.upgrade()) {
                let latest_enter_serial = pointer.pointer().winit_data().latest_enter_serial();

                pointer.pointer().set_cursor(latest_enter_serial, None, 0, 0);
            }
        }
    }

    /// Whether show or hide client side decorations.
    #[inline]
    pub fn set_decorate(&mut self, decorate: bool) {
        if decorate == self.decorate {
            return;
        }

        self.decorate = decorate;

        match self.last_configure.as_ref().map(|configure| configure.decoration_mode) {
            Some(DecorationMode::Server) if !self.decorate => {
                // To disable decorations we should request client and hide the frame.
                self.window.request_decoration_mode(Some(DecorationMode::Client))
            },
            _ if self.decorate => self.window.request_decoration_mode(Some(DecorationMode::Server)),
            _ => (),
        }

        if let Some(frame) = self.frame.as_mut() {
            frame.set_hidden(!decorate);
            // Force the resize.
            self.resize(self.size);
        }
    }

    /// Add seat focus for the window.
    #[inline]
    pub fn add_seat_focus(&mut self, seat: ObjectId) {
        self.seat_focus.insert(seat);
    }

    /// Remove seat focus from the window.
    #[inline]
    pub fn remove_seat_focus(&mut self, seat: &ObjectId) {
        self.seat_focus.remove(seat);
    }

    /// Create or destroy a keyboard-shortcuts inhibitor for this window. While
    /// active, the compositor forwards its reserved keys (e.g. Super) to us
    /// instead of handling them as global shortcuts — needed for key capture.
    pub fn set_keyboard_shortcuts_inhibit(&mut self, inhibit: bool) {
        if inhibit {
            if self.keyboard_shortcuts_inhibitor.is_none() {
                if let (Some(manager), Some(seat)) = (
                    self.keyboard_shortcuts_inhibit_manager.as_ref(),
                    self.keyboard_shortcuts_inhibit_seat.as_ref(),
                ) {
                    let inhibitor = manager.inhibit_shortcuts(
                        self.window.wl_surface(),
                        seat,
                        &self.queue_handle,
                        GlobalData,
                    );
                    self.keyboard_shortcuts_inhibitor = Some(inhibitor);
                }
            }
        } else if let Some(inhibitor) = self.keyboard_shortcuts_inhibitor.take() {
            inhibitor.destroy();
        }
    }

    /// Returns `true` if the requested state was applied.
    pub fn set_ime_allowed(&mut self, allowed: bool) -> bool {
        self.ime_allowed = allowed;
        if !allowed {
            self.ime_surrounding = None;
        }

        let mut applied = false;
        for text_input in &self.text_inputs {
            applied = true;
            if allowed {
                self.enable_text_input(text_input);
            } else {
                text_input.disable();
            }
            text_input.commit();
        }

        applied
    }

    /// Enable `text_input` with all the IME state the window holds; the caller commits.
    pub fn enable_text_input(&self, text_input: &ZwpTextInputV3) {
        text_input.enable();
        text_input.set_content_type_by_purpose(self.ime_purpose);
        if let Some((x, y, width, height)) = self.ime_cursor_area {
            text_input.set_cursor_rectangle(x, y, width, height);
        }
        if let Some(surrounding) = &self.ime_surrounding {
            text_input.set_surrounding(surrounding);
        }
    }

    /// Set the IME position.
    pub fn set_ime_cursor_area(&mut self, position: LogicalPosition<u32>, size: LogicalSize<u32>) {
        // FIXME: This won't fly unless user will have a way to request IME window per seat, since
        // the ime windows will be overlapping, but winit doesn't expose API to specify for
        // which seat we're setting IME position.
        let (x, y) = (position.x as i32, position.y as i32);
        let (width, height) = (size.width as i32, size.height as i32);
        self.ime_cursor_area = Some((x, y, width, height));
        for text_input in self.text_inputs.iter() {
            text_input.set_cursor_rectangle(x, y, width, height);
            text_input.commit();
        }
    }

    /// Set the IME purpose.
    pub fn set_ime_purpose(&mut self, purpose: ImePurpose) {
        self.ime_purpose = purpose;

        // A password field's text is never shared, nor the text of the field before it.
        let forget = purpose == ImePurpose::Password
            && self.ime_surrounding.take().is_some()
            && self.ime_allowed;
        for text_input in &self.text_inputs {
            if forget {
                self.enable_text_input(text_input);
            } else {
                text_input.set_content_type_by_purpose(purpose);
            }
            text_input.commit();
        }
    }

    /// Set the focused field's surrounding text.
    pub fn set_ime_surrounding_text(&mut self, surrounding: Option<&ImeSurroundingText>) {
        let next = SurroundingText::for_purpose(self.ime_purpose, surrounding);
        let change = SurroundingChange::between(
            self.ime_surrounding.as_ref(),
            next.as_ref(),
            self.ime_committed,
        );
        if change == SurroundingChange::Unchanged {
            return;
        }
        self.ime_surrounding = next;
        self.ime_committed = false;
        if !self.ime_allowed {
            return;
        }

        for text_input in &self.text_inputs {
            match (change, &self.ime_surrounding) {
                (SurroundingChange::Send(cause), Some(surrounding)) => {
                    text_input.set_surrounding(surrounding);
                    text_input.set_text_change_cause(cause);
                },
                _ => self.enable_text_input(text_input),
            }
            text_input.commit();
        }
    }

    /// An input method commit was delivered: the field's next change is its doing.
    pub fn ime_text_committed(&mut self) {
        self.ime_committed = true;
    }

    /// Get the IME purpose.
    pub fn ime_purpose(&self) -> ImePurpose {
        self.ime_purpose
    }

    /// Set the scale factor for the given window.
    #[inline]
    pub fn set_scale_factor(&mut self, scale_factor: f64) {
        self.scale_factor = scale_factor;

        // NOTE: When fractional scaling is not used update the buffer scale.
        if self.fractional_scale.is_none() {
            let _ = self.window.set_buffer_scale(self.scale_factor as _);
        }

        if let Some(frame) = self.frame.as_mut() {
            frame.set_scaling_factor(scale_factor);
        }
    }

    /// Make window background blurred
    #[inline]
    pub fn set_blur(&mut self, blurred: bool) {
        // Both protocols are driven from this one setting: a compositor
        // typically implements one or the other, and the one it does not
        // understand simply never binds.
        if blurred && self.background_effect.is_none() {
            if let Some(manager) = self.background_effect_manager.as_ref() {
                let effect =
                    manager.get_background_effect(self.window.wl_surface(), &self.queue_handle);
                self.background_effect = Some(effect);
                self.reload_blur_region();
            }
        } else if !blurred && self.background_effect.is_some() {
            // Dropping it destroys the object; unset first so the effect is
            // gone even if the compositor keeps the surface around.
            self.background_effect.as_ref().unwrap().unset();
            self.background_effect = None;
        }

        if blurred && self.blur.is_none() {
            if let Some(blur_manager) = self.blur_manager.as_ref() {
                let blur = blur_manager.blur(self.window.wl_surface(), &self.queue_handle);
                blur.commit();
                self.blur = Some(blur);
            } else {
                if self.background_effect_manager.is_none() {
                    info!("No blur protocol available, unable to change blur")
                }
            }
        } else if !blurred && self.blur.is_some() {
            self.blur_manager.as_ref().unwrap().unset(self.window.wl_surface());
            self.blur.take().unwrap().release();
        }
    }

    /// Request an animated resize to the target size.
    ///
    /// This uses the COSMIC animated resize protocol to request smooth
    /// compositor-driven resize animation. The compositor will send
    /// intermediate configure events for smooth animation.
    ///
    /// Returns `true` if the request was sent, `false` if the protocol
    /// is not available.
    ///
    /// # Arguments
    /// * `width` - Target width in logical pixels
    /// * `height` - Target height in logical pixels
    /// * `duration_ms` - Animation duration in milliseconds
    #[inline]
    pub fn request_animated_resize(&mut self, width: i32, height: i32, duration_ms: u32) -> bool {
        // Create controller if we don't have one yet
        if self.animated_resize_controller.is_none() {
            if let Some(manager) = self.animated_resize_manager.as_ref() {
                let controller =
                    manager.get_animated_resize(self.window.wl_surface(), &self.queue_handle);
                self.animated_resize_controller = Some(controller);
            } else {
                tracing::trace!("Animated resize manager unavailable");
                return false;
            }
        }

        if let Some(controller) = self.animated_resize_controller.as_ref() {
            tracing::trace!(width, height, duration_ms, "Requesting animated resize to compositor");
            controller.resize_to(width, height, duration_ms);
            true
        } else {
            false
        }
    }

    /// Request an animated resize with explicit position via the animated resize protocol.
    ///
    /// This uses the compositor's animated_resize protocol to smoothly animate
    /// the window from its current geometry to the target geometry.
    ///
    /// If the window is maximized, the position and size will be stored and used
    /// when the window is restored to normal state.
    ///
    /// # Arguments
    /// * `x` - Target x position in logical pixels
    /// * `y` - Target y position in logical pixels
    /// * `width` - Target width in logical pixels
    /// * `height` - Target height in logical pixels
    /// * `duration_ms` - Animation duration in milliseconds
    #[inline]
    pub fn request_animated_resize_with_position(
        &mut self,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
        duration_ms: u32,
    ) -> bool {
        // Create controller if we don't have one yet
        if self.animated_resize_controller.is_none() {
            if let Some(manager) = self.animated_resize_manager.as_ref() {
                let controller =
                    manager.get_animated_resize(self.window.wl_surface(), &self.queue_handle);
                self.animated_resize_controller = Some(controller);
            } else {
                tracing::trace!("Animated resize manager unavailable");
                return false;
            }
        }

        if let Some(controller) = self.animated_resize_controller.as_ref() {
            tracing::trace!(
                x,
                y,
                width,
                height,
                duration_ms,
                "Requesting animated resize with position to compositor"
            );
            controller.resize_to_with_position(x, y, width, height, duration_ms);
            true
        } else {
            false
        }
    }

    /// Set corner radius for this window.
    ///
    /// Communicates the corner radius hint to the compositor so it can
    /// draw proper blur outlines and rounded corners.
    ///
    /// Returns `true` if the request was sent, `false` if the protocol
    /// is not available.
    #[inline]
    pub fn set_corner_radius(
        &mut self,
        top_left: u32,
        top_right: u32,
        bottom_right: u32,
        bottom_left: u32,
    ) -> bool {
        // Create controller if we don't have one yet
        if self.corner_radius_controller.is_none() {
            if let Some(manager) = self.corner_radius_manager.as_ref() {
                let controller =
                    manager.get_corner_radius(self.window.wl_surface(), &self.queue_handle);
                self.corner_radius_controller = Some(controller);
            } else {
                tracing::trace!("Corner radius manager unavailable");
                return false;
            }
        }

        if let Some(controller) = self.corner_radius_controller.as_ref() {
            tracing::trace!(
                top_left,
                top_right,
                bottom_right,
                bottom_left,
                "Setting corner radius"
            );
            controller.set_radius(top_left, top_right, bottom_right, bottom_left);
            true
        } else {
            false
        }
    }

    /// Set the compositor-rendered backdrop color for this window.
    ///
    /// Returns `true` if the request was sent, `false` if the protocol
    /// is not available.
    #[inline]
    pub fn set_backdrop_color(&mut self, r: u32, g: u32, b: u32, a: u32) -> bool {
        if self.backdrop_color_controller.is_none() {
            if let Some(manager) = self.backdrop_color_manager.as_ref() {
                let controller =
                    manager.get_backdrop_color(self.window.wl_surface(), &self.queue_handle);
                self.backdrop_color_controller = Some(controller);
            } else {
                tracing::trace!("Backdrop color manager unavailable");
                return false;
            }
        }

        if let Some(controller) = self.backdrop_color_controller.as_ref() {
            tracing::trace!(r, g, b, a, "Setting backdrop color");
            controller.set_color(r, g, b, a);
            true
        } else {
            false
        }
    }

    /// Register this window to receive the device's special key.
    ///
    /// `is_default` also makes it the fallback receiver, used whenever no
    /// registered surface is focused — the home screen wants that, a chat
    /// window does not.
    ///
    /// Returns `false` if the compositor does not implement the protocol.
    pub fn register_special_action(&mut self, is_default: bool) -> bool {
        if self.special_action_receiver.is_some() {
            return true;
        }
        let Some(manager) = self.special_action_manager.as_ref() else {
            tracing::trace!("Special action manager unavailable");
            return false;
        };
        self.special_action_receiver = Some(manager.get_special_action(
            self.window.wl_surface(),
            is_default,
            &self.queue_handle,
        ));
        tracing::info!(is_default, "Registered window as a special action receiver");
        true
    }

    /// Stop receiving the special key.
    pub fn unregister_special_action(&mut self) -> bool {
        self.special_action_receiver.take().is_some()
    }

    /// Take the gestures that have arrived since the last drain.
    pub fn take_special_action_events(&self) -> Vec<SpecialActionEvent> {
        self.special_action_receiver
            .as_ref()
            .map(SpecialActionReceiver::take_events)
            .unwrap_or_default()
    }

    pub fn kora_identity(&self) -> Option<crate::window::Identity> {
        self.identity.as_ref().and_then(|identity| identity.current())
    }

    pub fn take_identity_events(&mut self) -> Vec<Option<crate::window::Identity>> {
        self.identity.as_mut().map(|identity| identity.take_events()).unwrap_or_default()
    }

    pub fn set_app_commands(&mut self, commands: &crate::window::AppCommands) {
        if let Some(handle) = self.app_commands.as_mut() {
            handle.publish(commands);
        }
    }

    pub fn note_key_press(&mut self, seat: WlSeat, serial: u32) {
        self.last_key_press = Some((seat, serial));
    }

    /// Ask for the shell's palette with the latest key press, or else the latest click.
    pub fn request_app_palette(&self) {
        let Some(handle) = self.app_commands.as_ref() else {
            return;
        };
        if let Some((seat, serial)) = &self.last_key_press {
            handle.request_palette(seat, *serial);
            return;
        }
        let mut sent = false;
        self.apply_on_pointer(|_, data| {
            let serial = data.latest_button_serial();
            if serial != 0 && !sent {
                handle.request_palette(data.seat(), serial);
                sent = true;
            }
        });
    }

    pub fn take_app_command_events(&mut self) -> Vec<crate::window::AppCommandRequest> {
        self.app_commands.as_mut().map(|handle| handle.take_events()).unwrap_or_default()
    }

    /// Embed a toplevel by process ID into this window's surface.
    ///
    /// This requests the compositor to embed the window created by the specified
    /// process into this window's surface. The compositor will monitor for new
    /// toplevels from the PID and embed the first matching one.
    ///
    /// Returns an embed ID that can be used to set geometry or remove the embed,
    /// or `None` if the surface embed protocol is not available.
    ///
    /// # Arguments
    /// * `pid` - Process ID of the application to embed
    /// * `app_id` - Optional app_id hint for verification (can be empty)
    /// * `x` - X position within this window's surface
    /// * `y` - Y position within this window's surface
    /// * `width` - Width of the embed region
    /// * `height` - Height of the embed region
    /// * `interactive` - Whether input should be routed to the embedded surface
    // Arity follows the protocol request; a struct would obscure it.
    #[allow(clippy::too_many_arguments)]
    pub fn embed_toplevel_by_pid(
        &mut self,
        pid: u32,
        app_id: &str,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
        interactive: bool,
    ) -> Option<u64> {
        let manager = self.surface_embed_manager.as_ref()?;

        let embedded = manager.embed_toplevel_by_pid(
            self.window.wl_surface(),
            pid,
            app_id,
            &self.queue_handle,
        );

        // Set initial geometry if width/height are provided
        // Skip set_geometry when width=0/height=0 (anchor-based positioning will be used)
        if width > 0 && height > 0 {
            embedded.set_geometry(x, y, width, height);
        }
        embedded.set_interactive(interactive);
        embedded.commit();

        let embed_id = self.next_embed_id;
        self.next_embed_id += 1;
        self.embedded_surfaces.insert(embed_id, embedded);

        tracing::info!(
            embed_id,
            pid,
            app_id,
            x,
            y,
            width,
            height,
            interactive,
            "Created embed for PID"
        );

        Some(embed_id)
    }

    /// Update the geometry of an embedded surface.
    ///
    /// # Arguments
    /// * `embed_id` - The ID returned from `embed_toplevel_by_pid`
    /// * `x` - X position within this window's surface
    /// * `y` - Y position within this window's surface
    /// * `width` - Width of the embed region
    /// * `height` - Height of the embed region
    pub fn set_embed_geometry(
        &mut self,
        embed_id: u64,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
    ) -> bool {
        if let Some(embedded) = self.embedded_surfaces.get(&embed_id) {
            embedded.set_geometry(x, y, width, height);
            embedded.commit();
            tracing::trace!(embed_id, x, y, width, height, "Updated embed geometry");
            true
        } else {
            tracing::warn!(embed_id, "Embed not found for geometry update");
            false
        }
    }

    /// Set anchor-based positioning for an embedded surface.
    ///
    /// Instead of specifying absolute (x, y) coordinates, this allows positioning
    /// relative to the parent window edges. The geometry is automatically
    /// recalculated by the compositor when the parent window resizes.
    ///
    /// # Arguments
    /// * `embed_id` - The embedded surface ID
    /// * `anchor` - Bitflags indicating which edges to anchor to (0=none, 1=top, 2=bottom, 4=left,
    ///   8=right)
    /// * `margin_top` - Margin from top edge
    /// * `margin_right` - Margin from right edge
    /// * `margin_bottom` - Margin from bottom edge
    /// * `margin_left` - Margin from left edge
    /// * `width` - Width of embed region (0 to stretch between left/right anchors)
    /// * `height` - Height of embed region (0 to stretch between top/bottom anchors)
    // Arity follows the protocol request; a struct would obscure it.
    #[allow(clippy::too_many_arguments)]
    pub fn set_embed_anchor(
        &mut self,
        embed_id: u64,
        anchor: u32,
        margin_top: i32,
        margin_right: i32,
        margin_bottom: i32,
        margin_left: i32,
        width: i32,
        height: i32,
    ) -> bool {
        if let Some(embedded) = self.embedded_surfaces.get(&embed_id) {
            embedded.set_anchor(
                anchor,
                margin_top,
                margin_right,
                margin_bottom,
                margin_left,
                width,
                height,
            );
            embedded.commit();
            tracing::trace!(
                embed_id,
                anchor,
                margin_top,
                margin_right,
                margin_bottom,
                margin_left,
                width,
                height,
                "Updated embed anchor"
            );
            true
        } else {
            tracing::warn!(embed_id, "Embed not found for anchor update");
            false
        }
    }

    /// Set corner radius for an embedded surface.
    ///
    /// This allows the parent to specify rounded corners that match its own UI.
    /// Each corner can have a different radius. Values are in logical pixels.
    pub fn set_embed_corner_radius(
        &mut self,
        embed_id: u64,
        top_left: u32,
        top_right: u32,
        bottom_right: u32,
        bottom_left: u32,
    ) -> bool {
        if let Some(embedded) = self.embedded_surfaces.get(&embed_id) {
            embedded.set_corner_radius(top_left, top_right, bottom_right, bottom_left);
            embedded.commit();
            tracing::trace!(
                embed_id,
                top_left,
                top_right,
                bottom_right,
                bottom_left,
                "Updated embed corner radius"
            );
            true
        } else {
            tracing::warn!(embed_id, "Embed not found for corner radius update");
            false
        }
    }

    /// Set interactivity for an embedded surface.
    ///
    /// When interactive, pointer/keyboard/touch events within the embed
    /// region will be routed to the embedded toplevel.
    pub fn set_embed_interactive(&mut self, embed_id: u64, interactive: bool) -> bool {
        if let Some(embedded) = self.embedded_surfaces.get(&embed_id) {
            embedded.set_interactive(interactive);
            embedded.commit();
            tracing::trace!(embed_id, interactive, "Updated embed interactivity");
            true
        } else {
            tracing::warn!(embed_id, "Embed not found for interactive update");
            false
        }
    }

    /// Remove an embedded surface.
    pub fn remove_embed(&mut self, embed_id: u64) -> bool {
        if self.embedded_surfaces.remove(&embed_id).is_some() {
            tracing::info!(embed_id, "Removed embed");
            true
        } else {
            tracing::warn!(embed_id, "Embed not found for removal");
            false
        }
    }

    /// Check if an embedded surface is still valid.
    pub fn is_embed_valid(&self, embed_id: u64) -> bool {
        self.embedded_surfaces.get(&embed_id).is_some_and(|e| e.is_valid())
    }

    /// Start a Wayland drag-and-drop operation from this window.
    ///
    /// Creates a `wl_data_source` with the given MIME types and actions,
    /// stores the pre-serialized data for `send` events, and calls
    /// `wl_data_device.start_drag(…)` with the latest pointer serial.
    ///
    /// Returns `true` if the drag was started, `false` if DnD is unavailable
    /// or no pointer serial is available.
    ///
    /// `icon_pixels` is `(width, height, pixels, buffer_scale)` for HiDPI support.
    pub fn start_drag(
        &mut self,
        mime_types: Vec<String>,
        actions: u32,
        data: Vec<Vec<u8>>,
        icon_pixels: Option<(u32, u32, Vec<u8>, i32)>,
    ) -> (bool, Vec<String>, Vec<Vec<u8>>) {
        use crate::platform_impl::wayland::types::wayland_dnd::DndSourceData;

        let dnd_manager = match self.dnd_manager.as_ref() {
            Some(m) => m,
            None => {
                tracing::error!("DnD manager unavailable, cannot start drag");
                return (false, mime_types, data);
            },
        };

        let data_device = match self.dnd_data_devices.first() {
            Some(d) => d.clone(),
            None => {
                tracing::error!("No data device available, cannot start drag");
                return (false, mime_types, data);
            },
        };

        // Get the latest pointer serial.
        let serial = self
            .pointers
            .iter()
            .filter_map(|p| p.upgrade())
            .map(|p| p.pointer().winit_data().latest_button_serial())
            .find(|&s| s != 0);

        let serial = match serial {
            Some(s) => s,
            None => {
                tracing::error!("No pointer serial available for DnD start_drag");
                return (false, mime_types, data);
            },
        };

        // Get the seat from the first pointer.
        let seat = self
            .pointers
            .iter()
            .filter_map(|p| p.upgrade())
            .map(|p| p.pointer().winit_data().seat().clone())
            .next();

        let _seat = match seat {
            Some(s) => s,
            None => {
                tracing::error!("No seat available for DnD start_drag");
                return (false, mime_types, data);
            },
        };

        // Create the data source with pre-serialized payload as user_data.
        let payload = DndSourceData { mime_types: mime_types.clone(), data: data.clone() };
        let source = dnd_manager.create_data_source(&self.queue_handle, payload);

        // Offer MIME types.
        for mime in &mime_types {
            source.offer(mime.clone());
        }

        // Set DnD actions on the source.
        use wayland_client::protocol::wl_data_device_manager::DndAction;
        let mut wl_actions = DndAction::empty();
        if actions & 1 != 0 {
            wl_actions |= DndAction::Copy;
        }
        if actions & 2 != 0 {
            wl_actions |= DndAction::Move;
        }
        if actions & 4 != 0 {
            wl_actions |= DndAction::Ask;
        }
        source.set_actions(wl_actions);

        // Create the icon surface for the drag visual.
        // If the caller provided custom ARGB pixels, use those; otherwise
        // fall back to a generic 48×48 semi-transparent rounded rectangle.
        let icon = {
            let mut pool = self.custom_cursor_pool.lock().unwrap();
            if let Some((w, h, pixels, scale)) = icon_pixels {
                crate::platform_impl::wayland::types::wayland_dnd::create_dnd_icon_from_pixels(
                    &self.compositor,
                    &mut pool,
                    &self.queue_handle,
                    w,
                    h,
                    &pixels,
                    scale,
                )
            } else {
                crate::platform_impl::wayland::types::wayland_dnd::create_dnd_icon_surface(
                    &self.compositor,
                    &mut pool,
                    &self.queue_handle,
                )
            }
        };
        let icon_surface_ref = icon.as_ref().map(|(s, _)| s);
        let had_icon = icon_surface_ref.is_some();

        let origin = self.window.wl_surface();
        data_device.start_drag(Some(&source), origin, icon_surface_ref, serial);

        // Keep icon surface + buffer alive for the drag duration.
        self.dnd_icon = icon;

        tracing::info!(
            serial,
            ?mime_types,
            has_icon = had_icon,
            "DnD: started drag from window (wl_data_device.start_drag)"
        );

        // Remember our own payload so a self-drag (a drop onto one of our own
        // windows) can read it DIRECTLY in `dnd_request_data` instead of the pipe:
        // the source `Send` handler runs on this same event-loop thread, so a
        // blocking pipe read would deadlock the whole process. Also record the
        // source window so source-side events reach the initiator. Overwriting
        // here also ensures a new drag never inherits a previous drag's state.
        {
            let wid = crate::platform_impl::wayland::make_wid(self.window.wl_surface());
            let pairs: Vec<(String, Vec<u8>)> =
                mime_types.iter().cloned().zip(data.iter().cloned()).collect();
            let mut shared = self.dnd_shared_offer.lock().unwrap();
            shared.self_source = Some(pairs);
            shared.source_window = Some(wid);
        }

        // Return the source info so the caller can store it in WinitState's dnd_session.
        (true, mime_types, data)
    }

    /// Accept a MIME type from the current DnD offer.
    ///
    /// Pass `None` to reject the current drag.
    pub fn dnd_accept_mime_type(&self, mime_type: Option<&str>) {
        let guard = self.dnd_shared_offer.lock().unwrap();
        if let Some(offer) = guard.current_offer.as_ref() {
            // Get the latest pointer serial for the accept call.
            let serial = self
                .pointers
                .iter()
                .filter_map(|p| p.upgrade())
                .map(|p| p.pointer().winit_data().latest_enter_serial())
                .find(|&s| s != 0)
                .unwrap_or(0);

            offer.accept(serial, mime_type.map(String::from));
            tracing::trace!(?mime_type, serial, "DnD: accept_mime_type");
        } else {
            tracing::warn!("DnD: accept_mime_type called with no current offer");
        }
    }

    /// Set the accepted DnD actions and preferred action.
    pub fn dnd_set_actions(&self, actions: u32, preferred: u32) {
        let guard = self.dnd_shared_offer.lock().unwrap();
        if let Some(offer) = guard.current_offer.as_ref() {
            use wayland_client::protocol::wl_data_device_manager::DndAction;
            let mut wl_actions = DndAction::empty();
            if actions & 1 != 0 {
                wl_actions |= DndAction::Copy;
            }
            if actions & 2 != 0 {
                wl_actions |= DndAction::Move;
            }
            if actions & 4 != 0 {
                wl_actions |= DndAction::Ask;
            }
            let mut wl_preferred = DndAction::empty();
            if preferred & 1 != 0 {
                wl_preferred |= DndAction::Copy;
            }
            if preferred & 2 != 0 {
                wl_preferred |= DndAction::Move;
            }
            if preferred & 4 != 0 {
                wl_preferred |= DndAction::Ask;
            }
            offer.set_actions(wl_actions, wl_preferred);
            tracing::trace!(?wl_actions, ?wl_preferred, "DnD: set_actions");
        } else {
            tracing::warn!("DnD: set_actions called with no current offer");
        }
    }

    /// Signal that the destination has finished processing the drop.
    pub fn dnd_finish(&self) {
        let mut guard = self.dnd_shared_offer.lock().unwrap();
        if let Some(offer) = guard.current_offer.take() {
            offer.finish();
            tracing::info!("DnD: finish - called offer.finish() and cleared offer");
        } else {
            tracing::warn!("DnD: finish called with no current offer");
        }
    }

    /// Request data from the current DnD offer for the specified MIME type.
    ///
    /// The data will be stored in `SharedDndOfferState::pending_data` for the
    /// event loop to pick up and dispatch as `DndWindowEvent::DataReceived`.
    pub fn dnd_request_data(&self, mime_type: &str) {
        use std::io::Read;
        use std::os::fd::AsFd;

        let mut guard = self.dnd_shared_offer.lock().unwrap();

        // Self-drag fast path: if WE are the source of this drag (a drop onto one
        // of our own windows), read the payload directly rather than via the pipe.
        // The source's `Send` handler runs on THIS event-loop thread, so a blocking
        // pipe read would deadlock the whole process (freezing every window).
        if let Some(pairs) = guard.self_source.as_ref() {
            if let Some((_, data)) = pairs.iter().find(|(m, _)| m == mime_type) {
                let data = data.clone();
                tracing::debug!(
                    mime_type,
                    bytes = data.len(),
                    "DnD: self-drag, data read directly"
                );
                guard.pending_data.push((mime_type.to_string(), data));
                return;
            }
        }

        let Some(offer) = guard.current_offer.as_ref() else {
            tracing::warn!("DnD: request_data called with no current offer");
            return;
        };

        // Create a pipe for the data transfer
        let (read_fd, write_fd) = match rustix::pipe::pipe() {
            Ok(fds) => fds,
            Err(e) => {
                tracing::error!(?e, "DnD: failed to create pipe for receive");
                return;
            },
        };

        tracing::trace!(?mime_type, "DnD: requesting data via receive");

        // Tell the source to write data to our pipe
        offer.receive(mime_type.to_string(), write_fd.as_fd());

        // Drop the write end so we get EOF when the source is done writing
        drop(write_fd);

        // We need to flush the Wayland connection so the source receives the request
        let _ = self.connection.flush();

        // Read the data from the pipe
        let mut read_file = std::fs::File::from(read_fd);
        let mut data = Vec::new();

        // Read with a reasonable buffer - the source should have written by now
        // after we flushed and the compositor forwarded the request
        if let Err(e) = read_file.read_to_end(&mut data) {
            tracing::error!(?e, "DnD: failed to read data from pipe");
            return;
        }

        tracing::trace!(mime_type, bytes = data.len(), "DnD: received data");

        // Store the data for the event loop to dispatch
        guard.pending_data.push((mime_type.to_string(), data));
    }

    /// Set the window title to a new value.
    ///
    /// This will automatically truncate the title to something meaningful.
    pub fn set_title(&mut self, mut title: String) {
        // Truncate the title to at most 1024 bytes, so that it does not blow up the protocol
        // messages
        if title.len() > 1024 {
            let mut new_len = 1024;
            while !title.is_char_boundary(new_len) {
                new_len -= 1;
            }
            title.truncate(new_len);
        }

        // Update the CSD title.
        if let Some(frame) = self.frame.as_mut() {
            frame.set_title(&title);
        }

        self.window.set_title(&title);
        self.title = title;
    }

    /// Mark the window as transparent.
    #[inline]
    pub fn set_transparent(&mut self, transparent: bool) {
        self.transparent = transparent;
        self.reload_transparency_hint();
    }

    /// Store the xdg-foreign import that parents this window to a foreign
    /// toplevel, keeping it alive for the window's lifetime.
    pub fn set_imported_parent(&mut self, imported: ImportedToplevel) {
        self.xdg_imported_parent = Some(imported);
    }

    /// Register text input on the top-level.
    #[inline]
    pub fn text_input_entered(&mut self, text_input: &ZwpTextInputV3) {
        if !self.text_inputs.iter().any(|t| t == text_input) {
            self.text_inputs.push(text_input.clone());
        }
    }

    /// The text input left the top-level.
    #[inline]
    pub fn text_input_left(&mut self, text_input: &ZwpTextInputV3) {
        if let Some(position) = self.text_inputs.iter().position(|t| t == text_input) {
            self.text_inputs.remove(position);
        }
    }

    /// Get the cached title.
    #[inline]
    pub fn title(&self) -> &str {
        &self.title
    }
}

impl Drop for WindowState {
    fn drop(&mut self) {
        if let Some(blur) = self.blur.take() {
            blur.release();
        }

        if let Some(fs) = self.fractional_scale.take() {
            fs.destroy();
        }

        if let Some(viewport) = self.viewport.take() {
            viewport.destroy();
        }

        // NOTE: the wl_surface used by the window is being cleaned up when
        // dropping SCTK `Window`.
    }
}

/// The state of the cursor grabs.
#[derive(Clone, Copy)]
struct GrabState {
    /// The grab mode requested by the user.
    user_grab_mode: CursorGrabMode,

    /// The current grab mode.
    current_grab_mode: CursorGrabMode,
}

impl GrabState {
    fn new() -> Self {
        Self { user_grab_mode: CursorGrabMode::None, current_grab_mode: CursorGrabMode::None }
    }
}

/// The state of the frame callback.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameCallbackState {
    /// No frame callback was requested.
    #[default]
    None,
    /// The frame callback was requested, but not yet arrived, the redraw events are throttled.
    Requested,
    /// The callback was marked as done, and user could receive redraw requested
    Received,
}

impl From<ResizeDirection> for XdgResizeEdge {
    fn from(value: ResizeDirection) -> Self {
        match value {
            ResizeDirection::North => XdgResizeEdge::Top,
            ResizeDirection::West => XdgResizeEdge::Left,
            ResizeDirection::NorthWest => XdgResizeEdge::TopLeft,
            ResizeDirection::NorthEast => XdgResizeEdge::TopRight,
            ResizeDirection::East => XdgResizeEdge::Right,
            ResizeDirection::SouthWest => XdgResizeEdge::BottomLeft,
            ResizeDirection::SouthEast => XdgResizeEdge::BottomRight,
            ResizeDirection::South => XdgResizeEdge::Bottom,
        }
    }
}

// NOTE: Rust doesn't allow `From<Option<Theme>>`.
#[cfg(feature = "sctk-adwaita")]
fn into_sctk_adwaita_config(theme: Option<Theme>) -> sctk_adwaita::FrameConfig {
    match theme {
        Some(Theme::Light) => sctk_adwaita::FrameConfig::light(),
        Some(Theme::Dark) => sctk_adwaita::FrameConfig::dark(),
        None => sctk_adwaita::FrameConfig::auto(),
    }
}