Skip to main content

dear_imnodes/
context.rs

1use crate::sys;
2use dear_imgui_rs::Ui;
3use dear_imgui_rs::sys as imgui_sys;
4use std::marker::PhantomData;
5use std::rc::Rc;
6
7mod editor;
8mod global;
9mod post;
10mod tokens;
11mod ui;
12
13pub use global::BoundEditor;
14pub use post::PostEditor;
15pub(crate) use tokens::AttrKind;
16pub use tokens::{AttributeToken, NodeToken};
17
18/// Global ImNodes context
19pub struct Context {
20    raw: *mut sys::ImNodesContext,
21    imgui_ctx_raw: *mut imgui_sys::ImGuiContext,
22    imgui_alive: dear_imgui_rs::ContextAliveToken,
23    // ImNodes context interacts with Dear ImGui state and is not thread-safe.
24    _not_send_sync: PhantomData<Rc<()>>,
25}
26
27/// An editor context allows multiple independent editors
28pub struct EditorContext {
29    raw: *mut sys::ImNodesEditorContext,
30    bound_ctx_raw: Option<*mut sys::ImNodesContext>,
31    bound_imgui_ctx_raw: Option<*mut imgui_sys::ImGuiContext>,
32    bound_imgui_alive: Option<dear_imgui_rs::ContextAliveToken>,
33    // Editor contexts are also tied to global ImNodes/ImGui state and must not cross threads.
34    _not_send_sync: PhantomData<Rc<()>>,
35}
36
37#[derive(Clone)]
38pub(crate) struct ImNodesScope {
39    imgui_ctx_raw: *mut imgui_sys::ImGuiContext,
40    imgui_alive: dear_imgui_rs::ContextAliveToken,
41    ctx_raw: *mut sys::ImNodesContext,
42    editor_raw: Option<*mut sys::ImNodesEditorContext>,
43}
44
45impl ImNodesScope {
46    #[inline]
47    pub(crate) fn bind(&self) {
48        assert!(
49            self.imgui_alive.is_alive(),
50            "dear-imnodes: ImGui context has been dropped"
51        );
52        unsafe {
53            sys::imnodes_SetImGuiContext(self.imgui_ctx_raw);
54            sys::imnodes_SetCurrentContext(self.ctx_raw);
55            if let Some(ed) = self.editor_raw {
56                sys::imnodes_EditorContextSet(ed);
57            }
58        }
59    }
60}
61
62/// Per-frame Ui extension entry point
63pub struct NodesUi<'ui> {
64    _ui: &'ui Ui,
65    _ctx: &'ui Context,
66}
67
68/// RAII token for a node editor frame
69pub struct NodeEditor<'ui> {
70    _ui: &'ui Ui,
71    _ctx: &'ui Context,
72    scope: ImNodesScope,
73    ended: bool,
74    minimap_callbacks: Vec<Box<MiniMapCallbackHolder<'ui>>>,
75}
76
77struct MiniMapCallbackHolder<'a> {
78    callback: Box<dyn FnMut(i32) + 'a>,
79}