waterui-cli 0.1.4

Cross-platform tooling for WaterUI applications
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
//! `water device` command implementation.

use std::path::PathBuf;

use clap::{Args as ClapArgs, Subcommand};
use color_eyre::eyre::{self, Result};

use crate::shell::Shell;
use crate::{error, line, note, success};
use waterui_cli::{android, apple, capture, gesture};

/// Arguments for the device command.
#[derive(ClapArgs, Debug)]
pub struct Args {
    #[command(subcommand)]
    command: DeviceCommand,
}

/// Device subcommands.
#[derive(Subcommand, Debug)]
pub enum DeviceCommand {
    /// Capture a screenshot from a device.
    Capture(CaptureArgs),

    /// Perform a tap gesture on a device.
    Tap(TapArgs),

    /// Perform a swipe gesture on a device.
    Swipe(SwipeArgs),

    /// Input text on a device.
    Text(TextArgs),

    /// Describe UI elements on the screen (for automation).
    Describe(DescribeArgs),
}

/// Arguments for the capture subcommand.
#[derive(ClapArgs, Debug)]
pub struct CaptureArgs {
    /// Device identifier (UDID for iOS, serial for Android, "local" for macOS).
    /// Mutually exclusive with --pid.
    #[arg(long, conflicts_with = "pid")]
    id: Option<String>,

    /// Process ID for macOS local app window capture.
    /// Mutually exclusive with --id.
    #[arg(long, conflicts_with = "id")]
    pid: Option<i32>,

    /// Capture a specific window by index (0-based). Default: 0 (main window).
    /// Only valid with --pid.
    #[arg(long, requires = "pid")]
    window: Option<usize>,

    /// Capture all windows of the process.
    /// Only valid with --pid.
    #[arg(long, requires = "pid", conflicts_with = "window")]
    all_windows: bool,

    /// Output file path. Defaults to `screenshot_YYYY-MM-DD_HHMMSS.png` in current directory.
    /// For --all-windows, this is ignored; use --output-dir instead.
    #[arg(short, long)]
    output: Option<PathBuf>,

    /// Output directory for multiple window screenshots (used with --all-windows).
    #[arg(long, requires = "all_windows")]
    output_dir: Option<PathBuf>,
}

/// Arguments for the tap subcommand.
#[derive(ClapArgs, Debug)]
pub struct TapArgs {
    /// Device identifier (UDID for iOS, serial for Android, "local" for macOS).
    #[arg(long)]
    id: String,

    /// X coordinate.
    #[arg(long)]
    x: u32,

    /// Y coordinate.
    #[arg(long)]
    y: u32,

    /// Capture before/after screenshots and output diff info.
    #[arg(long)]
    diff: bool,

    /// Path to save the diff image (only used with --diff).
    #[arg(long)]
    diff_output: Option<PathBuf>,

    /// Delay in milliseconds after gesture before capturing "after" screenshot.
    #[arg(long, default_value = "500")]
    delay: u32,
}

/// Arguments for the swipe subcommand.
#[derive(ClapArgs, Debug)]
pub struct SwipeArgs {
    /// Device identifier (UDID for iOS, serial for Android, "local" for macOS).
    #[arg(long)]
    id: String,

    /// Starting coordinates as "x,y".
    #[arg(long, value_parser = parse_coords)]
    from: (u32, u32),

    /// Ending coordinates as "x,y".
    #[arg(long, value_parser = parse_coords)]
    to: (u32, u32),

    /// Duration of the swipe in milliseconds.
    #[arg(long)]
    duration: Option<u32>,

    /// Capture before/after screenshots and output diff info.
    #[arg(long)]
    diff: bool,

    /// Path to save the diff image (only used with --diff).
    #[arg(long)]
    diff_output: Option<PathBuf>,

    /// Delay in milliseconds after gesture before capturing "after" screenshot.
    #[arg(long, default_value = "500")]
    delay: u32,
}

/// Arguments for the text subcommand.
#[derive(ClapArgs, Debug)]
pub struct TextArgs {
    /// Device identifier (UDID for iOS, serial for Android, "local" for macOS).
    #[arg(long)]
    id: String,

    /// Text to input.
    #[arg(long)]
    input: String,

    /// Capture before/after screenshots and output diff info.
    #[arg(long)]
    diff: bool,

    /// Path to save the diff image (only used with --diff).
    #[arg(long)]
    diff_output: Option<PathBuf>,

    /// Delay in milliseconds after gesture before capturing "after" screenshot.
    #[arg(long, default_value = "500")]
    delay: u32,
}

/// Arguments for the describe subcommand.
#[derive(ClapArgs, Debug)]
pub struct DescribeArgs {
    /// Device identifier (UDID for iOS, serial for Android).
    #[arg(long)]
    id: String,
}

/// Parse coordinate string "x,y" into tuple.
fn parse_coords(s: &str) -> Result<(u32, u32), String> {
    let parts: Vec<&str> = s.split(',').collect();
    if parts.len() != 2 {
        return Err("Expected format: x,y (e.g., 100,200)".to_string());
    }
    let x = parts[0]
        .trim()
        .parse::<u32>()
        .map_err(|_| "Invalid X coordinate")?;
    let y = parts[1]
        .trim()
        .parse::<u32>()
        .map_err(|_| "Invalid Y coordinate")?;
    Ok((x, y))
}

/// Run the device command.
pub async fn run(shell: &Shell, args: Args) -> Result<()> {
    match args.command {
        DeviceCommand::Capture(capture_args) => run_capture(shell, capture_args).await,
        DeviceCommand::Tap(tap_args) => run_tap(shell, tap_args).await,
        DeviceCommand::Swipe(swipe_args) => run_swipe(shell, swipe_args).await,
        DeviceCommand::Text(text_args) => run_text(shell, text_args).await,
        DeviceCommand::Describe(describe_args) => run_describe(shell, describe_args).await,
    }
}

/// Run the capture subcommand.
async fn run_capture(shell: &Shell, args: CaptureArgs) -> Result<()> {
    // Handle PID-based capture (macOS window capture)
    if let Some(pid) = args.pid {
        return run_capture_by_pid(
            shell,
            pid,
            args.window,
            args.all_windows,
            args.output,
            args.output_dir,
        )
        .await;
    }

    // Handle device ID-based capture
    let device_id = args.id.as_deref().unwrap_or(gesture::LOCAL_DEVICE_ID);

    // Handle local device for macOS (full screen)
    if device_id == gesture::LOCAL_DEVICE_ID {
        let output = args
            .output
            .unwrap_or_else(capture::generate_screenshot_filename);

        match waterui_cli::apple::local::screenshot(&output).await {
            Ok(()) => {
                success!(
                    shell,
                    "Screenshot saved to {} (from macOS local)",
                    output.display()
                );
                return Ok(());
            }
            Err(e) => {
                error!(shell, "Failed to capture screenshot: {e}");
                return Err(e);
            }
        }
    }

    // Verify the device exists
    let platform = match capture::verify_device(device_id).await {
        Ok(p) => p,
        Err(e) => {
            error!(shell, "Device not found: {e}");
            return Err(e);
        }
    };

    // Generate output filename if not provided
    let output = args
        .output
        .unwrap_or_else(capture::generate_screenshot_filename);

    // Capture the screenshot
    let platform_name = match platform {
        capture::DevicePlatform::Ios => "iOS simulator",
        capture::DevicePlatform::Android => "Android device",
    };

    match capture::screenshot(device_id, &output).await {
        Ok(()) => {
            success!(
                shell,
                "Screenshot saved to {} (from {})",
                output.display(),
                platform_name
            );
            Ok(())
        }
        Err(e) => {
            error!(shell, "Failed to capture screenshot: {e}");
            Err(e)
        }
    }
}

/// Run capture by PID (macOS window capture).
async fn run_capture_by_pid(
    shell: &Shell,
    pid: i32,
    window_index: Option<usize>,
    all_windows: bool,
    output: Option<PathBuf>,
    output_dir: Option<PathBuf>,
) -> Result<()> {
    use waterui_cli::apple::local::{list_windows_by_pid, screenshot_window};

    // Get windows for this PID
    let windows = list_windows_by_pid(pid)?;

    if windows.is_empty() {
        error!(shell, "No windows found for PID {pid}");
        eyre::bail!("No windows found for PID {pid}");
    }

    // Filter to only normal windows (layer 0)
    let normal_windows: Vec<_> = windows.iter().filter(|w| w.layer == 0).collect();

    if normal_windows.is_empty() {
        error!(
            shell,
            "No normal windows found for PID {pid} (found {} auxiliary windows)",
            windows.len()
        );
        eyre::bail!("No normal windows found for PID {pid}");
    }

    if all_windows {
        // Capture all windows
        let dir = output_dir.unwrap_or_else(|| PathBuf::from("."));
        smol::fs::create_dir_all(&dir).await?;

        for (i, window) in normal_windows.iter().enumerate() {
            let filename = if window.name.is_empty() {
                format!("window_{i}.png")
            } else {
                // Sanitize window name for filename
                let safe_name: String = window
                    .name
                    .chars()
                    .map(|c| {
                        if c.is_alphanumeric() || c == '-' || c == '_' {
                            c
                        } else {
                            '_'
                        }
                    })
                    .collect();
                format!("window_{i}_{safe_name}.png")
            };
            let path = dir.join(&filename);

            match screenshot_window(window.window_id, &path).await {
                Ok(()) => {
                    success!(
                        shell,
                        "Window {i} \"{}\" saved to {}",
                        window.name,
                        path.display()
                    );
                }
                Err(e) => {
                    error!(shell, "Failed to capture window {i}: {e}");
                }
            }
        }

        note!(
            shell,
            "Captured {} windows for PID {pid}",
            normal_windows.len()
        );
        Ok(())
    } else {
        // Capture single window
        let index = window_index.unwrap_or(0);

        if index >= normal_windows.len() {
            error!(
                shell,
                "Window index {index} out of range (found {} windows)",
                normal_windows.len()
            );
            eyre::bail!(
                "Window index {index} out of range (found {} windows)",
                normal_windows.len()
            );
        }

        let window = &normal_windows[index];
        let output_path = output.unwrap_or_else(capture::generate_screenshot_filename);

        match screenshot_window(window.window_id, &output_path).await {
            Ok(()) => {
                success!(
                    shell,
                    "Screenshot saved to {} (window \"{}\" from PID {pid})",
                    output_path.display(),
                    window.name
                );
                Ok(())
            }
            Err(e) => {
                error!(shell, "Failed to capture screenshot: {e}");
                Err(e)
            }
        }
    }
}

/// Build gesture options from args.
const fn build_gesture_options(
    diff: bool,
    diff_output: Option<PathBuf>,
    delay: u32,
) -> gesture::GestureOptions {
    gesture::GestureOptions {
        diff,
        diff_output,
        delay_ms: Some(delay),
    }
}

/// Print diff result if present.
fn print_diff_result(
    shell: &Shell,
    result: &gesture::GestureResult,
    diff_output: Option<&std::path::Path>,
) {
    if let Some(diff) = &result.diff {
        if let Some(path) = diff_output {
            success!(shell, "Diff image saved to {}", path.display());
        }
        note!(shell, "Diff result:\n{diff}");
    }
}

/// Run the tap subcommand.
async fn run_tap(shell: &Shell, args: TapArgs) -> Result<()> {
    let device_id = &args.id;

    // Verify device exists
    gesture::verify_device(device_id).await?;

    let options = build_gesture_options(args.diff, args.diff_output.clone(), args.delay);

    match gesture::tap(device_id, args.x, args.y, &options).await {
        Ok(result) => {
            success!(shell, "Tap at ({}, {})", args.x, args.y);
            print_diff_result(shell, &result, args.diff_output.as_deref());
            Ok(())
        }
        Err(e) => {
            error!(shell, "Failed to tap: {e}");
            Err(e)
        }
    }
}

/// Run the swipe subcommand.
async fn run_swipe(shell: &Shell, args: SwipeArgs) -> Result<()> {
    let device_id = &args.id;

    // Verify device exists
    gesture::verify_device(device_id).await?;

    let options = build_gesture_options(args.diff, args.diff_output.clone(), args.delay);

    match gesture::swipe(device_id, args.from, args.to, args.duration, &options).await {
        Ok(result) => {
            success!(
                shell,
                "Swipe from ({}, {}) to ({}, {})",
                args.from.0,
                args.from.1,
                args.to.0,
                args.to.1
            );
            print_diff_result(shell, &result, args.diff_output.as_deref());
            Ok(())
        }
        Err(e) => {
            error!(shell, "Failed to swipe: {e}");
            Err(e)
        }
    }
}

/// Run the text subcommand.
async fn run_text(shell: &Shell, args: TextArgs) -> Result<()> {
    let device_id = &args.id;

    // Verify device exists
    gesture::verify_device(device_id).await?;

    let options = build_gesture_options(args.diff, args.diff_output.clone(), args.delay);

    match gesture::text(device_id, &args.input, &options).await {
        Ok(result) => {
            success!(shell, "Text input: \"{}\"", args.input);
            print_diff_result(shell, &result, args.diff_output.as_deref());
            Ok(())
        }
        Err(e) => {
            error!(shell, "Failed to input text: {e}");
            Err(e)
        }
    }
}

/// Run the describe subcommand.
async fn run_describe(shell: &Shell, args: DescribeArgs) -> Result<()> {
    let device_id = &args.id;

    // Local macOS device is not supported
    if device_id == gesture::LOCAL_DEVICE_ID {
        eyre::bail!("Describe is not supported for local macOS device");
    }

    // Get platform and call appropriate describe function
    let json = match capture::detect_platform(device_id) {
        capture::DevicePlatform::Ios => apple::device::describe(device_id).await?,
        capture::DevicePlatform::Android => android::device::describe(device_id).await?,
    };

    if shell.is_json() {
        // JSON mode: output raw JSON
        let _ = shell.json_raw(&json);
    } else {
        // Readable mode: format as table
        print_ui_elements_readable(shell, &json)?;
    }

    Ok(())
}

/// Print UI elements in human-readable format.
fn print_ui_elements_readable(shell: &Shell, json: &str) -> Result<()> {
    let elements: Vec<serde_json::Value> = serde_json::from_str(json)?;

    line!(shell, "UI Elements ({} found):", elements.len());
    line!(shell, "{}", "-".repeat(80));

    for (i, elem) in elements.iter().enumerate() {
        let label = elem.get("AXLabel").and_then(|v| v.as_str()).unwrap_or("-");
        let elem_type = elem.get("type").and_then(|v| v.as_str()).unwrap_or("-");
        let value = elem.get("AXValue").and_then(|v| v.as_str()).unwrap_or("");

        // Get frame info
        let frame = elem.get("frame");
        let (x, y, w, h) = frame.map_or((0.0, 0.0, 0.0, 0.0), |frame| {
            (
                frame
                    .get("x")
                    .and_then(serde_json::Value::as_f64)
                    .unwrap_or(0.0),
                frame
                    .get("y")
                    .and_then(serde_json::Value::as_f64)
                    .unwrap_or(0.0),
                frame
                    .get("width")
                    .and_then(serde_json::Value::as_f64)
                    .unwrap_or(0.0),
                frame
                    .get("height")
                    .and_then(serde_json::Value::as_f64)
                    .unwrap_or(0.0),
            )
        });

        // Calculate center point for tapping
        let center_x = x + w / 2.0;
        let center_y = y + h / 2.0;

        // Only show elements with a label or value
        if label != "-" || !value.is_empty() {
            let display_value = if value.is_empty() { label } else { value };
            let label_suffix = if value.is_empty() || label == "-" {
                String::new()
            } else {
                format!(" ({label})")
            };
            line!(
                shell,
                "[{}] {} \"{}\"{}",
                i,
                elem_type,
                display_value,
                label_suffix
            );
            line!(
                shell,
                "    tap: --x {center_x:.0} --y {center_y:.0}  (frame: {x:.0},{y:.0} {w:.0}x{h:.0})"
            );
        }
    }

    Ok(())
}