dear-imgui-wgpu 0.16.0-alpha.2

WGPU renderer backend for dear-imgui-rs (native + WebAssembly)
Documentation
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
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::fmt;
use std::rc::Rc;

use dear_imgui_rs::render::ReconciledFrame;
use dear_imgui_rs::{
    Context, ContextAttachment, ContextAttachmentError, ContextAttachmentLease,
    ContextAttachmentRole, ContextAttachmentTeardownError, ContextBinding, ContextBindingError,
    ContextDestroyed, ContextId, ContextLifecycle, ContextTeardown, FrameToken,
};
use thiserror::Error;

use super::callbacks::{
    claim_callbacks, destroy_renderer_viewport_resources, detect_runtime_contract_drift,
    preflight_callbacks, preflight_renderer_viewport_resources, release_callbacks,
    revoke_renderer_viewport_capability_if_owned,
};
use super::registry::{
    GlobalHandles, drop_orphaned_viewport_data, preflight_runtime, register_runtime,
    renderer_globals, unregister_runtime,
};
use super::trace::{FrameTraceState, WgpuViewportFrameReport};
use crate::{ExternalTextureId, FramebufferExtent, GammaMode, RendererError, WgpuRenderer};

struct WgpuRendererAttachmentMarker;

/// Failure to attach or operate an owning WGPU multi-viewport runtime.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum WgpuViewportError {
    /// The Dear ImGui Context rejected the renderer attachment.
    #[error(transparent)]
    Attachment(#[from] ContextAttachmentError),
    /// The originating Context can no longer be entered normally.
    #[error(transparent)]
    Context(#[from] ContextBindingError),
    /// The underlying WGPU renderer operation failed.
    #[error(transparent)]
    Renderer(#[from] RendererError),
    /// The renderer and runtime Context identities differ.
    #[error("WGPU viewport runtime belongs to Context {expected:?}, not {actual:?}")]
    ContextMismatch {
        expected: ContextId,
        actual: ContextId,
    },
    /// A prepared frame was passed to a different runtime instance.
    #[error(
        "WGPU prepared frame belongs to another runtime instance (expected Context {expected:?}, frame Context {actual:?})"
    )]
    PreparedFrameRuntimeMismatch {
        expected: ContextId,
        actual: ContextId,
    },
    /// A callback entry was not running under this runtime's Context.
    #[error("the current Dear ImGui Context does not match WGPU runtime Context {expected:?}")]
    BoundContextMismatch { expected: ContextId },
    /// The renderer has not been initialized with GPU backend data.
    #[error("WGPU renderer is not initialized")]
    RendererNotInitialized,
    /// The renderer was initialized for another Dear ImGui Context.
    #[error("WGPU renderer is bound to a different Dear ImGui Context")]
    RendererContextMismatch,
    /// The renderer's bound Dear ImGui Context no longer exists.
    #[error("the Dear ImGui Context bound to this WGPU renderer has been dropped")]
    RendererContextDropped,
    /// Per-window surfaces require the WGPU instance used by the renderer.
    #[error("WGPU multi-viewport requires WgpuInitInfo::with_instance")]
    MissingInstance,
    /// Surface capability negotiation requires the WGPU adapter used by the renderer.
    #[error("WGPU multi-viewport requires WgpuInitInfo::with_adapter")]
    MissingAdapter,
    /// Renderer callbacks require an attached platform backend that supports viewports.
    #[error("WGPU multi-viewport requires an attached multi-viewport platform runtime")]
    PlatformBackendUnavailable,
    /// The typed platform owner supplied to the renderer belongs to another Context.
    #[error("WGPU viewport platform owner belongs to Context {actual:?}, not {expected:?}")]
    PlatformOwnerContextMismatch {
        expected: ContextId,
        actual: ContextId,
    },
    /// The typed Winit platform owner rejected renderer attachment.
    #[cfg(feature = "multi-viewport-winit")]
    #[error(transparent)]
    WinitPlatformOwner(#[from] dear_imgui_winit::WinitPlatformError),
    /// The typed SDL3 platform owner rejected renderer attachment.
    #[cfg(feature = "multi-viewport-sdl3")]
    #[error(transparent)]
    Sdl3PlatformOwner(#[from] dear_imgui_sdl3::Sdl3BackendError),
    /// A required platform callback is absent.
    #[error("required ImGuiPlatformIO callback `{callback}` is not installed")]
    PlatformCallbackUnavailable { callback: &'static str },
    /// PlatformIO itself is unavailable for the currently bound Context.
    #[error("the bound Dear ImGui Context has no PlatformIO")]
    PlatformIoUnavailable,
    /// The platform runtime has not published the main native window handle.
    #[error("the attached platform runtime has no main viewport window handle")]
    MainViewportHandleUnavailable,
    /// Another renderer already owns one renderer callback slot.
    #[error("ImGuiPlatformIO callback `{callback}` is already owned by another renderer")]
    RendererCallbackOccupied { callback: &'static str },
    /// Another renderer already advertises multi-viewport support.
    #[error("another renderer already advertises RENDERER_HAS_VIEWPORTS")]
    RendererViewportCapabilityOccupied,
    /// This runtime's renderer capability bit was cleared while it remained attached.
    #[error("WGPU renderer backend flag RENDERER_HAS_VIEWPORTS was removed while attached")]
    RendererViewportCapabilityLost,
    /// A callback claimed by this runtime was replaced while attached.
    #[error("WGPU renderer callback `{callback}` was replaced while the runtime was attached")]
    RendererCallbackReplaced { callback: &'static str },
    /// A secondary viewport already contains renderer-owned user data.
    #[error("a secondary viewport already has RendererUserData owned by another backend")]
    RendererUserDataOccupied,
    /// A callback observed non-null renderer data that is absent from this runtime's sidecar.
    #[error("WGPU callback `{callback}` observed foreign or unregistered RendererUserData")]
    RendererUserDataOwnershipLost { callback: &'static str },
    /// Existing platform windows would miss the renderer create callback.
    #[error("secondary platform windows already exist; destroy them before attaching WGPU")]
    PlatformWindowsAlreadyCreated,
    /// The aggregate size callback cannot be bridged safely by this Dear ImGui artifact.
    #[error("dear-imgui-sys was built without PlatformIO aggregate ABI hooks")]
    AggregateCallbackHooksUnavailable,
    /// The registry already contains a live runtime for this Context.
    #[error("a WGPU viewport runtime is already attached to this Context")]
    RuntimeAlreadyAttached,
    /// The owning runtime has shut down or Context-owned teardown has started.
    #[error("the WGPU viewport runtime is no longer attached")]
    RuntimeDetached,
    /// The renderer is already mutably borrowed by another runtime entry.
    #[error("WGPU renderer runtime is already active in `{callback}`")]
    CallbackReentered { callback: &'static str },
    /// A callback panic was contained at the C ABI boundary.
    #[error("WGPU renderer callback `{callback}` panicked")]
    CallbackPanicked { callback: &'static str },
    /// Dear ImGui passed an invalid viewport to a renderer callback.
    #[error("WGPU renderer callback `{callback}` received a null viewport")]
    InvalidViewport { callback: &'static str },
    /// Creating or configuring a viewport surface failed.
    #[error("WGPU viewport surface operation `{operation}` failed")]
    SurfaceOperationFailed { operation: &'static str },
    /// The renderer's target format is unavailable with its required secondary-surface encoding.
    #[error(
        "WGPU render target format {format:?} is unavailable for secondary viewports in {color_space}"
    )]
    UnsupportedSurfaceFormat {
        format: wgpu::TextureFormat,
        color_space: &'static str,
    },
    /// The renderer's multisample count cannot describe a WGPU render attachment.
    #[error("WGPU viewport attachments require a non-zero multisample count, received {count}")]
    InvalidMultisampleCount { count: u32 },
    /// A renderer attachment format does not support the configured sample count.
    #[error(
        "WGPU {attachment} format {format:?} does not support RENDER_ATTACHMENT at sample count {sample_count}"
    )]
    UnsupportedViewportAttachment {
        attachment: &'static str,
        format: wgpu::TextureFormat,
        sample_count: u32,
    },
    /// Surface acquisition returned a terminal result.
    #[error("WGPU viewport surface acquisition was rejected: {event}")]
    SurfaceRejected { event: &'static str },
    /// Native multi-viewport surfaces are unavailable on this target.
    #[error("WGPU native multi-viewport rendering is unavailable on this target")]
    UnsupportedTarget,
    /// A frame trace is already active for this runtime.
    #[error("a WGPU secondary-viewport frame trace is already active")]
    FrameTraceAlreadyActive,
}

/// One failure observed while preparing a WGPU multi-viewport route.
#[doc(hidden)]
#[derive(Debug)]
#[non_exhaustive]
pub enum WgpuViewportRouteFault<PlatformError> {
    /// Texture reconciliation or a renderer callback failed.
    Renderer(WgpuViewportError),
    /// The platform owner reported a deferred native-window fault.
    Platform(PlatformError),
}

impl<PlatformError> fmt::Display for WgpuViewportRouteFault<PlatformError>
where
    PlatformError: fmt::Display,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Renderer(error) => write!(formatter, "WGPU viewport route failed: {error}"),
            Self::Platform(error) => write!(formatter, "viewport platform route failed: {error}"),
        }
    }
}

impl<PlatformError> std::error::Error for WgpuViewportRouteFault<PlatformError>
where
    PlatformError: std::error::Error + 'static,
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Renderer(error) => Some(error),
            Self::Platform(error) => Some(error),
        }
    }
}

/// Ordered failures from one WGPU multi-viewport preparation transaction.
///
/// Renderer failures are reported before platform failures observed after the same native
/// callback pump. All failures from each source retain FIFO order.
#[doc(hidden)]
#[derive(Debug)]
pub struct WgpuViewportRouteError<PlatformError> {
    faults: Vec<WgpuViewportRouteFault<PlatformError>>,
}

impl<PlatformError> WgpuViewportRouteError<PlatformError> {
    pub(crate) fn new(faults: Vec<WgpuViewportRouteFault<PlatformError>>) -> Self {
        debug_assert!(!faults.is_empty());
        Self { faults }
    }

    /// Returns every route fault in reporting order.
    #[must_use]
    pub fn faults(&self) -> &[WgpuViewportRouteFault<PlatformError>] {
        &self.faults
    }

    /// Consumes the aggregate and returns every route fault in reporting order.
    #[must_use]
    pub fn into_faults(self) -> Vec<WgpuViewportRouteFault<PlatformError>> {
        self.faults
    }
}

impl<PlatformError> fmt::Display for WgpuViewportRouteError<PlatformError>
where
    PlatformError: fmt::Display,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let count = self.faults.len();
        write!(formatter, "{}", self.faults[0])?;
        if count > 1 {
            write!(formatter, " ({count} viewport route faults in total)")?;
        }
        Ok(())
    }
}

impl<PlatformError> std::error::Error for WgpuViewportRouteError<PlatformError>
where
    PlatformError: std::error::Error + 'static,
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.faults
            .first()
            .map(|fault| fault as &(dyn std::error::Error + 'static))
    }
}

pub(crate) fn finish_route_preparation<Prepared, PlatformError>(
    renderer_result: Option<Result<Prepared, WgpuViewportError>>,
    renderer_faults: Vec<WgpuViewportError>,
    platform_faults: Vec<PlatformError>,
) -> Result<Prepared, WgpuViewportRouteError<PlatformError>> {
    let direct_renderer_fault = if matches!(renderer_result.as_ref(), Some(Err(_))) {
        1
    } else {
        0
    };
    let mut faults =
        Vec::with_capacity(direct_renderer_fault + renderer_faults.len() + platform_faults.len());
    let prepared = match renderer_result {
        Some(Ok(prepared)) => Some(prepared),
        Some(Err(error)) => {
            faults.push(WgpuViewportRouteFault::Renderer(error));
            None
        }
        None => None,
    };
    faults.extend(
        renderer_faults
            .into_iter()
            .map(WgpuViewportRouteFault::Renderer),
    );
    faults.extend(
        platform_faults
            .into_iter()
            .map(WgpuViewportRouteFault::Platform),
    );

    if !faults.is_empty() {
        Err(WgpuViewportRouteError::new(faults))
    } else if let Some(prepared) = prepared {
        Ok(prepared)
    } else {
        Err(WgpuViewportRouteError::new(vec![
            WgpuViewportRouteFault::Renderer(WgpuViewportError::RuntimeDetached),
        ]))
    }
}

/// Runs a public route transaction only when its frame belongs to the attached Context.
///
/// The callback contains every platform-adapter entry and fault-queue read. Keeping it behind this
/// pure identity check makes foreign-frame rejection observably side-effect free.
pub(crate) fn prepare_route_for_context<Prepared, PlatformError>(
    expected: ContextId,
    actual: ContextId,
    prepare: impl FnOnce() -> Result<Prepared, WgpuViewportRouteError<PlatformError>>,
) -> Result<Prepared, WgpuViewportRouteError<PlatformError>> {
    if expected != actual {
        return Err(WgpuViewportRouteError::new(vec![
            WgpuViewportRouteFault::Renderer(WgpuViewportError::ContextMismatch {
                expected,
                actual,
            }),
        ]));
    }
    prepare()
}

/// Transactional attachment failure that returns the renderer unchanged.
pub struct WgpuViewportAttachError {
    error: WgpuViewportError,
    renderer: Box<WgpuRenderer>,
}

impl WgpuViewportAttachError {
    pub(crate) fn new(error: WgpuViewportError, renderer: WgpuRenderer) -> Self {
        Self {
            error,
            renderer: Box::new(renderer),
        }
    }

    /// Returns the reason attachment failed.
    pub fn error(&self) -> &WgpuViewportError {
        &self.error
    }

    /// Returns the renderer so the caller can retry, use it for one viewport, or destroy it.
    pub fn into_renderer(self) -> WgpuRenderer {
        *self.renderer
    }

    /// Returns both the typed failure and the unchanged renderer.
    pub fn into_parts(self) -> (WgpuViewportError, WgpuRenderer) {
        (self.error, *self.renderer)
    }
}

impl fmt::Debug for WgpuViewportAttachError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WgpuViewportAttachError")
            .field("error", &self.error)
            .field("renderer", &"returned to caller")
            .finish()
    }
}

impl fmt::Display for WgpuViewportAttachError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error.fmt(formatter)
    }
}

impl std::error::Error for WgpuViewportAttachError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.error)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum RuntimeState {
    Constructing,
    Attached,
    ShuttingDown,
    Detached,
    ResourceDropped,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CallbackState {
    Unclaimed,
    Claimed,
    Released,
}

enum ShutdownAction<'a> {
    Quiesce,
    Explicit(&'a mut Context),
}

/// Exact identity for one attached renderer runtime.
///
/// The identity is intentionally reference-counted with [`Rc`] because the owning runtime and
/// every prepared frame remain on the UI thread.
#[derive(Debug)]
struct RuntimeIdentity;

impl RuntimeIdentity {
    fn new() -> Rc<Self> {
        Rc::new(Self)
    }
}

pub(super) struct RuntimeControl {
    context_raw: *mut dear_imgui_rs::sys::ImGuiContext,
    binding: ContextBinding,
    identity: Rc<RuntimeIdentity>,
    state: Cell<RuntimeState>,
    renderer: RefCell<Option<Box<WgpuRenderer>>>,
    globals: RefCell<Option<GlobalHandles>>,
    attachment: RefCell<Option<ContextAttachmentLease>>,
    callback_state: Cell<CallbackState>,
    faults: RefCell<RuntimeFaults>,
    frame_trace: RefCell<FrameTraceState>,
    #[cfg(test)]
    panic_next_callback: Cell<bool>,
    #[cfg(test)]
    fail_next_viewport_cleanup: Cell<bool>,
    #[cfg(test)]
    transitions: RefCell<Vec<&'static str>>,
}

#[derive(Default)]
struct RuntimeFaults {
    pending: VecDeque<WgpuViewportError>,
    terminal_recorded: bool,
}

impl RuntimeFaults {
    fn record_terminal(&mut self, fault: WgpuViewportError) {
        if !self.terminal_recorded {
            self.pending.push_back(fault);
            self.terminal_recorded = true;
        }
    }

    fn record_non_terminal(&mut self, fault: WgpuViewportError) {
        self.pending.push_back(fault);
    }

    fn has_pending(&self) -> bool {
        !self.pending.is_empty()
    }

    fn take_next(&mut self) -> Option<WgpuViewportError> {
        self.pending.pop_front()
    }

    fn drain(&mut self) -> Vec<WgpuViewportError> {
        self.pending.drain(..).collect()
    }
}

impl fmt::Debug for RuntimeControl {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RuntimeControl")
            .field("context", &self.binding.id())
            .field("state", &self.state.get())
            .field("has_renderer", &self.renderer.borrow().is_some())
            .field("callback_state", &self.callback_state.get())
            .finish_non_exhaustive()
    }
}

impl RuntimeControl {
    fn new(context: &Context, renderer: WgpuRenderer, globals: Option<GlobalHandles>) -> Self {
        Self {
            context_raw: context.as_raw(),
            binding: context.binding(),
            identity: RuntimeIdentity::new(),
            state: Cell::new(RuntimeState::Constructing),
            renderer: RefCell::new(Some(Box::new(renderer))),
            globals: RefCell::new(globals),
            attachment: RefCell::new(None),
            callback_state: Cell::new(CallbackState::Unclaimed),
            faults: RefCell::new(RuntimeFaults::default()),
            frame_trace: RefCell::new(FrameTraceState::default()),
            #[cfg(test)]
            panic_next_callback: Cell::new(false),
            #[cfg(test)]
            fail_next_viewport_cleanup: Cell::new(false),
            #[cfg(test)]
            transitions: RefCell::new(Vec::new()),
        }
    }

    pub(super) fn context_raw(&self) -> *mut dear_imgui_rs::sys::ImGuiContext {
        self.context_raw
    }

    pub(super) fn binding(&self) -> &ContextBinding {
        &self.binding
    }

    pub(super) fn globals(&self) -> Option<GlobalHandles> {
        self.globals.borrow().clone()
    }

    pub(super) fn is_callback_accessible(&self) -> bool {
        self.state.get() == RuntimeState::Attached
            && self.callback_state.get() != CallbackState::Released
    }

    pub(super) fn is_cleanup_callback_accessible(&self) -> bool {
        matches!(
            self.state.get(),
            RuntimeState::Attached | RuntimeState::ShuttingDown
        ) && self.callback_state.get() == CallbackState::Claimed
    }

    pub(super) fn should_detect_callback_drift(&self) -> bool {
        self.state.get() == RuntimeState::Attached
            && self.callback_state.get() == CallbackState::Claimed
    }

    pub(super) fn callback_released(&self) -> bool {
        self.callback_state.get() == CallbackState::Released
    }

    pub(super) fn mark_callback_claimed(&self) {
        self.callback_state.set(CallbackState::Claimed);
    }

    pub(super) fn mark_callback_released(&self) {
        self.callback_state.set(CallbackState::Released);
        unregister_runtime(self.binding.id());
    }

    fn set_state(&self, state: RuntimeState) {
        #[cfg(test)]
        let previous = self.state.replace(state);
        #[cfg(not(test))]
        self.state.set(state);
        #[cfg(test)]
        if previous != state {
            match state {
                RuntimeState::ShuttingDown => self.transitions.borrow_mut().push("ShuttingDown"),
                RuntimeState::Detached => self.transitions.borrow_mut().push("Detached"),
                RuntimeState::ResourceDropped => {
                    self.transitions.borrow_mut().push("ResourceDropped");
                }
                RuntimeState::Constructing | RuntimeState::Attached => {}
            }
        }
    }

    pub(super) fn begin_shutdown(&self) {
        if matches!(
            self.state.get(),
            RuntimeState::Constructing | RuntimeState::Attached
        ) {
            self.set_state(RuntimeState::ShuttingDown);
        }
    }

    fn mark_detached(&self) {
        if !matches!(
            self.state.get(),
            RuntimeState::Detached | RuntimeState::ResourceDropped
        ) {
            self.set_state(RuntimeState::Detached);
        }
        unregister_runtime(self.binding.id());
    }

    pub(super) fn record_fault(&self, fault: WgpuViewportError) {
        self.faults.borrow_mut().record_non_terminal(fault);
    }

    fn record_terminal_fault(&self, fault: WgpuViewportError) {
        self.faults.borrow_mut().record_terminal(fault);
    }

    fn begin_frame_trace(&self) -> Result<(), WgpuViewportError> {
        self.ensure_entry()?;
        if self.frame_trace.borrow_mut().begin() {
            Ok(())
        } else {
            Err(WgpuViewportError::FrameTraceAlreadyActive)
        }
    }

    fn finish_frame_trace(&self) -> WgpuViewportFrameReport {
        self.frame_trace.borrow_mut().finish()
    }

    fn abort_frame_trace(&self) {
        self.frame_trace.borrow_mut().abort();
    }

    pub(super) fn record_viewport_render_submitted(&self, viewport_id: dear_imgui_rs::Id) {
        self.frame_trace
            .borrow_mut()
            .record_render_submitted(viewport_id);
    }

    pub(super) fn record_viewport_present_submitted(&self, viewport_id: dear_imgui_rs::Id) {
        self.frame_trace
            .borrow_mut()
            .record_present_submitted(viewport_id);
    }

    pub(super) fn record_runtime_contract_fault(&self, fault: WgpuViewportError) {
        let _ = self.binding.try_with_bound_context(|| {
            revoke_renderer_viewport_capability_if_owned(self);
        });
        self.record_terminal_fault(fault);
        self.begin_shutdown();
    }

    /// Returns whether this runtime can still prove a WGPU core renderer publication on the
    /// bound Context. A reentrant mutable borrow is not proof of ownership, so it preserves the
    /// shared capability bit until a later teardown can inspect the exact publications.
    pub(super) fn owns_core_renderer_publication_bound(&self) -> bool {
        let Ok(renderer) = self.renderer.try_borrow() else {
            return false;
        };
        renderer
            .as_deref()
            .is_some_and(WgpuRenderer::owns_context_publication_bound)
    }

    pub(super) fn record_entry_fault(&self, fault: WgpuViewportError) {
        if matches!(
            &fault,
            WgpuViewportError::Renderer(RendererError::RendererStateDrift { .. })
                | WgpuViewportError::RendererUserDataOwnershipLost { .. }
                | WgpuViewportError::CallbackPanicked { .. }
                | WgpuViewportError::SurfaceRejected { .. }
        ) {
            self.record_runtime_contract_fault(fault);
        } else {
            self.record_fault(fault);
        }
    }

    pub(super) fn core_renderer_contract_fault(&self) -> Option<WgpuViewportError> {
        let renderer = match self.renderer.try_borrow() {
            Ok(renderer) => renderer,
            Err(_) => {
                return Some(WgpuViewportError::CallbackReentered {
                    callback: "renderer contract validation",
                });
            }
        };
        let renderer = renderer
            .as_deref()
            .ok_or(WgpuViewportError::RuntimeDetached);
        match renderer {
            Ok(renderer) => renderer.ensure_renderer_contract().err().map(Into::into),
            Err(error) => Some(error),
        }
    }

    fn detect_and_take_fault(&self) -> Option<WgpuViewportError> {
        detect_runtime_contract_drift(self);
        self.faults.borrow_mut().take_next()
    }

    fn detect_and_drain_faults(&self) -> Vec<WgpuViewportError> {
        detect_runtime_contract_drift(self);
        self.faults.borrow_mut().drain()
    }

    fn ensure_context(&self, context: &Context) -> Result<(), WgpuViewportError> {
        if context.id() == self.binding.id() {
            Ok(())
        } else {
            Err(WgpuViewportError::ContextMismatch {
                expected: self.binding.id(),
                actual: context.id(),
            })
        }
    }

    fn ensure_entry(&self) -> Result<(), WgpuViewportError> {
        if let Some(fault) = self.detect_and_take_fault() {
            return Err(fault);
        }
        if self.state.get() == RuntimeState::Attached {
            Ok(())
        } else {
            Err(WgpuViewportError::RuntimeDetached)
        }
    }

    fn finish_entry(&self) -> Result<(), WgpuViewportError> {
        self.detect_and_take_fault().map_or(Ok(()), Err)
    }

    fn with_renderer_mut<R>(
        &self,
        callback: impl FnOnce(&mut WgpuRenderer) -> Result<R, WgpuViewportError>,
    ) -> Result<R, WgpuViewportError> {
        self.ensure_entry()?;
        let result = {
            let mut renderer = self.renderer.try_borrow_mut().map_err(|_| {
                WgpuViewportError::CallbackReentered {
                    callback: "Rust runtime entry",
                }
            })?;
            let renderer = renderer
                .as_deref_mut()
                .ok_or(WgpuViewportError::RuntimeDetached)?;
            callback(renderer)
        };
        let result = match result {
            Ok(result) => result,
            Err(error) => {
                if matches!(
                    &error,
                    WgpuViewportError::Renderer(RendererError::RendererStateDrift { .. })
                ) {
                    self.record_runtime_contract_fault(error);
                    return Err(self
                        .detect_and_take_fault()
                        .unwrap_or(WgpuViewportError::RuntimeDetached));
                }
                return Err(error);
            }
        };
        self.finish_entry()?;
        Ok(result)
    }

    pub(super) fn with_renderer_callback(
        &self,
        callback_name: &'static str,
        callback: impl FnOnce(&mut WgpuRenderer, &GlobalHandles) -> Result<(), WgpuViewportError>,
    ) {
        detect_runtime_contract_drift(self);
        if self.state.get() != RuntimeState::Attached || self.faults.borrow().has_pending() {
            return;
        }
        let Ok(mut renderer) = self.renderer.try_borrow_mut() else {
            self.record_fault(WgpuViewportError::CallbackReentered {
                callback: callback_name,
            });
            return;
        };
        let Some(renderer) = renderer.as_deref_mut() else {
            self.record_fault(WgpuViewportError::RuntimeDetached);
            return;
        };
        let Some(globals) = self.globals() else {
            self.record_fault(WgpuViewportError::RuntimeDetached);
            return;
        };
        if let Err(error) = callback(renderer, &globals) {
            self.record_entry_fault(error);
        }
    }

    fn preflight_renderer_shutdown(&self, context: &mut Context) -> Result<(), WgpuViewportError> {
        let renderer =
            self.renderer
                .try_borrow()
                .map_err(|_| WgpuViewportError::CallbackReentered {
                    callback: "WGPU viewport runtime shutdown preflight",
                })?;
        renderer
            .as_deref()
            .ok_or(WgpuViewportError::RuntimeDetached)?
            .preflight_shutdown(context)
            .map_err(Into::into)
    }

    fn release_renderer_explicit(&self, context: &mut Context) -> Result<(), WgpuViewportError> {
        if self.renderer.borrow().is_none() {
            self.globals.borrow_mut().take();
            self.set_state(RuntimeState::ResourceDropped);
            return Ok(());
        }
        let mut renderer =
            self.renderer
                .try_borrow_mut()
                .map_err(|_| WgpuViewportError::CallbackReentered {
                    callback: "WGPU viewport runtime shutdown",
                })?;
        renderer
            .as_deref_mut()
            .ok_or(WgpuViewportError::RuntimeDetached)?
            .shutdown(context)?;
        let renderer = renderer.take();
        drop(renderer);
        self.globals.borrow_mut().take();
        self.set_state(RuntimeState::ResourceDropped);
        Ok(())
    }

    fn release_renderer_during_context_teardown(
        &self,
        context: &ContextTeardown<'_>,
    ) -> Result<(), ContextAttachmentTeardownError> {
        if self.state.get() == RuntimeState::ResourceDropped {
            return Ok(());
        }

        // Do not acquire the Context reset transaction until every visible sidecar still proves
        // exact ownership. This is read-only, so either failure leaves callback publication,
        // renderer resources, and the consumer intact for Context's fail-stop path.
        preflight_renderer_viewport_resources(self).map_err(|error| {
            let message = error.to_string();
            self.record_fault(error);
            ContextAttachmentTeardownError::new(message)
        })?;

        if self.renderer.borrow().is_none() {
            self.mark_detached();
            self.globals.borrow_mut().take();
            self.set_state(RuntimeState::ResourceDropped);
            return Ok(());
        }

        let mut renderer_slot = self.renderer.try_borrow_mut().map_err(|_| {
            ContextAttachmentTeardownError::new(
                "WGPU renderer was reentered during Context renderer-resource teardown",
            )
        })?;
        let renderer = renderer_slot.as_deref_mut().ok_or_else(|| {
            ContextAttachmentTeardownError::new(
                "WGPU renderer disappeared during Context renderer-resource teardown",
            )
        })?;

        renderer.shutdown_during_context_teardown(context, || {
            self.begin_shutdown();
            destroy_renderer_viewport_resources(self).map_err(|error| {
                let message = error.to_string();
                self.record_fault(error);
                ContextAttachmentTeardownError::new(message)
            })?;
            release_callbacks(self).map_err(|error| {
                let message = error.to_string();
                self.record_fault(error);
                ContextAttachmentTeardownError::new(message)
            })?;
            self.mark_detached();
            Ok(())
        })?;

        let renderer = renderer_slot.take();
        drop(renderer);
        self.globals.borrow_mut().take();
        self.set_state(RuntimeState::ResourceDropped);
        Ok(())
    }

    fn shutdown_once(&self, mut action: ShutdownAction<'_>) -> Result<(), WgpuViewportError> {
        if self.state.get() == RuntimeState::ResourceDropped {
            self.detach_attachment();
            return Ok(());
        }

        // An explicit shutdown is retryable. Validate that no live renderer epoch prevents the
        // reset before mutating viewport sidecars, surfaces, callbacks, or runtime state.
        if let ShutdownAction::Explicit(context) = &mut action {
            self.preflight_renderer_shutdown(context)?;
        }

        // A foreign write to one sidecar makes the active DestroyWindow callback the only safe
        // reclaim path. Verify every reachable slot before changing the runtime state, dropping
        // any sidecar, or clearing callback publication.
        preflight_renderer_viewport_resources(self)?;

        self.begin_shutdown();
        let viewport_result = if matches!(action, ShutdownAction::Quiesce) {
            Ok(())
        } else {
            destroy_renderer_viewport_resources(self)
        };
        let mut viewport_error = viewport_result.err();
        if matches!(action, ShutdownAction::Explicit(_))
            && let Some(error) = viewport_error.take()
        {
            return Err(error);
        }
        let callback_result = release_callbacks(self);

        match action {
            ShutdownAction::Quiesce => callback_result,
            ShutdownAction::Explicit(context) => {
                self.mark_detached();
                let renderer_result = self.release_renderer_explicit(context);
                if self.state.get() == RuntimeState::ResourceDropped {
                    self.detach_attachment();
                }
                first_error([viewport_error, callback_result.err(), renderer_result.err()])
            }
        }
    }

    fn owner_dropped(&self) {
        if self.state.get() == RuntimeState::ResourceDropped {
            return;
        }
        match self.binding.lifecycle() {
            // Drop lacks an exclusive `&mut Context`, so it cannot prepare and commit the
            // renderer-texture reset transaction. Keep the renderer, sidecars, callback table,
            // and attachment alive for Context's ordered terminal teardown.
            ContextLifecycle::Alive => self.defer_attachment_to_context(),
            // Context already owns this attachment and is currently executing its teardown
            // phases. Entering native code here would violate that ordering.
            ContextLifecycle::Dropping => {}
            // Context teardown normally calls `context_destroyed` before the wrapper can be
            // released. This idempotent fallback touches only Rust-owned allocations and never
            // tries to make a destroyed native Context current.
            ContextLifecycle::NativeDestroyed => self.mark_context_destroyed(),
            _ => {}
        }
    }

    fn store_attachment(&self, attachment: ContextAttachmentLease) {
        self.attachment.borrow_mut().replace(attachment);
    }

    fn detach_attachment(&self) {
        if let Some(mut attachment) = self.attachment.borrow_mut().take() {
            let _ = attachment
                .detach()
                .expect("a renderer attachment cannot have a platform release dependency");
        }
    }

    fn defer_attachment_to_context(&self) {
        if let Some(attachment) = self.attachment.borrow_mut().take() {
            attachment.defer_to_context();
        }
    }

    fn recover_renderer(&self) -> WgpuRenderer {
        self.globals.borrow_mut().take();
        *self
            .renderer
            .borrow_mut()
            .take()
            .expect("failed WGPU runtime construction lost its renderer")
    }

    fn mark_context_destroyed(&self) {
        unregister_runtime(self.binding.id());
        // Native viewport slots are no longer touched after Context destruction, but the sidecar
        // still owns every remaining renderer allocation.
        drop_orphaned_viewport_data(self.binding.id());
        if self.renderer.borrow().is_some() {
            let mut renderer = self.renderer.borrow_mut();
            if let Some(renderer) = renderer.as_deref_mut() {
                renderer.shutdown_after_context_destroyed();
            }
            renderer.take();
            self.globals.borrow_mut().take();
        }
        self.attachment.borrow_mut().take();
        self.set_state(RuntimeState::ResourceDropped);
    }

    #[cfg(test)]
    pub(super) fn state(&self) -> RuntimeState {
        self.state.get()
    }

    #[cfg(test)]
    pub(super) fn borrow_renderer_for_test(
        &self,
    ) -> std::cell::RefMut<'_, Option<Box<WgpuRenderer>>> {
        self.renderer.borrow_mut()
    }

    #[cfg(test)]
    pub(super) fn has_renderer_for_test(&self) -> bool {
        self.renderer.borrow().is_some()
    }

    #[cfg(test)]
    pub(super) fn renderer_address_for_test(&self) -> *const WgpuRenderer {
        self.renderer
            .borrow()
            .as_deref()
            .map_or(std::ptr::null(), std::ptr::from_ref)
    }

    #[cfg(test)]
    pub(super) fn panic_next_callback_for_test(&self) {
        self.panic_next_callback.set(true);
    }

    #[cfg(test)]
    pub(super) fn maybe_panic_callback_for_test(&self) {
        assert!(
            !self.panic_next_callback.replace(false),
            "injected WGPU viewport callback panic"
        );
    }

    #[cfg(test)]
    pub(super) fn fail_next_viewport_cleanup_for_test(&self) {
        self.fail_next_viewport_cleanup.set(true);
    }

    #[cfg(test)]
    pub(super) fn take_viewport_cleanup_failure_for_test(&self) -> bool {
        self.fail_next_viewport_cleanup.replace(false)
    }

    #[cfg(test)]
    pub(super) fn transition_log_for_test(&self) -> Vec<&'static str> {
        self.transitions.borrow().clone()
    }
}

impl ContextAttachment for RuntimeControl {
    fn quiesce(&self, context: &ContextTeardown<'_>) -> Result<(), ContextAttachmentTeardownError> {
        context.with_bound_context(|| {
            self.shutdown_once(ShutdownAction::Quiesce)
                .map_err(|error| {
                    let message = error.to_string();
                    self.record_fault(error);
                    ContextAttachmentTeardownError::new(message)
                })
        })
    }

    fn release_renderer_resources(
        &self,
        context: &ContextTeardown<'_>,
    ) -> Result<(), ContextAttachmentTeardownError> {
        context.with_bound_context(|| self.release_renderer_during_context_teardown(context))
    }

    fn context_destroyed(&self, _context: ContextDestroyed) {
        self.mark_context_destroyed();
    }
}

/// Backend-local owning runtime shared by the Winit and SDL3 typed wrappers.
pub(crate) struct OwningViewportRuntime {
    control: Rc<RuntimeControl>,
}

/// A non-nestable trace scope for one secondary-viewport rendering pass.
///
/// Call [`Self::finish`] before acquiring or presenting the application's main surface to obtain
/// a report that proves which secondary surfaces completed renderer submission and presentation
/// within this scope. Dropping the guard discards the partial trace.
#[must_use = "finish the frame trace to obtain its report"]
pub(super) struct FrameTraceGuard<'runtime> {
    control: &'runtime RuntimeControl,
    active: bool,
}

/// Main-viewport frame whose managed textures and secondary viewports are already complete.
///
/// The owning viewport runtime is the only constructor. Applications may inspect secondary WSI
/// evidence before acquiring the main surface, then consume this capability with the route's
/// `render_main` method.
#[must_use = "render or explicitly drop the prepared main-viewport frame"]
pub struct WgpuPreparedViewportFrame<'frame> {
    frame: ReconciledFrame<'frame>,
    secondary: WgpuViewportFrameReport,
    runtime: Rc<RuntimeIdentity>,
}

impl WgpuPreparedViewportFrame<'_> {
    /// Returns the Dear ImGui Context identity carried by this prepared frame.
    #[must_use]
    pub fn context_id(&self) -> ContextId {
        self.frame.context_id()
    }

    /// Returns same-scope evidence for completed secondary submissions and presentations.
    #[must_use]
    pub fn secondary_report(&self) -> &WgpuViewportFrameReport {
        &self.secondary
    }
}

impl FrameTraceGuard<'_> {
    /// Ends the trace and returns its normalized, same-scope submission evidence.
    pub(super) fn finish(mut self) -> WgpuViewportFrameReport {
        let report = self.control.finish_frame_trace();
        self.active = false;
        report
    }
}

impl Drop for FrameTraceGuard<'_> {
    fn drop(&mut self) {
        if self.active {
            self.control.abort_frame_trace();
        }
    }
}

impl fmt::Debug for OwningViewportRuntime {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OwningViewportRuntime")
            .field("control", &self.control)
            .finish()
    }
}

impl OwningViewportRuntime {
    pub(super) fn begin_frame_trace(&self) -> Result<FrameTraceGuard<'_>, WgpuViewportError> {
        self.control.begin_frame_trace()?;
        Ok(FrameTraceGuard {
            control: self.control.as_ref(),
            active: true,
        })
    }

    pub(crate) fn attach(
        context: &mut Context,
        renderer: WgpuRenderer,
    ) -> Result<Self, WgpuViewportAttachError> {
        // The Context-owned attachment is the first ownership gate. In particular, a wrapper
        // that was dropped without explicit shutdown leaves this runtime alive for Context
        // teardown, so a replacement must be rejected without inspecting or mutating its
        // renderer argument.
        if let Err(error) = preflight_runtime(context.id()) {
            return Err(WgpuViewportAttachError::new(error, renderer));
        }
        if let Err(error) = renderer.ensure_context_matches(context) {
            let error = match error {
                RendererError::ContextDropped => WgpuViewportError::RendererContextDropped,
                RendererError::ContextMismatch => WgpuViewportError::RendererContextMismatch,
                other => WgpuViewportError::Renderer(other),
            };
            return Err(WgpuViewportAttachError::new(error, renderer));
        }
        if let Err(error) = renderer.ensure_renderer_contract() {
            return Err(WgpuViewportAttachError::new(error.into(), renderer));
        }
        let globals = match renderer_globals(&renderer) {
            Ok(globals) => globals,
            Err(error) => return Err(WgpuViewportAttachError::new(error, renderer)),
        };
        Self::attach_preflighted(context, renderer, Some(globals))
    }

    fn attach_preflighted(
        context: &mut Context,
        renderer: WgpuRenderer,
        globals: Option<GlobalHandles>,
    ) -> Result<Self, WgpuViewportAttachError> {
        if let Err(error) = preflight_callbacks(context) {
            return Err(WgpuViewportAttachError::new(error, renderer));
        }
        if let Err(error) = preflight_runtime(context.id()) {
            return Err(WgpuViewportAttachError::new(error, renderer));
        }

        if let Err(error) = renderer.ensure_renderer_contract() {
            return Err(WgpuViewportAttachError::new(error.into(), renderer));
        }
        let control = Rc::new(RuntimeControl::new(context, renderer, globals));
        let attachment = match context.register_attachment::<WgpuRendererAttachmentMarker>(
            ContextAttachmentRole::Renderer,
            Rc::clone(&control) as Rc<dyn ContextAttachment>,
        ) {
            Ok(attachment) => attachment,
            Err(error) => {
                let renderer = control.recover_renderer();
                return Err(WgpuViewportAttachError::new(error.into(), renderer));
            }
        };
        control.store_attachment(attachment);
        register_runtime(&control);
        claim_callbacks(&control, context);
        control.set_state(RuntimeState::Attached);
        Ok(Self { control })
    }

    #[cfg(test)]
    pub(super) fn attach_for_test(
        context: &mut Context,
        mut renderer: WgpuRenderer,
    ) -> Result<Self, WgpuViewportAttachError> {
        if let Err(error) = preflight_runtime(context.id()) {
            return Err(WgpuViewportAttachError::new(error, renderer));
        }
        if renderer.context_state.is_none() {
            let (flags, _) = match WgpuRenderer::configure_imgui_context(context) {
                Ok(configured) => configured,
                Err(error) => {
                    return Err(WgpuViewportAttachError::new(error.into(), renderer));
                }
            };
            if let Err(error) = renderer.bind_context(context, flags) {
                return Err(WgpuViewportAttachError::new(error.into(), renderer));
            }
            renderer.renderer_consumer = match context.create_synchronous_renderer_consumer() {
                Ok(consumer) => Some(consumer),
                Err(error) => {
                    return Err(WgpuViewportAttachError::new(
                        RendererError::from(error).into(),
                        renderer,
                    ));
                }
            };
        }
        Self::attach_preflighted(context, renderer, None)
    }

    pub(crate) fn poll_fault(&self) -> Result<(), WgpuViewportError> {
        self.control.detect_and_take_fault().map_or(Ok(()), Err)
    }

    pub(crate) fn drain_faults(&self) -> Vec<WgpuViewportError> {
        self.control.detect_and_drain_faults()
    }

    pub(crate) fn context_id(&self) -> ContextId {
        self.control.binding().id()
    }

    /// Rejects a frame whose UI belongs to another Context before entering any renderer-owned
    /// state. Route adapters call this before their platform transaction, and `prepare_frame`
    /// repeats it at the owning runtime boundary.
    pub(crate) fn ensure_frame_context(&self, actual: ContextId) -> Result<(), WgpuViewportError> {
        let expected = self.context_id();
        if expected == actual {
            Ok(())
        } else {
            Err(WgpuViewportError::ContextMismatch { expected, actual })
        }
    }

    pub(crate) fn prepare_frame<'frame>(
        &self,
        frame: FrameToken<'frame>,
    ) -> Result<WgpuPreparedViewportFrame<'frame>, WgpuViewportError> {
        self.ensure_frame_context(frame.ui().context_id())?;
        let frame = self.control.with_renderer_mut(|renderer| {
            let frame = frame
                .try_render(renderer.renderer_consumer()?)
                .map_err(RendererError::from)?;
            renderer
                .reconcile_frame(frame)
                .map_err(WgpuViewportError::from)
        })?;
        self.prepare_reconciled(frame)
    }

    fn prepare_reconciled<'frame>(
        &self,
        mut frame: ReconciledFrame<'frame>,
    ) -> Result<WgpuPreparedViewportFrame<'frame>, WgpuViewportError> {
        self.poll_fault()?;
        let trace = self.begin_frame_trace()?;
        frame.update_and_render_platform_windows_default();
        let secondary = trace.finish();
        self.poll_fault()?;
        Ok(WgpuPreparedViewportFrame {
            frame,
            secondary,
            runtime: Rc::clone(&self.control.identity),
        })
    }

    fn ensure_prepared_runtime(
        &self,
        runtime: &Rc<RuntimeIdentity>,
        actual: ContextId,
    ) -> Result<(), WgpuViewportError> {
        if Rc::ptr_eq(&self.control.identity, runtime) {
            Ok(())
        } else {
            Err(WgpuViewportError::PreparedFrameRuntimeMismatch {
                expected: self.context_id(),
                actual,
            })
        }
    }

    pub(crate) fn render_main(
        &self,
        prepared: WgpuPreparedViewportFrame<'_>,
        render_pass: &mut wgpu::RenderPass<'_>,
        framebuffer_extent: FramebufferExtent,
    ) -> Result<(), WgpuViewportError> {
        self.ensure_prepared_runtime(&prepared.runtime, prepared.context_id())?;
        let WgpuPreparedViewportFrame {
            frame,
            secondary: _,
            runtime: _,
        } = prepared;
        self.control.with_renderer_mut(|renderer| {
            renderer
                .render_reconciled(frame, render_pass, framebuffer_extent)
                .map_err(Into::into)
        })
    }

    pub(crate) fn invalidate_device_objects(
        &self,
        context: &mut Context,
    ) -> Result<(), WgpuViewportError> {
        self.control.ensure_context(context)?;
        self.control.with_renderer_mut(|renderer| {
            renderer
                .invalidate_device_objects(context)
                .map_err(Into::into)
        })
    }

    pub(crate) fn set_gamma_mode(&self, mode: GammaMode) -> Result<(), WgpuViewportError> {
        self.control.with_renderer_mut(|renderer| {
            renderer.set_gamma_mode(mode);
            Ok(())
        })
    }

    pub(crate) fn set_viewport_clear_color(
        &self,
        color: wgpu::Color,
    ) -> Result<(), WgpuViewportError> {
        self.control.with_renderer_mut(|renderer| {
            renderer.set_viewport_clear_color(color);
            Ok(())
        })
    }

    pub(crate) fn register_external_texture(
        &self,
        view: &wgpu::TextureView,
    ) -> Result<ExternalTextureId, WgpuViewportError> {
        self.control.with_renderer_mut(|renderer| {
            renderer.register_external_texture(view).map_err(Into::into)
        })
    }

    pub(crate) fn update_external_texture(
        &self,
        texture: ExternalTextureId,
        view: &wgpu::TextureView,
    ) -> Result<(), WgpuViewportError> {
        self.control.with_renderer_mut(|renderer| {
            renderer
                .update_external_texture(texture, view)
                .map_err(Into::into)
        })
    }

    pub(crate) fn unregister_external_texture(
        &self,
        texture: ExternalTextureId,
    ) -> Result<(), WgpuViewportError> {
        self.control.with_renderer_mut(|renderer| {
            renderer
                .unregister_external_texture(texture)
                .map_err(Into::into)
        })
    }

    pub(crate) fn shutdown(&mut self, context: &mut Context) -> Result<(), WgpuViewportError> {
        self.control.ensure_context(context)?;
        let pending = self.control.detect_and_take_fault();
        let binding = self.control.binding.clone();
        let result = binding
            .try_with_bound_context(|| {
                self.control
                    .shutdown_once(ShutdownAction::Explicit(context))
            })
            .map_err(Into::into)
            .and_then(|result| result);
        match (pending, result) {
            (Some(fault), Err(shutdown_error)) => {
                self.control.record_fault(shutdown_error);
                Err(fault)
            }
            (Some(fault), Ok(())) => Err(fault),
            (None, result) => result,
        }
    }

    #[cfg(test)]
    pub(super) fn renderer_address_for_test(&self) -> *const WgpuRenderer {
        self.control.renderer_address_for_test()
    }

    #[cfg(test)]
    pub(super) fn state_for_test(&self) -> RuntimeState {
        self.control.state()
    }

    #[cfg(test)]
    pub(super) fn transition_log_for_test(&self) -> Vec<&'static str> {
        self.control.transition_log_for_test()
    }

    #[cfg(test)]
    pub(super) fn control_for_test(&self) -> Rc<RuntimeControl> {
        Rc::clone(&self.control)
    }

    #[cfg(test)]
    pub(super) fn ensure_runtime_identity_for_test(
        &self,
        other: &Self,
    ) -> Result<(), WgpuViewportError> {
        self.ensure_prepared_runtime(&other.control.identity, other.context_id())
    }

    #[cfg(test)]
    pub(super) fn panic_next_callback_for_test(&self) {
        self.control.panic_next_callback_for_test();
    }

    #[cfg(test)]
    pub(super) fn fail_next_viewport_cleanup_for_test(&self) {
        self.control.fail_next_viewport_cleanup_for_test();
    }
}

impl Drop for OwningViewportRuntime {
    fn drop(&mut self) {
        self.control.owner_dropped();
    }
}

fn first_error<const N: usize>(
    errors: [Option<WgpuViewportError>; N],
) -> Result<(), WgpuViewportError> {
    errors.into_iter().flatten().next().map_or(Ok(()), Err)
}