strata-ui-platform 0.1.5

Native Hardware Abstraction Layer for Android, iOS, macOS, Windows, Linux, and Web
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! Native Windows Win32 windowing backend and hardware event loop.
//!
//! Provides a zero-dependency Win32 window implementation backed by
//! `CreateWindowExW`, standard Windows message pump (`PeekMessageW`, `DispatchMessageW`),
//! high-DPI scaling (`WM_DPICHANGED`), raw keyboard/mouse translation, and
//! hardware surface lifecycle management.

#![cfg(windows)]

use crate::events::{KeyCode, Modifiers, MouseButton, PlatformEvent};
use crate::vibrancy::{apply_vibrancy, VibrancyConfig};
use crate::window::{
    CursorIcon, EventLoop, EventLoopControl, PlatformWindow, WindowConfig, WindowDecoration,
    WindowMode,
};
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Instant;
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows_sys::Win32::Graphics::Gdi::{BeginPaint, EndPaint, InvalidateRect, PAINTSTRUCT};
use windows_sys::Win32::System::LibraryLoader::{
    GetModuleHandleA, GetModuleHandleW, GetProcAddress,
};
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
    GetKeyState, SetFocus, VK_BACK, VK_CONTROL, VK_DELETE, VK_DOWN, VK_ESCAPE, VK_LEFT, VK_MENU,
    VK_RETURN, VK_RIGHT, VK_SHIFT, VK_SPACE, VK_TAB, VK_UP,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
    AdjustWindowRectEx, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW,
    LoadCursorW, MsgWaitForMultipleObjectsEx, PeekMessageW, PostQuitMessage, RegisterClassExW,
    SetCursor, SetWindowPos, SetWindowTextW, ShowWindow, TranslateMessage, WaitMessage, CS_DBLCLKS,
    CS_HREDRAW, CS_VREDRAW, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO,
    IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_WAIT, MWMO_INPUTAVAILABLE,
    PM_REMOVE, QS_ALLINPUT, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, SW_SHOW, WM_CHAR, WM_CLOSE,
    WM_DESTROY, WM_DPICHANGED, WM_KEYDOWN, WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDBLCLK,
    WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEHWHEEL, WM_MOUSEMOVE,
    WM_MOUSEWHEEL, WM_NCHITTEST, WM_PAINT, WM_QUIT, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETFOCUS,
    WM_SIZE, WNDCLASSEXW, WS_EX_ACCEPTFILES, WS_EX_APPWINDOW, WS_EX_NOREDIRECTIONBITMAP,
    WS_OVERLAPPEDWINDOW, WS_POPUP, WS_VISIBLE,
};

/// Internal mutable window state shared with the static window procedure.
pub struct Win32WindowState {
    pub config: WindowConfig,
    pub scale_factor: f32,
    pub is_focused: bool,
    pub cursor: CursorIcon,
    pub redraw_requested: bool,
    pub event_queue: VecDeque<PlatformEvent>,
}

static WINDOW_REGISTRY: OnceLock<Mutex<HashMap<isize, Arc<Mutex<Win32WindowState>>>>> =
    OnceLock::new();

fn get_registry() -> &'static Mutex<HashMap<isize, Arc<Mutex<Win32WindowState>>>> {
    WINDOW_REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Native Win32 window implementation.
pub struct Win32Window {
    hwnd: HWND,
    title: String,
    state: Arc<Mutex<Win32WindowState>>,
}

impl Win32Window {
    /// Creates a new native Win32 window backed by `CreateWindowExW`.
    pub fn new(config: WindowConfig) -> Result<Self, String> {
        unsafe {
            let instance = GetModuleHandleW(std::ptr::null());
            let class_name: Vec<u16> = "StrataEngineWindowClass\0".encode_utf16().collect();

            // Enable Per-Monitor v2 DPI awareness if supported (Windows 10 1703+)
            static DPI_ONCE: OnceLock<()> = OnceLock::new();
            DPI_ONCE.get_or_init(|| {
                let user32 = GetModuleHandleA(b"user32.dll\0".as_ptr());
                if user32 != 0 {
                    let set_dpi_ctx = GetProcAddress(
                        user32,
                        b"SetProcessDpiAwarenessContext\0".as_ptr(),
                    );
                    if let Some(set_dpi_ctx_fn) = set_dpi_ctx {
                        let set_dpi_ctx: unsafe extern "system" fn(isize) -> windows_sys::Win32::Foundation::BOOL =
                            std::mem::transmute(set_dpi_ctx_fn);
                        // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4
                        set_dpi_ctx(-4);
                    }
                }
            });

            static REGISTER_ONCE: OnceLock<()> = OnceLock::new();
            REGISTER_ONCE.get_or_init(|| {
                let wnd_class = WNDCLASSEXW {
                    cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
                    style: CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS,
                    lpfnWndProc: Some(win32_wnd_proc),
                    cbClsExtra: 0,
                    cbWndExtra: 0,
                    hInstance: instance,
                    hIcon: 0,
                    hCursor: LoadCursorW(0, IDC_ARROW),
                    hbrBackground: 0,
                    lpszMenuName: std::ptr::null(),
                    lpszClassName: class_name.as_ptr(),
                    hIconSm: 0,
                };
                RegisterClassExW(&wnd_class);
            });

            let style = match config.decoration {
                WindowDecoration::NativeOs => WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                WindowDecoration::ClientSideDecorations
                | WindowDecoration::FramelessTransparent => WS_POPUP | WS_VISIBLE,
            };

            let ex_style = if config.transparent {
                WS_EX_APPWINDOW | WS_EX_NOREDIRECTIONBITMAP | WS_EX_ACCEPTFILES
            } else {
                WS_EX_APPWINDOW | WS_EX_ACCEPTFILES
            };

            let mut rect = RECT {
                left: 0,
                top: 0,
                right: config.width as i32,
                bottom: config.height as i32,
            };
            AdjustWindowRectEx(&mut rect, style, 0, ex_style);
            let window_w = rect.right - rect.left;
            let window_h = rect.bottom - rect.top;

            let wide_title: Vec<u16> = config
                .title
                .encode_utf16()
                .chain(std::iter::once(0))
                .collect();

            let hwnd = CreateWindowExW(
                ex_style,
                class_name.as_ptr(),
                wide_title.as_ptr(),
                style,
                0x80000000u32 as i32, // CW_USEDEFAULT
                0x80000000u32 as i32, // CW_USEDEFAULT
                window_w,
                window_h,
                0 as HWND,
                0,
                instance,
                std::ptr::null(),
            );

            if hwnd == 0 {
                return Err("CreateWindowExW failed to create Win32 window".to_string());
            }

            let hdc = windows_sys::Win32::Graphics::Gdi::GetDC(hwnd);
            let dpi = if hdc != 0 {
                let caps = windows_sys::Win32::Graphics::Gdi::GetDeviceCaps(
                    hdc,
                    windows_sys::Win32::Graphics::Gdi::LOGPIXELSY as i32,
                );
                windows_sys::Win32::Graphics::Gdi::ReleaseDC(hwnd, hdc);
                caps
            } else {
                96
            };
            let scale_factor = if dpi > 0 { dpi as f32 / 96.0 } else { 1.0 };

            let title = config.title.clone();
            let state = Arc::new(Mutex::new(Win32WindowState {
                config: config.clone(),
                scale_factor,
                is_focused: true,
                cursor: CursorIcon::Default,
                redraw_requested: true,
                event_queue: VecDeque::new(),
            }));

            // Register window in thread-safe registry for static wnd_proc routing
            get_registry()
                .lock()
                .unwrap()
                .insert(hwnd as isize, state.clone());

            // Apply backdrop vibrancy if configured
            if config.vibrancy != crate::vibrancy::VibrancyEffect::None {
                let _ = apply_vibrancy(hwnd as isize, VibrancyConfig::new(config.vibrancy));
            }

            ShowWindow(hwnd, SW_SHOW);

            Ok(Self { hwnd, title, state })
        }
    }

    /// Returns the raw Win32 `HWND` handle.
    pub fn hwnd(&self) -> HWND {
        self.hwnd
    }

    /// Presents a 32-bit BGRA buffer directly to the window client area via GDI.
    pub fn present_bgra(&self, pixels: &[u8], width: u32, height: u32) -> Result<(), String> {
        if pixels.is_empty() || width == 0 || height == 0 {
            return Ok(());
        }
        unsafe {
            let hdc = windows_sys::Win32::Graphics::Gdi::GetDC(self.hwnd);
            if hdc == 0 {
                return Err(
                    "Failed to acquire window device context (GetDC returned 0)".to_string()
                );
            }

            let bmi = windows_sys::Win32::Graphics::Gdi::BITMAPINFO {
                bmiHeader: windows_sys::Win32::Graphics::Gdi::BITMAPINFOHEADER {
                    biSize: std::mem::size_of::<windows_sys::Win32::Graphics::Gdi::BITMAPINFOHEADER>(
                    ) as u32,
                    biWidth: width as i32,
                    biHeight: -(height as i32), // top-down DIB
                    biPlanes: 1,
                    biBitCount: 32,
                    biCompression: windows_sys::Win32::Graphics::Gdi::BI_RGB,
                    biSizeImage: (width * height * 4) as u32,
                    biXPelsPerMeter: 0,
                    biYPelsPerMeter: 0,
                    biClrUsed: 0,
                    biClrImportant: 0,
                },
                bmiColors: [windows_sys::Win32::Graphics::Gdi::RGBQUAD {
                    rgbBlue: 0,
                    rgbGreen: 0,
                    rgbRed: 0,
                    rgbReserved: 0,
                }],
            };

            windows_sys::Win32::Graphics::Gdi::SetDIBitsToDevice(
                hdc,
                0,
                0,
                width,
                height,
                0,
                0,
                0,
                height,
                pixels.as_ptr() as *const _,
                &bmi,
                windows_sys::Win32::Graphics::Gdi::DIB_RGB_COLORS,
            );

            windows_sys::Win32::Graphics::Gdi::ReleaseDC(self.hwnd, hdc);
        }
        Ok(())
    }

    /// Pumps pending Win32 messages and returns any translated platform events.
    pub fn poll_native_events(&mut self) -> Vec<PlatformEvent> {
        let mut msg = unsafe { std::mem::zeroed() };
        unsafe {
            while PeekMessageW(&mut msg, self.hwnd, 0, 0, PM_REMOVE) != 0 {
                TranslateMessage(&msg);
                DispatchMessageW(&msg);
            }
        }
        self.state
            .lock()
            .unwrap()
            .event_queue
            .drain(..)
            .collect()
    }
}

impl Drop for Win32Window {
    fn drop(&mut self) {
        get_registry().lock().unwrap().remove(&(self.hwnd as isize));
        unsafe {
            DestroyWindow(self.hwnd);
        }
    }
}

impl PlatformWindow for Win32Window {
    fn title(&self) -> &str {
        &self.title
    }

    fn set_title(&mut self, title: &str) {
        self.title = title.to_string();
        let mut lock = self.state.lock().unwrap();
        lock.config.title = self.title.clone();
        let wide: Vec<u16> = title.encode_utf16().chain(std::iter::once(0)).collect();
        unsafe {
            SetWindowTextW(self.hwnd, wide.as_ptr());
        }
    }

    fn size(&self) -> (u32, u32) {
        let lock = self.state.lock().unwrap();
        (lock.config.width, lock.config.height)
    }

    fn set_size(&mut self, width: u32, height: u32) {
        {
            let mut lock = self.state.lock().unwrap();
            lock.config.width = width;
            lock.config.height = height;
            lock.event_queue
                .push_back(PlatformEvent::WindowResized { width, height });
        }
        unsafe {
            SetWindowPos(
                self.hwnd,
                0 as HWND,
                0,
                0,
                width as i32,
                height as i32,
                SWP_NOMOVE | SWP_NOZORDER,
            );
        }
    }

    fn scale_factor(&self) -> f32 {
        self.state.lock().unwrap().scale_factor
    }

    fn set_scale_factor(&mut self, scale_factor: f32) {
        let mut lock = self.state.lock().unwrap();
        lock.scale_factor = scale_factor;
        lock.event_queue
            .push_back(PlatformEvent::ScaleFactorChanged { scale_factor });
    }

    fn mode(&self) -> WindowMode {
        self.state.lock().unwrap().config.mode
    }

    fn set_mode(&mut self, mode: WindowMode) {
        let prev = self.state.lock().unwrap().config.mode;
        self.state.lock().unwrap().config.mode = mode;
        match mode {
            WindowMode::Maximized => {
                unsafe {
                    windows_sys::Win32::UI::WindowsAndMessaging::ShowWindow(
                        self.hwnd,
                        windows_sys::Win32::UI::WindowsAndMessaging::SW_MAXIMIZE,
                    );
                }
                if prev != WindowMode::Maximized {
                    self.push_event(PlatformEvent::WindowMaximized(true));
                }
            }
            WindowMode::Minimized => unsafe {
                windows_sys::Win32::UI::WindowsAndMessaging::ShowWindow(
                    self.hwnd,
                    windows_sys::Win32::UI::WindowsAndMessaging::SW_MINIMIZE,
                );
            },
            WindowMode::Windowed => {
                unsafe {
                    windows_sys::Win32::UI::WindowsAndMessaging::ShowWindow(
                        self.hwnd,
                        windows_sys::Win32::UI::WindowsAndMessaging::SW_RESTORE,
                    );
                }
                if prev == WindowMode::Maximized {
                    self.push_event(PlatformEvent::WindowMaximized(false));
                }
            }
            _ => {}
        }
    }

    fn is_focused(&self) -> bool {
        self.state.lock().unwrap().is_focused
    }

    fn set_focused(&mut self, focused: bool) {
        if focused {
            unsafe {
                SetFocus(self.hwnd);
            }
        }
    }

    fn cursor(&self) -> CursorIcon {
        self.state.lock().unwrap().cursor
    }

    fn set_cursor(&mut self, cursor: CursorIcon) {
        self.state.lock().unwrap().cursor = cursor;
        unsafe {
            let win32_cursor = match cursor {
                CursorIcon::Default => LoadCursorW(0, IDC_ARROW),
                CursorIcon::Pointer => LoadCursorW(0, IDC_HAND),
                CursorIcon::Text => LoadCursorW(0, IDC_IBEAM),
                CursorIcon::Crosshair => LoadCursorW(0, IDC_CROSS),
                CursorIcon::Move => LoadCursorW(0, IDC_SIZEALL),
                CursorIcon::NotAllowed => LoadCursorW(0, IDC_NO),
                CursorIcon::Wait => LoadCursorW(0, IDC_WAIT),
                CursorIcon::ResizeN | CursorIcon::ResizeS => LoadCursorW(0, IDC_SIZENS),
                CursorIcon::ResizeE | CursorIcon::ResizeW => LoadCursorW(0, IDC_SIZEWE),
                CursorIcon::ResizeNe | CursorIcon::ResizeSw => LoadCursorW(0, IDC_SIZENESW),
                CursorIcon::ResizeNw | CursorIcon::ResizeSe => LoadCursorW(0, IDC_SIZENWSE),
                CursorIcon::Help => LoadCursorW(0, IDC_HELP),
                _ => LoadCursorW(0, IDC_ARROW),
            };
            SetCursor(win32_cursor);
        }
    }

    fn request_redraw(&mut self) {
        self.state.lock().unwrap().redraw_requested = true;
        unsafe {
            InvalidateRect(self.hwnd, std::ptr::null(), 0);
        }
    }

    fn is_redraw_requested(&self) -> bool {
        self.state.lock().unwrap().redraw_requested
    }

    fn poll_events(&mut self) -> Vec<PlatformEvent> {
        self.poll_native_events()
    }

    fn push_event(&mut self, event: PlatformEvent) {
        self.state.lock().unwrap().event_queue.push_back(event);
    }

    fn begin_window_drag(&mut self, _x: f32, _y: f32) {
        unsafe {
            windows_sys::Win32::UI::Input::KeyboardAndMouse::ReleaseCapture();
            windows_sys::Win32::UI::WindowsAndMessaging::SendMessageW(
                self.hwnd,
                windows_sys::Win32::UI::WindowsAndMessaging::WM_SYSCOMMAND,
                (windows_sys::Win32::UI::WindowsAndMessaging::SC_MOVE | 2) as usize,
                0,
            );
        }
    }
}

impl crate::window::NativeSurfaceWindow for Win32Window {
    fn present_surface(
        &mut self,
        pixels: &[u8],
        width: u32,
        height: u32,
    ) -> Result<(), crate::surface::PresentError> {
        self.present_bgra(pixels, width, height)
            .map_err(crate::surface::PresentError::Custom)
    }
}

/// Win32 native event loop processing OS messages and driving Strata rendering.
pub struct Win32EventLoop {
    pub window: Win32Window,
    pub control: EventLoopControl,
}

impl Win32EventLoop {
    /// Creates a new Win32 event loop driving the given window.
    pub fn new(window: Win32Window) -> Self {
        Self {
            window,
            control: EventLoopControl::Poll,
        }
    }
}

impl EventLoop for Win32EventLoop {
    fn run<F>(&mut self, mut handler: F)
    where
        F: FnMut(PlatformEvent, &mut EventLoopControl),
    {
        let mut msg = unsafe { std::mem::zeroed() };
        while self.control != EventLoopControl::Exit {
            // 1. Process Win32 OS messages non-blockingly
            while unsafe { PeekMessageW(&mut msg, 0 as HWND, 0, 0, PM_REMOVE) } != 0 {
                if msg.message == WM_QUIT {
                    self.control = EventLoopControl::Exit;
                    break;
                }
                unsafe {
                    TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                }
            }

            if self.control == EventLoopControl::Exit {
                break;
            }

            // 2. Poll platform events generated by window procedure
            let events = self.window.poll_events();
            for event in events {
                handler(event, &mut self.control);
                if self.control == EventLoopControl::Exit {
                    break;
                }
            }

            // 3. Dispatch redraw frame if requested
            if self.window.is_redraw_requested() {
                self.window.state.lock().unwrap().redraw_requested = false;
                handler(PlatformEvent::RedrawRequested, &mut self.control);
            }

            // 4. Control flow and frame pacing
            match self.control {
                EventLoopControl::Poll => {
                    std::thread::yield_now();
                }
                EventLoopControl::Wait => unsafe {
                    WaitMessage();
                },
                EventLoopControl::WaitUntil(instant) => {
                    let now = Instant::now();
                    if let Some(dur) = instant.checked_duration_since(now) {
                        let ms = dur.as_millis().min(u32::MAX as u128) as u32;
                        unsafe {
                            MsgWaitForMultipleObjectsEx(
                                0,
                                std::ptr::null(),
                                ms,
                                QS_ALLINPUT,
                                MWMO_INPUTAVAILABLE,
                            );
                        }
                    }
                }
                EventLoopControl::Exit => break,
            }
        }
    }
}

unsafe extern "system" fn win32_wnd_proc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> LRESULT {
    let state_arc = {
        let registry = get_registry().lock().unwrap();
        registry.get(&(hwnd as isize)).cloned()
    };

    if let Some(state) = state_arc {
        match msg {
            WM_PAINT => {
                let mut ps: PAINTSTRUCT = std::mem::zeroed();
                let _hdc = BeginPaint(hwnd, &mut ps);
                state.lock().unwrap().redraw_requested = true;
                EndPaint(hwnd, &ps);
                return 0;
            }
            WM_SIZE => {
                let width = (lparam & 0xFFFF) as u32;
                let height = ((lparam >> 16) & 0xFFFF) as u32;
                let mut lock = state.lock().unwrap();
                lock.config.width = width;
                lock.config.height = height;
                lock.redraw_requested = true;
                lock.event_queue
                    .push_back(PlatformEvent::WindowResized { width, height });
                return 0;
            }
            WM_DPICHANGED => {
                let dpi_y = ((wparam >> 16) & 0xFFFF) as u32;
                let scale_factor = dpi_y as f32 / 96.0;
                let mut lock = state.lock().unwrap();
                lock.scale_factor = scale_factor;
                lock.redraw_requested = true;
                lock.event_queue
                    .push_back(PlatformEvent::ScaleFactorChanged { scale_factor });

                if lparam != 0 {
                    let suggested = *(lparam as *const RECT);
                    SetWindowPos(
                        hwnd,
                        0 as HWND,
                        suggested.left,
                        suggested.top,
                        suggested.right - suggested.left,
                        suggested.bottom - suggested.top,
                        SWP_NOZORDER | SWP_NOACTIVATE,
                    );
                }
                return 0;
            }
            WM_SETFOCUS => {
                let mut lock = state.lock().unwrap();
                lock.is_focused = true;
                lock.event_queue
                    .push_back(PlatformEvent::WindowFocused(true));
                return 0;
            }
            WM_KILLFOCUS => {
                let mut lock = state.lock().unwrap();
                lock.is_focused = false;
                lock.event_queue
                    .push_back(PlatformEvent::WindowFocused(false));
                return 0;
            }
            WM_NCHITTEST => {
                let lock = state.lock().unwrap();
                if lock.config.decoration == WindowDecoration::ClientSideDecorations {
                    let screen_x = (lparam & 0xFFFF) as i16 as i32;
                    let screen_y = ((lparam >> 16) & 0xFFFF) as i16 as i32;
                    let mut pt = windows_sys::Win32::Foundation::POINT {
                        x: screen_x,
                        y: screen_y,
                    };
                    unsafe {
                        windows_sys::Win32::Graphics::Gdi::ScreenToClient(hwnd, &mut pt);
                    }
                    let csd = crate::csd::CsdGeometry::default();
                    let zone = csd.hit_test(
                        lock.config.width as f32,
                        lock.config.height as f32,
                        pt.x as f32,
                        pt.y as f32,
                    );
                    return zone.to_win32_nchittest();
                }
            }
            WM_MOUSEMOVE => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::MouseMove { x, y });
                return 0;
            }
            WM_LBUTTONDBLCLK => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::DoubleClick {
                        button: MouseButton::Left,
                        x,
                        y,
                    });
                return 0;
            }
            WM_LBUTTONDOWN => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::MouseDown {
                        button: MouseButton::Left,
                        x,
                        y,
                    });
                return 0;
            }
            WM_LBUTTONUP => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::MouseUp {
                        button: MouseButton::Left,
                        x,
                        y,
                    });
                return 0;
            }
            WM_RBUTTONDOWN => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::MouseDown {
                        button: MouseButton::Right,
                        x,
                        y,
                    });
                return 0;
            }
            WM_RBUTTONUP => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::MouseUp {
                        button: MouseButton::Right,
                        x,
                        y,
                    });
                return 0;
            }
            WM_MBUTTONDOWN => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::MouseDown {
                        button: MouseButton::Middle,
                        x,
                        y,
                    });
                return 0;
            }
            WM_MBUTTONUP => {
                let x = (lparam & 0xFFFF) as i16 as f32;
                let y = ((lparam >> 16) & 0xFFFF) as i16 as f32;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::MouseUp {
                        button: MouseButton::Middle,
                        x,
                        y,
                    });
                return 0;
            }
            WM_MOUSEWHEEL => {
                let delta = ((wparam >> 16) & 0xFFFF) as i16 as f32 / 120.0;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::Scroll {
                        delta_x: 0.0,
                        delta_y: -delta,
                        is_momentum: false,
                    });
                return 0;
            }
            WM_MOUSEHWHEEL => {
                let delta = ((wparam >> 16) & 0xFFFF) as i16 as f32 / 120.0;
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::Scroll {
                        delta_x: delta,
                        delta_y: 0.0,
                        is_momentum: false,
                    });
                return 0;
            }
            WM_KEYDOWN => {
                if let Some(key) = map_virtual_key(wparam as u32) {
                    let modifiers = get_current_modifiers();
                    state
                        .lock()
                        .unwrap()
                        .event_queue
                        .push_back(PlatformEvent::KeyDown { key, modifiers });
                }
                return 0;
            }
            WM_KEYUP => {
                if let Some(key) = map_virtual_key(wparam as u32) {
                    let modifiers = get_current_modifiers();
                    state
                        .lock()
                        .unwrap()
                        .event_queue
                        .push_back(PlatformEvent::KeyUp { key, modifiers });
                }
                return 0;
            }
            WM_CHAR => {
                if let Some(ch) = char::from_u32(wparam as u32) {
                    if !ch.is_control() {
                        state
                            .lock()
                            .unwrap()
                            .event_queue
                            .push_back(PlatformEvent::ReceivedCharacter(ch));
                    }
                }
                return 0;
            }
            WM_CLOSE => {
                state
                    .lock()
                    .unwrap()
                    .event_queue
                    .push_back(PlatformEvent::WindowCloseRequested);
                return 0;
            }
            WM_DESTROY => {
                PostQuitMessage(0);
                return 0;
            }
            0x0233 => {
                // WM_DROPFILES
                let hdrop = wparam;
                let shell32 = GetModuleHandleA(b"shell32.dll\0".as_ptr());
                if shell32 != 0 && hdrop != 0 {
                    type DragQueryFileWFn =
                        unsafe extern "system" fn(usize, u32, *mut u16, u32) -> u32;
                    type DragFinishFn = unsafe extern "system" fn(usize);
                    if let Some(query_sym) = GetProcAddress(shell32, b"DragQueryFileW\0".as_ptr()) {
                        let drag_query: DragQueryFileWFn = std::mem::transmute(query_sym);
                        let count = drag_query(hdrop, 0xFFFF_FFFF, std::ptr::null_mut(), 0);
                        let mut paths = Vec::with_capacity(count as usize);
                        for idx in 0..count {
                            let len = drag_query(hdrop, idx, std::ptr::null_mut(), 0);
                            if len > 0 {
                                let mut buf = vec![0u16; (len + 1) as usize];
                                let written =
                                    drag_query(hdrop, idx, buf.as_mut_ptr(), len + 1);
                                if written > 0 {
                                    let s = String::from_utf16_lossy(&buf[..written as usize]);
                                    paths.push(std::path::PathBuf::from(s));
                                }
                            }
                        }
                        if !paths.is_empty() {
                            state
                                .lock()
                                .unwrap()
                                .event_queue
                                .push_back(PlatformEvent::FileDrop(paths));
                        }
                    }
                    if let Some(finish_sym) = GetProcAddress(shell32, b"DragFinish\0".as_ptr()) {
                        let drag_finish: DragFinishFn = std::mem::transmute(finish_sym);
                        drag_finish(hdrop);
                    }
                }
                return 0;
            }
            _ => {}
        }
    }

    DefWindowProcW(hwnd, msg, wparam, lparam)
}

unsafe fn get_current_modifiers() -> Modifiers {
    Modifiers {
        shift: (GetKeyState(VK_SHIFT as i32) as u16 & 0x8000) != 0,
        ctrl: (GetKeyState(VK_CONTROL as i32) as u16 & 0x8000) != 0,
        alt: (GetKeyState(VK_MENU as i32) as u16 & 0x8000) != 0,
        meta: false,
    }
}

fn map_virtual_key(vk: u32) -> Option<KeyCode> {
    match vk as u16 {
        VK_RETURN => Some(KeyCode::Enter),
        VK_ESCAPE => Some(KeyCode::Escape),
        VK_BACK => Some(KeyCode::Backspace),
        VK_TAB => Some(KeyCode::Tab),
        VK_SPACE => Some(KeyCode::Space),
        VK_LEFT => Some(KeyCode::ArrowLeft),
        VK_UP => Some(KeyCode::ArrowUp),
        VK_RIGHT => Some(KeyCode::ArrowRight),
        VK_DOWN => Some(KeyCode::ArrowDown),
        VK_DELETE => Some(KeyCode::Delete),
        0x30 => Some(KeyCode::Digit0),
        0x31 => Some(KeyCode::Digit1),
        0x32 => Some(KeyCode::Digit2),
        0x33 => Some(KeyCode::Digit3),
        0x34 => Some(KeyCode::Digit4),
        0x35 => Some(KeyCode::Digit5),
        0x36 => Some(KeyCode::Digit6),
        0x37 => Some(KeyCode::Digit7),
        0x38 => Some(KeyCode::Digit8),
        0x39 => Some(KeyCode::Digit9),
        0x41 => Some(KeyCode::KeyA),
        0x42 => Some(KeyCode::KeyB),
        0x43 => Some(KeyCode::KeyC),
        0x44 => Some(KeyCode::KeyD),
        0x45 => Some(KeyCode::KeyE),
        0x46 => Some(KeyCode::KeyF),
        0x47 => Some(KeyCode::KeyG),
        0x48 => Some(KeyCode::KeyH),
        0x49 => Some(KeyCode::KeyI),
        0x4A => Some(KeyCode::KeyJ),
        0x4B => Some(KeyCode::KeyK),
        0x4C => Some(KeyCode::KeyL),
        0x4D => Some(KeyCode::KeyM),
        0x4E => Some(KeyCode::KeyN),
        0x4F => Some(KeyCode::KeyO),
        0x50 => Some(KeyCode::KeyP),
        0x51 => Some(KeyCode::KeyQ),
        0x52 => Some(KeyCode::KeyR),
        0x53 => Some(KeyCode::KeyS),
        0x54 => Some(KeyCode::KeyT),
        0x55 => Some(KeyCode::KeyU),
        0x56 => Some(KeyCode::KeyV),
        0x57 => Some(KeyCode::KeyW),
        0x58 => Some(KeyCode::KeyX),
        0x59 => Some(KeyCode::KeyY),
        0x5A => Some(KeyCode::KeyZ),
        0xBF => Some(KeyCode::Slash),
        0xBC => Some(KeyCode::Comma),
        0xBE => Some(KeyCode::Period),
        0xBD => Some(KeyCode::Minus),
        0xBB => Some(KeyCode::Equals),
        0xDB => Some(KeyCode::BracketLeft),
        0xDD => Some(KeyCode::BracketRight),
        0xBA => Some(KeyCode::Semicolon),
        0xDE => Some(KeyCode::Quote),
        0xDC => Some(KeyCode::Backslash),
        0xC0 => Some(KeyCode::Backquote),
        _ => None,
    }
}