hwnd 0.0.0-2024-01-05

Well documented, safe-leaning, sound, low-level API bindings to `HWND`-adjacent APIs
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
//! Associate data with an [HWnd] in a thread-local manner.
//!
//! ### Common Errors
//! *   [ERROR::INVALID_WINDOW_HANDLE]      if an [HWnd] is invalid (or, for "early" slots, is being destroyed)
//! *   [ERROR::WINDOW_OF_OTHER_THREAD]     if an [HWnd] belongs to another thread or process
//! *   [ERROR::DATATYPE_MISMATCH]          if the existing/previous value associated with a [HWnd] didn't match the expected type (a bug?)
//!
//! ### Example
//! ```
//! # use hwnd::*;
//! # use winresult::*;
//! # use std::ptr::*;
//! # let local_process_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
//! # std::thread::spawn(move ||{
//! # let local_thread_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
//! #
//! use hwnd::assoc::local::*;
//!
//! static SLOT : Slot<&'static str> = Slot::new_drop_late();
//!
//! # #[cfg(xxx)] {
//! let local_thread_hwnd   : HWnd = ..; // hwnd belonging to local thread
//! let local_process_hwnd  : HWnd = ..; // hwnd belonging to local process, another thread
//! # }
//! let remote_process_hwnd : HWnd = get_desktop_window();
//!
//! assert_eq!(None,                          SLOT.set(local_thread_hwnd, "init").unwrap());
//! assert_eq!(Some("init"),                  SLOT.set(local_thread_hwnd, "slot").unwrap());
//! assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.set(local_process_hwnd,   "X").unwrap_err());
//! assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.set(remote_process_hwnd,  "X").unwrap_err());
//! assert_eq!(ERROR::INVALID_WINDOW_HANDLE,  SLOT.set(HWnd::NULL,           "X").unwrap_err());
//!
//! assert_eq!(Some("slot"),                  SLOT.get_copy(local_thread_hwnd    ).unwrap());
//! assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.get_copy(local_process_hwnd   ).unwrap_err());
//! assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.get_copy(remote_process_hwnd  ).unwrap_err());
//! assert_eq!(ERROR::INVALID_WINDOW_HANDLE,  SLOT.get_copy(HWnd::NULL           ).unwrap_err());
//! #
//! # }).join().unwrap();
//! ```

use crate::*;

use winapi::shared::windef::*;
use winapi::um::winuser::*;

use std::any::*;
use std::cell::*;
use std::collections::*;
use std::marker::*;
use std::ptr::*;
use std::sync::{*, atomic::{*, Ordering::*}};



/// A typed slot that can be used to set or retrieve data associated with an [HWnd].
pub struct Slot<T: 'static> {
    ty:             SlotType,
    dense_slot_no:  AtomicUsize, // 0 => not set, N => dense_slot_idx = N-1
    pd:             PhantomData<std::thread::LocalKey<&'static T>>,
}

impl<T: 'static> Slot<T> {
    /// Associated data will be dropped early (before [WM::DESTROY] or [WM::NCDESTROY]) when a window is [destroyed](destroy_window).
    ///
    /// Said data will, obviously, not be accessible from within [WM::DESTROY], [WM::NCDESTROY], or similar events as a result.
    /// This can sanely be used for e.g. references to Direct3D devices and resources that should simply be dropped before a window is destroyed.
    ///
    /// ### Example
    /// ```
    /// # use hwnd::*;
    /// use hwnd::assoc::local::*;
    ///
    /// static SLOT : Slot<&'static str> = Slot::new_drop_early();
    /// ```
    pub const fn new_drop_early() -> Self { Self::new_impl(SlotType::DenseDropEarly) }

    /// Associated data will be dropped late (after [WM::DESTROY] and [WM::NCDESTROY]) when a window is [destroyed](destroy_window).
    ///
    /// Said data will generally be accessible from within [WM::DESTROY] or [WM::NCDESTROY].
    /// You might use this for data you need to manually handle the destruction of within [WM::DESTROY].
    /// It's worth noting that in some edge cases (e.g. when calling [destroy_window] from within a [destroy_window] of the same hwnd) the data will have been removed anyways.
    ///
    /// ### Example
    /// ```
    /// # use hwnd::*;
    /// use hwnd::assoc::local::*;
    ///
    /// static SLOT : Slot<&'static str> = Slot::new_drop_late();
    /// ```
    pub const fn new_drop_late()  -> Self { Self::new_impl(SlotType::DenseDropLate) }

    // TODO: set_new, \*_ref?, ...

    /// Get the data for this slot associated with `hwnd`.
    ///
    /// ### Errors
    /// *   [ERROR::INVALID_WINDOW_HANDLE]      if `hwnd` is invalid (or, for "early" slots, is being destroyed)
    /// *   [ERROR::WINDOW_OF_OTHER_THREAD]     if `hwnd` belongs to another thread or process
    /// *   [ERROR::DATATYPE_MISMATCH]          if the slot isn't a `T` (bug?)
    ///
    /// ### Example
    /// ```
    /// # use hwnd::*;
    /// # use winresult::*;
    /// # use std::ptr::*;
    /// # let local_process_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
    /// # std::thread::spawn(move ||{
    /// # let local_thread_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
    /// #
    /// use hwnd::assoc::local::*;
    ///
    /// static SLOT : Slot<&'static str> = Slot::new_drop_late();
    ///
    /// # #[cfg(xxx)] {
    /// let local_thread_hwnd   : HWnd = ..; // hwnd belonging to local thread
    /// let local_process_hwnd  : HWnd = ..; // hwnd belonging to local process, another thread
    /// # }
    /// let remote_process_hwnd : HWnd = get_desktop_window();
    ///
    /// # assert_eq!(None,                        SLOT.set(local_thread_hwnd, "slot" ).unwrap());
    /// assert_eq!(Some("slot"),                  SLOT.get_copy(local_thread_hwnd    ).unwrap());
    /// assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.get_copy(local_process_hwnd   ).unwrap_err());
    /// assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.get_copy(remote_process_hwnd  ).unwrap_err());
    /// assert_eq!(ERROR::INVALID_WINDOW_HANDLE,  SLOT.get_copy(HWnd::NULL           ).unwrap_err());
    /// #
    /// # }).join().unwrap();
    /// ```
    pub fn get_copy(&'static self, hwnd: HWnd) -> Result<Option<T>, Error> where T : Copy { self.get_clone(hwnd) }

    /// Get (and [Clone::clone]) the data for this slot associated with `hwnd`.
    ///
    /// ### Errors
    /// *   [ERROR::INVALID_WINDOW_HANDLE]      if `hwnd` is invalid (or, for "early" slots, is being destroyed)
    /// *   [ERROR::WINDOW_OF_OTHER_THREAD]     if `hwnd` belongs to another thread or process
    /// *   [ERROR::DATATYPE_MISMATCH]          if the slot isn't a `T` (bug?)
    ///
    /// ### Example
    /// ```
    /// # use hwnd::*;
    /// # use winresult::*;
    /// # use std::ptr::*;
    /// # let local_process_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
    /// # std::thread::spawn(move ||{
    /// # let local_thread_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
    /// #
    /// use hwnd::assoc::local::*;
    ///
    /// static SLOT : Slot<String> = Slot::new_drop_late();
    ///
    /// # #[cfg(xxx)] {
    /// let local_thread_hwnd   : HWnd = ..; // hwnd belonging to local thread
    /// let local_process_hwnd  : HWnd = ..; // hwnd belonging to local process, another thread
    /// # }
    /// let remote_process_hwnd : HWnd = get_desktop_window();
    ///
    /// # assert_eq!(None,                        SLOT.set(local_thread_hwnd, String::from("slot")).unwrap());
    /// assert_eq!("slot", SLOT.get_clone(local_thread_hwnd).unwrap().unwrap_or(String::new()));
    /// assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.get_clone(local_process_hwnd  ).unwrap_err());
    /// assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.get_clone(remote_process_hwnd ).unwrap_err());
    /// assert_eq!(ERROR::INVALID_WINDOW_HANDLE,  SLOT.get_clone(HWnd::NULL          ).unwrap_err());
    /// #
    /// # }).join().unwrap();
    /// ```
    pub fn get_clone(&'static self, hwnd: HWnd) -> Result<Option<T>, Error> where T : Clone {
        check_window_thread_local(hwnd)?;

        let slot_idx = self.slot_idx();
        ThreadLocal::with(move |tl| {
            let forbid_destroying = tl.global.any_early.load(Acquire) && tl.global.dense_slots.read().unwrap()[slot_idx].drop_early;

            let pw = tl.per_window.borrow();
            let pw = match pw.get(&hwnd) {
                None        => return Ok(None),
                Some(pw)    => pw,
            };

            if forbid_destroying && pw.destroying.get() { return fn_err!(ERROR::INVALID_WINDOW_HANDLE) }

            let pw_dense_slots = pw.dense_slots.borrow();
            match pw_dense_slots.get(slot_idx) {
                None                => Ok(None), // slot_idx >= dense_slots.len()
                Some(None)          => Ok(None), // dense_slots[slot_idx].is_none()
                Some(Some(slot))    => {
                    if let Some(slot_t) = slot.downcast_ref::<T>() {
                        Ok(Some((*slot_t).clone()))
                    } else {
                        fn_err!(ERROR::DATATYPE_MISMATCH)
                        // Considered these error codes:
                        //  ERROR::DATATYPE_MISMATCH    Chosen!
                        //  ERROR::INVALID_HANDLE       Kinda makes sense?  Less specific tho.
                        //  ERROR::INVALID_DATATYPE     nah: The datatype is valid, just mismatched?
                        //  ERROR::BAD_TOKEN_TYPE       nah: The token *category* (dense thread local early/late slot) is fine, just what the token references is bad
                        //  ERROR::UNSUPPORTED_TYPE     nah: The type is supported, there's just a mismatch
                    }
                }
            }
        })
    }

    /// Get the data for this slot associated with `hwnd`.
    ///
    /// ### Returns
    /// *   Ok(Some(previous_value))    if the `hwnd` previously had a value for this slot
    /// *   Ok(None)                    if the `hwnd` had no previous value for this slot
    ///
    /// ### Errors
    /// *   [ERROR::INVALID_WINDOW_HANDLE]      if `hwnd` is invalid (or, for "early" slots, is being destroyed)
    /// *   [ERROR::WINDOW_OF_OTHER_THREAD]     if `hwnd` belongs to another thread or process
    /// *   [ERROR::DATATYPE_MISMATCH]          if the previous value in the slot isn't a `T` (bug?)
    ///
    /// ### Example
    /// ```
    /// # use hwnd::*;
    /// # use winresult::*;
    /// # use std::ptr::*;
    /// # let local_process_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
    /// # std::thread::spawn(move ||{
    /// # let local_thread_hwnd = unsafe { create_window_ex_w(0, abistr::cstr16!("Message"), (), 0, 0, 0, 0, 0, HWnd::MESSAGE, null_mut(), None, null_mut()) }.unwrap();
    /// #
    /// use hwnd::assoc::local::*;
    ///
    /// static SLOT : Slot<&'static str> = Slot::new_drop_late();
    ///
    /// # #[cfg(xxx)] {
    /// let local_thread_hwnd   : HWnd = ..; // hwnd belonging to local thread
    /// let local_process_hwnd  : HWnd = ..; // hwnd belonging to local process, another thread
    /// # }
    /// let remote_process_hwnd : HWnd = get_desktop_window();
    ///
    /// assert_eq!(None,                          SLOT.set(local_thread_hwnd, "init").unwrap());
    /// assert_eq!(Some("init"),                  SLOT.set(local_thread_hwnd, "slot").unwrap());
    /// assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.set(local_process_hwnd,   "X").unwrap_err());
    /// assert_eq!(ERROR::WINDOW_OF_OTHER_THREAD, SLOT.set(remote_process_hwnd,  "X").unwrap_err());
    /// assert_eq!(ERROR::INVALID_WINDOW_HANDLE,  SLOT.set(HWnd::NULL,           "X").unwrap_err());
    /// # assert_eq!(Some("slot"),                SLOT.get_copy(local_thread_hwnd    ).unwrap());
    /// #
    /// # }).join().unwrap();
    /// ```
    pub fn set(&'static self, hwnd: HWnd, value: T) -> Result<Option<T>, Error> {
        check_window_thread_local(hwnd)?;
        let value = Box::new(value);

        let slot_idx = self.slot_idx();
        let prev = ThreadLocal::with(move |tl| {
            let forbid_destroying = tl.global.any_early.load(Acquire) && tl.global.dense_slots.read().unwrap()[slot_idx].drop_early;

            let mut pw = tl.per_window.borrow_mut();
            let pw = pw.entry(hwnd).or_default();

            if forbid_destroying && pw.destroying.get() { return fn_err!(ERROR::INVALID_WINDOW_HANDLE) }

            let mut pw_dense_slots = pw.dense_slots.borrow_mut();
            if slot_idx >= pw_dense_slots.len() { pw_dense_slots.resize_with(slot_idx+1, || None) }
            let pw_dense_slot = &mut pw_dense_slots[slot_idx];

            Ok(pw_dense_slot.replace(value))
        })?;

        match prev.map(|p| p.downcast::<T>()) {
            Some(Ok(prev))  => Ok(Some(*prev)),
            Some(Err(_))    => fn_err!(ERROR::DATATYPE_MISMATCH),
            None            => Ok(None),
        }
    }

    const fn new_impl(ty: SlotType) -> Self {
        Self {
            ty,
            dense_slot_no:  AtomicUsize::new(0),
            pd:             PhantomData,
        }
    }

    fn slot_idx(&'static self) -> usize { self.slot_no() - 1 }
    fn slot_no(&'static self) -> usize {
        // https://en.wikipedia.org/wiki/Double-checked_locking

        let s = self.dense_slot_no.load(Acquire);
        if s != 0 { return s }

        let g = Global::get();
        let mut g_dense_slots = g.dense_slots.write().unwrap(); // XXX: avoid panicing?
        let s = self.dense_slot_no.load(Relaxed);
        if s != 0 { return s }

        let drop_early = match self.ty {
            SlotType::DenseDropEarly    => true,
            SlotType::DenseDropLate     => false,
        };

        if drop_early   { g.any_early.store(true, Release); }
        else            { g.any_late .store(true, Release); }

        g_dense_slots.push(DenseSlotMeta { drop_early });
        let slot_no = g_dense_slots.len();
        self.dense_slot_no.store(slot_no, Release);
        slot_no
    }
}



#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] enum SlotType {
    DenseDropEarly,
    DenseDropLate,
}



struct ThreadLocal {
    global:     &'static Global,
    hooks:      Hooks,
    per_window: RefCell<HashMap<HWnd, PerWindow>>,
}

impl Default for ThreadLocal {
    fn default() -> Self {
        Self {
            global:     Global::get(),
            hooks:      Default::default(),
            per_window: Default::default(),
        }
    }
}

impl ThreadLocal {
    fn with<R>(f: impl FnOnce(&ThreadLocal) -> R) -> R {
        thread_local! { static TL : ThreadLocal = ThreadLocal::default(); }
        TL.with(f)
    }
}



#[derive(Default)]
struct Global {
    any_early:      AtomicBool,
    any_late:       AtomicBool,
    dense_slots:    RwLock<Vec<DenseSlotMeta>>,
}

impl Global {
    fn get() -> &'static Self {
        lazy_static::lazy_static! { static ref G : Global = Global::default(); }
        &*G
    }
}



struct DenseSlotMeta {
    drop_early: bool,
}



#[derive(Default)]
struct PerWindow {
    destroying:     Cell<bool>,
    dense_slots:    RefCell<Vec<Option<Box<dyn Any + 'static>>>>,
}

impl PerWindow {
    /// Called before [WM::GETMINMAXINFO] if data is associated with the [HWnd]
    fn before_wm_get_min_max_info(&self) {
        // slot/handle was reused
        self.destroying.set(false);
    }

    /// Called before [WM::NC_CREATE] if data is associated with the [HWnd]
    fn before_wm_nc_create(&self) {
        // slot/handle was reused
        self.destroying.set(false);
    }

    /// Called after [WM::CREATE] if data is associated with the [HWnd]
    fn after_wm_create(&self) {
    }

    /// Called before [WM::DESTROY] if data is associated with the [HWnd]
    fn before_wm_destroy(&mut self, global: &Global) {
        self.destroying.set(true);
        if !global.any_early.load(Acquire) { return }

        // XXX: abort to avoid unwinding through FFI?
        let     g_dense_slots = global.dense_slots.read().unwrap();
        let mut s_dense_slots = self.dense_slots.borrow_mut();

        for (g_dense, s_dense) in g_dense_slots.iter().zip(s_dense_slots.iter_mut()) {
            if g_dense.drop_early {
                // TODO: abort on panics?  Avoids:
                //  * unwinding across FFI boundaries
                //  * early Drop s outliving WM::DESTROY
                let _ = s_dense.take();
            }
        }
    }

    /// Called after [WM::NCDESTROY] if data is associated with the [HWnd]
    fn after_wm_nc_destroy(mut self) {
        // TODO: control drop order?
        self.dense_slots.get_mut().clear();
    }
}



struct Hooks {
    wh_cbt:             HHOOK,
    wh_callwndproc:     HHOOK,
    wh_callwndprocret:  HHOOK,
}

impl Default for Hooks {
    fn default() -> Self {
        let thread = get_current_thread_id();
        let hooks = Self {
            wh_cbt:             unsafe { SetWindowsHookExW(WH_CBT,              Some(wh_cbt),               null_mut(), thread) },
            wh_callwndproc:     unsafe { SetWindowsHookExW(WH_CALLWNDPROC,      Some(wh_callwndproc),       null_mut(), thread) },
            wh_callwndprocret:  unsafe { SetWindowsHookExW(WH_CALLWNDPROCRET,   Some(wh_callwndprocret),    null_mut(), thread) },
        };
        debug_assert!(!hooks.wh_cbt             .is_null());
        debug_assert!(!hooks.wh_callwndproc     .is_null());
        debug_assert!(!hooks.wh_callwndprocret  .is_null());
        hooks
    }
}

impl Drop for Hooks {
    fn drop(&mut self) {
        let unhook_wh_cbt               = self.wh_cbt.is_null()             || unsafe { UnhookWindowsHookEx(self.wh_cbt             ) != 0 };
        let unhook_wh_callwndproc       = self.wh_callwndproc.is_null()     || unsafe { UnhookWindowsHookEx(self.wh_callwndproc     ) != 0 };
        let unhook_wh_callwndprocret    = self.wh_callwndprocret.is_null()  || unsafe { UnhookWindowsHookEx(self.wh_callwndprocret  ) != 0 };
        debug_assert!(unhook_wh_cbt);
        debug_assert!(unhook_wh_callwndproc);
        debug_assert!(unhook_wh_callwndprocret);
    }
}

/// Require [get_current_thread_id]\(\) == [get_window_thread_id]\(hwnd\)
fn check_window_thread_local(hwnd: HWnd) -> Result<(), Error> {
    fn_context!(assoc::local::check_window_thread_local => GetWindowThreadProcessId);
    let tid = get_window_thread_id(hwnd)?;
    if get_current_thread_id() != tid { return fn_err!(ERROR::WINDOW_OF_OTHER_THREAD) }
    Ok(())
}

// TODO: catch panics to avoid unwinding across FFI boundaries?
// Rust plans to catch unwinding through extern "system", but that hasn't landed yet:
// https://github.com/rust-lang/rust/issues/52652
// Review/use: https://docs.rs/unwind_aborts/ ?

/// \[[learn.microsoft.com](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms644977(v=vs.85)) \]
unsafe extern "system" fn wh_cbt(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    let hook = ThreadLocal::with(|tl| tl.hooks.wh_cbt);

    if code >= 0 {
    }

    let lr = unsafe { CallNextHookEx(hook, code, wparam, lparam) };
    lr
}

/// \[[learn.microsoft.com](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms644975(v=vs.85)) \]
/// CallWndProc callback
unsafe extern "system" fn wh_callwndproc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    let hook = ThreadLocal::with(|tl| tl.hooks.wh_callwndproc);

    if code == HC_ACTION {
        // "Specifies whether the message was sent by the current thread. If the message was sent by the current thread, it is nonzero; otherwise, it is zero."
        // NOTE: CallWndRetProc thinks this instead indicates if the message is instead sent by the current *process*.
        let _from_current_proc_or_thread = wparam != 0;

        let call    = unsafe { &*(lparam as *const CWPSTRUCT) };
        let hwnd    = HWnd::from(call.hwnd);
        let msg     = WM32::from(call.message);

        if !call.hwnd.is_null() {
            match msg {
                WM::GETMINMAXINFO   => { ThreadLocal::with(|tl| tl.per_window.borrow    ().get    (&hwnd).map(|pw| pw.before_wm_get_min_max_info()  )); },
                WM::NCCREATE        => { ThreadLocal::with(|tl| tl.per_window.borrow    ().get    (&hwnd).map(|pw| pw.before_wm_nc_create()         )); },
                WM::DESTROY         => { ThreadLocal::with(|tl| tl.per_window.borrow_mut().get_mut(&hwnd).map(|pw| pw.before_wm_destroy(tl.global)  )); },
                _                   => {}
            }
        }
    }

    let lr = unsafe { CallNextHookEx(hook, code, wparam, lparam) };
    lr
}

/// \[[learn.microsoft.com](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-hookproc)\]
/// CallWndRetProc
unsafe extern "system" fn wh_callwndprocret(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    let hook = ThreadLocal::with(|tl| tl.hooks.wh_callwndprocret);

    if code >= 0 {
        // "Specifies whether the message is sent by the current process. If the message is sent by the current process, it is nonzero; otherwise, it is NULL."
        // NOTE: CallWndProc thinks this instead indicates if the message is instead sent by the current *thread*.
        let _from_current_proc_or_thread = wparam != 0;

        let ret     = unsafe { &*(lparam as *const CWPRETSTRUCT) };
        let hwnd    = HWnd::from(ret.hwnd);
        let msg     = WM32::from(ret.message);

        if !hwnd.is_null() {
            match msg {
                WM::CREATE      => { ThreadLocal::with(|tl| tl.per_window.borrow    ().get   (&hwnd).map(|pw| pw.after_wm_create()    )); }
                WM::NCDESTROY   => { ThreadLocal::with(|tl| tl.per_window.borrow_mut().remove(&hwnd)).map(|pw| pw.after_wm_nc_destroy()); }
                _               => {}
            }
        }
    }

    let lr = unsafe { CallNextHookEx(hook, code, wparam, lparam) };
    lr
}