dear_imgui_rs/context/
suspended.rs1use std::ptr;
2use std::rc::Rc;
3
4use crate::clipboard::ClipboardContext;
5use crate::fonts::SharedFontAtlas;
6use crate::sys;
7
8use super::Context;
9use super::binding::{CTX_MUTEX, clear_current_context, no_current_context};
10
11impl Context {
12 pub fn suspend(self) -> SuspendedContext {
14 let _guard = CTX_MUTEX.lock();
15 assert!(
16 self.is_current_context(),
17 "context to be suspended is not the active context"
18 );
19 clear_current_context();
20 SuspendedContext(self)
21 }
22}
23
24#[derive(Debug)]
28pub struct SuspendedContext(pub(super) Context);
29
30impl SuspendedContext {
31 pub fn try_create() -> crate::error::ImGuiResult<Self> {
33 Self::try_create_internal(None)
34 }
35
36 pub fn try_create_with_shared_font_atlas(
38 shared_font_atlas: SharedFontAtlas,
39 ) -> crate::error::ImGuiResult<Self> {
40 Self::try_create_internal(Some(shared_font_atlas))
41 }
42
43 pub fn create() -> Self {
45 Self::try_create().expect("Failed to create Dear ImGui context")
46 }
47
48 pub fn create_with_shared_font_atlas(shared_font_atlas: SharedFontAtlas) -> Self {
50 Self::try_create_with_shared_font_atlas(shared_font_atlas)
51 .expect("Failed to create Dear ImGui context")
52 }
53
54 fn try_create_internal(
57 mut shared_font_atlas: Option<SharedFontAtlas>,
58 ) -> crate::error::ImGuiResult<Self> {
59 let _guard = CTX_MUTEX.lock();
60
61 let shared_font_atlas_ptr = match &mut shared_font_atlas {
62 Some(atlas) => atlas.as_ptr_mut(),
63 None => ptr::null_mut(),
64 };
65
66 let raw = unsafe { sys::igCreateContext(shared_font_atlas_ptr) };
67 if raw.is_null() {
68 return Err(crate::error::ImGuiError::ContextCreation {
69 reason: "ImGui_CreateContext returned null".to_string(),
70 });
71 }
72
73 let ctx = Context {
74 raw,
75 alive: Rc::new(()),
76 shared_font_atlas,
77 ini_filename: None,
78 log_filename: None,
79 platform_name: None,
80 renderer_name: None,
81 clipboard_ctx: Box::new(ClipboardContext::dummy()),
82 ui: crate::ui::Ui::new(),
83 };
84
85 if ctx.is_current_context() {
87 clear_current_context();
88 }
89
90 Ok(SuspendedContext(ctx))
91 }
92
93 pub fn activate(self) -> Result<Context, SuspendedContext> {
98 let _guard = CTX_MUTEX.lock();
99 if no_current_context() {
100 unsafe {
101 sys::igSetCurrentContext(self.0.raw);
102 }
103 Ok(self.0)
104 } else {
105 Err(self)
106 }
107 }
108}