win-auto-utils 0.1.1

Universal Windows automation utilities with memory, window, input, and color operations
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
//! SendInput-based mouse input (atomic high-performance API)
//!
//! This module provides minimal, zero-overhead functions that accept pre-built INPUT structures.
//! Zero runtime allocation - all INPUT structures are created at parse/compile time.
//!
//! For user-friendly APIs, see the convenience wrapper at the end of this file.

use windows::Win32::UI::Input::KeyboardAndMouse::{
    SendInput, INPUT, INPUT_0, INPUT_MOUSE, MOUSEINPUT, MOUSE_EVENT_FLAGS,
    MOUSEEVENTF_ABSOLUTE, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 
    MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, MOUSEEVENTF_MIDDLEDOWN,
    MOUSEEVENTF_MIDDLEUP, MOUSEEVENTF_MOVE, MOUSEEVENTF_WHEEL,
};
use windows::Win32::UI::WindowsAndMessaging::SetCursorPos;

// ============================================================================
// High-Performance Cursor Positioning (SetCursorPos API)
// ============================================================================

/// Set cursor position using SetCursorPos API (22x faster than SendInput MOVE)
/// 
/// # Performance
/// ~2.2 μs per call vs ~50 μs for SendInput(MOVE)
/// Throughput: ~450K IPS vs ~20K IPS
/// 
/// # Parameters
/// * `x` - Screen X coordinate in pixels
/// * `y` - Screen Y coordinate in pixels
#[inline]
pub fn set_cursor_pos(x: i32, y: i32) -> Result<(), SendInputError> {
    unsafe {
        SetCursorPos(x, y).map_err(|_| SendInputError::SetCursorPosFailed)?;
        Ok(())
    }
}

// ============================================================================
// Atomic High-Performance Functions (Zero Overhead - Direct INPUT Execution)
// ============================================================================

/// Execute INPUT structures directly (atomic operation)
/// 
/// # Performance
/// Zero overhead - accepts pre-built INPUT slice and sends directly via syscall
/// 
/// # Parameters
/// * `inputs` - Pre-built INPUT structures (created at parse/compile time)
#[inline]
pub fn execute_inputs(inputs: &[INPUT]) -> Result<(), SendInputError> {
    if inputs.is_empty() {
        return Ok(());
    }
    
    let result = unsafe {
        SendInput(
            inputs,
            std::mem::size_of::<INPUT>() as i32,
        )
    };
    
    if result == 0 {
        Err(SendInputError::SendInputFailed)
    } else {
        Ok(())
    }
}

/// Execute a single INPUT structure atomically
#[inline]
pub fn execute_single_input(input: &INPUT) -> Result<(), SendInputError> {
    execute_inputs(&[input.clone()])
}

// ============================================================================
// Helper Functions for Building INPUT Structures (Parse-time Use Only)
// ============================================================================

/// Helper function to convert screen coordinates to normalized absolute coordinates
/// Screen coordinates: 0-65535 range for full desktop
#[inline]
pub fn normalize_coords(x: i32, y: i32) -> (i32, i32) {
    let screen_width = unsafe { 
        windows::Win32::UI::WindowsAndMessaging::GetSystemMetrics(
            windows::Win32::UI::WindowsAndMessaging::SM_CXSCREEN
        )
    };
    let screen_height = unsafe { 
        windows::Win32::UI::WindowsAndMessaging::GetSystemMetrics(
            windows::Win32::UI::WindowsAndMessaging::SM_CYSCREEN
        )
    };
    
    // Use ceiling division to ensure we don't undershoot the target coordinate
    // Formula: (value * 65535 + screen_size - 1) / screen_size
    // This ensures that any fractional part rounds up, minimizing undershoot errors
    let nx = ((x as i64) * 65535 + (screen_width as i64) - 1) / (screen_width as i64);
    let ny = ((y as i64) * 65535 + (screen_height as i64) - 1) / (screen_height as i64);
    
    (nx as i32, ny as i32)
}

/// Build a MOUSE INPUT structure (for parse-time construction)
/// 
/// # Usage
/// Call this during instruction parsing to build static INPUT structures
#[inline]
pub fn build_mouse_input(flags: MOUSE_EVENT_FLAGS, dx: i32, dy: i32, data: u32) -> INPUT {
    INPUT {
        r#type: INPUT_MOUSE,
        Anonymous: INPUT_0 {
            mi: MOUSEINPUT {
                dx,
                dy,
                mouseData: data,
                dwFlags: flags,
                time: 0,
                dwExtraInfo: 0,
            },
        },
    }
}

/// Build left click INPUT pair at current position (parse-time)
#[inline]
pub fn build_click_left() -> [INPUT; 2] {
    [
        build_mouse_input(MOUSEEVENTF_LEFTDOWN, 0, 0, 0),
        build_mouse_input(MOUSEEVENTF_LEFTUP, 0, 0, 0),
    ]
}

/// Build left click INPUT sequence at specified coordinates (parse-time)
#[inline]
pub fn build_click_left_at(x: i32, y: i32) -> Vec<INPUT> {
    let (nx, ny) = normalize_coords(x, y);
    
    vec![
        build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0),
        build_mouse_input(MOUSEEVENTF_LEFTDOWN, 0, 0, 0),
        build_mouse_input(MOUSEEVENTF_LEFTUP, 0, 0, 0),
    ]
}

/// Build right click INPUT pair at current position (parse-time)
#[inline]
pub fn build_click_right() -> [INPUT; 2] {
    [
        build_mouse_input(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0),
        build_mouse_input(MOUSEEVENTF_RIGHTUP, 0, 0, 0),
    ]
}

/// Build right click INPUT sequence at specified coordinates (parse-time)
#[inline]
pub fn build_click_right_at(x: i32, y: i32) -> Vec<INPUT> {
    let (nx, ny) = normalize_coords(x, y);
    
    vec![
        build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0),
        build_mouse_input(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0),
        build_mouse_input(MOUSEEVENTF_RIGHTUP, 0, 0, 0),
    ]
}

/// Build middle click INPUT pair at current position (parse-time)
#[inline]
pub fn build_click_middle() -> [INPUT; 2] {
    [
        build_mouse_input(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0),
        build_mouse_input(MOUSEEVENTF_MIDDLEUP, 0, 0, 0),
    ]
}

/// Build middle click INPUT sequence at specified coordinates (parse-time)
#[inline]
pub fn build_click_middle_at(x: i32, y: i32) -> Vec<INPUT> {
    let (nx, ny) = normalize_coords(x, y);
    
    vec![
        build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0),
        build_mouse_input(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0),
        build_mouse_input(MOUSEEVENTF_MIDDLEUP, 0, 0, 0),
    ]
}

/// Build press left button INPUT (parse-time)
#[inline]
pub fn build_press_left() -> INPUT {
    build_mouse_input(MOUSEEVENTF_LEFTDOWN, 0, 0, 0)
}

/// Build press left button INPUT at specified coordinates (parse-time)
/// Moves to the position first, then presses
#[inline]
pub fn build_press_left_at(x: i32, y: i32) -> Vec<INPUT> {
    let (nx, ny) = normalize_coords(x, y);
    
    vec![
        build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0),
        build_mouse_input(MOUSEEVENTF_LEFTDOWN, 0, 0, 0),
    ]
}

/// Build release left button INPUT (parse-time)
#[inline]
pub fn build_release_left() -> INPUT {
    build_mouse_input(MOUSEEVENTF_LEFTUP, 0, 0, 0)
}

/// Build release left button INPUT at specified coordinates (parse-time)
/// Moves to the position first, then releases
#[inline]
pub fn build_release_left_at(x: i32, y: i32) -> Vec<INPUT> {
    let (nx, ny) = normalize_coords(x, y);
    
    vec![
        build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0),
        build_mouse_input(MOUSEEVENTF_LEFTUP, 0, 0, 0),
    ]
}

/// Build move to absolute coordinates INPUT (parse-time)
#[inline]
pub fn build_move(x: i32, y: i32) -> INPUT {
    let (nx, ny) = normalize_coords(x, y);
    build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0)
}

/// Build relative move INPUT (parse-time)
#[inline]
pub fn build_move_relative(dx: i32, dy: i32) -> INPUT {
    build_mouse_input(MOUSEEVENTF_MOVE, dx, dy, 0)
}

/// Build scroll up INPUT (parse-time)
#[inline]
pub fn build_scroll_up(delta: i32) -> INPUT {
    build_mouse_input(MOUSEEVENTF_WHEEL, 0, 0, delta as u32)
}

/// Build scroll up INPUT at specified coordinates (parse-time)
/// Moves to the position first, then scrolls
#[inline]
pub fn build_scroll_up_at(x: i32, y: i32, delta: i32) -> Vec<INPUT> {
    let (nx, ny) = normalize_coords(x, y);
    
    vec![
        build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0),
        build_mouse_input(MOUSEEVENTF_WHEEL, 0, 0, delta as u32),
    ]
}

/// Build scroll down INPUT (parse-time)
#[inline]
pub fn build_scroll_down(delta: i32) -> INPUT {
    build_mouse_input(MOUSEEVENTF_WHEEL, 0, 0, (-delta) as u32)
}

/// Build scroll down INPUT at specified coordinates (parse-time)
/// Moves to the position first, then scrolls
#[inline]
pub fn build_scroll_down_at(x: i32, y: i32, delta: i32) -> Vec<INPUT> {
    let (nx, ny) = normalize_coords(x, y);
    
    vec![
        build_mouse_input(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, nx, ny, 0),
        build_mouse_input(MOUSEEVENTF_WHEEL, 0, 0, (-delta) as u32),
    ]
}

// ============================================================================
// Convenience Wrapper (User-Friendly API)
// ============================================================================

/// Error type for SendInput operations
#[derive(Debug, Clone)]
pub enum SendInputError {
    /// SendInput API call failed
    SendInputFailed,
    /// SetCursorPos API call failed
    SetCursorPosFailed,
}

impl std::fmt::Display for SendInputError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SendInputError::SendInputFailed => write!(f, "SendInput API call failed"),
            SendInputError::SetCursorPosFailed => write!(f, "SetCursorPos API call failed"),
        }
    }
}

impl std::error::Error for SendInputError {}

/// Convenience wrapper for mouse input
/// 
/// # Note
/// This wrapper has runtime overhead from coordinate calculations. For maximum performance,
/// use the atomic functions directly with pre-built INPUT structures.
pub struct SendInputMouse;

impl SendInputMouse {
    /// Create new instance
    pub fn new() -> Self {
        Self
    }

    /// Click left button at current position (convenience method)
    pub fn click_left(&self) -> Result<(), SendInputError> {
        let inputs = build_click_left();
        execute_inputs(&inputs)
    }

    /// Click left button at specified coordinates
    pub fn click_left_at(&self, x: i32, y: i32) -> Result<(), SendInputError> {
        let inputs = build_click_left_at(x, y);
        execute_inputs(&inputs)
    }

    /// Click right button at current position
    pub fn click_right(&self) -> Result<(), SendInputError> {
        let inputs = build_click_right();
        execute_inputs(&inputs)
    }

    /// Click right button at specified coordinates
    pub fn click_right_at(&self, x: i32, y: i32) -> Result<(), SendInputError> {
        let inputs = build_click_right_at(x, y);
        execute_inputs(&inputs)
    }

    /// Click middle button at current position
    pub fn click_middle(&self) -> Result<(), SendInputError> {
        let inputs = build_click_middle();
        execute_inputs(&inputs)
    }

    /// Click middle button at specified coordinates
    pub fn click_middle_at(&self, x: i32, y: i32) -> Result<(), SendInputError> {
        let inputs = build_click_middle_at(x, y);
        execute_inputs(&inputs)
    }

    /// Press left button
    pub fn press_left(&self) -> Result<(), SendInputError> {
        let input = build_press_left();
        execute_single_input(&input)
    }

    /// Release left button
    pub fn release_left(&self) -> Result<(), SendInputError> {
        let input = build_release_left();
        execute_single_input(&input)
    }

    /// Move mouse to absolute coordinates
    pub fn move_to(&self, x: i32, y: i32) -> Result<(), SendInputError> {
        let input = build_move(x, y);
        execute_single_input(&input)
    }

    /// Move mouse by relative offset
    pub fn move_relative(&self, dx: i32, dy: i32) -> Result<(), SendInputError> {
        let input = build_move_relative(dx, dy);
        execute_single_input(&input)
    }

    /// Scroll up
    pub fn scroll_up(&self, delta: i32) -> Result<(), SendInputError> {
        let input = build_scroll_up(delta);
        execute_single_input(&input)
    }

    /// Scroll down
    pub fn scroll_down(&self, delta: i32) -> Result<(), SendInputError> {
        let input = build_scroll_down(delta);
        execute_single_input(&input)
    }
}

impl Default for SendInputMouse {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_build_and_execute_inputs() {
        // Test building INPUT structures and executing them
        let inputs = build_click_left();
        
        // Just verify compilation and structure correctness
        assert_eq!(inputs.len(), 2);
        assert_eq!(inputs[0].r#type, INPUT_MOUSE);
        assert_eq!(inputs[1].r#type, INPUT_MOUSE);
    }

    #[test]
    fn test_build_click_at_inputs() {
        let inputs = build_click_left_at(100, 200);
        
        // Should have 3 inputs: move + down + up
        assert_eq!(inputs.len(), 3);
    }

    #[test]
    fn test_atomic_functions_compile() {
        // Verify atomic functions compile correctly
        let inputs = build_click_left();
        
        // These will fail at runtime in test environment but should compile
        let _result = execute_inputs(&inputs);
        
        assert!(true); // Compilation check
    }
}