windows-api-utils 0.2.0

Windows API utilities for coordinate conversion, bit operations, and message parameter handling with feature gating
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
//! Windows message parameter handling.
//!
//! This module provides types and utilities for working with
//! Windows message parameters (WPARAM, LPARAM) and common messages.
//!
//! Requires the `messages` feature to be enabled.

use core::fmt;

/// Windows message parameter - 完全匹配 windows crate 的 WPARAM
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WPARAM(pub usize);

/// Windows message parameter - 完全匹配 windows crate 的 LPARAM
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LPARAM(pub isize);

/// Message result type - 完全匹配 windows crate 的 LRESULT
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LRESULT(pub isize);

/// Newtype wrapper for WPARAM with utility methods.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WParam(pub WPARAM);

impl WParam {
    /// Creates a new WPARAM wrapper.
    pub const fn new(value: usize) -> Self {
        Self(WPARAM(value))
    }

    /// Returns the raw value.
    pub const fn raw(&self) -> WPARAM {
        self.0
    }

    /// Returns the inner usize value.
    pub const fn as_usize(&self) -> usize {
        self.0 .0
    }

    /// Converts to u32 (truncating on 64-bit platforms).
    pub fn as_u32(&self) -> u32 {
        self.0 .0 as u32
    }

    /// Converts to i32 (truncating on 64-bit platforms).
    pub fn as_i32(&self) -> i32 {
        self.0 .0 as i32
    }
}

impl From<usize> for WParam {
    fn from(value: usize) -> Self {
        Self::new(value)
    }
}

impl From<WParam> for usize {
    fn from(wparam: WParam) -> Self {
        wparam.as_usize()
    }
}

impl fmt::Display for WParam {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "WPARAM(0x{:X})", self.0 .0)
    }
}

/// Newtype wrapper for LPARAM with utility methods.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct LParam(pub LPARAM);

impl LParam {
    /// Creates a new LPARAM wrapper.
    pub const fn new(value: isize) -> Self {
        Self(LPARAM(value))
    }

    /// Returns the raw value.
    pub const fn raw(&self) -> LPARAM {
        self.0
    }

    /// Returns the inner isize value.
    pub const fn as_isize(&self) -> isize {
        self.0 .0
    }

    /// Converts to u32 (truncating on 64-bit platforms).
    pub fn as_u32(&self) -> u32 {
        self.0 .0 as u32
    }

    /// Converts to i32 (truncating on 64-bit platforms).
    pub fn as_i32(&self) -> i32 {
        self.0 .0 as i32
    }

    /// Extracts coordinates from LPARAM (for mouse messages).
    pub fn as_point(&self) -> (i16, i16) {
        let value = self.as_u32();
        ((value & 0xFFFF) as i16, ((value >> 16) & 0xFFFF) as i16)
    }

    /// Creates LPARAM from coordinates.
    pub fn from_point(x: i16, y: i16) -> Self {
        let value = ((y as u32) << 16) | (x as u32 & 0xFFFF);
        Self::new(value as isize)
    }
}

impl From<isize> for LParam {
    fn from(value: isize) -> Self {
        Self::new(value)
    }
}

impl From<LParam> for isize {
    fn from(lparam: LParam) -> Self {
        lparam.as_isize()
    }
}

impl fmt::Display for LParam {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "LPARAM(0x{:X})", self.0 .0)
    }
}

/// Mouse button enumeration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MouseButton {
    /// Left mouse button
    Left,
    /// Right mouse button
    Right,
    /// Middle mouse button
    Middle,
    /// X1 button (back)
    X1,
    /// X2 button (forward)
    X2,
}

/// Keyboard modifier keys.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct KeyModifiers {
    /// Shift key pressed
    pub shift: bool,
    /// Control key pressed
    pub ctrl: bool,
    /// Alt key pressed
    pub alt: bool,
}

/// Mouse event information.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MouseEvent {
    /// X coordinate
    pub x: i32,
    /// Y coordinate
    pub y: i32,
    /// Mouse button (if any)
    pub button: Option<MouseButton>,
    /// Modifier keys
    pub modifiers: KeyModifiers,
}

/// Keyboard event information.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct KeyEvent {
    /// Virtual key code
    pub virtual_key: u16,
    /// Scan code
    pub scan_code: u16,
    /// Modifier keys
    pub modifiers: KeyModifiers,
    /// Repeat count
    pub repeat_count: u16,
}

/// Windows message structure.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WindowMessage {
    /// Message identifier
    pub msg: u32,
    /// WPARAM parameter
    pub wparam: WParam,
    /// LPARAM parameter
    pub lparam: LParam,
}

impl WindowMessage {
    /// Creates a new window message.
    pub const fn new(msg: u32, wparam: WParam, lparam: LParam) -> Self {
        Self {
            msg,
            wparam,
            lparam,
        }
    }

    /// Creates a mouse movement message.
    pub fn mouse_move(x: i16, y: i16, modifiers: KeyModifiers) -> Self {
        let wparam = Self::make_mouse_wparam(modifiers, None);
        let lparam = LParam::from_point(x, y);
        Self::new(windows_messages::WM_MOUSEMOVE, wparam, lparam)
    }

    /// Creates a mouse button message.
    pub fn mouse_button(
        button: MouseButton,
        pressed: bool,
        x: i16,
        y: i16,
        modifiers: KeyModifiers,
    ) -> Self {
        let msg = match (button, pressed) {
            (MouseButton::Left, true) => windows_messages::WM_LBUTTONDOWN,
            (MouseButton::Left, false) => windows_messages::WM_LBUTTONUP,
            (MouseButton::Right, true) => windows_messages::WM_RBUTTONDOWN,
            (MouseButton::Right, false) => windows_messages::WM_RBUTTONUP,
            (MouseButton::Middle, true) => windows_messages::WM_MBUTTONDOWN,
            (MouseButton::Middle, false) => windows_messages::WM_MBUTTONUP,
            _ => windows_messages::WM_MOUSEMOVE,
        };

        let wparam = Self::make_mouse_wparam(modifiers, Some(button));
        let lparam = LParam::from_point(x, y);
        Self::new(msg, wparam, lparam)
    }

    /// Creates a keyboard message.
    pub fn key_event(msg: u32, virtual_key: u16, scan_code: u16, repeat_count: u16) -> Self {
        let wparam = WParam::new(virtual_key as usize);
        let lparam_value = (((scan_code as u32) << 16) | (repeat_count as u32)) as isize;
        Self::new(msg, wparam, LParam::new(lparam_value))
    }

    fn make_mouse_wparam(modifiers: KeyModifiers, button: Option<MouseButton>) -> WParam {
        let mut wparam = 0u32;

        if modifiers.shift {
            wparam |= 0x0004; // MK_SHIFT
        }
        if modifiers.ctrl {
            wparam |= 0x0008; // MK_CONTROL
        }

        if let Some(button) = button {
            match button {
                MouseButton::Left => wparam |= 0x0001,   // MK_LBUTTON
                MouseButton::Right => wparam |= 0x0002,  // MK_RBUTTON
                MouseButton::Middle => wparam |= 0x0010, // MK_MBUTTON
                MouseButton::X1 => wparam |= 0x0020,     // MK_XBUTTON1
                MouseButton::X2 => wparam |= 0x0040,     // MK_XBUTTON2
            }
        }

        WParam::new(wparam as usize)
    }
}

/// Parser for Windows message parameters.
pub struct MessageParser;

impl MessageParser {
    /// Parses a mouse message.
    pub fn parse_mouse_message(message: WindowMessage) -> Option<MouseEvent> {
        match message.msg {
            windows_messages::WM_MOUSEMOVE
            | windows_messages::WM_LBUTTONDOWN
            | windows_messages::WM_LBUTTONUP
            | windows_messages::WM_RBUTTONDOWN
            | windows_messages::WM_RBUTTONUP
            | windows_messages::WM_MBUTTONDOWN
            | windows_messages::WM_MBUTTONUP => {
                let (x, y) = message.lparam.as_point();
                let wparam = message.wparam.as_u32();

                let modifiers = KeyModifiers {
                    shift: (wparam & 0x0004) != 0,
                    ctrl: (wparam & 0x0008) != 0,
                    alt: false, // ALT state not in wparam
                };

                let button = match message.msg {
                    windows_messages::WM_LBUTTONDOWN | windows_messages::WM_LBUTTONUP => {
                        Some(MouseButton::Left)
                    }
                    windows_messages::WM_RBUTTONDOWN | windows_messages::WM_RBUTTONUP => {
                        Some(MouseButton::Right)
                    }
                    windows_messages::WM_MBUTTONDOWN | windows_messages::WM_MBUTTONUP => {
                        Some(MouseButton::Middle)
                    }
                    _ => None,
                };

                Some(MouseEvent {
                    x: x as i32,
                    y: y as i32,
                    button,
                    modifiers,
                })
            }
            _ => None,
        }
    }

    /// Parses a keyboard message.
    pub fn parse_key_message(message: WindowMessage) -> Option<KeyEvent> {
        match message.msg {
            windows_messages::WM_KEYDOWN
            | windows_messages::WM_KEYUP
            | windows_messages::WM_SYSKEYDOWN
            | windows_messages::WM_SYSKEYUP => {
                let virtual_key = message.wparam.as_u32() as u16;
                let lparam = message.lparam.as_u32();

                let scan_code = ((lparam >> 16) & 0xFF) as u16;
                let repeat_count = (lparam & 0xFFFF) as u16;

                // In real implementation, you'd query key states
                let modifiers = KeyModifiers::default();

                Some(KeyEvent {
                    virtual_key,
                    scan_code,
                    modifiers,
                    repeat_count,
                })
            }
            _ => None,
        }
    }

    /// Parses a window size message.
    pub fn parse_size_message(message: WindowMessage) -> Option<(i32, i32)> {
        if message.msg == windows_messages::WM_SIZE {
            let (width, height) = message.lparam.as_point();
            Some((width as i32, height as i32))
        } else {
            None
        }
    }
}

/// Common Windows message constants.
///
/// This module contains common Windows message constants used throughout the crate.
pub mod windows_messages {
    /// Null message.
    pub const WM_NULL: u32 = 0x0000;
    /// Window creation message.
    pub const WM_CREATE: u32 = 0x0001;
    /// Window destruction message.
    pub const WM_DESTROY: u32 = 0x0002;
    /// Window move message.
    pub const WM_MOVE: u32 = 0x0003;
    /// Window size message.
    pub const WM_SIZE: u32 = 0x0005;
    /// Paint message.
    pub const WM_PAINT: u32 = 0x000F;
    /// Close message.
    pub const WM_CLOSE: u32 = 0x0010;
    /// Quit message.
    pub const WM_QUIT: u32 = 0x0012;

    /// Key down message.
    pub const WM_KEYDOWN: u32 = 0x0100;
    /// Key up message.
    pub const WM_KEYUP: u32 = 0x0101;
    /// System key down message.
    pub const WM_SYSKEYDOWN: u32 = 0x0104;
    /// System key up message.
    pub const WM_SYSKEYUP: u32 = 0x0105;

    /// Mouse move message.
    pub const WM_MOUSEMOVE: u32 = 0x0200;
    /// Left button down message.
    pub const WM_LBUTTONDOWN: u32 = 0x0201;
    /// Left button up message.
    pub const WM_LBUTTONUP: u32 = 0x0202;
    /// Right button down message.
    pub const WM_RBUTTONDOWN: u32 = 0x0204;
    /// Right button up message.
    pub const WM_RBUTTONUP: u32 = 0x0205;
    /// Middle button down message.
    pub const WM_MBUTTONDOWN: u32 = 0x0207;
    /// Middle button up message.
    pub const WM_MBUTTONUP: u32 = 0x0208;
}

// Windows crate 互操作性
#[cfg(feature = "windows-interop")]
/// Windows crate interoperability module.
///
/// This module provides seamless conversion between `windows-api-utils` types
/// and the `windows` crate types for WPARAM, LPARAM, and LRESULT.
///
/// # Examples
///
/// ```rust
/// use windows_api_utils::prelude::*;
/// use windows::Win32::Foundation::{WPARAM, LPARAM};
///
/// // Convert from windows crate types
/// let win_wparam = WPARAM(0x1234);
/// let our_wparam = WParam::from(win_wparam);
///
/// // Convert back to windows crate types
/// let back_to_win: WPARAM = our_wparam.into();
/// assert_eq!(win_wparam.0, back_to_win.0);
///
/// // Test coordinate conversion
/// let win_lparam = LPARAM(0x00C80064); // x=100, y=200
/// let our_lparam = LParam::from(win_lparam);
/// let (x, y) = our_lparam.as_point();
/// assert_eq!(x, 100);
/// assert_eq!(y, 200);
/// ```
pub mod windows_interop {
    use super::*;

    impl From<WParam> for windows::Win32::Foundation::WPARAM {
        fn from(wparam: WParam) -> Self {
            windows::Win32::Foundation::WPARAM(wparam.as_usize())
        }
    }

    impl From<windows::Win32::Foundation::WPARAM> for WParam {
        fn from(wparam: windows::Win32::Foundation::WPARAM) -> Self {
            WParam::new(wparam.0)
        }
    }

    impl From<LParam> for windows::Win32::Foundation::LPARAM {
        fn from(lparam: LParam) -> Self {
            windows::Win32::Foundation::LPARAM(lparam.as_isize())
        }
    }

    impl From<windows::Win32::Foundation::LPARAM> for LParam {
        fn from(lparam: windows::Win32::Foundation::LPARAM) -> Self {
            LParam::new(lparam.0)
        }
    }

    impl From<LRESULT> for windows::Win32::Foundation::LRESULT {
        fn from(result: LRESULT) -> Self {
            windows::Win32::Foundation::LRESULT(result.0)
        }
    }

    impl From<windows::Win32::Foundation::LRESULT> for LRESULT {
        fn from(result: windows::Win32::Foundation::LRESULT) -> Self {
            LRESULT(result.0)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_message_creation() {
        let msg = WindowMessage::mouse_move(100, 200, KeyModifiers::default());
        assert_eq!(msg.msg, windows_messages::WM_MOUSEMOVE);

        if let Some(mouse_event) = MessageParser::parse_mouse_message(msg) {
            assert_eq!(mouse_event.x, 100);
            assert_eq!(mouse_event.y, 200);
        }
    }

    #[test]
    fn test_lparam_point_conversion() {
        let lparam = LParam::from_point(100, 200);
        let (x, y) = lparam.as_point();
        assert_eq!(x, 100);
        assert_eq!(y, 200);
    }

    #[test]
    fn test_type_compatibility() {
        // 测试我们的类型与 windows crate 的内存布局兼容性
        let our_wparam = WParam::new(0x12345678);
        let our_lparam = LParam::new(0x87654321);

        // 验证底层表示
        assert_eq!(our_wparam.as_usize(), 0x12345678);
        assert_eq!(our_lparam.as_isize(), 0x87654321);
    }
}