waterui-ffi 0.5.1

FFI bindings for the WaterUI cross-platform UI framework
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
//! FFI bindings for the `GpuSurface` raw view.
//!
//! This module provides the FFI interface for high-performance GPU rendering
//! using wgpu. Uses a shared GPU context for efficient multi-view rendering.
//!
//! The native backend is responsible for:
//! 1. Creating persistent renderer state with `waterui_gpu_surface_create`
//! 2. Providing somewhere to draw, which differs by platform:
//!    - Android attaches a `SurfaceView`'s `ANativeWindow` with
//!      `waterui_gpu_surface_attach`, replaces it as its lifecycle demands, and
//!      renders into the swapchain with `waterui_gpu_surface_render`.
//!    - Apple owns the presentation memory itself: a pair of `IOSurface`-backed
//!      `MTLTexture`s shown as a plain layer's `contents`. It declares the
//!      target format once with `waterui_gpu_surface_prepare_metal_texture` and
//!      renders each frame with `waterui_gpu_surface_render_to_metal_texture`,
//!      so there is no swapchain to attach and `attach`, `detach` and `render`
//!      panic there.
//! 3. Calling into whichever of those applies when the redraw callback fires
//! 4. Calling `waterui_gpu_surface_drop` when the semantic view is destroyed
//!
//! # Thread affinity
//!
//! `WuiGpuSurfaceState` is single-threaded `Rc`/`RefCell` state. Every entry
//! point taking a `WuiGpuSurfaceState` pointer must run on the thread that
//! created the state (the renderer's owning thread), whether or not an
//! individual safety comment repeats it. The only cross-thread contracts are
//! the installed redraw callback (safe to fire from any thread) and the
//! capture-completion callback, which runs on the shared GPU completion
//! thread.

use core::ffi::c_void;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};

use alloc::boxed::Box;
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
use alloc::vec;
use executor_core::spawn_local;
use futures::FutureExt;

#[cfg(any(target_os = "macos", target_os = "ios"))]
use {
    objc2::{rc::Retained, runtime::ProtocolObject},
    objc2_metal::{MTLPixelFormat, MTLTexture, MTLTextureType},
    wgpu_hal::{Api, api::Metal as MetalApi},
};

use waterui_graphics::gpu_surface::{
    GestureState, GpuContext, GpuFrame, GpuSurface, PointerState, RedrawHandle,
};
use waterui_graphics::shared_context::{GpuRuntime, GpuSubmissionCompletionDriver};

use waterui_core::Str;

use crate::components::layouting::layout::{WuiProposalSize, WuiViewDimensions};
use crate::{IntoFFI, IntoRust, WuiStr};

/// FFI representation of a `GpuSurface` view.
///
/// This struct is passed to the native backend when rendering the view tree.
/// The native backend consumes it with `waterui_gpu_surface_create`, then owns
/// the returned state for the semantic view lifetime.
#[repr(C)]
#[derive(Debug)]
pub struct WuiGpuSurface {
    /// Opaque pointer to the boxed `GpuSurface`.
    /// This is consumed during state creation and should not be used after.
    pub surface: *mut c_void,
    /// Whether this surface should register as a picture-in-picture host.
    pub has_picture_in_picture_host_id: bool,
    /// Stable picture-in-picture host id when `has_picture_in_picture_host_id` is true.
    pub picture_in_picture_host_id: u64,
}

impl IntoFFI for GpuSurface {
    type FFI = WuiGpuSurface;

    fn into_ffi(self) -> Self::FFI {
        // Box the GpuSurface for FFI transfer.
        let boxed = Box::new(self);
        let picture_in_picture_host_id = boxed.picture_in_picture_host();
        let ptr = Box::into_raw(boxed).cast::<c_void>();
        WuiGpuSurface {
            surface: ptr,
            has_picture_in_picture_host_id: picture_in_picture_host_id.is_some(),
            picture_in_picture_host_id: picture_in_picture_host_id.unwrap_or(0),
        }
    }
}

// Generate waterui_gpu_surface_id() and waterui_force_as_gpu_surface()
ffi_view!(GpuSurface, WuiGpuSurface, gpu_surface);

/// Opaque state held by the native backend after initialization.
///
/// Owns the semantic renderer and environment GPU runtime independently of the
/// currently attached presentation surface.
pub struct WuiGpuSurfaceState {
    /// Explicit environment-owned GPU runtime used by this semantic view.
    runtime: GpuRuntime,
    /// Native presentation surface currently attached to this semantic GPU view.
    ///
    /// Android may replace the underlying `ANativeWindow` while preserving the
    /// `GpuView` and its persistent resources. Apple platforms present through
    /// host-owned textures instead and never attach a swapchain.
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    wgpu_surface: Option<wgpu::Surface<'static>>,
    /// Surface configuration
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    config: Option<wgpu::SurfaceConfiguration>,
    /// The `ANativeWindow` `layer` was — kept so the surface can be recreated
    /// on a rebuilt runtime after device loss without another attach call.
    /// Valid while `wgpu_surface` is `Some`; stale otherwise.
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    attached_layer: *mut c_void,
    /// The HDR preference `attach` configured the surface with.
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    attached_prefers_hdr: bool,
    /// The [`SharedGpuContext`] generation `wgpu_surface`, `config` and the
    /// renderer were built under. Anything else means they belong to a dead
    /// device and must be recreated before the next frame.
    #[cfg(not(any(target_os = "macos", target_os = "ios")))]
    context_generation: u64,
    /// The format selected when asynchronous renderer setup starts.
    renderer_format: Cell<Option<wgpu::TextureFormat>>,
    /// Where this surface's frame is drawn when an enclosing capture wants it.
    ///
    /// Android's HWUI records a `SurfaceView` as a cleared hole, so a surface
    /// inside a filtered or effected subtree is missing from that subtree's
    /// captured buffer and is drawn into it from here instead. Kept across
    /// frames and reallocated only when the size or the renderer's format
    /// changes.
    #[cfg(target_os = "android")]
    composite_texture: Option<wgpu::Texture>,
    /// Becomes true only after the local setup future has completed.
    setup_ready: Rc<Cell<bool>>,
    /// Maximum MSAA sample count requested by the public `GpuSurface` API.
    msaa_max_samples: core::num::NonZeroU32,
    /// Main-thread semantic renderer and environment. Setup temporarily moves
    /// this value into its local future, then returns it to the slot.
    semantic: Rc<RefCell<Option<GpuSurfaceSemantic>>>,
    /// Layout priority does not change during renderer setup.
    priority: i32,
    /// Current width from layout
    current_width: u32,
    /// Current height from layout
    current_height: u32,
    /// Current pointer/cursor state
    pointer_state: PointerState,
    /// Current gesture state (pinch, pan, double-tap)
    gesture_state: GestureState,
    /// Animation clock start for frame timing.
    start_time: Instant,
    /// Timestamp of the previous render.
    last_frame_time: Instant,
    /// Redraw handle for external redraw triggers.
    redraw_handle: RedrawHandle,
    /// Whether the semantic GPU view takes its own keyboard, IME and scroll
    /// input, captured once when this state is created.
    ///
    /// `GpuView::wants_input_events` answers a registration-time question, and
    /// hosts ask it before the asynchronous renderer setup has necessarily
    /// finished — while the semantic slot is temporarily empty. Caching the
    /// answer keeps it available for the whole life of the state.
    wants_input_events: bool,
}

impl core::fmt::Debug for WuiGpuSurfaceState {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("WuiGpuSurfaceState")
            .field("current_width", &self.current_width)
            .field("current_height", &self.current_height)
            .finish_non_exhaustive()
    }
}

impl WuiGpuSurfaceState {
    /// Whether the semantic GPU view takes its own input.
    ///
    /// See the field of the same name for why the answer is cached rather than
    /// asked of the renderer on every call.
    pub(super) const fn wants_input_events(&self) -> bool {
        self.wants_input_events
    }

    /// The semantic GPU view's text caret, in logical surface-local coordinates.
    ///
    /// `None` while the renderer's asynchronous setup is still running, and
    /// whenever the view has no caret to place an input-method panel against.
    pub(super) fn ime_caret(&self) -> Option<kurbo::Rect> {
        self.semantic
            .borrow()
            .as_ref()
            .and_then(|semantic| semantic.gpu_surface.ime_caret())
    }

    /// What the semantic GPU view says about itself, for a screen reader.
    ///
    /// `None` while the renderer's asynchronous setup is still running, and
    /// whenever the view has nothing to say about its pixels.
    fn accessibility_label(&self) -> Option<Str> {
        self.semantic
            .borrow()
            .as_ref()
            .and_then(|semantic| semantic.gpu_surface.accessibility_label())
            .map(Str::from)
    }

    /// The semantic content the GPU view carries, for a screen reader.
    ///
    /// `None` while the renderer's asynchronous setup is still running, and
    /// whenever the view publishes no semantic value.
    fn accessibility_value(&self) -> Option<Str> {
        self.semantic
            .borrow()
            .as_ref()
            .and_then(|semantic| semantic.gpu_surface.accessibility_value())
            .map(Str::from)
    }
}

/// What this surface's content says about itself, for a screen reader.
///
/// A surface is an opaque rectangle to the platform's accessibility layer:
/// whatever the formula, chart or diagram inside it means, nothing outside the
/// content can read it back off the pixels. A host names the surface's element
/// with this when the application named it nothing, so an explicit label from
/// the application always wins.
///
/// Ask again after each frame. A view whose content follows a signal re-draws
/// and re-describes itself at the same moment, and the answer is empty until
/// asynchronous renderer setup finishes, which is before the first frame.
///
/// # Returns
///
/// An owning [`WuiStr`], empty when this surface has nothing to say — which a
/// host treats the same way it treats a view that never had a label. There is
/// deliberately no third state: "no label" and "the empty label" are the same
/// instruction to a screen reader, so the ABI does not carry a distinction
/// nothing acts on.
///
/// # Safety
///
/// `state` must be a valid pointer returned by
/// [`waterui_gpu_surface_create`], on the thread that created it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_accessibility_label(
    state: *const WuiGpuSurfaceState,
) -> WuiStr {
    // SAFETY: the caller contract requires `state` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let state = unsafe { crate::borrow_ffi(state) };
    state.accessibility_label().unwrap_or_default().into_ffi()
}

/// The semantic value this surface's content carries, for a screen reader.
///
/// This is the value channel's counterpart to
/// [`waterui_gpu_surface_accessibility_label`]: the content's own semantic
/// payload — a formula's spoken mathematics, a chart's summary — which a host
/// publishes on the surface's element so an application-supplied label does not
/// have to stand in for it.
///
/// Ask again after each frame, for the same reason as the label: a view whose
/// content follows a signal re-draws and re-describes itself at the same
/// moment, and the answer is empty until asynchronous renderer setup finishes.
///
/// # Returns
///
/// An owning [`WuiStr`], empty when this surface publishes no value. There is
/// no third state: "no value" and "the empty value" are the same instruction
/// to a screen reader.
///
/// # Safety
///
/// `state` must be a valid pointer returned by
/// [`waterui_gpu_surface_create`], on the thread that created it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_accessibility_value(
    state: *const WuiGpuSurfaceState,
) -> WuiStr {
    // SAFETY: the caller contract requires `state` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let state = unsafe { crate::borrow_ffi(state) };
    state.accessibility_value().unwrap_or_default().into_ffi()
}

struct GpuSurfaceSemantic {
    gpu_surface: GpuSurface,
    env: waterui::Environment,
}

/// Submission fence returned after encoding an external-texture capture.
///
/// The renderer state remains on its owning UI thread. Native consumes this
/// token by registering a completion with
/// [`waterui_gpu_capture_fence_on_complete`].
#[derive(Debug)]
pub struct WuiGpuCaptureFence {
    completion_driver: GpuSubmissionCompletionDriver,
    submission: wgpu::SubmissionIndex,
}

impl WuiGpuCaptureFence {
    /// Wraps one queue submission as the token native waits on.
    ///
    /// Every external capture path ends here, whichever platform primitive it
    /// started from, so `waterui_gpu_capture_fence_on_complete` is the one way a
    /// backend learns that the GPU is finished with the memory it lent us.
    // Only the platforms with an external capture path produce a fence: Metal
    // on Apple, `AHardwareBuffer` on Android. Elsewhere the type is consumed by
    // `waterui_gpu_capture_fence_on_complete` alone, so a constructor would be
    // dead code.
    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        all(target_os = "android", feature = "gpu")
    ))]
    pub(crate) const fn new(
        completion_driver: GpuSubmissionCompletionDriver,
        submission: wgpu::SubmissionIndex,
    ) -> Self {
        Self {
            completion_driver,
            submission,
        }
    }
}

/// Completion function invoked after an external GPU capture submission.
pub type WuiGpuCaptureCompletionCallback = unsafe extern "C" fn(context: *mut c_void);

/// Releases the foreign completion context after its callback returns.
pub type WuiGpuCaptureCompletionDrop = unsafe extern "C" fn(context: *mut c_void);

struct ForeignGpuCaptureCompletion {
    context: usize,
    callback: WuiGpuCaptureCompletionCallback,
    drop: WuiGpuCaptureCompletionDrop,
}

impl ForeignGpuCaptureCompletion {
    fn complete(self) {
        // SAFETY: `callback` and `context` were registered together by the backend,
        // and the context outlives this handle.
        unsafe { (self.callback)(self.context as *mut c_void) };
    }
}

impl Drop for ForeignGpuCaptureCompletion {
    fn drop(&mut self) {
        // SAFETY: `drop` and `context` are one registration from the backend, and
        // `Drop` runs once.
        unsafe { (self.drop)(self.context as *mut c_void) };
    }
}

fn advance_frame_timing(state: &mut WuiGpuSurfaceState) -> (Duration, Duration) {
    let now = Instant::now();
    let elapsed = now.duration_since(state.start_time);
    let delta = now
        .duration_since(state.last_frame_time)
        .min(Duration::from_millis(100));
    state.last_frame_time = now;
    (elapsed, delta)
}

/// Native callback invoked when an idle `GpuSurface` becomes dirty.
pub type WuiGpuSurfaceRedrawCallback = unsafe extern "C" fn(context: *mut c_void);

struct ForeignRedrawTarget {
    context: usize,
    wake: WuiGpuSurfaceRedrawCallback,
    drop: WuiGpuSurfaceRedrawCallback,
}

// SAFETY: native installs callbacks whose context is explicitly documented as
// callable and releasable from any thread. The target owns that context until
// its `drop` callback runs.
unsafe impl Send for ForeignRedrawTarget {}
// SAFETY: see the `Send` implementation. The wake callback must be thread-safe.
unsafe impl Sync for ForeignRedrawTarget {}

impl ForeignRedrawTarget {
    fn wake(&self) {
        // SAFETY: `wake` and `context` were registered together by the backend, and
        // the context outlives this waker.
        unsafe { (self.wake)(self.context as *mut c_void) };
    }
}

impl Drop for ForeignRedrawTarget {
    fn drop(&mut self) {
        // SAFETY: `drop` and `context` are one registration from the backend, and
        // `Drop` runs once.
        unsafe { (self.drop)(self.context as *mut c_void) };
    }
}

/// Renderer-driven HDR preference exported to native backends before init.
///
/// `has_preference = false` means the surface should follow backend/global policy.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct WuiGpuSurfaceHdrPreference {
    /// Whether the renderer provided an explicit HDR/SDR preference.
    pub has_preference: bool,
    /// Explicit preferred dynamic range when `has_preference` is true.
    pub prefers_hdr: bool,
}

/// Returns the renderer-driven HDR preference for a `WuiGpuSurface`.
///
/// This must be called before `waterui_gpu_surface_create` consumes the surface.
///
/// # Safety
///
/// - `surface` must be a valid pointer obtained from `waterui_force_as_gpu_surface`
/// - `surface` must not have been consumed by `waterui_gpu_surface_create`
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_hdr_preference(
    surface: *const WuiGpuSurface,
) -> WuiGpuSurfaceHdrPreference {
    // SAFETY: the caller contract requires `surface` to be a valid descriptor alive
    // for this call.
    let wui_surface = unsafe { &*surface };
    // SAFETY: a descriptor that has not been consumed holds a live `GpuSurface`; the
    // consuming path below nulls the field, so a stale read cannot reach here.
    let gpu_surface = unsafe { &*(wui_surface.surface as *const GpuSurface) };
    let explicit = gpu_surface.resolved_hdr_preference();
    WuiGpuSurfaceHdrPreference {
        has_preference: explicit.is_some(),
        prefers_hdr: explicit.unwrap_or(false),
    }
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn attached_surface_format(
    capabilities: &wgpu::SurfaceCapabilities,
    renderer_format: Option<wgpu::TextureFormat>,
    prefer_hdr: bool,
) -> wgpu::TextureFormat {
    renderer_format.map_or_else(
        || {
            waterui_graphics::gpu_surface::preferred_surface_format_with_preference(
                capabilities,
                prefer_hdr,
            )
        },
        |format| {
            assert!(
                capabilities.formats.contains(&format),
                "waterui_gpu_surface_attach: replacement surface does not support the renderer's established format {format:?}"
            );
            format
        },
    )
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn create_attached_surface(
    gpu: &waterui_graphics::shared_context::SharedGpuContext,
    layer: *mut c_void,
    width: u32,
    height: u32,
    renderer_format: Option<wgpu::TextureFormat>,
    prefer_hdr: bool,
) -> (wgpu::Surface<'static>, wgpu::SurfaceConfiguration) {
    assert!(
        width > 0 && height > 0,
        "waterui_gpu_surface_attach: native surface dimensions must be non-zero, got {width}x{height}"
    );

    let wgpu_surface = create_surface_from_layer(&gpu.instance, layer);
    let surface_caps = wgpu_surface.get_capabilities(&gpu.adapter);

    let format = attached_surface_format(&surface_caps, renderer_format, prefer_hdr);

    assert!(
        surface_caps
            .present_modes
            .contains(&wgpu::PresentMode::Fifo),
        "waterui_gpu_surface_attach: surface does not support FIFO presentation"
    );

    let alpha_mode = [
        wgpu::CompositeAlphaMode::PreMultiplied,
        wgpu::CompositeAlphaMode::PostMultiplied,
        wgpu::CompositeAlphaMode::Inherit,
        wgpu::CompositeAlphaMode::Opaque,
    ]
    .into_iter()
    .find(|mode| surface_caps.alpha_modes.contains(mode))
    .unwrap_or_else(|| {
        panic!("waterui_gpu_surface_attach: surface reports no supported composite alpha mode")
    });

    let config = wgpu::SurfaceConfiguration {
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        format,
        width,
        height,
        present_mode: wgpu::PresentMode::Fifo,
        alpha_mode,
        view_formats: vec![],
        desired_maximum_frame_latency: 2,
    };
    super::checked_surface_configure(
        &wgpu_surface,
        &gpu.device,
        &config,
        "waterui_gpu_surface_attach",
    );
    (wgpu_surface, config)
}

fn start_renderer_setup(state: &WuiGpuSurfaceState, format: wgpu::TextureFormat) {
    if let Some(existing) = state.renderer_format.get() {
        assert_eq!(
            existing, format,
            "GpuSurface target format changed after renderer setup started"
        );
        return;
    }

    state.renderer_format.set(Some(format));
    spawn_renderer_setup(state, format);
}

/// Re-runs renderer setup after the runtime's device was lost and rebuilt.
///
/// The `GpuView`'s pipelines and textures all belonged to the dead device, so
/// `setup` runs again on the fresh context; `setup_ready` drops for the
/// duration and the redraw it schedules replaces whatever the last frame on
/// the dead device looked like.
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn restart_renderer_setup(state: &WuiGpuSurfaceState, format: wgpu::TextureFormat) {
    // A setup already in flight read the rebuilt context when it started, so it
    // is the recovery; starting another one would panic on the empty slot.
    if state.semantic.borrow().is_none() {
        return;
    }
    state.setup_ready.set(false);
    spawn_renderer_setup(state, format);
}

fn spawn_renderer_setup(state: &WuiGpuSurfaceState, format: wgpu::TextureFormat) {
    let mut semantic = state
        .semantic
        .borrow_mut()
        .take()
        .expect("GpuSurface semantic renderer is unavailable before setup starts");
    let semantic_slot = Rc::clone(&state.semantic);
    let setup_ready = Rc::clone(&state.setup_ready);
    let runtime = state.runtime.clone();
    let redraw_handle = state.redraw_handle.clone();
    let msaa_max_samples = state.msaa_max_samples;

    spawn_local(async move {
        let GpuSurfaceSemantic { gpu_surface, env } = &mut semantic;
        // Setup retries until it completes on the context that is still the
        // runtime's current one. A device loss mid-setup leaves the just-built
        // pipelines bound to a dead device — installing them would panic the
        // next frame inside `wgpu`'s purged storage, so a stale or crashed
        // attempt loops around and runs again on the rebuilt context.
        loop {
            let gpu = runtime.context();
            let outcome = {
                let ctx = GpuContext::new(
                    &gpu.adapter,
                    &gpu.device,
                    &gpu.queue,
                    format,
                    gpu.shader_cache.as_ref(),
                    gpu.scene_renderer(),
                    msaa_max_samples,
                    redraw_handle.clone(),
                    gpu.device_loss(),
                );
                std::panic::AssertUnwindSafe(gpu_surface.setup(&ctx, env))
                    .catch_unwind()
                    .await
            };
            if let Err(payload) = outcome {
                if gpu.device_lost_reason().is_none() {
                    std::panic::resume_unwind(payload);
                }
                continue;
            }
            if gpu.device_lost_reason().is_none()
                && runtime.context().generation() == gpu.generation()
            {
                break;
            }
        }
        semantic_slot.replace(Some(semantic));
        setup_ready.set(true);
        redraw_handle.request_redraw();
    })
    .detach();
}

/// Whether the process was asked to fake one device loss, for end-to-end
/// recovery checks on real Android drivers that do not lose on demand.
///
/// `WATERUI_SIMULATE_GPU_LOSS` is a testing hook: when set, the first render
/// call marks the shared context lost and `ensure_current_context` takes the
/// same rebuild a driver-reported loss would.
#[cfg(target_os = "android")]
fn simulate_device_loss_requested() -> bool {
    static REQUESTED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *REQUESTED.get_or_init(|| std::env::var_os("WATERUI_SIMULATE_GPU_LOSS").is_some())
}

/// Marks the shared context lost exactly once per process when the
/// `WATERUI_SIMULATE_GPU_LOSS` test hook is set.
#[cfg(target_os = "android")]
fn simulate_device_loss_once(state: &WuiGpuSurfaceState) {
    static FIRED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
    if !FIRED.swap(true, core::sync::atomic::Ordering::Relaxed) && simulate_device_loss_requested()
    {
        state
            .runtime
            .context()
            .mark_device_lost_for_testing("simulated loss via WATERUI_SIMULATE_GPU_LOSS");
    }
}

/// The runtime's current context, recreating the attached surface and the
/// renderer when the generation this state was built under died with its
/// device.
///
/// The `ANativeWindow` outlives any `wgpu::Surface` made from it, so recovery
/// is a local rebuild: the frame this state was asked for still runs, just
/// against the fresh device.
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
pub(crate) fn ensure_current_context(
    state: &mut WuiGpuSurfaceState,
) -> Arc<waterui_graphics::shared_context::SharedGpuContext> {
    let gpu = state.runtime.context();
    if gpu.generation() == state.context_generation {
        return gpu;
    }

    tracing::warn!(
        old = state.context_generation,
        new = gpu.generation(),
        "GPU device was replaced; recreating the surface and renderer"
    );
    state.context_generation = gpu.generation();
    #[cfg(target_os = "android")]
    {
        state.composite_texture = None;
    }

    // A detached surface has no `wgpu::Surface` to recreate, but its renderer —
    // set up back at the first attach — is still device-bound.
    if state.wgpu_surface.is_some() {
        drop(state.wgpu_surface.take());
        state.config = None;
        let (surface, config) = create_attached_surface(
            &gpu,
            state.attached_layer,
            state.current_width,
            state.current_height,
            state.renderer_format.get(),
            state.attached_prefers_hdr,
        );
        state.config = Some(config);
        state.wgpu_surface = Some(surface);
    }
    if let Some(format) = state.renderer_format.get() {
        restart_renderer_setup(state, format);
    }
    gpu
}

fn with_semantic_mut<T>(
    state: &WuiGpuSurfaceState,
    use_semantic: impl FnOnce(&mut GpuSurfaceSemantic) -> T,
) -> T {
    assert!(
        state.setup_ready.get(),
        "GpuSurface renderer used before asynchronous setup completed"
    );
    let mut semantic = state.semantic.borrow_mut();
    use_semantic(
        semantic
            .as_mut()
            .expect("GpuSurface ready state is missing its semantic renderer"),
    )
}

/// Runs `use_surface` against the semantic GPU view when one is available.
///
/// Unlike [`with_semantic_mut`], a missing renderer is not a contract
/// violation here: input can land on a surface whose asynchronous setup has not
/// finished, and the caller reports that to the host as "the event did not
/// reach the view" rather than crashing on the user's keystroke.
pub(super) fn with_semantic_input<T>(
    state: &WuiGpuSurfaceState,
    use_surface: impl FnOnce(&mut GpuSurface) -> T,
) -> Option<T> {
    state
        .semantic
        .borrow_mut()
        .as_mut()
        .map(|semantic| use_surface(&mut semantic.gpu_surface))
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn attached_surface<'a>(
    state: &'a WuiGpuSurfaceState,
    scope: &'static str,
) -> &'a wgpu::Surface<'static> {
    state
        .wgpu_surface
        .as_ref()
        .unwrap_or_else(|| panic!("{scope}: native surface is detached"))
}

#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn attached_config<'a>(
    state: &'a WuiGpuSurfaceState,
    scope: &'static str,
) -> &'a wgpu::SurfaceConfiguration {
    state
        .config
        .as_ref()
        .unwrap_or_else(|| panic!("{scope}: native surface is detached"))
}

/// Creates the persistent state for one semantic `GpuSurface`.
///
/// This consumes the renderer exactly once. Native presentation surfaces are
/// attached and detached independently with [`waterui_gpu_surface_attach`] and
/// [`waterui_gpu_surface_detach`].
///
/// # Safety
///
/// - `surface` must be a valid, unconsumed descriptor returned by
///   `waterui_force_as_gpu_surface`.
/// - `env` must remain valid for this call; the state stores its own clone.
///
/// # Panics
///
/// Panics if `surface`'s inner `GpuSurface` pointer is null, meaning the
/// descriptor was already consumed by a previous call to this function.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_create(
    surface: *mut WuiGpuSurface,
    env: *const crate::WuiEnv,
) -> *mut WuiGpuSurfaceState {
    // SAFETY: the caller contract requires `surface` to be a valid descriptor that no
    // one else is borrowing for this call.
    let wui_surface = unsafe { &mut *surface };
    assert!(
        !wui_surface.surface.is_null(),
        "waterui_gpu_surface_create: descriptor was already consumed"
    );
    let gpu_surface: GpuSurface =
        // SAFETY: the assert above proves the descriptor still owns its `GpuSurface`,
        // and the field is nulled immediately after, so it is reclaimed once.
        unsafe { *Box::from_raw(wui_surface.surface.cast::<GpuSurface>()) };
    wui_surface.surface = core::ptr::null_mut();

    let msaa_max_samples = gpu_surface.msaa_sample_limit();
    let priority = gpu_surface.priority();
    let wants_input_events = gpu_surface.wants_input_events();
    // SAFETY: the caller contract requires `env` to be a valid handle alive for this
    // call; it is only borrowed before cloning.
    let env = unsafe { &*env }.0.clone();
    let runtime = super::gpu_runtime::gpu_runtime(&env);
    let now = Instant::now();
    Box::into_raw(Box::new(WuiGpuSurfaceState {
        runtime,
        #[cfg(not(any(target_os = "macos", target_os = "ios")))]
        wgpu_surface: None,
        #[cfg(not(any(target_os = "macos", target_os = "ios")))]
        attached_layer: core::ptr::null_mut(),
        #[cfg(not(any(target_os = "macos", target_os = "ios")))]
        attached_prefers_hdr: false,
        #[cfg(not(any(target_os = "macos", target_os = "ios")))]
        context_generation: 0,
        renderer_format: Cell::new(None),
        #[cfg(target_os = "android")]
        composite_texture: None,
        setup_ready: Rc::new(Cell::new(false)),
        msaa_max_samples,
        #[cfg(not(any(target_os = "macos", target_os = "ios")))]
        config: None,
        semantic: Rc::new(RefCell::new(Some(GpuSurfaceSemantic { gpu_surface, env }))),
        priority,
        current_width: 0,
        current_height: 0,
        pointer_state: PointerState::default(),
        gesture_state: GestureState::default(),
        start_time: now,
        last_frame_time: now
            .checked_sub(Duration::from_secs_f32(1.0 / 60.0))
            .unwrap(),
        redraw_handle: RedrawHandle::new(),
        wants_input_events,
    }))
}

/// Measures the semantic GPU view without touching presentation resources.
///
/// # Safety
///
/// `state` must be valid and this function must run on the renderer's owning
/// thread.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_measure(
    state: *const WuiGpuSurfaceState,
    proposal: WuiProposalSize,
) -> WuiViewDimensions {
    // SAFETY: the caller contract requires `state` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let state = unsafe { crate::borrow_ffi(state) };
    // SAFETY: the caller contract makes `proposal` an owning handle from the
    // matching FFI constructor; it is consumed here and not observed again.
    measure_state(state, unsafe { proposal.into_rust() }).into_ffi()
}

pub(crate) fn measure_state(
    state: &WuiGpuSurfaceState,
    proposal: waterui_core::layout::ProposalSize,
) -> waterui_core::layout::ViewDimensions {
    let semantic = state.semantic.borrow();
    semantic.as_ref().map_or_else(
        || {
            // Asynchronous setup owns the renderer right now, and hosts
            // legitimately lay out while it runs. Answer with `GpuView`'s own
            // default measurement (fill the proposal); setup completion wakes
            // the host, which re-measures custom-sized views.
            waterui_core::layout::ViewDimensions::new(waterui_core::layout::Size::new(
                proposal.width.unwrap_or(0.0),
                proposal.height.unwrap_or(0.0),
            ))
        },
        |semantic| semantic.gpu_surface.measure(proposal),
    )
}

/// Returns the layout priority declared by the semantic GPU view.
///
/// # Safety
///
/// `state` must be valid and this function must run on the renderer's owning
/// thread.
#[unsafe(no_mangle)]
pub const unsafe extern "C" fn waterui_gpu_surface_priority(
    state: *const WuiGpuSurfaceState,
) -> i32 {
    // SAFETY: the caller contract requires `state` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let state = unsafe { crate::borrow_ffi(state) };
    priority_state(state)
}

pub(crate) const fn priority_state(state: &WuiGpuSurfaceState) -> i32 {
    state.priority
}

/// Replaces the native presentation surface while preserving the semantic
/// `GpuView` and its persistent renderer resources.
///
/// Android calls this when `SurfaceView` receives a replacement `Surface`.
/// Apple platforms have no swapchain to replace and call
/// [`waterui_gpu_surface_prepare_metal_texture`] instead.
///
/// # Safety
///
/// - `state` must be a valid pointer returned by [`waterui_gpu_surface_create`].
/// - `layer` must remain valid until [`waterui_gpu_surface_detach`] is called.
/// - The state must currently be detached.
///
/// # Panics
///
/// Panics if `state` already has a native surface attached, or if `width` or
/// `height` is zero. Panics unconditionally on Apple platforms.
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_attach(
    state: *mut WuiGpuSurfaceState,
    layer: *mut c_void,
    width: u32,
    height: u32,
    prefers_hdr: bool,
) {
    // SAFETY: the caller contract requires `state` to be a valid handle, alive and
    // not otherwise borrowed for this call; the exclusive borrow ends here.
    let state = unsafe { crate::borrow_ffi_mut(state) };
    assert!(
        state.wgpu_surface.is_none(),
        "waterui_gpu_surface_attach: native surface is already attached"
    );

    let gpu = state.runtime.context();
    let (surface, config) = create_attached_surface(
        &gpu,
        layer,
        width,
        height,
        state.renderer_format.get(),
        prefers_hdr,
    );

    state.current_width = width;
    state.current_height = height;
    let format = config.format;
    state.config = Some(config);
    state.wgpu_surface = Some(surface);
    state.attached_layer = layer;
    state.attached_prefers_hdr = prefers_hdr;
    state.context_generation = gpu.generation();
    start_renderer_setup(state, format);
}

/// Attaches a native presentation surface (non-Apple only).
///
/// # Safety
///
/// `state` must come from [`waterui_gpu_surface_create`].
///
/// # Panics
///
/// Always panics: Apple hosts own their presentation memory and start the
/// renderer with [`waterui_gpu_surface_prepare_metal_texture`].
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_attach(
    _state: *mut WuiGpuSurfaceState,
    _layer: *mut c_void,
    _width: u32,
    _height: u32,
    _prefers_hdr: bool,
) {
    panic!(
        "waterui_gpu_surface_attach: Apple hosts start the renderer with waterui_gpu_surface_prepare_metal_texture"
    );
}

/// Detaches the current native presentation surface without destroying the
/// semantic `GpuView` or its persistent renderer resources.
///
/// # Safety
///
/// `state` must be valid and currently have an attached native surface.
///
/// # Panics
///
/// Panics if `state` does not currently have a native surface attached. Panics
/// unconditionally on Apple platforms, which never attach one.
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_detach(state: *mut WuiGpuSurfaceState) {
    // SAFETY: the caller contract requires `state` to be a valid handle, alive and
    // not otherwise borrowed for this call; the exclusive borrow ends here.
    let state = unsafe { crate::borrow_ffi_mut(state) };
    let surface = state
        .wgpu_surface
        .take()
        .expect("waterui_gpu_surface_detach: native surface is already detached");
    drop(surface);
    state.config = None;
}

/// Detaches the native presentation surface (non-Apple only).
///
/// # Safety
///
/// `state` must come from [`waterui_gpu_surface_create`].
///
/// # Panics
///
/// Always panics: an Apple host releases its own textures and has no swapchain
/// to detach.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_detach(_state: *mut WuiGpuSurfaceState) {
    panic!("waterui_gpu_surface_detach: Apple hosts own their presentation textures");
}

/// Installs the native wake target for renderer-driven redraw requests.
///
/// The wake callback may be called from any thread. `drop_callback` releases
/// `context` after the callback is replaced or the GPU state is destroyed.
///
/// # Safety
///
/// - `state` and `context` must be valid.
/// - Both callbacks must be thread-safe and use `context` only for the lifetime
///   retained by `drop_callback`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_set_redraw_callback(
    state: *mut WuiGpuSurfaceState,
    context: *mut c_void,
    wake: WuiGpuSurfaceRedrawCallback,
    drop_callback: WuiGpuSurfaceRedrawCallback,
) {
    // SAFETY: the caller contract requires `state` to be a valid handle, alive and
    // not otherwise borrowed for this call; the exclusive borrow ends here.
    let state = unsafe { crate::borrow_ffi_mut(state) };
    let target = ForeignRedrawTarget {
        context: context as usize,
        wake,
        drop: drop_callback,
    };
    state
        .redraw_handle
        .set_waker(Some(Arc::new(move || target.wake())));
}

/// Returns whether the renderer's asynchronous setup has completed.
///
/// Setup completion also triggers the installed redraw callback, so native
/// backends can use this value to resolve first-paint readiness without polling.
///
/// # Safety
///
/// `state` must be a valid pointer returned by [`waterui_gpu_surface_create`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_is_ready(state: *const WuiGpuSurfaceState) -> bool {
    // SAFETY: the caller contract requires `state` to be a valid handle that stays
    // alive for this call; it is only borrowed.
    let state = unsafe { crate::borrow_ffi(state) };
    state.setup_ready.get()
}

/// Render a single frame.
///
/// This function should be called when the surface is dirty (size/input/state changed)
/// and backend should schedule another frame when `needs_redraw` is true.
///
/// # Arguments
///
/// * `state` - Pointer to the persistent state from `waterui_gpu_surface_create`
/// * `width` - Current surface width in physical pixels (from layout)
/// * `height` - Current surface height in physical pixels (from layout)
/// * `scale` - Physical pixels per logical unit for this frame (2.0 on a
///   Retina display). It is passed per frame rather than at attach time
///   because it changes when the window moves between displays.
///
/// # Returns
///
/// Whether another frame should be scheduled immediately.
///
/// # Safety
///
/// `state` must be valid and have an attached native surface.
///
/// # Panics
///
/// Panics if `width` or `height` is zero, or if `scale` is not positive and
/// finite. Panics unconditionally on Apple platforms.
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_render(
    state: *mut WuiGpuSurfaceState,
    width: u32,
    height: u32,
    scale: f64,
) -> bool {
    // SAFETY: the caller contract requires `state` to be a valid handle, alive and
    // not otherwise borrowed for this call; the exclusive borrow ends here.
    let state = unsafe { crate::borrow_ffi_mut(state) };
    assert!(
        width > 0 && height > 0,
        "waterui_gpu_surface_render: dimensions must be non-zero"
    );
    assert!(
        scale.is_finite() && scale > 0.0,
        "waterui_gpu_surface_render: scale must be a positive, finite device-pixel ratio, got {scale}"
    );

    // Test hook first so the marked loss is recovered inside this same frame.
    #[cfg(target_os = "android")]
    simulate_device_loss_once(state);

    // A device loss between frames lands here: the runtime swaps in a rebuilt
    // context, and the surface — bound to the dead device — is recreated from
    // the retained `ANativeWindow` before this frame touches it.
    let gpu = ensure_current_context(state);

    // A `None` is the mid-frame device-loss path: the frame stays pending and
    // the next render call lands on the rebuilt context.
    super::run_gpu_frame(&gpu, "waterui_gpu_surface_render", || {
        render_frame_body(state, &gpu, width, height, scale)
    })
    .unwrap_or(true)
}

/// Runs one frame's worth of work against `gpu` on an attached surface.
///
/// Split from [`waterui_gpu_surface_render`] so the frame body can run inside
/// [`super::run_gpu_frame`]'s `catch_unwind`: a driver-reported device loss
/// mid-call purges `wgpu`'s storage while the frame is still using it, and the
/// resulting internal panic is what the caller catches — but only when the
/// context confirms the loss.
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn render_frame_body(
    state: &mut WuiGpuSurfaceState,
    gpu: &Arc<waterui_graphics::shared_context::SharedGpuContext>,
    width: u32,
    height: u32,
    scale: f64,
) -> bool {
    // Handle resize if needed
    if width != state.current_width || height != state.current_height {
        {
            let config = state
                .config
                .as_mut()
                .expect("waterui_gpu_surface_render: native surface is detached");
            config.width = width;
            config.height = height;
        }

        super::checked_surface_configure(
            attached_surface(state, "waterui_gpu_surface_render"),
            &gpu.device,
            attached_config(state, "waterui_gpu_surface_render"),
            "waterui_gpu_surface_render",
        );
        state.current_width = width;
        state.current_height = height;
    }

    let format = attached_config(state, "waterui_gpu_surface_render").format;
    if !state.setup_ready.get() {
        // The renderer is mid-setup — first attach or a device-loss rebuild —
        // so the frame stays pending and the host comes back for it.
        return true;
    }

    let Some(output) = super::acquire_surface_texture(
        attached_surface(state, "waterui_gpu_surface_render"),
        gpu,
        attached_config(state, "waterui_gpu_surface_render"),
        "waterui_gpu_surface_render",
    ) else {
        // Nothing was drawn, so the frame this call was asked for is still
        // pending: the host must come back for it once the surface can be
        // acquired again. Reporting it done here would strand a view whose only
        // clock is its own render loop.
        return true;
    };
    let view = output.texture.create_view(&wgpu::TextureViewDescriptor {
        label: Some("GpuSurface Frame View"),
        format: Some(format),
        ..Default::default()
    });

    let (elapsed, delta) = advance_frame_timing(state);

    // Create frame data
    let mut frame = GpuFrame::new(
        &gpu.device,
        &gpu.queue,
        &output.texture,
        view,
        format,
        width,
        height,
        scale,
        state.pointer_state,
        state.gesture_state,
        elapsed,
        delta,
    );

    // The dirty request that scheduled this frame is now satisfied. A new
    // request arriving during the renderer callback remains pending below.
    let _ = state.redraw_handle.take_dirty();
    with_semantic_mut(state, |semantic| {
        semantic.gpu_surface.render(&mut frame);
    });
    let needs_redraw = frame.was_redraw_requested() || state.redraw_handle.take_dirty();

    output.present();
    // Queue order retires this marker only after the frame's real work and
    // the present, so resolving it is what records this generation as having
    // presented — the signal the rebuild budget reads after a device loss.
    gpu.note_presented_submission(gpu.queue.submit([]));

    needs_redraw
}

/// Renders one frame into the attached swapchain (non-Apple only).
///
/// # Safety
///
/// `state` must come from [`waterui_gpu_surface_create`].
///
/// # Panics
///
/// Always panics: Apple hosts render with
/// [`waterui_gpu_surface_render_to_metal_texture`].
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_render(
    _state: *mut WuiGpuSurfaceState,
    _width: u32,
    _height: u32,
    _scale: f64,
) -> bool {
    panic!(
        "waterui_gpu_surface_render: Apple hosts render with waterui_gpu_surface_render_to_metal_texture"
    );
}

#[cfg(any(target_os = "macos", target_os = "ios"))]
fn metal_texture_format(texture: &ProtocolObject<dyn MTLTexture>) -> wgpu::TextureFormat {
    match texture.pixelFormat() {
        MTLPixelFormat::BGRA8Unorm => wgpu::TextureFormat::Bgra8Unorm,
        MTLPixelFormat::BGRA8Unorm_sRGB => wgpu::TextureFormat::Bgra8UnormSrgb,
        MTLPixelFormat::RGBA16Float => wgpu::TextureFormat::Rgba16Float,
        other => panic!("GpuSurface external Metal texture has unsupported format {other:?}"),
    }
}

/// Starts asynchronous renderer setup for an external Metal render target.
///
/// Completion triggers the installed redraw callback. Native must wait until
/// [`waterui_gpu_surface_is_ready`] returns true before rendering into the texture.
///
/// # Safety
///
/// `state` must be valid and `texture` must point to a live `MTLTexture`.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_prepare_metal_texture(
    state: *mut WuiGpuSurfaceState,
    texture: *mut c_void,
) {
    // SAFETY: the caller contract requires `state` to be a valid handle, alive and
    // not otherwise borrowed for this call; the exclusive borrow ends here.
    let state = unsafe { crate::borrow_ffi_mut(state) };
    // SAFETY: the caller contract requires `texture` to be a live `MTLTexture` that
    // stays alive for this call; it is only borrowed to read its pixel format.
    let texture = unsafe { &*texture.cast::<ProtocolObject<dyn MTLTexture>>() };
    start_renderer_setup(state, metal_texture_format(texture));
}

/// Render a single frame into an external Metal texture (Apple only).
///
/// `width` and `height` are physical pixels; `scale` is how many of them one
/// logical unit spans, so the renderer can work in the coordinate space the
/// view was laid out in.
///
/// # Safety
/// `state` must be valid, `texture` must point to a `MTLTexture`.
///
/// # Panics
///
/// Panics if `texture` is null, or if `scale` is not positive and finite.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_render_to_metal_texture(
    state: *mut WuiGpuSurfaceState,
    texture: *mut core::ffi::c_void,
    width: u32,
    height: u32,
    scale: f64,
) -> *mut WuiGpuCaptureFence {
    assert!(
        scale.is_finite() && scale > 0.0,
        "waterui_gpu_surface_render_to_metal_texture: scale must be a positive, finite device-pixel ratio, got {scale}"
    );
    // SAFETY: the caller contract requires `state` to be a valid handle that no one
    // else is borrowing for this call.
    let state = unsafe { &mut *state };
    // SAFETY: the caller contract requires `texture` to be a live `MTLTexture`;
    // `retain` takes its own reference, so it stays alive for the render below.
    let metal_texture = unsafe {
        Retained::<ProtocolObject<dyn MTLTexture>>::retain(texture.cast())
            .expect("waterui_gpu_surface_render_to_metal_texture received a null texture")
    };

    let target_format = metal_texture_format(&metal_texture);
    assert_eq!(
        state.renderer_format.get(),
        Some(target_format),
        "waterui_gpu_surface_render_to_metal_texture called before preparing this target format"
    );
    assert!(
        state.setup_ready.get(),
        "waterui_gpu_surface_render_to_metal_texture called before asynchronous setup completed"
    );

    // SAFETY: `metal_texture` is the retained texture above, and the format and size
    // passed alongside it are read from that same texture, so the HAL description
    // matches the real resource.
    let hal_texture = unsafe {
        <MetalApi as Api>::Device::texture_from_raw(
            metal_texture,
            target_format,
            MTLTextureType::Type2D,
            1,
            1,
            wgpu_hal::CopyExtent {
                width,
                height,
                depth: 1,
            },
        )
    };
    let texture_desc = wgpu::TextureDescriptor {
        label: Some("GpuSurface Imported Metal Texture"),
        size: wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: target_format,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        view_formats: &[],
    };

    // SAFETY: the HAL texture above was created from this runtime's device, which is
    // the device the wgpu texture is being created on.
    let wgpu_texture = unsafe {
        state
            .runtime
            .context()
            .device
            .create_texture_from_hal::<MetalApi>(hal_texture, &texture_desc)
    };
    let view = wgpu_texture.create_view(&wgpu::TextureViewDescriptor {
        label: Some("GpuSurface Metal Frame View"),
        format: Some(target_format),
        ..Default::default()
    });
    render_into_texture(
        state,
        &wgpu_texture,
        view,
        target_format,
        width,
        height,
        scale,
    );
    let submission = state.runtime.context().queue.submit([]);
    let fence = WuiGpuCaptureFence::new(
        state.runtime.context().submission_completion_driver(),
        submission,
    );
    Box::into_raw(Box::new(fence))
}

/// Renders one frame of the semantic GPU view into a texture it does not own.
///
/// Every path that captures a surface into foreign memory ends here: Apple's
/// imported `MTLTexture` and Android's compositing of a surface nested inside a
/// captured subtree both hand in a texture of the renderer's established format
/// and take whatever the renderer draws into it. The redraw bookkeeping is a
/// presented frame's, so a renderer that asks for another frame from inside its
/// own draw is woken the same way whether it was presenting or being captured.
///
/// Nothing is submitted here: the renderer submits its own work, and the caller
/// decides what the frame is ordered against.
///
/// # Panics
///
/// Panics if the renderer's asynchronous setup has not completed.
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))]
pub(super) fn render_into_texture(
    state: &mut WuiGpuSurfaceState,
    texture: &wgpu::Texture,
    view: wgpu::TextureView,
    format: wgpu::TextureFormat,
    width: u32,
    height: u32,
    scale: f64,
) {
    let (elapsed, delta) = advance_frame_timing(state);
    let gpu = state.runtime.context();
    let mut frame = GpuFrame::new(
        &gpu.device,
        &gpu.queue,
        texture,
        view,
        format,
        width,
        height,
        scale,
        state.pointer_state,
        state.gesture_state,
        elapsed,
        delta,
    );

    let _ = state.redraw_handle.take_dirty();
    with_semantic_mut(state, |semantic| {
        semantic.gpu_surface.render(&mut frame);
    });
    if frame.was_redraw_requested() || state.redraw_handle.take_dirty() {
        state.redraw_handle.request_redraw();
    }
}

/// The GPU runtime this surface renders on, for a caller that needs its own
/// handle on the device and queue while the surface state is borrowed.
#[cfg(target_os = "android")]
pub(super) fn composite_runtime(state: &WuiGpuSurfaceState) -> GpuRuntime {
    state.runtime.clone()
}

/// Whether the surface's renderer setup has completed — `false` while a
/// device-loss rebuild is re-running it, when a composite would panic inside
/// `with_semantic_mut` instead of drawing.
#[cfg(target_os = "android")]
pub(super) fn composite_source_ready(state: &WuiGpuSurfaceState) -> bool {
    state.setup_ready.get()
}

/// Renders this surface's next frame into the texture a capture reads it from.
///
/// The returned texture holds one frame of the semantic GPU view at
/// `width`x`height` in the renderer's established format, ready to be drawn
/// into the enclosing capture's texture. It belongs to this state and is reused
/// for every frame of the same size.
///
/// # Panics
///
/// Panics if the renderer has no established format yet — a surface that has
/// never been attached has drawn nothing and cannot be composited — or if its
/// asynchronous setup has not completed.
#[cfg(target_os = "android")]
pub(super) fn render_composite_source(
    state: &mut WuiGpuSurfaceState,
    width: u32,
    height: u32,
    scale: f64,
) -> &wgpu::Texture {
    assert!(
        width > 0 && height > 0,
        "GpuSurface composite source must be non-zero, got {width}x{height}"
    );
    let format = state
        .renderer_format
        .get()
        .expect("GpuSurface cannot be composited into a capture before it has been attached once");
    let matches_request = state.composite_texture.as_ref().is_some_and(|texture| {
        texture.width() == width && texture.height() == height && texture.format() == format
    });
    if !matches_request {
        state.composite_texture = Some(state.runtime.context().device.create_texture(
            &wgpu::TextureDescriptor {
                label: Some("GpuSurface Composite Source"),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            },
        ));
    }

    // Lent out for the render so the renderer's own `&mut` borrow of the state
    // and the texture do not overlap, then returned to its slot.
    let texture = state
        .composite_texture
        .take()
        .expect("GpuSurface composite source was just ensured");
    let view = texture.create_view(&wgpu::TextureViewDescriptor {
        label: Some("GpuSurface Composite Source View"),
        format: Some(format),
        ..Default::default()
    });
    render_into_texture(state, &texture, view, format, width, height, scale);
    state.composite_texture = Some(texture);
    state
        .composite_texture
        .as_ref()
        .expect("GpuSurface composite source was just returned")
}

/// Schedules one external capture submission completion and consumes its fence.
///
/// `callback` runs exactly once on the shared GPU completion thread. `drop`
/// then runs exactly once on that same thread, including if the completion
/// driver fails before invoking `callback`. Native callbacks should only
/// enqueue their next platform-specific stage and return immediately.
///
/// # Safety
///
/// `fence` must be a valid owning pointer returned by an external capture entry
/// point — `waterui_gpu_surface_render_to_metal_texture` on Apple,
/// `waterui_applied_filter_set_capture_hardware_buffer` or
/// `waterui_view_effect_set_input_hardware_buffer` on Android — and must be
/// consumed once.
/// `context`, `callback`, and `drop` must remain valid until completion; Rust
/// consumes the context and releases it through `drop`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_capture_fence_on_complete(
    fence: *mut WuiGpuCaptureFence,
    context: *mut c_void,
    callback: WuiGpuCaptureCompletionCallback,
    drop: WuiGpuCaptureCompletionDrop,
) {
    // A null fence is what a capture entry point returns when the device was
    // lost mid-copy: there is no submission to wait on, so the completion runs
    // immediately and the backend can release the buffer it lent.
    if fence.is_null() {
        // SAFETY: `callback`, `drop`, and `context` were registered together and
        // the context is still live — the copy never submitted, so nothing else
        // consumed it.
        unsafe {
            callback(context);
            drop(context);
        }
        return;
    }
    // SAFETY: the caller contract makes `fence` an owning pointer from the matching
    // FFI constructor, so reclaiming the box frees it exactly once.
    let fence = unsafe { Box::from_raw(fence) };
    let completion = ForeignGpuCaptureCompletion {
        context: context as usize,
        callback,
        drop,
    };
    fence
        .completion_driver
        .on_complete(fence.submission, move || completion.complete());
}

/// Clean up GPU resources.
///
/// This function should be called when the `GpuSurface` view is destroyed.
///
/// # Safety
///
/// `state` must be a valid pointer from `waterui_gpu_surface_create`,
/// and must not be used after this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_drop(state: *mut WuiGpuSurfaceState) {
    // SAFETY: the caller contract makes `state` an owning handle from the matching
    // constructor that has not been dropped; clearing the waker before it falls out of
    // scope releases the backend's context first.
    unsafe {
        let state = Box::from_raw(state);
        state.redraw_handle.set_waker(None);
    }
}

/// FFI-safe pointer state for passing from native.
///
/// Native backends should update this before each render call to provide
/// current pointer/cursor information to the GPU renderer.
#[repr(C)]
#[derive(Debug)]
pub struct WuiPointerState {
    /// Whether the pointer is currently over this surface.
    pub has_position: bool,
    /// X coordinate in surface-local pixels.
    pub x: f32,
    /// Y coordinate in surface-local pixels.
    pub y: f32,
    /// Whether there's an active hit (press/touch in progress).
    pub has_hit: bool,
    /// X coordinate where hit started.
    pub hit_x: f32,
    /// Y coordinate where hit started.
    pub hit_y: f32,
}

#[inline]
const fn pointer_state_from_ffi(pointer: &WuiPointerState) -> PointerState {
    PointerState {
        position: if pointer.has_position {
            Some(waterui_core::layout::Point::new(pointer.x, pointer.y))
        } else {
            None
        },
        hit: if pointer.has_hit {
            Some(waterui_core::layout::Point::new(
                pointer.hit_x,
                pointer.hit_y,
            ))
        } else {
            None
        },
    }
}

/// FFI-safe gesture state for zoom/pan interactions.
///
/// Native backends should update this when pinch, pan, or double-tap
/// gestures are detected to enable interactive chart zoom/pan.
#[repr(C)]
#[derive(Debug)]
pub struct WuiGestureState {
    /// Whether a gesture is currently active.
    pub active: bool,
    /// Cumulative pinch scale factor (1.0 = no scaling).
    pub pinch_scale: f32,
    /// Whether a pinch center is present.
    pub has_pinch_center: bool,
    /// X coordinate of pinch center in surface-local pixels.
    pub pinch_center_x: f32,
    /// Y coordinate of pinch center in surface-local pixels.
    pub pinch_center_y: f32,
    /// Pan offset X in pixels since gesture began.
    pub pan_offset_x: f32,
    /// Pan offset Y in pixels since gesture began.
    pub pan_offset_y: f32,
    /// Whether a double-tap was detected this frame.
    pub double_tap: bool,
}

#[inline]
const fn gesture_state_from_ffi(gesture: &WuiGestureState) -> GestureState {
    GestureState {
        pinch_scale: gesture.pinch_scale,
        pinch_center: if gesture.has_pinch_center {
            Some(waterui_core::layout::Point::new(
                gesture.pinch_center_x,
                gesture.pinch_center_y,
            ))
        } else {
            None
        },
        pan_offset: waterui_core::layout::Point::new(gesture.pan_offset_x, gesture.pan_offset_y),
        double_tap: gesture.double_tap,
        active: gesture.active,
    }
}

/// FFI-safe combined input state for a `GpuSurface`.
///
/// This keeps the native bridge minimal by forwarding pointer and gesture
/// snapshots in one call.
#[repr(C)]
#[derive(Debug)]
pub struct WuiGpuSurfaceInput {
    /// Current pointer snapshot.
    pub pointer: WuiPointerState,
    /// Current gesture snapshot.
    pub gesture: WuiGestureState,
}

/// Update both pointer and gesture state for a `GpuSurface`.
///
/// Native backends should prefer this API to minimize bridge calls.
///
/// # Arguments
///
/// * `state` - Pointer to the persistent state from `waterui_gpu_surface_create`
/// * `input` - Combined pointer + gesture snapshot
///
/// # Safety
///
/// `state` must be a valid pointer from `waterui_gpu_surface_create`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn waterui_gpu_surface_set_input(
    state: *mut WuiGpuSurfaceState,
    input: WuiGpuSurfaceInput,
) {
    // SAFETY: the caller contract requires `state` to be a valid handle, alive and
    // not otherwise borrowed for this call; the exclusive borrow ends here.
    let state = unsafe { crate::borrow_ffi_mut(state) };
    state.pointer_state = pointer_state_from_ffi(&input.pointer);
    state.gesture_state = gesture_state_from_ffi(&input.gesture);
}

/// Create a wgpu Surface from a platform-specific layer pointer.
///
/// Apple has no arm here on purpose: nothing on those platforms presents
/// through a swapchain any more. A `CAMetalLayer`'s drawable is readable only
/// by the pipeline that presented it, so every Apple host now renders into a
/// host-owned `IOSurface` texture instead (#519, #579).
#[cfg(target_os = "android")]
pub(crate) fn create_surface_from_layer(
    instance: &wgpu::Instance,
    layer: *mut c_void,
) -> wgpu::Surface<'static> {
    use raw_window_handle::{AndroidNdkWindowHandle, RawWindowHandle};
    use std::ptr::NonNull;

    // On Android, layer is an ANativeWindow*
    let window_ptr = NonNull::new(layer).expect("ANativeWindow pointer must be non-null");
    let handle = AndroidNdkWindowHandle::new(window_ptr);

    // SAFETY: `create_surface_unsafe` requires the raw handle to stay valid for as
    // long as the returned surface. `layer` is the `ANativeWindow*` the Android
    // backend holds for this surface and releases only after dropping it.
    unsafe {
        instance
            .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
                raw_display_handle: Some(raw_window_handle::RawDisplayHandle::Android(
                    raw_window_handle::AndroidDisplayHandle::new(),
                )),
                raw_window_handle: RawWindowHandle::AndroidNdk(handle),
            })
            .expect("failed to create wgpu surface from ANativeWindow")
    }
}

#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))]
pub(crate) fn create_surface_from_layer(
    _instance: &wgpu::Instance,
    _layer: *mut c_void,
) -> wgpu::Surface<'static> {
    panic!("native GpuSurface presentation is unsupported on this platform")
}

#[cfg(all(test, not(any(target_os = "macos", target_os = "ios"))))]
mod tests {
    use super::*;

    fn surface_capabilities() -> wgpu::SurfaceCapabilities {
        wgpu::SurfaceCapabilities {
            formats: vec![
                wgpu::TextureFormat::Bgra8UnormSrgb,
                wgpu::TextureFormat::Rgba16Float,
            ],
            ..wgpu::SurfaceCapabilities::default()
        }
    }

    #[test]
    fn first_surface_uses_dynamic_range_preference() {
        let capabilities = surface_capabilities();
        assert_eq!(
            attached_surface_format(&capabilities, None, false),
            wgpu::TextureFormat::Bgra8UnormSrgb
        );
        assert_eq!(
            attached_surface_format(&capabilities, None, true),
            wgpu::TextureFormat::Rgba16Float
        );
    }

    #[test]
    fn replacement_surface_reuses_established_renderer_format() {
        let capabilities = surface_capabilities();
        assert_eq!(
            attached_surface_format(&capabilities, Some(wgpu::TextureFormat::Rgba16Float), false,),
            wgpu::TextureFormat::Rgba16Float
        );
    }

    #[test]
    #[should_panic(
        expected = "replacement surface does not support the renderer's established format"
    )]
    fn replacement_surface_rejects_unsupported_renderer_format() {
        let capabilities = wgpu::SurfaceCapabilities {
            formats: vec![wgpu::TextureFormat::Bgra8UnormSrgb],
            ..wgpu::SurfaceCapabilities::default()
        };
        let _ =
            attached_surface_format(&capabilities, Some(wgpu::TextureFormat::Rgba16Float), true);
    }
}