cranpose 0.0.64

Cranpose runtime and UI facade
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
//! Input event recorder for generating robot tests from manual interactions.
//!
//! This module captures mouse and keyboard events with precise timestamps,
//! then generates Rust robot test code that can replay the exact interaction.
//!
//! # Example
//!
//! ```no_run
//! use cranpose::AppLauncher;
//!
//! AppLauncher::new()
//!     .with_recording("/tmp/my_test.rs")
//!     .run(|| {
//!         // Your app - interact with it, then close
//!     });
//! // Generated test file will be at /tmp/my_test.rs
//! ```
//!
//! # Data-Driven Tests
//!
//! Generated tests use the [`RobotAction`] enum and [`execute_actions`] function
//! for compact, data-driven test representation:
//!
//! ```ignore
//! use cranpose::recorder::{RobotAction, execute_actions};
//!
//! let actions = [
//!     RobotAction::Sleep(100),
//!     RobotAction::MouseMove(100.0, 200.0),
//!     RobotAction::MouseDown,
//!     RobotAction::Sleep(50),
//!     RobotAction::MouseUp,
//! ];
//! execute_actions(&robot, &actions);
//! ```

use std::io::Write;
use std::path::PathBuf;
use std::time::Instant;

/// An action that can be executed by a robot test.
///
/// This enum represents all possible actions in a robot test sequence,
/// making tests more compact and data-driven compared to verbose inline code.
#[derive(Debug, Clone, PartialEq)]
pub enum RobotAction {
    /// Sleep for the specified number of milliseconds
    Sleep(u64),
    /// Move the mouse to the specified coordinates
    MouseMove(f32, f32),
    /// Press the mouse button down
    MouseDown,
    /// Release the mouse button
    MouseUp,
    /// Send a key press (press + release)
    Key(String),
}

/// Execute a sequence of robot actions.
///
/// This function takes a reference to a Robot and a slice of actions,
/// executing them in order. This is the runtime counterpart to the
/// data-driven test format generated by the recorder.
///
/// # Example
///
/// ```ignore
/// let actions = [
///     RobotAction::Sleep(100),
///     RobotAction::MouseMove(400.0, 300.0),
///     RobotAction::MouseDown,
///     RobotAction::Sleep(50),
///     RobotAction::MouseUp,
/// ];
/// execute_actions(&robot, &actions);
/// ```
#[cfg(feature = "robot")]
pub fn execute_actions(robot: &crate::Robot, actions: &[RobotAction]) {
    for action in actions {
        match action {
            RobotAction::Sleep(ms) => {
                std::thread::sleep(std::time::Duration::from_millis(*ms));
            }
            RobotAction::MouseMove(x, y) => {
                let _ = robot.mouse_move(*x, *y);
            }
            RobotAction::MouseDown => {
                let _ = robot.mouse_down();
            }
            RobotAction::MouseUp => {
                let _ = robot.mouse_up();
            }
            RobotAction::Key(key) => {
                let _ = robot.send_key(key);
            }
        }
    }
}

/// A recorded input event with timestamp
#[derive(Debug, Clone)]
pub enum RecordedEvent {
    /// Mouse cursor moved
    MouseMove {
        /// Timestamp in milliseconds since recording started
        time_ms: u64,
        /// X coordinate in logical pixels
        x: f32,
        /// Y coordinate in logical pixels
        y: f32,
    },
    /// Left mouse button pressed
    MouseDown {
        /// Timestamp in milliseconds since recording started
        time_ms: u64,
    },
    /// Left mouse button released
    MouseUp {
        /// Timestamp in milliseconds since recording started
        time_ms: u64,
    },
    /// Key pressed
    KeyDown {
        /// Timestamp in milliseconds since recording started
        time_ms: u64,
        /// Key name
        key: String,
    },
    /// Key released
    KeyUp {
        /// Timestamp in milliseconds since recording started
        time_ms: u64,
        /// Key name
        key: String,
    },
}

/// Input recorder that captures events with timestamps
pub struct InputRecorder {
    /// When recording started
    start_time: Instant,
    /// All recorded events
    events: Vec<RecordedEvent>,
    /// Output file path
    output_path: PathBuf,
    /// Last mouse position (to avoid duplicate moves)
    last_mouse_pos: Option<(f32, f32)>,
}

impl InputRecorder {
    /// Create a new recorder that will save to the given path
    pub fn new(output_path: impl Into<PathBuf>) -> Self {
        let path = output_path.into();
        eprintln!("[Recorder] Recording started - will save to {:?}", path);
        Self {
            start_time: Instant::now(),
            events: Vec::new(),
            output_path: path,
            last_mouse_pos: None,
        }
    }

    /// Get elapsed time in milliseconds since recording started
    fn elapsed_ms(&self) -> u64 {
        self.start_time.elapsed().as_millis() as u64
    }

    /// Record a mouse move event
    pub fn record_mouse_move(&mut self, x: f32, y: f32) {
        // Skip if same position (within 0.5px)
        if let Some((lx, ly)) = self.last_mouse_pos {
            if (x - lx).abs() < 0.5 && (y - ly).abs() < 0.5 {
                return;
            }
        }
        self.last_mouse_pos = Some((x, y));
        let time_ms = self.elapsed_ms();
        self.events.push(RecordedEvent::MouseMove { time_ms, x, y });
    }

    /// Record a mouse down event
    pub fn record_mouse_down(&mut self) {
        let time_ms = self.elapsed_ms();
        self.events.push(RecordedEvent::MouseDown { time_ms });
    }

    /// Record a mouse up event
    pub fn record_mouse_up(&mut self) {
        let time_ms = self.elapsed_ms();
        self.events.push(RecordedEvent::MouseUp { time_ms });
    }

    /// Record a key press event
    pub fn record_key_down(&mut self, key: &str) {
        let time_ms = self.elapsed_ms();
        self.events.push(RecordedEvent::KeyDown {
            time_ms,
            key: key.to_string(),
        });
    }

    /// Record a key release event
    pub fn record_key_up(&mut self, key: &str) {
        let time_ms = self.elapsed_ms();
        self.events.push(RecordedEvent::KeyUp {
            time_ms,
            key: key.to_string(),
        });
    }

    /// Finish recording and generate the robot test file.
    ///
    /// The generated test uses a data-driven format with [`RobotAction`] enum
    /// for compact representation:
    ///
    /// ```ignore
    /// const ACTIONS: &[RobotAction] = &[
    ///     Sleep(100),
    ///     MouseMove(400.0, 300.0),
    ///     MouseDown,
    ///     Sleep(50),
    ///     MouseUp,
    /// ];
    /// ```
    pub fn finish(&self) -> std::io::Result<()> {
        if self.events.is_empty() {
            eprintln!("[Recorder] No events recorded, skipping file generation");
            return Ok(());
        }

        eprintln!(
            "[Recorder] Generating robot test with {} events to {:?}",
            self.events.len(),
            self.output_path
        );

        let mut file = std::fs::File::create(&self.output_path)?;

        // Convert events to actions
        let actions = self.events_to_actions();

        // Write header
        writeln!(file, "//! Auto-generated robot test from recording")?;
        writeln!(file, "//! Generated at: {}", chrono_lite())?;
        writeln!(file, "//! Events: {}", self.events.len())?;
        writeln!(file, "//! Actions: {}", actions.len())?;
        writeln!(file)?;
        writeln!(
            file,
            "use cranpose::recorder::{{RobotAction, execute_actions}};"
        )?;
        writeln!(file, "use cranpose::AppLauncher;")?;
        writeln!(file, "use RobotAction::*;")?;
        writeln!(file, "use std::time::Duration;")?;
        writeln!(file)?;

        // Write the actions array
        writeln!(file, "const ACTIONS: &[RobotAction] = &[")?;
        for action in &actions {
            let action_str = match action {
                RobotAction::Sleep(ms) => format!("    Sleep({}),", ms),
                RobotAction::MouseMove(x, y) => format!("    MouseMove({:.1}, {:.1}),", x, y),
                RobotAction::MouseDown => "    MouseDown,".to_string(),
                RobotAction::MouseUp => "    MouseUp,".to_string(),
                RobotAction::Key(key) => format!("    Key(\"{}\".into()),", key),
            };
            writeln!(file, "{}", action_str)?;
        }
        writeln!(file, "];")?;
        writeln!(file)?;

        // Write main function
        writeln!(file, "fn main() {{")?;
        writeln!(file, "    AppLauncher::new()")?;
        writeln!(file, "        .with_headless(true)")?;
        writeln!(file, "        .with_test_driver(|robot| {{")?;
        writeln!(
            file,
            "            std::thread::sleep(Duration::from_millis(500));"
        )?;
        writeln!(file, "            let _ = robot.wait_for_idle();")?;
        writeln!(file)?;
        writeln!(file, "            execute_actions(&robot, ACTIONS);")?;
        writeln!(file)?;
        writeln!(
            file,
            "            std::thread::sleep(Duration::from_secs(1));"
        )?;
        writeln!(file, "            let _ = robot.exit();")?;
        writeln!(file, "        }})")?;
        writeln!(file, "        .run(|| {{")?;
        writeln!(
            file,
            "            // TODO: Replace with your app's composable"
        )?;
        writeln!(file, "            // desktop_app::app::combined_app();")?;
        writeln!(file, "        }});")?;
        writeln!(file, "}}")?;

        eprintln!("[Recorder] Robot test saved to {:?}", self.output_path);
        Ok(())
    }

    /// Convert recorded events to robot actions.
    ///
    /// This transforms timestamped events into a sequence of actions with
    /// relative Sleep delays between them.
    fn events_to_actions(&self) -> Vec<RobotAction> {
        let mut actions = Vec::new();
        let mut last_time_ms = 0u64;

        for event in &self.events {
            let (time_ms, action) = match event {
                RecordedEvent::MouseMove { time_ms, x, y } => {
                    (*time_ms, Some(RobotAction::MouseMove(*x, *y)))
                }
                RecordedEvent::MouseDown { time_ms } => (*time_ms, Some(RobotAction::MouseDown)),
                RecordedEvent::MouseUp { time_ms } => (*time_ms, Some(RobotAction::MouseUp)),
                RecordedEvent::KeyDown { time_ms, key } => {
                    (*time_ms, Some(RobotAction::Key(key.clone())))
                }
                RecordedEvent::KeyUp { time_ms: _, key: _ } => {
                    // Skip key up - send_key does press+release
                    continue;
                }
            };

            // Add sleep for timing (only if > 5ms to avoid noise)
            let delta = time_ms.saturating_sub(last_time_ms);
            if delta > 5 {
                actions.push(RobotAction::Sleep(delta));
            }

            if let Some(action) = action {
                actions.push(action);
            }
            last_time_ms = time_ms;
        }

        actions
    }
}

impl Drop for InputRecorder {
    fn drop(&mut self) {
        if let Err(e) = self.finish() {
            eprintln!("[Recorder] Failed to save recording: {}", e);
        }
    }
}

/// Simple timestamp without chrono
fn chrono_lite() -> String {
    // Just use a placeholder - actual time would require chrono crate
    "timestamp".to_string()
}

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

    #[test]
    fn test_recorder_generates_data_driven_code() {
        let temp_path = std::env::temp_dir().join("test_recording.rs");
        {
            let mut recorder = InputRecorder::new(&temp_path);
            recorder.record_mouse_move(100.0, 200.0);
            recorder.record_mouse_down();
            recorder.record_mouse_up();
            // finish() called on drop
        }

        let mut content = String::new();
        std::fs::File::open(&temp_path)
            .unwrap()
            .read_to_string(&mut content)
            .unwrap();

        // Verify data-driven format
        assert!(content.contains("use cranpose::recorder::{RobotAction, execute_actions};"));
        assert!(content.contains("const ACTIONS: &[RobotAction] = &["));
        assert!(content.contains("MouseMove(100.0, 200.0)"));
        assert!(content.contains("MouseDown,"));
        assert!(content.contains("MouseUp,"));
        assert!(content.contains("execute_actions(&robot, ACTIONS);"));

        std::fs::remove_file(&temp_path).ok();
    }

    #[test]
    fn test_events_to_actions_conversion() {
        let mut recorder = InputRecorder::new("/dev/null");

        // Simulate events with timestamps
        recorder.events.push(RecordedEvent::MouseMove {
            time_ms: 0,
            x: 100.0,
            y: 200.0,
        });
        recorder
            .events
            .push(RecordedEvent::MouseDown { time_ms: 50 });
        recorder.events.push(RecordedEvent::MouseMove {
            time_ms: 60,
            x: 150.0,
            y: 250.0,
        });
        recorder
            .events
            .push(RecordedEvent::MouseUp { time_ms: 100 });

        let actions = recorder.events_to_actions();

        // Verify conversion: 4 actions + 3 sleeps (first event at 0ms has no preceding sleep)
        assert_eq!(actions.len(), 7);
        assert!(matches!(actions[0], RobotAction::MouseMove(100.0, 200.0)));
        assert!(matches!(actions[1], RobotAction::Sleep(50)));
        assert!(matches!(actions[2], RobotAction::MouseDown));
        assert!(matches!(actions[3], RobotAction::Sleep(10)));
        assert!(matches!(actions[4], RobotAction::MouseMove(150.0, 250.0)));
        assert!(matches!(actions[5], RobotAction::Sleep(40)));
        assert!(matches!(actions[6], RobotAction::MouseUp));
    }

    #[test]
    fn test_robot_action_enum() {
        // Verify enum variants can be constructed
        let actions = [
            RobotAction::Sleep(100),
            RobotAction::MouseMove(50.0, 75.5),
            RobotAction::MouseDown,
            RobotAction::MouseUp,
            RobotAction::Key("Enter".to_string()),
        ];

        assert_eq!(actions.len(), 5);
        assert_eq!(actions[0], RobotAction::Sleep(100));
        assert_eq!(actions[1], RobotAction::MouseMove(50.0, 75.5));
        assert_eq!(actions[2], RobotAction::MouseDown);
        assert_eq!(actions[3], RobotAction::MouseUp);
        assert_eq!(actions[4], RobotAction::Key("Enter".to_string()));
    }
}