Skip to main content

cvkg_render_native/
lib.rs

1//! # CVKG Agentic Development Guidelines (v1.3)
2//!
3//! All AI agents contributing to this crate MUST follow ALL eight rules:
4//!
5//! ── Karpathy Guidelines (1–4) ────────────────────────────────────────────
6//! 1. THINK FIRST     — State assumptions. Surface ambiguity. Push back on complexity.
7//! 2. STAY SIMPLE     — Minimum code. No speculative features. No unasked-for abstractions.
8//! 3. BE SURGICAL     — Touch only what's required. Own your orphans. Don't improve neighbors.
9//! 4. VERIFY GOALS    — Turn tasks into checkable criteria. Loop until they pass. Never commit broken.
10//!
11//! ── CVKG Extended Protocols (5–8) ────────────────────────────────────────
12//! 5. TRIPLE-PASS     — Read the target, its surrounding context, and its full call graph
13//!                      at least THREE TIMES before making any edit or revision.
14//! 6. COMMENT ALL     — Every major pub fn, unsafe block, and non-trivial algorithm in
15//!                      every .rs/.ts/.h/.wgsl file MUST have a descriptive doc comment.
16//!                      Comments describe WHY and WHAT CONTRACT, not HOW mechanically.
17//! 7. MONITOR LOOPS   — Check every tool call / command for progress every 30 seconds.
18//!                      After 3 consecutive identical failures, stop, write BLOCKED.md,
19//!                      and move to unblocked work. Never silently accept a broken state.
20//! 8. HARDWARE VERIFIED — NEVER declare success based on mock data/rendering for native crates.
21//!                      Any change to input, rendering, or lifecycle MUST be verified via physical
22//!                      loopback (e.g., cargo run -p berserker) and signal path tracing.
23//!
24//! Sources:
25//! Karpathy: https://github.com/multica-ai/andrej-karpathy-skills
26//! CVKG Extended: Section 14 of the CVKG Design Specification (v1.3)
27#![allow(
28    unused_imports,
29    clippy::single_component_path_imports,
30    dead_code,
31    clippy::items_after_test_module,
32    clippy::field_reassign_with_default,
33    clippy::collapsible_if,
34    clippy::unnecessary_map_or
35)]
36
37//! Platform-native widget delegation using winit and AccessKit
38//!
39//! This crate provides platform-specific rendering backends for native desktop targets
40//  using winit for window/event handling and AccessKit for accessibility tree integration.
41
42use cvkg_core::{FrameRenderer, Renderer};
43use image;
44// FIX #10: Wayland import gated to Linux only — was unconditional, broke macOS/Windows builds.
45use std::sync::Arc;
46use winit::{
47    application::ApplicationHandler,
48    event::{DeviceEvent, DeviceId, WindowEvent},
49    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
50    window::{Window, WindowId},
51};
52
53/// Represents the current state of a window.
54///
55/// Used by [`WindowStateDetector`] to track lifecycle transitions and drive
56/// rendering decisions (e.g., skip frames when occluded or minimized).
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum WindowState {
59    /// Window is visible and active.
60    Normal,
61    /// Window is minimized to the Dock or taskbar.
62    Minimized,
63    /// Window is in fullscreen mode.
64    Fullscreen,
65    /// Window is in Split View (side-by-side with another window).
66    SplitView,
67    /// Window is occluded by another window.
68    Occluded,
69    /// Window is hidden (ordered out).
70    Hidden,
71}
72
73/// Tracks the current [`WindowState`] based on incoming winit [`WindowEvent`]s.
74///
75/// The detector maps raw winit events to high-level window states and exposes
76/// helpers for render-loop decisions ([`should_render`], [`control_flow`]).
77///
78/// # Usage
79///
80/// ```no_run
81/// use cvkg_render_native::{WindowStateDetector, WindowState};
82/// let mut detector = WindowStateDetector::new();
83/// // In your event loop:
84/// // if let Some(new_state) = detector.update_from_event(&event) { ... }
85/// ```
86pub struct WindowStateDetector {
87    state: WindowState,
88    is_key: bool,
89    is_main: bool,
90}
91
92impl WindowStateDetector {
93    /// Creates a new detector initialized to [`WindowState::Normal`].
94    pub fn new() -> Self {
95        Self {
96            state: WindowState::Normal,
97            is_key: false,
98            is_main: false,
99        }
100    }
101
102    /// Returns the current window state.
103    pub fn state(&self) -> WindowState {
104        self.state
105    }
106
107    /// Returns whether the window is the key (first responder) window.
108    pub fn is_key(&self) -> bool {
109        self.is_key
110    }
111
112    /// Returns whether the window is the main window.
113    pub fn is_main(&self) -> bool {
114        self.is_main
115    }
116
117    /// Updates the internal state based on a winit [`WindowEvent`].
118    ///
119    /// Returns `Some(WindowState)` if the state changed, `None` otherwise.
120    ///
121    /// # State mapping
122    ///
123    /// | winit event | resulting state |
124    /// |---|---|
125    /// | `Occluded(true)` | `Occluded` |
126    /// | `Focused(true)` | updates `is_key`; checks fullscreen |
127    /// | `Focused(false)` | updates `is_key` |
128    /// | Default | `Normal` |
129    ///
130    /// Note: `Minimized` and `Fullscreen` detection requires querying the
131    /// winit `Window` directly (see [`update_from_window`]).
132    pub fn update_from_event(&mut self, event: &WindowEvent) -> Option<WindowState> {
133        let old_state = self.state;
134        match event {
135            WindowEvent::Occluded(true) => {
136                self.state = WindowState::Occluded;
137            }
138            WindowEvent::Focused(focused) => {
139                self.is_key = *focused;
140                if !focused && self.state != WindowState::Minimized {
141                    self.state = WindowState::Normal;
142                }
143            }
144            _ => {}
145        };
146        if self.state != old_state {
147            Some(self.state)
148        } else {
149            None
150        }
151    }
152
153    /// Updates the state by querying the winit `Window` directly.
154    ///
155    /// This should be called once per frame to detect states that winit
156    /// does not emit as events (minimized, fullscreen).
157    ///
158    /// Returns `Some(WindowState)` if the state changed, `None` otherwise.
159    pub fn update_from_window(&mut self, window: &winit::window::Window) -> Option<WindowState> {
160        let old_state = self.state;
161        if window.is_minimized().unwrap_or(false) {
162            self.state = WindowState::Minimized;
163        } else if window.fullscreen().is_some() {
164            self.state = WindowState::Fullscreen;
165        } else if self.state == WindowState::Minimized || self.state == WindowState::Fullscreen {
166            // Transition back to Normal when no longer minimized/fullscreen
167            self.state = WindowState::Normal;
168        }
169        if self.state != old_state {
170            Some(self.state)
171        } else {
172            None
173        }
174    }
175
176    /// Returns `true` if the window should render a frame in the current state.
177    ///
178    /// Returns `false` for [`WindowState::Occluded`], [`WindowState::Minimized`],
179    /// and [`WindowState::Hidden`].
180    pub fn should_render(&self) -> bool {
181        !matches!(
182            self.state,
183            WindowState::Occluded | WindowState::Minimized | WindowState::Hidden
184        )
185    }
186
187    /// Returns the appropriate [`ControlFlow`] for the current state.
188    ///
189    /// Non-rendering states get `ControlFlow::Wait` (save CPU cycles);
190    /// rendering states get `ControlFlow::Poll` for maximum responsiveness.
191    pub fn control_flow(&self) -> ControlFlow {
192        if self.should_render() {
193            ControlFlow::Poll
194        } else {
195            ControlFlow::Wait
196        }
197    }
198}
199
200impl Default for WindowStateDetector {
201    fn default() -> Self {
202        Self::new()
203    }
204}
205
206/// Hit-test helper for resize handles on windows with rounded corners.
207///
208/// macOS Tahoe uses a 26pt corner radius, which means the visual corner arc
209/// does not cover the full 19×19 resize hotspot. This struct expands the
210/// clickable area 8px beyond the visual corner edge so users can still grab
211/// the resize handle reliably.
212pub struct ResizeHitTest {
213    /// The size of the window in physical pixels.
214    window_size: winit::dpi::PhysicalSize<u32>,
215    /// The corner radius in points (logical pixels).
216    corner_radius: f32,
217    /// Extra expansion in pixels beyond the visual corner edge.
218    expansion: f32,
219}
220
221impl ResizeHitTest {
222    /// Creates a new hit-test helper.
223    ///
224    /// # Arguments
225    ///
226    /// * `window_size` — the current window size in physical pixels.
227    /// * `corner_radius` — the corner radius in points (e.g., 26.0 for Tahoe).
228    /// * `expansion` — extra pixels to expand beyond the visual edge (e.g., 8.0).
229    pub fn new(
230        window_size: winit::dpi::PhysicalSize<u32>,
231        corner_radius: f32,
232        expansion: f32,
233    ) -> Self {
234        Self {
235            window_size,
236            corner_radius,
237            expansion,
238        }
239    }
240
241    /// Tests whether `pos` (a point relative to the window's top-left corner)
242    /// falls within the expanded resize-hit region for any corner.
243    ///
244    /// The hit region for each corner is a square of side `corner_radius + expansion`,
245    /// anchored at the corner. A point is considered a hit if it falls within
246    /// any of the four corner squares.
247    pub fn hit_test(&self, pos: winit::dpi::PhysicalSize<u32>, corner_radius: f32) -> bool {
248        let r = corner_radius + self.expansion;
249        let w = self.window_size.width as f32;
250        let h = self.window_size.height as f32;
251        let px = pos.width as f32;
252        let py = pos.height as f32;
253
254        // Top-left corner: square [0, r) x [0, r)
255        if px <= r && py <= r {
256            return true;
257        }
258
259        // Top-right corner: square [w-r, w) x [0, r)
260        if px >= w - r && py <= r {
261            return true;
262        }
263
264        // Bottom-left corner: square [0, r) x [h-r, h)
265        if px <= r && py >= h - r {
266            return true;
267        }
268
269        // Bottom-right corner: square [w-r, w) x [h-r, h)
270        if px >= w - r && py >= h - r {
271            return true;
272        }
273
274        false
275    }
276}
277
278/// Platform safe area insets (menu bar, notch, etc.).
279///
280/// Values are in logical points.
281#[derive(Debug, Clone, Copy, PartialEq)]
282pub struct SafeAreaInsets {
283    /// Top inset (e.g., menu bar on macOS).
284    pub top: f32,
285    /// Bottom inset (e.g., Dock when at bottom).
286    pub bottom: f32,
287    /// Left inset.
288    pub left: f32,
289    /// Right inset.
290    pub right: f32,
291}
292
293impl SafeAreaInsets {
294    /// Returns zero insets on all sides.
295    pub fn zero() -> Self {
296        Self {
297            top: 0.0,
298            bottom: 0.0,
299            left: 0.0,
300            right: 0.0,
301        }
302    }
303
304    /// Returns appropriate safe-area insets for a given [`WindowState`].
305    ///
306    /// # Platform behavior
307    ///
308    /// * **Fullscreen** — zero insets (window owns the entire screen).
309    /// * **Normal** — 24pt top on macOS for the menu bar, 0 on other platforms.
310    /// * **All other states** — same as Normal.
311    pub fn for_window_state(state: WindowState) -> Self {
312        if state == WindowState::Fullscreen {
313            return Self::zero();
314        }
315        #[cfg(target_os = "macos")]
316        let top = 24.0;
317        #[cfg(not(target_os = "macos"))]
318        let top = 0.0;
319        Self {
320            top,
321            bottom: 0.0,
322            left: 0.0,
323            right: 0.0,
324        }
325    }
326}
327
328/// Native renderer backend implementing the Renderer trait.
329/// It wraps a shared SurtrRenderer for high-performance GPU drawing.
330pub struct NativeRenderer {
331    gpu: Arc<std::sync::Mutex<cvkg_render_gpu::SurtrRenderer>>,
332    delta_time: f32,
333    elapsed_time: f32,
334    berserker_mode: cvkg_core::BerserkerMode,
335    rage: f32,
336    window: Arc<Window>,
337}
338
339/// Custom events for the native application event loop, handling accessibility
340/// callbacks and routing window lifecycle control events from background threads.
341#[derive(Debug)]
342pub enum AppEvent {
343    /// Action request from the accessibility subsystem.
344    AccessibilityAction(accesskit::ActionRequest),
345    /// Request to close a specific window.
346    CloseWindow(winit::window::WindowId),
347    /// Request to set the title bar string of a window.
348    SetTitle(winit::window::WindowId, String),
349    /// Request to resize a window.
350    SetSize(winit::window::WindowId, f32, f32),
351    /// Request to change visibility of a window.
352    SetVisible(winit::window::WindowId, bool),
353    /// Request to bring a window to the front and focus it.
354    BringToFront(winit::window::WindowId),
355}
356
357impl NativeRenderer {
358    /// Create a new NativeRenderer (internal use by App)
359    fn new(
360        window: Arc<Window>,
361        gpu: Arc<std::sync::Mutex<cvkg_render_gpu::SurtrRenderer>>,
362        delta_time: f32,
363        elapsed_time: f32,
364        berserker_mode: cvkg_core::BerserkerMode,
365        rage: f32,
366    ) -> Self {
367        Self {
368            gpu,
369            delta_time,
370            elapsed_time,
371            berserker_mode,
372            rage,
373            window,
374        }
375    }
376
377    /// Start the CVKG native application with the given view.
378    /// This is the main entry point for desktop applications.
379    pub fn run<V: cvkg_core::View + 'static>(view: V) {
380        let event_loop = EventLoop::<AppEvent>::with_user_event()
381            .build()
382            .expect("Failed to create event loop");
383        event_loop.set_control_flow(ControlFlow::Wait);
384
385        let mut app = App {
386            view,
387            window_manager: WindowManager::new(),
388            gpu: None,
389            asset_manager: std::sync::Arc::new(NativeAssetManager::new()),
390            proxy: event_loop.create_proxy(),
391            start_time: std::time::Instant::now(),
392            last_frame_time: std::time::Instant::now(),
393            berserker_mode: cvkg_core::BerserkerMode::Normal,
394            rage: 0.0,
395            state_detector: WindowStateDetector::new(),
396            modifiers: winit::keyboard::ModifiersState::default(),
397            audio_engine: None,
398            haptic_engine: Arc::new(VisualHapticEngine::new()),
399        };
400
401        event_loop.run_app(&mut app).expect("Event loop error");
402    }
403}
404
405/// Native implementation of the cvkg_core::Window trait.
406/// Communicates state updates back to the winit event loop thread using an EventLoopProxy.
407struct NativeWindowWrapper {
408    winit_id: winit::window::WindowId,
409    window: Arc<winit::window::Window>,
410    proxy: winit::event_loop::EventLoopProxy<AppEvent>,
411    is_key: Arc<std::sync::atomic::AtomicBool>,
412    is_main: bool,
413}
414
415impl cvkg_core::Window for NativeWindowWrapper {
416    /// Request that this window be closed.
417    fn close(&self) {
418        let _ = self.proxy.send_event(AppEvent::CloseWindow(self.winit_id));
419    }
420
421    /// Change the title bar text of this window.
422    fn set_title(&self, title: &str) {
423        let _ = self
424            .proxy
425            .send_event(AppEvent::SetTitle(self.winit_id, title.to_string()));
426    }
427
428    /// Request updating this window's dimensions.
429    fn set_size(&self, width: f32, height: f32) {
430        let _ = self
431            .proxy
432            .send_event(AppEvent::SetSize(self.winit_id, width, height));
433    }
434
435    /// Return true if this window has key focus.
436    fn is_key(&self) -> bool {
437        self.is_key.load(std::sync::atomic::Ordering::SeqCst)
438    }
439
440    /// Return true if this is the primary application window.
441    fn is_main(&self) -> bool {
442        self.is_main
443    }
444
445    /// Return true if this window is visible.
446    fn is_visible(&self) -> bool {
447        self.window.is_visible().unwrap_or(false)
448    }
449
450    /// Show or hide this window.
451    fn set_visible(&self, visible: bool) {
452        let _ = self
453            .proxy
454            .send_event(AppEvent::SetVisible(self.winit_id, visible));
455    }
456
457    /// Focus and bring this window to the foreground.
458    fn bring_to_front(&self) {
459        let _ = self.proxy.send_event(AppEvent::BringToFront(self.winit_id));
460    }
461}
462
463/// Dynamic manager for all active native windows and their rendering contexts.
464pub struct WindowManager {
465    /// Mapping from native winit WindowId to internal WindowData.
466    pub windows: std::collections::HashMap<winit::window::WindowId, WindowData>,
467    /// Stack of windows ordered from back to front (end of vector is top-most).
468    pub window_stack: Vec<winit::window::WindowId>,
469    /// Mapping of winit window IDs to core IDs.
470    pub winit_to_core: std::collections::HashMap<winit::window::WindowId, cvkg_core::WindowId>,
471    /// Mapping of core window IDs to winit IDs.
472    pub core_to_winit: std::collections::HashMap<cvkg_core::WindowId, winit::window::WindowId>,
473    /// Monotonic counter to allocate unique core window IDs.
474    pub next_core_id: u64,
475}
476
477impl Default for WindowManager {
478    fn default() -> Self {
479        Self::new()
480    }
481}
482
483impl WindowManager {
484    /// Create an empty WindowManager.
485    pub fn new() -> Self {
486        Self {
487            windows: std::collections::HashMap::new(),
488            window_stack: Vec::new(),
489            winit_to_core: std::collections::HashMap::new(),
490            core_to_winit: std::collections::HashMap::new(),
491            next_core_id: 1,
492        }
493    }
494
495    /// Create and register a new native window.
496    pub fn create_window(
497        &mut self,
498        event_loop: &ActiveEventLoop,
499        gpu: &Option<Arc<std::sync::Mutex<cvkg_render_gpu::SurtrRenderer>>>,
500        proxy: winit::event_loop::EventLoopProxy<AppEvent>,
501        config: cvkg_core::WindowConfig,
502        is_main: bool,
503        view: &impl cvkg_core::View,
504    ) -> cvkg_core::WindowHandle {
505        let mut window_attrs = Window::default_attributes()
506            .with_title(&config.title)
507            .with_visible(true)
508            .with_transparent(config.transparent)
509            .with_decorations(config.decorations)
510            .with_inner_size(winit::dpi::LogicalSize::new(config.size.0, config.size.1));
511
512        if let Some(min) = config.min_size {
513            window_attrs =
514                window_attrs.with_min_inner_size(winit::dpi::LogicalSize::new(min.0, min.1));
515        }
516        if let Some(max) = config.max_size {
517            window_attrs =
518                window_attrs.with_max_inner_size(winit::dpi::LogicalSize::new(max.0, max.1));
519        }
520
521        let winit_level = match config.level {
522            cvkg_core::WindowLevel::Normal => winit::window::WindowLevel::Normal,
523            cvkg_core::WindowLevel::AlwaysOnTop => winit::window::WindowLevel::AlwaysOnTop,
524            cvkg_core::WindowLevel::PopUpMenu => winit::window::WindowLevel::AlwaysOnTop,
525        };
526        window_attrs = window_attrs.with_window_level(winit_level);
527
528        let window = Arc::new(
529            event_loop
530                .create_window(window_attrs)
531                .expect("Failed to create window"),
532        );
533
534        let winit_id = window.id();
535        let core_id = cvkg_core::WindowId(self.next_core_id);
536        self.next_core_id += 1;
537
538        let is_key_focused = Arc::new(std::sync::atomic::AtomicBool::new(true));
539
540        let wrapper = Arc::new(NativeWindowWrapper {
541            winit_id,
542            window: window.clone(),
543            proxy: proxy.clone(),
544            is_key: is_key_focused.clone(),
545            is_main,
546        });
547
548        let handle = cvkg_core::WindowHandle::new(core_id, wrapper);
549
550        let vdom = cvkg_vdom::VDom::build(
551            view,
552            cvkg_core::Rect::new(0.0, 0.0, config.size.0, config.size.1),
553        );
554
555        let data = WindowData {
556            window: window.clone(),
557            accesskit_adapter: None,
558            vdom: Some(vdom),
559            cursor_pos: [0.0, 0.0],
560            last_redraw_start: std::time::Instant::now(),
561            frame_history: std::collections::VecDeque::with_capacity(60),
562            frame_count: 0,
563            last_pos: None,
564            is_dragging: false,
565            drag_start_pos: [0.0, 0.0],
566            drag_button: 0,
567            drag_threshold: 5.0,
568            is_key_focused,
569            is_main,
570            core_id,
571            window_handle: handle.clone(),
572        };
573
574        self.windows.insert(winit_id, data);
575        self.window_stack.push(winit_id);
576        self.winit_to_core.insert(winit_id, core_id);
577        self.core_to_winit.insert(core_id, winit_id);
578
579        if let Some(gpu_mutex) = gpu {
580            gpu_mutex.lock().unwrap().register_window(window.clone());
581        }
582
583        handle
584    }
585
586    /// Close and unregister a native window.
587    pub fn close_window(&mut self, winit_id: winit::window::WindowId) {
588        self.windows.remove(&winit_id);
589        self.window_stack.retain(|id| *id != winit_id);
590        if let Some(core_id) = self.winit_to_core.remove(&winit_id) {
591            self.core_to_winit.remove(&core_id);
592        }
593    }
594
595    /// Bring a native window to the foreground and focus it.
596    pub fn bring_to_front(&mut self, winit_id: winit::window::WindowId) {
597        self.window_stack.retain(|id| *id != winit_id);
598        self.window_stack.push(winit_id);
599        if let Some(data) = self.windows.get(&winit_id) {
600            data.window.focus_window();
601        }
602    }
603
604    /// Get a reference to a window's data.
605    pub fn window(&self, winit_id: winit::window::WindowId) -> Option<&WindowData> {
606        self.windows.get(&winit_id)
607    }
608
609    /// Get a mutable reference to a window's data.
610    pub fn window_mut(&mut self, winit_id: winit::window::WindowId) -> Option<&mut WindowData> {
611        self.windows.get_mut(&winit_id)
612    }
613
614    /// Return the list of window IDs in current Z-order stack.
615    pub fn window_order(&self) -> &[winit::window::WindowId] {
616        &self.window_stack
617    }
618}
619
620pub struct WindowData {
621    window: Arc<Window>,
622    accesskit_adapter: Option<accesskit_winit::Adapter>,
623    vdom: Option<cvkg_vdom::VDom>,
624    cursor_pos: [f32; 2],
625    /// The instant the last redraw finished, used for measuring inter-frame gap timing.
626    last_redraw_start: std::time::Instant,
627    /// Sliding window of frame times for tail latency (P99) calculation.
628    frame_history: std::collections::VecDeque<f32>,
629    /// Total frames rendered on this window.
630    frame_count: u64,
631    /// Last window position for shake detection.
632    last_pos: Option<[i32; 2]>,
633    // ── Drag tracking ──────────────────────────────────────────────────────
634    /// Whether a drag is currently in progress.
635    is_dragging: bool,
636    /// The position where the drag started.
637    drag_start_pos: [f32; 2],
638    /// The button that initiated the drag.
639    drag_button: u32,
640    /// Drag threshold in logical pixels (pointer must move this far to start drag).
641    drag_threshold: f32,
642
643    // ── Multi-window tracking ──────────────────────────────────────────────
644    is_key_focused: Arc<std::sync::atomic::AtomicBool>,
645    is_main: bool,
646    core_id: cvkg_core::WindowId,
647    window_handle: cvkg_core::WindowHandle,
648}
649
650struct App<V: cvkg_core::View> {
651    view: V,
652    window_manager: WindowManager,
653    gpu: Option<Arc<std::sync::Mutex<cvkg_render_gpu::SurtrRenderer>>>,
654    #[allow(dead_code)]
655    asset_manager: std::sync::Arc<NativeAssetManager>,
656    proxy: winit::event_loop::EventLoopProxy<AppEvent>,
657    start_time: std::time::Instant,
658    last_frame_time: std::time::Instant,
659    berserker_mode: cvkg_core::BerserkerMode,
660    rage: f32,
661    /// Tracks the current window state for render-loop decisions.
662    state_detector: WindowStateDetector,
663    /// Tracks active modifier key states (Ctrl, Shift, Command, etc.).
664    modifiers: winit::keyboard::ModifiersState,
665    /// Cross-platform audio engine for spatialized sound cues.
666    audio_engine: Option<Arc<dyn cvkg_core::AudioEngine>>,
667    /// Visual haptic engine for micro-feedback animations.
668    haptic_engine: Arc<dyn cvkg_core::HapticEngine>,
669}
670
671impl<V: cvkg_core::View + 'static> ApplicationHandler<AppEvent> for App<V> {
672    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
673        if self.gpu.is_none() {
674            // Detect and apply system accessibility preferences at startup
675            let a11y_prefs = cvkg_core::AccessibilityPreferences::detect_from_system();
676            cvkg_core::set_accessibility_preferences(a11y_prefs);
677            if a11y_prefs.reduce_motion
678                || a11y_prefs.reduce_transparency
679                || a11y_prefs.increase_contrast
680            {
681                log::info!(
682                    "[Native] Accessibility prefs: motion={} transparency={} contrast={}",
683                    a11y_prefs.reduce_motion,
684                    a11y_prefs.reduce_transparency,
685                    a11y_prefs.increase_contrast
686                );
687            }
688
689            // Detect and apply system theme (dark/light)
690            let system_theme = cvkg_core::detect_system_theme();
691            log::info!("[Native] System theme detected: {:?}", system_theme);
692
693            // Initialize cross-platform audio engine
694            self.audio_engine =
695                RodioAudioEngine::new().map(|e| Arc::new(e) as Arc<dyn cvkg_core::AudioEngine>);
696
697            // Initialize visual haptic engine for micro-feedback
698            self.haptic_engine = Arc::new(VisualHapticEngine::new());
699
700            log::info!("[Native] App instance (resumed): {:p}", self);
701
702            let config = cvkg_core::WindowConfig {
703                title: "CVKG Berserker".to_string(),
704                size: (1280.0, 720.0),
705                min_size: None,
706                max_size: None,
707                resizable: true,
708                transparent: false,
709                decorations: true,
710                level: cvkg_core::WindowLevel::Normal,
711            };
712
713            let handle = self.window_manager.create_window(
714                event_loop,
715                &self.gpu,
716                self.proxy.clone(),
717                config,
718                true, // is_main
719                &self.view,
720            );
721
722            let winit_id = self
723                .window_manager
724                .core_to_winit
725                .get(&handle.id)
726                .copied()
727                .expect("Failed to get winit_id");
728            let window = self
729                .window_manager
730                .windows
731                .get(&winit_id)
732                .unwrap()
733                .window
734                .clone();
735
736            // Immediately set self.gpu to prevent re-entry
737            let gpu = pollster::block_on(cvkg_render_gpu::SurtrRenderer::forge(window.clone()));
738            self.gpu = Some(Arc::new(std::sync::Mutex::new(gpu)));
739
740            // Register the window surface with the newly forged GPU renderer
741            if let Some(gpu_mutex) = &self.gpu {
742                gpu_mutex
743                    .lock()
744                    .expect("Failed to lock GPU mutex")
745                    .register_window(window.clone());
746            }
747
748            log::info!("[Native] Initialization complete.");
749            window.request_redraw();
750        }
751    }
752
753    fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
754        if matches!(cause, winit::event::StartCause::Poll) {
755            // Too noisy
756        } else {
757            log::debug!("[Native] Event Loop Wake: {:?}", cause);
758        }
759    }
760
761    fn device_event(
762        &mut self,
763        _event_loop: &ActiveEventLoop,
764        _device_id: winit::event::DeviceId,
765        event: winit::event::DeviceEvent,
766    ) {
767        if matches!(event, winit::event::DeviceEvent::MouseMotion { .. }) {
768            // log::trace!("[Native] Raw Mouse Motion");
769        } else {
770            log::info!("[Native] DEVICE EVENT: {:?}", event);
771        }
772    }
773
774    fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
775        if !matches!(event, WindowEvent::RedrawRequested)
776            && !matches!(event, WindowEvent::CursorMoved { .. })
777        {
778            log::info!(
779                "[Native] App instance: {:p} | WINDOW EVENT: {:?}",
780                self,
781                event
782            );
783        }
784
785        let gpu_arc = if let Some(g) = &self.gpu {
786            g.clone()
787        } else {
788            log::warn!("[Native] DROPPING EVENT: GPU not initialized yet");
789            return;
790        };
791
792        let mut close_window = false;
793        let mut bring_to_front = false;
794        let mut create_new_window = false;
795        // Cmd+Q was pressed — close all windows after the state block ends.
796        let mut quit_all = false;
797
798        {
799            let state = if let Some(s) = self.window_manager.windows.get_mut(&id) {
800                s
801            } else {
802                return;
803            };
804
805            match event {
806                WindowEvent::Moved(pos) => {
807                    let dx = state.last_pos.map_or(0, |last| pos.x - last[0]);
808                    let dy = state.last_pos.map_or(0, |last| pos.y - last[1]);
809                    let speed = ((dx.pow(2) + dy.pow(2)) as f32).sqrt();
810
811                    if speed > 0.1 {
812                        // Significant kinetic injection
813                        self.rage = (self.rage + 0.2).min(1.0);
814                        log::info!("[Native] Kinetic Injection! Rage: {}", self.rage);
815                    }
816
817                    state.last_pos = Some([pos.x, pos.y]);
818                    state.window.request_redraw();
819                }
820                WindowEvent::DroppedFile(path) => {
821                    if let Some(vdom) = &state.vdom {
822                        vdom.dispatch_event(cvkg_core::Event::FileDrop {
823                            path: path.to_string_lossy().into_owned(),
824                        });
825                    }
826                }
827                WindowEvent::CloseRequested => {
828                    let close_action = cvkg_core::WindowCloseAction::Allow;
829                    match close_action {
830                        cvkg_core::WindowCloseAction::Allow
831                        | cvkg_core::WindowCloseAction::Confirm => {
832                            close_window = true;
833                        }
834                        cvkg_core::WindowCloseAction::Deny => {
835                            log::info!("[Native] Close request denied for window {:?}", id);
836                        }
837                    }
838                }
839                WindowEvent::Resized(physical_size) => {
840                    gpu_arc
841                        .lock()
842                        .expect("GPU mutex poisoned during resize")
843                        .resize(
844                            id,
845                            physical_size.width,
846                            physical_size.height,
847                            state.window.scale_factor() as f32,
848                        );
849                    state.window.request_redraw();
850                }
851                WindowEvent::Focused(focused) => {
852                    log::info!("[Native] Window focus changed: {}", focused);
853                    state
854                        .is_key_focused
855                        .store(focused, std::sync::atomic::Ordering::SeqCst);
856                    if focused {
857                        bring_to_front = true;
858                    }
859                }
860                WindowEvent::RedrawRequested => {
861                    if state.frame_count % 60 == 0 {
862                        log::info!("[Native] RedrawRequested (frame {})", state.frame_count);
863                    }
864                    let size = state.window.inner_size();
865                    let scale = state.window.scale_factor();
866                    let logical_size = size.to_logical::<f32>(scale);
867
868                    let rect = cvkg_core::Rect {
869                        x: 0.0,
870                        y: 0.0,
871                        width: logical_size.width,
872                        height: logical_size.height,
873                    };
874
875                    // Record the start of this redraw and snapshot the previous frame's
876                    // start time before overwriting it, so inter-frame gap is measurable.
877                    let redraw_start = std::time::Instant::now();
878                    let last_redraw_start = state.last_redraw_start;
879                    // Update last_redraw_start immediately so the next frame measures correctly
880                    // even if this frame returns early.
881                    state.last_redraw_start = redraw_start;
882
883                    // Build new vdom and diff (layout pass)
884                    let layout_start = std::time::Instant::now();
885                    let new_vdom = cvkg_vdom::VDom::build(&self.view, rect);
886                    let layout_end = std::time::Instant::now();
887
888                    // Apply patches to the accessibility tree and the previous VDOM
889                    let state_flush_start = std::time::Instant::now();
890                    if let Some(prev_vdom) = &mut state.vdom {
891                        let patches = prev_vdom.diff(&new_vdom);
892                        let mut nodes = Vec::new();
893                        for patch in &patches {
894                            if let cvkg_vdom::VDomPatch::Create(node)
895                            | cvkg_vdom::VDomPatch::Replace { node, .. } = patch
896                            {
897                                nodes
898                                    .push((accesskit::NodeId(node.id.0), node.to_accesskit_node()));
899                            } else if let cvkg_vdom::VDomPatch::Update { id, .. } = patch
900                                && let Some(node) = new_vdom.nodes.get(id)
901                            {
902                                nodes
903                                    .push((accesskit::NodeId(node.id.0), node.to_accesskit_node()));
904                            }
905                        }
906                        if !nodes.is_empty() {
907                            if let Some(adapter) = &mut state.accesskit_adapter {
908                                adapter.update_if_active(|| accesskit::TreeUpdate {
909                                    nodes,
910                                    tree: None,
911                                    focus: accesskit::NodeId(1),
912                                });
913                            }
914                        }
915                        prev_vdom.apply_patches(patches);
916                    } else {
917                        state.vdom = Some(new_vdom);
918                    }
919                    let state_flush_end = std::time::Instant::now();
920
921                    // GPU rendering
922                    let draw_start = std::time::Instant::now();
923                    let delta_time = redraw_start.duration_since(last_redraw_start).as_secs_f32();
924                    let elapsed_time = redraw_start.duration_since(self.start_time).as_secs_f32();
925                    let mut gpu = gpu_arc
926                        .lock()
927                        .expect("GPU mutex poisoned during frame begin");
928                    let encoder = gpu.begin_frame(id);
929                    let mut renderer = NativeRenderer::new(
930                        state.window.clone(),
931                        gpu_arc.clone(),
932                        delta_time,
933                        elapsed_time,
934                        self.berserker_mode,
935                        self.rage,
936                    );
937                    // Release the gpu lock before calling render — the render methods each
938                    // re-acquire it per-call, allowing the view tree to interleave with other
939                    // work without holding one giant critical section across the whole draw.
940                    drop(gpu);
941                    self.view.render(&mut renderer, rect);
942                    let draw_end = std::time::Instant::now();
943
944                    // Re-acquire to submit the frame
945                    let gpu_submit_start = std::time::Instant::now();
946                    let mut gpu = gpu_arc
947                        .lock()
948                        .expect("GPU mutex poisoned during frame submit");
949                    gpu.render_frame();
950                    gpu.end_frame(encoder);
951                    let gpu_submit_end = std::time::Instant::now();
952
953                    // Build telemetry from this frame's timing measurements.
954                    // NOTE: input_time_ms measures the inter-frame gap (time from end of last frame
955                    // to start of this one), not input dispatch latency. The field name is defined
956                    // in cvkg_core::TelemetryData and kept as-is to match that struct.
957                    let mut telemetry = cvkg_core::TelemetryData::default();
958                    telemetry.input_time_ms =
959                        redraw_start.duration_since(last_redraw_start).as_secs_f32() * 1000.0;
960                    telemetry.layout_time_ms =
961                        layout_end.duration_since(layout_start).as_secs_f32() * 1000.0;
962                    telemetry.state_flush_time_ms = state_flush_end
963                        .duration_since(state_flush_start)
964                        .as_secs_f32()
965                        * 1000.0;
966                    telemetry.draw_time_ms =
967                        draw_end.duration_since(draw_start).as_secs_f32() * 1000.0;
968                    telemetry.gpu_submit_time_ms = gpu_submit_end
969                        .duration_since(gpu_submit_start)
970                        .as_secs_f32()
971                        * 1000.0;
972
973                    // Total frame time from redraw request to GPU submission complete
974                    let frame_time_ms =
975                        gpu_submit_end.duration_since(redraw_start).as_secs_f32() * 1000.0;
976                    telemetry.frame_time_ms = frame_time_ms;
977
978                    // Tail Latency Tracking (P99 and Jitter) over a 100-frame sliding window.
979                    state.frame_history.push_back(frame_time_ms);
980                    if state.frame_history.len() > 100 {
981                        state.frame_history.pop_front();
982                    }
983
984                    let mut sorted_frames: Vec<f32> = state.frame_history.iter().copied().collect();
985                    sorted_frames
986                        .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
987
988                    if !sorted_frames.is_empty() {
989                        let p99_idx = (sorted_frames.len() as f32 * 0.99).floor() as usize;
990                        telemetry.p99_frame_time_ms =
991                            sorted_frames[p99_idx.min(sorted_frames.len() - 1)];
992
993                        // Jitter: standard deviation of frame times over the sliding window.
994                        let avg = sorted_frames.iter().sum::<f32>() / sorted_frames.len() as f32;
995                        let variance = sorted_frames.iter().map(|f| (f - avg).powi(2)).sum::<f32>()
996                            / sorted_frames.len() as f32;
997                        telemetry.frame_jitter_ms = variance.sqrt();
998                    }
999
1000                    // FIX #8: hardware_stall_detected is now reset each frame based on current
1001                    // jitter rather than being set once and never cleared. A single jittery frame
1002                    // no longer permanently flags the session. Jitter > 20ms is a heuristic for
1003                    // scheduling disruption (GC, OS preemption, slow layout) — not a confirmed
1004                    // hardware stall, but the field name is defined in cvkg_core::TelemetryData.
1005                    telemetry.hardware_stall_detected = telemetry.frame_jitter_ms > 20.0;
1006
1007                    state.frame_count += 1;
1008
1009                    telemetry.berserker_rage = self.rage;
1010                    gpu.telemetry = telemetry;
1011                }
1012                WindowEvent::CursorEntered { .. } => {
1013                    log::info!("[Native] Cursor ENTERED window");
1014                    if let Some(vdom) = &state.vdom {
1015                        vdom.dispatch_event(cvkg_core::Event::PointerEnter);
1016                    }
1017                    state.window.request_redraw();
1018                }
1019                WindowEvent::CursorLeft { .. } => {
1020                    log::info!("[Native] Cursor LEFT window");
1021                    if let Some(vdom) = &state.vdom {
1022                        vdom.dispatch_event(cvkg_core::Event::PointerLeave);
1023                    }
1024                    state.window.request_redraw();
1025                }
1026                WindowEvent::CursorMoved { position, .. } => {
1027                    let scale = state.window.scale_factor();
1028                    let logical = position.to_logical::<f32>(scale);
1029                    log::info!(
1030                        "[Native] Cursor Moved: Physical={:?} Logical={:?} Scale={}",
1031                        position,
1032                        logical,
1033                        scale
1034                    );
1035                    state.cursor_pos = [logical.x, logical.y];
1036                    if let Some(vdom) = &state.vdom {
1037                        vdom.dispatch_event(cvkg_core::Event::PointerMove {
1038                            x: state.cursor_pos[0],
1039                            y: state.cursor_pos[1],
1040                            proximity_field: 0.0,
1041                        });
1042                    }
1043                    state.window.request_redraw();
1044                }
1045                WindowEvent::MouseInput {
1046                    state: mouse_state,
1047                    button,
1048                    ..
1049                } => {
1050                    log::info!(
1051                        "[Native] MOUSE INPUT: {:?} button={:?} pos={:?}",
1052                        mouse_state,
1053                        button,
1054                        state.cursor_pos
1055                    );
1056                    if let Some(vdom) = &state.vdom {
1057                        let btn_id = match button {
1058                            winit::event::MouseButton::Left => 0,
1059                            winit::event::MouseButton::Right => 2,
1060                            winit::event::MouseButton::Middle => 1,
1061                            winit::event::MouseButton::Back => 3,
1062                            winit::event::MouseButton::Forward => 4,
1063                            winit::event::MouseButton::Other(id) => id as u32,
1064                        };
1065
1066                        match mouse_state {
1067                            winit::event::ElementState::Pressed => {
1068                                log::info!("[Native] Dispatching PointerDown to VDOM");
1069                                vdom.dispatch_event(cvkg_core::Event::PointerDown {
1070                                    x: state.cursor_pos[0],
1071                                    y: state.cursor_pos[1],
1072                                    button: btn_id,
1073                                    proximity_field: 0.0,
1074                                });
1075                            }
1076                            winit::event::ElementState::Released => {
1077                                log::info!("[Native] Dispatching PointerUp to VDOM");
1078                                vdom.dispatch_event(cvkg_core::Event::PointerUp {
1079                                    x: state.cursor_pos[0],
1080                                    y: state.cursor_pos[1],
1081                                    button: btn_id,
1082                                });
1083                            }
1084                        }
1085                        state.window.request_redraw();
1086                    } else {
1087                        log::warn!("[Native] Mouse input received but state.vdom is None!");
1088                    }
1089                }
1090                WindowEvent::MouseWheel { delta, .. } => {
1091                    if let Some(vdom) = &state.vdom {
1092                        let (dx, dy) = match delta {
1093                            winit::event::MouseScrollDelta::LineDelta(x, y) => (x * 10.0, y * 10.0),
1094                            winit::event::MouseScrollDelta::PixelDelta(pos) => {
1095                                (pos.x as f32, pos.y as f32)
1096                            }
1097                        };
1098                        vdom.dispatch_event(cvkg_core::Event::PointerWheel {
1099                            x: state.cursor_pos[0],
1100                            y: state.cursor_pos[1],
1101                            delta_x: dx,
1102                            delta_y: dy,
1103                        });
1104                        state.window.request_redraw();
1105                    }
1106                }
1107                // ── Trackpad gestures (pinch-to-zoom, swipe) ──────────────────────
1108                // OS-agnostic: winit provides these on macOS trackpad, Windows precision
1109                // touchpads, and Linux (where supported). Falls back gracefully.
1110                WindowEvent::PinchGesture { delta, .. } => {
1111                    if let Some(vdom) = &state.vdom {
1112                        let scale = 1.0 + delta as f32;
1113                        let velocity = delta as f32;
1114                        vdom.dispatch_event(cvkg_core::Event::GesturePinch {
1115                            center: state.cursor_pos,
1116                            scale,
1117                            velocity,
1118                            phase: cvkg_core::TouchPhase::Moved,
1119                        });
1120                    }
1121                    // Provide micro-feedback on pinch
1122                    if let Some(audio) = &self.audio_engine {
1123                        audio.play_sound("nav_tick", 0.3);
1124                    }
1125                    self.haptic_engine
1126                        .visual_tick((delta.abs() as f32 * 5.0).min(1.0));
1127                    state.window.request_redraw();
1128                }
1129                WindowEvent::RotationGesture { delta, .. } => {
1130                    if let Some(vdom) = &state.vdom {
1131                        let angle = delta;
1132                        vdom.dispatch_event(cvkg_core::Event::GestureSwipe {
1133                            direction: [angle.cos(), angle.sin()],
1134                            velocity: delta.abs(),
1135                            phase: cvkg_core::TouchPhase::Moved,
1136                        });
1137                    }
1138                    state.window.request_redraw();
1139                }
1140                WindowEvent::KeyboardInput { event, .. } => {
1141                    if event.state == winit::event::ElementState::Pressed {
1142                        if let winit::keyboard::PhysicalKey::Code(code) = event.physical_key {
1143                            // Cross-platform "command" key: ⌘ on macOS, Ctrl on all other OSes.
1144                            // This ensures keyboard shortcuts work identically on every platform
1145                            // without separate branches in every handler.
1146                            let is_cmd = if cfg!(target_os = "macos") {
1147                                self.modifiers.super_key()
1148                            } else {
1149                                self.modifiers.control_key()
1150                            };
1151                            let is_shift = self.modifiers.shift_key();
1152
1153                            if is_cmd {
1154                                match code {
1155                                    // ── Undo / Redo ───────────────────────────────
1156                                    winit::keyboard::KeyCode::KeyZ => {
1157                                        if is_shift {
1158                                            log::info!("[Native] Shortcut: Redo (Cmd+Shift+Z)");
1159                                            let mut redo_action = None;
1160                                            cvkg_core::update_system_state(|s| {
1161                                                let mut s = s.clone();
1162                                                redo_action = s.undo_manager.redo();
1163                                                s
1164                                            });
1165                                            if let Some(action) = redo_action {
1166                                                action();
1167                                            }
1168                                            state.window.request_redraw();
1169                                        } else {
1170                                            log::info!("[Native] Shortcut: Undo (Cmd+Z)");
1171                                            let mut undo_action = None;
1172                                            cvkg_core::update_system_state(|s| {
1173                                                let mut s = s.clone();
1174                                                undo_action = s.undo_manager.undo();
1175                                                s
1176                                            });
1177                                            if let Some(action) = undo_action {
1178                                                action();
1179                                            }
1180                                            state.window.request_redraw();
1181                                        }
1182                                    }
1183                                    // Ctrl+Y as alternative Redo on non-macOS
1184                                    winit::keyboard::KeyCode::KeyY
1185                                        if !cfg!(target_os = "macos") =>
1186                                    {
1187                                        log::info!("[Native] Shortcut: Redo (Ctrl+Y)");
1188                                        let mut redo_action = None;
1189                                        cvkg_core::update_system_state(|s| {
1190                                            let mut s = s.clone();
1191                                            redo_action = s.undo_manager.redo();
1192                                            s
1193                                        });
1194                                        if let Some(action) = redo_action {
1195                                            action();
1196                                        }
1197                                        state.window.request_redraw();
1198                                    }
1199                                    // ── File operations ───────────────────────────
1200                                    winit::keyboard::KeyCode::KeyN => {
1201                                        log::info!("[Native] Shortcut: New Window (Cmd+N)");
1202                                        create_new_window = true;
1203                                    }
1204                                    winit::keyboard::KeyCode::KeyO => {
1205                                        log::info!("[Native] Shortcut: Open File (Cmd+O)");
1206                                        if let Some(vdom) = &state.vdom {
1207                                            vdom.dispatch_event(cvkg_core::Event::KeyDown {
1208                                                key: "cmd+o".to_string(),
1209                                            });
1210                                        }
1211                                        state.window.request_redraw();
1212                                    }
1213                                    winit::keyboard::KeyCode::KeyS => {
1214                                        log::info!("[Native] Shortcut: Save (Cmd+S)");
1215                                        if let Some(vdom) = &state.vdom {
1216                                            vdom.dispatch_event(cvkg_core::Event::KeyDown {
1217                                                key: "cmd+s".to_string(),
1218                                            });
1219                                        }
1220                                        state.window.request_redraw();
1221                                    }
1222                                    winit::keyboard::KeyCode::KeyW => {
1223                                        log::info!("[Native] Shortcut: Close Window (Cmd+W)");
1224                                        close_window = true;
1225                                    }
1226                                    winit::keyboard::KeyCode::KeyQ => {
1227                                        log::info!("[Native] Shortcut: Quit (Cmd+Q)");
1228                                        // Defer closing all windows until after the state borrow ends.
1229                                        quit_all = true;
1230                                    }
1231                                    // ── Clipboard ────────────────────────────────
1232                                    winit::keyboard::KeyCode::KeyC => {
1233                                        log::info!("[Native] Shortcut: Copy (Cmd+C)");
1234                                        if let Some(vdom) = &state.vdom {
1235                                            vdom.dispatch_event(cvkg_core::Event::Copy);
1236                                        }
1237                                        state.window.request_redraw();
1238                                    }
1239                                    winit::keyboard::KeyCode::KeyV => {
1240                                        log::info!("[Native] Shortcut: Paste (Cmd+V)");
1241                                        // Read the system clipboard. Fall back to empty string on
1242                                        // error so the Paste event is always delivered to the VDOM.
1243                                        let text = arboard::Clipboard::new()
1244                                            .ok()
1245                                            .and_then(|mut cb| cb.get_text().ok())
1246                                            .unwrap_or_default();
1247                                        if let Some(vdom) = &state.vdom {
1248                                            vdom.dispatch_event(cvkg_core::Event::Paste(text));
1249                                        }
1250                                        state.window.request_redraw();
1251                                    }
1252                                    winit::keyboard::KeyCode::KeyX => {
1253                                        log::info!("[Native] Shortcut: Cut (Cmd+X)");
1254                                        if let Some(vdom) = &state.vdom {
1255                                            vdom.dispatch_event(cvkg_core::Event::Cut);
1256                                        }
1257                                        state.window.request_redraw();
1258                                    }
1259                                    // ── Selection / search ────────────────────────
1260                                    winit::keyboard::KeyCode::KeyA => {
1261                                        log::info!("[Native] Shortcut: Select All (Cmd+A)");
1262                                        if let Some(vdom) = &state.vdom {
1263                                            vdom.dispatch_event(cvkg_core::Event::KeyDown {
1264                                                key: "cmd+a".to_string(),
1265                                            });
1266                                        }
1267                                        state.window.request_redraw();
1268                                    }
1269                                    winit::keyboard::KeyCode::KeyF => {
1270                                        log::info!("[Native] Shortcut: Find (Cmd+F)");
1271                                        if let Some(vdom) = &state.vdom {
1272                                            vdom.dispatch_event(cvkg_core::Event::KeyDown {
1273                                                key: "cmd+f".to_string(),
1274                                            });
1275                                        }
1276                                        state.window.request_redraw();
1277                                    }
1278                                    _ => {}
1279                                }
1280                            }
1281                        }
1282                    }
1283
1284                    if let Some(vdom) = &state.vdom
1285                        && let Some(cvkg_event) = convert_keyboard_event(event)
1286                    {
1287                        vdom.dispatch_event(cvkg_event);
1288                        state.window.request_redraw();
1289                    }
1290                }
1291
1292                WindowEvent::Ime(ime_event) => {
1293                    if let Some(vdom) = &state.vdom
1294                        && let Some(cvkg_event) = convert_ime_event(ime_event)
1295                    {
1296                        vdom.dispatch_event(cvkg_event);
1297                        state.window.request_redraw();
1298                    }
1299                }
1300                WindowEvent::ModifiersChanged(new_modifiers) => {
1301                    self.modifiers = new_modifiers.state();
1302                    let shift = self.modifiers.shift_key();
1303                    let ctrl = self.modifiers.control_key();
1304                    let alt = self.modifiers.alt_key();
1305                    let logo = self.modifiers.super_key();
1306                    cvkg_core::update_system_state(|st| {
1307                        let mut new_st = st.clone();
1308                        new_st.modifiers_shift = shift;
1309                        new_st.modifiers_ctrl = ctrl;
1310                        new_st.modifiers_alt = alt;
1311                        new_st.modifiers_logo = logo;
1312                        new_st
1313                    });
1314                }
1315                _ => {}
1316            }
1317        } // end of state block
1318
1319        if close_window {
1320            self.window_manager.close_window(id);
1321        }
1322        if quit_all {
1323            // Drain all windows; the is_empty check below will exit the event loop.
1324            for wid in self.window_manager.window_order().to_vec() {
1325                self.window_manager.close_window(wid);
1326            }
1327        }
1328        // Exit the event loop when all windows are closed (Cmd+W on last window, or Cmd+Q).
1329        if self.window_manager.windows.is_empty() {
1330            event_loop.exit();
1331        }
1332        if bring_to_front {
1333            self.window_manager.bring_to_front(id);
1334        }
1335        if create_new_window {
1336            self.window_manager.create_window(
1337                event_loop,
1338                &self.gpu,
1339                self.proxy.clone(),
1340                cvkg_core::WindowConfig {
1341                    title: "New CVKG Window".to_string(),
1342                    size: (800.0, 600.0),
1343                    ..Default::default()
1344                },
1345                false, // is_main
1346                &self.view,
1347            );
1348        }
1349    }
1350
1351    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: AppEvent) {
1352        match event {
1353            AppEvent::AccessibilityAction(request) => {
1354                let node_id = cvkg_vdom::NodeId(request.target.0);
1355                let target_state = self.window_manager.windows.values_mut().find(|s| {
1356                    s.vdom
1357                        .as_ref()
1358                        .map_or(false, |v| v.nodes.contains_key(&node_id))
1359                });
1360
1361                if let Some(state) = target_state
1362                    && let Some(vdom) = &state.vdom
1363                    && let Some(node) = vdom.nodes.get(&node_id)
1364                    && request.action == accesskit::Action::Click
1365                {
1366                    let event = cvkg_core::Event::PointerClick {
1367                        x: node.layout.x + node.layout.width / 2.0,
1368                        y: node.layout.y + node.layout.height / 2.0,
1369                        button: 0, // Assume left click for accessibility actions
1370                    };
1371                    vdom.dispatch_event(event);
1372                }
1373            }
1374            AppEvent::CloseWindow(winit_id) => {
1375                self.window_manager.close_window(winit_id);
1376                if self.window_manager.windows.is_empty() {
1377                    event_loop.exit();
1378                }
1379            }
1380            AppEvent::SetTitle(winit_id, title) => {
1381                if let Some(data) = self.window_manager.windows.get(&winit_id) {
1382                    data.window.set_title(&title);
1383                }
1384            }
1385            AppEvent::SetSize(winit_id, width, height) => {
1386                if let Some(data) = self.window_manager.windows.get(&winit_id) {
1387                    let _ = data
1388                        .window
1389                        .request_inner_size(winit::dpi::LogicalSize::new(width, height));
1390                }
1391            }
1392            AppEvent::SetVisible(winit_id, visible) => {
1393                if let Some(data) = self.window_manager.windows.get(&winit_id) {
1394                    data.window.set_visible(visible);
1395                }
1396            }
1397            AppEvent::BringToFront(winit_id) => {
1398                self.window_manager.bring_to_front(winit_id);
1399            }
1400        }
1401    }
1402
1403    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
1404        // Apply Rage Decay: rage naturally settles to 0 over time.
1405        self.rage = (self.rage - 0.02).max(0.0);
1406
1407        // Frame Throttling: 60FPS target (16.6ms)
1408        let now = std::time::Instant::now();
1409        let target_interval = std::time::Duration::from_millis(16);
1410
1411        if now.duration_since(self.last_frame_time) >= target_interval {
1412            if self.rage > 0.01 {
1413                // Only log heartbeat when there is kinetic activity
1414                log::debug!("[Native] Heartbeat ticking (rage: {})", self.rage);
1415            }
1416            self.last_frame_time = now;
1417            for window_state in self.window_manager.windows.values() {
1418                window_state.window.request_redraw();
1419            }
1420            event_loop.set_control_flow(winit::event_loop::ControlFlow::WaitUntil(
1421                now + target_interval,
1422            ));
1423        } else {
1424            event_loop.set_control_flow(winit::event_loop::ControlFlow::WaitUntil(
1425                self.last_frame_time + target_interval,
1426            ));
1427        }
1428    }
1429}
1430
1431impl cvkg_core::ElapsedTime for NativeRenderer {
1432    fn delta_time(&self) -> f32 {
1433        self.delta_time
1434    }
1435
1436    fn elapsed_time(&self) -> f32 {
1437        self.elapsed_time
1438    }
1439}
1440
1441impl cvkg_core::Renderer for NativeRenderer {
1442    fn fill_rect(&mut self, rect: cvkg_core::Rect, color: [f32; 4]) {
1443        self.gpu
1444            .lock()
1445            .expect("GPU mutex poisoned: fill_rect")
1446            .fill_rect(rect, color);
1447    }
1448    fn fill_rounded_rect(&mut self, rect: cvkg_core::Rect, radius: f32, color: [f32; 4]) {
1449        self.gpu
1450            .lock()
1451            .expect("GPU mutex poisoned: fill_rounded_rect")
1452            .fill_rounded_rect(rect, radius, color);
1453    }
1454    fn fill_ellipse(&mut self, rect: cvkg_core::Rect, color: [f32; 4]) {
1455        self.gpu
1456            .lock()
1457            .expect("GPU mutex poisoned: fill_ellipse")
1458            .fill_ellipse(rect, color);
1459    }
1460    fn stroke_rect(&mut self, rect: cvkg_core::Rect, color: [f32; 4], stroke_width: f32) {
1461        self.gpu
1462            .lock()
1463            .expect("GPU mutex poisoned: stroke_rect")
1464            .stroke_rect(rect, color, stroke_width);
1465    }
1466    fn stroke_rounded_rect(
1467        &mut self,
1468        rect: cvkg_core::Rect,
1469        radius: f32,
1470        color: [f32; 4],
1471        stroke_width: f32,
1472    ) {
1473        self.gpu
1474            .lock()
1475            .expect("GPU mutex poisoned: stroke_rounded_rect")
1476            .stroke_rounded_rect(rect, radius, color, stroke_width);
1477    }
1478    fn stroke_ellipse(&mut self, rect: cvkg_core::Rect, color: [f32; 4], stroke_width: f32) {
1479        self.gpu
1480            .lock()
1481            .expect("GPU mutex poisoned: stroke_ellipse")
1482            .stroke_ellipse(rect, color, stroke_width);
1483    }
1484    fn draw_line(
1485        &mut self,
1486        x1: f32,
1487        y1: f32,
1488        x2: f32,
1489        y2: f32,
1490        color: [f32; 4],
1491        stroke_width: f32,
1492    ) {
1493        self.gpu
1494            .lock()
1495            .expect("GPU mutex poisoned: draw_line")
1496            .draw_line(x1, y1, x2, y2, color, stroke_width);
1497    }
1498    fn draw_text(&mut self, text: &str, x: f32, y: f32, size: f32, color: [f32; 4]) {
1499        self.gpu
1500            .lock()
1501            .expect("GPU mutex poisoned: draw_text")
1502            .draw_text(text, x, y, size, color);
1503    }
1504    fn measure_text(&mut self, text: &str, size: f32) -> (f32, f32) {
1505        self.gpu
1506            .lock()
1507            .expect("GPU mutex poisoned: measure_text")
1508            .measure_text(text, size)
1509    }
1510    fn draw_linear_gradient(
1511        &mut self,
1512        rect: cvkg_core::Rect,
1513        start_color: [f32; 4],
1514        end_color: [f32; 4],
1515        angle: f32,
1516    ) {
1517        self.gpu
1518            .lock()
1519            .expect("GPU mutex poisoned: draw_linear_gradient")
1520            .draw_linear_gradient(rect, start_color, end_color, angle);
1521    }
1522    fn draw_radial_gradient(
1523        &mut self,
1524        rect: cvkg_core::Rect,
1525        inner_color: [f32; 4],
1526        outer_color: [f32; 4],
1527    ) {
1528        self.gpu
1529            .lock()
1530            .expect("GPU mutex poisoned: draw_radial_gradient")
1531            .draw_radial_gradient(rect, inner_color, outer_color);
1532    }
1533    fn draw_texture(&mut self, texture_id: u32, rect: cvkg_core::Rect) {
1534        self.gpu
1535            .lock()
1536            .expect("GPU mutex poisoned: draw_texture")
1537            .draw_texture(texture_id, rect);
1538    }
1539    fn draw_image(&mut self, image_name: &str, rect: cvkg_core::Rect) {
1540        self.gpu
1541            .lock()
1542            .expect("GPU mutex poisoned: draw_image")
1543            .draw_image(image_name, rect);
1544    }
1545    fn load_image(&mut self, name: &str, data: &[u8]) {
1546        self.gpu
1547            .lock()
1548            .expect("GPU mutex poisoned: load_image")
1549            .load_image(name, data);
1550    }
1551    fn push_clip_rect(&mut self, rect: cvkg_core::Rect) {
1552        self.gpu
1553            .lock()
1554            .expect("GPU mutex poisoned: push_clip_rect")
1555            .push_clip_rect(rect);
1556    }
1557    fn pop_clip_rect(&mut self) {
1558        self.gpu
1559            .lock()
1560            .expect("GPU mutex poisoned: pop_clip_rect")
1561            .pop_clip_rect();
1562    }
1563    fn push_opacity(&mut self, opacity: f32) {
1564        self.gpu
1565            .lock()
1566            .expect("GPU mutex poisoned: push_opacity")
1567            .push_opacity(opacity);
1568    }
1569    fn draw_3d_cube(&mut self, rect: cvkg_core::Rect, color: [f32; 4], rotation: [f32; 3]) {
1570        self.gpu
1571            .lock()
1572            .expect("GPU mutex poisoned: draw_3d_cube")
1573            .draw_3d_cube(rect, color, rotation);
1574    }
1575    fn pop_opacity(&mut self) {
1576        self.gpu
1577            .lock()
1578            .expect("GPU mutex poisoned: pop_opacity")
1579            .pop_opacity();
1580    }
1581    fn bifrost(&mut self, rect: cvkg_core::Rect, blur: f32, saturation: f32, opacity: f32) {
1582        self.gpu
1583            .lock()
1584            .expect("GPU mutex poisoned: bifrost")
1585            .bifrost(rect, blur, saturation, opacity);
1586    }
1587    fn push_mjolnir_slice(&mut self, angle: f32, offset: f32) {
1588        self.gpu
1589            .lock()
1590            .expect("GPU mutex poisoned: push_mjolnir_slice")
1591            .push_mjolnir_slice(angle, offset);
1592    }
1593    fn pop_mjolnir_slice(&mut self) {
1594        self.gpu
1595            .lock()
1596            .expect("GPU mutex poisoned: pop_mjolnir_slice")
1597            .pop_mjolnir_slice();
1598    }
1599    fn mjolnir_shatter(&mut self, rect: cvkg_core::Rect, pieces: u32, force: f32, color: [f32; 4]) {
1600        self.gpu
1601            .lock()
1602            .expect("GPU mutex poisoned: mjolnir_shatter")
1603            .mjolnir_shatter(rect, pieces, force, color);
1604    }
1605    fn mjolnir_fluid_shatter(
1606        &mut self,
1607        rect: cvkg_core::Rect,
1608        pieces: u32,
1609        force: f32,
1610        color: [f32; 4],
1611    ) {
1612        self.gpu
1613            .lock()
1614            .expect("GPU mutex poisoned: mjolnir_fluid_shatter")
1615            .mjolnir_fluid_shatter(rect, pieces, force, color);
1616    }
1617    fn draw_mjolnir_bolt(&mut self, from: [f32; 2], to: [f32; 2], color: [f32; 4]) {
1618        self.gpu
1619            .lock()
1620            .expect("GPU mutex poisoned: draw_mjolnir_bolt")
1621            .draw_mjolnir_bolt(from, to, color);
1622    }
1623    fn gungnir(&mut self, rect: cvkg_core::Rect, color: [f32; 4], radius: f32, intensity: f32) {
1624        self.gpu
1625            .lock()
1626            .expect("GPU mutex poisoned: gungnir")
1627            .gungnir(rect, color, radius, intensity);
1628    }
1629    fn mani_glow(&mut self, rect: cvkg_core::Rect, color: [f32; 4], radius: f32) {
1630        self.gpu
1631            .lock()
1632            .expect("GPU mutex poisoned: mani_glow")
1633            .mani_glow(rect, color, radius);
1634    }
1635    fn register_handler(
1636        &mut self,
1637        event_type: &str,
1638        handler: std::sync::Arc<dyn Fn(cvkg_core::Event) + Send + Sync>,
1639    ) {
1640        self.gpu
1641            .lock()
1642            .expect("GPU mutex poisoned: register_handler")
1643            .register_handler(event_type, handler);
1644    }
1645    fn push_vnode(&mut self, rect: cvkg_core::Rect, name: &'static str) {
1646        self.gpu
1647            .lock()
1648            .expect("GPU mutex poisoned: push_vnode")
1649            .push_vnode(rect, name);
1650    }
1651    fn pop_vnode(&mut self) {
1652        self.gpu
1653            .lock()
1654            .expect("GPU mutex poisoned: pop_vnode")
1655            .pop_vnode();
1656    }
1657    // FIX #1: Removed duplicate definitions of set_z_index and get_z_index.
1658    // They appeared twice in this impl block (after pop_vnode and after register_shared_element),
1659    // which is a hard compiler error. Exactly one definition of each is kept here.
1660    fn set_z_index(&mut self, z: f32) {
1661        self.gpu
1662            .lock()
1663            .expect("GPU mutex poisoned: set_z_index")
1664            .set_z_index(z);
1665    }
1666    fn get_z_index(&self) -> f32 {
1667        self.gpu
1668            .lock()
1669            .expect("GPU mutex poisoned: get_z_index")
1670            .get_z_index()
1671    }
1672    fn register_shared_element(&mut self, id: &str, rect: cvkg_core::Rect) {
1673        self.gpu
1674            .lock()
1675            .expect("GPU mutex poisoned: register_shared_element")
1676            .register_shared_element(id, rect);
1677    }
1678    fn load_svg(&mut self, name: &str, svg_data: &[u8]) {
1679        self.gpu
1680            .lock()
1681            .expect("GPU mutex poisoned: load_svg")
1682            .load_svg(name, svg_data);
1683    }
1684    fn draw_svg(&mut self, name: &str, rect: cvkg_core::Rect) {
1685        self.gpu
1686            .lock()
1687            .expect("GPU mutex poisoned: draw_svg")
1688            .draw_svg(name, rect, None, 0);
1689    }
1690    fn get_telemetry(&self) -> cvkg_core::TelemetryData {
1691        self.gpu
1692            .lock()
1693            .expect("GPU mutex poisoned: get_telemetry")
1694            .telemetry
1695            .clone()
1696    }
1697    fn prewarm_vram(&mut self, assets: Vec<(String, Vec<u8>)>) {
1698        self.gpu
1699            .lock()
1700            .expect("GPU mutex poisoned: prewarm_vram")
1701            .prewarm_vram(assets);
1702    }
1703    fn push_transform(&mut self, translation: [f32; 2], scale: [f32; 2], rotation: f32) {
1704        self.gpu
1705            .lock()
1706            .expect("GPU mutex poisoned: push_transform")
1707            .push_transform(translation, scale, rotation);
1708    }
1709    fn pop_transform(&mut self) {
1710        self.gpu
1711            .lock()
1712            .expect("GPU mutex poisoned: pop_transform")
1713            .pop_transform();
1714    }
1715
1716    fn set_berserker_mode(&mut self, state: cvkg_core::BerserkerMode) {
1717        self.berserker_mode = state;
1718
1719        // Berserker Determinism: Apply OS-level scheduler priority hints for GodMode.
1720        // SAFETY: setpriority is a POSIX syscall. We pass PRIO_PROCESS with pid=0 (self).
1721        // Failure is silently ignored via let _ because insufficient permissions are expected
1722        // in unprivileged environments and must not crash the render loop.
1723        if state == cvkg_core::BerserkerMode::GodMode {
1724            log::info!("ENTERING GOD MODE: Activating Berserker Determinism (High Priority)");
1725            #[cfg(target_os = "linux")]
1726            unsafe {
1727                let _ = libc::setpriority(libc::PRIO_PROCESS, 0, -10);
1728            }
1729        } else {
1730            #[cfg(target_os = "linux")]
1731            unsafe {
1732                let _ = libc::setpriority(libc::PRIO_PROCESS, 0, 0);
1733            }
1734        }
1735
1736        self.gpu
1737            .lock()
1738            .expect("GPU mutex poisoned: set_berserker_mode")
1739            .set_berserker_mode(state);
1740    }
1741
1742    fn set_rage(&mut self, rage: f32) {
1743        self.rage = rage;
1744        self.gpu
1745            .lock()
1746            .expect("GPU mutex poisoned: set_rage")
1747            .set_rage(rage);
1748    }
1749
1750    fn memoize(&mut self, id: u64, data_hash: u64, render_fn: &dyn Fn(&mut dyn Renderer)) {
1751        self.gpu
1752            .lock()
1753            .expect("GPU mutex poisoned: memoize")
1754            .memoize(id, data_hash, render_fn);
1755    }
1756    fn request_redraw(&mut self) {
1757        self.window.request_redraw();
1758    }
1759
1760    /// Captures the current frame as a PNG-encoded byte buffer via GPU readback.
1761    /// Captures the current frame as a PNG-encoded byte buffer via GPU readback.
1762    ///
1763    /// FIX #4: capture_frame() returns a Future that borrows the SurtrRenderer, so the
1764    /// MutexGuard must remain alive until block_on completes — the guard cannot be dropped
1765    /// before the future is driven to completion. The lock is held for the duration of the
1766    /// GPU readback. This is acceptable because capture_png is an infrequent, explicit
1767    /// user-triggered operation (not called on the hot render path), so blocking other
1768    /// render calls for the readback duration is not a practical concern.
1769    fn capture_png(&mut self) -> Vec<u8> {
1770        log::info!("CAPTURING_FRAME: Initiating GPU readback...");
1771        // INVARIANT: The MutexGuard `gpu` must outlive the future returned by capture_frame()
1772        // because the future borrows from the SurtrRenderer. We therefore lock, block_on the
1773        // future (driving it to completion), and only then allow the guard to drop.
1774        let gpu = self.gpu.lock().expect("GPU mutex poisoned: capture_png");
1775        pollster::block_on(gpu.capture_frame()).unwrap_or_else(|e| {
1776            log::error!("GPU frame capture failed: {}", e);
1777            Vec::new() // Return empty buffer on failure — do not panic the render loop
1778        })
1779    }
1780
1781    fn print(&mut self) {
1782        log::info!("PRINT_BRIDGE: Spooling mission status to native printer...");
1783        // In a production environment, this would interface with CUPS/GDI/AirPrint.
1784        // For the Ulfhednar prototype, we simulate the handshake.
1785        println!("[BRIDGE] PRINTER_READY // SPOOLING_DATA...");
1786    }
1787}
1788
1789// ── Native Menu Bar Builder ───────────────────────────────────────────
1790
1791// ── Event Conversion Helpers ───────────────────────────────────────────
1792
1793fn convert_keyboard_event(event: winit::event::KeyEvent) -> Option<cvkg_core::Event> {
1794    if let winit::keyboard::PhysicalKey::Code(code) = event.physical_key {
1795        let key_str = format!("{:?}", code);
1796        if event.state == winit::event::ElementState::Pressed {
1797            Some(cvkg_core::Event::KeyDown { key: key_str })
1798        } else {
1799            Some(cvkg_core::Event::KeyUp { key: key_str })
1800        }
1801    } else {
1802        None
1803    }
1804}
1805
1806fn convert_ime_event(event: winit::event::Ime) -> Option<cvkg_core::Event> {
1807    if let winit::event::Ime::Commit(string) = event {
1808        Some(cvkg_core::Event::Ime(string))
1809    } else {
1810        None
1811    }
1812}
1813
1814fn convert_mouse_event(
1815    state: winit::event::ElementState,
1816    position: [f32; 2],
1817    button: u32,
1818) -> cvkg_core::Event {
1819    match state {
1820        winit::event::ElementState::Pressed => cvkg_core::Event::PointerDown {
1821            x: position[0],
1822            y: position[1],
1823            button,
1824            proximity_field: 0.0,
1825        },
1826        winit::event::ElementState::Released => cvkg_core::Event::PointerUp {
1827            x: position[0],
1828            y: position[1],
1829            button,
1830        },
1831    }
1832}
1833
1834// Platform-specific implementations for macOS, Windows, and Linux are handled by winit and AccessKit.
1835
1836struct ShieldWall {
1837    proxy: winit::event_loop::EventLoopProxy<AppEvent>,
1838}
1839
1840impl accesskit::ActionHandler for ShieldWall {
1841    fn do_action(&mut self, request: accesskit::ActionRequest) {
1842        let _ = self
1843            .proxy
1844            .send_event(AppEvent::AccessibilityAction(request));
1845    }
1846}
1847
1848impl accesskit::ActivationHandler for ShieldWall {
1849    fn request_initial_tree(&mut self) -> Option<accesskit::TreeUpdate> {
1850        let mut root = accesskit::Node::new(accesskit::Role::Window);
1851        root.set_label("CVKG Application");
1852
1853        let root_id = accesskit::NodeId(1);
1854        Some(accesskit::TreeUpdate {
1855            nodes: vec![(root_id, root)],
1856            tree: Some(accesskit::Tree::new(root_id)),
1857            focus: root_id,
1858        })
1859    }
1860}
1861
1862impl accesskit::DeactivationHandler for ShieldWall {
1863    fn deactivate_accessibility(&mut self) {}
1864}
1865
1866type AssetCacheMap =
1867    std::collections::HashMap<String, cvkg_core::AssetState<std::sync::Arc<Vec<u8>>>>;
1868
1869/// A concrete AssetManager for native desktop targets that loads from the local filesystem.
1870///
1871/// The cache is read on every render frame (lock-free via `ArcSwap::load()`) but written
1872/// at most once per URL after disk I/O completes. `rcu()` atomically inserts the result
1873/// without blocking concurrent render-loop readers.
1874pub struct NativeAssetManager {
1875    cache: std::sync::Arc<arc_swap::ArcSwap<AssetCacheMap>>,
1876}
1877
1878impl Default for NativeAssetManager {
1879    fn default() -> Self {
1880        Self::new()
1881    }
1882}
1883
1884impl NativeAssetManager {
1885    /// Create a new, empty NativeAssetManager.
1886    pub fn new() -> Self {
1887        Self {
1888            cache: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(
1889                std::collections::HashMap::new(),
1890            )),
1891        }
1892    }
1893}
1894
1895impl cvkg_core::AssetManager for NativeAssetManager {
1896    /// Return the cached asset state for `url`.
1897    ///
1898    /// Fast path: lock-free snapshot read via `ArcSwap::load()`.
1899    /// Slow path (cache miss): atomically insert a Loading sentinel via `rcu()`,
1900    /// then spawn a background thread for I/O. The `rcu()` closure may execute
1901    /// more than once under contention, so `already_tracked` is determined by
1902    /// whether the closure actually inserted the Loading entry (detected by checking
1903    /// the returned map). This prevents duplicate I/O threads for the same URL.
1904    ///
1905    /// FIX #5: The previous implementation set `already_tracked` inside the `rcu`
1906    /// closure body, which is incorrect because `rcu` retries the closure on
1907    /// contention — the bool would reflect only the last execution. The fix uses
1908    /// the fast-path check result plus the atomic `rcu` insertion to determine
1909    /// whether a thread must be spawned, making the logic correct under concurrency.
1910    fn load_image(&self, url: &str) -> cvkg_core::AssetState<std::sync::Arc<Vec<u8>>> {
1911        // Fast path: lock-free read from the current cache snapshot.
1912        if let Some(state) = self.cache.load().get(url) {
1913            return state.clone();
1914        }
1915
1916        let cache = self.cache.clone();
1917        let key = url.to_string();
1918
1919        // Slow path: atomically insert Loading if the key is absent.
1920        // `rcu` returns the final committed map; we inspect it to determine
1921        // whether *this* call was the one that inserted Loading (and thus
1922        // should spawn the I/O thread) versus a concurrent call that beat us.
1923        let mut we_inserted = false;
1924        self.cache.rcu(|map| {
1925            if map.contains_key(&key) {
1926                // Another caller already claimed this URL — do not insert.
1927                (**map).clone()
1928            } else {
1929                we_inserted = true;
1930                let mut m = (**map).clone();
1931                m.insert(key.clone(), cvkg_core::AssetState::Loading);
1932                m
1933            }
1934        });
1935
1936        // Only the caller that performed the insertion spawns the I/O thread,
1937        // preventing duplicate concurrent reads for the same asset URL.
1938        if we_inserted {
1939            let cache_inner = cache.clone();
1940            let key_inner = key.clone();
1941
1942            std::thread::spawn(move || {
1943                log::debug!("[Native] Asynchronously loading asset: {}", key_inner);
1944                let result = match std::fs::read(&key_inner) {
1945                    Ok(data) => cvkg_core::AssetState::Ready(std::sync::Arc::new(data)),
1946                    Err(e) => cvkg_core::AssetState::Error(e.to_string()),
1947                };
1948
1949                cache_inner.rcu(move |map| {
1950                    let mut m = (**map).clone();
1951                    m.insert(key_inner.clone(), result.clone());
1952                    m
1953                });
1954            });
1955        }
1956
1957        cvkg_core::AssetState::Loading
1958    }
1959
1960    /// Trigger a background load of `url` without waiting for the result.
1961    ///
1962    /// FIX #6: The previous implementation had a bare fast-path check followed
1963    /// by an unconditional thread spawn, allowing two concurrent calls for the
1964    /// same URL to both spawn I/O threads. Now uses the same rcu-based insertion
1965    /// guard as `load_image` to ensure exactly one thread is spawned per URL.
1966    fn preload_image(&self, url: &str) {
1967        // Fast path: if already in cache (any state), no work to do.
1968        if self.cache.load().contains_key(url) {
1969            return;
1970        }
1971
1972        let cache = self.cache.clone();
1973        let key = url.to_string();
1974
1975        let mut we_inserted = false;
1976        self.cache.rcu(|map| {
1977            if map.contains_key(&key) {
1978                (**map).clone()
1979            } else {
1980                we_inserted = true;
1981                let mut m = (**map).clone();
1982                m.insert(key.clone(), cvkg_core::AssetState::Loading);
1983                m
1984            }
1985        });
1986
1987        if we_inserted {
1988            std::thread::spawn(move || {
1989                log::debug!("[Native] Preloading asset: {}", key);
1990                let result = match std::fs::read(&key) {
1991                    Ok(data) => cvkg_core::AssetState::Ready(std::sync::Arc::new(data)),
1992                    Err(e) => cvkg_core::AssetState::Error(e.to_string()),
1993                };
1994
1995                cache.rcu(move |map| {
1996                    let mut m = (**map).clone();
1997                    m.insert(key.clone(), result.clone());
1998                    m
1999                });
2000            });
2001        }
2002    }
2003}
2004
2005#[cfg(test)]
2006mod tests {
2007    use super::*;
2008    use cvkg_core::AssetManager;
2009    use std::io::Write;
2010
2011    /// FIX #12: Replaced hardcoded relative path "test_asset.png" with a temp-dir path
2012    /// constructed from a unique per-test name. The previous path was written to the
2013    /// process working directory, which varies by invocation and causes collisions when
2014    /// tests run in parallel or when a prior run panics before cleanup.
2015    #[test]
2016    fn test_native_asset_manager_loading() {
2017        let manager = NativeAssetManager::new();
2018        let temp_path = std::env::temp_dir().join("cvkg_test_asset_loading.png");
2019        let temp_file_path = temp_path.to_str().expect("temp path must be valid UTF-8");
2020        let test_data = b"fake-image-data";
2021
2022        // Create a temporary file in the OS temp directory
2023        let mut file = std::fs::File::create(temp_file_path).unwrap();
2024        file.write_all(test_data).unwrap();
2025        drop(file);
2026
2027        // First call returns Loading and spawns the background I/O thread
2028        let mut state = manager.load_image(temp_file_path);
2029
2030        // Poll until Ready or timeout
2031        let start = std::time::Instant::now();
2032        while matches!(state, cvkg_core::AssetState::Loading) && start.elapsed().as_secs() < 5 {
2033            std::thread::sleep(std::time::Duration::from_millis(10));
2034            state = manager.load_image(temp_file_path);
2035        }
2036
2037        if let cvkg_core::AssetState::Ready(data) = state {
2038            assert_eq!(&*data, test_data);
2039        } else {
2040            let _ = std::fs::remove_file(temp_file_path);
2041            panic!("Expected Ready state, got {:?}", state);
2042        }
2043
2044        // Verify fast path returns Ready immediately from cache
2045        let state2 = manager.load_image(temp_file_path);
2046        if let cvkg_core::AssetState::Ready(data) = state2 {
2047            assert_eq!(&*data, test_data);
2048        } else {
2049            let _ = std::fs::remove_file(temp_file_path);
2050            panic!("Expected Ready state (cached), got {:?}", state2);
2051        }
2052
2053        let _ = std::fs::remove_file(temp_file_path);
2054    }
2055
2056    #[test]
2057    fn test_native_asset_manager_error() {
2058        let manager = NativeAssetManager::new();
2059        let path = "non_existent_file_cvkg_test.png";
2060        let mut state = manager.load_image(path);
2061
2062        let start = std::time::Instant::now();
2063        while matches!(state, cvkg_core::AssetState::Loading) && start.elapsed().as_secs() < 5 {
2064            std::thread::sleep(std::time::Duration::from_millis(10));
2065            state = manager.load_image(path);
2066        }
2067
2068        if let cvkg_core::AssetState::Error(_) = state {
2069            // Expected — non-existent file must produce an Error state
2070        } else {
2071            panic!("Expected Error state, got {:?}", state);
2072        }
2073    }
2074
2075    #[test]
2076    fn test_event_conversion() {
2077        // Mouse press event
2078        let event = convert_mouse_event(winit::event::ElementState::Pressed, [10.0, 20.0], 0);
2079        if let cvkg_core::Event::PointerDown { x, y, button, .. } = event {
2080            assert_eq!(x, 10.0);
2081            assert_eq!(y, 20.0);
2082            assert_eq!(button, 0);
2083        } else {
2084            panic!("Expected PointerDown");
2085        }
2086
2087        // IME commit event
2088        let event = convert_ime_event(winit::event::Ime::Commit("hello".to_string()));
2089        if let Some(cvkg_core::Event::Ime(s)) = event {
2090            assert_eq!(s, "hello");
2091        } else {
2092            panic!("Expected Ime event");
2093        }
2094    }
2095}
2096
2097/// load_icon — Searches known asset directories for 'icon.png'.
2098/// Returns a winit Icon if found and decodable, None otherwise.
2099/// All failures are logged at warn level — missing icons are non-fatal.
2100fn load_icon() -> Option<winit::window::Icon> {
2101    // FIX #13: Replaced unwrap_or_default() with unwrap_or_else that logs the failure.
2102    // unwrap_or_default() produced an empty PathBuf silently, making all subsequent
2103    // icon path lookups silently fail with no diagnostic output.
2104    let base = std::env::current_dir().unwrap_or_else(|e| {
2105        log::warn!(
2106            "[Native] Failed to get current directory for icon search: {}",
2107            e
2108        );
2109        std::path::PathBuf::new()
2110    });
2111
2112    let mut candidates = vec![
2113        base.join("icon.png"),
2114        base.join("crates/ulfhednar/icons/icon.png"),
2115        base.join("ulfhednar/icons/icon.png"),
2116        base.join("crates/ulfhednar/assets/icon.png"),
2117        base.join("ulfhednar/assets/icon.png"),
2118        base.join("assets/icon.png"),
2119    ];
2120
2121    // Also search relative to the executable directory
2122    if let Ok(exe_path) = std::env::current_exe()
2123        && let Some(exe_dir) = exe_path.parent()
2124    {
2125        candidates.push(exe_dir.join("icons/icon.png"));
2126        candidates.push(exe_dir.join("assets/icon.png"));
2127        candidates.push(exe_dir.join("icon.png"));
2128        if let Some(parent) = exe_dir.parent() {
2129            candidates.push(parent.join("icons/icon.png"));
2130            candidates.push(parent.join("assets/icon.png"));
2131            candidates.push(parent.join("icon.png"));
2132        }
2133    }
2134
2135    for path in candidates {
2136        if !path.exists() {
2137            log::debug!("[Native] Icon candidate not found: {:?}", path);
2138            continue;
2139        }
2140
2141        match image::open(&path) {
2142            Ok(img) => {
2143                let rgba = img.to_rgba8();
2144                let (width, height) = rgba.dimensions();
2145                match winit::window::Icon::from_rgba(rgba.into_raw(), width, height) {
2146                    Ok(icon) => {
2147                        log::info!("[Native] Successfully loaded app icon from: {:?}", path);
2148                        return Some(icon);
2149                    }
2150                    Err(e) => {
2151                        log::warn!("[Native] Icon format error at {:?}: {}", path, e);
2152                    }
2153                }
2154            }
2155            Err(e) => {
2156                log::warn!("[Native] Failed to open icon image at {:?}: {}", path, e);
2157            }
2158        }
2159    }
2160
2161    log::warn!(
2162        "[Native] Failed to find icon.png in any search path (CWD: {:?})",
2163        base
2164    );
2165    None
2166}
2167
2168// =============================================================================
2169// AUDIO / HAPTIC ENGINES — Cross-platform micro-feedback
2170// =============================================================================
2171
2172/// Cross-platform audio engine using rodio for spatialized sound cues.
2173/// Uses rodio 0.21 API: OutputStreamBuilder::open_default_stream() returns
2174/// OutputStream directly. Playback via Sink::try_new(&stream.mixer()) + append.
2175pub struct RodioAudioEngine {
2176    _stream: rodio::OutputStream,
2177}
2178
2179// OutputStream is not Send+Sync on macOS due to CoreAudio, but we only use it
2180// from the main thread. The AudioEngine trait requires Send+Sync for use in
2181// App struct fields, which is safe here because we never move it across threads.
2182unsafe impl Send for RodioAudioEngine {}
2183unsafe impl Sync for RodioAudioEngine {}
2184
2185impl RodioAudioEngine {
2186    /// Create a new audio engine. Falls back to None if audio init fails.
2187    pub fn new() -> Option<Self> {
2188        match rodio::OutputStreamBuilder::open_default_stream() {
2189            Ok(stream) => {
2190                log::info!("[Native] Audio engine initialized (rodio)");
2191                Some(Self { _stream: stream })
2192            }
2193            Err(e) => {
2194                log::warn!("[Native] Audio init failed (no sound): {}", e);
2195                None
2196            }
2197        }
2198    }
2199}
2200
2201impl cvkg_core::AudioEngine for RodioAudioEngine {
2202    fn play_sound(&self, name: &str, volume: f32) {
2203        let data: &[u8] = match name {
2204            "nav_tick" => cvkg_core::sounds::NAVIGATION_TICK,
2205            "success_chime" => cvkg_core::sounds::SUCCESS_CHIME,
2206            "warning_tone" => cvkg_core::sounds::WARNING_TONE,
2207            _ => {
2208                log::warn!("[Native] Unknown sound: {}", name);
2209                return;
2210            }
2211        };
2212        self.play_buffer(data, volume);
2213    }
2214
2215    fn play_buffer(&self, data: &[u8], _volume: f32) {
2216        use std::io::Cursor;
2217        let cursor = Cursor::new(data.to_vec());
2218        let mixer = self._stream.mixer();
2219        match rodio::play(mixer, cursor) {
2220            Ok(_sink) => {}
2221            Err(e) => log::warn!("[Native] Audio play failed: {}", e),
2222        }
2223    }
2224
2225    fn play_spatial(&self, name: &str, _position: [f32; 3], volume: f32) {
2226        // Spatial audio: play sound without positional attenuation (OS-agnostic fallback)
2227        self.play_sound(name, volume);
2228    }
2229}
2230
2231/// Visual haptic engine that translates haptic requests into visual micro-animations.
2232/// Used as a cross-platform fallback where native haptics are unavailable.
2233pub struct VisualHapticEngine {
2234    last_impact: std::sync::Mutex<std::time::Instant>,
2235}
2236
2237impl Default for VisualHapticEngine {
2238    fn default() -> Self {
2239        Self::new()
2240    }
2241}
2242
2243impl VisualHapticEngine {
2244    pub fn new() -> Self {
2245        Self {
2246            last_impact: std::sync::Mutex::new(std::time::Instant::now()),
2247        }
2248    }
2249}
2250
2251impl cvkg_core::HapticEngine for VisualHapticEngine {
2252    fn impact(&self, intensity: cvkg_core::HapticIntensity) {
2253        let _ = intensity;
2254        *self.last_impact.lock().unwrap() = std::time::Instant::now();
2255    }
2256    fn selection(&self) {
2257        self.impact(cvkg_core::HapticIntensity::Light);
2258    }
2259    fn success(&self) {
2260        self.impact(cvkg_core::HapticIntensity::Medium);
2261    }
2262    fn warning(&self) {
2263        self.impact(cvkg_core::HapticIntensity::Medium);
2264    }
2265    fn error(&self) {
2266        self.impact(cvkg_core::HapticIntensity::Heavy);
2267    }
2268    fn visual_tick(&self, _intensity: f32) {
2269        *self.last_impact.lock().unwrap() = std::time::Instant::now();
2270    }
2271}