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

use std::{
    fmt, mem, thread,
    time::{Duration, Instant},
};

use extensions::ViewExtensions;
use gl::GlContextManager;
use image_cache::ImageCache;
use keyboard::KeyLocation;
use util::WinitToPx;
use winit::{
    event::{DeviceEvent, WindowEvent},
    event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
    keyboard::ModifiersState,
    monitor::MonitorHandle,
};

#[cfg(not(target_os = "android"))]
use winit::platform::modifier_supplement::KeyEventExtModifierSupplement;

#[cfg(target_os = "android")]
use winit::platform::android::EventLoopBuilderExtAndroid;

mod config;
mod display_list;
mod gl;
mod image_cache;
mod low_memory;
mod px_wr;
mod surface;
mod util;
mod window;

use surface::*;

pub mod extensions;

pub mod platform;

/// Webrender build used in the view-process.
#[doc(no_inline)]
pub use webrender;

/// OpenGL bindings used by Webrender.
#[doc(no_inline)]
pub use gleam;

use webrender::api::*;
use window::Window;
use zng_txt::Txt;
use zng_unit::{Dip, DipPoint, DipRect, DipSideOffsets, DipSize, Factor, Px, PxPoint, PxRect, PxToDip};
use zng_view_api::{
    api_extension::{ApiExtensionId, ApiExtensionPayload},
    dialog::{DialogId, FileDialog, MsgDialog, MsgDialogResponse},
    font::{FontFaceId, FontId, FontOptions, FontVariationName},
    image::{ImageId, ImageLoadedData, ImageMaskMode, ImageRequest, ImageTextureId},
    ipc::{IpcBytes, IpcBytesReceiver},
    keyboard::{Key, KeyCode, KeyState},
    mouse::ButtonId,
    touch::{TouchId, TouchUpdate},
    window::{
        CursorIcon, CursorImage, EventCause, EventFrameRendered, FocusIndicator, FrameRequest, FrameUpdateRequest, FrameWaitId,
        HeadlessOpenData, HeadlessRequest, MonitorId, MonitorInfo, VideoMode, WindowChanged, WindowId, WindowOpenData, WindowRequest,
        WindowState, WindowStateAll,
    },
    Inited, *,
};

use rustc_hash::FxHashMap;

#[cfg(ipc)]
zng_env::on_process_start!(|_| {
    if std::env::var("ZNG_VIEW_NO_INIT_START").is_err() {
        view_process_main();
    }
});

/// Runs the view-process server.
///
/// Note that this only needs to be called if the view-process is not built on the same executable, if
/// it is you only need to call [`zng_env::init!`] at the beginning of the executable main.
///
/// You can also disable start on init by setting the `ZNG_VIEW_NO_INIT_START` environment variable. In this
/// case you must manually call this function.
#[cfg(ipc)]
pub fn view_process_main() {
    let config = match ViewConfig::from_env() {
        Some(c) => c,
        None => return,
    };

    std::panic::set_hook(Box::new(init_abort));
    config.assert_version(false);
    let c = ipc::connect_view_process(config.server_name).expect("failed to connect to app-process");

    let mut ext = ViewExtensions::new();
    for e in extensions::VIEW_EXTENSIONS {
        e(&mut ext);
    }

    if config.headless {
        App::run_headless(c, ext);
    } else {
        App::run_headed(c, ext);
    }

    zng_env::exit(0)
}

#[cfg(ipc)]
#[doc(hidden)]
#[no_mangle]
pub extern "C" fn extern_view_process_main() {
    std::panic::set_hook(Box::new(ffi_abort));
    view_process_main()
}

/// Runs the view-process server in the current process and calls `run_app` to also
/// run the app in the current process. Note that `run_app` will be called in a different thread.
///
/// In this mode the app only uses a single process, reducing the memory footprint, but it is also not
/// resilient to video driver crashes, the view server **does not** respawn in this mode.
///
/// # Panics
///
/// Panics if not called in the main thread, this is a requirement of some operating systems.
///
/// ## Background Panics Warning
///
/// Note that `webrender` can freeze due to panics in worker threads without propagating
/// the panics to the main thread, this causes the app to stop responding while still receiving
/// event signals, causing the operating system to not detect that the app is frozen. It is recommended
/// that you build with `panic=abort` or use [`std::panic::set_hook`] to detect these background panics.
///
/// # Android
///
/// In Android builds `android::init_android_app` must be called before this function, otherwise it will panic.
pub fn run_same_process(run_app: impl FnOnce() + Send + 'static) {
    run_same_process_extended(run_app, ViewExtensions::new)
}

/// Like [`run_same_process`] but with custom API extensions.
///
/// Note that any linked [`view_process_extension!`] extensions are also run, after `ext`.
pub fn run_same_process_extended(run_app: impl FnOnce() + Send + 'static, ext: fn() -> ViewExtensions) {
    let app_thread = thread::Builder::new()
        .name("app".to_owned())
        .spawn(move || {
            // SAFETY: we exit the process in case of panic.
            if let Err(e) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(run_app)) {
                thread::spawn(|| {
                    // Sometimes the channel does not disconnect on panic,
                    // observed this issue on a panic in `AppExtension::init`.
                    //
                    // This workaround ensures that don't become a zombie process.
                    thread::sleep(std::time::Duration::from_secs(5));
                    eprintln!("run_same_process did not exit after 5s of a fatal panic, exiting now");
                    zng_env::exit(101);
                });
                // Propagate panic in case the normal disconnect/shutdown handler works.
                std::panic::resume_unwind(e);
            }
        })
        .unwrap();

    let config = ViewConfig::wait_same_process();
    config.assert_version(true);

    let c = ipc::connect_view_process(config.server_name).expect("failed to connect to app in same process");

    let mut ext = ext();
    for e in extensions::VIEW_EXTENSIONS {
        e(&mut ext);
    }

    if config.headless {
        App::run_headless(c, ext);
    } else {
        App::run_headed(c, ext);
    }

    if let Err(p) = app_thread.join() {
        std::panic::resume_unwind(p);
    }
}

#[cfg(ipc)]
#[doc(hidden)]
#[no_mangle]
pub extern "C" fn extern_run_same_process(patch: &StaticPatch, run_app: extern "C" fn()) {
    std::panic::set_hook(Box::new(ffi_abort));

    // SAFETY:
    // safe because it is called before any view related code in the library.
    unsafe {
        patch.install();
    }

    #[expect(clippy::redundant_closure)] // false positive
    run_same_process(move || run_app())
}
#[cfg(ipc)]
fn init_abort(info: &std::panic::PanicHookInfo) {
    panic_hook(info, "note: aborting to respawn");
}
#[cfg(ipc)]
fn ffi_abort(info: &std::panic::PanicHookInfo) {
    panic_hook(info, "note: aborting to avoid unwind across FFI");
}
#[cfg(ipc)]
fn panic_hook(info: &std::panic::PanicHookInfo, details: &str) {
    // see `default_hook` in https://doc.rust-lang.org/src/std/panicking.rs.html#182

    let panic = util::SuppressedPanic::from_hook(info, std::backtrace::Backtrace::force_capture());

    if crate::util::suppress_panic() {
        crate::util::set_suppressed_panic(panic);
    } else {
        eprintln!("{panic}\n{details}");
        zng_env::exit(101) // Rust panic exit code.
    }
}

/// The backend implementation.
pub(crate) struct App {
    headless: bool,

    exts: ViewExtensions,

    gl_manager: GlContextManager,
    winit_loop: util::WinitEventLoop,
    idle: IdleTrace,
    app_sender: AppEventSender,
    request_recv: flume::Receiver<RequestEvent>,

    response_sender: ipc::ResponseSender,
    event_sender: ipc::EventSender,
    image_cache: ImageCache,

    generation: ViewProcessGen,
    device_events: bool,

    windows: Vec<Window>,
    surfaces: Vec<Surface>,

    monitor_id_gen: MonitorId,
    pub monitors: Vec<(MonitorId, MonitorHandle)>,

    device_id_gen: DeviceId,
    devices: Vec<(DeviceId, winit::event::DeviceId)>,

    dialog_id_gen: DialogId,

    resize_frame_wait_id_gen: FrameWaitId,

    coalescing_event: Option<(Event, Instant)>,
    // winit only sends a CursorMove after CursorEntered if the cursor is in a different position,
    // but this makes refreshing hit-tests weird, do we hit-test the previous known point at each CursorEnter?
    //
    // This flag causes a MouseMove at the same previous position if no mouse move was send after CursorEnter and before
    // MainEventsCleared.
    cursor_entered_expect_move: Vec<WindowId>,

    #[cfg(windows)]
    skip_ralt: bool,

    pressed_modifiers: FxHashMap<(Key, KeyLocation), (DeviceId, KeyCode)>,
    pending_modifiers_update: Option<ModifiersState>,
    pending_modifiers_focus_clear: bool,

    #[cfg(not(any(windows, target_os = "android")))]
    arboard: Option<arboard::Clipboard>,

    #[cfg(windows)]
    low_memory_monitor: Option<low_memory::LowMemoryMonitor>,

    config_listener_exit: Option<Box<dyn FnOnce()>>,

    app_state: AppState,
    exited: bool,
}
impl fmt::Debug for App {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HeadlessBackend")
            .field("app_state", &self.app_state)
            .field("generation", &self.generation)
            .field("device_events", &self.device_events)
            .field("windows", &self.windows)
            .field("surfaces", &self.surfaces)
            .finish_non_exhaustive()
    }
}
impl winit::application::ApplicationHandler<AppEvent> for App {
    fn resumed(&mut self, winit_loop: &ActiveEventLoop) {
        if let AppState::Suspended = self.app_state {
            let mut winit_loop_guard = self.winit_loop.set(winit_loop);

            self.exts.resumed();
            self.generation = self.generation.next();
            let available_monitors = self.available_monitors();
            self.notify(Event::Inited(Inited {
                generation: self.generation,
                is_respawn: true,
                available_monitors,
                multi_click_config: config::multi_click_config(),
                key_repeat_config: config::key_repeat_config(),
                touch_config: config::touch_config(),
                font_aa: config::font_aa(),
                animations_config: config::animations_config(),
                locale_config: config::locale_config(),
                colors_config: config::colors_config(),
                chrome_config: config::chrome_config(),
                extensions: self.exts.api_extensions(),
            }));

            winit_loop_guard.unset(&mut self.winit_loop);
        } else {
            self.exts.init(&self.app_sender);
        }
        self.app_state = AppState::Resumed;

        self.update_memory_monitor(winit_loop);
    }

    fn window_event(&mut self, winit_loop: &ActiveEventLoop, window_id: winit::window::WindowId, event: WindowEvent) {
        let i = if let Some((i, _)) = self.windows.iter_mut().enumerate().find(|(_, w)| w.window_id() == window_id) {
            i
        } else {
            return;
        };

        let _s = tracing::trace_span!("on_window_event", ?event).entered();

        let mut winit_loop_guard = self.winit_loop.set(winit_loop);

        self.windows[i].on_window_event(&event);

        let id = self.windows[i].id();
        let scale_factor = self.windows[i].scale_factor();

        // Linux dialog is not actually modal, the parent window can continue to receive interaction events,
        // this macro return early when a modal dialog is open in Linux.
        #[cfg(any(
            target_os = "linux",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        let modal_dialog_active = self.windows[i].modal_dialog_active();
        #[cfg(any(
            target_os = "linux",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        macro_rules! linux_modal_dialog_bail {
            () => {
                if modal_dialog_active {
                    winit_loop_guard.unset(&mut self.winit_loop);
                    return;
                }
            };
        }
        #[cfg(not(any(
            target_os = "linux",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd"
        )))]
        macro_rules! linux_modal_dialog_bail {
            () => {};
        }

        match event {
            WindowEvent::RedrawRequested => self.windows[i].redraw(),
            WindowEvent::Resized(_) => {
                let size = if let Some(size) = self.windows[i].resized() {
                    size
                } else {
                    winit_loop_guard.unset(&mut self.winit_loop);
                    return;
                };

                // give the app 300ms to send a new frame, this is the collaborative way to
                // resize, it should reduce the changes of the user seeing the clear color.

                let deadline = Instant::now() + Duration::from_millis(300);

                // await already pending frames.
                if self.windows[i].is_rendering_frame() {
                    tracing::debug!("resize requested while still rendering");

                    // forward requests until webrender finishes or timeout.
                    while let Ok(req) = self.request_recv.recv_deadline(deadline) {
                        match req {
                            RequestEvent::Request(req) => {
                                let rsp = self.respond(req);
                                if rsp.must_be_send() {
                                    let _ = self.response_sender.send(rsp);
                                }
                            }
                            RequestEvent::FrameReady(id, msg) => {
                                self.on_frame_ready(id, msg);
                                if id == self.windows[i].id() {
                                    break;
                                }
                            }
                        }
                    }
                }

                if let Some(state) = self.windows[i].state_change() {
                    self.notify(Event::WindowChanged(WindowChanged::state_changed(id, state, EventCause::System)));
                }

                if let Some(handle) = self.windows[i].monitor_change() {
                    let m_id = self.monitor_handle_to_id(&handle);

                    self.notify(Event::WindowChanged(WindowChanged::monitor_changed(id, m_id, EventCause::System)));
                }

                let wait_id = Some(self.resize_frame_wait_id_gen.incr());

                // send event, the app code should send a frame in the new size as soon as possible.
                self.notify(Event::WindowChanged(WindowChanged::resized(id, size, EventCause::System, wait_id)));

                self.flush_coalesced();

                // "modal" loop, breaks in 300ms or when a frame is received.
                let mut received_frame = false;
                loop {
                    match self.request_recv.recv_deadline(deadline) {
                        Ok(req) => {
                            match req {
                                RequestEvent::Request(req) => {
                                    received_frame = req.is_frame(id, wait_id);
                                    if received_frame || req.affects_window_rect(id) {
                                        // received new frame
                                        let rsp = self.respond(req);
                                        if rsp.must_be_send() {
                                            let _ = self.response_sender.send(rsp);
                                        }
                                        break;
                                    } else {
                                        // received some other request, forward it.
                                        let rsp = self.respond(req);
                                        if rsp.must_be_send() {
                                            let _ = self.response_sender.send(rsp);
                                        }
                                    }
                                }
                                RequestEvent::FrameReady(id, msg) => self.on_frame_ready(id, msg),
                            }
                        }

                        Err(flume::RecvTimeoutError::Timeout) => {
                            // did not receive a new frame in time.
                            break;
                        }
                        Err(flume::RecvTimeoutError::Disconnected) => {
                            winit_loop_guard.unset(&mut self.winit_loop);
                            unreachable!()
                        }
                    }
                }

                // if we are still within 300ms, await webrender.
                if received_frame && deadline > Instant::now() {
                    // forward requests until webrender finishes or timeout.
                    while let Ok(req) = self.request_recv.recv_deadline(deadline) {
                        match req {
                            RequestEvent::Request(req) => {
                                let rsp = self.respond(req);
                                if rsp.must_be_send() {
                                    let _ = self.response_sender.send(rsp);
                                }
                            }
                            RequestEvent::FrameReady(id, msg) => {
                                self.on_frame_ready(id, msg);
                                if id == self.windows[i].id() {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            WindowEvent::Moved(_) => {
                let (global_position, position) = if let Some(p) = self.windows[i].moved() {
                    p
                } else {
                    winit_loop_guard.unset(&mut self.winit_loop);
                    return;
                };

                if let Some(state) = self.windows[i].state_change() {
                    self.notify(Event::WindowChanged(WindowChanged::state_changed(id, state, EventCause::System)));
                }

                self.notify(Event::WindowChanged(WindowChanged::moved(
                    id,
                    global_position,
                    position,
                    EventCause::System,
                )));

                if let Some(handle) = self.windows[i].monitor_change() {
                    let m_id = self.monitor_handle_to_id(&handle);

                    self.notify(Event::WindowChanged(WindowChanged::monitor_changed(id, m_id, EventCause::System)));
                }
            }
            WindowEvent::CloseRequested => {
                linux_modal_dialog_bail!();
                self.notify(Event::WindowCloseRequested(id))
            }
            WindowEvent::Destroyed => {
                self.windows.remove(i);
                self.notify(Event::WindowClosed(id));
            }
            WindowEvent::DroppedFile(file) => {
                linux_modal_dialog_bail!();
                self.notify(Event::DroppedFile { window: id, file })
            }
            WindowEvent::HoveredFile(file) => {
                linux_modal_dialog_bail!();
                self.notify(Event::HoveredFile { window: id, file })
            }
            WindowEvent::HoveredFileCancelled => {
                linux_modal_dialog_bail!();
                self.notify(Event::HoveredFileCancelled(id))
            }
            WindowEvent::Focused(mut focused) => {
                if self.windows[i].focused_changed(&mut focused) {
                    if focused {
                        self.notify(Event::FocusChanged { prev: None, new: Some(id) });

                        // some platforms (Wayland) don't change size on minimize/restore, so we check here too.
                        if let Some(state) = self.windows[i].state_change() {
                            self.notify(Event::WindowChanged(WindowChanged::state_changed(id, state, EventCause::System)));
                        }
                    } else {
                        self.pending_modifiers_focus_clear = true;
                        self.notify(Event::FocusChanged { prev: Some(id), new: None });
                    }
                }
            }
            WindowEvent::KeyboardInput {
                device_id,
                event,
                is_synthetic,
            } => {
                linux_modal_dialog_bail!();

                if !is_synthetic && self.windows[i].is_focused() {
                    // see the Window::focus comments.
                    #[cfg(windows)]
                    if self.skip_ralt {
                        if let winit::keyboard::PhysicalKey::Code(winit::keyboard::KeyCode::AltRight) = event.physical_key {
                            winit_loop_guard.unset(&mut self.winit_loop);
                            return;
                        }
                    }

                    let state = util::element_state_to_key_state(event.state);
                    #[cfg(not(target_os = "android"))]
                    let key = util::winit_key_to_key(event.key_without_modifiers());
                    let key_modified = util::winit_key_to_key(event.logical_key);
                    #[cfg(target_os = "android")]
                    let key = key_modified.clone();
                    let key_code = util::winit_physical_key_to_key_code(event.physical_key);
                    let key_location = util::winit_key_location_to_zng(event.location);
                    let d_id = self.device_id(device_id);

                    let mut send_event = true;

                    if key.is_modifier() {
                        match state {
                            KeyState::Pressed => {
                                send_event = self
                                    .pressed_modifiers
                                    .insert((key.clone(), key_location), (d_id, key_code))
                                    .is_none();
                            }
                            KeyState::Released => send_event = self.pressed_modifiers.remove(&(key.clone(), key_location)).is_some(),
                        }
                    }

                    if send_event {
                        self.notify(Event::KeyboardInput {
                            window: id,
                            device: d_id,
                            key_code,
                            key_location,
                            state,
                            text: match event.text {
                                Some(s) => Txt::from_str(s.as_str()),
                                #[cfg(target_os = "android")]
                                None => match (state, &key) {
                                    (KeyState::Pressed, Key::Char(c)) => Txt::from(*c),
                                    (KeyState::Pressed, Key::Str(s)) => s.clone(),
                                    _ => Txt::default(),
                                },
                                #[cfg(not(target_os = "android"))]
                                None => Txt::default(),
                            },
                            key,
                            key_modified,
                        });
                    }
                }
            }
            WindowEvent::ModifiersChanged(m) => {
                linux_modal_dialog_bail!();
                if self.windows[i].is_focused() {
                    self.pending_modifiers_update = Some(m.state());
                }
            }
            WindowEvent::CursorMoved { device_id, position, .. } => {
                linux_modal_dialog_bail!();

                let px_p = position.to_px();
                let p = px_p.to_dip(scale_factor);
                let d_id = self.device_id(device_id);

                let mut is_after_cursor_enter = false;
                if let Some(i) = self.cursor_entered_expect_move.iter().position(|&w| w == id) {
                    self.cursor_entered_expect_move.remove(i);
                    is_after_cursor_enter = true;
                }

                if self.windows[i].cursor_moved(p, d_id) || is_after_cursor_enter {
                    self.notify(Event::MouseMoved {
                        window: id,
                        device: d_id,
                        coalesced_pos: vec![],
                        position: p,
                    });
                }
            }
            WindowEvent::CursorEntered { device_id } => {
                linux_modal_dialog_bail!();
                if self.windows[i].cursor_entered() {
                    let d_id = self.device_id(device_id);
                    self.notify(Event::MouseEntered { window: id, device: d_id });
                    self.cursor_entered_expect_move.push(id);
                }
            }
            WindowEvent::CursorLeft { device_id } => {
                linux_modal_dialog_bail!();
                if self.windows[i].cursor_left() {
                    let d_id = self.device_id(device_id);
                    self.notify(Event::MouseLeft { window: id, device: d_id });

                    // unlikely but possible?
                    if let Some(i) = self.cursor_entered_expect_move.iter().position(|&w| w == id) {
                        self.cursor_entered_expect_move.remove(i);
                    }
                }
            }
            WindowEvent::MouseWheel {
                device_id, delta, phase, ..
            } => {
                linux_modal_dialog_bail!();
                let d_id = self.device_id(device_id);
                self.notify(Event::MouseWheel {
                    window: id,
                    device: d_id,
                    delta: util::winit_mouse_wheel_delta_to_zng(delta),
                    phase: util::winit_touch_phase_to_zng(phase),
                });
            }
            WindowEvent::MouseInput {
                device_id, state, button, ..
            } => {
                linux_modal_dialog_bail!();
                let d_id = self.device_id(device_id);
                self.notify(Event::MouseInput {
                    window: id,
                    device: d_id,
                    state: util::element_state_to_button_state(state),
                    button: util::winit_mouse_button_to_zng(button),
                });
            }
            WindowEvent::TouchpadPressure {
                device_id,
                pressure,
                stage,
            } => {
                linux_modal_dialog_bail!();
                let d_id = self.device_id(device_id);
                self.notify(Event::TouchpadPressure {
                    window: id,
                    device: d_id,
                    pressure,
                    stage,
                });
            }
            WindowEvent::AxisMotion { device_id, axis, value } => {
                linux_modal_dialog_bail!();
                let d_id = self.device_id(device_id);
                self.notify(Event::AxisMotion {
                    window: id,
                    device: d_id,
                    axis: AxisId(axis),
                    value,
                });
            }
            WindowEvent::Touch(t) => {
                let d_id = self.device_id(t.device_id);
                let position = t.location.to_px().to_dip(scale_factor);

                let notify = match t.phase {
                    winit::event::TouchPhase::Moved => self.windows[i].touch_moved(position, d_id, t.id),
                    winit::event::TouchPhase::Started => true,
                    winit::event::TouchPhase::Ended | winit::event::TouchPhase::Cancelled => {
                        self.windows[i].touch_end(d_id, t.id);
                        true
                    }
                };

                if notify {
                    self.notify(Event::Touch {
                        window: id,
                        device: d_id,
                        touches: vec![TouchUpdate {
                            phase: util::winit_touch_phase_to_zng(t.phase),
                            position,
                            force: t.force.map(util::winit_force_to_zng),
                            touch: TouchId(t.id),
                        }],
                    });
                }
            }
            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                let monitor;
                let mut is_monitor_change = false;

                if let Some(new_monitor) = self.windows[i].monitor_change() {
                    monitor = Some(new_monitor);
                    is_monitor_change = true;
                } else {
                    monitor = self.windows[i].monitor();
                }

                let monitor = if let Some(handle) = monitor {
                    self.monitor_handle_to_id(&handle)
                } else {
                    MonitorId::INVALID
                };

                if is_monitor_change {
                    self.notify(Event::WindowChanged(WindowChanged::monitor_changed(
                        id,
                        monitor,
                        EventCause::System,
                    )));
                }
                self.notify(Event::ScaleFactorChanged {
                    monitor,
                    windows: vec![id],
                    scale_factor: scale_factor as f32,
                });

                if let Some(size) = self.windows[i].resized() {
                    self.notify(Event::WindowChanged(WindowChanged::resized(id, size, EventCause::System, None)));
                }
            }
            WindowEvent::Ime(ime) => {
                linux_modal_dialog_bail!();

                match ime {
                    winit::event::Ime::Preedit(s, c) => {
                        let caret = c.unwrap_or((s.len(), s.len()));
                        let ime = Ime::Preview(s.into(), caret);
                        self.notify(Event::Ime { window: id, ime });
                    }
                    winit::event::Ime::Commit(s) => {
                        let ime = Ime::Commit(s.into());
                        self.notify(Event::Ime { window: id, ime });
                    }
                    winit::event::Ime::Enabled => {}
                    winit::event::Ime::Disabled => {}
                }
            }
            WindowEvent::ThemeChanged(_) => {}
            WindowEvent::Occluded(_) => {}
            WindowEvent::ActivationTokenDone { .. } => {}
            WindowEvent::PinchGesture { .. } => {}
            WindowEvent::RotationGesture { .. } => {}
            WindowEvent::DoubleTapGesture { .. } => {}
            WindowEvent::PanGesture { .. } => {}
        }

        winit_loop_guard.unset(&mut self.winit_loop);
    }

    fn new_events(&mut self, _winit_loop: &ActiveEventLoop, _cause: winit::event::StartCause) {
        self.idle.exit();

        #[cfg(windows)]
        if let winit::event::StartCause::ResumeTimeReached { .. } = _cause {
            self.update_memory_monitor(_winit_loop);
        }
    }

    fn user_event(&mut self, winit_loop: &ActiveEventLoop, ev: AppEvent) {
        let mut winit_loop_guard = self.winit_loop.set(winit_loop);
        match ev {
            AppEvent::Request => {
                while let Ok(req) = self.request_recv.try_recv() {
                    match req {
                        RequestEvent::Request(req) => {
                            let rsp = self.respond(req);
                            if rsp.must_be_send() && self.response_sender.send(rsp).is_err() {
                                // lost connection to app-process
                                self.exited = true;
                                self.winit_loop.exit();
                            }
                        }
                        RequestEvent::FrameReady(wid, msg) => self.on_frame_ready(wid, msg),
                    }
                }
            }
            AppEvent::Notify(ev) => self.notify(ev),
            AppEvent::WinitFocused(window_id, focused) => self.window_event(winit_loop, window_id, WindowEvent::Focused(focused)),
            AppEvent::RefreshMonitors => self.refresh_monitors(),
            AppEvent::ParentProcessExited => {
                self.exited = true;
                self.winit_loop.exit();
            }
            AppEvent::ImageLoaded(data) => {
                self.image_cache.loaded(data);
            }
            AppEvent::MonitorPowerChanged => {
                // if a window opens in power-off it is blank until redraw.
                for w in &mut self.windows {
                    w.redraw();
                }
            }
            AppEvent::InitDeviceEvents(enabled) => {
                self.init_device_events(enabled, Some(winit_loop));
            }
        }
        winit_loop_guard.unset(&mut self.winit_loop);
    }

    fn device_event(&mut self, winit_loop: &ActiveEventLoop, device_id: winit::event::DeviceId, event: DeviceEvent) {
        if self.device_events {
            let _s = tracing::trace_span!("on_device_event", ?event);

            let mut winit_loop_guard = self.winit_loop.set(winit_loop);

            let d_id = self.device_id(device_id);
            match event {
                DeviceEvent::Added => self.notify(Event::DeviceAdded(d_id)),
                DeviceEvent::Removed => self.notify(Event::DeviceRemoved(d_id)),
                DeviceEvent::MouseMotion { delta } => self.notify(Event::DeviceMouseMotion {
                    device: d_id,
                    delta: euclid::vec2(delta.0, delta.1),
                }),
                DeviceEvent::MouseWheel { delta } => self.notify(Event::DeviceMouseWheel {
                    device: d_id,
                    delta: util::winit_mouse_wheel_delta_to_zng(delta),
                }),
                DeviceEvent::Motion { axis, value } => self.notify(Event::DeviceMotion {
                    device: d_id,
                    axis: AxisId(axis),
                    value,
                }),
                DeviceEvent::Button { button, state } => self.notify(Event::DeviceButton {
                    device: d_id,
                    button: ButtonId(button),
                    state: util::element_state_to_button_state(state),
                }),
                DeviceEvent::Key(k) => self.notify(Event::DeviceKey {
                    device: d_id,
                    key_code: util::winit_physical_key_to_key_code(k.physical_key),
                    state: util::element_state_to_key_state(k.state),
                }),
            }

            winit_loop_guard.unset(&mut self.winit_loop);
        }
    }

    fn about_to_wait(&mut self, winit_loop: &ActiveEventLoop) {
        let mut winit_loop_guard = self.winit_loop.set(winit_loop);

        self.finish_cursor_entered_move();
        self.update_modifiers();
        self.flush_coalesced();
        #[cfg(windows)]
        {
            self.skip_ralt = false;
        }
        self.idle.enter();

        winit_loop_guard.unset(&mut self.winit_loop);
    }

    fn suspended(&mut self, _: &ActiveEventLoop) {
        #[cfg(target_os = "android")]
        if let Some(w) = &self.windows.first() {
            self.notify(Event::FocusChanged {
                prev: Some(w.id()),
                new: None,
            });
        }

        self.app_state = AppState::Suspended;
        self.windows.clear();
        self.surfaces.clear();
        self.image_cache.clear();
        self.exts.suspended();

        self.notify(Event::Suspended);
    }

    fn exiting(&mut self, event_loop: &ActiveEventLoop) {
        let _ = event_loop;
        if let Some(t) = self.config_listener_exit.take() {
            t();
        }
    }

    fn memory_warning(&mut self, winit_loop: &ActiveEventLoop) {
        let mut winit_loop_guard = self.winit_loop.set(winit_loop);

        self.image_cache.on_low_memory();
        for w in &mut self.windows {
            w.on_low_memory();
        }
        for s in &mut self.surfaces {
            s.on_low_memory();
        }
        self.exts.on_low_memory();
        self.notify(Event::LowMemory);

        winit_loop_guard.unset(&mut self.winit_loop);
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AppState {
    PreInitSuspended,
    Resumed,
    Suspended,
}

struct IdleTrace(Option<tracing::span::EnteredSpan>);
impl IdleTrace {
    pub fn enter(&mut self) {
        self.0 = Some(tracing::trace_span!("<winit-idle>").entered());
    }
    pub fn exit(&mut self) {
        self.0 = None;
    }
}
impl App {
    fn init_device_events(&mut self, enabled: bool, t: Option<&ActiveEventLoop>) {
        self.device_events = enabled;

        if let Some(t) = t {
            if enabled {
                t.listen_device_events(winit::event_loop::DeviceEvents::Always);
            } else {
                t.listen_device_events(winit::event_loop::DeviceEvents::Never);
            }
        } else {
            self.device_events = false;
        }
    }

    pub fn run_headless(ipc: ipc::ViewChannels, ext: ViewExtensions) {
        tracing::info!("running headless view-process");

        gl::warmup();

        let (app_sender, app_receiver) = flume::unbounded();
        let (request_sender, request_receiver) = flume::unbounded();
        let mut app = App::new(
            AppEventSender::Headless(app_sender, request_sender),
            ipc.response_sender,
            ipc.event_sender,
            request_receiver,
            ext,
        );
        app.headless = true;

        let winit_span = tracing::trace_span!("winit::EventLoop::new").entered();
        #[cfg(not(target_os = "android"))]
        let event_loop = EventLoop::builder().build().unwrap();
        #[cfg(target_os = "android")]
        let event_loop = EventLoop::builder()
            .with_android_app(platform::android::android_app())
            .build()
            .unwrap();
        drop(winit_span);

        let mut app = HeadlessApp {
            app,
            request_receiver: Some(ipc.request_receiver),
            app_receiver,
        };
        if let Err(e) = event_loop.run_app(&mut app) {
            if app.app.exited {
                // Ubuntu CI runs can get an error here:
                //
                //  "GLXBadWindow", error_code: 170, request_code: 150, minor_code: 32
                //
                // The app run exit ok, so we just log and ignore.
                tracing::error!("winit event loop error after app exit, {e}");
            } else {
                panic!("winit event loop error, {e}");
            }
        }

        struct HeadlessApp {
            app: App,
            request_receiver: Option<ipc::RequestReceiver>,
            app_receiver: flume::Receiver<AppEvent>,
        }
        impl winit::application::ApplicationHandler<()> for HeadlessApp {
            fn resumed(&mut self, winit_loop: &ActiveEventLoop) {
                let mut winit_loop_guard = self.app.winit_loop.set(winit_loop);

                self.app.resumed(winit_loop);
                self.app.start_receiving(self.request_receiver.take().unwrap());

                'app_loop: while !self.app.exited {
                    match self.app_receiver.recv() {
                        Ok(app_ev) => match app_ev {
                            AppEvent::Request => {
                                while let Ok(request) = self.app.request_recv.try_recv() {
                                    match request {
                                        RequestEvent::Request(request) => {
                                            let response = self.app.respond(request);
                                            if response.must_be_send() && self.app.response_sender.send(response).is_err() {
                                                self.app.exited = true;
                                                break 'app_loop;
                                            }
                                        }
                                        RequestEvent::FrameReady(id, msg) => {
                                            let r = if let Some(s) = self.app.surfaces.iter_mut().find(|s| s.id() == id) {
                                                Some(s.on_frame_ready(msg, &mut self.app.image_cache))
                                            } else {
                                                None
                                            };
                                            if let Some((frame_id, image)) = r {
                                                self.app.notify(Event::FrameRendered(EventFrameRendered {
                                                    window: id,
                                                    frame: frame_id,
                                                    frame_image: image,
                                                }));
                                            }
                                        }
                                    }
                                }
                            }
                            AppEvent::Notify(ev) => {
                                if self.app.event_sender.send(ev).is_err() {
                                    self.app.exited = true;
                                    break 'app_loop;
                                }
                            }
                            AppEvent::RefreshMonitors => {
                                panic!("no monitor info in headless mode")
                            }
                            AppEvent::WinitFocused(_, _) => {
                                panic!("no winit event loop in headless mode")
                            }
                            AppEvent::ParentProcessExited => {
                                self.app.exited = true;
                                break 'app_loop;
                            }
                            AppEvent::ImageLoaded(data) => {
                                self.app.image_cache.loaded(data);
                            }
                            AppEvent::MonitorPowerChanged => {} // headless
                            AppEvent::InitDeviceEvents(enabled) => {
                                self.app.init_device_events(enabled, None);
                            }
                        },
                        Err(_) => {
                            self.app.exited = true;
                            break 'app_loop;
                        }
                    }
                }

                self.app.winit_loop.exit();

                winit_loop_guard.unset(&mut self.app.winit_loop);
            }

            fn window_event(&mut self, _: &ActiveEventLoop, _: winit::window::WindowId, _: WindowEvent) {}

            fn suspended(&mut self, event_loop: &ActiveEventLoop) {
                self.app.suspended(event_loop);
            }
        }
    }

    pub fn run_headed(ipc: ipc::ViewChannels, ext: ViewExtensions) {
        tracing::info!("running headed view-process");

        gl::warmup();

        let winit_span = tracing::trace_span!("winit::EventLoop::new").entered();
        #[cfg(not(target_os = "android"))]
        let event_loop = EventLoop::with_user_event().build().unwrap();
        #[cfg(target_os = "android")]
        let event_loop = EventLoop::with_user_event()
            .with_android_app(platform::android::android_app())
            .build()
            .unwrap();
        drop(winit_span);
        let app_sender = event_loop.create_proxy();

        let (request_sender, request_receiver) = flume::unbounded();
        let mut app = App::new(
            AppEventSender::Headed(app_sender, request_sender),
            ipc.response_sender,
            ipc.event_sender,
            request_receiver,
            ext,
        );
        app.start_receiving(ipc.request_receiver);

        app.config_listener_exit = config::spawn_listener(app.app_sender.clone());

        if let Err(e) = event_loop.run_app(&mut app) {
            if app.exited {
                tracing::error!("winit event loop error after app exit, {e}");
            } else {
                panic!("winit event loop error, {e}");
            }
        }
    }

    fn new(
        app_sender: AppEventSender,
        response_sender: ipc::ResponseSender,
        event_sender: ipc::EventSender,
        request_recv: flume::Receiver<RequestEvent>,
        mut exts: ViewExtensions,
    ) -> Self {
        exts.renderer("zng-view.webrender_debug", extensions::RendererDebugExt::new);
        #[cfg(windows)]
        {
            exts.window("zng-view.prefer_angle", extensions::PreferAngleExt::new);
        }
        let mut idle = IdleTrace(None);
        idle.enter();
        App {
            headless: false,
            exts,
            idle,
            gl_manager: GlContextManager::default(),
            image_cache: ImageCache::new(app_sender.clone()),
            app_sender,
            request_recv,
            response_sender,
            event_sender,
            winit_loop: util::WinitEventLoop::default(),
            generation: ViewProcessGen::INVALID,
            device_events: false,
            windows: vec![],
            surfaces: vec![],
            monitors: vec![],
            monitor_id_gen: MonitorId::INVALID,
            devices: vec![],
            device_id_gen: DeviceId::INVALID,
            dialog_id_gen: DialogId::INVALID,
            resize_frame_wait_id_gen: FrameWaitId::INVALID,
            coalescing_event: None,
            cursor_entered_expect_move: Vec::with_capacity(1),
            app_state: AppState::PreInitSuspended,
            exited: false,
            #[cfg(windows)]
            skip_ralt: false,
            pressed_modifiers: FxHashMap::default(),
            pending_modifiers_update: None,
            pending_modifiers_focus_clear: false,
            config_listener_exit: None,

            #[cfg(not(any(windows, target_os = "android")))]
            arboard: None,
            #[cfg(windows)]
            low_memory_monitor: low_memory::LowMemoryMonitor::new(),
        }
    }

    fn start_receiving(&mut self, mut request_recv: ipc::RequestReceiver) {
        let app_sender = self.app_sender.clone();
        thread::spawn(move || {
            while let Ok(r) = request_recv.recv() {
                if let Err(ipc::Disconnected) = app_sender.request(r) {
                    break;
                }
            }
            let _ = app_sender.send(AppEvent::ParentProcessExited);
        });
    }

    fn monitor_handle_to_id(&mut self, handle: &MonitorHandle) -> MonitorId {
        if let Some((id, _)) = self.monitors.iter().find(|(_, h)| h == handle) {
            *id
        } else {
            self.refresh_monitors();
            if let Some((id, _)) = self.monitors.iter().find(|(_, h)| h == handle) {
                *id
            } else {
                MonitorId::INVALID
            }
        }
    }

    fn update_modifiers(&mut self) {
        // Winit monitors the modifiers keys directly, so this generates events
        // that are not send to the window by the operating system.
        //
        // An Example:
        // In Windows +LShift +RShift -LShift -RShift only generates +LShift +RShift -RShift, notice the missing -LShift.

        if mem::take(&mut self.pending_modifiers_focus_clear) && self.windows.iter().all(|w| !w.is_focused()) {
            self.pressed_modifiers.clear();
        }

        if let Some(m) = self.pending_modifiers_update.take() {
            if let Some(id) = self.windows.iter().find(|w| w.is_focused()).map(|w| w.id()) {
                let mut notify = vec![];
                self.pressed_modifiers.retain(|(key, location), (d_id, s_code)| {
                    let mut retain = true;
                    if matches!(key, Key::Super) && !m.super_key() {
                        retain = false;
                        notify.push(Event::KeyboardInput {
                            window: id,
                            device: *d_id,
                            key_code: *s_code,
                            state: KeyState::Released,
                            key: key.clone(),
                            key_location: *location,
                            key_modified: key.clone(),
                            text: Txt::from_str(""),
                        });
                    }
                    if matches!(key, Key::Shift) && !m.shift_key() {
                        retain = false;
                        notify.push(Event::KeyboardInput {
                            window: id,
                            device: *d_id,
                            key_code: *s_code,
                            state: KeyState::Released,
                            key: key.clone(),
                            key_location: *location,
                            key_modified: key.clone(),
                            text: Txt::from_str(""),
                        });
                    }
                    if matches!(key, Key::Alt | Key::AltGraph) && !m.alt_key() {
                        retain = false;
                        notify.push(Event::KeyboardInput {
                            window: id,
                            device: *d_id,
                            key_code: *s_code,
                            state: KeyState::Released,
                            key: key.clone(),
                            key_location: *location,
                            key_modified: key.clone(),
                            text: Txt::from_str(""),
                        });
                    }
                    if matches!(key, Key::Ctrl) && !m.control_key() {
                        retain = false;
                        notify.push(Event::KeyboardInput {
                            window: id,
                            device: *d_id,
                            key_code: *s_code,
                            state: KeyState::Released,
                            key: key.clone(),
                            key_location: *location,
                            key_modified: key.clone(),
                            text: Txt::from_str(""),
                        });
                    }
                    retain
                });

                for ev in notify {
                    self.notify(ev);
                }
            }
        }
    }

    fn refresh_monitors(&mut self) {
        let mut monitors = Vec::with_capacity(self.monitors.len());

        let mut changed = false;

        for (fresh_handle, (id, handle)) in self.winit_loop.available_monitors().zip(&self.monitors) {
            let id = if &fresh_handle == handle {
                *id
            } else {
                changed = true;
                self.monitor_id_gen.incr()
            };
            monitors.push((id, fresh_handle))
        }

        if changed {
            self.monitors = monitors;

            let monitors = self.available_monitors();
            self.notify(Event::MonitorsChanged(monitors));
        }
    }

    fn on_frame_ready(&mut self, window_id: WindowId, msg: FrameReadyMsg) {
        let _s = tracing::trace_span!("on_frame_ready").entered();

        if let Some(w) = self.windows.iter_mut().find(|w| w.id() == window_id) {
            let r = w.on_frame_ready(msg, &mut self.image_cache);

            let _ = self.event_sender.send(Event::FrameRendered(EventFrameRendered {
                window: window_id,
                frame: r.frame_id,
                frame_image: r.image,
            }));

            if r.first_frame {
                let size = w.size();
                self.notify(Event::WindowChanged(WindowChanged::resized(window_id, size, EventCause::App, None)));
            }
        } else if let Some(s) = self.surfaces.iter_mut().find(|w| w.id() == window_id) {
            let (frame_id, image) = s.on_frame_ready(msg, &mut self.image_cache);

            self.notify(Event::FrameRendered(EventFrameRendered {
                window: window_id,
                frame: frame_id,
                frame_image: image,
            }))
        }
    }

    pub(crate) fn notify(&mut self, event: Event) {
        let now = Instant::now();
        if let Some((mut coal, timestamp)) = self.coalescing_event.take() {
            let r = if now.saturating_duration_since(timestamp) >= Duration::from_millis(16) {
                Err(event)
            } else {
                coal.coalesce(event)
            };
            match r {
                Ok(()) => self.coalescing_event = Some((coal, timestamp)),
                Err(event) => match (&mut coal, event) {
                    (
                        Event::KeyboardInput {
                            window,
                            device,
                            state,
                            text,
                            ..
                        },
                        Event::KeyboardInput {
                            window: n_window,
                            device: n_device,
                            text: n_text,
                            ..
                        },
                    ) if !n_text.is_empty() && *window == n_window && *device == n_device && *state == KeyState::Pressed => {
                        // text after key-press
                        if text.is_empty() {
                            *text = n_text;
                        } else {
                            text.push_str(&n_text);
                        };
                        self.coalescing_event = Some((coal, now));
                    }
                    (_, event) => {
                        let mut error = self.event_sender.send(coal).is_err();
                        error |= self.event_sender.send(event).is_err();

                        if error {
                            let _ = self.app_sender.send(AppEvent::ParentProcessExited);
                        }
                    }
                },
            }
        } else {
            self.coalescing_event = Some((event, now));
        }

        if self.headless {
            self.flush_coalesced();
        }
    }

    pub(crate) fn finish_cursor_entered_move(&mut self) {
        let mut moves = vec![];
        for window_id in self.cursor_entered_expect_move.drain(..) {
            if let Some(w) = self.windows.iter().find(|w| w.id() == window_id) {
                let (position, device) = w.last_cursor_pos();
                moves.push(Event::MouseMoved {
                    window: w.id(),
                    device,
                    coalesced_pos: vec![],
                    position,
                });
            }
        }
        for ev in moves {
            self.notify(ev);
        }
    }

    /// Send pending coalesced events.
    pub(crate) fn flush_coalesced(&mut self) {
        if let Some((coal, _)) = self.coalescing_event.take() {
            if self.event_sender.send(coal).is_err() {
                let _ = self.app_sender.send(AppEvent::ParentProcessExited);
            }
        }
    }

    #[track_caller]
    fn assert_resumed(&self) {
        assert_eq!(self.app_state, AppState::Resumed);
    }

    fn with_window<R>(&mut self, id: WindowId, action: impl FnOnce(&mut Window) -> R, not_found: impl FnOnce() -> R) -> R {
        self.assert_resumed();
        self.windows.iter_mut().find(|w| w.id() == id).map(action).unwrap_or_else(|| {
            tracing::error!("headed window `{id:?}` not found, will return fallback result");
            not_found()
        })
    }

    fn monitor_id(&mut self, handle: &MonitorHandle) -> MonitorId {
        if let Some((id, _)) = self.monitors.iter().find(|(_, h)| h == handle) {
            *id
        } else {
            let id = self.monitor_id_gen.incr();
            self.monitors.push((id, handle.clone()));
            id
        }
    }

    fn device_id(&mut self, device_id: winit::event::DeviceId) -> DeviceId {
        if let Some((id, _)) = self.devices.iter().find(|(_, id)| *id == device_id) {
            *id
        } else {
            let id = self.device_id_gen.incr();
            self.devices.push((id, device_id));
            id
        }
    }

    fn available_monitors(&mut self) -> Vec<(MonitorId, MonitorInfo)> {
        let _span = tracing::trace_span!("available_monitors").entered();

        let primary = self.winit_loop.primary_monitor();
        self.winit_loop
            .available_monitors()
            .map(|m| {
                let id = self.monitor_id(&m);
                let is_primary = primary.as_ref().map(|h| h == &m).unwrap_or(false);
                let mut info = util::monitor_handle_to_info(&m);
                info.is_primary = is_primary;
                (id, info)
            })
            .collect()
    }

    fn update_memory_monitor(&mut self, _winit_loop: &ActiveEventLoop) {
        #[cfg(windows)]
        if let Some(m) = &mut self.low_memory_monitor {
            if m.notify() {
                use winit::application::ApplicationHandler as _;
                self.memory_warning(_winit_loop);
            }
            _winit_loop.set_control_flow(winit::event_loop::ControlFlow::wait_duration(Duration::from_secs(5)));
        }
    }
}
macro_rules! with_window_or_surface {
    ($self:ident, $id:ident, |$el:ident|$action:expr, ||$fallback:expr) => {
        if let Some($el) = $self.windows.iter_mut().find(|w| w.id() == $id) {
            $action
        } else if let Some($el) = $self.surfaces.iter_mut().find(|w| w.id() == $id) {
            $action
        } else {
            tracing::error!("window `{:?}` not found, will return fallback result", $id);
            $fallback
        }
    };
}
impl Drop for App {
    fn drop(&mut self) {
        if let Some(f) = self.config_listener_exit.take() {
            f();
        }
    }
}
impl App {
    fn open_headless_impl(&mut self, config: HeadlessRequest) -> HeadlessOpenData {
        self.assert_resumed();
        let surf = Surface::open(
            self.generation,
            config,
            &self.winit_loop,
            &mut self.gl_manager,
            self.exts.new_window(),
            self.exts.new_renderer(),
            self.app_sender.clone(),
        );
        let render_mode = surf.render_mode();

        self.surfaces.push(surf);

        HeadlessOpenData { render_mode }
    }

    #[cfg(not(any(windows, target_os = "android")))]
    fn arboard(&mut self) -> Result<&mut arboard::Clipboard, clipboard::ClipboardError> {
        if self.arboard.is_none() {
            match arboard::Clipboard::new() {
                Ok(c) => self.arboard = Some(c),
                Err(e) => return Err(util::arboard_to_clip(e)),
            }
        }
        Ok(self.arboard.as_mut().unwrap())
    }
}

impl Api for App {
    fn init(&mut self, gen: ViewProcessGen, is_respawn: bool, device_events: bool, headless: bool) {
        if self.exited {
            panic!("cannot restart exited");
        }

        self.generation = gen;
        self.device_events = device_events;
        self.headless = headless;

        self.app_sender.send(AppEvent::InitDeviceEvents(device_events)).unwrap();

        let available_monitors = self.available_monitors();
        self.notify(Event::Inited(Inited {
            generation: gen,
            is_respawn,
            available_monitors,
            multi_click_config: config::multi_click_config(),
            key_repeat_config: config::key_repeat_config(),
            touch_config: config::touch_config(),
            font_aa: config::font_aa(),
            animations_config: config::animations_config(),
            locale_config: config::locale_config(),
            colors_config: config::colors_config(),
            chrome_config: config::chrome_config(),
            extensions: self.exts.api_extensions(),
        }));
    }

    fn exit(&mut self) {
        self.assert_resumed();
        self.exited = true;
        if let Some(t) = self.config_listener_exit.take() {
            t();
        }
        // not really, but just to exit winit loop
        let _ = self.app_sender.send(AppEvent::ParentProcessExited);
    }

    fn open_window(&mut self, mut config: WindowRequest) {
        let _s = tracing::debug_span!("open", ?config).entered();

        config.state.clamp_size();
        config.enforce_kiosk();

        if self.headless {
            let id = config.id;
            let data = self.open_headless_impl(HeadlessRequest {
                id: config.id,
                scale_factor: Factor(1.0),
                size: config.state.restore_rect.size,
                render_mode: config.render_mode,
                extensions: config.extensions,
            });
            let msg = WindowOpenData {
                render_mode: data.render_mode,
                monitor: None,
                position: (PxPoint::zero(), DipPoint::zero()),
                size: config.state.restore_rect.size,
                scale_factor: Factor(1.0),
                safe_padding: DipSideOffsets::zero(),
                state: WindowStateAll {
                    state: WindowState::Fullscreen,
                    global_position: PxPoint::zero(),
                    restore_rect: DipRect::from_size(config.state.restore_rect.size),
                    restore_state: WindowState::Fullscreen,
                    min_size: DipSize::zero(),
                    max_size: DipSize::new(Dip::MAX, Dip::MAX),
                    chrome_visible: false,
                },
            };

            self.notify(Event::WindowOpened(id, msg));
        } else {
            self.assert_resumed();

            #[cfg(target_os = "android")]
            if !self.windows.is_empty() {
                tracing::error!("android can only have one window");
                return;
            }

            let id = config.id;
            let win = Window::open(
                self.generation,
                config.icon.and_then(|i| self.image_cache.get(i)).and_then(|i| i.icon()),
                config
                    .cursor_image
                    .and_then(|(i, h)| self.image_cache.get(i).and_then(|i| i.cursor(h, &self.winit_loop))),
                config,
                &self.winit_loop,
                &mut self.gl_manager,
                self.exts.new_window(),
                self.exts.new_renderer(),
                self.app_sender.clone(),
            );

            let msg = WindowOpenData {
                monitor: win.monitor().map(|h| self.monitor_id(&h)),
                position: win.inner_position(),
                size: win.size(),
                scale_factor: win.scale_factor(),
                render_mode: win.render_mode(),
                state: win.state(),
                safe_padding: win.safe_padding(),
            };

            self.windows.push(win);

            self.notify(Event::WindowOpened(id, msg));

            // winit does not notify focus for Android window
            #[cfg(target_os = "android")]
            {
                self.windows.last_mut().unwrap().focused_changed(&mut true);
                self.notify(Event::FocusChanged { prev: None, new: Some(id) });
            }
        }
    }

    fn open_headless(&mut self, config: HeadlessRequest) {
        let _s = tracing::debug_span!("open_headless", ?config).entered();

        let id = config.id;
        let msg = self.open_headless_impl(config);

        self.notify(Event::HeadlessOpened(id, msg));
    }

    fn close(&mut self, id: WindowId) {
        let _s = tracing::debug_span!("close_window", ?id);

        self.assert_resumed();
        if let Some(i) = self.windows.iter().position(|w| w.id() == id) {
            let _ = self.windows.swap_remove(i);
        }
        if let Some(i) = self.surfaces.iter().position(|w| w.id() == id) {
            let _ = self.surfaces.swap_remove(i);
        }
    }

    fn set_title(&mut self, id: WindowId, title: Txt) {
        self.with_window(id, |w| w.set_title(title), || ())
    }

    fn set_visible(&mut self, id: WindowId, visible: bool) {
        self.with_window(id, |w| w.set_visible(visible), || ())
    }

    fn set_always_on_top(&mut self, id: WindowId, always_on_top: bool) {
        self.with_window(id, |w| w.set_always_on_top(always_on_top), || ())
    }

    fn set_movable(&mut self, id: WindowId, movable: bool) {
        self.with_window(id, |w| w.set_movable(movable), || ())
    }

    fn set_resizable(&mut self, id: WindowId, resizable: bool) {
        self.with_window(id, |w| w.set_resizable(resizable), || ())
    }

    fn set_taskbar_visible(&mut self, id: WindowId, visible: bool) {
        self.with_window(id, |w| w.set_taskbar_visible(visible), || ())
    }

    fn bring_to_top(&mut self, id: WindowId) {
        self.with_window(id, |w| w.bring_to_top(), || ())
    }

    fn set_state(&mut self, id: WindowId, state: WindowStateAll) {
        if let Some(w) = self.windows.iter_mut().find(|w| w.id() == id) {
            if w.set_state(state.clone()) {
                let mut change = WindowChanged::state_changed(id, state, EventCause::App);

                change.size = w.resized();
                change.position = w.moved();
                if let Some(handle) = w.monitor_change() {
                    let monitor = self.monitor_handle_to_id(&handle);
                    change.monitor = Some(monitor);
                }

                let _ = self.app_sender.send(AppEvent::Notify(Event::WindowChanged(change)));
            }
        }
    }

    fn set_headless_size(&mut self, renderer: WindowId, size: DipSize, scale_factor: Factor) {
        self.assert_resumed();
        if let Some(surf) = self.surfaces.iter_mut().find(|s| s.id() == renderer) {
            surf.set_size(size, scale_factor)
        }
    }

    fn set_video_mode(&mut self, id: WindowId, mode: VideoMode) {
        self.with_window(id, |w| w.set_video_mode(mode), || ())
    }

    fn set_icon(&mut self, id: WindowId, icon: Option<ImageId>) {
        let icon = icon.and_then(|i| self.image_cache.get(i)).and_then(|i| i.icon());
        self.with_window(id, |w| w.set_icon(icon), || ())
    }

    fn set_focus_indicator(&mut self, id: WindowId, request: Option<FocusIndicator>) {
        self.with_window(id, |w| w.set_focus_request(request), || ())
    }

    fn focus(&mut self, id: WindowId) -> FocusResult {
        #[cfg(windows)]
        {
            let (r, s) = self.with_window(id, |w| w.focus(), || (FocusResult::Requested, false));
            self.skip_ralt = s;
            r
        }

        #[cfg(not(windows))]
        {
            self.with_window(id, |w| w.focus(), || FocusResult::Requested)
        }
    }

    fn drag_move(&mut self, id: WindowId) {
        self.with_window(id, |w| w.drag_move(), || ())
    }

    fn drag_resize(&mut self, id: WindowId, direction: zng_view_api::window::ResizeDirection) {
        self.with_window(id, |w| w.drag_resize(direction), || ())
    }

    fn set_enabled_buttons(&mut self, id: WindowId, buttons: zng_view_api::window::WindowButton) {
        self.with_window(id, |w| w.set_enabled_buttons(buttons), || ())
    }

    fn open_title_bar_context_menu(&mut self, id: WindowId, position: DipPoint) {
        self.with_window(id, |w| w.open_title_bar_context_menu(position), || ())
    }

    fn set_cursor(&mut self, id: WindowId, icon: Option<CursorIcon>) {
        self.with_window(id, |w| w.set_cursor(icon), || ())
    }

    fn set_cursor_image(&mut self, id: WindowId, icon: Option<CursorImage>) {
        let icon = icon.and_then(|img| self.image_cache.get(img.img).and_then(|i| i.cursor(img.hotspot, &self.winit_loop)));
        self.with_window(id, |w| w.set_cursor_image(icon), || ());
    }

    fn set_ime_area(&mut self, id: WindowId, area: Option<DipRect>) {
        self.with_window(id, |w| w.set_ime_area(area), || ())
    }

    fn image_decoders(&mut self) -> Vec<Txt> {
        image_cache::DECODERS.iter().map(|&s| Txt::from_static(s)).collect()
    }

    fn image_encoders(&mut self) -> Vec<Txt> {
        image_cache::ENCODERS.iter().map(|&s| Txt::from_static(s)).collect()
    }

    fn add_image(&mut self, request: ImageRequest<IpcBytes>) -> ImageId {
        self.image_cache.add(request)
    }

    fn add_image_pro(&mut self, request: ImageRequest<IpcBytesReceiver>) -> ImageId {
        self.image_cache.add_pro(request)
    }

    fn forget_image(&mut self, id: ImageId) {
        self.image_cache.forget(id)
    }

    fn encode_image(&mut self, id: ImageId, format: Txt) {
        self.image_cache.encode(id, format)
    }

    fn use_image(&mut self, id: WindowId, image_id: ImageId) -> ImageTextureId {
        if let Some(img) = self.image_cache.get(image_id) {
            with_window_or_surface!(self, id, |w| w.use_image(img), || ImageTextureId::INVALID)
        } else {
            ImageTextureId::INVALID
        }
    }

    fn update_image_use(&mut self, id: WindowId, texture_id: ImageTextureId, image_id: ImageId) {
        if let Some(img) = self.image_cache.get(image_id) {
            with_window_or_surface!(self, id, |w| w.update_image(texture_id, img), || ())
        }
    }

    fn delete_image_use(&mut self, id: WindowId, texture_id: ImageTextureId) {
        with_window_or_surface!(self, id, |w| w.delete_image(texture_id), || ())
    }

    fn add_font_face(&mut self, id: WindowId, bytes: IpcBytes, index: u32) -> FontFaceId {
        with_window_or_surface!(self, id, |w| w.add_font_face(bytes.to_vec(), index), || FontFaceId::INVALID)
    }

    fn delete_font_face(&mut self, id: WindowId, font_face_id: FontFaceId) {
        with_window_or_surface!(self, id, |w| w.delete_font_face(font_face_id), || ())
    }

    fn add_font(
        &mut self,
        id: WindowId,
        font_face_id: FontFaceId,
        glyph_size: Px,
        options: FontOptions,
        variations: Vec<(FontVariationName, f32)>,
    ) -> FontId {
        with_window_or_surface!(self, id, |w| w.add_font(font_face_id, glyph_size, options, variations), || {
            FontId::INVALID
        })
    }

    fn delete_font(&mut self, id: WindowId, font_id: FontId) {
        with_window_or_surface!(self, id, |w| w.delete_font(font_id), || ())
    }

    fn set_capture_mode(&mut self, id: WindowId, enabled: bool) {
        self.with_window(id, |w| w.set_capture_mode(enabled), || ())
    }

    fn frame_image(&mut self, id: WindowId, mask: Option<ImageMaskMode>) -> ImageId {
        with_window_or_surface!(self, id, |w| w.frame_image(&mut self.image_cache, mask), || ImageId::INVALID)
    }

    fn frame_image_rect(&mut self, id: WindowId, rect: PxRect, mask: Option<ImageMaskMode>) -> ImageId {
        with_window_or_surface!(self, id, |w| w.frame_image_rect(&mut self.image_cache, rect, mask), || {
            ImageId::INVALID
        })
    }

    fn render(&mut self, id: WindowId, frame: FrameRequest) {
        with_window_or_surface!(self, id, |w| w.render(frame), || ())
    }

    fn render_update(&mut self, id: WindowId, frame: FrameUpdateRequest) {
        with_window_or_surface!(self, id, |w| w.render_update(frame), || ())
    }

    fn access_update(&mut self, id: WindowId, update: access::AccessTreeUpdate) {
        if let Some(s) = self.windows.iter_mut().find(|s| s.id() == id) {
            s.access_update(update, &self.app_sender);
        }
    }

    fn message_dialog(&mut self, id: WindowId, dialog: MsgDialog) -> DialogId {
        let r_id = self.dialog_id_gen.incr();
        if let Some(s) = self.windows.iter_mut().find(|s| s.id() == id) {
            s.message_dialog(dialog, r_id, self.app_sender.clone());
        } else {
            let r = MsgDialogResponse::Error(Txt::from_static("window not found"));
            let _ = self.app_sender.send(AppEvent::Notify(Event::MsgDialogResponse(r_id, r)));
        }
        r_id
    }

    fn file_dialog(&mut self, id: WindowId, dialog: FileDialog) -> DialogId {
        let r_id = self.dialog_id_gen.incr();
        if let Some(s) = self.windows.iter_mut().find(|s| s.id() == id) {
            s.file_dialog(dialog, r_id, self.app_sender.clone());
        } else {
            let r = MsgDialogResponse::Error(Txt::from_static("window not found"));
            let _ = self.app_sender.send(AppEvent::Notify(Event::MsgDialogResponse(r_id, r)));
        };
        r_id
    }

    #[cfg(windows)]
    fn read_clipboard(&mut self, data_type: clipboard::ClipboardType) -> Result<clipboard::ClipboardData, clipboard::ClipboardError> {
        match data_type {
            clipboard::ClipboardType::Text => {
                let _clip = clipboard_win::Clipboard::new_attempts(10).map_err(util::clipboard_win_to_clip)?;

                clipboard_win::get(clipboard_win::formats::Unicode)
                    .map_err(util::clipboard_win_to_clip)
                    .map(|s: String| clipboard::ClipboardData::Text(Txt::from_str(&s)))
            }
            clipboard::ClipboardType::Image => {
                let _clip = clipboard_win::Clipboard::new_attempts(10).map_err(util::clipboard_win_to_clip)?;

                let bitmap = clipboard_win::get(clipboard_win::formats::Bitmap).map_err(util::clipboard_win_to_clip)?;

                let id = self.image_cache.add(ImageRequest {
                    format: image::ImageDataFormat::FileExtension(Txt::from_str("bmp")),
                    data: IpcBytes::from_vec(bitmap),
                    max_decoded_len: u64::MAX,
                    downscale: None,
                    mask: None,
                });
                Ok(clipboard::ClipboardData::Image(id))
            }
            clipboard::ClipboardType::FileList => {
                let _clip = clipboard_win::Clipboard::new_attempts(10).map_err(util::clipboard_win_to_clip)?;

                clipboard_win::get(clipboard_win::formats::FileList)
                    .map_err(util::clipboard_win_to_clip)
                    .map(clipboard::ClipboardData::FileList)
            }
            clipboard::ClipboardType::Extension(_) => Err(clipboard::ClipboardError::NotSupported),
        }
    }

    #[cfg(windows)]
    fn write_clipboard(&mut self, data: clipboard::ClipboardData) -> Result<(), clipboard::ClipboardError> {
        use zng_txt::formatx;

        match data {
            clipboard::ClipboardData::Text(t) => {
                let _clip = clipboard_win::Clipboard::new_attempts(10).map_err(util::clipboard_win_to_clip)?;

                clipboard_win::set(clipboard_win::formats::Unicode, t).map_err(util::clipboard_win_to_clip)
            }
            clipboard::ClipboardData::Image(id) => {
                let _clip = clipboard_win::Clipboard::new_attempts(10).map_err(util::clipboard_win_to_clip)?;

                if let Some(img) = self.image_cache.get(id) {
                    let mut bmp = vec![];
                    img.encode(::image::ImageFormat::Bmp, &mut bmp)
                        .map_err(|e| clipboard::ClipboardError::Other(formatx!("{e:?}")))?;
                    clipboard_win::set(clipboard_win::formats::Bitmap, bmp).map_err(util::clipboard_win_to_clip)
                } else {
                    Err(clipboard::ClipboardError::Other(Txt::from_str("image not found")))
                }
            }
            clipboard::ClipboardData::FileList(l) => {
                use clipboard_win::Setter;
                let _clip = clipboard_win::Clipboard::new_attempts(10).map_err(util::clipboard_win_to_clip)?;

                // clipboard_win does not implement write from PathBuf
                let strs = l.into_iter().map(|p| p.display().to_string()).collect::<Vec<String>>();
                clipboard_win::formats::FileList
                    .write_clipboard(&strs)
                    .map_err(util::clipboard_win_to_clip)
            }
            clipboard::ClipboardData::Extension { .. } => Err(clipboard::ClipboardError::NotSupported),
        }
    }

    #[cfg(not(any(windows, target_os = "android")))]
    fn read_clipboard(&mut self, data_type: clipboard::ClipboardType) -> Result<clipboard::ClipboardData, clipboard::ClipboardError> {
        match data_type {
            clipboard::ClipboardType::Text => self
                .arboard()?
                .get_text()
                .map_err(util::arboard_to_clip)
                .map(|s| clipboard::ClipboardData::Text(zng_txt::Txt::from(s))),
            clipboard::ClipboardType::Image => {
                let bitmap = self.arboard()?.get_image().map_err(util::arboard_to_clip)?;
                let mut data = bitmap.bytes.into_owned();
                for rgba in data.chunks_exact_mut(4) {
                    rgba.swap(0, 2); // to bgra
                }
                let id = self.image_cache.add(image::ImageRequest {
                    format: image::ImageDataFormat::Bgra8 {
                        size: zng_unit::PxSize::new(Px(bitmap.width as _), Px(bitmap.height as _)),
                        ppi: None,
                    },
                    data: IpcBytes::from_vec(data),
                    max_decoded_len: u64::MAX,
                    downscale: None,
                    mask: None,
                });
                Ok(clipboard::ClipboardData::Image(id))
            }
            clipboard::ClipboardType::FileList => Err(clipboard::ClipboardError::NotSupported),
            clipboard::ClipboardType::Extension(_) => Err(clipboard::ClipboardError::NotSupported),
        }
    }

    #[cfg(not(any(windows, target_os = "android")))]
    fn write_clipboard(&mut self, data: clipboard::ClipboardData) -> Result<(), clipboard::ClipboardError> {
        match data {
            clipboard::ClipboardData::Text(t) => self.arboard()?.set_text(t).map_err(util::arboard_to_clip),
            clipboard::ClipboardData::Image(id) => {
                self.arboard()?;
                if let Some(img) = self.image_cache.get(id) {
                    let size = img.size();
                    let mut data = img.pixels().clone().to_vec();
                    for rgba in data.chunks_exact_mut(4) {
                        rgba.swap(0, 2); // to rgba
                    }
                    let board = self.arboard()?;
                    let _ = board.set_image(arboard::ImageData {
                        width: size.width.0 as _,
                        height: size.height.0 as _,
                        bytes: std::borrow::Cow::Owned(data),
                    });
                    Ok(())
                } else {
                    Err(clipboard::ClipboardError::Other(zng_txt::Txt::from_static("image not found")))
                }
            }
            clipboard::ClipboardData::FileList(_) => Err(clipboard::ClipboardError::NotSupported),
            clipboard::ClipboardData::Extension { .. } => Err(clipboard::ClipboardError::NotSupported),
        }
    }

    #[cfg(target_os = "android")]
    fn read_clipboard(&mut self, data_type: clipboard::ClipboardType) -> Result<clipboard::ClipboardData, clipboard::ClipboardError> {
        let _ = data_type;
        Err(clipboard::ClipboardError::Other(Txt::from_static(
            "clipboard not implemented for Android",
        )))
    }

    #[cfg(target_os = "android")]
    fn write_clipboard(&mut self, data: clipboard::ClipboardData) -> Result<(), clipboard::ClipboardError> {
        let _ = data;
        Err(clipboard::ClipboardError::Other(Txt::from_static(
            "clipboard not implemented for Android",
        )))
    }

    fn set_system_shutdown_warn(&mut self, id: WindowId, reason: Txt) {
        self.with_window(id, move |w| w.set_system_shutdown_warn(reason), || ())
    }

    fn third_party_licenses(&mut self) -> Vec<zng_tp_licenses::LicenseUsed> {
        #[cfg(feature = "bundle_licenses")]
        {
            zng_tp_licenses::include_bundle!()
        }
        #[cfg(not(feature = "bundle_licenses"))]
        {
            vec![]
        }
    }

    fn app_extension(&mut self, extension_id: ApiExtensionId, extension_request: ApiExtensionPayload) -> ApiExtensionPayload {
        self.exts.call_command(extension_id, extension_request)
    }

    fn window_extension(
        &mut self,
        id: WindowId,
        extension_id: ApiExtensionId,
        extension_request: ApiExtensionPayload,
    ) -> ApiExtensionPayload {
        self.with_window(
            id,
            |w| w.window_extension(extension_id, extension_request),
            || ApiExtensionPayload::invalid_request(extension_id, "window not found"),
        )
    }

    fn render_extension(
        &mut self,
        id: WindowId,
        extension_id: ApiExtensionId,
        extension_request: ApiExtensionPayload,
    ) -> ApiExtensionPayload {
        with_window_or_surface!(self, id, |w| w.render_extension(extension_id, extension_request), || {
            ApiExtensionPayload::invalid_request(extension_id, "renderer not found")
        })
    }
}

/// Message inserted in the event loop from the view-process.
#[derive(Debug)]
pub(crate) enum AppEvent {
    /// One or more [`RequestEvent`] are pending in the request channel.
    Request,
    /// Notify an event.
    Notify(Event),
    /// Re-query available monitors and send update event.
    #[cfg_attr(not(windows), allow(unused))]
    RefreshMonitors,

    /// Simulate winit window event Focused.
    #[cfg_attr(not(windows), allow(unused))]
    WinitFocused(winit::window::WindowId, bool),

    /// Lost connection with app-process.
    ParentProcessExited,

    /// Image finished decoding, must call [`ImageCache::loaded`].
    ImageLoaded(ImageLoadedData),

    /// Send after init with `device_events`.
    InitDeviceEvents(bool),

    /// Send when monitor was turned on/off by the OS, need to redraw all screens to avoid blank issue.
    #[allow(unused)]
    MonitorPowerChanged,
}

/// Message inserted in the request loop from the view-process.
///
/// These *events* are detached from [`AppEvent`] so that we can continue receiving requests while
/// the main loop is blocked in a resize operation.
#[derive(Debug)]
enum RequestEvent {
    /// A request from the [`Api`].
    Request(Request),
    /// Webrender finished rendering a frame, ready for redraw.
    FrameReady(WindowId, FrameReadyMsg),
}

#[derive(Debug)]
pub(crate) struct FrameReadyMsg {
    pub composite_needed: bool,
}

/// Abstraction over channel senders that can inject [`AppEvent`] in the app loop.
#[derive(Clone)]
pub(crate) enum AppEventSender {
    Headed(EventLoopProxy<AppEvent>, flume::Sender<RequestEvent>),
    Headless(flume::Sender<AppEvent>, flume::Sender<RequestEvent>),
}
impl AppEventSender {
    /// Send an event.
    fn send(&self, ev: AppEvent) -> Result<(), ipc::Disconnected> {
        match self {
            AppEventSender::Headed(p, _) => p.send_event(ev).map_err(|_| ipc::Disconnected),
            AppEventSender::Headless(p, _) => p.send(ev).map_err(|_| ipc::Disconnected),
        }
    }

    /// Send a request.
    fn request(&self, req: Request) -> Result<(), ipc::Disconnected> {
        match self {
            AppEventSender::Headed(_, p) => p.send(RequestEvent::Request(req)).map_err(|_| ipc::Disconnected),
            AppEventSender::Headless(_, p) => p.send(RequestEvent::Request(req)).map_err(|_| ipc::Disconnected),
        }?;
        self.send(AppEvent::Request)
    }

    /// Send a frame-ready.
    fn frame_ready(&self, window_id: WindowId, msg: FrameReadyMsg) -> Result<(), ipc::Disconnected> {
        match self {
            AppEventSender::Headed(_, p) => p.send(RequestEvent::FrameReady(window_id, msg)).map_err(|_| ipc::Disconnected),
            AppEventSender::Headless(_, p) => p.send(RequestEvent::FrameReady(window_id, msg)).map_err(|_| ipc::Disconnected),
        }?;
        self.send(AppEvent::Request)
    }
}

/// Webrender frame-ready notifier.
pub(crate) struct WrNotifier {
    id: WindowId,
    sender: AppEventSender,
}
impl WrNotifier {
    pub fn create(id: WindowId, sender: AppEventSender) -> Box<dyn RenderNotifier> {
        Box::new(WrNotifier { id, sender })
    }
}
impl RenderNotifier for WrNotifier {
    fn clone(&self) -> Box<dyn RenderNotifier> {
        Box::new(Self {
            id: self.id,
            sender: self.sender.clone(),
        })
    }

    fn wake_up(&self, _: bool) {}

    fn new_frame_ready(&self, _document_id: DocumentId, _scrolled: bool, composite_needed: bool, _: FramePublishId) {
        let msg = FrameReadyMsg { composite_needed };
        let _ = self.sender.frame_ready(self.id, msg);
    }
}

#[cfg(target_arch = "wasm32")]
compile_error!("zng-view does not support Wasm");