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
#![cfg(windows)]
#![no_std]

//! Rust wrapper of [ATL thunk](https://learn.microsoft.com/en-us/windows/win32/api/atlthunk/) type.

use ::windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use ::windows::Win32::System::Memory::AtlThunkData_t;
use ::windows::Win32::UI::WindowsAndMessaging::WNDPROC;
use core::ffi::c_void;
use core::mem;
use core::ptr::NonNull;

pub mod windows {
    pub use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
}

#[cfg_attr(
    target_arch = "x86",
    link(
        name = "atlthunk.dll",
        kind = "raw-dylib",
        modifiers = "+verbatim",
        import_name_type = "undecorated"
    )
)]
#[cfg_attr(
    not(target_arch = "x86"),
    link(name = "atlthunk.dll", kind = "raw-dylib", modifiers = "+verbatim")
)]
extern "system" {
    /// <https://learn.microsoft.com/en-us/windows/win32/api/atlthunk/nf-atlthunk-atlthunk_allocatedata>.
    fn AtlThunk_AllocateData() -> *mut AtlThunkData_t;

    /// <https://learn.microsoft.com/en-us/windows/win32/api/atlthunk/nf-atlthunk-atlthunk_datatocode>.
    fn AtlThunk_DataToCode(thunk: *mut AtlThunkData_t) -> WNDPROC;

    /// <https://learn.microsoft.com/en-us/windows/win32/api/atlthunk/nf-atlthunk-atlthunk_freedata>.
    fn AtlThunk_FreeData(thunk: *mut AtlThunkData_t);

    /// <https://learn.microsoft.com/en-us/windows/win32/api/atlthunk/nf-atlthunk-atlthunk_initdata>.
    fn AtlThunk_InitData(thunk: *mut AtlThunkData_t, proc: *mut c_void, first_parameter: usize);
}

type RawWindowProcedure<T> = unsafe extern "system" fn(T, u32, WPARAM, LPARAM) -> LRESULT;

/// Rust wrapper of [ATL thunk](https://learn.microsoft.com/en-us/windows/win32/api/atlthunk/) type. It is used as
/// a [window procedure](https://learn.microsoft.com/en-us/windows/win32/winmsg/about-window-procedures) with associated
/// data.
pub struct AtlThunk {
    thunk: NonNull<AtlThunkData_t>,
}

impl AtlThunk {
    /// Creates a new [`AtlThunk`] object.
    pub fn try_new(procedure: RawWindowProcedure<usize>, first_parameter: usize) -> ::windows::core::Result<Self> {
        let thunk = unsafe { AtlThunk_AllocateData() };

        let Some(thunk) = NonNull::new(thunk) else {
            return Err(::windows::core::Error::from_win32());
        };

        let mut result = Self { thunk };

        result.set_data(procedure, first_parameter);

        Ok(result)
    }

    /// Returns a wrapped window procedure. The returned function pointer is only valid before the corresponding
    /// [`AtlThunk`] object drops.
    #[inline(always)]
    pub fn as_raw_window_procedure(&self) -> RawWindowProcedure<HWND> {
        unsafe { AtlThunk_DataToCode(self.thunk.as_ptr()).unwrap_unchecked() }
    }

    /// Updates the associated window procedure and data.
    #[inline(always)]
    pub fn set_data(&mut self, procedure: RawWindowProcedure<usize>, first_parameter: usize) {
        unsafe {
            #[expect(clippy::transmutes_expressible_as_ptr_casts, reason = "by-design")]
            let procedure = mem::transmute::<RawWindowProcedure<usize>, *mut c_void>(procedure);

            AtlThunk_InitData(self.thunk.as_mut(), procedure, first_parameter);
        }
    }
}

impl Drop for AtlThunk {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe { AtlThunk_FreeData(self.thunk.as_ptr()) };
    }
}

unsafe impl Send for AtlThunk {}
unsafe impl Sync for AtlThunk {}

#[cfg(test)]
mod tests {
    use super::AtlThunk;
    use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};

    #[test]
    fn test_thunk() {
        unsafe extern "system" fn callback_1(
            first_parameter: usize,
            message: u32,
            w_param: WPARAM,
            l_param: LPARAM,
        ) -> LRESULT {
            assert_eq!(first_parameter, 2);
            assert_eq!(message, 3);
            assert_eq!(w_param.0, 5);
            assert_eq!(l_param.0, 7);

            LRESULT(11)
        }

        unsafe extern "system" fn callback_2(
            first_parameter: usize,
            message: u32,
            w_param: WPARAM,
            l_param: LPARAM,
        ) -> LRESULT {
            assert_eq!(first_parameter, 13);
            assert_eq!(message, 17);
            assert_eq!(w_param.0, 19);
            assert_eq!(l_param.0, 23);

            LRESULT(29)
        }

        let mut thunk = AtlThunk::try_new(callback_1, 2).unwrap();

        assert_eq!(
            unsafe { thunk.as_raw_window_procedure()(HWND::default(), 3, WPARAM(5), LPARAM(7)) }.0,
            11,
        );

        thunk.set_data(callback_2, 13);

        assert_eq!(
            unsafe { thunk.as_raw_window_procedure()(HWND::default(), 17, WPARAM(19), LPARAM(23)) }.0,
            29,
        );
    }
}