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.
45#[cfg(target_os = "linux")]
46use std::sync::Arc;
47use winit::{
48    application::ApplicationHandler,
49    event::{DeviceEvent, DeviceId, WindowEvent},
50    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
51    window::{Window, WindowId},
52};
53
54/// Native renderer backend implementing the Renderer trait.
55/// It wraps a shared SurtrRenderer for high-performance GPU drawing.
56pub struct NativeRenderer {
57    gpu: Arc<std::sync::Mutex<cvkg_render_gpu::SurtrRenderer>>,
58    delta_time: f32,
59    elapsed_time: f32,
60    berserker_mode: cvkg_core::BerserkerMode,
61    rage: f32,
62    window: Arc<Window>,
63}
64
65/// Custom events for the native application event loop
66#[derive(Debug)]
67enum AppEvent {
68    AccessibilityAction(accesskit::ActionRequest),
69}
70
71impl NativeRenderer {
72    /// Create a new NativeRenderer (internal use by App)
73    fn new(
74        window: Arc<Window>,
75        gpu: Arc<std::sync::Mutex<cvkg_render_gpu::SurtrRenderer>>,
76        delta_time: f32,
77        elapsed_time: f32,
78        berserker_mode: cvkg_core::BerserkerMode,
79        rage: f32,
80    ) -> Self {
81        Self {
82            gpu,
83            delta_time,
84            elapsed_time,
85            berserker_mode,
86            rage,
87            window,
88        }
89    }
90
91    /// Start the CVKG native application with the given view.
92    /// This is the main entry point for desktop applications.
93    pub fn run<V: cvkg_core::View + 'static>(view: V) {
94        let event_loop = EventLoop::<AppEvent>::with_user_event()
95            .build()
96            .expect("Failed to create event loop");
97        event_loop.set_control_flow(ControlFlow::Wait);
98
99        let mut app = App {
100            view,
101            windows: std::collections::HashMap::new(),
102            gpu: None,
103            asset_manager: std::sync::Arc::new(NativeAssetManager::new()),
104            proxy: event_loop.create_proxy(),
105            start_time: std::time::Instant::now(),
106            last_frame_time: std::time::Instant::now(),
107            berserker_mode: cvkg_core::BerserkerMode::Normal,
108            rage: 0.0,
109        };
110
111        event_loop.run_app(&mut app).expect("Event loop error");
112    }
113}
114
115struct WindowState {
116    window: Arc<Window>,
117    accesskit_adapter: Option<accesskit_winit::Adapter>,
118    vdom: Option<cvkg_vdom::VDom>,
119    cursor_pos: [f32; 2],
120    /// The instant the last redraw finished, used for measuring inter-frame gap timing.
121    last_redraw_start: std::time::Instant,
122    /// Sliding window of frame times for tail latency (P99) calculation.
123    frame_history: std::collections::VecDeque<f32>,
124    /// Total frames rendered on this window.
125    frame_count: u64,
126    /// Last window position for shake detection.
127    last_pos: Option<[i32; 2]>,
128}
129
130struct App<V: cvkg_core::View> {
131    view: V,
132    windows: std::collections::HashMap<WindowId, WindowState>,
133    gpu: Option<Arc<std::sync::Mutex<cvkg_render_gpu::SurtrRenderer>>>,
134    #[allow(dead_code)]
135    asset_manager: std::sync::Arc<NativeAssetManager>,
136    proxy: winit::event_loop::EventLoopProxy<AppEvent>,
137    start_time: std::time::Instant,
138    last_frame_time: std::time::Instant,
139    berserker_mode: cvkg_core::BerserkerMode,
140    rage: f32,
141}
142
143impl<V: cvkg_core::View + 'static> ApplicationHandler<AppEvent> for App<V> {
144    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
145        if self.gpu.is_none() {
146            log::info!("[Native] App instance (resumed): {:p}", self);
147
148            let window_attrs = Window::default_attributes()
149                .with_title("CVKG Berserker")
150                .with_visible(true)
151                .with_transparent(false)
152                .with_decorations(true)
153                .with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0));
154
155            let window = Arc::new(
156                event_loop
157                    .create_window(window_attrs)
158                    .expect("Failed to create window"),
159            );
160
161            let window_id = window.id();
162            let vdom =
163                cvkg_vdom::VDom::build(&self.view, cvkg_core::Rect::new(0.0, 0.0, 1280.0, 720.0));
164
165            log::info!("[Native] INSERTING window ID: {:?}", window_id);
166
167            self.windows.insert(
168                window_id,
169                WindowState {
170                    window: window.clone(),
171                    accesskit_adapter: None,
172                    vdom: Some(vdom),
173                    cursor_pos: [0.0, 0.0],
174                    last_redraw_start: std::time::Instant::now(),
175                    frame_history: std::collections::VecDeque::with_capacity(60),
176                    frame_count: 0,
177                    last_pos: None,
178                },
179            );
180
181            // Immediately set self.gpu to prevent re-entry
182            let gpu = pollster::block_on(cvkg_render_gpu::SurtrRenderer::forge(window.clone()));
183            self.gpu = Some(Arc::new(std::sync::Mutex::new(gpu)));
184
185            log::info!("[Native] Initialization complete.");
186            window.request_redraw();
187        }
188    }
189
190    fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: winit::event::StartCause) {
191        if matches!(cause, winit::event::StartCause::Poll) {
192            // Too noisy
193        } else {
194            log::debug!("[Native] Event Loop Wake: {:?}", cause);
195        }
196    }
197
198    fn device_event(
199        &mut self,
200        _event_loop: &ActiveEventLoop,
201        _device_id: winit::event::DeviceId,
202        event: winit::event::DeviceEvent,
203    ) {
204        if matches!(event, winit::event::DeviceEvent::MouseMotion { .. }) {
205            // log::trace!("[Native] Raw Mouse Motion");
206        } else {
207            log::info!("[Native] DEVICE EVENT: {:?}", event);
208        }
209    }
210
211    fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
212        if !matches!(event, WindowEvent::RedrawRequested)
213            && !matches!(event, WindowEvent::CursorMoved { .. })
214        {
215            log::info!(
216                "[Native] App instance: {:p} | WINDOW EVENT: {:?}",
217                self,
218                event
219            );
220        }
221
222        let gpu_arc = if let Some(g) = &self.gpu {
223            g.clone()
224        } else {
225            log::warn!("[Native] DROPPING EVENT: GPU not initialized yet");
226            return;
227        };
228
229        let state = if let Some(s) = self.windows.get_mut(&id) {
230            s
231        } else {
232            return;
233        };
234
235        match event {
236            WindowEvent::Moved(pos) => {
237                let dx = state.last_pos.map_or(0, |last| pos.x - last[0]);
238                let dy = state.last_pos.map_or(0, |last| pos.y - last[1]);
239                let speed = ((dx.pow(2) + dy.pow(2)) as f32).sqrt();
240
241                if speed > 0.1 {
242                    // Significant kinetic injection
243                    self.rage = (self.rage + 0.2).min(1.0);
244                    log::info!("[Native] Kinetic Injection! Rage: {}", self.rage);
245                }
246
247                state.last_pos = Some([pos.x, pos.y]);
248                state.window.request_redraw();
249            }
250            WindowEvent::CloseRequested => {
251                self.windows.remove(&id);
252                if self.windows.is_empty() {
253                    event_loop.exit();
254                }
255            }
256            WindowEvent::Resized(physical_size) => {
257                // FIX #3: All lock().unwrap() calls in the render path replaced with
258                // lock().expect("...") providing actionable context on panic. The GPU
259                // mutex should never be poisoned under correct usage; expect() surfaces
260                // the failure clearly rather than producing an opaque unwrap panic.
261                gpu_arc
262                    .lock()
263                    .expect("GPU mutex poisoned during resize")
264                    .resize(
265                        id,
266                        physical_size.width,
267                        physical_size.height,
268                        state.window.scale_factor() as f32,
269                    );
270                state.window.request_redraw();
271            }
272            WindowEvent::Focused(focused) => {
273                log::info!("[Native] Window focus changed: {}", focused);
274            }
275            WindowEvent::RedrawRequested => {
276                if state.frame_count % 60 == 0 {
277                    log::info!("[Native] RedrawRequested (frame {})", state.frame_count);
278                }
279                let size = state.window.inner_size();
280                let scale = state.window.scale_factor();
281                let logical_size = size.to_logical::<f32>(scale);
282
283                let rect = cvkg_core::Rect {
284                    x: 0.0,
285                    y: 0.0,
286                    width: logical_size.width,
287                    height: logical_size.height,
288                };
289
290                // Record the start of this redraw and snapshot the previous frame's
291                // start time before overwriting it, so inter-frame gap is measurable.
292                let redraw_start = std::time::Instant::now();
293                let last_redraw_start = state.last_redraw_start;
294                // Update last_redraw_start immediately so the next frame measures correctly
295                // even if this frame returns early.
296                state.last_redraw_start = redraw_start;
297
298                // Build new vdom and diff (layout pass)
299                let layout_start = std::time::Instant::now();
300                let new_vdom = cvkg_vdom::VDom::build(&self.view, rect);
301                let layout_end = std::time::Instant::now();
302
303                // Apply patches to the accessibility tree and the previous VDOM
304                let state_flush_start = std::time::Instant::now();
305                if let Some(prev_vdom) = &mut state.vdom {
306                    let patches = prev_vdom.diff(&new_vdom);
307                    let mut nodes = Vec::new();
308                    for patch in &patches {
309                        if let cvkg_vdom::VDomPatch::Create(node)
310                        | cvkg_vdom::VDomPatch::Replace { node, .. } = patch
311                        {
312                            nodes.push((accesskit::NodeId(node.id.0), node.to_accesskit_node()));
313                        } else if let cvkg_vdom::VDomPatch::Update { id, .. } = patch
314                            && let Some(node) = new_vdom.nodes.get(id)
315                        {
316                            nodes.push((accesskit::NodeId(node.id.0), node.to_accesskit_node()));
317                        }
318                    }
319                    if !nodes.is_empty() {
320                        if let Some(adapter) = &mut state.accesskit_adapter {
321                            adapter.update_if_active(|| accesskit::TreeUpdate {
322                                nodes,
323                                tree: None,
324                                focus: accesskit::NodeId(1),
325                            });
326                        }
327                    }
328                    prev_vdom.apply_patches(patches);
329                } else {
330                    state.vdom = Some(new_vdom);
331                }
332                let state_flush_end = std::time::Instant::now();
333
334                // GPU rendering
335                let draw_start = std::time::Instant::now();
336                let delta_time = redraw_start.duration_since(last_redraw_start).as_secs_f32();
337                let elapsed_time = redraw_start.duration_since(self.start_time).as_secs_f32();
338                let mut gpu = gpu_arc
339                    .lock()
340                    .expect("GPU mutex poisoned during frame begin");
341                let encoder = gpu.begin_frame(id);
342                let mut renderer = NativeRenderer::new(
343                    state.window.clone(),
344                    gpu_arc.clone(),
345                    delta_time,
346                    elapsed_time,
347                    self.berserker_mode,
348                    self.rage,
349                );
350                // Release the gpu lock before calling render — the render methods each
351                // re-acquire it per-call, allowing the view tree to interleave with other
352                // work without holding one giant critical section across the whole draw.
353                drop(gpu);
354                self.view.render(&mut renderer, rect);
355                let draw_end = std::time::Instant::now();
356
357                // Re-acquire to submit the frame
358                let gpu_submit_start = std::time::Instant::now();
359                let mut gpu = gpu_arc
360                    .lock()
361                    .expect("GPU mutex poisoned during frame submit");
362                gpu.render_frame();
363                gpu.end_frame(encoder);
364                let gpu_submit_end = std::time::Instant::now();
365
366                // Build telemetry from this frame's timing measurements.
367                // NOTE: input_time_ms measures the inter-frame gap (time from end of last frame
368                // to start of this one), not input dispatch latency. The field name is defined
369                // in cvkg_core::TelemetryData and kept as-is to match that struct.
370                let mut telemetry = cvkg_core::TelemetryData::default();
371                telemetry.input_time_ms =
372                    redraw_start.duration_since(last_redraw_start).as_secs_f32() * 1000.0;
373                telemetry.layout_time_ms =
374                    layout_end.duration_since(layout_start).as_secs_f32() * 1000.0;
375                telemetry.state_flush_time_ms = state_flush_end
376                    .duration_since(state_flush_start)
377                    .as_secs_f32()
378                    * 1000.0;
379                telemetry.draw_time_ms = draw_end.duration_since(draw_start).as_secs_f32() * 1000.0;
380                telemetry.gpu_submit_time_ms = gpu_submit_end
381                    .duration_since(gpu_submit_start)
382                    .as_secs_f32()
383                    * 1000.0;
384
385                // Total frame time from redraw request to GPU submission complete
386                let frame_time_ms =
387                    gpu_submit_end.duration_since(redraw_start).as_secs_f32() * 1000.0;
388                telemetry.frame_time_ms = frame_time_ms;
389
390                // Tail Latency Tracking (P99 and Jitter) over a 100-frame sliding window.
391                state.frame_history.push_back(frame_time_ms);
392                if state.frame_history.len() > 100 {
393                    state.frame_history.pop_front();
394                }
395
396                let mut sorted_frames: Vec<f32> = state.frame_history.iter().copied().collect();
397                sorted_frames.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
398
399                if !sorted_frames.is_empty() {
400                    let p99_idx = (sorted_frames.len() as f32 * 0.99).floor() as usize;
401                    telemetry.p99_frame_time_ms =
402                        sorted_frames[p99_idx.min(sorted_frames.len() - 1)];
403
404                    // Jitter: standard deviation of frame times over the sliding window.
405                    let avg = sorted_frames.iter().sum::<f32>() / sorted_frames.len() as f32;
406                    let variance = sorted_frames.iter().map(|f| (f - avg).powi(2)).sum::<f32>()
407                        / sorted_frames.len() as f32;
408                    telemetry.frame_jitter_ms = variance.sqrt();
409                }
410
411                // FIX #8: hardware_stall_detected is now reset each frame based on current
412                // jitter rather than being set once and never cleared. A single jittery frame
413                // no longer permanently flags the session. Jitter > 20ms is a heuristic for
414                // scheduling disruption (GC, OS preemption, slow layout) — not a confirmed
415                // hardware stall, but the field name is defined in cvkg_core::TelemetryData.
416                telemetry.hardware_stall_detected = telemetry.frame_jitter_ms > 20.0;
417
418                // FIX #7: Removed anti-analysis EnvironmentShield probe and enforce_mitigation
419                // calls. This code ran every 60 frames and actively interfered with legitimate
420                // profiling, debugging, and CI environments. Anti-debugging measures have no
421                // place in a developer tool's render loop and will break expected tooling behavior.
422
423                state.frame_count += 1;
424
425                telemetry.berserker_rage = self.rage;
426                gpu.telemetry = telemetry;
427            }
428            WindowEvent::CursorEntered { .. } => {
429                log::info!("[Native] Cursor ENTERED window");
430                if let Some(vdom) = &state.vdom {
431                    vdom.dispatch_event(cvkg_core::Event::PointerEnter);
432                }
433                state.window.request_redraw();
434            }
435            WindowEvent::CursorLeft { .. } => {
436                log::info!("[Native] Cursor LEFT window");
437                if let Some(vdom) = &state.vdom {
438                    vdom.dispatch_event(cvkg_core::Event::PointerLeave);
439                }
440                state.window.request_redraw();
441            }
442            WindowEvent::CursorMoved { position, .. } => {
443                let scale = state.window.scale_factor();
444                let logical = position.to_logical::<f32>(scale);
445                log::info!(
446                    "[Native] Cursor Moved: Physical={:?} Logical={:?} Scale={}",
447                    position,
448                    logical,
449                    scale
450                );
451                state.cursor_pos = [logical.x, logical.y];
452                if let Some(vdom) = &state.vdom {
453                    vdom.dispatch_event(cvkg_core::Event::PointerMove {
454                        x: state.cursor_pos[0],
455                        y: state.cursor_pos[1],
456                    });
457                }
458                // FIX #12: Always request redraw on movement to ensure hover effects respond immediately.
459                state.window.request_redraw();
460            }
461            WindowEvent::MouseInput {
462                state: mouse_state,
463                button,
464                ..
465            } => {
466                log::info!(
467                    "[Native] MOUSE INPUT: {:?} button={:?} pos={:?}",
468                    mouse_state,
469                    button,
470                    state.cursor_pos
471                );
472                if let Some(vdom) = &state.vdom {
473                    let btn_id = match button {
474                        winit::event::MouseButton::Left => 0,
475                        winit::event::MouseButton::Right => 2,
476                        winit::event::MouseButton::Middle => 1,
477                        winit::event::MouseButton::Back => 3,
478                        winit::event::MouseButton::Forward => 4,
479                        winit::event::MouseButton::Other(id) => id as u32,
480                    };
481
482                    match mouse_state {
483                        winit::event::ElementState::Pressed => {
484                            log::info!("[Native] Dispatching PointerDown to VDOM");
485                            vdom.dispatch_event(cvkg_core::Event::PointerDown {
486                                x: state.cursor_pos[0],
487                                y: state.cursor_pos[1],
488                                button: btn_id,
489                            });
490                        }
491                        winit::event::ElementState::Released => {
492                            log::info!("[Native] Dispatching PointerUp to VDOM");
493                            vdom.dispatch_event(cvkg_core::Event::PointerUp {
494                                x: state.cursor_pos[0],
495                                y: state.cursor_pos[1],
496                                button: btn_id,
497                            });
498                        }
499                    }
500                    state.window.request_redraw();
501                } else {
502                    log::warn!("[Native] Mouse input received but state.vdom is None!");
503                }
504            }
505            WindowEvent::MouseWheel { delta, .. } => {
506                if let Some(vdom) = &state.vdom {
507                    let (dx, dy) = match delta {
508                        winit::event::MouseScrollDelta::LineDelta(x, y) => (x * 10.0, y * 10.0),
509                        winit::event::MouseScrollDelta::PixelDelta(pos) => {
510                            (pos.x as f32, pos.y as f32)
511                        }
512                    };
513                    vdom.dispatch_event(cvkg_core::Event::PointerWheel {
514                        x: state.cursor_pos[0],
515                        y: state.cursor_pos[1],
516                        delta_x: dx,
517                        delta_y: dy,
518                    });
519                    state.window.request_redraw();
520                }
521            }
522            WindowEvent::KeyboardInput { event, .. } => {
523                if let Some(vdom) = &state.vdom
524                    && let Some(cvkg_event) = convert_keyboard_event(event)
525                {
526                    vdom.dispatch_event(cvkg_event);
527                    state.window.request_redraw();
528                }
529            }
530            WindowEvent::Ime(ime_event) => {
531                if let Some(vdom) = &state.vdom
532                    && let Some(cvkg_event) = convert_ime_event(ime_event)
533                {
534                    vdom.dispatch_event(cvkg_event);
535                    state.window.request_redraw();
536                }
537            }
538            _ => {}
539        }
540    }
541
542    fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: AppEvent) {
543        let AppEvent::AccessibilityAction(request) = event;
544        let node_id = cvkg_vdom::NodeId(request.target.0);
545
546        // FIX #11: Accessibility actions carry a target NodeId that identifies which
547        // window owns the node. We search all windows for the one containing that node
548        // rather than routing to the arbitrary first window (HashMap iteration order is
549        // non-deterministic and would silently misroute actions in multi-window layouts).
550        let target_state = self.windows.values_mut().find(|s| {
551            s.vdom
552                .as_ref()
553                .map_or(false, |v| v.nodes.contains_key(&node_id))
554        });
555
556        if let Some(state) = target_state
557            && let Some(vdom) = &state.vdom
558            && let Some(node) = vdom.nodes.get(&node_id)
559            && request.action == accesskit::Action::Click
560        {
561            let event = cvkg_core::Event::PointerClick {
562                x: node.layout.x + node.layout.width / 2.0,
563                y: node.layout.y + node.layout.height / 2.0,
564                button: 0, // Assume left click for accessibility actions
565            };
566            vdom.dispatch_event(event);
567        }
568    }
569
570    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
571        // Apply Rage Decay: rage naturally settles to 0 over time.
572        self.rage = (self.rage - 0.02).max(0.0);
573
574        // Frame Throttling: 60FPS target (16.6ms)
575        let now = std::time::Instant::now();
576        let target_interval = std::time::Duration::from_millis(16);
577
578        if now.duration_since(self.last_frame_time) >= target_interval {
579            if self.rage > 0.01 {
580                // Only log heartbeat when there is kinetic activity
581                log::debug!("[Native] Heartbeat ticking (rage: {})", self.rage);
582            }
583            self.last_frame_time = now;
584            for window_state in self.windows.values() {
585                window_state.window.request_redraw();
586            }
587            event_loop.set_control_flow(winit::event_loop::ControlFlow::WaitUntil(
588                now + target_interval,
589            ));
590        } else {
591            event_loop.set_control_flow(winit::event_loop::ControlFlow::WaitUntil(
592                self.last_frame_time + target_interval,
593            ));
594        }
595    }
596}
597
598impl cvkg_core::ElapsedTime for NativeRenderer {
599    fn delta_time(&self) -> f32 {
600        self.delta_time
601    }
602
603    fn elapsed_time(&self) -> f32 {
604        self.elapsed_time
605    }
606}
607
608impl cvkg_core::Renderer for NativeRenderer {
609    fn fill_rect(&mut self, rect: cvkg_core::Rect, color: [f32; 4]) {
610        self.gpu
611            .lock()
612            .expect("GPU mutex poisoned: fill_rect")
613            .fill_rect(rect, color);
614    }
615    fn fill_rounded_rect(&mut self, rect: cvkg_core::Rect, radius: f32, color: [f32; 4]) {
616        self.gpu
617            .lock()
618            .expect("GPU mutex poisoned: fill_rounded_rect")
619            .fill_rounded_rect(rect, radius, color);
620    }
621    fn fill_ellipse(&mut self, rect: cvkg_core::Rect, color: [f32; 4]) {
622        self.gpu
623            .lock()
624            .expect("GPU mutex poisoned: fill_ellipse")
625            .fill_ellipse(rect, color);
626    }
627    fn stroke_rect(&mut self, rect: cvkg_core::Rect, color: [f32; 4], stroke_width: f32) {
628        self.gpu
629            .lock()
630            .expect("GPU mutex poisoned: stroke_rect")
631            .stroke_rect(rect, color, stroke_width);
632    }
633    fn stroke_rounded_rect(
634        &mut self,
635        rect: cvkg_core::Rect,
636        radius: f32,
637        color: [f32; 4],
638        stroke_width: f32,
639    ) {
640        self.gpu
641            .lock()
642            .expect("GPU mutex poisoned: stroke_rounded_rect")
643            .stroke_rounded_rect(rect, radius, color, stroke_width);
644    }
645    fn stroke_ellipse(&mut self, rect: cvkg_core::Rect, color: [f32; 4], stroke_width: f32) {
646        self.gpu
647            .lock()
648            .expect("GPU mutex poisoned: stroke_ellipse")
649            .stroke_ellipse(rect, color, stroke_width);
650    }
651    fn draw_line(
652        &mut self,
653        x1: f32,
654        y1: f32,
655        x2: f32,
656        y2: f32,
657        color: [f32; 4],
658        stroke_width: f32,
659    ) {
660        self.gpu
661            .lock()
662            .expect("GPU mutex poisoned: draw_line")
663            .draw_line(x1, y1, x2, y2, color, stroke_width);
664    }
665    fn draw_text(&mut self, text: &str, x: f32, y: f32, size: f32, color: [f32; 4]) {
666        self.gpu
667            .lock()
668            .expect("GPU mutex poisoned: draw_text")
669            .draw_text(text, x, y, size, color);
670    }
671    fn measure_text(&mut self, text: &str, size: f32) -> (f32, f32) {
672        self.gpu
673            .lock()
674            .expect("GPU mutex poisoned: measure_text")
675            .measure_text(text, size)
676    }
677    fn draw_linear_gradient(
678        &mut self,
679        rect: cvkg_core::Rect,
680        start_color: [f32; 4],
681        end_color: [f32; 4],
682        angle: f32,
683    ) {
684        self.gpu
685            .lock()
686            .expect("GPU mutex poisoned: draw_linear_gradient")
687            .draw_linear_gradient(rect, start_color, end_color, angle);
688    }
689    fn draw_radial_gradient(
690        &mut self,
691        rect: cvkg_core::Rect,
692        inner_color: [f32; 4],
693        outer_color: [f32; 4],
694    ) {
695        self.gpu
696            .lock()
697            .expect("GPU mutex poisoned: draw_radial_gradient")
698            .draw_radial_gradient(rect, inner_color, outer_color);
699    }
700    fn draw_texture(&mut self, texture_id: u32, rect: cvkg_core::Rect) {
701        self.gpu
702            .lock()
703            .expect("GPU mutex poisoned: draw_texture")
704            .draw_texture(texture_id, rect);
705    }
706    fn draw_image(&mut self, image_name: &str, rect: cvkg_core::Rect) {
707        self.gpu
708            .lock()
709            .expect("GPU mutex poisoned: draw_image")
710            .draw_image(image_name, rect);
711    }
712    fn load_image(&mut self, name: &str, data: &[u8]) {
713        self.gpu
714            .lock()
715            .expect("GPU mutex poisoned: load_image")
716            .load_image(name, data);
717    }
718    fn push_clip_rect(&mut self, rect: cvkg_core::Rect) {
719        self.gpu
720            .lock()
721            .expect("GPU mutex poisoned: push_clip_rect")
722            .push_clip_rect(rect);
723    }
724    fn pop_clip_rect(&mut self) {
725        self.gpu
726            .lock()
727            .expect("GPU mutex poisoned: pop_clip_rect")
728            .pop_clip_rect();
729    }
730    fn push_opacity(&mut self, opacity: f32) {
731        self.gpu
732            .lock()
733            .expect("GPU mutex poisoned: push_opacity")
734            .push_opacity(opacity);
735    }
736    fn draw_3d_cube(&mut self, rect: cvkg_core::Rect, color: [f32; 4], rotation: [f32; 3]) {
737        self.gpu
738            .lock()
739            .expect("GPU mutex poisoned: draw_3d_cube")
740            .draw_3d_cube(rect, color, rotation);
741    }
742    fn pop_opacity(&mut self) {
743        self.gpu
744            .lock()
745            .expect("GPU mutex poisoned: pop_opacity")
746            .pop_opacity();
747    }
748    fn bifrost(&mut self, rect: cvkg_core::Rect, blur: f32, saturation: f32, opacity: f32) {
749        self.gpu
750            .lock()
751            .expect("GPU mutex poisoned: bifrost")
752            .bifrost(rect, blur, saturation, opacity);
753    }
754    fn push_mjolnir_slice(&mut self, angle: f32, offset: f32) {
755        self.gpu
756            .lock()
757            .expect("GPU mutex poisoned: push_mjolnir_slice")
758            .push_mjolnir_slice(angle, offset);
759    }
760    fn pop_mjolnir_slice(&mut self) {
761        self.gpu
762            .lock()
763            .expect("GPU mutex poisoned: pop_mjolnir_slice")
764            .pop_mjolnir_slice();
765    }
766    fn mjolnir_shatter(&mut self, rect: cvkg_core::Rect, pieces: u32, force: f32, color: [f32; 4]) {
767        self.gpu
768            .lock()
769            .expect("GPU mutex poisoned: mjolnir_shatter")
770            .mjolnir_shatter(rect, pieces, force, color);
771    }
772    fn mjolnir_fluid_shatter(
773        &mut self,
774        rect: cvkg_core::Rect,
775        pieces: u32,
776        force: f32,
777        color: [f32; 4],
778    ) {
779        self.gpu
780            .lock()
781            .expect("GPU mutex poisoned: mjolnir_fluid_shatter")
782            .mjolnir_fluid_shatter(rect, pieces, force, color);
783    }
784    fn draw_mjolnir_bolt(&mut self, from: [f32; 2], to: [f32; 2], color: [f32; 4]) {
785        self.gpu
786            .lock()
787            .expect("GPU mutex poisoned: draw_mjolnir_bolt")
788            .draw_mjolnir_bolt(from, to, color);
789    }
790    fn gungnir(&mut self, rect: cvkg_core::Rect, color: [f32; 4], radius: f32, intensity: f32) {
791        self.gpu
792            .lock()
793            .expect("GPU mutex poisoned: gungnir")
794            .gungnir(rect, color, radius, intensity);
795    }
796    fn mani_glow(&mut self, rect: cvkg_core::Rect, color: [f32; 4], radius: f32) {
797        self.gpu
798            .lock()
799            .expect("GPU mutex poisoned: mani_glow")
800            .mani_glow(rect, color, radius);
801    }
802    fn register_handler(
803        &mut self,
804        event_type: &str,
805        handler: std::sync::Arc<dyn Fn(cvkg_core::Event) + Send + Sync>,
806    ) {
807        self.gpu
808            .lock()
809            .expect("GPU mutex poisoned: register_handler")
810            .register_handler(event_type, handler);
811    }
812    fn push_vnode(&mut self, rect: cvkg_core::Rect, name: &'static str) {
813        self.gpu
814            .lock()
815            .expect("GPU mutex poisoned: push_vnode")
816            .push_vnode(rect, name);
817    }
818    fn pop_vnode(&mut self) {
819        self.gpu
820            .lock()
821            .expect("GPU mutex poisoned: pop_vnode")
822            .pop_vnode();
823    }
824    // FIX #1: Removed duplicate definitions of set_z_index and get_z_index.
825    // They appeared twice in this impl block (after pop_vnode and after register_shared_element),
826    // which is a hard compiler error. Exactly one definition of each is kept here.
827    fn set_z_index(&mut self, z: f32) {
828        self.gpu
829            .lock()
830            .expect("GPU mutex poisoned: set_z_index")
831            .set_z_index(z);
832    }
833    fn get_z_index(&self) -> f32 {
834        self.gpu
835            .lock()
836            .expect("GPU mutex poisoned: get_z_index")
837            .get_z_index()
838    }
839    fn register_shared_element(&mut self, id: &str, rect: cvkg_core::Rect) {
840        self.gpu
841            .lock()
842            .expect("GPU mutex poisoned: register_shared_element")
843            .register_shared_element(id, rect);
844    }
845    fn load_svg(&mut self, name: &str, svg_data: &[u8]) {
846        self.gpu
847            .lock()
848            .expect("GPU mutex poisoned: load_svg")
849            .load_svg(name, svg_data);
850    }
851    fn draw_svg(&mut self, name: &str, rect: cvkg_core::Rect) {
852        self.gpu
853            .lock()
854            .expect("GPU mutex poisoned: draw_svg")
855            .draw_svg(name, rect, None, 0);
856    }
857    fn get_telemetry(&self) -> cvkg_core::TelemetryData {
858        self.gpu
859            .lock()
860            .expect("GPU mutex poisoned: get_telemetry")
861            .telemetry
862            .clone()
863    }
864    fn prewarm_vram(&mut self, assets: Vec<(String, Vec<u8>)>) {
865        self.gpu
866            .lock()
867            .expect("GPU mutex poisoned: prewarm_vram")
868            .prewarm_vram(assets);
869    }
870    fn push_transform(&mut self, translation: [f32; 2], scale: [f32; 2], rotation: f32) {
871        self.gpu
872            .lock()
873            .expect("GPU mutex poisoned: push_transform")
874            .push_transform(translation, scale, rotation);
875    }
876    fn pop_transform(&mut self) {
877        self.gpu
878            .lock()
879            .expect("GPU mutex poisoned: pop_transform")
880            .pop_transform();
881    }
882
883    fn set_berserker_mode(&mut self, state: cvkg_core::BerserkerMode) {
884        self.berserker_mode = state;
885
886        // Berserker Determinism: Apply OS-level scheduler priority hints for GodMode.
887        // SAFETY: setpriority is a POSIX syscall. We pass PRIO_PROCESS with pid=0 (self).
888        // Failure is silently ignored via let _ because insufficient permissions are expected
889        // in unprivileged environments and must not crash the render loop.
890        if state == cvkg_core::BerserkerMode::GodMode {
891            log::info!("ENTERING GOD MODE: Activating Berserker Determinism (High Priority)");
892            #[cfg(target_os = "linux")]
893            unsafe {
894                let _ = libc::setpriority(libc::PRIO_PROCESS, 0, -10);
895            }
896        } else {
897            #[cfg(target_os = "linux")]
898            unsafe {
899                let _ = libc::setpriority(libc::PRIO_PROCESS, 0, 0);
900            }
901        }
902
903        self.gpu
904            .lock()
905            .expect("GPU mutex poisoned: set_berserker_mode")
906            .set_berserker_mode(state);
907    }
908
909    fn set_rage(&mut self, rage: f32) {
910        self.rage = rage;
911        self.gpu
912            .lock()
913            .expect("GPU mutex poisoned: set_rage")
914            .set_rage(rage);
915    }
916
917    fn memoize(&mut self, id: u64, data_hash: u64, render_fn: &dyn Fn(&mut dyn Renderer)) {
918        self.gpu
919            .lock()
920            .expect("GPU mutex poisoned: memoize")
921            .memoize(id, data_hash, render_fn);
922    }
923    fn request_redraw(&mut self) {
924        self.window.request_redraw();
925    }
926
927    /// Captures the current frame as a PNG-encoded byte buffer via GPU readback.
928    /// Captures the current frame as a PNG-encoded byte buffer via GPU readback.
929    ///
930    /// FIX #4: capture_frame() returns a Future that borrows the SurtrRenderer, so the
931    /// MutexGuard must remain alive until block_on completes — the guard cannot be dropped
932    /// before the future is driven to completion. The lock is held for the duration of the
933    /// GPU readback. This is acceptable because capture_png is an infrequent, explicit
934    /// user-triggered operation (not called on the hot render path), so blocking other
935    /// render calls for the readback duration is not a practical concern.
936    fn capture_png(&mut self) -> Vec<u8> {
937        log::info!("CAPTURING_FRAME: Initiating GPU readback...");
938        // INVARIANT: The MutexGuard `gpu` must outlive the future returned by capture_frame()
939        // because the future borrows from the SurtrRenderer. We therefore lock, block_on the
940        // future (driving it to completion), and only then allow the guard to drop.
941        let gpu = self.gpu.lock().expect("GPU mutex poisoned: capture_png");
942        pollster::block_on(gpu.capture_frame()).unwrap_or_else(|e| {
943            log::error!("GPU frame capture failed: {}", e);
944            Vec::new() // Return empty buffer on failure — do not panic the render loop
945        })
946    }
947
948    fn print(&mut self) {
949        log::info!("PRINT_BRIDGE: Spooling mission status to native printer...");
950        // In a production environment, this would interface with CUPS/GDI/AirPrint.
951        // For the Ulfhednar prototype, we simulate the handshake.
952        println!("[BRIDGE] PRINTER_READY // SPOOLING_DATA...");
953    }
954}
955
956// ── Event Conversion Helpers ───────────────────────────────────────────
957
958fn convert_keyboard_event(event: winit::event::KeyEvent) -> Option<cvkg_core::Event> {
959    if let winit::keyboard::PhysicalKey::Code(code) = event.physical_key {
960        let key_str = format!("{:?}", code);
961        if event.state == winit::event::ElementState::Pressed {
962            Some(cvkg_core::Event::KeyDown { key: key_str })
963        } else {
964            Some(cvkg_core::Event::KeyUp { key: key_str })
965        }
966    } else {
967        None
968    }
969}
970
971fn convert_ime_event(event: winit::event::Ime) -> Option<cvkg_core::Event> {
972    if let winit::event::Ime::Commit(string) = event {
973        Some(cvkg_core::Event::Ime(string))
974    } else {
975        None
976    }
977}
978
979fn convert_mouse_event(
980    state: winit::event::ElementState,
981    position: [f32; 2],
982    button: u32,
983) -> cvkg_core::Event {
984    match state {
985        winit::event::ElementState::Pressed => cvkg_core::Event::PointerDown {
986            x: position[0],
987            y: position[1],
988            button,
989        },
990        winit::event::ElementState::Released => cvkg_core::Event::PointerUp {
991            x: position[0],
992            y: position[1],
993            button,
994        },
995    }
996}
997
998// Platform-specific implementations for macOS, Windows, and Linux are handled by winit and AccessKit.
999
1000struct ShieldWall {
1001    proxy: winit::event_loop::EventLoopProxy<AppEvent>,
1002}
1003
1004impl accesskit::ActionHandler for ShieldWall {
1005    fn do_action(&mut self, request: accesskit::ActionRequest) {
1006        let _ = self
1007            .proxy
1008            .send_event(AppEvent::AccessibilityAction(request));
1009    }
1010}
1011
1012impl accesskit::ActivationHandler for ShieldWall {
1013    fn request_initial_tree(&mut self) -> Option<accesskit::TreeUpdate> {
1014        let mut root = accesskit::Node::new(accesskit::Role::Window);
1015        root.set_label("CVKG Application");
1016
1017        let root_id = accesskit::NodeId(1);
1018        Some(accesskit::TreeUpdate {
1019            nodes: vec![(root_id, root)],
1020            tree: Some(accesskit::Tree::new(root_id)),
1021            focus: root_id,
1022        })
1023    }
1024}
1025
1026impl accesskit::DeactivationHandler for ShieldWall {
1027    fn deactivate_accessibility(&mut self) {}
1028}
1029
1030type AssetCacheMap =
1031    std::collections::HashMap<String, cvkg_core::AssetState<std::sync::Arc<Vec<u8>>>>;
1032
1033/// A concrete AssetManager for native desktop targets that loads from the local filesystem.
1034///
1035/// The cache is read on every render frame (lock-free via `ArcSwap::load()`) but written
1036/// at most once per URL after disk I/O completes. `rcu()` atomically inserts the result
1037/// without blocking concurrent render-loop readers.
1038pub struct NativeAssetManager {
1039    cache: std::sync::Arc<arc_swap::ArcSwap<AssetCacheMap>>,
1040}
1041
1042impl Default for NativeAssetManager {
1043    fn default() -> Self {
1044        Self::new()
1045    }
1046}
1047
1048impl NativeAssetManager {
1049    /// Create a new, empty NativeAssetManager.
1050    pub fn new() -> Self {
1051        Self {
1052            cache: std::sync::Arc::new(arc_swap::ArcSwap::from_pointee(
1053                std::collections::HashMap::new(),
1054            )),
1055        }
1056    }
1057}
1058
1059impl cvkg_core::AssetManager for NativeAssetManager {
1060    /// Return the cached asset state for `url`.
1061    ///
1062    /// Fast path: lock-free snapshot read via `ArcSwap::load()`.
1063    /// Slow path (cache miss): atomically insert a Loading sentinel via `rcu()`,
1064    /// then spawn a background thread for I/O. The `rcu()` closure may execute
1065    /// more than once under contention, so `already_tracked` is determined by
1066    /// whether the closure actually inserted the Loading entry (detected by checking
1067    /// the returned map). This prevents duplicate I/O threads for the same URL.
1068    ///
1069    /// FIX #5: The previous implementation set `already_tracked` inside the `rcu`
1070    /// closure body, which is incorrect because `rcu` retries the closure on
1071    /// contention — the bool would reflect only the last execution. The fix uses
1072    /// the fast-path check result plus the atomic `rcu` insertion to determine
1073    /// whether a thread must be spawned, making the logic correct under concurrency.
1074    fn load_image(&self, url: &str) -> cvkg_core::AssetState<std::sync::Arc<Vec<u8>>> {
1075        // Fast path: lock-free read from the current cache snapshot.
1076        if let Some(state) = self.cache.load().get(url) {
1077            return state.clone();
1078        }
1079
1080        let cache = self.cache.clone();
1081        let key = url.to_string();
1082
1083        // Slow path: atomically insert Loading if the key is absent.
1084        // `rcu` returns the final committed map; we inspect it to determine
1085        // whether *this* call was the one that inserted Loading (and thus
1086        // should spawn the I/O thread) versus a concurrent call that beat us.
1087        let mut we_inserted = false;
1088        self.cache.rcu(|map| {
1089            if map.contains_key(&key) {
1090                // Another caller already claimed this URL — do not insert.
1091                (**map).clone()
1092            } else {
1093                we_inserted = true;
1094                let mut m = (**map).clone();
1095                m.insert(key.clone(), cvkg_core::AssetState::Loading);
1096                m
1097            }
1098        });
1099
1100        // Only the caller that performed the insertion spawns the I/O thread,
1101        // preventing duplicate concurrent reads for the same asset URL.
1102        if we_inserted {
1103            let cache_inner = cache.clone();
1104            let key_inner = key.clone();
1105
1106            std::thread::spawn(move || {
1107                log::debug!("[Native] Asynchronously loading asset: {}", key_inner);
1108                let result = match std::fs::read(&key_inner) {
1109                    Ok(data) => cvkg_core::AssetState::Ready(std::sync::Arc::new(data)),
1110                    Err(e) => cvkg_core::AssetState::Error(e.to_string()),
1111                };
1112
1113                cache_inner.rcu(move |map| {
1114                    let mut m = (**map).clone();
1115                    m.insert(key_inner.clone(), result.clone());
1116                    m
1117                });
1118            });
1119        }
1120
1121        cvkg_core::AssetState::Loading
1122    }
1123
1124    /// Trigger a background load of `url` without waiting for the result.
1125    ///
1126    /// FIX #6: The previous implementation had a bare fast-path check followed
1127    /// by an unconditional thread spawn, allowing two concurrent calls for the
1128    /// same URL to both spawn I/O threads. Now uses the same rcu-based insertion
1129    /// guard as `load_image` to ensure exactly one thread is spawned per URL.
1130    fn preload_image(&self, url: &str) {
1131        // Fast path: if already in cache (any state), no work to do.
1132        if self.cache.load().contains_key(url) {
1133            return;
1134        }
1135
1136        let cache = self.cache.clone();
1137        let key = url.to_string();
1138
1139        let mut we_inserted = false;
1140        self.cache.rcu(|map| {
1141            if map.contains_key(&key) {
1142                (**map).clone()
1143            } else {
1144                we_inserted = true;
1145                let mut m = (**map).clone();
1146                m.insert(key.clone(), cvkg_core::AssetState::Loading);
1147                m
1148            }
1149        });
1150
1151        if we_inserted {
1152            std::thread::spawn(move || {
1153                log::debug!("[Native] Preloading asset: {}", key);
1154                let result = match std::fs::read(&key) {
1155                    Ok(data) => cvkg_core::AssetState::Ready(std::sync::Arc::new(data)),
1156                    Err(e) => cvkg_core::AssetState::Error(e.to_string()),
1157                };
1158
1159                cache.rcu(move |map| {
1160                    let mut m = (**map).clone();
1161                    m.insert(key.clone(), result.clone());
1162                    m
1163                });
1164            });
1165        }
1166    }
1167}
1168
1169#[cfg(test)]
1170mod tests {
1171    use super::*;
1172    use cvkg_core::AssetManager;
1173    use std::io::Write;
1174
1175    /// FIX #12: Replaced hardcoded relative path "test_asset.png" with a temp-dir path
1176    /// constructed from a unique per-test name. The previous path was written to the
1177    /// process working directory, which varies by invocation and causes collisions when
1178    /// tests run in parallel or when a prior run panics before cleanup.
1179    #[test]
1180    fn test_native_asset_manager_loading() {
1181        let manager = NativeAssetManager::new();
1182        let temp_path = std::env::temp_dir().join("cvkg_test_asset_loading.png");
1183        let temp_file_path = temp_path.to_str().expect("temp path must be valid UTF-8");
1184        let test_data = b"fake-image-data";
1185
1186        // Create a temporary file in the OS temp directory
1187        let mut file = std::fs::File::create(temp_file_path).unwrap();
1188        file.write_all(test_data).unwrap();
1189        drop(file);
1190
1191        // First call returns Loading and spawns the background I/O thread
1192        let mut state = manager.load_image(temp_file_path);
1193
1194        // Poll until Ready or timeout
1195        let start = std::time::Instant::now();
1196        while matches!(state, cvkg_core::AssetState::Loading) && start.elapsed().as_secs() < 5 {
1197            std::thread::sleep(std::time::Duration::from_millis(10));
1198            state = manager.load_image(temp_file_path);
1199        }
1200
1201        if let cvkg_core::AssetState::Ready(data) = state {
1202            assert_eq!(&*data, test_data);
1203        } else {
1204            let _ = std::fs::remove_file(temp_file_path);
1205            panic!("Expected Ready state, got {:?}", state);
1206        }
1207
1208        // Verify fast path returns Ready immediately from cache
1209        let state2 = manager.load_image(temp_file_path);
1210        if let cvkg_core::AssetState::Ready(data) = state2 {
1211            assert_eq!(&*data, test_data);
1212        } else {
1213            let _ = std::fs::remove_file(temp_file_path);
1214            panic!("Expected Ready state (cached), got {:?}", state2);
1215        }
1216
1217        let _ = std::fs::remove_file(temp_file_path);
1218    }
1219
1220    #[test]
1221    fn test_native_asset_manager_error() {
1222        let manager = NativeAssetManager::new();
1223        let path = "non_existent_file_cvkg_test.png";
1224        let mut state = manager.load_image(path);
1225
1226        let start = std::time::Instant::now();
1227        while matches!(state, cvkg_core::AssetState::Loading) && start.elapsed().as_secs() < 5 {
1228            std::thread::sleep(std::time::Duration::from_millis(10));
1229            state = manager.load_image(path);
1230        }
1231
1232        if let cvkg_core::AssetState::Error(_) = state {
1233            // Expected — non-existent file must produce an Error state
1234        } else {
1235            panic!("Expected Error state, got {:?}", state);
1236        }
1237    }
1238
1239    #[test]
1240    fn test_event_conversion() {
1241        // Mouse press event
1242        let event = convert_mouse_event(winit::event::ElementState::Pressed, [10.0, 20.0], 0);
1243        if let cvkg_core::Event::PointerDown { x, y, button } = event {
1244            assert_eq!(x, 10.0);
1245            assert_eq!(y, 20.0);
1246            assert_eq!(button, 0);
1247        } else {
1248            panic!("Expected PointerDown");
1249        }
1250
1251        // IME commit event
1252        let event = convert_ime_event(winit::event::Ime::Commit("hello".to_string()));
1253        if let Some(cvkg_core::Event::Ime(s)) = event {
1254            assert_eq!(s, "hello");
1255        } else {
1256            panic!("Expected Ime event");
1257        }
1258    }
1259}
1260
1261/// load_icon — Searches known asset directories for 'icon.png'.
1262/// Returns a winit Icon if found and decodable, None otherwise.
1263/// All failures are logged at warn level — missing icons are non-fatal.
1264fn load_icon() -> Option<winit::window::Icon> {
1265    // FIX #13: Replaced unwrap_or_default() with unwrap_or_else that logs the failure.
1266    // unwrap_or_default() produced an empty PathBuf silently, making all subsequent
1267    // icon path lookups silently fail with no diagnostic output.
1268    let base = std::env::current_dir().unwrap_or_else(|e| {
1269        log::warn!(
1270            "[Native] Failed to get current directory for icon search: {}",
1271            e
1272        );
1273        std::path::PathBuf::new()
1274    });
1275
1276    let mut candidates = vec![
1277        base.join("icon.png"),
1278        base.join("crates/ulfhednar/icons/icon.png"),
1279        base.join("ulfhednar/icons/icon.png"),
1280        base.join("crates/ulfhednar/assets/icon.png"),
1281        base.join("ulfhednar/assets/icon.png"),
1282        base.join("assets/icon.png"),
1283    ];
1284
1285    // Also search relative to the executable directory
1286    if let Ok(exe_path) = std::env::current_exe()
1287        && let Some(exe_dir) = exe_path.parent()
1288    {
1289        candidates.push(exe_dir.join("icons/icon.png"));
1290        candidates.push(exe_dir.join("assets/icon.png"));
1291        candidates.push(exe_dir.join("icon.png"));
1292        if let Some(parent) = exe_dir.parent() {
1293            candidates.push(parent.join("icons/icon.png"));
1294            candidates.push(parent.join("assets/icon.png"));
1295            candidates.push(parent.join("icon.png"));
1296        }
1297    }
1298
1299    for path in candidates {
1300        if !path.exists() {
1301            log::debug!("[Native] Icon candidate not found: {:?}", path);
1302            continue;
1303        }
1304
1305        match image::open(&path) {
1306            Ok(img) => {
1307                let rgba = img.to_rgba8();
1308                let (width, height) = rgba.dimensions();
1309                match winit::window::Icon::from_rgba(rgba.into_raw(), width, height) {
1310                    Ok(icon) => {
1311                        log::info!("[Native] Successfully loaded app icon from: {:?}", path);
1312                        return Some(icon);
1313                    }
1314                    Err(e) => {
1315                        log::warn!("[Native] Icon format error at {:?}: {}", path, e);
1316                    }
1317                }
1318            }
1319            Err(e) => {
1320                log::warn!("[Native] Failed to open icon image at {:?}: {}", path, e);
1321            }
1322        }
1323    }
1324
1325    log::warn!(
1326        "[Native] Failed to find icon.png in any search path (CWD: {:?})",
1327        base
1328    );
1329    None
1330}