Skip to main content

dear_imgui_rs/context/
fonts.rs

1use crate::fonts::{FontAtlas, SharedFontAtlas};
2
3use super::Context;
4use super::binding::CTX_MUTEX;
5
6impl Context {
7    /// Borrow the font atlas from the IO structure.
8    ///
9    /// Font-atlas mutation is exposed through this shared view because Dear ImGui permits one
10    /// native atlas to be registered with multiple contexts. Mutating methods validate the native
11    /// atlas lock before entering FFI.
12    pub fn font_atlas(&self) -> &FontAtlas {
13        let _guard = CTX_MUTEX.lock();
14
15        // wasm32 import-style builds keep Dear ImGui state in a separate module
16        // and share linear memory. When the experimental font-atlas feature is
17        // enabled, we allow direct access to the atlas pointer, assuming the
18        // provider has been correctly configured via xtask.
19        #[cfg(all(target_arch = "wasm32", feature = "wasm-font-atlas-experimental"))]
20        unsafe {
21            let io = self.io_ptr("Context::font_atlas()");
22            let atlas_ptr = (*io).Fonts;
23            assert!(
24                !atlas_ptr.is_null(),
25                "ImGui IO Fonts pointer is null on wasm; provider not initialized?"
26            );
27            FontAtlas::from_raw(atlas_ptr)
28        }
29
30        // Default wasm path: keep this API disabled to avoid accidental UB.
31        #[cfg(all(target_arch = "wasm32", not(feature = "wasm-font-atlas-experimental")))]
32        {
33            panic!(
34                "font_atlas() is not supported on wasm32 targets without \
35                 `wasm-font-atlas-experimental` feature; \
36                 see docs/WASM.md for current limitations."
37            );
38        }
39
40        #[cfg(not(target_arch = "wasm32"))]
41        unsafe {
42            let io = self.io_ptr("Context::font_atlas()");
43            let atlas_ptr = (*io).Fonts;
44            FontAtlas::from_raw(atlas_ptr)
45        }
46    }
47
48    /// Attempts to clone the interior shared font atlas **if it exists**.
49    pub fn clone_shared_font_atlas(&self) -> Option<SharedFontAtlas> {
50        self.shared_font_atlas.clone()
51    }
52}