euv-core 0.51.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use super::*;

/// Runs `operation` with `ctx` bound as the active ambient `Context`, restoring any previous context on exit.
///
/// # Arguments
///
/// - `Context` - Framework context to bind during `operation`.
/// - `CallbackFn` - Closure executing declarative UI construction (`view!` or components).
///
/// # Returns
///
/// - `ReturnValue` - Value returned by `operation`.
pub fn with_context<CallbackFn, ReturnValue>(ctx: Context, operation: CallbackFn) -> ReturnValue
where
    CallbackFn: FnOnce() -> ReturnValue,
{
    let previous: Option<Context> =
        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow_mut().replace(ctx));
    let _guard: ContextGuard = ContextGuard::new(previous);
    operation()
}

/// Borrows the active ambient `Context` without cloning its 216-byte struct or bumping its `Rc` handles.
///
/// # Arguments
///
/// - `CallbackFn` - Closure receiving a borrowed `&Context` reference.
///
/// # Returns
///
/// - `ReturnValue` - Value returned by `operation`.
pub fn with_current_context<CallbackFn, ReturnValue>(operation: CallbackFn) -> ReturnValue
where
    CallbackFn: FnOnce(&Context) -> ReturnValue,
{
    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
        let borrowed: Ref<'_, Option<Context>> = slot.borrow();
        if let Some(ctx) = borrowed.as_ref() {
            operation(ctx)
        } else {
            drop(borrowed);
            let fallback: Context = Context::new(SceneHandle::new_tree(), PlatformKind::Headless);
            operation(&fallback)
        }
    })
}

/// Returns a cloned handle to the active ambient `Context`.
///
/// # Returns
///
/// - `Context` - Currently bound ambient framework context.
#[must_use]
pub fn current_context() -> Context {
    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
        slot.borrow()
            .clone()
            .unwrap_or_else(|| Context::new(SceneHandle::new_tree(), PlatformKind::Headless))
    })
}

/// Returns `true` when an ambient `Context` is currently bound on this thread.
///
/// # Returns
///
/// - `bool` - Whether `with_context` or `App::mount` is active.
#[must_use]
pub fn has_context() -> bool {
    ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| slot.borrow().is_some())
}

/// Returns the active `PlatformKind` from the ambient `Context`.
///
/// # Returns
///
/// - `PlatformKind` - Execution platform kind.
#[must_use]
pub fn current_platform() -> PlatformKind {
    with_current_context(|ctx: &Context| ctx.get_platform())
}

/// Mounts a reactive `Text` node in the ambient `Context` without cloning the full `Context` struct.
///
/// # Arguments
///
/// - `Style` - Initial text style.
/// - `CallbackFn` - Reactive text producer closure.
///
/// # Returns
///
/// - `NodeId` - Created reactive text node handle.
pub fn mount_reactive_text<CallbackFn>(style: Style, producer: CallbackFn) -> NodeId
where
    CallbackFn: FnMut() -> String + 'static,
{
    let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
    let node_id: NodeId = handle.with_write(
        |tree: &mut SceneTree| tree.create_text(String::new(), style),
        NodeId::default(),
    );
    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_text(node_id, producer));
    handle.mutate(move |tree: &mut SceneTree| {
        tree.attach_scope(node_id, scope);
    });
    node_id
}

/// Binds a reactive `Style` closure onto `node_id` in the ambient `Context` without cloning `Context`.
///
/// # Arguments
///
/// - `NodeId` - Target scene node handle.
/// - `CallbackFn` - Reactive `Style` producer closure.
pub fn bind_style_current<CallbackFn>(node_id: NodeId, producer: CallbackFn)
where
    CallbackFn: FnMut() -> Style + 'static,
{
    let handle: SceneHandle = with_current_context(|ctx: &Context| ctx.get_scene().clone());
    let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| handle.bind_style(node_id, producer));
    handle.mutate(move |tree: &mut SceneTree| {
        tree.attach_scope(node_id, scope);
    });
}

/// Mounts a reactive child builder onto `host` using the ambient `Context`.
///
/// # Arguments
///
/// - `NodeId` - Host container node handle.
/// - `CallbackFn` - Reactive child builder returning ordered `NodeId` values.
pub fn bind_children_current<CallbackFn>(host: NodeId, builder: CallbackFn)
where
    CallbackFn: FnMut() -> Vec<NodeId> + 'static,
{
    let mut ctx: Context = current_context();
    ctx.bind_children(host, builder);
}

/// Converts any string-like value into an owned `String` for declarative `view!` macro expansion.
///
/// # Arguments
///
/// - `ValueType` - String-like text value implementing `Into<String>`.
///
/// # Returns
///
/// - `String` - Owned UTF-8 text string.
#[must_use]
pub fn into_text<ValueType>(value: ValueType) -> String
where
    ValueType: Into<String>,
{
    value.into()
}

/// Registers a zero-allocation platform frame-wakeup callback invoked whenever reactive or scene state dirties an idle frame loop.
///
/// # Arguments
///
/// - `fn()` - Wakeup callback requesting the next host VSync or `requestAnimationFrame` presentation.
pub fn register_frame_wakeup(hook: fn()) {
    FRAME_WAKEUP_HOOK.store(hook as *mut (), Ordering::Release);
    if FRAME_NEEDED.load(Ordering::Acquire) {
        hook();
    }
}

/// Unregisters any active platform frame-wakeup callback.
pub fn clear_frame_wakeup() {
    FRAME_WAKEUP_HOOK.store(null_mut(), Ordering::Release);
}

/// Marks that pending reactive or scene updates require presentation and invokes the registered wakeup hook on idle-to-dirty edges.
#[inline(always)]
pub fn notify_frame_needed() {
    if !FRAME_NEEDED.load(Ordering::Relaxed) && !FRAME_NEEDED.swap(true, Ordering::AcqRel) {
        let raw: *mut () = FRAME_WAKEUP_HOOK.load(Ordering::Acquire);
        if !raw.is_null() {
            // SAFETY: `raw` is stored exclusively via `register_frame_wakeup` from a valid `fn()` pointer.
            let hook: fn() = unsafe { transmute::<*mut (), fn()>(raw) };
            hook();
        }
    }
}

/// Atomically consumes and clears the pending frame-wakeup flag before rendering a frame.
///
/// # Returns
///
/// - `bool` - `true` when at least one reactive or scene invalidation occurred since the previous take.
#[must_use]
#[inline(always)]
pub fn take_frame_needed() -> bool {
    FRAME_NEEDED.swap(false, Ordering::AcqRel)
}

/// Returns whether a reactive or scene invalidation has marked a new frame as needed without consuming the flag.
///
/// # Returns
///
/// - `bool` - `true` when a new frame presentation has been requested.
#[must_use]
#[inline(always)]
pub fn is_frame_needed() -> bool {
    FRAME_NEEDED.load(Ordering::Acquire)
}

/// Returns `true` when any `SceneTree` borrow is currently active on the current thread.
///
/// # Returns
///
/// - `bool` - Whether a `SceneTree` read or write guard is active on this thread.
#[must_use]
#[inline(always)]
pub(crate) fn is_scene_borrowed() -> bool {
    SCENE_BORROW_DEPTH
        .try_with(|depth: &Cell<u32>| depth.get() > 0)
        .unwrap_or(false)
}

/// Records that `flush_effects` deferred effect execution until the active `SceneTree` borrow exits.
#[inline(always)]
pub(crate) fn defer_effect_flush_while_borrowed() {
    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
        flag.set(true);
    });
    notify_frame_needed();
}

/// Returns `true` when a deferred reactive effect flush is queued for the current thread without clearing it.
///
/// # Returns
///
/// - `bool` - Whether deferred reactive effects are waiting for the outer scene borrow to drop.
#[must_use]
#[inline(always)]
pub(crate) fn has_deferred_effect_flush() -> bool {
    DEFERRED_EFFECT_FLUSH.try_with(Cell::get).unwrap_or(false)
}

/// Consumes and clears the thread-local deferred reactive effect flush flag.
///
/// # Returns
///
/// - `bool` - `true` when effects were deferred while a `SceneTree` borrow was active.
#[must_use]
#[inline(always)]
pub(crate) fn take_deferred_effect_flush() -> bool {
    DEFERRED_EFFECT_FLUSH
        .try_with(|flag: &Cell<bool>| flag.replace(false))
        .unwrap_or(false)
}

/// Resets thread-local scene borrow-depth tracking and deferred flush state during runtime resets.
pub(crate) fn reset_scene_borrow_state() {
    let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
        depth.set(0);
    });
    let _: Result<(), _> = DEFERRED_EFFECT_FLUSH.try_with(|flag: &Cell<bool>| {
        flag.set(false);
    });
    FRAME_NEEDED.store(false, Ordering::Release);
}

/// Inserts a decoded RGBA8 `ImageBuffer` into the thread-local network image cache under `url`.
///
/// # Arguments
///
/// - `&str` - Canonical resolved image URL or asset path.
/// - `ImageBuffer` - Decoded RGBA8 image buffer.
pub fn cache_network_image(url: &str, buffer: ImageBuffer) {
    let _: Result<(), _> =
        NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
            let _: Option<ImageBuffer> = slot.borrow_mut().insert(url.to_string(), buffer);
        });
}

/// Looks up a previously decoded `ImageBuffer` for `url` in O(1) without triggering network I/O.
///
/// # Arguments
///
/// - `&str` - Canonical resolved image URL or asset path.
///
/// # Returns
///
/// - `Option<ImageBuffer>` - Cached RGBA8 image buffer when available.
#[must_use]
pub fn cached_network_image(url: &str) -> Option<ImageBuffer> {
    NETWORK_IMAGE_CACHE
        .try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| slot.borrow().get(url).cloned())
        .ok()
        .flatten()
}

/// Clears all entries from the thread-local decoded network image cache and pending waiter registry.
pub fn clear_network_image_cache() {
    let _: Result<(), _> =
        NETWORK_IMAGE_CACHE.try_with(|slot: &RefCell<HashMap<String, ImageBuffer>>| {
            slot.borrow_mut().clear();
        });
    let _: Result<(), _> = NETWORK_IMAGE_WAITERS.try_with(
        |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
            slot.borrow_mut().clear();
        },
    );
}

/// Finalizes an in-flight network image fetch for `url`, caching successful buffers and notifying all waiting callbacks.
///
/// # Arguments
///
/// - `&str` - Resolved image URL key.
/// - `Option<ImageBuffer>` - Decoded RGBA8 buffer on success, or `None` on load failure.
pub fn complete_network_image_load(url: &str, result: Option<ImageBuffer>) {
    if let Some(buf) = result.as_ref() {
        cache_network_image(url, buf.clone());
    }
    let waiters: Vec<NetworkImageCallback> = NETWORK_IMAGE_WAITERS
        .try_with(
            |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
                slot.borrow_mut().remove(url).unwrap_or_default()
            },
        )
        .unwrap_or_default();
    for callback_fn in waiters.into_iter() {
        callback_fn(result.clone());
    }
    notify_frame_needed();
}

/// Requests a decoded RGBA8 `ImageBuffer` for `url`, invoking `on_ready` immediately on cache hit or asynchronously once decoded on WebAssembly.
///
/// # Arguments
///
/// - `&str` - Resolved asset URL or path to load.
/// - `NetworkImageCallback` - Callback receiving `Some(ImageBuffer)` on success or `None` on failure.
pub fn request_network_image(url: &str, on_ready: NetworkImageCallback) {
    let trimmed: &str = url.trim();
    if trimmed.is_empty() {
        on_ready(None);
        return;
    }
    if let Some(hit) = cached_network_image(trimmed) {
        on_ready(Some(hit));
        return;
    }
    #[cfg(target_arch = "wasm32")]
    {
        let should_fetch: bool = NETWORK_IMAGE_WAITERS
            .try_with(
                |slot: &RefCell<HashMap<String, Vec<NetworkImageCallback>>>| {
                    let mut map: RefMut<'_, HashMap<String, Vec<NetworkImageCallback>>> =
                        slot.borrow_mut();
                    if let Some(list) = map.get_mut(trimmed) {
                        list.push(on_ready.clone());
                        false
                    } else {
                        let _: Option<Vec<NetworkImageCallback>> =
                            map.insert(trimmed.to_string(), vec![on_ready.clone()]);
                        true
                    }
                },
            )
            .unwrap_or(false);
        if should_fetch {
            web_load_network_image(trimmed);
        }
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        on_ready(None);
    }
}

/// Canonicalizes an `f32` into deterministic `u32` bits collapsing `-0.0` and `NaN` bit patterns.
///
/// # Arguments
///
/// - `f32` - Floating-point style scalar.
///
/// # Returns
///
/// - `u32` - Canonical 32-bit bit representation.
#[inline(always)]
fn canon_f32_sig_bits(val: f32) -> u32 {
    if val.is_nan() {
        u32::MAX
    } else if val == 0.0 {
        0
    } else {
        val.to_bits()
    }
}

/// Mixes a 32-bit word into a 64-bit FNV-1a accumulator.
///
/// # Arguments
///
/// - `u64` - Running 64-bit hash state.
/// - `u32` - Next 32-bit payload word.
///
/// # Returns
///
/// - `u64` - Updated 64-bit hash state.
#[inline(always)]
fn fnv_mix_u32(acc: u64, word: u32) -> u64 {
    (acc ^ (word as u64)).wrapping_mul(0x0000_0100_0000_01B3)
}

/// Computes compact `(layout_sig, text_metric_sig)` 64-bit fingerprints for `style` in zero allocations.
///
/// Pure paint mutations (`background`, `gradient`, `color`, `border.color`, `radius`, `shadow`,
/// `opacity`, `transform`, `cursor`, `underline`, `strikethrough`) leave both signatures unchanged
/// so `DIRTY_PAINT` / `DIRTY_COMPOSITE` fast paths remain zero-layout-cost, while any mutation to
/// `LayoutStyle`, `border.width`, or glyph-measuring `TextStyle` properties changes the signature.
///
/// # Arguments
///
/// - `&Style` - Compiled node style to fingerprint.
///
/// # Returns
///
/// - `(u64, u64)` - Pair `(layout_sig, text_metric_sig)`.
#[must_use]
#[inline]
pub(crate) fn compute_style_sigs(style: &Style) -> (u64, u64) {
    let lay: &LayoutStyle = style.layout_ref();
    let vals: [f32; 7] = lay.get_length_vals();
    let margin: Edges = lay.get_margin();
    let padding: Edges = lay.get_padding();
    let mut lh: u64 = 0xCBF2_9CE4_8422_2325;
    lh = fnv_mix_u32(lh, lay.get_flags());
    lh = fnv_mix_u32(lh, lay.get_length_tags());
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[0]));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[1]));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[2]));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[3]));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[4]));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[5]));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(vals[6]));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_grow()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_flex_shrink()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_top()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_right()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_bottom()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(margin.get_left()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_top()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_right()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_bottom()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(padding.get_left()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_row_gap()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_column_gap()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_top_val()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_right_val()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_bottom_val()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_left_val()));
    lh = fnv_mix_u32(lh, canon_f32_sig_bits(lay.get_aspect_ratio_val()));
    lh = fnv_mix_u32(lh, lay.get_z_index() as u32);
    lh = fnv_mix_u32(lh, u32::from(lay.get_grid_columns()));
    lh = fnv_mix_u32(
        lh,
        canon_f32_sig_bits(style.paint_ref().get_border().get_width()),
    );
    let txt: &TextStyle = style.text_ref();
    let fam_tag: u32 = match txt.get_family() {
        FontFamily::Sans => 0,
        FontFamily::Monospace => 1,
        FontFamily::Serif => 2,
    };
    let weight_tag: u32 = match txt.get_weight() {
        FontWeight::Light => 0,
        FontWeight::Normal => 1,
        FontWeight::Medium => 2,
        FontWeight::SemiBold => 3,
        FontWeight::Bold => 4,
    };
    let align_tag: u32 = match txt.get_align() {
        TextAlign::Left => 0,
        TextAlign::Center => 1,
        TextAlign::Right => 2,
    };
    let ov_tag: u32 = match txt.get_overflow() {
        TextOverflow::Wrap => 0,
        TextOverflow::Clip => 1,
        TextOverflow::Ellipsis => 2,
    };
    let packed_enums: u32 = fam_tag
        | (weight_tag << 3)
        | (align_tag << 7)
        | (ov_tag << 10)
        | (u32::from(txt.get_italic()) << 13);
    let mut th: u64 = 0xCBF2_9CE4_8422_2325;
    th = fnv_mix_u32(th, packed_enums);
    th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_font_size()));
    th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_line_height()));
    th = fnv_mix_u32(th, canon_f32_sig_bits(txt.get_letter_spacing()));
    (lh, th)
}