Skip to main content

dear_imgui_rs/stacks/
font.rs

1use crate::fonts::FontId;
2use crate::{Ui, sys};
3
4/// # Parameter stacks (shared)
5impl Ui {
6    /// Switches to the given font by pushing it to the font stack.
7    ///
8    /// Returns a `FontStackToken` that must be popped by calling `.pop()`
9    ///
10    /// # Panics
11    ///
12    /// Panics before calling Dear ImGui if the `FontId` came from a different atlas,
13    /// was invalidated by font atlas mutation, or is no longer present in the
14    /// current context's atlas.
15    ///
16    /// # Examples
17    ///
18    /// ```no_run
19    /// # use dear_imgui_rs::*;
20    /// # let mut ctx = Context::create();
21    /// # let font_data_sources = [];
22    /// // At initialization time
23    /// let my_custom_font = ctx.fonts().add_font(&font_data_sources);
24    /// # let ui = ctx.frame();
25    /// // During UI construction
26    /// let font = ui.push_font(my_custom_font);
27    /// ui.text("I use the custom font!");
28    /// font.pop();
29    /// ```
30    #[doc(alias = "PushFont")]
31    pub fn push_font(&self, id: FontId) -> FontStackToken<'_> {
32        self.run_with_bound_context(|| unsafe {
33            let font_ptr =
34                crate::fonts::validate_font_id_for_current_context(id, "Ui::push_font()");
35            sys::igPushFont(font_ptr, 0.0);
36        });
37        FontStackToken::new(self)
38    }
39}
40
41create_token!(
42    /// Tracks a font pushed to the font stack that can be popped by calling `.end()`
43    /// or by dropping.
44    pub struct FontStackToken<'ui>;
45
46    /// Pops a change from the font stack.
47    drop { unsafe { sys::igPopFont() } }
48);
49
50impl FontStackToken<'_> {
51    /// Pops a change from the font stack.
52    pub fn pop(self) {
53        self.end()
54    }
55}