pixelactions 0.4.0

Execute desktop interactions from pixelcoords sessions: resolve a labeled region, act at the verified point, confirm it landed
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
//! pixelactions — execute desktop interactions from pixelcoords sessions.
//!
//! `plan` resolves and reports without touching anything; `run` performs
//! the flow and confirms each step against a fresh capture. Dry-run is
//! permanent, not a phase — a wrong coordinate is a click in the wrong
//! place, and seeing the numbers first is how that gets caught.

mod cli;
mod doctor;
#[cfg(target_os = "linux")]
mod eis;
mod inject;
#[cfg(target_os = "macos")]
mod mac;
#[cfg(target_os = "linux")]
mod portal;
mod run;
mod serve;
mod session;
mod verify;
#[cfg(target_os = "windows")]
mod win;

use anyhow::Result;
use clap::Parser;
use pixelactions_core::convert::Space;
use pixelactions_core::flow::Flow;
use pixelactions_core::plan::{Plan, plan};

/// Exit codes are the API (same contract as the sister tool, plus 3):
/// 0 done · 1 a step failed honestly · 2 malformed question · 3 refused.
const EXIT_MALFORMED: i32 = 2;
pub const EXIT_REFUSED: i32 = 3;

fn main() {
    // Before anything asks Windows about a coordinate. A process that is
    // not per-monitor-v2 aware is handed coordinates virtualized against
    // the primary monitor's scale, so on a mixed-DPI desktop the numbers
    // the OS reports and the pixels pixelcoords recorded would be different
    // quantities — and pixelcoords declares the same awareness, in the same
    // place, for the same reason. Idempotent and best-effort; `doctor`
    // reports whether it actually holds.
    #[cfg(target_os = "windows")]
    let _ = win::become_dpi_aware();

    let cli = cli::Cli::parse();
    let result = match cli.command {
        cli::Command::Plan {
            flow,
            session,
            verbs,
            json,
            space,
        } => run_plan(
            &Source {
                flow,
                session,
                verbs,
            },
            json,
            space.map(Into::into),
        ),
        cli::Command::Run {
            flow,
            session,
            verbs,
            json,
            yes,
        } => run_flow(
            &Source {
                flow,
                session,
                verbs,
            },
            json,
            yes,
        ),
        cli::Command::Serve { session } => serve::run(&expand_home(&session.display().to_string())),
        cli::Command::Doctor { json, probe } => doctor::run(json, probe),
    };
    match result {
        Ok(code) => std::process::exit(code),
        Err(error) => {
            eprintln!("pixelactions: {error:#}");
            std::process::exit(EXIT_MALFORMED);
        }
    }
}

/// Perform a flow. Returns the process exit code rather than exiting, so
/// the run report is always printed first.
fn run_flow(source: &Source, json: bool, yes: bool) -> Result<i32> {
    // Whether input can be synthesized is a runtime question on Linux —
    // an X11 session and a Wayland session need different paths, and the
    // compositor may implement neither. Asked before anything is loaded,
    // so a refusal is the first thing the reader sees.
    if let Err(reason) = inject::availability() {
        eprintln!("pixelactions: {reason}");
        return Ok(EXIT_REFUSED);
    }
    // Refuse before acting, not after a confusing failure: relocation and
    // verification both run through the pixelcoords binary.
    if let Err(reason) = doctor::require_supported_pixelcoords() {
        eprintln!("pixelactions: {reason}");
        return Ok(EXIT_REFUSED);
    }
    let (flow, session_path, session) = load_flow(source)?;
    let space = flow.settings.space;
    let resolved = plan(&flow, &session, space)?;

    if !yes {
        eprintln!(
            "about to perform {} steps — this moves your mouse and keyboard.",
            resolved.steps.len()
        );
        eprintln!(
            "run the same arguments with `plan` first to see every coordinate, then pass --yes."
        );
        return Ok(EXIT_REFUSED);
    }

    let mut verifier =
        |session: &std::path::Path, label: Option<&str>| verify::find(session, label);

    if !json {
        println!("session: {}", session_path.display());
        println!();
    }
    // Say what the pause is. Confirming a region is a real screen capture
    // and a template match — seconds, not milliseconds — and a terminal
    // that sits blank through it looks hung rather than careful.
    let checking = flow.acting_targets();
    if flow.settings.relocate && !checking.is_empty() {
        eprintln!("checking {} region(s) before acting", checking.len());
    }
    // Reported one at a time, because each is a real capture and match —
    // roughly a second and a half apiece. A single line up front would go
    // quiet for as long as the check takes.
    let found = |label: &str| {
        use std::io::Write;
        eprintln!("  found {label}");
        let _ = std::io::stderr().flush();
    };

    // Refuse before acting when the screen has drifted from the capture:
    // clicking coordinates whose regions have moved is vandalism, not
    // automation.
    let corrections = match run::preflight(
        &flow,
        &session_path,
        &session.monitors,
        space,
        &mut verifier,
        &found,
    ) {
        Ok(corrections) => corrections,
        Err(refusal) => {
            eprintln!("pixelactions: {refusal:#}");
            return Ok(EXIT_REFUSED);
        }
    };
    if !corrections.is_empty() {
        eprintln!(
            "{} region(s) moved since capture — acting on where they are now",
            corrections.len()
        );
    }

    // Machine output is one document, so it cannot be streamed; a human
    // watching an eleven-second run should see each step as it finishes
    // rather than a silent terminal and then a wall of text.
    let live = |step: &pixelactions_core::report::StepReport| print_step(step);
    let progress: &dyn Fn(&pixelactions_core::report::StepReport) =
        if json { run::silent() } else { &live };

    let mut injector = make_injector(&session.monitors)?;
    let report = run::execute(
        injector.as_mut(),
        &run::Context {
            flow: &flow,
            plan: &resolved,
            session: &session_path,
            monitors: &session.monitors,
            corrections: &corrections,
            // Preflight just swept every region this run will act on.
            checked: flow.settings.relocate,
            progress,
        },
        &mut verifier,
    );

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    }
    Ok(report.exit_code())
}

/// Build the real injector.
///
/// The monitors are a parameter because Wayland needs them: a physical
/// pixel only means something there once it is mapped into the region the
/// compositor granted, and that mapping needs the session's own layout.
/// Platforms whose input space is knowable at compile time ignore them.
#[cfg(target_os = "macos")]
pub fn make_injector(
    _monitors: &[pixelcoords_core::session::MonitorRecord],
) -> Result<Box<dyn inject::Injector>> {
    Ok(Box::new(inject::RealInjector::new()?))
}

/// Linux picks its injector at runtime, because the display server is not
/// a build-time fact. Getting this wrong is worse than failing: XTEST on a
/// Wayland session reaches `XWayland` clients only, so the pointer would
/// travel over native windows that never see the events. `availability`
/// has already refused a session with no path by the time this runs; the
/// arm is here so that stays true by construction rather than by comment.
#[cfg(target_os = "linux")]
pub fn make_injector(
    monitors: &[pixelcoords_core::session::MonitorRecord],
) -> Result<Box<dyn inject::Injector>> {
    use pixelactions_core::display::Server;

    match inject::session_server() {
        Server::X11 => Ok(Box::new(inject::X11Injector::new()?)),
        Server::Wayland => Ok(Box::new(inject::WaylandInjector::new(monitors)?)),
        Server::Unknown => anyhow::bail!(
            "no desktop session was found — neither XDG_SESSION_TYPE, WAYLAND_DISPLAY nor \
             DISPLAY names one, so there is nothing to send input to"
        ),
    }
}

/// Windows has one input path and no grant to negotiate, so this is as
/// direct as macOS. What differs is underneath: the pointer goes out as
/// `SendInput` across the virtual desktop rather than through enigo, which
/// would address the primary monitor only.
#[cfg(target_os = "windows")]
pub fn make_injector(
    _monitors: &[pixelcoords_core::session::MonitorRecord],
) -> Result<Box<dyn inject::Injector>> {
    Ok(Box::new(inject::WindowsInjector::new()?))
}

#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
pub fn make_injector(
    _monitors: &[pixelcoords_core::session::MonitorRecord],
) -> Result<Box<dyn inject::Injector>> {
    anyhow::bail!("input synthesis is not implemented for this platform yet")
}

/// One finished step, printed as it lands.
///
/// Flushed rather than left to line buffering: a run spends seconds in
/// screen captures, and a step that has finished should be on screen
/// before the next one starts, whether stdout is a terminal or a pipe.
fn print_step(step: &pixelactions_core::report::StepReport) {
    use std::io::Write;

    // Padded to a fixed width so the step list reads as a column.
    let mark = format!("{:<8}", step.outcome.name());
    println!(
        "  {} {:>2}. {} ({} ms)",
        mark,
        step.index + 1,
        step.summary,
        step.elapsed_ms
    );
    if let Some(detail) = &step.detail {
        println!("            {detail}");
    }
    let _ = std::io::stdout().flush();
}

/// Where a run's steps came from: a flow file, or verbs chained on the
/// command line. Both produce the same `Flow`, so everything downstream
/// — resolution, relocation, bounds, verification — is identical, and
/// learning one surface teaches the other.
pub struct Source {
    pub flow: Option<std::path::PathBuf>,
    pub session: Option<std::path::PathBuf>,
    pub verbs: Vec<String>,
}

/// Read a flow and its session together — the pairing every command needs.
fn load_flow(
    source: &Source,
) -> Result<(
    Flow,
    std::path::PathBuf,
    pixelcoords_core::session::SessionFile,
)> {
    let flow = build_flow(source)?;
    let session_path = expand_home(&flow.session);
    let session = session::load(&session_path)?;
    Ok((flow, session_path, session))
}

fn build_flow(source: &Source) -> Result<Flow> {
    if let Some(path) = &source.flow {
        if !source.verbs.is_empty() {
            anyhow::bail!(
                "pass a flow file or chained verbs, not both — the flow already lists its steps"
            );
        }
        let text = std::fs::read_to_string(path)
            .map_err(|e| anyhow::anyhow!("cannot read {}: {e}", path.display()))?;
        return Ok(Flow::parse(&text)?);
    }
    let Some(directory) = &source.session else {
        anyhow::bail!("need either --flow FILE or --session DIR with chained verbs");
    };
    if source.verbs.is_empty() {
        anyhow::bail!("nothing to do — pass verbs like click:submit, or --flow with a file");
    }
    Ok(Flow {
        session: directory.display().to_string(),
        settings: pixelactions_core::flow::Settings::default(),
        steps: pixelactions_core::verb::parse_all(&source.verbs)?,
    })
}

/// Resolve every step and print the result. Acts on nothing.
fn run_plan(source: &Source, json: bool, space: Option<Space>) -> Result<i32> {
    let (flow, session_path, session) = load_flow(source)?;
    let space = space.unwrap_or(flow.settings.space);
    let resolved = plan(&flow, &session, space)?;

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&as_json(&flow, &resolved))?
        );
        return Ok(0);
    }
    print_human(&flow, &resolved, &session_path);
    Ok(0)
}

fn print_human(flow: &Flow, resolved: &Plan, session_path: &std::path::Path) {
    println!("session:  {}", session_path.display());
    println!(
        "settings: relocate={} verify={:?} space={:?} settle={}ms",
        flow.settings.relocate, flow.settings.verify, flow.settings.space, flow.settings.settle_ms
    );
    println!("steps:    {}", resolved.steps.len());
    println!();
    for step in &resolved.steps {
        println!("  {:>2}. {}", step.index + 1, step.summary);
        for point in &step.points {
            println!(
                "      → ({:.0}, {:.0}) {:?} on monitor {} (scale {})",
                point.x, point.y, point.space, point.monitor, point.scale
            );
        }
    }
    println!();
    println!("nothing was executed — this build resolves only");
}

fn as_json(flow: &Flow, resolved: &Plan) -> serde_json::Value {
    serde_json::json!({
        "schema": 1,
        "session": flow.session,
        "settings": {
            "relocate": flow.settings.relocate,
            "space": flow.settings.space,
            "settle_ms": flow.settings.settle_ms,
        },
        "steps": resolved.steps.iter().map(|step| serde_json::json!({
            "index": step.index,
            "summary": step.summary,
            "points": step.points,
        })).collect::<Vec<_>>(),
        "executed": false,
    })
}

/// Expand a leading `~` — flow files are hand-written, and a session path
/// under the home directory is the common case.
fn expand_home(path: &str) -> std::path::PathBuf {
    let Some(rest) = path.strip_prefix("~/") else {
        return std::path::PathBuf::from(path);
    };
    let Some(home) = std::env::var_os("HOME") else {
        return std::path::PathBuf::from(path);
    };
    std::path::PathBuf::from(home).join(rest)
}

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

    #[test]
    fn home_expansion_handles_the_common_shapes() {
        // SAFETY-free: this only reads the variable it just set.
        unsafe { std::env::set_var("HOME", "/home/tester") };
        // Built with `join` rather than spelled out, because the
        // separator it inserts is the platform's own — a literal
        // "/home/tester/captures/x" passes on Unix and fails on Windows,
        // where the correct answer contains a backslash.
        assert_eq!(
            expand_home("~/captures/x"),
            std::path::PathBuf::from("/home/tester").join("captures/x")
        );
        assert_eq!(
            expand_home("/absolute/path").to_str(),
            Some("/absolute/path")
        );
        assert_eq!(expand_home("relative/path").to_str(), Some("relative/path"));
        // A bare "~" is not a home reference in shell either.
        assert_eq!(expand_home("~").to_str(), Some("~"));
    }
}