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
//! Mouse automation instructions
//!
//! Provides seven mouse instructions for automating mouse operations:
//! - `click`: Click at position (or current position)
//! - `move`: Move to absolute position
//! - `moverel`: Move relatively from current position
//! - `scrollup`: Scroll wheel up
//! - `scrolldown`: Scroll wheel down
//! - `press`: Press and hold left button
//! - `release`: Release left button
//!
//! # Coordinate System and Execution Modes
//!
//! Mouse instructions support two execution modes:
//! - `send` (foreground, default): Direct input simulation to the system
//! - `post` (background): Sends messages to a specific window
//!
//! ## Performance Optimization
//!
//! All mouse instructions pre-build their INPUT structures at parse time for zero runtime overhead.
//! For instructions with coordinates (`click`, `move`, `scrollup`, `scrolldown`), the execution flow is:
//! 1. **Parse phase**: Pre-build the action part of INPUT (e.g., mouse down/up events)
//! 2. **Execute phase**: Use `SetCursorPos` for positioning (if coordinates provided), then execute pre-built INPUT
//!
//! This approach eliminates runtime INPUT construction and HashMap lookup overhead, achieving optimal performance.
//!
//! In contrast, `moverel` performs relative movement and doesn't require coordinate transformation,
//! so it directly uses the pre-built INPUT without additional positioning.
//!
//! # Instructions
//!
//! ## `click` - Click at position
//!
//! Performs a complete mouse click (press + release).
//!
//! **Syntax:** `click [x] [y] [delay_ms] [mode]`
//!
//! **Parameters:**
//! - `[x] [y]` (optional): Coordinates to click at. If omitted in Send mode, uses current cursor position.
//! - `[delay_ms]` (optional): Delay in milliseconds after click (0-1000ms). Useful for applications that ignore rapid consecutive clicks.
//! - `[mode]` (optional): Execution mode - `send` (foreground, default) or `post` (background)
//!
//! **Examples:**
//! ```text
//! click 100 200 # Click at (100, 200) in foreground
//! click 100 200 post # Click at (100, 200) in background
//! click # Click at current position (foreground only)
//! click send # Click at current position (explicit foreground)
//! click 100 200 50 # Click at (100, 200) with 50ms delay
//! click 100 200 100 post # Click at (100, 200) in background with 100ms delay
//! ```
//!
//! **Notes:**
//! - PostMessage mode requires both x and y coordinates
//! - PostMessage mode requires `target_hwnd` to be set in VM state
//! - SendInput mode without coordinates uses current cursor position
//!
//! ---
//!
//! ## `move` - Move to absolute position
//!
//! Moves the mouse cursor to an absolute screen position.
//!
//! **Syntax:** `move <x> <y> [mode]`
//!
//! **Parameters:**
//! - `<x> <y>` (required): Target coordinates
//! - `[mode]` (optional): Execution mode - `send` (foreground, default) or `post` (background)
//!
//! **Examples:**
//! ```text
//! move 100 200 # Move to (100, 200) in foreground
//! move 100 200 post # Move to (100, 200) in background
//! ```
//!
//! **Notes:**
//! - PostMessage mode sends WM_MOUSEMOVE message to target window
//!
//! ---
//!
//! ## `moverel` - Move relatively
//!
//! Moves the mouse cursor relative to its current position.
//!
//! **Syntax:** `moverel <dx> <dy> [mode]`
//!
//! **Parameters:**
//! - `<dx> <dy>` (required): Offset from current position (positive = right/down, negative = left/up)
//! - `[mode]` (optional): Execution mode - `send` (foreground, default) or `post` (background)
//!
//! **Examples:**
//! ```text
//! moverel 10 -5 # Move 10px right, 5px up (foreground)
//! moverel 10 -5 post # Move relatively in background
//! ```
//!
//! **Notes:**
//! - Relative movement is primarily designed for SendInput mode
//!
//! ---
//!
//! ## `scrollup` - Scroll wheel up
//!
//! Scrolls the mouse wheel upward by a specified number of notches.
//!
//! **Syntax:** `scrollup [x] [y] [times] [mode]`
//!
//! **Parameters:**
//! - `[x] [y]` (optional): Coordinates to scroll at.
//! - **PostMessage mode**: Specifies the position within the target window where the scroll occurs (mouse does NOT move).
//! - **SendInput mode**: If provided, moves the mouse to the specified screen coordinates first, then scrolls. If omitted, scrolls at current cursor position.
//! - `[times]` (optional): Number of scroll notches (default: 1, range: 1-100). Each notch = 120 units (Windows standard).
//! - `[mode]` (optional): Execution mode - `send` (foreground, default) or `post` (background)
//!
//! **Examples:**
//! ```text
//! scrollup # Scroll up 1 notch at current cursor position (foreground)
//! scrollup 3 # Scroll up 3 notches at current position
//! scrollup 100 200 # Move to (100, 200) then scroll up 1 notch (foreground)
//! scrollup 100 200 5 # Move to (100, 200) then scroll up 5 notches (foreground)
//! scrollup 100 200 post # Scroll up 1 notch at position (100, 200) within target window (background)
//! scrollup 100 200 3 post # Scroll up 3 notches at position (100, 200) within target window (background)
//! ```
//!
//! **Important Notes:**
//! - Uses intuitive "times" parameter instead of raw delta values for better usability
//! - **PostMessage mode**: Does NOT move the mouse cursor. The x,y coordinates indicate where the scroll event occurs within the target window.
//! - **SendInput mode with coordinates**: Moves the mouse to the specified position BEFORE scrolling. This allows scrolling in different areas of an application without manual mouse positioning.
//! - **SendInput mode without coordinates**: Scrolls at the current mouse cursor position without moving.
//! - PostMessage mode requires `target_hwnd` to be set in VM state
//!
//! ---
//!
//! ## `scrolldown` - Scroll wheel down
//!
//! Scrolls the mouse wheel downward by a specified number of notches.
//!
//! **Syntax:** `scrolldown [x] [y] [times] [mode]`
//!
//! **Parameters:**
//! - `[x] [y]` (optional): Coordinates to scroll at.
//! - **PostMessage mode**: Specifies the position within the target window where the scroll occurs (mouse does NOT move).
//! - **SendInput mode**: If provided, moves the mouse to the specified screen coordinates first, then scrolls. If omitted, scrolls at current cursor position.
//! - `[times]` (optional): Number of scroll notches (default: 1, range: 1-100). Each notch = 120 units (Windows standard).
//! - `[mode]` (optional): Execution mode - `send` (foreground, default) or `post` (background)
//!
//! **Examples:**
//! ```text
//! scrolldown # Scroll down 1 notch at current cursor position (foreground)
//! scrolldown 3 # Scroll down 3 notches at current position
//! scrolldown 100 200 # Move to (100, 200) then scroll down 1 notch (foreground)
//! scrolldown 100 200 5 # Move to (100, 200) then scroll down 5 notches (foreground)
//! scrolldown 100 200 post # Scroll down 1 notch at position (100, 200) within target window (background)
//! scrolldown 100 200 3 post # Scroll down 3 notches at position (100, 200) within target window (background)
//! ```
//!
//! **Important Notes:**
//! - Uses intuitive "times" parameter instead of raw delta values for better usability
//! - **PostMessage mode**: Does NOT move the mouse cursor. The x,y coordinates indicate where the scroll event occurs within the target window.
//! - **SendInput mode with coordinates**: Moves the mouse to the specified position BEFORE scrolling. This allows scrolling in different areas of an application without manual mouse positioning.
//! - **SendInput mode without coordinates**: Scrolls at the current mouse cursor position without moving.
//! - PostMessage mode requires `target_hwnd` to be set in VM state
//!
//! ---
//!
//! ## `press` - Press and hold left button
//!
//! Presses the left mouse button without releasing it. Use with `release` for drag operations.
//!
//! **Syntax:** `press [mode]`
//!
//! **Parameters:**
//! - `[mode]` (optional): Execution mode - `send` (foreground, default) or `post` (background)
//!
//! **Examples:**
//! ```text
//! press # Press left button (foreground)
//! press post # Press left button (background, uses coordinates 0,0)
//! ```
//!
//! **Notes:**
//! - Use with `release` to create drag operations
//! - In PostMessage mode, uses default coordinates (0, 0)
//!
//! ---
//!
//! ## `release` - Release left button
//!
//! Releases the left mouse button that was previously pressed.
//!
//! **Syntax:** `release [mode]`
//!
//! **Parameters:**
//! - `[mode]` (optional): Execution mode - `send` (foreground, default) or `post` (background)
//!
//! **Examples:**
//! ```text
//! release # Release left button (foreground)
//! release post # Release left button (background, uses coordinates 0,0)
//! ```
//!
//! **Notes:**
//! - Must be paired with `press` to avoid stuck buttons
//! - In PostMessage mode, uses default coordinates (0, 0)
//!
//! ---
//!
//! # Execution Modes
//!
//! ## Foreground Mode (`send`) - Default
//!
//! Simulates input using SendInput API (global system input).
//! - No target window configuration needed
//! - Works with the currently focused application
//! - Supports operations without coordinates (uses current cursor position)
//!
//! ```text
//! click # Same as: click send
//! move 100 200 # Same as: move 100 200 send
//! ```
//!
//! ## Background Mode (`post`)
//!
//! Sends messages directly to a specific window using PostMessage API.
//! - Requires `target_hwnd` to be set in VM state before execution
//! - Works even when window is not in focus
//! - Must specify mode explicitly
//! - Requires coordinates for most operations
//!
//! ```text
//! # Set target window first (in your Rust code)
//! # vm.set_persistent_state("target_hwnd", hwnd);
//!
//! click 100 200 post # Click in background window
//! move 100 200 post # Move in background window
//! ```
//!
//! ---
//!
//! # Common Use Cases
//!
//! ## Simple Click
//! ```text
//! click 100 200 # Click at specific position
//! click # Click at current position
//! ```
//!
//! ## Drag and Drop
//! ```text
//! # Move to source position
//! move 100 100
//! # Press and hold
//! press
//! # Move to destination
//! move 300 300
//! # Release
//! release
//! ```
//!
//! ## Drag and Drop (Background)
//! ```text
//! # Set target window first
//! # vm.set_persistent_state("target_hwnd", hwnd);
//!
//! press post
//! move 300 300 post
//! release post
//! ```
//!
//! ## Scrolling
//! ```text
//! scrollup 2 # Scroll up two notches
//! scrolldown 1 # Scroll down one notch
//! ```
//!
//! ---
//!
//! # Error Messages
//!
//! The parser provides clear error messages for common mistakes:
//!
//! ```text
//! click post → "PostMessage mode requires coordinates"
//! move 100 → "Missing coordinates"
//! moverel invalid 5 → "Invalid dx offset 'invalid'"
//! scrollup abc → "Invalid scroll amount 'abc'"
//! ```
//!
//! ---
//!
//! # Important Notes
//!
//! 1. **Background mode requires setup**: Before using `post` mode, you must set the target window handle in your Rust code:
//! ```rust
//! vm.set_persistent_state("target_hwnd", some_hwnd);
//! ```
//!
//! 2. **Coordinates are required in PostMessage mode**: Most operations in background mode require explicit coordinates.
//!
//! 3. **Press/Release pairing**: Always pair `press` with `release` to avoid stuck mouse buttons.
//!
//! 4. **Scroll amounts**: Standard scroll notch is 120 units. Multiply for faster scrolling (e.g., 240 = 2 notches).
use crate;
use UIINPUT;
// Submodules - each instruction handler in its own file
// Re-export handlers for convenience
pub use ClickHandler;
pub use MoveHandler;
pub use MoveRelHandler;
pub use PressHandler;
pub use ReleaseHandler;
pub use ScrollDownHandler;
pub use ScrollUpHandler;
// ============================================================================
// Common Types and Utilities
// ============================================================================
/// Mouse operation mode
/// Pre-compiled mouse click parameters (with window coordinates)
/// Pre-compiled mouse move parameters (with pre-built INPUT)
/// Pre-compiled mouse relative move parameters (with pre-built INPUT)
/// Pre-compiled scroll parameters (with pre-built INPUT)
/// Pre-compiled mouse press parameters
/// Pre-compiled mouse release parameters
/// Helper function to parse mouse mode parameter from instruction arguments.
///
/// Examines the last argument to determine if it's a mode specifier ("send" or "post").
/// Returns the parsed mode and the number of arguments consumed (0 or 1).
///
/// # Arguments
/// * `args` - Instruction arguments slice
/// * `default_mode` - Default mode to use if no mode is specified
///
/// # Returns
/// * `(MouseMode, usize)` - Tuple of (parsed mode, number of args consumed)
///
/// # Examples
/// ```ignore
/// parse_mouse_mode(&["100", "200"], MouseMode::Send) // → (Send, 0)
/// parse_mouse_mode(&["100", "200", "post"], MouseMode::Send) // → (Post, 1)
/// ```
pub
/// Constant key for storing/retrieving the default input mode in VM persistent state.
///
/// This key is used by `get_input_mode()` to fetch the current default mode setting.
/// Users can set this via `vm.set_persistent_state(INPUT_MODE_KEY, "post")` to change
/// the default mode for all subsequent mouse/keyboard instructions.
const INPUT_MODE_KEY: &str = "input_mode";
/// Get the current default input mode from VM persistent state.
///
/// Returns the mode configured via `vm.set_persistent_state("input_mode", ...)`.
/// If not set, defaults to "send" (foreground mode).
///
/// # Arguments
/// * `vm` - Virtual machine context reference
///
/// # Returns
/// Current default mode as a string ("send" or "post")
///
/// # Examples
/// ```ignore
/// let mode = get_input_mode(vm); // → "send" (default)
/// vm.set_persistent_state("input_mode", "post");
/// let mode = get_input_mode(vm); // → "post"
/// ```
pub
/// Convert window-relative coordinates to screen coordinates for SendInput mode.
///
/// This function adds the window's screen offset to convert coordinates that are relative
/// to the window rectangle (including title bar and borders) into absolute screen coordinates.
///
/// # Coordinate System
/// - **Input**: Window-relative coordinates (0,0 = top-left corner of window including non-client area)
/// - **Output**: Screen coordinates (absolute position on the desktop)
///
/// # Arguments
/// * `vm` - Virtual machine context containing process/window information
/// * `window_rel_x` - X coordinate relative to window rectangle
/// * `window_rel_y` - Y coordinate relative to window rectangle
///
/// # Returns
/// * `Ok((screen_x, screen_y))` - Converted screen coordinates
/// * `Err(ScriptError::NoWindowHandle)` - If window geometry is not available
///
/// # Formula
/// ```text
/// screen_x = window_rel_x + window_left_offset
/// screen_y = window_rel_y + window_top_offset
/// ```
///
/// # Examples
/// ```ignore
/// // If window is at screen position (100, 200) with title bar height 30px
/// let (sx, sy) = convert_to_window_coords(vm, 50, 80)?;
/// // → sx = 150, sy = 280 (50+100, 80+200)
/// ```
///
/// # Notes
/// - Only available when `script_process_context` feature is enabled
/// - Requires `vm.process.window_geometry` to be set (via HWND tracking)
pub
/// Convert window-relative coordinates to client area coordinates for PostMessage mode.
///
/// This function subtracts the non-client area offset (title bar, borders) to convert
/// coordinates that are relative to the window rectangle into coordinates relative to
/// the client area (the actual content area of the window).
///
/// # Coordinate System
/// - **Input**: Window-relative coordinates (0,0 = top-left corner of window including title bar/borders)
/// - **Output**: Client area coordinates (0,0 = top-left corner of the client/content area)
///
/// # Arguments
/// * `vm` - Virtual machine context containing process/window information
/// * `window_rel_x` - X coordinate relative to window rectangle
/// * `window_rel_y` - Y coordinate relative to window rectangle
///
/// # Returns
/// * `Ok((client_x, client_y))` - Converted client area coordinates
/// * `Err(ScriptError::NoWindowHandle)` - If window geometry is not available
///
/// # Formula
/// ```text
/// client_x = window_rel_x - offset_x (offset_x = distance from window edge to client area)
/// client_y = window_rel_y - offset_y (offset_y = title bar height + border width)
/// ```
///
/// # Examples
/// ```ignore
/// // If window has 8px border and 30px title bar (offset_x=8, offset_y=38)
/// let (cx, cy) = convert_to_client_coords(vm, 50, 80)?;
/// // → cx = 42, cy = 42 (50-8, 80-38)
/// ```
///
/// # Notes
/// - Only available when `script_process_context` feature is enabled
/// - Requires `vm.process.window_geometry` to be set (via HWND tracking)
/// - Essential for PostMessage API which uses client area coordinates
pub