moirai-pal 0.7.0

Platform Abstraction Layer for Moirai async I/O operations
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
//! Win32 handle ownership, message translation and software presentation.

use std::ffi::c_void;
use std::io;
use std::mem::size_of;
use std::time::Duration;

use windows::Win32::Foundation::{
    ERROR_CLASS_ALREADY_EXISTS, GetLastError, HINSTANCE, HWND, LPARAM, LRESULT, RECT, WAIT_FAILED,
    WAIT_TIMEOUT, WPARAM,
};
use windows::Win32::Graphics::Gdi::{HDC, UpdateWindow};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::HiDpi::{
    DPI_AWARENESS_CONTEXT, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetThreadDpiAwarenessContext,
};
use windows::Win32::UI::Input::Ime::{
    GCS_COMPSTR, GCS_RESULTSTR, ImmGetCompositionStringW, ImmGetContext, ImmReleaseContext,
};
use windows::Win32::UI::WindowsAndMessaging::{
    AdjustWindowRectEx, CS_HREDRAW, CS_VREDRAW, CreateWindowExW, DefWindowProcW, DestroyWindow,
    DispatchMessageW, GWLP_USERDATA, GetClientRect, GetWindowLongPtrW, HMENU, IDC_ARROW, IsWindow,
    LoadCursorW, MWMO_INPUTAVAILABLE, MsgWaitForMultipleObjectsEx, PM_REMOVE, PeekMessageW,
    QS_ALLINPUT, RegisterClassW, SW_SHOW, SW_SHOWMAXIMIZED, SetWindowLongPtrW, ShowWindow,
    TranslateMessage, WINDOW_EX_STYLE, WM_CHAR, WM_CLOSE, WM_COMMAND, WM_DESTROY, WM_DPICHANGED,
    WM_ERASEBKGND, WM_HOTKEY, WM_IME_COMPOSITION, WM_IME_ENDCOMPOSITION, WM_IME_STARTCOMPOSITION,
    WM_KEYDOWN, WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP,
    WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_NCCREATE, WM_NCDESTROY, WM_PAINT, WM_PRINT,
    WM_PRINTCLIENT, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETFOCUS, WM_SIZE, WM_SYSKEYDOWN, WM_SYSKEYUP,
    WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSW, WS_OVERLAPPEDWINDOW,
};
use windows::core::PCWSTR;

use super::accessibility::{
    ACCESSIBILITY_WAKE_MESSAGE, AccessibilityTree, WindowsAccessibilityAdapter,
};
use super::config::{
    MAX_COMPOSITION_UNITS, MAX_PUMP_MESSAGES, MAX_WAIT_MILLISECONDS, WindowConfig,
    WindowVisibility, allocation_error, coordinate_error, validate_frame_dimensions, windows_error,
};
use super::event::{CompositionPhase, WindowEvent};
use super::hotkey::HotkeyId;
use super::input::{
    client_point_from_wheel_lparam, extent_from_lparam, mouse_button, point_from_lparam,
    wheel_deltas,
};
use super::present::{paint, paint_frame};
use super::state::{SharedWindowState, WindowState, decode_composition};
use super::tray::{OwnedIcon, TRAY_CALLBACK_MESSAGE};

const WINDOW_CLASS_NAME: &[u16] = &[
    b'M' as u16,
    b'o' as u16,
    b'i' as u16,
    b'r' as u16,
    b'a' as u16,
    b'i' as u16,
    b'W' as u16,
    b'i' as u16,
    b'n' as u16,
    b'd' as u16,
    b'o' as u16,
    b'w' as u16,
    0,
];

/// A thread-owned native Win32 window and bounded software presenter.
pub struct NativeWindow {
    pub(crate) hwnd: HWND,
    #[expect(dead_code, reason = "the guard's Drop restores the thread context")]
    dpi_context: ThreadDpiAwarenessContext,
    pub(super) state: SharedWindowState,
    accessibility: Option<WindowsAccessibilityAdapter>,
    pub(super) visible: bool,
    pub(super) show_maximized: bool,
    pub(super) hotkeys: Vec<HotkeyId>,
    pub(super) tray_icon: Option<OwnedIcon>,
    /// Owned by the window once attached; destroyed with it.
    pub(super) menu_bar: Option<HMENU>,
    pub(super) menu_shape: Vec<usize>,
    destroyed: bool,
}

/// Restores the creating thread's DPI context when the native window leaves it.
struct ThreadDpiAwarenessContext {
    previous: DPI_AWARENESS_CONTEXT,
}

impl ThreadDpiAwarenessContext {
    fn enter() -> io::Result<Self> {
        // SAFETY: the requested context is an operating-system constant and the
        // call affects only the current thread, which owns the NativeWindow.
        let previous =
            unsafe { SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) };
        if previous.is_invalid() {
            let error = unsafe { GetLastError() };
            return Err(io::Error::from_raw_os_error(error.0 as i32));
        }
        Ok(Self { previous })
    }
}

impl Drop for ThreadDpiAwarenessContext {
    fn drop(&mut self) {
        if !self.previous.is_invalid() {
            // SAFETY: the guard is dropped with its thread-owned NativeWindow;
            // the retained opaque context came from this same thread.
            unsafe {
                SetThreadDpiAwarenessContext(self.previous);
            }
        }
    }
}

impl NativeWindow {
    /// Creates a native window using the current thread's message queue.
    ///
    /// The configured Unicode title is available even while the window is hidden.
    ///
    /// # Errors
    /// Returns the native error when class registration or window creation
    /// fails, or `InvalidInput` for invalid configuration.
    pub fn new(config: &WindowConfig) -> io::Result<Self> {
        let mut window = Self::new_hidden(config)?;
        if let Some(placement) = config.placement() {
            window.set_placement(placement)?;
        }
        if config.visibility() == WindowVisibility::Visible {
            window.show()?;
        }
        Ok(window)
    }

    fn new_hidden(config: &WindowConfig) -> io::Result<Self> {
        let dpi_context = ThreadDpiAwarenessContext::enter()?;
        let instance = register_class()?;
        let (outer_width, outer_height) = outer_dimensions(config.width(), config.height())?;
        let state = SharedWindowState::new(WindowState::new()?);
        // SAFETY: `instance`, the class/title UTF-16 buffers and the state
        // creation parameter remain valid for the complete synchronous
        // CreateWindowExW call. The window procedure adopts its own strong
        // count of the state during WM_NCCREATE and releases it in
        // WM_NCDESTROY, so the HWND never observes freed state.
        let hwnd = unsafe {
            CreateWindowExW(
                WINDOW_EX_STYLE::default(),
                PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
                PCWSTR(config.title_utf16().as_ptr()),
                WS_OVERLAPPEDWINDOW,
                0,
                0,
                outer_width,
                outer_height,
                None,
                None,
                Some(HINSTANCE::from(instance)),
                Some(state.create_param()),
            )
        }
        .map_err(windows_error)?;
        let window = Self {
            hwnd,
            dpi_context,
            state,
            accessibility: None,
            visible: false,
            show_maximized: false,
            hotkeys: Vec::new(),
            tray_icon: None,
            menu_bar: None,
            menu_shape: Vec::new(),
            destroyed: false,
        };
        let resized = window.state.with(|state| {
            state
                .events
                .iter()
                .any(|event| matches!(event, WindowEvent::Resized { .. }))
        });
        if !resized {
            let (width, height) = client_dimensions(hwnd)?;
            window
                .state
                .with(|state| state.push(WindowEvent::Resized { width, height }));
        }
        Ok(window)
    }

    /// Shows a hidden window after host adapters have been installed.
    ///
    /// # Errors
    /// Returns the native repaint error or an invalid-state error for a closed
    /// window.
    pub fn show(&mut self) -> io::Result<()> {
        if self.destroyed {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "cannot show a destroyed native window",
            ));
        }
        if self.visible {
            return Ok(());
        }
        // SAFETY: `self.hwnd` is the live handle created on this thread and the
        // calls are synchronous; no pointer is retained by either operation.
        let updated = unsafe {
            let command = if self.show_maximized {
                SW_SHOWMAXIMIZED
            } else {
                SW_SHOW
            };
            let _ = ShowWindow(self.hwnd, command);
            UpdateWindow(self.hwnd).as_bool()
        };
        if !updated {
            let error = io::Error::last_os_error();
            let _ = self.close();
            return Err(error);
        }
        self.visible = true;
        Ok(())
    }

    /// Installs the Windows accessibility adapter while the HWND is hidden.
    ///
    /// # Errors
    /// Returns an invalid-state error when the window is visible or already has
    /// an adapter, or a validation error for the supplied tree.
    pub fn install_accessibility(&mut self, tree: AccessibilityTree) -> io::Result<()> {
        if self.visible {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "native accessibility must be installed before the window is shown",
            ));
        }
        if self.accessibility.is_some() {
            return Err(io::Error::new(
                io::ErrorKind::AlreadyExists,
                "native accessibility is already installed",
            ));
        }
        self.accessibility = Some(WindowsAccessibilityAdapter::new(self.hwnd, tree)?);
        Ok(())
    }

    /// Replaces the current native accessibility tree and raises its events.
    ///
    /// # Errors
    /// Returns a validation, queue or native accessibility error.
    pub fn update_accessibility(&mut self, tree: AccessibilityTree) -> io::Result<()> {
        self.accessibility
            .as_mut()
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::NotFound,
                    "native accessibility is not installed",
                )
            })?
            .update(tree)
    }

    /// Returns whether the HWND has completed destruction.
    #[must_use]
    pub const fn is_destroyed(&self) -> bool {
        self.destroyed
    }

    /// Pumps at most [`MAX_PUMP_MESSAGES`] messages addressed to this HWND.
    ///
    /// A later call continues a larger native burst, so this method never spins
    /// indefinitely when another producer keeps posting messages.
    ///
    /// # Errors
    /// Returns an error if the bounded event queue overflowed or a native pump
    /// operation reports failure.
    pub fn poll_events(&mut self) -> io::Result<Vec<WindowEvent>> {
        if self.destroyed {
            return Ok(Vec::new());
        }
        let mut message = windows::Win32::UI::WindowsAndMessaging::MSG::default();
        for _ in 0..MAX_PUMP_MESSAGES {
            // SAFETY: `message` is writable storage owned by this call; the HWND
            // filter prevents consuming another window's queue entries.
            let present = unsafe { PeekMessageW(&mut message, Some(self.hwnd), 0, 0, PM_REMOVE) };
            if !present.as_bool() {
                break;
            }
            // SAFETY: `message` was populated by PeekMessageW and remains valid
            // for both synchronous message-dispatch calls.
            unsafe {
                let _ = TranslateMessage(&message);
                DispatchMessageW(&message);
            }
        }
        let mut events = self.state.with(|state| {
            if let Some(error) = state.error.take() {
                return Err(error);
            }
            if state.overflowed {
                state.overflowed = false;
                return Err(io::Error::other(
                    "native window event queue capacity exceeded",
                ));
            }
            Ok(state.events.drain(..).collect::<Vec<WindowEvent>>())
        })?;
        if let Some(accessibility) = self.accessibility.as_mut() {
            events.extend(
                accessibility
                    .take_actions()?
                    .into_iter()
                    .map(|request| WindowEvent::AccessibilityAction { request }),
            );
        }
        Ok(events)
    }

    /// Waits for native input for a finite duration, then returns one bounded
    /// event batch.
    ///
    /// A zero duration performs an immediate readiness check. The wait is
    /// limited to [`MAX_WAIT_MILLISECONDS`] so a caller cannot turn a window
    /// operation into an unbounded blocking point.
    ///
    /// # Errors
    /// Returns an invalid-duration or native wait error, or the same queue
    /// overflow error as [`Self::poll_events`].
    pub fn wait_events(&mut self, timeout: Duration) -> io::Result<Vec<WindowEvent>> {
        if self.destroyed {
            return Ok(Vec::new());
        }
        let milliseconds = u32::try_from(timeout.as_millis()).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "native event wait exceeds the 30 second bound",
            )
        })?;
        if milliseconds > MAX_WAIT_MILLISECONDS {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "native event wait exceeds the 30 second bound",
            ));
        }
        let pending = self
            .state
            .with(|state| !state.events.is_empty() || state.overflowed || state.error.is_some());
        if pending
            || self
                .accessibility
                .as_ref()
                .is_some_and(WindowsAccessibilityAdapter::has_pending_actions)
        {
            return self.poll_events();
        }
        // SAFETY: the call observes only this thread's message queue, accepts
        // no handles, and retains no pointer after returning.
        let result = unsafe {
            MsgWaitForMultipleObjectsEx(None, milliseconds, QS_ALLINPUT, MWMO_INPUTAVAILABLE)
        };
        if result == WAIT_FAILED {
            return Err(io::Error::last_os_error());
        }
        if result == WAIT_TIMEOUT {
            return Ok(Vec::new());
        }
        self.poll_events()
    }

    /// Destroys the window synchronously and drains its callback state.
    ///
    /// # Errors
    /// Returns the native destruction error. Calling this method after a native
    /// destroy message is harmless and reports success.
    pub fn close(&mut self) -> io::Result<()> {
        if self.destroyed {
            return Ok(());
        }
        self.release_hotkeys();
        self.release_tray_icon();
        // Remove the subclass while the HWND is still valid. The adapter's
        // destructor is thread-affine and restores the original window proc.
        self.accessibility.take();
        // SAFETY: the handle belongs to this thread and IsWindow only observes
        // the handle before the synchronous DestroyWindow call.
        if unsafe { IsWindow(Some(self.hwnd)) }.as_bool() {
            unsafe { DestroyWindow(self.hwnd) }.map_err(windows_error)?;
        }
        self.destroyed = true;
        Ok(())
    }
}

impl Drop for NativeWindow {
    fn drop(&mut self) {
        if !self.destroyed {
            self.release_hotkeys();
            self.release_tray_icon();
            self.accessibility.take();
            // Drop cannot report errors. DestroyWindow is the synchronous RAII
            // fallback. The window holds its own count of the callback state,
            // so a failed call leaves the window with valid state rather than
            // freeing it under a live handle.
            // SAFETY: the handle was created on this thread and remains owned by
            // this object until the destructor finishes.
            if unsafe { IsWindow(Some(self.hwnd)) }.as_bool() {
                let _ = unsafe { DestroyWindow(self.hwnd) };
            }
            self.destroyed = true;
        }
    }
}

fn register_class() -> io::Result<windows::Win32::Foundation::HMODULE> {
    // SAFETY: querying the current module with a null name is a process-local
    // read and returns a handle valid for the class registration lifetime.
    let instance = unsafe { GetModuleHandleW(None) }.map_err(windows_error)?;
    // SAFETY: `WINDOW_CLASS_NAME` is a static NUL-terminated UTF-16 buffer and
    // `window_proc` has the system callback ABI required by WNDCLASSW.
    let cursor = unsafe { LoadCursorW(None, IDC_ARROW) }.map_err(windows_error)?;
    let class = WNDCLASSW {
        style: CS_HREDRAW | CS_VREDRAW,
        lpfnWndProc: Some(window_proc),
        hInstance: HINSTANCE::from(instance),
        hCursor: cursor,
        lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),
        ..Default::default()
    };
    // SAFETY: `class` points to valid static strings and a function pointer for
    // the duration of this synchronous registration call.
    let atom = unsafe { RegisterClassW(&class) };
    if atom == 0 {
        // SAFETY: GetLastError reads the thread-local status set by RegisterClassW.
        let error = unsafe { GetLastError() };
        if error != ERROR_CLASS_ALREADY_EXISTS {
            return Err(io::Error::from_raw_os_error(error.0 as i32));
        }
    }
    Ok(instance)
}

unsafe extern "system" fn window_proc(
    hwnd: HWND,
    message: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> LRESULT {
    unsafe {
        if message == WM_NCCREATE {
            // SAFETY: WM_NCCREATE supplies a CREATESTRUCTW pointer for this window;
            // null checks guard malformed caller data before reading it.
            let create = lparam.0 as *const windows::Win32::UI::WindowsAndMessaging::CREATESTRUCTW;
            if create.is_null() {
                return LRESULT(0);
            }
            let create_param = (*create).lpCreateParams.cast_const();
            if create_param.is_null() {
                return LRESULT(0);
            }
            // SAFETY: the creation parameter is the live state that
            // `NativeWindow::new_hidden` lent for the synchronous
            // CreateWindowExW call. The window takes its own count here and
            // returns it in WM_NCDESTROY.
            SetWindowLongPtrW(
                hwnd,
                GWLP_USERDATA,
                SharedWindowState::adopt_create_param(create_param),
            );
            // Default creation stores the caption supplied to CreateWindowExW.
            return DefWindowProcW(hwnd, message, wparam, lparam);
        }

        // SAFETY: GWLP_USERDATA is written only by WM_NCCREATE above for this HWND
        // and cleared in WM_NCDESTROY; zero means a window not created by this
        // module, or one whose state was already released.
        let Some(state) =
            SharedWindowState::borrow_userdata(GetWindowLongPtrW(hwnd, GWLP_USERDATA))
        else {
            return DefWindowProcW(hwnd, message, wparam, lparam);
        };
        // Every access below lends the state to a closure that makes no
        // native call: a message a native call delivers re-entrantly to this
        // procedure therefore always finds the state unborrowed.
        //
        // SendInput delivers a UTF-16 surrogate pair as two WM_CHAR messages
        // with keyboard and repaint messages between them. Keep the high
        // surrogate pending across that interleave so native emoji input
        // remains one scalar instead of being replaced before its low
        // surrogate arrives. Focus and IME transitions are the boundaries
        // that terminate an incomplete text unit.
        if matches!(
            message,
            WM_KILLFOCUS
                | WM_IME_STARTCOMPOSITION
                | WM_IME_COMPOSITION
                | WM_IME_ENDCOMPOSITION
                | WM_NCDESTROY
        ) {
            state.with(WindowState::finish_text);
        }
        match message {
            WM_CLOSE => state.with(|state| state.push(WindowEvent::CloseRequested)),
            WM_HOTKEY => state.with(|state| state.push_hotkey(wparam.0)),
            WM_COMMAND => state.with(|state| state.push_menu_command(wparam.0, lparam.0)),
            TRAY_CALLBACK_MESSAGE => state.with(|state| state.push_tray(wparam.0, lparam.0)),
            WM_DESTROY => {}
            WM_SETFOCUS => state.with(|state| state.push(WindowEvent::FocusGained)),
            WM_KILLFOCUS => state.with(|state| {
                state.clear_modifiers();
                state.push(WindowEvent::FocusLost);
            }),
            WM_MOUSEMOVE => {
                let (x, y) = point_from_lparam(lparam);
                state.with(|state| state.push(WindowEvent::PointerMove { x, y }));
            }
            WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN | WM_XBUTTONDOWN => {
                let (x, y) = point_from_lparam(lparam);
                if let Some(button) = mouse_button(message, wparam) {
                    state.with(|state| state.push(WindowEvent::PointerDown { x, y, button }));
                }
            }
            WM_LBUTTONUP | WM_RBUTTONUP | WM_MBUTTONUP | WM_XBUTTONUP => {
                let (x, y) = point_from_lparam(lparam);
                if let Some(button) = mouse_button(message, wparam) {
                    state.with(|state| state.push(WindowEvent::PointerUp { x, y, button }));
                }
            }
            WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
                if let Some((delta_x, delta_y)) = wheel_deltas(message, wparam) {
                    let point = client_point_from_wheel_lparam(hwnd, lparam);
                    state.with(|state| match point {
                        Ok((x, y)) => {
                            let modifiers = state.modifiers.with_wheel_message_flags(wparam.0);
                            state.push(WindowEvent::PointerWheel {
                                x,
                                y,
                                delta_x,
                                delta_y,
                                modifiers,
                            });
                        }
                        Err(error) => state.record_error(error),
                    });
                }
            }
            message @ (WM_KEYDOWN | WM_SYSKEYDOWN) => {
                state.with(|state| push_key_event(state, wparam, lparam, true));
                // System-key messages carry Alt/menu and F10/F4 behavior that
                // DefWindowProcW must retain after the PAL records the value event.
                if message == WM_SYSKEYDOWN {
                    return DefWindowProcW(hwnd, message, wparam, lparam);
                }
            }
            message @ (WM_KEYUP | WM_SYSKEYUP) => {
                state.with(|state| push_key_event(state, wparam, lparam, false));
                if message == WM_SYSKEYUP {
                    return DefWindowProcW(hwnd, message, wparam, lparam);
                }
            }
            WM_CHAR => state.with(|state| state.push_text_unit(wparam.0 as u16)),
            WM_IME_STARTCOMPOSITION => state.with(|state| {
                state.push_composition(CompositionPhase::Started, String::new());
            }),
            WM_IME_COMPOSITION => {
                if let Err(error) = composition_message(hwnd, &state, lparam) {
                    state.with(|state| state.record_error(error));
                }
            }
            WM_IME_ENDCOMPOSITION => state.with(cancel_composition),
            WM_SIZE => {
                let (width, height) = extent_from_lparam(lparam);
                state.with(|state| state.push(WindowEvent::Resized { width, height }));
            }
            WM_DPICHANGED => {
                let dpi = (wparam.0 & 0xffff) as u32;
                if dpi != 0 {
                    state.with(|state| state.push(WindowEvent::DpiChanged { dpi }));
                }
            }
            WM_ERASEBKGND => return LRESULT(1),
            WM_PRINT => {
                // DefWindowProcW sends WM_PRINTCLIENT and WM_ERASEBKGND to this
                // window synchronously; no state is lent across the call.
                let result = DefWindowProcW(hwnd, message, wparam, lparam);
                let hdc = HDC(wparam.0 as *mut c_void);
                // SAFETY: WM_PRINT supplies a live destination HDC for the
                // synchronous full-window render.
                paint_frame(hwnd, &state, hdc);
                return result;
            }
            WM_PRINTCLIENT => {
                let hdc = HDC(wparam.0 as *mut c_void);
                // SAFETY: WM_PRINTCLIENT supplies a live destination HDC for
                // the synchronous client-area render.
                paint_frame(hwnd, &state, hdc);
            }
            WM_PAINT => {
                // SAFETY: the callback owns the live HWND for the duration of
                // the synchronous paint operation.
                paint(hwnd, &state);
            }
            WM_NCDESTROY => {
                state.with(|state| state.push(WindowEvent::Destroyed));
                // SAFETY: clearing the module-owned userdata before returning from
                // WM_NCDESTROY prevents later messages from observing stale state.
                SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
                // Release the caption and other default nonclient resources.
                let result = DefWindowProcW(hwnd, message, wparam, lparam);
                // The last message this window receives: return the count that
                // WM_NCCREATE adopted. `state` is not used afterwards.
                SharedWindowState::release_userdata(state);
                return result;
            }
            ACCESSIBILITY_WAKE_MESSAGE => {}
            _ => return DefWindowProcW(hwnd, message, wparam, lparam),
        }
        LRESULT(0)
    }
}

fn cancel_composition(state: &mut WindowState) {
    if state.composition_active {
        state.push_composition(CompositionPhase::Canceled, String::new());
    }
}

#[inline(always)]
fn push_key_event(state: &mut WindowState, wparam: WPARAM, lparam: LPARAM, pressed: bool) {
    let virtual_key = wparam.0 as u32;
    state.update_modifier(virtual_key, lparam, pressed);
    let modifiers = state.modifiers;
    if pressed {
        state.push(WindowEvent::KeyDown {
            virtual_key,
            repeated: (lparam.0 & (1 << 30)) != 0,
            modifiers,
        });
    } else {
        state.push(WindowEvent::KeyUp {
            virtual_key,
            modifiers,
        });
    }
}

fn composition_message(hwnd: HWND, state: &SharedWindowState, lparam: LPARAM) -> io::Result<()> {
    let flags = u32::try_from(lparam.0).map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "native IME composition flags are negative",
        )
    })?;
    let (phase, kind) = if flags & GCS_RESULTSTR.0 != 0 {
        (CompositionPhase::Committed, GCS_RESULTSTR)
    } else if flags & GCS_COMPSTR.0 != 0 {
        (CompositionPhase::Updated, GCS_COMPSTR)
    } else {
        state.with(cancel_composition);
        return Ok(());
    };
    let text = read_composition_text(hwnd, kind)?;
    state.with(|state| state.push_composition(phase, text));
    Ok(())
}

fn read_composition_text(
    hwnd: HWND,
    kind: windows::Win32::UI::Input::Ime::IME_COMPOSITION_STRING,
) -> io::Result<String> {
    // SAFETY: `hwnd` is the live window whose callback is executing; the IME
    // context is acquired and released synchronously on the owning thread.
    let context = unsafe { ImmGetContext(hwnd) };
    if context.is_invalid() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            "native IME composition context is unavailable",
        ));
    }
    let result = read_composition_buffer(context, kind);
    // SAFETY: `context` was returned for `hwnd` by ImmGetContext and is released
    // on the same thread before this callback returns.
    let released = unsafe { ImmReleaseContext(hwnd, context) };
    if !released.as_bool() {
        return Err(io::Error::last_os_error());
    }
    result
}

fn read_composition_buffer(
    context: windows::Win32::UI::Input::Ime::HIMC,
    kind: windows::Win32::UI::Input::Ime::IME_COMPOSITION_STRING,
) -> io::Result<String> {
    // SAFETY: the IME context is valid for this synchronous query and the null
    // destination requests only the required byte count.
    let byte_count = unsafe { ImmGetCompositionStringW(context, kind, None, 0) };
    if byte_count < 0 {
        return Err(io::Error::other(
            "native IME composition string query failed",
        ));
    }
    let byte_count = usize::try_from(byte_count).map_err(|_| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            "native IME composition length is not representable",
        )
    })?;
    if byte_count % size_of::<u16>() != 0 {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "native IME composition length is not UTF-16 aligned",
        ));
    }
    let units = byte_count / size_of::<u16>();
    if units > MAX_COMPOSITION_UNITS {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "native IME composition exceeds the bounded UTF-16 limit",
        ));
    }
    let mut buffer = Vec::new();
    buffer
        .try_reserve_exact(units)
        .map_err(|_| allocation_error())?;
    buffer.resize(units, 0);
    if byte_count != 0 {
        let length = u32::try_from(byte_count).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "native IME composition length exceeds the API bound",
            )
        })?;
        // SAFETY: `buffer` has exactly `units` initialized `u16` slots, and the
        // IME API writes exactly `length` bytes into that writable allocation.
        let read = unsafe {
            ImmGetCompositionStringW(context, kind, Some(buffer.as_mut_ptr().cast()), length)
        };
        if read < 0 || usize::try_from(read).ok() != Some(byte_count) {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "native IME composition changed during retrieval",
            ));
        }
    }
    decode_composition(&buffer)
}

pub(super) fn outer_dimensions(width: u32, height: u32) -> io::Result<(i32, i32)> {
    validate_frame_dimensions(width, height)?;
    let right = i32::try_from(width).map_err(|_| coordinate_error())?;
    let bottom = i32::try_from(height).map_err(|_| coordinate_error())?;
    let mut rect = RECT {
        right,
        bottom,
        ..Default::default()
    };
    // SAFETY: `rect` is writable storage owned by this call; the style and
    // extended style are constants, and no menu is attached to the window.
    unsafe {
        AdjustWindowRectEx(
            &mut rect,
            WS_OVERLAPPEDWINDOW,
            false,
            WINDOW_EX_STYLE::default(),
        )
    }
    .map_err(windows_error)?;
    let outer_width = rect
        .right
        .checked_sub(rect.left)
        .ok_or_else(coordinate_error)?;
    let outer_height = rect
        .bottom
        .checked_sub(rect.top)
        .ok_or_else(coordinate_error)?;
    if outer_width <= 0 || outer_height <= 0 {
        return Err(coordinate_error());
    }
    Ok((outer_width, outer_height))
}

fn client_dimensions(hwnd: HWND) -> io::Result<(u32, u32)> {
    let mut rect = RECT::default();
    // SAFETY: `rect` is writable storage owned by this call and hwnd is the
    // live handle returned by CreateWindowExW.
    unsafe { GetClientRect(hwnd, &mut rect) }.map_err(windows_error)?;
    let width = rect
        .right
        .checked_sub(rect.left)
        .ok_or_else(coordinate_error)?;
    let height = rect
        .bottom
        .checked_sub(rect.top)
        .ok_or_else(coordinate_error)?;
    Ok((
        u32::try_from(width).map_err(|_| coordinate_error())?,
        u32::try_from(height).map_err(|_| coordinate_error())?,
    ))
}