euv-example 0.51.0

Cross-platform native showcase application demonstrating euv fine-grained reactivity, multi-mode rendering, window controls, and euv-ui components.
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
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::{
    env,
    thread::sleep,
    time::{Duration, Instant},
};
#[cfg(target_os = "macos")]
use std::{
    ffi::c_void,
    ptr::{null, null_mut},
    sync::atomic::{AtomicBool, Ordering},
};

#[cfg(target_os = "macos")]
use euv::PlatformKind;
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
use euv_automation::{AiAppHooks, AiSchemaProtocol, DEV_AI_INSPECTOR_ADDR, DevAutomationBridge};
#[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
use euv_example::{
    ENV_AI_INSPECTOR_ADDR, FLAG_AI_QUERY, FLAG_AI_SCHEMA, FLAG_AI_URI, dispatch_automation_uri,
};
#[cfg(not(target_arch = "wasm32"))]
use euv_example::{FLAG_CAPTURE_DIR, capture_showcase_screenshots};
#[cfg(target_os = "macos")]
use euv_example::{MACOS_CF_STRING_ENCODING_UTF8, MACOS_EVENT_TRACKING_RUN_LOOP_MODE};
use {
    euv::{
        AdaptiveFrameMetrics, AdaptiveRouterSnapshot, App, FrameStats, MIN_REFRESH_RATE_HZ,
        PlatformError, Rect, RenderMode, is_frame_needed,
    },
    euv_example::{
        FLAG_HARDWARE, FLAG_HEADLESS, FLAG_HYBRID, FLAG_INTERACTIVE, FLAG_SOFTWARE,
        ShowcaseAdaptiveSyncKey, ShowcaseState, create_showcase_app, run_headless_smoke,
        showcase_has_active_game_viewport, sync_showcase_adaptive_if_changed,
    },
};

/// Upper display refresh-rate ceiling supported by the interactive native showcase loop (`1000 Hz`).
const MAIN_MAX_REFRESH_RATE_HZ: f32 = 1000.0;

/// CoreFoundation `CFRunLoopTimerContext` ABI layout for macOS modal live-resize repaints.
#[cfg(target_os = "macos")]
#[repr(C)]
struct MainCfRunLoopTimerContext {
    /// Structure version (`0`).
    version: isize,
    /// Opaque user payload pointer.
    info: *mut c_void,
    /// Optional retain callback.
    retain: *const c_void,
    /// Optional release callback.
    release: *const c_void,
    /// Optional description callback.
    copy_description: *const c_void,
}

/// Stack-pinned context shared with the macOS `NSEventTrackingRunLoopMode` live-resize timer callback.
#[cfg(target_os = "macos")]
struct MainMacosLiveResizeState {
    /// Live pointer to the active showcase `App` on the main AppKit thread.
    app_ptr: *mut App,
    /// Re-entrancy guard preventing recursive `step_frame` execution.
    in_step: AtomicBool,
}

#[cfg(target_os = "macos")]
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
    /// Returns the monotonic CoreFoundation absolute time in seconds.
    ///
    /// # Returns
    ///
    /// - `f64` - Seconds since the CoreFoundation reference epoch.
    fn CFAbsoluteTimeGetCurrent() -> f64;
    /// Returns the current thread's `CFRunLoopRef`.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Current `CFRunLoopRef`.
    fn CFRunLoopGetCurrent() -> *mut c_void;
    /// Creates a `CFStringRef` from UTF-8 bytes without heap copying when external representation is false.
    ///
    /// # Arguments
    ///
    /// - `*const c_void` - Allocator (`null`).
    /// - `*const u8` - UTF-8 byte pointer.
    /// - `isize` - Byte count.
    /// - `u32` - String encoding (`MACOS_CF_STRING_ENCODING_UTF8`).
    /// - `u8` - External representation flag (`0`).
    ///
    /// # Returns
    ///
    /// - `*const c_void` - Retained `CFStringRef`.
    fn CFStringCreateWithBytes(
        alloc: *const c_void,
        bytes: *const u8,
        num_bytes: isize,
        encoding: u32,
        is_external_representation: u8,
    ) -> *const c_void;
    /// Creates a `CFRunLoopTimerRef` firing at the display refresh interval during live resize tracking.
    ///
    /// # Arguments
    ///
    /// - `*const c_void` - Allocator (`null`).
    /// - `f64` - First fire timestamp in CF absolute time.
    /// - `f64` - Repeat interval in seconds.
    /// - `u64` - Reserved flags (`0`).
    /// - `isize` - Priority order (`0`).
    /// - `unsafe extern "C" fn(*mut c_void, *mut c_void)` - Timer callback.
    /// - `*mut MainCfRunLoopTimerContext` - Context struct carrying user info pointer.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Retained `CFRunLoopTimerRef`.
    fn CFRunLoopTimerCreate(
        allocator: *const c_void,
        fire_date: f64,
        interval: f64,
        flags: u64,
        order: isize,
        callout: unsafe extern "C" fn(*mut c_void, *mut c_void),
        context: *mut MainCfRunLoopTimerContext,
    ) -> *mut c_void;
    /// Adds `timer` to `rl` in the specified run-loop `mode`.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Target `CFRunLoopRef`.
    /// - `*mut c_void` - `CFRunLoopTimerRef`.
    /// - `*const c_void` - Run-loop mode `CFStringRef`.
    fn CFRunLoopAddTimer(rl: *mut c_void, timer: *mut c_void, mode: *const c_void);
    /// Invalidates a `CFRunLoopTimerRef`, removing it from all run-loop modes.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - `CFRunLoopTimerRef` to invalidate.
    fn CFRunLoopTimerInvalidate(timer: *mut c_void);
    /// Releases a CoreFoundation object reference.
    ///
    /// # Arguments
    ///
    /// - `*const c_void` - CoreFoundation object pointer.
    fn CFRelease(cf: *const c_void);
}

/// CoreFoundation timer callback attached strictly to `NSEventTrackingRunLoopMode` so macOS window border drags repaint smoothly at native Hz while firing zero times during idle sleep.
///
/// # Arguments
///
/// - `*mut c_void` - Unused `CFRunLoopTimerRef`.
/// - `*mut c_void` - Pointer to `MainMacosLiveResizeState`.
#[cfg(target_os = "macos")]
unsafe extern "C" fn macos_live_resize_callout(_timer: *mut c_void, info: *mut c_void) {
    if info.is_null() {
        return;
    }
    // SAFETY: `info` points to the stack-pinned `MainMacosLiveResizeState` for the exact lifetime of the interactive loop.
    let resize_state: &MainMacosLiveResizeState =
        unsafe { &*info.cast::<MainMacosLiveResizeState>() };
    if resize_state
        .in_step
        .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
        .is_err()
    {
        return;
    }
    if !resize_state.app_ptr.is_null() {
        // SAFETY: `app_ptr` points to the live `App` on the main thread and `in_step` prevents re-entrancy.
        let app: &mut App = unsafe { &mut *resize_state.app_ptr };
        if app.should_pump_frames() {
            let _: Result<FrameStats, PlatformError> = app.step_frame();
        }
    }
    resize_state.in_step.store(false, Ordering::Release);
}

/// Installs a `CFRunLoopTimer` strictly on `NSEventTrackingRunLoopMode` for zero-idle-overhead macOS live window resizing.
///
/// # Arguments
///
/// - `f32` - Active display refresh rate in Hertz.
/// - `*mut MainMacosLiveResizeState` - Pinned live-resize callback state pointer.
///
/// # Returns
///
/// - `*mut c_void` - Retained `CFRunLoopTimerRef` to release via `macos_remove_tracking_resize_timer`, or null.
#[cfg(target_os = "macos")]
fn macos_install_tracking_resize_timer(
    refresh_hz: f32,
    state_ptr: *mut MainMacosLiveResizeState,
) -> *mut c_void {
    let interval: f64 =
        1.0 / f64::from(refresh_hz.clamp(MIN_REFRESH_RATE_HZ, MAIN_MAX_REFRESH_RATE_HZ));
    let mut ctx: MainCfRunLoopTimerContext = MainCfRunLoopTimerContext {
        version: 0,
        info: state_ptr.cast::<c_void>(),
        retain: null(),
        release: null(),
        copy_description: null(),
    };
    let mode_bytes: &[u8] = MACOS_EVENT_TRACKING_RUN_LOOP_MODE.as_bytes();
    // SAFETY: CoreFoundation run-loop timer APIs called on the main AppKit thread.
    unsafe {
        let fire_date: f64 = CFAbsoluteTimeGetCurrent() + interval;
        let timer: *mut c_void = CFRunLoopTimerCreate(
            null(),
            fire_date,
            interval,
            0,
            0,
            macos_live_resize_callout,
            &mut ctx,
        );
        if timer.is_null() {
            return null_mut();
        }
        let rl: *mut c_void = CFRunLoopGetCurrent();
        let mode_cf: *const c_void = CFStringCreateWithBytes(
            null(),
            mode_bytes.as_ptr(),
            mode_bytes.len() as isize,
            MACOS_CF_STRING_ENCODING_UTF8,
            0,
        );
        if !rl.is_null() && !mode_cf.is_null() {
            CFRunLoopAddTimer(rl, timer, mode_cf);
        }
        if !mode_cf.is_null() {
            CFRelease(mode_cf);
        }
        timer
    }
}

/// Invalidates and releases a macOS live-resize `CFRunLoopTimerRef` returned by `macos_install_tracking_resize_timer`.
///
/// # Arguments
///
/// - `*mut c_void` - Retained `CFRunLoopTimerRef` (no-op when null).
#[cfg(target_os = "macos")]
fn macos_remove_tracking_resize_timer(timer: *mut c_void) {
    if timer.is_null() {
        return;
    }
    // SAFETY: Valid `CFRunLoopTimerRef` owned by `run_interactive_showcase`.
    unsafe {
        CFRunLoopTimerInvalidate(timer);
        CFRelease(timer.cast_const());
    }
}

/// Runs the interactive native showcase event loop with macOS live-resize support, zero-wakeup event-driven idle sleep, and zero-allocation steady-state telemetry synchronization.
///
/// # Arguments
///
/// - `&mut App` - Live native showcase application.
/// - `&ShowcaseState` - Shared reactive showcase state.
///
/// # Returns
///
/// - `FrameStats` - Telemetry from the final rendered frame.
fn run_interactive_showcase(app: &mut App, state: &ShowcaseState) -> FrameStats {
    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
    let explicit_bridge_env: bool = env::var(ENV_AI_INSPECTOR_ADDR)
        .ok()
        .is_some_and(|text_value: String| !text_value.trim().is_empty());
    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
    let mut dev_bridge: DevAutomationBridge = {
        let bind_addr: String = env::var(ENV_AI_INSPECTOR_ADDR)
            .ok()
            .filter(|text_value: &String| !text_value.trim().is_empty())
            .unwrap_or_else(|| DEV_AI_INSPECTOR_ADDR.to_string());
        DevAutomationBridge::start(&bind_addr).with_hooks(state.build_ai_hooks())
    };
    #[cfg(target_os = "macos")]
    let mut live_resize_state: MainMacosLiveResizeState = MainMacosLiveResizeState {
        app_ptr: app as *mut App,
        in_step: AtomicBool::new(false),
    };
    #[cfg(target_os = "macos")]
    let live_resize_timer: *mut c_void = if app.platform_kind() == PlatformKind::MacOs {
        macos_install_tracking_resize_timer(app.display_refresh_rate_hz(), &mut live_resize_state)
    } else {
        null_mut()
    };
    let mut last_stats: FrameStats = FrameStats::default();
    let mut last_sync_key: Option<ShowcaseAdaptiveSyncKey> = None;
    let mut active_game_bounds: Vec<Rect> = Vec::new();
    let mut prev_tick: Instant = Instant::now();
    let mut next_deadline: Instant = prev_tick;
    let mut rendered_initial_frame: bool = false;
    while app.get_running() {
        let async_loaded: bool = state.poll_async_loads();
        let has_game: bool = showcase_has_active_game_viewport(app, state, &mut active_game_bounds);
        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
        let bridge_requires_poll: bool = explicit_bridge_env;
        #[cfg(not(all(debug_assertions, not(target_arch = "wasm32"))))]
        let bridge_requires_poll: bool = false;
        let idle_sleep: bool = !app.should_pump_frames()
            || (rendered_initial_frame
                && app.is_idle()
                && !app.has_active_animations()
                && !is_frame_needed()
                && !async_loaded
                && !has_game
                && !bridge_requires_poll);
        if idle_sleep {
            let wait_result: Result<FrameStats, PlatformError> = app.wait_background_events();
            match wait_result {
                Ok(stats) => {
                    let _: bool = sync_showcase_adaptive_if_changed(state, app, &mut last_sync_key);
                    last_stats = stats;
                }
                Err(err) => {
                    eprintln!("{err}");
                    break;
                }
            }
            let resume_now: Instant = Instant::now();
            prev_tick = resume_now;
            next_deadline = resume_now;
            continue;
        }
        let frame_start: Instant = Instant::now();
        let dt: f32 = frame_start
            .duration_since(prev_tick)
            .as_secs_f32()
            .clamp(1.0 / MAIN_MAX_REFRESH_RATE_HZ, 0.05);
        prev_tick = frame_start;
        #[cfg(target_os = "macos")]
        live_resize_state.in_step.store(true, Ordering::Release);
        let step_result: Result<FrameStats, PlatformError> = app.step_game_frame(dt);
        #[cfg(target_os = "macos")]
        live_resize_state.in_step.store(false, Ordering::Release);
        match step_result {
            Ok(stats) => {
                rendered_initial_frame = true;
                let _: bool = sync_showcase_adaptive_if_changed(state, app, &mut last_sync_key);
                last_stats = stats;
            }
            Err(err) => {
                eprintln!("{err}");
                break;
            }
        }
        #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
        {
            let _: usize = dev_bridge.poll(app);
        }
        let native_hz: f64 = f64::from(
            app.display_refresh_rate_hz()
                .clamp(MIN_REFRESH_RATE_HZ, MAIN_MAX_REFRESH_RATE_HZ),
        );
        let target_hz: f64 = app
            .fps_limit()
            .map(|fps: u32| f64::from(fps.max(1)))
            .unwrap_or(native_hz);
        let target: Duration = Duration::from_secs_f64(1.0 / target_hz);
        next_deadline = next_deadline.checked_add(target).unwrap_or(frame_start);
        let now: Instant = Instant::now();
        if now >= next_deadline {
            if now.duration_since(next_deadline) > target {
                next_deadline = now;
            }
        } else {
            let remaining: Duration = next_deadline.duration_since(now);
            sleep(remaining);
        }
    }
    #[cfg(target_os = "macos")]
    macos_remove_tracking_resize_timer(live_resize_timer);
    last_stats
}

/// Body of the `main` free function.
fn main() {
    let args: Vec<String> = env::args().collect();
    #[cfg(not(target_arch = "wasm32"))]
    if let Some(pos) = args.iter().position(|arg: &String| arg == FLAG_CAPTURE_DIR)
        && let Some(dir) = args.get(pos + 1)
    {
        match capture_showcase_screenshots(Path::new(dir)) {
            Ok(item_count) => println!("captured={item_count} dir={dir}"),
            Err(err) => eprintln!("{err}"),
        }
        return;
    }
    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
    if args.iter().any(|arg: &String| arg == FLAG_AI_SCHEMA) {
        if let Ok((mut app, state)) = create_showcase_app(true, RenderMode::Software) {
            drop(app.step_frame());
            let hooks: AiAppHooks = state.build_ai_hooks();
            println!(
                "{}",
                AiSchemaProtocol::snapshot_pretty_json_with_hooks(&app, Some(&hooks))
            );
        }
        return;
    }
    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
    if let Some(pos) = args.iter().position(|arg: &String| arg == FLAG_AI_QUERY)
        && let Some(query_json) = args.get(pos + 1)
    {
        if let Ok((mut app, state)) = create_showcase_app(true, RenderMode::Software) {
            drop(app.step_frame());
            let hooks: AiAppHooks = state.build_ai_hooks();
            println!(
                "{}",
                AiSchemaProtocol::handle_json_with_hooks(&mut app, query_json, Some(&hooks))
            );
        }
        return;
    }
    #[cfg(all(debug_assertions, not(target_arch = "wasm32")))]
    if let Some(pos) = args.iter().position(|arg: &String| arg == FLAG_AI_URI)
        && let Some(uri) = args.get(pos + 1)
    {
        if let Ok((mut app, state)) = create_showcase_app(true, RenderMode::Software) {
            drop(app.step_frame());
            if let Some(out) = dispatch_automation_uri(&mut app, &state, uri) {
                println!("{out}");
            }
        }
        return;
    }
    let headless: bool = args.iter().any(|arg: &String| arg == FLAG_HEADLESS);
    let interactive: bool = args.iter().any(|arg: &String| arg == FLAG_INTERACTIVE);
    let mode: RenderMode = if args.iter().any(|arg: &String| arg == FLAG_SOFTWARE) {
        RenderMode::Software
    } else if args.iter().any(|arg: &String| arg == FLAG_HARDWARE) {
        RenderMode::Hardware
    } else if args.iter().any(|arg: &String| arg == FLAG_HYBRID) {
        RenderMode::Hybrid
    } else {
        RenderMode::Auto
    };
    if headless {
        match run_headless_smoke(mode) {
            Ok(stats) => {
                print_stats(&stats);
            }
            Err(err) => {
                eprintln!("{err}");
            }
        }
    } else {
        match create_showcase_app(false, mode) {
            Ok((mut app, state)) => {
                if interactive {
                    let last_stats: FrameStats = run_interactive_showcase(&mut app, &state);
                    print_stats(&last_stats);
                } else if let Ok(stats) = app.run_frames(Some(1)) {
                    state.sync_adaptive_from_app(&mut app);
                    let snap: AdaptiveRouterSnapshot = app.adaptive_router_snapshot();
                    let metrics: AdaptiveFrameMetrics = app.adaptive_frame_metrics();
                    println!(
                        "backend={:?} adaptive_candidate={:?} cpu_mirror={} upload={:?} draw_commands={} draw_batches={} layout_nodes={} frame_hash={:#018x}",
                        stats.get_active_backend(),
                        snap.get_active_candidate(),
                        metrics.get_cpu_mirror_active(),
                        metrics.get_upload_strategy(),
                        stats.get_draw_commands(),
                        stats.get_draw_batches(),
                        stats.get_layout_nodes(),
                        stats.get_frame_hash()
                    );
                }
            }
            Err(err) => {
                eprintln!("{err}");
            }
        }
    }
}

/// Body of the `print_stats` free function.
///
/// # Arguments
///
/// - `&FrameStats` - Shared reference to a `FrameStats`.
fn print_stats(stats: &FrameStats) {
    println!(
        "backend={:?} draw_commands={} draw_batches={} layout_nodes={} frame_hash={:#018x}",
        stats.get_active_backend(),
        stats.get_draw_commands(),
        stats.get_draw_batches(),
        stats.get_layout_nodes(),
        stats.get_frame_hash()
    );
}