dear-imgui-rs 0.12.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
//! 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::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(());

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

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

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 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 the active context's IO object
    pub fn io_mut(&mut self) -> &mut Io {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            // Bindings provide igGetIO_Nil; use it to access current IO
            let io_ptr = sys::igGetIO_Nil();
            if io_ptr.is_null() {
                panic!("Context::io_mut() requires an active ImGui context");
            }
            &mut *(io_ptr as *mut Io)
        }
    }

    /// Get access to the IO structure
    pub fn io(&self) -> &crate::io::Io {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            // Bindings provide igGetIO_Nil; use it to access current IO
            let io_ptr = sys::igGetIO_Nil();
            if io_ptr.is_null() {
                panic!("Context::io() requires an active ImGui context");
            }
            &*(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 {
            let style_ptr = sys::igGetStyle();
            if style_ptr.is_null() {
                panic!("Context::style() requires an active 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 {
            let style_ptr = sys::igGetStyle();
            if style_ptr.is_null() {
                panic!("Context::style_mut() requires an active 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();

        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();
        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();
        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 a `TextureData` yourself (e.g. `OwnedTextureData::new()`), 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.
    ///
    /// # Safety & Lifetime
    /// The underlying `ImTextureData` must remain alive and registered until you call
    /// `unregister_user_texture()`. Unregister before dropping the texture to avoid leaving a
    /// dangling pointer inside ImGui.
    pub fn register_user_texture(&mut self, texture: &mut crate::texture::TextureData) {
        let _guard = CTX_MUTEX.lock();
        assert!(
            self.is_current_context(),
            "Context::register_user_texture() requires the context to be current"
        );
        unsafe {
            sys::igRegisterUserTexture(texture.as_raw_mut());
        }
    }

    /// Register a user-created texture and return an RAII token which unregisters on drop.
    ///
    /// This is a convenience wrapper around `register_user_texture()`.
    ///
    /// # Safety & Drop Ordering
    /// The returned token must be dropped before the underlying `ImGuiContext` is destroyed.
    /// If you store it in a struct alongside `Context`, ensure the token is dropped first.
    pub fn register_user_texture_token(
        &mut self,
        texture: &mut crate::texture::TextureData,
    ) -> RegisteredUserTexture {
        self.register_user_texture(texture);
        RegisteredUserTexture {
            ctx: self.raw,
            tex: texture.as_raw_mut(),
        }
    }

    /// 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::TextureData) {
        let _guard = CTX_MUTEX.lock();
        assert!(
            self.is_current_context(),
            "Context::unregister_user_texture() requires the context to be current"
        );
        unsafe {
            sys::igUnregisterUserTexture(texture.as_raw_mut());
        }
    }

    /// 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 = sys::igGetIO_Nil();
            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 = sys::igGetIO_Nil();
            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 = sys::igGetIO_Nil();
            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 = sys::igGetIO_Nil();
            if io.is_null() {
                panic!("igGetIO_Nil() returned null");
            }
            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 = sys::igGetPlatformIO_Nil();
            if pio.is_null() {
                panic!("Context::platform_io() requires an active ImGui context");
            }
            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 = sys::igGetPlatformIO_Nil();
            if pio.is_null() {
                panic!("igGetPlatformIO_Nil() returned null");
            }
            crate::platform_io::PlatformIo::from_raw_mut(pio)
        }
    }

    /// Returns a reference to the main Dear ImGui viewport.
    ///
    /// The returned reference is owned by the currently active 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 {
            let ptr = sys::igGetMainViewport();
            if ptr.is_null() {
                panic!("Context::main_viewport() requires an active 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 {
            // 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 {
            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 {
            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 {
            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 {
            sys::igPopFont();
        }
    }

    /// Get the current font
    #[doc(alias = "GetFont")]
    pub fn current_font(&self) -> &Font {
        let _guard = CTX_MUTEX.lock();
        unsafe { 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 { 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 = sys::igGetIO_Nil();
            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 = sys::igGetIO_Nil();
            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 = sys::igGetIO_Nil();
            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 = sys::igGetIO_Nil();
            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 {
            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 {
            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 { 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 { 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 {
            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 {
            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_Nil();
            if platform_io.is_null() {
                panic!("Context::set_clipboard_backend() requires an active 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() {
                if sys::igGetCurrentContext() == self.raw {
                    clear_current_context();
                }
                sys::igDestroyContext(self.raw);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::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);
    }

    #[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,
        ) -> crate::sys::ImVec2 {
            crate::sys::ImVec2 { x: 10.0, y: 20.0 }
        }
        unsafe extern "C" fn get_size(
            _viewport: *mut crate::sys::ImGuiViewport,
        ) -> crate::sys::ImVec2 {
            crate::sys::ImVec2 { x: 30.0, y: 40.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));

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

        pio.set_platform_get_window_pos_raw(None);
        pio.set_platform_get_window_size_raw(None);

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

/// 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.
///
/// # Safety
/// - The referenced `ImTextureData` must remain alive while the token exists.
/// - The token must be dropped before the `ImGuiContext` is destroyed.
#[derive(Debug)]
pub struct RegisteredUserTexture {
    ctx: *mut sys::ImGuiContext,
    tex: *mut sys::ImTextureData,
}

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

        let _guard = CTX_MUTEX.lock();
        unsafe {
            // Best-effort: temporarily bind the context so we can call Unregister in cases where
            // multiple contexts are used via activate/suspend.
            let prev = sys::igGetCurrentContext();
            if prev != self.ctx {
                sys::igSetCurrentContext(self.ctx);
            }
            sys::igUnregisterUserTexture(self.tex);
            if prev != self.ctx {
                sys::igSetCurrentContext(prev);
            }
        }
    }
}

// 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.