Skip to main content

dear_imgui_rs/ui/
core.rs

1use super::*;
2
3impl Ui {
4    pub(crate) fn assert_finite_f32(caller: &str, name: &str, value: f32) {
5        assert!(value.is_finite(), "{caller} {name} must be finite");
6    }
7
8    pub(super) fn assert_finite_vec2(caller: &str, name: &str, value: [f32; 2]) {
9        assert!(
10            value[0].is_finite() && value[1].is_finite(),
11            "{caller} {name} must contain finite values"
12        );
13    }
14
15    /// Creates a new Ui instance
16    ///
17    /// This should only be called by Context::create()
18    pub(crate) fn new(
19        ctx: *mut sys::ImGuiContext,
20        ctx_binding: crate::ContextBinding,
21        texture_registry: crate::context::SharedTextureRegistry,
22        ime: std::rc::Rc<std::cell::RefCell<crate::context::ime::ImeState>>,
23    ) -> Self {
24        Ui {
25            ctx,
26            ctx_binding,
27            texture_registry,
28            ime,
29            native_scopes: std::cell::RefCell::new(crate::scope::NativeScopeTracker::default()),
30            scratch_buffers: std::rc::Rc::default(),
31        }
32    }
33
34    pub(crate) fn context_raw(&self) -> *mut sys::ImGuiContext {
35        self.ctx
36    }
37
38    /// Returns a persistent capability for the Context that owns this `Ui`.
39    pub fn binding(&self) -> crate::ContextBinding {
40        self.ctx_binding.clone()
41    }
42
43    /// Returns the process-unique identity of the Context that owns this `Ui`.
44    pub fn context_id(&self) -> crate::ContextId {
45        self.ctx_binding.id()
46    }
47
48    pub(crate) fn run_with_bound_context<R>(&self, f: impl FnOnce() -> R) -> R {
49        self.assert_native_scopes_usable();
50        self.ctx_binding.with_bound_context(f)
51    }
52
53    pub(crate) fn resolve_texture_ref(
54        &self,
55        texture: crate::texture::TextureRef<'_>,
56    ) -> Result<sys::ImTextureRef, crate::texture::ManagedTextureError> {
57        match texture.source() {
58            crate::texture::TextureSource::Legacy(id) => Ok(sys::ImTextureRef {
59                _TexData: std::ptr::null_mut(),
60                _TexID: sys::ImTextureID::from(id),
61            }),
62            crate::texture::TextureSource::Managed(id) => {
63                self.texture_registry.borrow().resolve(id)
64            }
65            crate::texture::TextureSource::FontAtlas { atlas, texture } => {
66                let io = unsafe { sys::igGetIO_ContextPtr(self.ctx) };
67                if io.is_null() || !std::ptr::eq(unsafe { (*io).Fonts }, atlas) {
68                    return Err(crate::texture::ManagedTextureError::ForeignFontAtlas);
69                }
70                Ok(texture)
71            }
72        }
73    }
74
75    /// Resolve a logical texture for submission to this frame's native draw lists.
76    ///
77    /// # Safety
78    ///
79    /// Use the reference on the owning context's thread. An extension may queue it until the
80    /// end of its drawing scope to emit commands into this same ImGui frame. The context keeps
81    /// managed and atlas textures alive for the resulting draw data. Limit the extension's own
82    /// copy to this submission and consume the resulting frame through its renderer API.
83    /// For a legacy texture ID, the caller supplies the renderer binding and its lifetime.
84    #[doc(hidden)]
85    pub unsafe fn resolve_texture_ref_raw(
86        &self,
87        texture: crate::texture::TextureRef<'_>,
88    ) -> Result<sys::ImTextureRef, crate::texture::ManagedTextureError> {
89        self.run_with_bound_context(|| self.resolve_texture_ref(texture))
90    }
91
92    /// Runs a closure while this `Ui`'s owning ImGui context is current.
93    ///
94    /// The previously current context is restored before this method returns,
95    /// including when the closure panics. This is primarily intended for
96    /// extension crates that need to call raw Dear ImGui-adjacent FFI while
97    /// still honoring the `Ui` that created the safe wrapper.
98    pub fn with_bound_context<R>(&self, f: impl FnOnce() -> R) -> R {
99        self.run_with_bound_context(f)
100    }
101
102    /// Returns an immutable reference to the inputs/outputs object
103    #[doc(alias = "GetIO")]
104    pub fn io(&self) -> &crate::io::Io {
105        self.run_with_bound_context(|| unsafe {
106            let io = sys::igGetIO_Nil();
107            if io.is_null() {
108                panic!("Ui::io() requires an active ImGui context");
109            }
110            &*(io as *const crate::io::Io)
111        })
112    }
113
114    /// Internal method to push a single text to our scratch buffer.
115    pub(crate) fn scratch_txt(&self, txt: impl AsRef<str>) -> *const std::os::raw::c_char {
116        self.with_scratch_buffer(|buf| buf.scratch_txt(txt))
117    }
118
119    /// Stages an explicit text range with a readable NUL sentinel at its end.
120    pub(crate) fn scratch_txt_range(
121        &self,
122        txt: impl AsRef<str>,
123    ) -> std::ops::Range<*const std::os::raw::c_char> {
124        self.with_scratch_buffer(|buf| buf.scratch_txt_range(txt))
125    }
126
127    /// Helper method for two strings
128    pub(crate) fn scratch_txt_two(
129        &self,
130        txt_0: impl AsRef<str>,
131        txt_1: impl AsRef<str>,
132    ) -> (*const std::os::raw::c_char, *const std::os::raw::c_char) {
133        self.with_scratch_buffer(|buf| buf.scratch_txt_two(txt_0, txt_1))
134    }
135
136    /// Helper method with one optional value
137    pub(crate) fn scratch_txt_with_opt(
138        &self,
139        txt_0: impl AsRef<str>,
140        txt_1: Option<impl AsRef<str>>,
141    ) -> (*const std::os::raw::c_char, *const std::os::raw::c_char) {
142        self.with_scratch_buffer(|buf| buf.scratch_txt_with_opt(txt_0, txt_1))
143    }
144
145    /// Keeps the latest scratch allocation alive throughout `f`. Reentrant calls use another
146    /// buffer. On return or unwind this buffer becomes the next one available for reuse.
147    pub(crate) fn with_scratch_buffer<R>(&self, f: impl FnOnce(&mut UiBuffer) -> R) -> R {
148        self.scratch_buffers.with(f)
149    }
150
151    /// Returns an ID from a string label in the current ID scope.
152    ///
153    /// This mirrors `ImGui::GetID(label)`. Useful for building stable IDs
154    /// for widgets or dockspaces inside the current window/scope.
155    #[doc(alias = "GetID")]
156    pub fn get_id(&self, label: &str) -> Id {
157        let label = self.scratch_txt_range(label);
158        self.run_with_bound_context(|| unsafe {
159            Id::from(sys::igGetID_StrStr(label.start, label.end))
160        })
161    }
162}