1#![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
37use cvkg_core::{FrameRenderer, Renderer};
43use image;
44use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum WindowState {
59 Normal,
61 Minimized,
63 Fullscreen,
65 SplitView,
67 Occluded,
69 Hidden,
71}
72
73pub struct WindowStateDetector {
87 state: WindowState,
88 is_key: bool,
89 is_main: bool,
90}
91
92impl WindowStateDetector {
93 pub fn new() -> Self {
95 Self {
96 state: WindowState::Normal,
97 is_key: false,
98 is_main: false,
99 }
100 }
101
102 pub fn state(&self) -> WindowState {
104 self.state
105 }
106
107 pub fn is_key(&self) -> bool {
109 self.is_key
110 }
111
112 pub fn is_main(&self) -> bool {
114 self.is_main
115 }
116
117 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 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 self.state = WindowState::Normal;
168 }
169 if self.state != old_state {
170 Some(self.state)
171 } else {
172 None
173 }
174 }
175
176 pub fn should_render(&self) -> bool {
181 !matches!(
182 self.state,
183 WindowState::Occluded | WindowState::Minimized | WindowState::Hidden
184 )
185 }
186
187 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
206pub struct ResizeHitTest {
213 window_size: winit::dpi::PhysicalSize<u32>,
215 corner_radius: f32,
217 expansion: f32,
219}
220
221impl ResizeHitTest {
222 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 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 if px <= r && py <= r {
256 return true;
257 }
258
259 if px >= w - r && py <= r {
261 return true;
262 }
263
264 if px <= r && py >= h - r {
266 return true;
267 }
268
269 if px >= w - r && py >= h - r {
271 return true;
272 }
273
274 false
275 }
276}
277
278#[derive(Debug, Clone, Copy, PartialEq)]
282pub struct SafeAreaInsets {
283 pub top: f32,
285 pub bottom: f32,
287 pub left: f32,
289 pub right: f32,
291}
292
293impl SafeAreaInsets {
294 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 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
328pub 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#[derive(Debug)]
342pub enum AppEvent {
343 AccessibilityAction(accesskit::ActionRequest),
345 CloseWindow(winit::window::WindowId),
347 SetTitle(winit::window::WindowId, String),
349 SetSize(winit::window::WindowId, f32, f32),
351 SetVisible(winit::window::WindowId, bool),
353 BringToFront(winit::window::WindowId),
355}
356
357impl NativeRenderer {
358 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 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
405struct 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 fn close(&self) {
418 let _ = self.proxy.send_event(AppEvent::CloseWindow(self.winit_id));
419 }
420
421 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 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 fn is_key(&self) -> bool {
437 self.is_key.load(std::sync::atomic::Ordering::SeqCst)
438 }
439
440 fn is_main(&self) -> bool {
442 self.is_main
443 }
444
445 fn is_visible(&self) -> bool {
447 self.window.is_visible().unwrap_or(false)
448 }
449
450 fn set_visible(&self, visible: bool) {
452 let _ = self
453 .proxy
454 .send_event(AppEvent::SetVisible(self.winit_id, visible));
455 }
456
457 fn bring_to_front(&self) {
459 let _ = self.proxy.send_event(AppEvent::BringToFront(self.winit_id));
460 }
461}
462
463pub struct WindowManager {
465 pub windows: std::collections::HashMap<winit::window::WindowId, WindowData>,
467 pub window_stack: Vec<winit::window::WindowId>,
469 pub winit_to_core: std::collections::HashMap<winit::window::WindowId, cvkg_core::WindowId>,
471 pub core_to_winit: std::collections::HashMap<cvkg_core::WindowId, winit::window::WindowId>,
473 pub next_core_id: u64,
475}
476
477impl Default for WindowManager {
478 fn default() -> Self {
479 Self::new()
480 }
481}
482
483impl WindowManager {
484 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 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 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 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 pub fn window(&self, winit_id: winit::window::WindowId) -> Option<&WindowData> {
606 self.windows.get(&winit_id)
607 }
608
609 pub fn window_mut(&mut self, winit_id: winit::window::WindowId) -> Option<&mut WindowData> {
611 self.windows.get_mut(&winit_id)
612 }
613
614 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 last_redraw_start: std::time::Instant,
627 frame_history: std::collections::VecDeque<f32>,
629 frame_count: u64,
631 last_pos: Option<[i32; 2]>,
633 is_dragging: bool,
636 drag_start_pos: [f32; 2],
638 drag_button: u32,
640 drag_threshold: f32,
642
643 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 state_detector: WindowStateDetector,
663 modifiers: winit::keyboard::ModifiersState,
665 audio_engine: Option<Arc<dyn cvkg_core::AudioEngine>>,
667 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 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 let system_theme = cvkg_core::detect_system_theme();
691 log::info!("[Native] System theme detected: {:?}", system_theme);
692
693 self.audio_engine =
695 RodioAudioEngine::new().map(|e| Arc::new(e) as Arc<dyn cvkg_core::AudioEngine>);
696
697 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, &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 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 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 } 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 } 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 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 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 let redraw_start = std::time::Instant::now();
878 let last_redraw_start = state.last_redraw_start;
879 state.last_redraw_start = redraw_start;
882
883 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 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 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 drop(gpu);
941 self.view.render(&mut renderer, rect);
942 let draw_end = std::time::Instant::now();
943
944 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 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 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 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 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 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 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 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 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 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 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 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 quit_all = true;
1230 }
1231 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 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 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 } if close_window {
1320 self.window_manager.close_window(id);
1321 }
1322 if quit_all {
1323 for wid in self.window_manager.window_order().to_vec() {
1325 self.window_manager.close_window(wid);
1326 }
1327 }
1328 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, &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, };
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 self.rage = (self.rage - 0.02).max(0.0);
1406
1407 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 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 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 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 fn capture_png(&mut self) -> Vec<u8> {
1770 log::info!("CAPTURING_FRAME: Initiating GPU readback...");
1771 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() })
1779 }
1780
1781 fn print(&mut self) {
1782 log::info!("PRINT_BRIDGE: Spooling mission status to native printer...");
1783 println!("[BRIDGE] PRINTER_READY // SPOOLING_DATA...");
1786 }
1787}
1788
1789fn 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
1834struct 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
1869pub 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 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 fn load_image(&self, url: &str) -> cvkg_core::AssetState<std::sync::Arc<Vec<u8>>> {
1911 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 let mut we_inserted = false;
1924 self.cache.rcu(|map| {
1925 if map.contains_key(&key) {
1926 (**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 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 fn preload_image(&self, url: &str) {
1967 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 #[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 let mut file = std::fs::File::create(temp_file_path).unwrap();
2024 file.write_all(test_data).unwrap();
2025 drop(file);
2026
2027 let mut state = manager.load_image(temp_file_path);
2029
2030 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 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 } else {
2071 panic!("Expected Error state, got {:?}", state);
2072 }
2073 }
2074
2075 #[test]
2076 fn test_event_conversion() {
2077 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 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
2097fn load_icon() -> Option<winit::window::Icon> {
2101 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 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
2168pub struct RodioAudioEngine {
2176 _stream: rodio::OutputStream,
2177}
2178
2179unsafe impl Send for RodioAudioEngine {}
2183unsafe impl Sync for RodioAudioEngine {}
2184
2185impl RodioAudioEngine {
2186 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 self.play_sound(name, volume);
2228 }
2229}
2230
2231pub 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}