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/// - `CallbackFn` - Closure executing declarative UI construction (`view!` or components).
9///
10/// # Returns
11///
12/// - `ReturnValue` - Value returned by `operation`.
13pub fn with_context<CallbackFn, ReturnValue>(ctx: Context, operation: CallbackFn) -> ReturnValue
14where
15    CallbackFn: FnOnce() -> ReturnValue,
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/// - `CallbackFn` - Closure receiving a borrowed `&Context` reference.
28///
29/// # Returns
30///
31/// - `ReturnValue` - Value returned by `operation`.
32pub fn with_current_context<CallbackFn, ReturnValue>(operation: CallbackFn) -> ReturnValue
33where
34    CallbackFn: FnOnce(&Context) -> ReturnValue,
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/// - `CallbackFn` - Reactive text producer closure.
88///
89/// # Returns
90///
91/// - `NodeId` - Created reactive text node handle.
92pub fn mount_reactive_text<CallbackFn>(style: Style, producer: CallbackFn) -> NodeId
93where
94    CallbackFn: 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/// - `CallbackFn` - Reactive `Style` producer closure.
114pub fn bind_style_current<CallbackFn>(node_id: NodeId, producer: CallbackFn)
115where
116    CallbackFn: 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/// - `CallbackFn` - Reactive child builder returning ordered `NodeId` values.
131pub fn bind_children_current<CallbackFn>(host: NodeId, builder: CallbackFn)
132where
133    CallbackFn: 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/// - `ValueType` - 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<ValueType>(value: ValueType) -> String
150where
151    ValueType: 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/// Requests that the active application immediately cancel ongoing touch-fling inertia and smooth-scroll momentum.
209pub fn request_cancel_scroll_inertia() {
210    let _: bool = SCROLL_INERTIA_CANCEL_REQUESTED
211        .try_with(|flag: &Cell<bool>| {
212            flag.set(true);
213            true
214        })
215        .unwrap_or(false);
216}
217
218/// Consumes and clears any pending scroll-inertia cancellation request for the current thread.
219///
220/// # Returns
221///
222/// - `bool` - `true` when active scroll inertia and smooth-scroll momentum should be halted immediately.
223#[must_use]
224pub fn take_cancel_scroll_inertia_request() -> bool {
225    SCROLL_INERTIA_CANCEL_REQUESTED
226        .try_with(|flag: &Cell<bool>| flag.replace(false))
227        .unwrap_or(false)
228}
229
230/// Returns `true` when any `SceneTree` borrow is currently active on the current thread.
231///
232/// # Returns
233///
234/// - `bool` - Whether a `SceneTree` read or write guard is active on this thread.
235#[must_use]
236#[inline(always)]
237pub(crate) fn is_scene_borrowed() -> bool {
238    SCENE_BORROW_DEPTH
239        .try_with(|depth: &Cell<u32>| depth.get() > 0)
240        .unwrap_or(false)
241}
242
243/// Records that `flush_effects` deferred effect execution until the active `SceneTree` borrow exits.
244#[inline(always)]
245pub(crate) fn defer_effect_flush_while_borrowed() {
246    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
247        flag.set(true);
248    });
249    notify_frame_needed();
250}
251
252/// Returns `true` when a deferred reactive effect flush is queued for the current thread without clearing it.
253///
254/// # Returns
255///
256/// - `bool` - Whether deferred reactive effects are waiting for the outer scene borrow to drop.
257#[must_use]
258#[inline(always)]
259pub(crate) fn has_deferred_effect_flush() -> bool {
260    DEFERRED_EFFECT_FLUSH.try_with(Cell::get).unwrap_or(false)
261}
262
263/// Consumes and clears the thread-local deferred reactive effect flush flag.
264///
265/// # Returns
266///
267/// - `bool` - `true` when effects were deferred while a `SceneTree` borrow was active.
268#[must_use]
269#[inline(always)]
270pub(crate) fn take_deferred_effect_flush() -> bool {
271    DEFERRED_EFFECT_FLUSH
272        .try_with(|flag: &Cell<bool>| flag.replace(false))
273        .unwrap_or(false)
274}
275
276/// Resets thread-local scene borrow-depth tracking and deferred flush state during runtime resets.
277pub(crate) fn reset_scene_borrow_state() {
278    let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
279        depth.set(0);
280    });
281    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
282        flag.set(false);
283    });
284    FRAME_NEEDED.store(false, Ordering::Release);
285}
286
287/// Inserts a decoded RGBA8 `ImageBuffer` into the thread-local network image cache under `url`.
288///
289/// # Arguments
290///
291/// - `&str` - Canonical resolved image URL or asset path.
292/// - `ImageBuffer` - Decoded RGBA8 image buffer.
293pub fn cache_network_image(url: &str, buffer: ImageBuffer) {
294    let _: Result<(), _> =
295        NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
296            let _: Option<ImageBuffer> = slot.borrow_mut().insert(url.to_string(), buffer);
297        });
298}
299
300/// Looks up a previously decoded `ImageBuffer` for `url` in O(1) without triggering network I/O.
301///
302/// # Arguments
303///
304/// - `&str` - Canonical resolved image URL or asset path.
305///
306/// # Returns
307///
308/// - `Option<ImageBuffer>` - Cached RGBA8 image buffer when available.
309#[must_use]
310pub fn cached_network_image(url: &str) -> Option<ImageBuffer> {
311    NETWORK_IMAGE_CACHE
312        .try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| slot.borrow().get(url).cloned())
313        .ok()
314        .flatten()
315}
316
317/// Clears all entries from the thread-local decoded network image cache and pending waiter registry.
318pub fn clear_network_image_cache() {
319    let _: Result<(), _> =
320        NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
321            slot.borrow_mut().clear();
322        });
323    let _: Result<(), _> = NETWORK_IMAGE_WAITERS.try_with(
324        |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
325            slot.borrow_mut().clear();
326        },
327    );
328}
329
330/// Finalizes an in-flight network image fetch for `url`, caching successful buffers and notifying all waiting callbacks.
331///
332/// # Arguments
333///
334/// - `&str` - Resolved image URL key.
335/// - `Option<ImageBuffer>` - Decoded RGBA8 buffer on success, or `None` on load failure.
336pub fn complete_network_image_load(url: &str, result: Option<ImageBuffer>) {
337    if let Some(buf) = result.as_ref() {
338        cache_network_image(url, buf.clone());
339    }
340    let waiters: Vec<NetworkImageCallback> = NETWORK_IMAGE_WAITERS
341        .try_with(
342            |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
343                slot.borrow_mut().remove(url).unwrap_or_default()
344            },
345        )
346        .unwrap_or_default();
347    for callback_fn in waiters.into_iter() {
348        callback_fn(result.clone());
349    }
350    notify_frame_needed();
351}
352
353/// Requests a decoded RGBA8 `ImageBuffer` for `url`, invoking `on_ready` immediately on cache hit or asynchronously once decoded on WebAssembly.
354///
355/// # Arguments
356///
357/// - `&str` - Resolved asset URL or path to load.
358/// - `NetworkImageCallback` - Callback receiving `Some(ImageBuffer)` on success or `None` on failure.
359pub fn request_network_image(url: &str, on_ready: NetworkImageCallback) {
360    let trimmed: &str = url.trim();
361    if trimmed.is_empty() {
362        on_ready(None);
363        return;
364    }
365    if let Some(hit) = cached_network_image(trimmed) {
366        on_ready(Some(hit));
367        return;
368    }
369    #[cfg(target_arch = "wasm32")]
370    {
371        let should_fetch: bool = NETWORK_IMAGE_WAITERS
372            .try_with(
373                |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
374                    let mut map: RefMut<'_, HashMap<String, Vec<NetworkImageCallback>>> =
375                        slot.borrow_mut();
376                    if let Some(list) = map.get_mut(trimmed) {
377                        list.push(on_ready.clone());
378                        false
379                    } else {
380                        let _: Option<Vec<NetworkImageCallback>> =
381                            map.insert(trimmed.to_string(), vec![on_ready.clone()]);
382                        true
383                    }
384                },
385            )
386            .unwrap_or(false);
387        if should_fetch {
388            web_load_network_image(trimmed);
389        }
390    }
391    #[cfg(not(target_arch = "wasm32"))]
392    {
393        on_ready(None);
394    }
395}
396
397/// Canonicalizes an `f32` into deterministic `u32` bits collapsing `-0.0` and `NaN` bit patterns.
398///
399/// # Arguments
400///
401/// - `f32` - Floating-point style scalar.
402///
403/// # Returns
404///
405/// - `u32` - Canonical 32-bit bit representation.
406#[inline(always)]
407fn canon_f32_sig_bits(val: f32) -> u32 {
408    if val.is_nan() {
409        u32::MAX
410    } else if val == 0.0 {
411        0
412    } else {
413        val.to_bits()
414    }
415}
416
417/// Mixes a 32-bit word into a 64-bit FNV-1a accumulator.
418///
419/// # Arguments
420///
421/// - `u64` - Running 64-bit hash state.
422/// - `u32` - Next 32-bit payload word.
423///
424/// # Returns
425///
426/// - `u64` - Updated 64-bit hash state.
427#[inline(always)]
428fn fnv_mix_u32(acc: u64, word: u32) -> u64 {
429    (acc ^ (word as u64)).wrapping_mul(0x0000_0100_0000_01B3)
430}
431
432/// Computes compact `(layout_sig, text_metric_sig)` 64-bit fingerprints for `style` in zero allocations.
433///
434/// Pure paint mutations (`background`, `gradient`, `color`, `border.color`, `radius`, `shadow`,
435/// `opacity`, `transform`, `cursor`, `underline`, `strikethrough`) leave both signatures unchanged
436/// so `DIRTY_PAINT` / `DIRTY_COMPOSITE` fast paths remain zero-layout-cost, while any mutation to
437/// `LayoutStyle`, `border.width`, or glyph-measuring `TextStyle` properties changes the signature.
438///
439/// # Arguments
440///
441/// - `&Style` - Compiled node style to fingerprint.
442///
443/// # Returns
444///
445/// - `(u64, u64)` - Pair `(layout_sig, text_metric_sig)`.
446#[must_use]
447#[inline]
448pub(crate) fn compute_style_sigs(style: &Style) -> (u64, u64) {
449    let lay: &LayoutStyle = style.layout_ref();
450    let vals: [f32; 7] = lay.get_length_vals();
451    let margin: Edges = lay.get_margin();
452    let padding: Edges = lay.get_padding();
453    let mut lh: u64 = 0xCBF2_9CE4_8422_2325;
454    lh = fnv_mix_u32(lh, lay.get_flags());
455    lh = fnv_mix_u32(lh, lay.get_length_tags());
456    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[0]));
457    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[1]));
458    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[2]));
459    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[3]));
460    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[4]));
461    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[5]));
462    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[6]));
463    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_grow()));
464    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_shrink()));
465    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_top()));
466    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_right()));
467    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_bottom()));
468    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_left()));
469    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_top()));
470    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_right()));
471    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_bottom()));
472    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_left()));
473    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_row_gap()));
474    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_column_gap()));
475    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_top_val()));
476    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_right_val()));
477    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_bottom_val()));
478    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_left_val()));
479    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_aspect_ratio_val()));
480    lh = fnv_mix_u32(lh, lay.get_z_index() as u32);
481    lh = fnv_mix_u32(lh, u32::from(lay.get_grid_columns()));
482    lh = fnv_mix_u32(
483        lh,
484        canon_f32_sig_bits(style.paint_ref().get_border().get_width()),
485    );
486    let txt: &TextStyle = style.text_ref();
487    let fam_tag: u32 = match txt.get_family() {
488        FontFamily::Sans => 0,
489        FontFamily::Monospace => 1,
490        FontFamily::Serif => 2,
491    };
492    let weight_tag: u32 = match txt.get_weight() {
493        FontWeight::Light => 0,
494        FontWeight::Normal => 1,
495        FontWeight::Medium => 2,
496        FontWeight::SemiBold => 3,
497        FontWeight::Bold => 4,
498    };
499    let align_tag: u32 = match txt.get_align() {
500        TextAlign::Left => 0,
501        TextAlign::Center => 1,
502        TextAlign::Right => 2,
503    };
504    let ov_tag: u32 = match txt.get_overflow() {
505        TextOverflow::Wrap => 0,
506        TextOverflow::Clip => 1,
507        TextOverflow::Ellipsis => 2,
508    };
509    let packed_enums: u32 = fam_tag
510        | (weight_tag << 3)
511        | (align_tag << 7)
512        | (ov_tag << 10)
513        | (u32::from(txt.get_italic()) << 13);
514    let mut th: u64 = 0xCBF2_9CE4_8422_2325;
515    th = fnv_mix_u32(th, packed_enums);
516    th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_font_size()));
517    th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_line_height()));
518    th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_letter_spacing()));
519    (lh, th)
520}