dear-imgui-rs 0.13.0

High-level Rust bindings to Dear ImGui v1.92.7 with docking, WGPU/GL backends, and extensions (ImPlot/ImPlot3D, ImNodes, ImGuizmo, file browser, reflection-based UI)
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
//! ImGui context lifecycle
//!
//! Creates, manages and destroys the single active Dear ImGui context used by
//! the crate. Obtain a `Ui` each frame via `Context::frame()` and render using
//! your chosen backend. See struct-level docs for details and caveats about one
//! active context at a time.
//!
use parking_lot::ReentrantMutex;
use std::cell::{RefCell, UnsafeCell};
use std::ffi::CString;
use std::ops::Drop;
use std::path::PathBuf;
use std::ptr;
use std::rc::{Rc, Weak};

use crate::clipboard::{ClipboardBackend, ClipboardContext};
use crate::fonts::{Font, FontAtlas, SharedFontAtlas};
use crate::io::Io;

use crate::sys;

/// An imgui context.
///
/// A context needs to be created to access most library functions. Due to current Dear ImGui
/// design choices, at most one active Context can exist at any time. This limitation will likely
/// be removed in a future Dear ImGui version.
///
/// If you need more than one context, you can use suspended contexts. As long as only one context
/// is active at a time, it's possible to have multiple independent contexts.
///
/// # Examples
///
/// Creating a new active context:
/// ```
/// let ctx = dear_imgui_rs::Context::create();
/// // ctx is dropped naturally when it goes out of scope, which deactivates and destroys the
/// // context
/// ```
///
/// Never try to create an active context when another one is active:
///
/// ```should_panic
/// let ctx1 = dear_imgui_rs::Context::create();
///
/// let ctx2 = dear_imgui_rs::Context::create(); // PANIC
/// ```
#[derive(Debug)]
pub struct Context {
    raw: *mut sys::ImGuiContext,
    alive: Rc<()>,
    shared_font_atlas: Option<SharedFontAtlas>,
    ini_filename: Option<CString>,
    log_filename: Option<CString>,
    platform_name: Option<CString>,
    renderer_name: Option<CString>,
    // We need to box this because we hand imgui a pointer to it,
    // and we don't want to deal with finding `clipboard_ctx`.
    // We also put it in an UnsafeCell since we're going to give
    // imgui a mutable pointer to it.
    clipboard_ctx: Box<UnsafeCell<ClipboardContext>>,
    ui: crate::ui::Ui,
}

// This mutex needs to be used to guard all public functions that can affect the underlying
// Dear ImGui active context
static CTX_MUTEX: ReentrantMutex<()> = parking_lot::const_reentrant_mutex(());

#[derive(Clone)]
struct UserTextureRegistration {
    ctx: *mut sys::ImGuiContext,
    tex: *mut sys::ImTextureData,
    alive: Weak<()>,
}

thread_local! {
    static USER_TEXTURE_REGISTRATIONS: RefCell<Vec<UserTextureRegistration>> = RefCell::new(Vec::new());
}

fn clear_current_context() {
    unsafe {
        sys::igSetCurrentContext(ptr::null_mut());
    }
}

fn no_current_context() -> bool {
    let ctx = unsafe { sys::igGetCurrentContext() };
    ctx.is_null()
}

struct BoundContextGuard {
    prev: *mut sys::ImGuiContext,
    restore: bool,
}

impl BoundContextGuard {
    fn bind(ctx: *mut sys::ImGuiContext) -> Self {
        unsafe {
            let prev = sys::igGetCurrentContext();
            let restore = prev != ctx;
            if restore {
                sys::igSetCurrentContext(ctx);
            }
            Self { prev, restore }
        }
    }
}

impl Drop for BoundContextGuard {
    fn drop(&mut self) {
        if self.restore {
            unsafe {
                sys::igSetCurrentContext(self.prev);
            }
        }
    }
}

fn with_bound_context<R>(ctx: *mut sys::ImGuiContext, f: impl FnOnce() -> R) -> R {
    let _guard = BoundContextGuard::bind(ctx);
    f()
}

fn prune_dead_user_texture_registrations(registrations: &mut Vec<UserTextureRegistration>) {
    registrations.retain(|registration| registration.alive.upgrade().is_some());
}

fn is_user_texture_registered(ctx: *mut sys::ImGuiContext, tex: *mut sys::ImTextureData) -> bool {
    USER_TEXTURE_REGISTRATIONS.with(|registrations| {
        let mut registrations = registrations.borrow_mut();
        prune_dead_user_texture_registrations(&mut registrations);
        registrations
            .iter()
            .any(|registration| registration.ctx == ctx && registration.tex == tex)
    })
}

fn track_user_texture_registration(
    ctx: *mut sys::ImGuiContext,
    tex: *mut sys::ImTextureData,
    alive: Weak<()>,
) {
    USER_TEXTURE_REGISTRATIONS.with(|registrations| {
        let mut registrations = registrations.borrow_mut();
        prune_dead_user_texture_registrations(&mut registrations);
        registrations.push(UserTextureRegistration { ctx, tex, alive });
    });
}

fn take_user_texture_registration(
    ctx: *mut sys::ImGuiContext,
    tex: *mut sys::ImTextureData,
) -> Option<UserTextureRegistration> {
    USER_TEXTURE_REGISTRATIONS.with(|registrations| {
        let mut registrations = registrations.borrow_mut();
        prune_dead_user_texture_registrations(&mut registrations);
        registrations
            .iter()
            .position(|registration| registration.ctx == ctx && registration.tex == tex)
            .map(|index| registrations.remove(index))
    })
}

fn unregister_user_texture_registration(registration: UserTextureRegistration) {
    if registration.ctx.is_null()
        || registration.tex.is_null()
        || registration.alive.upgrade().is_none()
    {
        return;
    }

    unsafe {
        with_bound_context(registration.ctx, || {
            sys::igUnregisterUserTexture(registration.tex);
        });
    }
}

pub(crate) fn unregister_user_texture_from_all_contexts(tex: *mut sys::ImTextureData) {
    if tex.is_null() {
        return;
    }

    let registrations = USER_TEXTURE_REGISTRATIONS.with(|registrations| {
        let mut registrations = registrations.borrow_mut();
        let mut taken = Vec::new();
        let mut index = 0;
        while index < registrations.len() {
            if registrations[index].alive.upgrade().is_none() {
                registrations.remove(index);
            } else if registrations[index].tex == tex {
                taken.push(registrations.remove(index));
            } else {
                index += 1;
            }
        }
        taken
    });

    let _guard = CTX_MUTEX.lock();
    for registration in registrations {
        unregister_user_texture_registration(registration);
    }
}

fn unregister_user_textures_for_context(ctx: *mut sys::ImGuiContext) {
    if ctx.is_null() {
        return;
    }

    let registrations = USER_TEXTURE_REGISTRATIONS.with(|registrations| {
        let mut registrations = registrations.borrow_mut();
        let mut taken = Vec::new();
        let mut index = 0;
        while index < registrations.len() {
            if registrations[index].alive.upgrade().is_none() || registrations[index].ctx == ctx {
                let registration = registrations.remove(index);
                if registration.ctx == ctx {
                    taken.push(registration);
                }
            } else {
                index += 1;
            }
        }
        taken
    });

    for registration in registrations {
        unregister_user_texture_registration(registration);
    }
}

impl Context {
    /// Tries to create a new active Dear ImGui context.
    ///
    /// Returns an error if another context is already active or creation fails.
    pub fn try_create() -> crate::error::ImGuiResult<Context> {
        Self::try_create_internal(None)
    }

    /// Tries to create a new active Dear ImGui context with a shared font atlas.
    pub fn try_create_with_shared_font_atlas(
        shared_font_atlas: SharedFontAtlas,
    ) -> crate::error::ImGuiResult<Context> {
        Self::try_create_internal(Some(shared_font_atlas))
    }

    /// Creates a new active Dear ImGui context (panics on error).
    ///
    /// This aligns with imgui-rs behavior. For fallible creation use `try_create()`.
    pub fn create() -> Context {
        Self::try_create().expect("Failed to create Dear ImGui context")
    }

    /// Creates a new active Dear ImGui context with a shared font atlas (panics on error).
    pub fn create_with_shared_font_atlas(shared_font_atlas: SharedFontAtlas) -> Context {
        Self::try_create_with_shared_font_atlas(shared_font_atlas)
            .expect("Failed to create Dear ImGui context")
    }

    /// Returns the raw `ImGuiContext*` for FFI integrations.
    pub fn as_raw(&self) -> *mut sys::ImGuiContext {
        self.raw
    }

    /// Returns a token that can be used to check whether this context is still alive.
    ///
    /// Useful for extension crates that store raw pointers and need to avoid calling into FFI
    /// after the owning `Context` has been dropped.
    pub fn alive_token(&self) -> ContextAliveToken {
        ContextAliveToken(Rc::downgrade(&self.alive))
    }

    // removed legacy create_or_panic variants (use create()/try_create())

    fn io_ptr(&self, caller: &str) -> *mut sys::ImGuiIO {
        let io = unsafe { sys::igGetIO_ContextPtr(self.raw) };
        if io.is_null() {
            panic!("{caller} requires a valid ImGui context");
        }
        io
    }

    fn platform_io_ptr(&self, caller: &str) -> *mut sys::ImGuiPlatformIO {
        let pio = unsafe { sys::igGetPlatformIO_ContextPtr(self.raw) };
        if pio.is_null() {
            panic!("{caller} requires a valid ImGui context");
        }
        pio
    }

    fn assert_current_context(&self, caller: &str) {
        assert!(
            self.is_current_context(),
            "{caller} requires this context to be current"
        );
    }

    fn try_create_internal(
        mut shared_font_atlas: Option<SharedFontAtlas>,
    ) -> crate::error::ImGuiResult<Context> {
        let _guard = CTX_MUTEX.lock();

        if !no_current_context() {
            return Err(crate::error::ImGuiError::ContextAlreadyActive);
        }

        let shared_font_atlas_ptr = match &mut shared_font_atlas {
            Some(atlas) => atlas.as_ptr_mut(),
            None => ptr::null_mut(),
        };

        // Create the actual ImGui context
        let raw = unsafe { sys::igCreateContext(shared_font_atlas_ptr) };
        if raw.is_null() {
            return Err(crate::error::ImGuiError::ContextCreation {
                reason: "ImGui_CreateContext returned null".to_string(),
            });
        }

        // Set it as the current context
        unsafe {
            sys::igSetCurrentContext(raw);
        }

        Ok(Context {
            raw,
            alive: Rc::new(()),
            shared_font_atlas,
            ini_filename: None,
            log_filename: None,
            platform_name: None,
            renderer_name: None,
            clipboard_ctx: Box::new(UnsafeCell::new(ClipboardContext::dummy())),
            ui: crate::ui::Ui::new(),
        })
    }

    /// Returns a mutable reference to this context's IO object.
    pub fn io_mut(&mut self) -> &mut Io {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            let io_ptr = self.io_ptr("Context::io_mut()");
            &mut *(io_ptr as *mut Io)
        }
    }

    /// Get shared access to this context's IO object.
    pub fn io(&self) -> &crate::io::Io {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            let io_ptr = self.io_ptr("Context::io()");
            &*(io_ptr as *const crate::io::Io)
        }
    }

    /// Get access to the Style structure
    pub fn style(&self) -> &crate::style::Style {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                let style_ptr = sys::igGetStyle();
                if style_ptr.is_null() {
                    panic!("Context::style() requires a valid ImGui context");
                }
                &*(style_ptr as *const crate::style::Style)
            })
        }
    }

    /// Get mutable access to the Style structure
    pub fn style_mut(&mut self) -> &mut crate::style::Style {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                let style_ptr = sys::igGetStyle();
                if style_ptr.is_null() {
                    panic!("Context::style_mut() requires a valid ImGui context");
                }
                &mut *(style_ptr as *mut crate::style::Style)
            })
        }
    }

    /// Creates a new frame and returns a Ui object for building the interface.
    ///
    /// Note: you must update `io.DisplaySize` (and usually `io.DeltaTime`) before calling this,
    /// unless you are using a platform backend that does it for you (e.g. `dear-imgui-winit`).
    pub fn frame(&mut self) -> &mut crate::ui::Ui {
        let _guard = CTX_MUTEX.lock();
        self.assert_current_context("Context::frame()");

        unsafe {
            // Dear ImGui initializes DisplaySize to (-1, -1). Calling NewFrame() without a
            // platform backend (or without setting DisplaySize manually) will trip an internal
            // assertion and abort the process. Fail fast with a Rust panic to make the setup
            // requirement obvious.
            let io = sys::igGetIO_Nil();
            if !io.is_null() && ((*io).DisplaySize.x < 0.0 || (*io).DisplaySize.y < 0.0) {
                panic!(
                    "Context::frame() called with invalid io.DisplaySize ({}, {}). \
Set io.DisplaySize (and typically io.DeltaTime) before starting a frame. \
If you are using a windowing/event-loop library, prefer a platform backend such as \
dear-imgui-winit::WinitPlatform::prepare_frame().",
                    (*io).DisplaySize.x,
                    (*io).DisplaySize.y
                );
            }
            sys::igNewFrame();
        }
        &mut self.ui
    }

    /// Create a new frame with a callback
    pub fn frame_with<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&crate::ui::Ui) -> R,
    {
        let ui = self.frame();
        f(ui)
    }

    /// Renders the frame and returns a reference to the resulting draw data
    ///
    /// This finalizes the Dear ImGui frame and prepares all draw data for rendering.
    /// The returned draw data contains all the information needed to render the frame.
    pub fn render(&mut self) -> &crate::render::DrawData {
        let _guard = CTX_MUTEX.lock();
        self.assert_current_context("Context::render()");

        unsafe {
            sys::igRender();
            let dd = sys::igGetDrawData();
            if dd.is_null() {
                panic!("Context::render() returned null draw data");
            }
            &*(dd as *const crate::render::DrawData)
        }
    }

    /// Gets the draw data for the current frame
    ///
    /// This returns the draw data without calling render. Only valid after
    /// `render()` has been called and before the next `new_frame()`.
    pub fn draw_data(&self) -> Option<&crate::render::DrawData> {
        let _guard = CTX_MUTEX.lock();
        self.assert_current_context("Context::draw_data()");

        unsafe {
            let draw_data = sys::igGetDrawData();
            if draw_data.is_null() {
                None
            } else {
                let data = &*(draw_data as *const crate::render::DrawData);
                if data.valid() { Some(data) } else { None }
            }
        }
    }

    /// Register a user-created texture in ImGui's global texture list (ImGui 1.92+).
    ///
    /// Dear ImGui builds `DrawData::textures()` from its internal `PlatformIO.Textures[]` list.
    /// If you create an `OwnedTextureData` yourself, you must register
    /// it for renderer backends (with `BackendFlags::RENDERER_HAS_TEXTURES`) to receive
    /// Create/Update/Destroy requests automatically.
    ///
    /// Note: `RegisterUserTexture()` is currently an experimental ImGui API.
    ///
    /// The registration is tracked by this crate and will be removed automatically when the
    /// `Context` or the `OwnedTextureData` is dropped.
    pub fn register_user_texture(&mut self, texture: &mut crate::texture::OwnedTextureData) {
        self.register_user_texture_ptr(texture.as_mut().as_raw_mut());
    }

    /// Register a borrowed/raw texture data pointer in ImGui's global texture list.
    ///
    /// Prefer [`Context::register_user_texture`] for `OwnedTextureData`.
    ///
    /// # Safety
    /// The caller must guarantee that `texture` remains alive until it is unregistered, the
    /// owning `Context` is dropped, or the texture owner unregisters it from all contexts before
    /// destruction.
    pub unsafe fn register_user_texture_raw(&mut self, texture: &mut crate::texture::TextureData) {
        self.register_user_texture_ptr(texture.as_raw_mut());
    }

    fn register_user_texture_ptr(&mut self, texture: *mut sys::ImTextureData) {
        let _guard = CTX_MUTEX.lock();
        self.assert_current_context("Context::register_user_texture()");
        assert!(
            !texture.is_null(),
            "Context::register_user_texture() received a null texture"
        );
        if is_user_texture_registered(self.raw, texture) {
            return;
        }
        unsafe {
            sys::igRegisterUserTexture(texture);
        }
        track_user_texture_registration(self.raw, texture, Rc::downgrade(&self.alive));
    }

    /// Register a user-created texture and return an RAII token which unregisters on drop.
    ///
    /// This is a convenience wrapper around `register_user_texture()`.
    pub fn register_user_texture_token(
        &mut self,
        texture: &mut crate::texture::OwnedTextureData,
    ) -> RegisteredUserTexture {
        self.register_user_texture(texture);
        RegisteredUserTexture {
            ctx: self.raw,
            tex: texture.as_mut().as_raw_mut(),
            alive: Rc::downgrade(&self.alive),
        }
    }

    /// Unregister a user texture previously registered with `register_user_texture()`.
    ///
    /// This removes the `ImTextureData*` from ImGui's internal texture list.
    pub fn unregister_user_texture(&mut self, texture: &mut crate::texture::OwnedTextureData) {
        self.unregister_user_texture_ptr(texture.as_mut().as_raw_mut());
    }

    /// Unregister a borrowed/raw user texture previously registered with
    /// [`Context::register_user_texture_raw`].
    ///
    /// # Safety
    /// The pointer must refer to the same live `TextureData` object that was previously
    /// registered for this context.
    pub unsafe fn unregister_user_texture_raw(
        &mut self,
        texture: &mut crate::texture::TextureData,
    ) {
        self.unregister_user_texture_ptr(texture.as_raw_mut());
    }

    fn unregister_user_texture_ptr(&mut self, texture: *mut sys::ImTextureData) {
        let _guard = CTX_MUTEX.lock();
        self.assert_current_context("Context::unregister_user_texture()");
        assert!(
            !texture.is_null(),
            "Context::unregister_user_texture() received a null texture"
        );
        if let Some(registration) = take_user_texture_registration(self.raw, texture) {
            unregister_user_texture_registration(registration);
        }
    }

    /// Sets the INI filename for settings persistence
    ///
    /// # Errors
    ///
    /// Returns an error if the filename contains null bytes
    pub fn set_ini_filename<P: Into<PathBuf>>(
        &mut self,
        filename: Option<P>,
    ) -> crate::error::ImGuiResult<()> {
        use crate::error::SafeStringConversion;
        let _guard = CTX_MUTEX.lock();

        self.ini_filename = match filename {
            Some(f) => Some(f.into().to_string_lossy().to_cstring_safe()?),
            None => None,
        };

        unsafe {
            let io = self.io_ptr("Context::set_ini_filename()");
            let ptr = self
                .ini_filename
                .as_ref()
                .map(|s| s.as_ptr())
                .unwrap_or(ptr::null());
            (*io).IniFilename = ptr;
        }
        Ok(())
    }

    // removed legacy set_ini_filename_or_panic (use set_ini_filename())

    /// Sets the log filename
    ///
    /// # Errors
    ///
    /// Returns an error if the filename contains null bytes
    pub fn set_log_filename<P: Into<PathBuf>>(
        &mut self,
        filename: Option<P>,
    ) -> crate::error::ImGuiResult<()> {
        use crate::error::SafeStringConversion;
        let _guard = CTX_MUTEX.lock();

        self.log_filename = match filename {
            Some(f) => Some(f.into().to_string_lossy().to_cstring_safe()?),
            None => None,
        };

        unsafe {
            let io = self.io_ptr("Context::set_log_filename()");
            let ptr = self
                .log_filename
                .as_ref()
                .map(|s| s.as_ptr())
                .unwrap_or(ptr::null());
            (*io).LogFilename = ptr;
        }
        Ok(())
    }

    // removed legacy set_log_filename_or_panic (use set_log_filename())

    /// Sets the platform name
    ///
    /// # Errors
    ///
    /// Returns an error if the name contains null bytes
    pub fn set_platform_name<S: Into<String>>(
        &mut self,
        name: Option<S>,
    ) -> crate::error::ImGuiResult<()> {
        use crate::error::SafeStringConversion;
        let _guard = CTX_MUTEX.lock();

        self.platform_name = match name {
            Some(n) => Some(n.into().to_cstring_safe()?),
            None => None,
        };

        unsafe {
            let io = self.io_ptr("Context::set_platform_name()");
            let ptr = self
                .platform_name
                .as_ref()
                .map(|s| s.as_ptr())
                .unwrap_or(ptr::null());
            (*io).BackendPlatformName = ptr;
        }
        Ok(())
    }

    // removed legacy set_platform_name_or_panic (use set_platform_name())

    /// Sets the renderer name
    ///
    /// # Errors
    ///
    /// Returns an error if the name contains null bytes
    pub fn set_renderer_name<S: Into<String>>(
        &mut self,
        name: Option<S>,
    ) -> crate::error::ImGuiResult<()> {
        use crate::error::SafeStringConversion;
        let _guard = CTX_MUTEX.lock();

        self.renderer_name = match name {
            Some(n) => Some(n.into().to_cstring_safe()?),
            None => None,
        };

        unsafe {
            let io = self.io_ptr("Context::set_renderer_name()");
            let ptr = self
                .renderer_name
                .as_ref()
                .map(|s| s.as_ptr())
                .unwrap_or(ptr::null());
            (*io).BackendRendererName = ptr;
        }
        Ok(())
    }

    // removed legacy set_renderer_name_or_panic (use set_renderer_name())

    /// Get shared access to the platform IO.
    ///
    /// Note: `ImGuiPlatformIO` exists even when multi-viewport is disabled. We expose it
    /// unconditionally so callers can use ImGui 1.92+ texture management via `PlatformIO.Textures[]`.
    pub fn platform_io(&self) -> &crate::platform_io::PlatformIo {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            let pio = self.platform_io_ptr("Context::platform_io()");
            crate::platform_io::PlatformIo::from_raw(pio)
        }
    }

    /// Get mutable access to the platform IO.
    ///
    /// Note: `ImGuiPlatformIO` exists even when multi-viewport is disabled. We expose it
    /// unconditionally so callers can use ImGui 1.92+ texture management via `PlatformIO.Textures[]`.
    pub fn platform_io_mut(&mut self) -> &mut crate::platform_io::PlatformIo {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            let pio = self.platform_io_ptr("Context::platform_io_mut()");
            crate::platform_io::PlatformIo::from_raw_mut(pio)
        }
    }

    /// Returns a reference to the main Dear ImGui viewport.
    ///
    /// The returned reference is owned by this ImGui context and
    /// must not be used after the context is destroyed.
    #[doc(alias = "GetMainViewport")]
    pub fn main_viewport(&mut self) -> &crate::platform_io::Viewport {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                let ptr = sys::igGetMainViewport();
                if ptr.is_null() {
                    panic!("Context::main_viewport() requires a valid ImGui context");
                }
                crate::platform_io::Viewport::from_raw(ptr as *const sys::ImGuiViewport)
            })
        }
    }

    /// Enable multi-viewport support flags
    #[cfg(feature = "multi-viewport")]
    pub fn enable_multi_viewport(&mut self) {
        // Enable viewport flags
        crate::viewport_backend::utils::enable_viewport_flags(self.io_mut());
    }

    /// Update platform windows
    ///
    /// This function should be called every frame when multi-viewport is enabled.
    /// It updates all platform windows and handles viewport management.
    #[cfg(feature = "multi-viewport")]
    pub fn update_platform_windows(&mut self) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                // Ensure main viewport is properly set up before updating platform windows
                let main_viewport = sys::igGetMainViewport();
                if !main_viewport.is_null() && (*main_viewport).PlatformHandle.is_null() {
                    eprintln!(
                        "update_platform_windows: main viewport not set up, setting it up now"
                    );
                    // The main viewport needs to be set up - this should be done by the backend
                    // For now, we'll just log this and continue
                }

                sys::igUpdatePlatformWindows();
            });
        }
    }

    /// Render platform windows with default implementation
    ///
    /// This function renders all platform windows using the default implementation.
    /// It calls the platform and renderer backends to render each viewport.
    #[cfg(feature = "multi-viewport")]
    pub fn render_platform_windows_default(&mut self) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                sys::igRenderPlatformWindowsDefault(std::ptr::null_mut(), std::ptr::null_mut());
            });
        }
    }

    /// Destroy all platform windows
    ///
    /// This function should be called during shutdown to properly clean up
    /// all platform windows and their associated resources.
    #[cfg(feature = "multi-viewport")]
    pub fn destroy_platform_windows(&mut self) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                sys::igDestroyPlatformWindows();
            });
        }
    }

    /// Suspends this context so another context can be the active context
    pub fn suspend(self) -> SuspendedContext {
        let _guard = CTX_MUTEX.lock();
        assert!(
            self.is_current_context(),
            "context to be suspended is not the active context"
        );
        clear_current_context();
        SuspendedContext(self)
    }

    fn is_current_context(&self) -> bool {
        let ctx = unsafe { sys::igGetCurrentContext() };
        self.raw == ctx
    }

    /// Push a font onto the font stack
    pub fn push_font(&mut self, font: &Font) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                sys::igPushFont(font.raw(), 0.0);
            });
        }
    }

    /// Pop a font from the font stack
    ///
    /// This restores the previous font. Must be paired with a call to `push_font()`.
    #[doc(alias = "PopFont")]
    pub fn pop_font(&mut self) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                sys::igPopFont();
            });
        }
    }

    /// Get the current font
    #[doc(alias = "GetFont")]
    pub fn current_font(&self) -> &Font {
        let _guard = CTX_MUTEX.lock();
        unsafe { with_bound_context(self.raw, || Font::from_raw(sys::igGetFont() as *const _)) }
    }

    /// Get the current font size
    #[doc(alias = "GetFontSize")]
    pub fn current_font_size(&self) -> f32 {
        let _guard = CTX_MUTEX.lock();
        unsafe { with_bound_context(self.raw, || sys::igGetFontSize()) }
    }

    /// Get the font atlas from the IO structure
    pub fn font_atlas(&self) -> FontAtlas {
        let _guard = CTX_MUTEX.lock();

        // wasm32 import-style builds keep Dear ImGui state in a separate module
        // and share linear memory. When the experimental font-atlas feature is
        // enabled, we allow direct access to the atlas pointer, assuming the
        // provider has been correctly configured via xtask.
        #[cfg(all(target_arch = "wasm32", feature = "wasm-font-atlas-experimental"))]
        unsafe {
            let io = self.io_ptr("Context::font_atlas()");
            let atlas_ptr = (*io).Fonts;
            assert!(
                !atlas_ptr.is_null(),
                "ImGui IO Fonts pointer is null on wasm; provider not initialized?"
            );
            FontAtlas::from_raw(atlas_ptr)
        }

        // Default wasm path: keep this API disabled to avoid accidental UB.
        #[cfg(all(target_arch = "wasm32", not(feature = "wasm-font-atlas-experimental")))]
        {
            panic!(
                "font_atlas() is not supported on wasm32 targets without \
                 `wasm-font-atlas-experimental` feature; \
                 see docs/WASM.md for current limitations."
            );
        }

        #[cfg(not(target_arch = "wasm32"))]
        unsafe {
            let io = self.io_ptr("Context::font_atlas()");
            let atlas_ptr = (*io).Fonts;
            FontAtlas::from_raw(atlas_ptr)
        }
    }

    /// Get a mutable reference to the font atlas from the IO structure
    pub fn font_atlas_mut(&mut self) -> FontAtlas {
        let _guard = CTX_MUTEX.lock();

        // wasm32 import-style builds keep Dear ImGui state in a separate module
        // and share linear memory. When the experimental font-atlas feature is
        // enabled, we allow direct access to the atlas pointer, assuming the
        // provider has been correctly configured via xtask.
        #[cfg(all(target_arch = "wasm32", feature = "wasm-font-atlas-experimental"))]
        unsafe {
            let io = self.io_ptr("Context::font_atlas_mut()");
            let atlas_ptr = (*io).Fonts;
            assert!(
                !atlas_ptr.is_null(),
                "ImGui IO Fonts pointer is null on wasm; provider not initialized?"
            );
            return FontAtlas::from_raw(atlas_ptr);
        }

        // Default wasm path: keep this API disabled to avoid accidental UB.
        #[cfg(all(target_arch = "wasm32", not(feature = "wasm-font-atlas-experimental")))]
        {
            panic!(
                "font_atlas_mut()/fonts() are not supported on wasm32 targets yet; \
                 enable `wasm-font-atlas-experimental` to opt-in for experiments."
            );
        }

        #[cfg(not(target_arch = "wasm32"))]
        unsafe {
            let io = self.io_ptr("Context::font_atlas_mut()");
            let atlas_ptr = (*io).Fonts;
            FontAtlas::from_raw(atlas_ptr)
        }
    }

    /// Returns the font atlas (alias for font_atlas_mut)
    ///
    /// This provides compatibility with imgui-rs naming convention
    pub fn fonts(&mut self) -> FontAtlas {
        self.font_atlas_mut()
    }

    /// Attempts to clone the interior shared font atlas **if it exists**.
    pub fn clone_shared_font_atlas(&mut self) -> Option<SharedFontAtlas> {
        self.shared_font_atlas.clone()
    }

    /// Loads settings from a string slice containing settings in .Ini file format
    #[doc(alias = "LoadIniSettingsFromMemory")]
    pub fn load_ini_settings(&mut self, data: &str) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                sys::igLoadIniSettingsFromMemory(data.as_ptr() as *const _, data.len());
            });
        }
    }

    /// Saves settings to a mutable string buffer in .Ini file format
    #[doc(alias = "SaveIniSettingsToMemory")]
    pub fn save_ini_settings(&mut self, buf: &mut String) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                let mut out_ini_size: usize = 0;
                let data_ptr = sys::igSaveIniSettingsToMemory(&mut out_ini_size as *mut usize);
                if data_ptr.is_null() || out_ini_size == 0 {
                    return;
                }

                let mut bytes = std::slice::from_raw_parts(data_ptr as *const u8, out_ini_size);
                if bytes.last() == Some(&0) {
                    bytes = &bytes[..bytes.len().saturating_sub(1)];
                }
                buf.push_str(&String::from_utf8_lossy(bytes));
            });
        }
    }

    /// Loads settings from a `.ini` file on disk.
    ///
    /// This is a convenience wrapper over `ImGui::LoadIniSettingsFromDisk`.
    ///
    /// Note: this is not available on `wasm32` targets.
    #[cfg(not(target_arch = "wasm32"))]
    #[doc(alias = "LoadIniSettingsFromDisk")]
    pub fn load_ini_settings_from_disk<P: Into<PathBuf>>(
        &mut self,
        filename: P,
    ) -> crate::error::ImGuiResult<()> {
        use crate::error::SafeStringConversion;
        let _guard = CTX_MUTEX.lock();
        let cstr = filename.into().to_string_lossy().to_cstring_safe()?;
        unsafe {
            with_bound_context(self.raw, || {
                sys::igLoadIniSettingsFromDisk(cstr.as_ptr());
            });
        }
        Ok(())
    }

    /// Saves settings to a `.ini` file on disk.
    ///
    /// This is a convenience wrapper over `ImGui::SaveIniSettingsToDisk`.
    ///
    /// Note: this is not available on `wasm32` targets.
    #[cfg(not(target_arch = "wasm32"))]
    #[doc(alias = "SaveIniSettingsToDisk")]
    pub fn save_ini_settings_to_disk<P: Into<PathBuf>>(
        &mut self,
        filename: P,
    ) -> crate::error::ImGuiResult<()> {
        use crate::error::SafeStringConversion;
        let _guard = CTX_MUTEX.lock();
        let cstr = filename.into().to_string_lossy().to_cstring_safe()?;
        unsafe {
            with_bound_context(self.raw, || {
                sys::igSaveIniSettingsToDisk(cstr.as_ptr());
            });
        }
        Ok(())
    }

    /// Returns the current clipboard text, if available.
    ///
    /// This calls Dear ImGui's clipboard callbacks (configured via
    /// [`Context::set_clipboard_backend`]). When no backend is installed, this returns `None`.
    ///
    /// Note: returned data is copied into a new `String`.
    #[doc(alias = "GetClipboardText")]
    pub fn clipboard_text(&self) -> Option<String> {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                let ptr = sys::igGetClipboardText();
                if ptr.is_null() {
                    return None;
                }
                Some(std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned())
            })
        }
    }

    /// Sets the clipboard text.
    ///
    /// This calls Dear ImGui's clipboard callbacks (configured via
    /// [`Context::set_clipboard_backend`]). If no backend is installed, this is a no-op.
    ///
    /// Interior NUL bytes are sanitized to `?` to match other scratch-string helpers.
    #[doc(alias = "SetClipboardText")]
    pub fn set_clipboard_text(&self, text: impl AsRef<str>) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                sys::igSetClipboardText(self.ui.scratch_txt(text.as_ref()));
            });
        }
    }

    /// Sets the clipboard backend used for clipboard operations
    pub fn set_clipboard_backend<T: ClipboardBackend>(&mut self, backend: T) {
        let _guard = CTX_MUTEX.lock();

        let clipboard_ctx: Box<UnsafeCell<_>> =
            Box::new(UnsafeCell::new(ClipboardContext::new(backend)));

        // On native/desktop targets, register clipboard callbacks in ImGui PlatformIO
        // so ImGui can call back into Rust for copy/paste.
        //
        // On wasm32 (import-style build), function pointers cannot safely cross the
        // module boundary between the Rust main module and the cimgui provider. We
        // therefore keep the backend alive on the Rust side but do not hook it into
        // ImGui's PlatformIO yet; clipboard integration for web will need a dedicated
        // design using JS bindings.
        #[cfg(not(target_arch = "wasm32"))]
        unsafe {
            let platform_io = sys::igGetPlatformIO_ContextPtr(self.raw);
            if platform_io.is_null() {
                panic!("Context::set_clipboard_backend() requires a valid ImGui context");
            }
            (*platform_io).Platform_SetClipboardTextFn = Some(crate::clipboard::set_clipboard_text);
            (*platform_io).Platform_GetClipboardTextFn = Some(crate::clipboard::get_clipboard_text);
            (*platform_io).Platform_ClipboardUserData = clipboard_ctx.get() as *mut _;
        }

        self.clipboard_ctx = clipboard_ctx;
    }
}

impl Drop for Context {
    fn drop(&mut self) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            if !self.raw.is_null() {
                unregister_user_textures_for_context(self.raw);
                crate::platform_io::clear_typed_callbacks_for_context(self.raw);
                with_bound_context(self.raw, || {
                    crate::platform_io::clear_out_param_callbacks_for_current_context();
                });
                if sys::igGetCurrentContext() == self.raw {
                    clear_current_context();
                }
                sys::igDestroyContext(self.raw);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Context, with_bound_context};

    #[test]
    fn platform_io_shared_and_mut_views_match() {
        let mut ctx = Context::create();
        let shared = ctx.platform_io().as_raw();
        let mutable = ctx.platform_io_mut().as_raw();
        assert_eq!(shared, mutable);
    }

    #[test]
    fn with_bound_context_restores_previous_context_after_panic() {
        let ctx_a = Context::create();
        let raw_a = ctx_a.raw;
        let suspended_a = ctx_a.suspend();
        let ctx_b = Context::create();
        let raw_b = ctx_b.raw;

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            with_bound_context(raw_a, || panic!("forced panic while context is rebound"));
        }));

        assert!(result.is_err());
        assert_eq!(unsafe { crate::sys::igGetCurrentContext() }, raw_b);

        drop(ctx_b);
        drop(suspended_a);
    }

    #[test]
    fn io_and_platform_io_accessors_use_self_context_not_current_context() {
        let mut ctx_a = Context::create();
        let marker_a = std::ptr::NonNull::<u8>::dangling().as_ptr().cast();
        ctx_a.io_mut().set_backend_language_user_data(marker_a);
        let pio_a = ctx_a.platform_io().as_raw();
        let suspended_a = ctx_a.suspend();

        let mut ctx_b = Context::create();
        let marker_b = std::ptr::NonNull::<u16>::dangling().as_ptr().cast();
        ctx_b.io_mut().set_backend_language_user_data(marker_b);
        let pio_b = ctx_b.platform_io().as_raw();

        assert_ne!(marker_a, marker_b);
        assert_ne!(pio_a, pio_b);

        let ctx_a = suspended_a.activate().expect_err("ctx_b is still active");
        assert_eq!(ctx_a.0.io().backend_language_user_data(), marker_a);
        assert_eq!(ctx_a.0.platform_io().as_raw(), pio_a);
        assert_eq!(unsafe { crate::sys::igGetCurrentContext() }, ctx_b.raw);

        drop(ctx_b);
        drop(ctx_a);
    }

    #[test]
    fn style_and_main_viewport_accessors_use_self_context_not_current_context() {
        let mut ctx_a = Context::create();
        ctx_a.style_mut().set_alpha(0.25);
        let viewport_a = ctx_a.main_viewport().as_raw();
        let suspended_a = ctx_a.suspend();

        let mut ctx_b = Context::create();
        ctx_b.style_mut().set_alpha(0.75);
        let viewport_b = ctx_b.main_viewport().as_raw();

        assert_ne!(viewport_a, viewport_b);

        let mut ctx_a = suspended_a.activate().expect_err("ctx_b is still active");
        assert_eq!(ctx_a.0.style().alpha(), 0.25);
        assert_eq!(ctx_a.0.main_viewport().as_raw(), viewport_a);
        assert_eq!(unsafe { crate::sys::igGetCurrentContext() }, ctx_b.raw);

        drop(ctx_b);
        drop(ctx_a);
    }

    #[test]
    fn io_font_global_scale_uses_owner_context_not_current_context() {
        let mut ctx_a = Context::create();
        ctx_a.style_mut().set_font_scale_main(1.25);
        let suspended_a = ctx_a.suspend();

        let mut ctx_b = Context::create();
        ctx_b.style_mut().set_font_scale_main(2.0);

        let mut ctx_a = suspended_a.activate().expect_err("ctx_b is still active");
        assert_eq!(ctx_a.0.io().font_global_scale(), 1.25);

        ctx_a.0.io_mut().set_font_global_scale(1.5);

        assert_eq!(ctx_a.0.style().font_scale_main(), 1.5);
        assert_eq!(ctx_b.style().font_scale_main(), 2.0);
        assert_eq!(unsafe { crate::sys::igGetCurrentContext() }, ctx_b.raw);

        drop(ctx_b);
        drop(ctx_a);
    }

    #[test]
    fn frame_lifecycle_requires_receiver_to_be_current_context() {
        let ctx_a = Context::create();
        let suspended_a = ctx_a.suspend();
        let ctx_b = Context::create();

        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _ = suspended_a.0.draw_data();
        }));

        assert!(result.is_err());
        assert_eq!(unsafe { crate::sys::igGetCurrentContext() }, ctx_b.raw);

        drop(ctx_b);
        drop(suspended_a);
    }

    #[cfg(feature = "multi-viewport")]
    #[test]
    fn platform_io_get_window_pos_and_size_setters_install_handlers() {
        unsafe extern "C" fn get_pos(
            _viewport: *mut crate::sys::ImGuiViewport,
            out_pos: *mut crate::sys::ImVec2,
        ) {
            if let Some(out_pos) = unsafe { out_pos.as_mut() } {
                *out_pos = crate::sys::ImVec2 { x: 10.0, y: 20.0 };
            }
        }
        unsafe extern "C" fn get_size(
            _viewport: *mut crate::sys::ImGuiViewport,
            out_size: *mut crate::sys::ImVec2,
        ) {
            if let Some(out_size) = unsafe { out_size.as_mut() } {
                *out_size = crate::sys::ImVec2 { x: 30.0, y: 40.0 };
            }
        }
        unsafe extern "C" fn get_scale(
            _viewport: *mut crate::sys::ImGuiViewport,
            out_scale: *mut crate::sys::ImVec2,
        ) {
            if let Some(out_scale) = unsafe { out_scale.as_mut() } {
                *out_scale = crate::sys::ImVec2 { x: 1.0, y: 2.0 };
            }
        }
        unsafe extern "C" fn get_insets(
            _viewport: *mut crate::sys::ImGuiViewport,
            out_insets: *mut crate::sys::ImVec4,
        ) {
            if let Some(out_insets) = unsafe { out_insets.as_mut() } {
                *out_insets = crate::sys::ImVec4::new(1.0, 2.0, 3.0, 4.0);
            }
        }

        let mut ctx = Context::create();

        {
            let pio = ctx.platform_io_mut();
            pio.set_platform_get_window_pos_raw(Some(get_pos));
            pio.set_platform_get_window_size_raw(Some(get_size));
            pio.set_platform_get_window_framebuffer_scale_raw(Some(get_scale));
            pio.set_platform_get_window_work_area_insets_raw(Some(get_insets));

            let raw = unsafe { &*pio.as_raw() };
            assert!(raw.Platform_GetWindowPos.is_some());
            assert!(raw.Platform_GetWindowSize.is_some());
            assert!(raw.Platform_GetWindowFramebufferScale.is_some());
            assert!(raw.Platform_GetWindowWorkAreaInsets.is_some());
        }
        assert!(
            ctx.io().backend_language_user_data().is_null(),
            "PlatformIO out-param helpers must not occupy BackendLanguageUserData"
        );

        let pio = ctx.platform_io_mut();
        pio.set_platform_get_window_pos_raw(None);
        pio.set_platform_get_window_size_raw(None);
        pio.set_platform_get_window_framebuffer_scale_raw(None);
        pio.set_platform_get_window_work_area_insets_raw(None);

        let raw = unsafe { &*pio.as_raw() };
        assert!(raw.Platform_GetWindowPos.is_none());
        assert!(raw.Platform_GetWindowSize.is_none());
        assert!(raw.Platform_GetWindowFramebufferScale.is_none());
        assert!(raw.Platform_GetWindowWorkAreaInsets.is_none());
    }

    #[test]
    fn registered_user_texture_token_survives_context_drop() {
        let mut ctx = Context::create();
        let mut texture = crate::texture::OwnedTextureData::new();

        let token = ctx.register_user_texture_token(&mut texture);
        drop(ctx);
        drop(token);
        drop(texture);
    }

    #[test]
    fn registered_user_texture_token_survives_texture_drop() {
        let mut ctx = Context::create();
        let token = {
            let mut texture = crate::texture::OwnedTextureData::new();
            ctx.register_user_texture_token(&mut texture)
        };

        drop(token);
        drop(ctx);
    }

    #[test]
    fn user_texture_registration_is_idempotent_and_unregister_is_noop_when_missing() {
        let mut ctx = Context::create();
        let mut texture = crate::texture::OwnedTextureData::new();

        ctx.register_user_texture(&mut texture);
        ctx.register_user_texture(&mut texture);
        ctx.unregister_user_texture(&mut texture);
        ctx.unregister_user_texture(&mut texture);
    }
}

/// A suspended Dear ImGui context
///
/// A suspended context retains its state, but is not usable without activating it first.
#[derive(Debug)]
pub struct SuspendedContext(Context);

/// A weak token that indicates whether a `Context` is still alive.
#[derive(Clone, Debug)]
pub struct ContextAliveToken(Weak<()>);

impl ContextAliveToken {
    /// Returns true if the originating `Context` has not been dropped.
    pub fn is_alive(&self) -> bool {
        self.0.upgrade().is_some()
    }
}

impl SuspendedContext {
    /// Tries to create a new suspended Dear ImGui context
    pub fn try_create() -> crate::error::ImGuiResult<Self> {
        Self::try_create_internal(None)
    }

    /// Tries to create a new suspended Dear ImGui context with a shared font atlas
    pub fn try_create_with_shared_font_atlas(
        shared_font_atlas: SharedFontAtlas,
    ) -> crate::error::ImGuiResult<Self> {
        Self::try_create_internal(Some(shared_font_atlas))
    }

    /// Creates a new suspended Dear ImGui context (panics on error)
    pub fn create() -> Self {
        Self::try_create().expect("Failed to create Dear ImGui context")
    }

    /// Creates a new suspended Dear ImGui context with a shared font atlas (panics on error)
    pub fn create_with_shared_font_atlas(shared_font_atlas: SharedFontAtlas) -> Self {
        Self::try_create_with_shared_font_atlas(shared_font_atlas)
            .expect("Failed to create Dear ImGui context")
    }

    // removed legacy create_or_panic variants (use create()/try_create())

    fn try_create_internal(
        mut shared_font_atlas: Option<SharedFontAtlas>,
    ) -> crate::error::ImGuiResult<Self> {
        let _guard = CTX_MUTEX.lock();

        let shared_font_atlas_ptr = match &mut shared_font_atlas {
            Some(atlas) => atlas.as_ptr_mut(),
            None => ptr::null_mut(),
        };

        let raw = unsafe { sys::igCreateContext(shared_font_atlas_ptr) };
        if raw.is_null() {
            return Err(crate::error::ImGuiError::ContextCreation {
                reason: "ImGui_CreateContext returned null".to_string(),
            });
        }

        let ctx = Context {
            raw,
            alive: Rc::new(()),
            shared_font_atlas,
            ini_filename: None,
            log_filename: None,
            platform_name: None,
            renderer_name: None,
            clipboard_ctx: Box::new(UnsafeCell::new(ClipboardContext::dummy())),
            ui: crate::ui::Ui::new(),
        };

        // If the context was activated during creation, deactivate it
        if ctx.is_current_context() {
            clear_current_context();
        }

        Ok(SuspendedContext(ctx))
    }

    /// Attempts to activate this suspended context
    ///
    /// If there is no active context, this suspended context is activated and `Ok` is returned.
    /// If there is already an active context, nothing happens and `Err` is returned.
    pub fn activate(self) -> Result<Context, SuspendedContext> {
        let _guard = CTX_MUTEX.lock();
        if no_current_context() {
            unsafe {
                sys::igSetCurrentContext(self.0.raw);
            }
            Ok(self.0)
        } else {
            Err(self)
        }
    }
}

/// RAII token returned by `Context::register_user_texture_token()`.
///
/// On drop, this unregisters the corresponding `ImTextureData*` from ImGui's internal user texture
/// list.
#[derive(Debug)]
pub struct RegisteredUserTexture {
    ctx: *mut sys::ImGuiContext,
    tex: *mut sys::ImTextureData,
    alive: Weak<()>,
}

impl Drop for RegisteredUserTexture {
    fn drop(&mut self) {
        if self.ctx.is_null() || self.tex.is_null() || self.alive.upgrade().is_none() {
            return;
        }

        let _guard = CTX_MUTEX.lock();
        if let Some(registration) = take_user_texture_registration(self.ctx, self.tex) {
            unregister_user_texture_registration(registration);
        }
    }
}

// Dear ImGui is not thread-safe. The Context must not be sent or shared across
// threads. If you need multi-threaded rendering, capture render data via
// OwnedDrawData and move that to another thread for rendering.