Skip to main content

dear_imgui_rs/scope/
window.rs

1use super::{ScopeSnapshot, TableScope};
2use crate::{Ui, sys};
3
4#[derive(Debug)]
5pub(super) struct WindowBoundary {
6    pub(super) first_id: u64,
7    host_depth: usize,
8    table: Option<TableScope>,
9    draw_list: *mut sys::ImDrawList,
10}
11
12/// The window `Begin` instance and table cell hosting a native extension.
13///
14/// Obtained from [`Ui::with_native_window_scope`]. A native extension can borrow this handle
15/// to check its host before making a call and to balance core tokens around application code.
16#[derive(Debug)]
17pub struct NativeWindowScope<'ui> {
18    ui: &'ui Ui,
19    host: ScopeSnapshot,
20    depth: usize,
21}
22
23impl NativeWindowScope<'_> {
24    /// Returns whether this extension is current in its original frame, window `Begin`, and
25    /// table cell. A nested extension has its own identity even if it uses the same window.
26    pub fn is_current(&self) -> bool {
27        self.ui
28            .ctx_binding
29            .with_bound_context(|| self.is_current_bound())
30    }
31
32    fn is_current_bound(&self) -> bool {
33        let tracker = self.ui.native_scopes.borrow();
34        // The public handle is only ever borrowed from its closure, so its stack position
35        // cannot be reused while an extension can still call this method.
36        tracker
37            .window_boundaries
38            .last()
39            .is_some_and(|boundary| boundary.host_depth == self.depth)
40            && self.ui.current_native_scope() == self.host
41    }
42
43    /// Runs application code and closes any core native scopes it leaves open, even on unwind.
44    /// The surrounding host and its enclosing tokens stay active throughout the call.
45    ///
46    /// For a nested native `Begin`/`End` pair, construct its guard inside an outer `run`
47    /// and call `run` again around application code. The inner call closes application tokens
48    /// before the guard ends. The outer call defers earlier tokens until after the guard ends.
49    /// Both calls retain the same extension identity.
50    ///
51    /// # Panics
52    ///
53    /// Panics if called from a different window or table cell, or during scope order recovery.
54    pub fn run<R>(&self, f: impl FnOnce() -> R) -> R {
55        self.ui.run_with_bound_context(|| {
56            assert!(
57                self.is_current_bound(),
58                "native extension requires its own window scope and table cell"
59            );
60            let _boundary = WindowBoundaryGuard::enter(self);
61            f()
62        })
63    }
64}
65
66impl Ui {
67    /// Keeps the current window and table cell active while a native extension uses them.
68    ///
69    /// Dropping a core token opened before this boundary defers its native `End` or `Pop`.
70    /// Tokens dropped across a nested window or table wait for that container to end as well.
71    /// On return or unwind, the boundary closes the core scopes opened inside it in native
72    /// stack order. Tokens retained by the caller can then be dropped harmlessly.
73    ///
74    /// Construct the extension's RAII guard inside this closure and invoke application code
75    /// through [`NativeWindowScope::run`]. This restores the core scopes before the guard's
76    /// destructor ends the extension, while the outer boundary still holds the host open.
77    ///
78    /// Inside a table, select a cell before entering. Its row, column, and draw channel are
79    /// fixed for the duration of the extension. Nested tables can use their own cells normally.
80    /// The extension has exclusive use of its host draw list's channel splitter.
81    ///
82    /// # Panics
83    ///
84    /// Panics without a current window, between table cells, or during scope order recovery.
85    pub fn with_native_window_scope<R>(&self, f: impl FnOnce(&NativeWindowScope<'_>) -> R) -> R {
86        self.run_with_bound_context(|| {
87            let host = self.current_native_scope();
88            assert!(
89                host.window.is_some(),
90                "native extension requires a current window"
91            );
92            if host.table.is_some() {
93                // Before the first cell, even querying sort specs can initialize the table's
94                // draw splitter and push its clip rect. A list clipper can also end a row
95                // while its previous CurrentColumn value is still set.
96                assert!(
97                    host.column >= 0 && unsafe { (*sys::igGetCurrentTable()).IsInsideRow },
98                    "native extension inside a table requires a current table cell"
99                );
100            }
101            let depth = self.native_scopes.borrow().window_boundaries.len();
102            let scope = NativeWindowScope {
103                ui: self,
104                host,
105                depth,
106            };
107            let _boundary = WindowBoundaryGuard::enter(&scope);
108            f(&scope)
109        })
110    }
111
112    pub(crate) fn native_window_scope_holds_table(&self, table: Option<TableScope>) -> bool {
113        let tracker = self.native_scopes.borrow();
114        table.is_some()
115            && tracker
116                .window_boundaries
117                .iter()
118                .any(|scope| scope.table == table)
119    }
120
121    pub(crate) fn native_window_scope_depth(&self) -> usize {
122        self.native_scopes.borrow().window_boundaries.len()
123    }
124
125    pub(crate) fn assert_host_table_can_change(&self, table: Option<TableScope>, operation: &str) {
126        assert!(
127            !self.native_window_scope_holds_table(table),
128            "{operation} cannot change the table cell hosting a native extension"
129        );
130    }
131
132    pub(crate) fn assert_draw_list_splitter_available(&self, draw_list: *mut sys::ImDrawList) {
133        let tracker = self.native_scopes.borrow();
134        assert!(
135            !tracker
136                .window_boundaries
137                .iter()
138                .any(|scope| scope.draw_list == draw_list),
139            "a native extension is using this window's draw list splitter"
140        );
141    }
142}
143
144struct WindowBoundaryGuard<'ui>(&'ui Ui);
145
146impl<'ui> WindowBoundaryGuard<'ui> {
147    // The caller has bound the Ui and checked that the host is current.
148    fn enter(scope: &NativeWindowScope<'ui>) -> Self {
149        let mut tracker = scope.ui.native_scopes.borrow_mut();
150        let first_id = tracker.next_id;
151        tracker.window_boundaries.push(WindowBoundary {
152            first_id,
153            host_depth: scope.depth,
154            table: scope.host.table,
155            draw_list: unsafe { (*sys::igGetCurrentWindowRead()).DrawList },
156        });
157        Self(scope.ui)
158    }
159}
160
161impl Drop for WindowBoundaryGuard<'_> {
162    fn drop(&mut self) {
163        let ui = self.0;
164        // Both constructors keep the Ui's context bound until this guard has dropped.
165        {
166            let mut tracker = ui.native_scopes.borrow_mut();
167            let first = tracker
168                .window_boundaries
169                .last()
170                .expect("active native window scope")
171                .first_id;
172            for entry in tracker
173                .entries
174                .values_mut()
175                .filter(|entry| entry.id >= first)
176            {
177                entry.abandoned = true;
178            }
179            tracker.refresh_pending_recovery();
180        }
181        ui.finish_abandoned_native_scopes();
182        {
183            let mut tracker = ui.native_scopes.borrow_mut();
184            tracker
185                .window_boundaries
186                .pop()
187                .expect("active native window scope");
188            tracker.refresh_pending_recovery();
189        }
190        // The native extension has finished its work at this depth. Restore the clipper
191        // temporary stack before releasing any enclosing window or table that was deferred.
192        unsafe { crate::list_clipper::drain_finished_clippers(ui) };
193        ui.finish_abandoned_native_scopes();
194    }
195}