euv-core 0.48.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use super::*;

/// Invokes a snapshot of system event callbacks outside any hub or scene borrow.
///
/// # Arguments
///
/// - `Vec<SystemEventCallback>` - Ordered listener callbacks to invoke.
/// - `&SystemEvent` - Normalized system event payload.
fn invoke_system_callbacks(callbacks: Vec<SystemEventCallback>, event: &SystemEvent) {
    for callback in callbacks.into_iter() {
        if let Ok(mut func) = callback.try_borrow_mut() {
            func(event);
        }
    }
}

/// Dispatches `event` synchronously to all active (non-frozen) scoped system event listeners.
///
/// # Arguments
///
/// - `&SystemEvent` - Normalized system event payload.
pub(crate) fn dispatch_system_event_listeners(event: &SystemEvent) {
    let callbacks: Vec<SystemEventCallback> = SYSTEM_EVENT_HUB
        .try_with(|cell: &RefCell<SystemEventHub>| {
            cell.try_borrow()
                .map(|hub: Ref<'_, SystemEventHub>| hub.snapshot_active())
                .unwrap_or_default()
        })
        .unwrap_or_default();
    invoke_system_callbacks(callbacks, event);
}

/// Dispatches `event` synchronously to listeners owned by any reactive scope within `scopes`.
///
/// # Arguments
///
/// - `&[ScopeId]` - Root scope identifiers defining the target page or component subtree.
/// - `&SystemEvent` - System event payload (`Appear` or `Disappear`).
pub(crate) fn dispatch_system_event_to_scopes(scopes: &[ScopeId], event: &SystemEvent) {
    let callbacks: Vec<SystemEventCallback> = SYSTEM_EVENT_HUB
        .try_with(|cell: &RefCell<SystemEventHub>| {
            cell.try_borrow()
                .map(|hub: Ref<'_, SystemEventHub>| hub.snapshot_for_scopes(scopes))
                .unwrap_or_default()
        })
        .unwrap_or_default();
    invoke_system_callbacks(callbacks, event);
}

/// Sanitizes a single sensor floating-point scalar, replacing non-finite values with `fallback` and clamping to `[-limit, limit]`.
///
/// # Arguments
///
/// - `f32` - Raw sensor scalar.
/// - `f32` - Symmetric physical clamp magnitude.
/// - `f32` - Replacement value when `value` is NaN or infinite.
///
/// # Returns
///
/// - `f32` - Finite clamped scalar.
#[must_use]
pub(crate) fn sanitize_motion_scalar(value: f32, limit: f32, fallback: f32) -> f32 {
    if value.is_finite() {
        value.clamp(-limit, limit)
    } else {
        fallback
    }
}

/// Rotates a natural-portrait 3D device vector `(+X_right, +Y_up, +Z_out)` into the active screen's `(+X_right, +Y_up, +Z_out)` frame for display rotation angles `0`, `90`, `180`, or `270` degrees.
///
/// # Arguments
///
/// - `[f32; 3]` - Vector in natural device coordinates.
/// - `i32` - Display rotation angle in degrees (`0`, `90`, `180`, `270`, or negative equivalent).
///
/// # Returns
///
/// - `[f32; 3]` - Screen-aligned vector in `(+X_right, +Y_up, +Z_out)`.
#[must_use]
pub(crate) fn rotate_device_vec_to_screen_up(vec: [f32; 3], screen_angle_deg: i32) -> [f32; 3] {
    let norm_deg: i32 = screen_angle_deg.rem_euclid(360);
    let snapped: i32 = ((norm_deg + 45) / 90) % 4;
    let dx: f32 = vec[0];
    let dy: f32 = vec[1];
    let dz: f32 = vec[2];
    match snapped {
        1 => [-dy, dx, dz],
        2 => [-dx, -dy, dz],
        3 => [dy, -dx, dz],
        _ => [dx, dy, dz],
    }
}

/// Records the latest sanitized `DeviceMotionSample` on the current UI thread without heap allocation.
///
/// # Arguments
///
/// - `DeviceMotionSample` - Sanitized motion sensor sample.
pub(crate) fn record_latest_device_motion(sample: DeviceMotionSample) {
    let _: Result<(), _> = LATEST_DEVICE_MOTION.try_with(|cell: &Cell<DeviceMotionSample>| {
        cell.set(sample);
    });
}

/// Returns the most recent sanitized `DeviceMotionSample` dispatched on the current UI thread.
///
/// # Returns
///
/// - `DeviceMotionSample` - Latest sensor sample, or upright default when inactive.
#[must_use]
pub fn latest_device_motion() -> DeviceMotionSample {
    LATEST_DEVICE_MOTION
        .try_with(|cell: &Cell<DeviceMotionSample>| cell.get())
        .unwrap_or_default()
}

/// Clears all registered thread-local system event listeners when resetting the reactive runtime.
pub(crate) fn reset_system_event_hub() {
    let _: Result<(), _> = SYSTEM_EVENT_HUB.try_with(|cell: &RefCell<SystemEventHub>| {
        if let Ok(mut hub) = cell.try_borrow_mut() {
            hub.clear();
        }
    });
    let _: Result<(), _> = LATEST_DEVICE_MOTION.try_with(|cell: &Cell<DeviceMotionSample>| {
        cell.set(DeviceMotionSample::upright());
    });
}

/// Subscribes a scoped listener invoked for every normalized cross-platform `SystemEvent`.
///
/// Automatically unregisters when the enclosing reactive `Scope` disposes.
///
/// # Arguments
///
/// - `F` - Handler closure receiving `&SystemEvent`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Copyable handle supporting optional early `.unsubscribe()`.
pub fn on_system_event<F>(handler: F) -> SystemEventSubscription
where
    F: FnMut(&SystemEvent) + 'static,
{
    let owner_scope: Option<ScopeId> =
        with_runtime(|rt: &mut ReactiveRuntime| rt.current_scope_id(), None);
    let callback: SystemEventCallback = Rc::new(RefCell::new(handler));
    let id: u64 = SYSTEM_EVENT_HUB
        .try_with(|cell: &RefCell<SystemEventHub>| {
            cell.try_borrow_mut()
                .map(|mut hub: RefMut<'_, SystemEventHub>| hub.register(owner_scope, callback))
                .unwrap_or(0)
        })
        .unwrap_or(0);
    let sub: SystemEventSubscription = SystemEventSubscription::new(id);
    if owner_scope.is_some() && id != 0 {
        on_cleanup(move || {
            sub.unsubscribe();
        });
    }
    sub
}

/// Subscribes a scoped handler invoked when the application window or current routed page appears.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::Appear`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_appear<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::Appear) {
            handler();
        }
    })
}

/// Subscribes a scoped handler invoked when the application window or current routed page disappears.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::Disappear`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_disappear<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::Disappear) {
            handler();
        }
    })
}

/// Subscribes a scoped handler invoked when the application enters active foreground execution.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::Foreground`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_foreground<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::Foreground) {
            handler();
        }
    })
}

/// Subscribes a scoped handler invoked when the application enters background execution.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::Background`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_background<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::Background) {
            handler();
        }
    })
}

/// Subscribes a scoped handler invoked when the application transitions to inactive status.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::Inactive`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_inactive<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::Inactive) {
            handler();
        }
    })
}

/// Subscribes a scoped handler invoked when the application is terminating gracefully.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::Terminate`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_terminate<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::Terminate) {
            handler();
        }
    })
}

/// Subscribes a scoped handler invoked whenever window focus changes.
///
/// # Arguments
///
/// - `F` - Callback receiving `true` on focus gain and `false` on focus loss.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_focus_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(bool) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::FocusChanged(focused) = event {
            handler(*focused);
        }
    })
}

/// Subscribes a scoped handler invoked whenever logical viewport size or DPI scale changes.
///
/// # Arguments
///
/// - `F` - Callback receiving `(width, height, scale_factor)`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_resize<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(f32, f32, f32) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::Resize {
            width,
            height,
            scale_factor,
        } = event
        {
            handler(*width, *height, *scale_factor);
        }
    })
}

/// Subscribes a scoped handler invoked whenever safe-area insets change.
///
/// # Arguments
///
/// - `F` - Callback receiving updated `SafeAreaInsets`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_safe_area_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(SafeAreaInsets) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::SafeAreaChanged(insets) = event {
            handler(*insets);
        }
    })
}

/// Subscribes a scoped handler invoked whenever screen orientation changes.
///
/// # Arguments
///
/// - `F` - Callback receiving updated `ScreenOrientation`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_orientation_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(ScreenOrientation) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::OrientationChanged(orient) = event {
            handler(*orient);
        }
    })
}

/// Subscribes a scoped handler invoked whenever host OS/browser light or dark theme changes.
///
/// # Arguments
///
/// - `F` - Callback receiving updated `ThemeMode`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_theme_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(ThemeMode) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::ThemeChanged(theme) = event {
            handler(*theme);
        }
    })
}

/// Subscribes a scoped handler invoked whenever host OS/browser preferred locale changes.
///
/// # Arguments
///
/// - `F` - Callback receiving the updated BCP-47 locale tag slice.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_locale_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(&str) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::LocaleChanged(locale) = event {
            handler(locale.as_str());
        }
    })
}

/// Subscribes a scoped handler invoked whenever soft keyboard visibility or height changes.
///
/// # Arguments
///
/// - `F` - Callback receiving `(visible, height_dp)`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_keyboard_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(bool, f32) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::KeyboardVisibilityChanged { visible, height } = event {
            handler(*visible, *height);
        }
    })
}

/// Subscribes a scoped handler invoked whenever the OS signals memory pressure.
///
/// # Arguments
///
/// - `F` - Callback receiving `MemoryPressure`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_memory_warning<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(MemoryPressure) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::MemoryWarning(pressure) = event {
            handler(*pressure);
        }
    })
}

/// Subscribes a scoped handler invoked whenever OS battery saver / low-power mode toggles.
///
/// # Arguments
///
/// - `F` - Callback receiving `true` when low-power mode is enabled.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_low_power_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(bool) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::LowPowerModeChanged(enabled) = event {
            handler(*enabled);
        }
    })
}

/// Subscribes a scoped handler invoked whenever host network connectivity status changes.
///
/// # Arguments
///
/// - `F` - Callback receiving updated `NetworkStatus`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_network_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(NetworkStatus) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::NetworkStatusChanged(status) = event {
            handler(*status);
        }
    })
}

/// Subscribes a scoped handler invoked whenever a system back gesture or key press occurs.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::BackPressed`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_system_back<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::BackPressed) {
            handler();
        }
    })
}

/// Subscribes a scoped handler invoked whenever the host OS delivers a deep link URI.
///
/// # Arguments
///
/// - `F` - Callback receiving the deep link URI slice.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_deep_link<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(&str) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::DeepLink(uri) = event {
            handler(uri.as_str());
        }
    })
}

/// Subscribes a scoped handler invoked whenever the system clipboard changes.
///
/// # Arguments
///
/// - `F` - Zero-argument callback invoked on `SystemEvent::ClipboardChanged`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_clipboard_change<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut() + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if matches!(event, SystemEvent::ClipboardChanged) {
            handler();
        }
    })
}

/// Returns the reactive `Signal<AppState>` from the active ambient `Context`.
///
/// # Returns
///
/// - `Signal<AppState>` - Reactive application lifecycle state signal.
#[must_use]
pub fn use_app_state() -> Signal<AppState> {
    current_context().app_state_signal()
}

/// Returns the reactive `Signal<ThemeMode>` from the active ambient `Context`.
///
/// # Returns
///
/// - `Signal<ThemeMode>` - Reactive OS light/dark theme signal.
#[must_use]
pub fn use_system_theme() -> Signal<ThemeMode> {
    current_context().get_theme_mode()
}

/// Returns the reactive `Signal<NetworkStatus>` from the active ambient `Context`.
///
/// # Returns
///
/// - `Signal<NetworkStatus>` - Reactive network connectivity status signal.
#[must_use]
pub fn use_network_status() -> Signal<NetworkStatus> {
    current_context().get_network_status()
}

/// Returns the reactive `Signal<f32>` carrying current soft keyboard height in logical pixels.
///
/// # Returns
///
/// - `Signal<f32>` - Reactive keyboard height signal (`0.0` when hidden).
#[must_use]
pub fn use_keyboard_height() -> Signal<f32> {
    current_context().get_keyboard_height()
}

/// Subscribes a scoped handler invoked whenever a 6-DOF gyroscope/accelerometer sample arrives.
///
/// # Arguments
///
/// - `F` - Callback receiving the sanitized screen-aligned `DeviceMotionSample`.
///
/// # Returns
///
/// - `SystemEventSubscription` - Subscription handle auto-cleaned on `Scope` disposal.
pub fn on_device_motion<F>(mut handler: F) -> SystemEventSubscription
where
    F: FnMut(DeviceMotionSample) + 'static,
{
    on_system_event(move |event: &SystemEvent| {
        if let SystemEvent::DeviceMotion(sample) = event {
            handler(*sample);
        }
    })
}

/// Returns the reactive `Signal<SafeAreaInsets>` from the active ambient `Context`.
///
/// # Returns
///
/// - `Signal<SafeAreaInsets>` - Reactive display safe-area insets signal.
#[must_use]
pub fn use_safe_area() -> Signal<SafeAreaInsets> {
    current_context().get_safe_area()
}

/// Returns the reactive `Signal<DeviceMotionSample>` from the active ambient `Context`.
///
/// # Returns
///
/// - `Signal<DeviceMotionSample>` - Reactive screen-aligned 6-DOF device motion signal.
#[must_use]
pub fn use_device_motion() -> Signal<DeviceMotionSample> {
    current_context().get_device_motion()
}

/// Requests Web browser gyroscope/accelerometer permission (required by iOS Safari inside a user gesture) and attaches sensor listeners.
///
/// On native targets this is a safe no-op returning `true` since hardware sensors are bridged directly via OS APIs.
///
/// # Returns
///
/// - `bool` - `true` when browser permission was requested/granted or sensors are natively managed.
#[must_use]
pub fn request_web_motion_permission() -> bool {
    #[cfg(target_arch = "wasm32")]
    {
        web_request_motion_permission_impl()
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        true
    }
}