Skip to main content

euv_core/scene/tree/
fn.rs

1use super::*;
2
3/// Runs `operation` with `ctx` bound as the active ambient `Context`, restoring any previous context on exit.
4///
5/// # Arguments
6///
7/// - `Context` - Framework context to bind during `operation`.
8/// - `F` - Closure executing declarative UI construction (`view!` or components).
9///
10/// # Returns
11///
12/// - `R` - Value returned by `operation`.
13pub fn with_context<F, R>(ctx: Context, operation: F) -> R
14where
15    F: FnOnce() -> R,
16{
17    let previous: Option<Context> =
18        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow_mut().replace(ctx));
19    let _guard: ContextGuard = ContextGuard::new(previous);
20    operation()
21}
22
23/// Borrows the active ambient `Context` without cloning its 216-byte struct or bumping its `Rc` handles.
24///
25/// # Arguments
26///
27/// - `F` - Closure receiving a borrowed `&Context` reference.
28///
29/// # Returns
30///
31/// - `R` - Value returned by `operation`.
32pub fn with_current_context<F, R>(operation: F) -> R
33where
34    F: FnOnce(&Context) -> R,
35{
36    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
37        let borrowed: Ref<'_, Option<Context>> = slot.borrow();
38        if let Some(ctx) = borrowed.as_ref() {
39            operation(ctx)
40        } else {
41            drop(borrowed);
42            let fallback: Context = Context::new(SceneHandle::new_tree(), PlatformKind::Headless);
43            operation(&fallback)
44        }
45    })
46}
47
48/// Returns a cloned handle to the active ambient `Context`.
49///
50/// # Returns
51///
52/// - `Context` - Currently bound ambient framework context.
53#[must_use]
54pub fn current_context() -> Context {
55    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
56        slot.borrow()
57            .clone()
58            .unwrap_or_else(|| Context::new(SceneHandle::new_tree(), PlatformKind::Headless))
59    })
60}
61
62/// Returns `true` when an ambient `Context` is currently bound on this thread.
63///
64/// # Returns
65///
66/// - `bool` - Whether `with_context` or `App::mount` is active.
67#[must_use]
68pub fn has_context() -> bool {
69    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow().is_some())
70}
71
72/// Returns the active `PlatformKind` from the ambient `Context`.
73///
74/// # Returns
75///
76/// - `PlatformKind` - Execution platform kind.
77#[must_use]
78pub fn current_platform() -> PlatformKind {
79    with_current_context(|ctx: &Context| ctx.get_platform())
80}
81
82/// Mounts a reactive `Text` node in the ambient `Context` without cloning the full `Context` struct.
83///
84/// # Arguments
85///
86/// - `Style` - Initial text style.
87/// - `F` - Reactive text producer closure.
88///
89/// # Returns
90///
91/// - `NodeId` - Created reactive text node handle.
92pub fn mount_reactive_text<F>(style: Style, producer: F) -> NodeId
93where
94    F: FnMut() -> String + 'static,
95{
96    let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
97    let node_id: NodeId = handle.with_write(
98        |tree: &mut SceneTree| tree.create_text(String::new(), style),
99        NodeId::default(),
100    );
101    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_text(node_id, producer));
102    handle.mutate(move |tree: &mut SceneTree| {
103        tree.attach_scope(node_id, scope);
104    });
105    node_id
106}
107
108/// Binds a reactive `Style` closure onto `node_id` in the ambient `Context` without cloning `Context`.
109///
110/// # Arguments
111///
112/// - `NodeId` - Target scene node handle.
113/// - `F` - Reactive `Style` producer closure.
114pub fn bind_style_current<F>(node_id: NodeId, producer: F)
115where
116    F: FnMut() -> Style + 'static,
117{
118    let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
119    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_style(node_id, producer));
120    handle.mutate(move |tree: &mut SceneTree| {
121        tree.attach_scope(node_id, scope);
122    });
123}
124
125/// Mounts a reactive child builder onto `host` using the ambient `Context`.
126///
127/// # Arguments
128///
129/// - `NodeId` - Host container node handle.
130/// - `F` - Reactive child builder returning ordered `NodeId` values.
131pub fn bind_children_current<F>(host: NodeId, builder: F)
132where
133    F: FnMut() -> Vec<NodeId> + 'static,
134{
135    let mut ctx: Context = current_context();
136    ctx.bind_children(host, builder);
137}
138
139/// Converts any string-like value into an owned `String` for declarative `view!` macro expansion.
140///
141/// # Arguments
142///
143/// - `T` - String-like text value implementing `Into<String>`.
144///
145/// # Returns
146///
147/// - `String` - Owned UTF-8 text string.
148#[must_use]
149pub fn into_text<T>(value: T) -> String
150where
151    T: Into<String>,
152{
153    value.into()
154}
155
156/// Registers a zero-allocation platform frame-wakeup callback invoked whenever reactive or scene state dirties an idle frame loop.
157///
158/// # Arguments
159///
160/// - `fn()` - Wakeup callback requesting the next host VSync or `requestAnimationFrame` presentation.
161pub fn register_frame_wakeup(hook: fn()) {
162    FRAME_WAKEUP_HOOK.store(hook as *mut (), Ordering::Release);
163    if FRAME_NEEDED.load(Ordering::Acquire) {
164        hook();
165    }
166}
167
168/// Unregisters any active platform frame-wakeup callback.
169pub fn clear_frame_wakeup() {
170    FRAME_WAKEUP_HOOK.store(null_mut(), Ordering::Release);
171}
172
173/// Marks that pending reactive or scene updates require presentation and invokes the registered wakeup hook on idle-to-dirty edges.
174#[inline(always)]
175pub fn notify_frame_needed() {
176    if !FRAME_NEEDED.load(Ordering::Relaxed) && !FRAME_NEEDED.swap(true, Ordering::AcqRel) {
177        let raw: *mut () = FRAME_WAKEUP_HOOK.load(Ordering::Acquire);
178        if !raw.is_null() {
179            // SAFETY: `raw` is stored exclusively via `register_frame_wakeup` from a valid `fn()` pointer.
180            let hook: fn() = unsafe { transmute::<*mut (), fn()>(raw) };
181            hook();
182        }
183    }
184}
185
186/// Atomically consumes and clears the pending frame-wakeup flag before rendering a frame.
187///
188/// # Returns
189///
190/// - `bool` - `true` when at least one reactive or scene invalidation occurred since the previous take.
191#[must_use]
192#[inline(always)]
193pub fn take_frame_needed() -> bool {
194    FRAME_NEEDED.swap(false, Ordering::AcqRel)
195}
196
197/// Returns whether a reactive or scene invalidation has marked a new frame as needed without consuming the flag.
198///
199/// # Returns
200///
201/// - `bool` - `true` when a new frame presentation has been requested.
202#[must_use]
203#[inline(always)]
204pub fn is_frame_needed() -> bool {
205    FRAME_NEEDED.load(Ordering::Acquire)
206}
207
208/// Returns `true` when any `SceneTree` borrow is currently active on the current thread.
209///
210/// # Returns
211///
212/// - `bool` - Whether a `SceneTree` read or write guard is active on this thread.
213#[must_use]
214#[inline(always)]
215pub(crate) fn is_scene_borrowed() -> bool {
216    SCENE_BORROW_DEPTH
217        .try_with(|depth: &Cell<u32>| depth.get() > 0)
218        .unwrap_or(false)
219}
220
221/// Records that `flush_effects` deferred effect execution until the active `SceneTree` borrow exits.
222#[inline(always)]
223pub(crate) fn defer_effect_flush_while_borrowed() {
224    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
225        flag.set(true);
226    });
227    notify_frame_needed();
228}
229
230/// Returns `true` when a deferred reactive effect flush is queued for the current thread without clearing it.
231///
232/// # Returns
233///
234/// - `bool` - Whether deferred reactive effects are waiting for the outer scene borrow to drop.
235#[must_use]
236#[inline(always)]
237pub(crate) fn has_deferred_effect_flush() -> bool {
238    DEFERRED_EFFECT_FLUSH.try_with(Cell::get).unwrap_or(false)
239}
240
241/// Consumes and clears the thread-local deferred reactive effect flush flag.
242///
243/// # Returns
244///
245/// - `bool` - `true` when effects were deferred while a `SceneTree` borrow was active.
246#[must_use]
247#[inline(always)]
248pub(crate) fn take_deferred_effect_flush() -> bool {
249    DEFERRED_EFFECT_FLUSH
250        .try_with(|flag: &Cell<bool>| flag.replace(false))
251        .unwrap_or(false)
252}
253
254/// Resets thread-local scene borrow-depth tracking and deferred flush state during runtime resets.
255pub(crate) fn reset_scene_borrow_state() {
256    let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
257        depth.set(0);
258    });
259    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
260        flag.set(false);
261    });
262    FRAME_NEEDED.store(false, Ordering::Release);
263}
264
265/// Inserts a decoded RGBA8 `ImageBuffer` into the thread-local network image cache under `url`.
266///
267/// # Arguments
268///
269/// - `&str` - Canonical resolved image URL or asset path.
270/// - `ImageBuffer` - Decoded RGBA8 image buffer.
271pub fn cache_network_image(url: &str, buffer: ImageBuffer) {
272    let _: Result<(), _> =
273        NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
274            let _: Option<ImageBuffer> = slot.borrow_mut().insert(url.to_string(), buffer);
275        });
276}
277
278/// Looks up a previously decoded `ImageBuffer` for `url` in O(1) without triggering network I/O.
279///
280/// # Arguments
281///
282/// - `&str` - Canonical resolved image URL or asset path.
283///
284/// # Returns
285///
286/// - `Option<ImageBuffer>` - Cached RGBA8 image buffer when available.
287#[must_use]
288pub fn cached_network_image(url: &str) -> Option<ImageBuffer> {
289    NETWORK_IMAGE_CACHE
290        .try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| slot.borrow().get(url).cloned())
291        .ok()
292        .flatten()
293}
294
295/// Clears all entries from the thread-local decoded network image cache and pending waiter registry.
296pub fn clear_network_image_cache() {
297    let _: Result<(), _> =
298        NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
299            slot.borrow_mut().clear();
300        });
301    let _: Result<(), _> = NETWORK_IMAGE_WAITERS.try_with(
302        |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
303            slot.borrow_mut().clear();
304        },
305    );
306}
307
308/// Finalizes an in-flight network image fetch for `url`, caching successful buffers and notifying all waiting callbacks.
309///
310/// # Arguments
311///
312/// - `&str` - Resolved image URL key.
313/// - `Option<ImageBuffer>` - Decoded RGBA8 buffer on success, or `None` on load failure.
314pub fn complete_network_image_load(url: &str, result: Option<ImageBuffer>) {
315    if let Some(buf) = result.as_ref() {
316        cache_network_image(url, buf.clone());
317    }
318    let waiters: Vec<NetworkImageCallback> = NETWORK_IMAGE_WAITERS
319        .try_with(
320            |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
321                slot.borrow_mut().remove(url).unwrap_or_default()
322            },
323        )
324        .unwrap_or_default();
325    for cb in waiters.into_iter() {
326        cb(result.clone());
327    }
328    notify_frame_needed();
329}
330
331/// Requests a decoded RGBA8 `ImageBuffer` for `url`, invoking `on_ready` immediately on cache hit or asynchronously once decoded on WebAssembly.
332///
333/// # Arguments
334///
335/// - `&str` - Resolved asset URL or path to load.
336/// - `NetworkImageCallback` - Callback receiving `Some(ImageBuffer)` on success or `None` on failure.
337pub fn request_network_image(url: &str, on_ready: NetworkImageCallback) {
338    let trimmed: &str = url.trim();
339    if trimmed.is_empty() {
340        on_ready(None);
341        return;
342    }
343    if let Some(hit) = cached_network_image(trimmed) {
344        on_ready(Some(hit));
345        return;
346    }
347    #[cfg(target_arch = "wasm32")]
348    {
349        let should_fetch: bool = NETWORK_IMAGE_WAITERS
350            .try_with(
351                |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
352                    let mut map: RefMut<'_, HashMap<String, Vec<NetworkImageCallback>>> =
353                        slot.borrow_mut();
354                    if let Some(list) = map.get_mut(trimmed) {
355                        list.push(on_ready.clone());
356                        false
357                    } else {
358                        let _: Option<Vec<NetworkImageCallback>> =
359                            map.insert(trimmed.to_string(), vec![on_ready.clone()]);
360                        true
361                    }
362                },
363            )
364            .unwrap_or(false);
365        if should_fetch {
366            web_load_network_image(trimmed);
367        }
368    }
369    #[cfg(not(target_arch = "wasm32"))]
370    {
371        on_ready(None);
372    }
373}