Skip to main content

agentmux_mcp/
desktop_input.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What `Desktop` does to a native app's window: mapping a point in a
5//! screenshot to the screen, reading a key chord, and (on Windows) sending
6//! the input (docs/specs/SPEC_DESKTOP_DRIVING_2026_10_20.md §5.1–5.2).
7//!
8//! Everything before [`win`] is plain logic, tested on every platform. The
9//! rules it enforces are the spec's defence against a stale or invented
10//! coordinate landing on the wrong thing: a point is relative to the image the
11//! last `look` returned, and it is refused if the window moved or resized
12//! since, or the point is outside the window.
13
14use std::collections::HashMap;
15use std::sync::Mutex;
16
17/// `type` takes at most this many characters.
18pub(crate) const MAX_TEXT_CHARS: usize = 500;
19/// `wait` takes at most this long.
20pub(crate) const MAX_WAIT_MS: u64 = 5000;
21/// A screenshot is scaled to at most this on its long edge.
22pub(crate) const MAX_IMAGE_EDGE: u32 = 1568;
23
24/// A window's place on the screen, in physical pixels.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub(crate) struct Rect {
27    pub(crate) x: i32,
28    pub(crate) y: i32,
29    pub(crate) w: u32,
30    pub(crate) h: u32,
31}
32
33/// What the last `look` at a window returned: where the window was, and the
34/// size of the image the agent was shown. Clicks are in that image's pixels.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub(crate) struct Look {
37    pub(crate) rect: Rect,
38    pub(crate) image_w: u32,
39    pub(crate) image_h: u32,
40    /// Which look of this window it was: 1 for the first, one more each time.
41    /// Set by [`remember_look`].
42    pub(crate) n: u32,
43}
44
45static LOOKS: Mutex<Option<HashMap<u32, Look>>> = Mutex::new(None);
46
47/// Remember what `look` showed of window `id`, as the look after the one
48/// before it. Returns the look as stored (numbered) and the one it replaced.
49pub(crate) fn remember_look(id: u32, look: Look) -> (Look, Option<Look>) {
50    let mut g = LOOKS.lock().unwrap_or_else(|e| e.into_inner());
51    let map = g.get_or_insert_with(HashMap::new);
52    let before = map.get(&id).copied();
53    let stored = Look { n: before.map_or(1, |b| b.n.wrapping_add(1).max(1)), ..look };
54    map.insert(id, stored);
55    (stored, before)
56}
57
58/// Whether coordinates the agent says come from look `of` can be used: they
59/// can when `of` is the window's latest look. Otherwise the answer says which
60/// look is the latest, and whether its size differs from the one the
61/// coordinates came from, so the agent knows they are stale.
62pub(crate) fn check_of_look(latest: &Look, of: i64) -> Result<(), String> {
63    if of == latest.n as i64 {
64        return Ok(());
65    }
66    Err(format!(
67        "your coordinates are from look #{of}, but the latest look at this window is #{} ({}×{} pixels); coordinates from an older look can point at the wrong place. Use the latest look's pixels, or look again",
68        latest.n, latest.image_w, latest.image_h
69    ))
70}
71
72/// What a `look` says about how its image relates to the window and to the
73/// look before it: the scale (window pixels per image pixel), and a warning
74/// when the image's size changed since the last look of the same window.
75pub(crate) fn describe_scale(look: &Look, before: Option<&Look>) -> String {
76    let scale = if look.image_w == 0 { 1.0 } else { look.rect.w as f64 / look.image_w as f64 };
77    let mut out = format!(
78        "This is look #{}: the image is {}×{} pixels for a window of {}×{} on the screen (scale {:.2}).",
79        look.n, look.image_w, look.image_h, look.rect.w, look.rect.h, scale
80    );
81    if let Some(b) = before {
82        if (b.image_w, b.image_h) != (look.image_w, look.image_h) {
83            out.push_str(&format!(
84                " The window's size changed since look #{} ({}×{}): coordinates from that look, or any earlier one, are stale.",
85                b.n, b.image_w, b.image_h
86            ));
87        }
88    }
89    out
90}
91
92/// A region of the last look, in that look's pixels, to be shown zoomed.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub(crate) struct Region {
95    pub(crate) x: u32,
96    pub(crate) y: u32,
97    pub(crate) w: u32,
98    pub(crate) h: u32,
99}
100
101/// The smallest region `look` zooms into: smaller is not worth an image.
102pub(crate) const MIN_REGION: u32 = 8;
103/// The most a region is enlarged.
104pub(crate) const MAX_ZOOM: f64 = 4.0;
105
106/// A region inside `look`'s image, or why not.
107pub(crate) fn check_region(look: &Look, x: i64, y: i64, w: i64, h: i64) -> Result<Region, String> {
108    if w < MIN_REGION as i64 || h < MIN_REGION as i64 {
109        return Err(format!("the region is {w}×{h}; it must be at least {MIN_REGION}×{MIN_REGION} pixels"));
110    }
111    // Checked sums: a huge x or y from the caller must read as outside, not overflow.
112    let right = x.checked_add(w);
113    let bottom = y.checked_add(h);
114    if x < 0 || y < 0 || right.is_none_or(|r| r > look.image_w as i64) || bottom.is_none_or(|b| b > look.image_h as i64) {
115        return Err(format!(
116            "the region ({x}, {y}, {w}×{h}) is not inside look #{}'s image, which is {}×{}",
117            look.n, look.image_w, look.image_h
118        ));
119    }
120    Ok(Region { x: x as u32, y: y as u32, w: w as u32, h: h as u32 })
121}
122
123/// How much a `w`×`h` region is enlarged: up to [`MAX_ZOOM`], and not past
124/// [`MAX_IMAGE_EDGE`] on its long edge. Never below 1.
125pub(crate) fn zoom_for(w: u32, h: u32) -> f64 {
126    let long = w.max(h).max(1) as f64;
127    (MAX_IMAGE_EDGE as f64 / long).clamp(1.0, MAX_ZOOM)
128}
129
130/// What the last `look` at window `id` showed, if there was one.
131pub(crate) fn last_look(id: u32) -> Option<Look> {
132    let g = LOOKS.lock().unwrap_or_else(|e| e.into_inner());
133    g.as_ref().and_then(|m| m.get(&id).copied())
134}
135
136/// The size a `w`×`h` window is shown at: its long edge at most
137/// [`MAX_IMAGE_EDGE`], never enlarged.
138pub(crate) fn scaled_size(w: u32, h: u32) -> (u32, u32) {
139    let long = w.max(h);
140    if long <= MAX_IMAGE_EDGE || long == 0 {
141        return (w, h);
142    }
143    let scale = MAX_IMAGE_EDGE as f64 / long as f64;
144    (((w as f64 * scale).round() as u32).max(1), ((h as f64 * scale).round() as u32).max(1))
145}
146
147/// The screen point for image point (`x`, `y`) of `look`, given where the
148/// window is `now`. Refuses, with a reason the agent can act on, when the
149/// window moved or resized since the look or the point is outside the image.
150pub(crate) fn to_screen(look: &Look, now: Rect, x: i64, y: i64) -> Result<(i32, i32), String> {
151    if now != look.rect {
152        return Err("the window moved or resized since you last looked at it; look again".into());
153    }
154    if look.image_w == 0 || look.image_h == 0 || now.w == 0 || now.h == 0 {
155        return Err("the window has no size".into());
156    }
157    if x < 0 || y < 0 || x >= look.image_w as i64 || y >= look.image_h as i64 {
158        return Err(format!(
159            "({x}, {y}) is outside the window's image, which is {}×{}; use the pixels of your last look",
160            look.image_w, look.image_h
161        ));
162    }
163    // The middle of the image pixel, scaled back to the window's own pixels.
164    let sx = now.x as f64 + (x as f64 + 0.5) * now.w as f64 / look.image_w as f64;
165    let sy = now.y as f64 + (y as f64 + 0.5) * now.h as f64 / look.image_h as f64;
166    Ok((sx.floor() as i32, sy.floor() as i32))
167}
168
169/// A screen point as `SendInput` wants it with `MOUSEEVENTF_ABSOLUTE |
170/// MOUSEEVENTF_VIRTUALDESK`: 0..=65535 across the whole virtual screen, which
171/// starts at (`vx`, `vy`) and is `vw`×`vh` pixels.
172pub(crate) fn to_absolute(sx: i32, sy: i32, vx: i32, vy: i32, vw: u32, vh: u32) -> (i32, i32) {
173    let norm = |p: i32, origin: i32, size: u32| -> i32 {
174        let span = (size.max(2) - 1) as i64;
175        (((p as i64 - origin as i64) * 65535) / span).clamp(0, 65535) as i32
176    };
177    (norm(sx, vx, vw), norm(sy, vy, vh))
178}
179
180/// A drag passes through at most this many given points besides its two ends.
181pub(crate) const MAX_DRAG_WAYPOINTS: usize = 8;
182/// The most mouse moves one drag sends, however far it goes.
183pub(crate) const MAX_DRAG_MOVES: usize = 80;
184/// Roughly one move per this many pixels, so an app that samples the pointer
185/// sees a path, not a jump.
186const DRAG_PIXELS_PER_MOVE: f64 = 12.0;
187/// Every leg of a drag has at least this many moves.
188const DRAG_MIN_MOVES_PER_LEG: usize = 4;
189
190/// The screen points a drag moves through, from `start` to `end` by way of
191/// `via`, in order. Each leg is cut into short steps (the last step of a leg
192/// lands exactly on its end), and the whole drag is at most
193/// [`MAX_DRAG_MOVES`] moves. The first point is `start` itself.
194pub(crate) fn drag_path(start: (i32, i32), via: &[(i32, i32)], end: (i32, i32)) -> Vec<(i32, i32)> {
195    let mut stops = vec![start];
196    stops.extend_from_slice(via);
197    stops.push(end);
198    let legs = stops.len() - 1;
199    // Each leg gets the moves its length asks for, within the drag's total.
200    let wanted: Vec<usize> = stops
201        .windows(2)
202        .map(|w| {
203            let d = (((w[1].0 - w[0].0) as f64).powi(2) + ((w[1].1 - w[0].1) as f64).powi(2)).sqrt();
204            ((d / DRAG_PIXELS_PER_MOVE).ceil() as usize).max(DRAG_MIN_MOVES_PER_LEG)
205        })
206        .collect();
207    let total: usize = wanted.iter().sum();
208    let budget = MAX_DRAG_MOVES.max(legs);
209    let mut path = vec![start];
210    for (i, w) in stops.windows(2).enumerate() {
211        let n = if total <= budget { wanted[i] } else { (wanted[i] * budget / total).max(1) };
212        for k in 1..=n {
213            let f = k as f64 / n as f64;
214            let p = if k == n {
215                w[1]
216            } else {
217                (
218                    (w[0].0 as f64 + (w[1].0 - w[0].0) as f64 * f).round() as i32,
219                    (w[0].1 as f64 + (w[1].1 - w[0].1) as f64 * f).round() as i32,
220                )
221            };
222            path.push(p);
223        }
224    }
225    path
226}
227
228/// What a drag does to the mouse and keyboard, one step at a time, for
229/// [`run_drag`] to hand to whatever sends it.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231#[cfg_attr(not(windows), allow(dead_code))]
232pub(crate) enum DragStep {
233    /// Move the pointer to a screen point.
234    Move(i32, i32),
235    KeyDown(u16),
236    KeyUp(u16),
237    ButtonDown,
238    ButtonUp,
239    /// Wait this many milliseconds.
240    Pause(u64),
241}
242
243/// Pause after the pointer arrives and the modifiers go down, before the press.
244const DRAG_SETTLE_MS: u64 = 40;
245/// Pause after the press, before the first move: an app that starts a drag on
246/// the first motion needs to have seen the press.
247const DRAG_PRESS_MS: u64 = 120;
248/// Pause between moves.
249const DRAG_STEP_MS: u64 = 8;
250/// Pause on the last point before the release, so a drop target registers.
251const DRAG_DROP_MS: u64 = 150;
252
253/// Hold `modifiers`, press the button at the first point, move through the
254/// rest, pause, and let go at the last. `out` does each step. Whatever was
255/// pressed is let go again on every exit, including when a step fails: the
256/// button first, then the modifiers in reverse, so a failed drag never leaves
257/// one held. The first error is the one returned.
258#[cfg_attr(not(windows), allow(dead_code))]
259pub(crate) fn run_drag(
260    points: &[(i32, i32)],
261    modifiers: &[u16],
262    out: &mut dyn FnMut(DragStep) -> Result<(), String>,
263) -> Result<(), String> {
264    let mut button_down = false;
265    let mut modifiers_down = 0usize;
266    let result = (|| -> Result<(), String> {
267        let (first, rest) = points.split_first().ok_or("a drag needs points")?;
268        out(DragStep::Move(first.0, first.1))?;
269        for m in modifiers {
270            out(DragStep::KeyDown(*m))?;
271            modifiers_down += 1;
272        }
273        out(DragStep::Pause(DRAG_SETTLE_MS))?;
274        out(DragStep::ButtonDown)?;
275        button_down = true;
276        out(DragStep::Pause(DRAG_PRESS_MS))?;
277        for p in rest {
278            out(DragStep::Move(p.0, p.1))?;
279            out(DragStep::Pause(DRAG_STEP_MS))?;
280        }
281        out(DragStep::Pause(DRAG_DROP_MS))?;
282        out(DragStep::ButtonUp)?;
283        button_down = false;
284        Ok(())
285    })();
286    // Let go of whatever is still held, whatever happened above. Each is tried
287    // even if an earlier one fails.
288    if button_down {
289        let _ = out(DragStep::ButtonUp);
290    }
291    for m in modifiers.iter().take(modifiers_down).rev() {
292        let _ = out(DragStep::KeyUp(*m));
293    }
294    result
295}
296
297/// The modifiers `drag` may hold while it drags: ctrl, alt and shift, written
298/// like a chord without a key (`ctrl+shift`). The Windows key is refused for
299/// the same reason `key` refuses it.
300pub(crate) fn parse_hold(spec: &str) -> Result<Vec<u16>, String> {
301    let mut modifiers = Vec::new();
302    for m in spec.split('+').map(str::trim).filter(|p| !p.is_empty()) {
303        let code = match m.to_lowercase().as_str() {
304            "ctrl" | "control" => VK_CONTROL,
305            "alt" | "option" => VK_MENU,
306            "shift" => VK_SHIFT,
307            "win" | "windows" | "meta" | "cmd" | "command" | "super" => {
308                return Err("the Windows/Command key is not allowed: it acts on the operating system, not the app".into())
309            }
310            other => return Err(format!("unknown key to hold {other:?}; use ctrl, alt or shift")),
311        };
312        if !modifiers.contains(&code) {
313            modifiers.push(code);
314        }
315    }
316    Ok(modifiers)
317}
318
319/// A key chord such as `ctrl+shift+s`: modifiers held, then one key.
320#[derive(Debug, Clone, PartialEq, Eq)]
321pub(crate) struct Chord {
322    /// Virtual-key codes of the modifiers, in the order written.
323    pub(crate) modifiers: Vec<u16>,
324    pub(crate) key: u16,
325}
326
327const VK_SHIFT: u16 = 0x10;
328const VK_CONTROL: u16 = 0x11;
329const VK_MENU: u16 = 0x12;
330
331/// The virtual-key code of a key name, or `None`.
332fn key_code(name: &str) -> Option<u16> {
333    let n = name.to_lowercase();
334    if n.chars().count() == 1 {
335        let c = n.chars().next().unwrap();
336        return match c {
337            'a'..='z' => Some(0x41 + (c as u16 - 'a' as u16)),
338            '0'..='9' => Some(0x30 + (c as u16 - '0' as u16)),
339            _ => None,
340        };
341    }
342    if let Some(num) = n.strip_prefix('f').and_then(|d| d.parse::<u16>().ok()) {
343        return (1..=12).contains(&num).then(|| 0x70 + num - 1);
344    }
345    Some(match n.as_str() {
346        "enter" | "return" => 0x0D,
347        "tab" => 0x09,
348        "esc" | "escape" => 0x1B,
349        "space" => 0x20,
350        "backspace" => 0x08,
351        "delete" | "del" => 0x2E,
352        "insert" => 0x2D,
353        "home" => 0x24,
354        "end" => 0x23,
355        "pageup" => 0x21,
356        "pagedown" => 0x22,
357        "left" => 0x25,
358        "up" => 0x26,
359        "right" => 0x27,
360        "down" => 0x28,
361        _ => return None,
362    })
363}
364
365/// Read a chord. The Windows key is refused: a chord with it acts on the
366/// operating system (Run, the Start menu, lock), not on the app the user
367/// allowed.
368pub(crate) fn parse_keys(spec: &str) -> Result<Chord, String> {
369    let parts: Vec<&str> = spec.split('+').map(str::trim).filter(|p| !p.is_empty()).collect();
370    let Some((last, mods)) = parts.split_last() else {
371        return Err("keys is empty; give a key such as \"enter\" or a chord such as \"ctrl+s\"".into());
372    };
373    let mut modifiers = Vec::new();
374    for m in mods {
375        let code = match m.to_lowercase().as_str() {
376            "ctrl" | "control" => VK_CONTROL,
377            "alt" | "option" => VK_MENU,
378            "shift" => VK_SHIFT,
379            "win" | "windows" | "meta" | "cmd" | "command" | "super" => {
380                return Err("the Windows/Command key is not allowed: it acts on the operating system, not the app".into())
381            }
382            other => return Err(format!("unknown modifier {other:?}; use ctrl, alt or shift")),
383        };
384        if !modifiers.contains(&code) {
385            modifiers.push(code);
386        }
387    }
388    let key = key_code(last).ok_or_else(|| {
389        format!("unknown key {last:?}; use a letter, a digit, f1–f12, or enter, tab, esc, space, backspace, delete, insert, home, end, pageup, pagedown, left, up, right, down")
390    })?;
391    Ok(Chord { modifiers, key })
392}
393
394/// `type`'s text must be non-empty, short, and free of control characters
395/// other than newline and tab.
396pub(crate) fn check_text(text: &str) -> Result<(), String> {
397    if text.is_empty() {
398        return Err("text is empty".into());
399    }
400    let n = text.chars().count();
401    if n > MAX_TEXT_CHARS {
402        return Err(format!("text is {n} characters; the most one call types is {MAX_TEXT_CHARS}"));
403    }
404    if text.chars().any(|c| c.is_control() && c != '\n' && c != '\t') {
405        return Err("text has a control character; use the key action for keys such as escape".into());
406    }
407    Ok(())
408}
409
410#[cfg(windows)]
411pub(crate) mod win {
412    //! `SendInput` for Windows. The process is made per-monitor DPI aware once,
413    //! so the window rectangles `xcap` reports and the points sent here are in
414    //! the same physical pixels.
415
416    use std::mem::size_of;
417    use std::sync::Once;
418    use std::time::Duration;
419
420    use windows_sys::Win32::Foundation::{CloseHandle, BOOL, HWND, LPARAM, POINT, RECT};
421    use windows_sys::Win32::System::Threading::{
422        AttachThreadInput, GetCurrentThreadId, OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
423    };
424    use windows_sys::Win32::UI::HiDpi::{SetProcessDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2};
425    use windows_sys::Win32::UI::Input::KeyboardAndMouse::*;
426    use windows_sys::Win32::UI::WindowsAndMessaging::{
427        BringWindowToTop, EnumChildWindows, GetAncestor, GetForegroundWindow, GetSystemMetrics, GetWindowRect,
428        GetWindowThreadProcessId, IsIconic, SetForegroundWindow, ShowWindow, WindowFromPoint,
429        GA_ROOT, GA_ROOTOWNER, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_RESTORE,
430    };
431
432    use super::{to_absolute, Chord, DragStep, Rect};
433
434    pub(crate) fn ensure_dpi_aware() {
435        static ONCE: Once = Once::new();
436        ONCE.call_once(|| unsafe {
437            // Fails harmlessly if the process already has an awareness.
438            SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
439        });
440    }
441
442    /// The whole window, invisible resize borders included, in physical
443    /// pixels: the area `PrintWindow` (what `look` captures) covers, so an
444    /// image pixel maps onto it without an offset. `xcap`'s own rectangle is
445    /// the visible frame, a few pixels smaller.
446    pub(crate) fn window_rect(id: u32) -> Option<Rect> {
447        ensure_dpi_aware();
448        let mut r = RECT { left: 0, top: 0, right: 0, bottom: 0 };
449        let ok = unsafe { GetWindowRect(id as usize as HWND, &mut r) };
450        if ok == 0 || r.right <= r.left || r.bottom <= r.top {
451            return None;
452        }
453        Some(Rect { x: r.left, y: r.top, w: (r.right - r.left) as u32, h: (r.bottom - r.top) as u32 })
454    }
455
456    /// The executable's file name of the process that owns `hwnd`.
457    fn window_exe_name(hwnd: HWND) -> Option<String> {
458        let mut pid = 0u32;
459        unsafe { GetWindowThreadProcessId(hwnd, &mut pid) };
460        if pid == 0 {
461            return None;
462        }
463        unsafe {
464            let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
465            if process.is_null() {
466                return None;
467            }
468            let mut buf = [0u16; 1024];
469            let mut len = buf.len() as u32;
470            let ok = QueryFullProcessImageNameW(process, PROCESS_NAME_WIN32, buf.as_mut_ptr(), &mut len);
471            CloseHandle(process);
472            if ok == 0 || len == 0 {
473                return None;
474            }
475            let path = String::from_utf16_lossy(&buf[..len as usize]);
476            path.rsplit(['\\', '/']).next().map(str::to_string)
477        }
478    }
479
480    /// Restore window `id` if it is minimised, and wait for it to be drawn.
481    /// Returns whether it was minimised.
482    pub(crate) fn restore_if_minimized(id: u32) -> bool {
483        ensure_dpi_aware();
484        let hwnd = id as usize as HWND;
485        unsafe {
486            if IsIconic(hwnd) == 0 {
487                return false;
488            }
489            ShowWindow(hwnd, SW_RESTORE);
490            for _ in 0..20 {
491                if IsIconic(hwnd) == 0 {
492                    break;
493                }
494                std::thread::sleep(Duration::from_millis(50));
495            }
496        }
497        // Let it paint before it is captured.
498        std::thread::sleep(Duration::from_millis(300));
499        true
500    }
501
502    /// Try to make `hwnd` the foreground window: ask; then join the input
503    /// queue of the window that has the focus (Windows lets a thread joined to
504    /// it take the focus) and ask again. It sends no key or click: whatever
505    /// app has the focus is not one the user allowed, so nothing goes to it.
506    unsafe fn try_foreground(hwnd: HWND) -> bool {
507        unsafe {
508            if GetForegroundWindow() == hwnd {
509                return true;
510            }
511            SetForegroundWindow(hwnd);
512            if GetForegroundWindow() == hwnd {
513                return true;
514            }
515            let fg = GetForegroundWindow();
516            let fg_thread = if fg.is_null() { 0 } else { GetWindowThreadProcessId(fg, std::ptr::null_mut()) };
517            let me = GetCurrentThreadId();
518            let joined = fg_thread != 0 && fg_thread != me && AttachThreadInput(me, fg_thread, 1) != 0;
519            BringWindowToTop(hwnd);
520            SetForegroundWindow(hwnd);
521            if joined {
522                AttachThreadInput(me, fg_thread, 0);
523            }
524            GetForegroundWindow() == hwnd
525        }
526    }
527
528    /// Whether `hwnd` is the foreground window, after a few tries at bringing
529    /// it there (restoring it if minimised). When it can't be, the error names
530    /// the window that has the focus.
531    pub(crate) fn bring_to_front(id: u32) -> Result<(), String> {
532        ensure_dpi_aware();
533        let hwnd = id as usize as HWND;
534        restore_if_minimized(id);
535        for attempt in 0..3u32 {
536            if unsafe { try_foreground(hwnd) } {
537                // Give the app a moment to take the focus before input goes to it.
538                std::thread::sleep(Duration::from_millis(100));
539                if unsafe { GetForegroundWindow() } == hwnd {
540                    return Ok(());
541                }
542            }
543            std::thread::sleep(Duration::from_millis(150 * (attempt as u64 + 1)));
544        }
545        if unsafe { GetForegroundWindow() } == hwnd {
546            return Ok(());
547        }
548        let fg = unsafe { GetForegroundWindow() };
549        let holder = if fg.is_null() {
550            "no window".to_string()
551        } else {
552            // The app only, never its title: the title of an app the user hasn't
553            // allowed could be sensitive (`apps` hides a blocked window's too).
554            window_exe_name(fg).unwrap_or_else(|| "another app".into())
555        };
556        Err(format!(
557            "could not bring the window to the front: {holder} has the focus and Windows would not hand it over. Call again in a few seconds; if it keeps failing, ask the person to click this app's window once"
558        ))
559    }
560
561    /// The window at screen point (`sx`, `sy`) must be `id` itself, a child
562    /// of it, or a window it owns: an open menu, dropdown or dialog of the app
563    /// is a top-level window of its own, owned by the app's window
564    /// (`GA_ROOTOWNER`). If anything else covers the point, the click would
565    /// land there, so it is refused.
566    pub(crate) fn point_belongs_to(id: u32, sx: i32, sy: i32) -> Result<(), String> {
567        let target = id as usize as HWND;
568        unsafe {
569            let at = WindowFromPoint(POINT { x: sx, y: sy });
570            if at.is_null() {
571                return Err("nothing is at that point".into());
572            }
573            let root = GetAncestor(at, GA_ROOT);
574            let owner = GetAncestor(at, GA_ROOTOWNER);
575            if root == target || owner == target || at == target {
576                Ok(())
577            } else {
578                Err("another window covers that point; the click would land there".into())
579            }
580        }
581    }
582
583    /// The executable of the app a Windows Store (UWP) frame hosts. Its
584    /// top-level window belongs to `ApplicationFrameHost.exe`, which hosts
585    /// every such app, so the app itself is the process of a child window
586    /// that isn't the frame host's. `None` when there is none, as while the
587    /// app is minimised and suspended.
588    pub(crate) fn hosted_app_exe(id: u32) -> Option<String> {
589        struct Search {
590            frame_pid: u32,
591            found: u32,
592        }
593        unsafe extern "system" fn each(child: HWND, lparam: LPARAM) -> BOOL {
594            let search = unsafe { &mut *(lparam as *mut Search) };
595            let mut pid = 0u32;
596            unsafe { GetWindowThreadProcessId(child, &mut pid) };
597            if pid != 0 && pid != search.frame_pid {
598                search.found = pid;
599                return 0;
600            }
601            1
602        }
603        let frame = id as usize as HWND;
604        let mut search = Search { frame_pid: 0, found: 0 };
605        unsafe {
606            GetWindowThreadProcessId(frame, &mut search.frame_pid);
607            EnumChildWindows(frame, Some(each), &mut search as *mut Search as LPARAM);
608        }
609        if search.found == 0 {
610            return None;
611        }
612        unsafe {
613            let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, search.found);
614            if process.is_null() {
615                return None;
616            }
617            let mut buf = [0u16; 1024];
618            let mut len = buf.len() as u32;
619            let ok = QueryFullProcessImageNameW(process, PROCESS_NAME_WIN32, buf.as_mut_ptr(), &mut len);
620            CloseHandle(process);
621            (ok != 0 && len > 0).then(|| String::from_utf16_lossy(&buf[..len as usize]))
622        }
623    }
624
625    fn send(inputs: &[INPUT]) -> Result<(), String> {
626        let sent = unsafe { SendInput(inputs.len() as u32, inputs.as_ptr(), size_of::<INPUT>() as i32) };
627        if sent as usize == inputs.len() {
628            Ok(())
629        } else {
630            Err(format!("Windows accepted {sent} of {} input events (an elevated window refuses input from here)", inputs.len()))
631        }
632    }
633
634    fn mouse(dx: i32, dy: i32, data: i32, flags: MOUSE_EVENT_FLAGS) -> INPUT {
635        INPUT {
636            r#type: INPUT_MOUSE,
637            Anonymous: INPUT_0 { mi: MOUSEINPUT { dx, dy, mouseData: data as u32, dwFlags: flags, time: 0, dwExtraInfo: 0 } },
638        }
639    }
640
641    fn key(vk: u16, unicode: u16, flags: KEYBD_EVENT_FLAGS) -> INPUT {
642        INPUT {
643            r#type: INPUT_KEYBOARD,
644            Anonymous: INPUT_0 { ki: KEYBDINPUT { wVk: vk, wScan: unicode, dwFlags: flags, time: 0, dwExtraInfo: 0 } },
645        }
646    }
647
648    fn virtual_screen() -> (i32, i32, u32, u32) {
649        unsafe {
650            (
651                GetSystemMetrics(SM_XVIRTUALSCREEN),
652                GetSystemMetrics(SM_YVIRTUALSCREEN),
653                GetSystemMetrics(SM_CXVIRTUALSCREEN).max(1) as u32,
654                GetSystemMetrics(SM_CYVIRTUALSCREEN).max(1) as u32,
655            )
656        }
657    }
658
659    fn move_to(sx: i32, sy: i32) -> INPUT {
660        let (vx, vy, vw, vh) = virtual_screen();
661        let (ax, ay) = to_absolute(sx, sy, vx, vy, vw, vh);
662        mouse(ax, ay, 0, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK)
663    }
664
665    fn button_flags(button: &str) -> Result<(MOUSE_EVENT_FLAGS, MOUSE_EVENT_FLAGS), String> {
666        match button {
667            "left" => Ok((MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP)),
668            "right" => Ok((MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP)),
669            "middle" => Ok((MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP)),
670            other => Err(format!("unknown button {other:?}; use left, right or middle")),
671        }
672    }
673
674    /// Hold `modifiers`, press `button` at the first point, move through the
675    /// rest in short steps and let go at the last (see `run_drag`). It takes
676    /// about a second at most, and lets go on every exit path.
677    pub(crate) fn drag(points: &[(i32, i32)], button: &str, modifiers: &[u16]) -> Result<(), String> {
678        let (down, up) = button_flags(button)?;
679        super::run_drag(points, modifiers, &mut |step| match step {
680            DragStep::Move(x, y) => send(&[move_to(x, y)]),
681            DragStep::KeyDown(vk) => send(&[key(vk, 0, 0)]),
682            DragStep::KeyUp(vk) => send(&[key(vk, 0, KEYEVENTF_KEYUP)]),
683            DragStep::ButtonDown => send(&[mouse(0, 0, 0, down)]),
684            DragStep::ButtonUp => send(&[mouse(0, 0, 0, up)]),
685            DragStep::Pause(ms) => {
686                std::thread::sleep(Duration::from_millis(ms));
687                Ok(())
688            }
689        })
690    }
691
692    /// Click `count` times at a screen point with `button` ("left", "right",
693    /// "middle").
694    pub(crate) fn click(sx: i32, sy: i32, button: &str, count: u32) -> Result<(), String> {
695        let (down, up) = button_flags(button)?;
696        let mut events = vec![move_to(sx, sy)];
697        for _ in 0..count.clamp(1, 3) {
698            events.push(mouse(0, 0, 0, down));
699            events.push(mouse(0, 0, 0, up));
700        }
701        send(&events)
702    }
703
704    /// Scroll at a screen point: `dy` notches (positive is up), `dx` notches
705    /// (positive is right).
706    pub(crate) fn scroll(sx: i32, sy: i32, dx: i32, dy: i32) -> Result<(), String> {
707        let mut events = vec![move_to(sx, sy)];
708        if dy != 0 {
709            events.push(mouse(0, 0, dy.clamp(-50, 50) * 120, MOUSEEVENTF_WHEEL));
710        }
711        if dx != 0 {
712            events.push(mouse(0, 0, dx.clamp(-50, 50) * 120, MOUSEEVENTF_HWHEEL));
713        }
714        send(&events)
715    }
716
717    /// Press a chord: modifiers down, the key, modifiers up.
718    pub(crate) fn press(chord: &Chord) -> Result<(), String> {
719        let mut events = Vec::new();
720        for m in &chord.modifiers {
721            events.push(key(*m, 0, 0));
722        }
723        events.push(key(chord.key, 0, 0));
724        events.push(key(chord.key, 0, KEYEVENTF_KEYUP));
725        for m in chord.modifiers.iter().rev() {
726            events.push(key(*m, 0, KEYEVENTF_KEYUP));
727        }
728        let result = send(&events);
729        if result.is_err() {
730            // Do not leave a modifier held down.
731            let ups: Vec<INPUT> = chord.modifiers.iter().map(|m| key(*m, 0, KEYEVENTF_KEYUP)).collect();
732            let _ = send(&ups);
733        }
734        result
735    }
736
737    /// Type `text` into whatever has the focus. Newline is Enter and tab is
738    /// Tab; everything else is sent as the character itself.
739    pub(crate) fn type_text(text: &str) -> Result<(), String> {
740        let mut events = Vec::new();
741        for c in text.chars() {
742            match c {
743                '\n' => {
744                    events.push(key(VK_RETURN, 0, 0));
745                    events.push(key(VK_RETURN, 0, KEYEVENTF_KEYUP));
746                }
747                '\t' => {
748                    events.push(key(VK_TAB, 0, 0));
749                    events.push(key(VK_TAB, 0, KEYEVENTF_KEYUP));
750                }
751                _ => {
752                    let mut buf = [0u16; 2];
753                    for unit in c.encode_utf16(&mut buf) {
754                        events.push(key(0, *unit, KEYEVENTF_UNICODE));
755                        events.push(key(0, *unit, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP));
756                    }
757                }
758            }
759        }
760        send(&events)
761    }
762}
763
764/// Other platforms: the tool answers that driving is Windows-only for now
765/// (spec §8, phases 3 and 4).
766#[cfg(not(windows))]
767pub(crate) mod win {
768    use super::{Chord, Rect};
769
770    const NOT_YET: &str = "Desktop driving works on Windows in this version; macOS and Linux (X11) come later";
771
772    pub(crate) fn ensure_dpi_aware() {}
773    pub(crate) fn window_rect(_id: u32) -> Option<Rect> {
774        None
775    }
776    pub(crate) fn bring_to_front(_id: u32) -> Result<(), String> {
777        Err(NOT_YET.into())
778    }
779    pub(crate) fn restore_if_minimized(_id: u32) -> bool {
780        false
781    }
782    pub(crate) fn point_belongs_to(_id: u32, _sx: i32, _sy: i32) -> Result<(), String> {
783        Err(NOT_YET.into())
784    }
785    pub(crate) fn hosted_app_exe(_id: u32) -> Option<String> {
786        None
787    }
788    pub(crate) fn click(_sx: i32, _sy: i32, _button: &str, _count: u32) -> Result<(), String> {
789        Err(NOT_YET.into())
790    }
791    pub(crate) fn scroll(_sx: i32, _sy: i32, _dx: i32, _dy: i32) -> Result<(), String> {
792        Err(NOT_YET.into())
793    }
794    pub(crate) fn drag(_points: &[(i32, i32)], _button: &str, _modifiers: &[u16]) -> Result<(), String> {
795        Err(NOT_YET.into())
796    }
797    pub(crate) fn press(_chord: &Chord) -> Result<(), String> {
798        Err(NOT_YET.into())
799    }
800    pub(crate) fn type_text(_text: &str) -> Result<(), String> {
801        Err(NOT_YET.into())
802    }
803}
804
805#[cfg(test)]
806mod tests {
807    use super::*;
808
809    fn look() -> Look {
810        Look { rect: Rect { x: 100, y: 50, w: 2000, h: 1000 }, image_w: 1000, image_h: 500, n: 0 }
811    }
812
813    #[test]
814    fn a_big_window_is_shown_at_most_1568_on_its_long_edge() {
815        assert_eq!(scaled_size(3136, 1568), (1568, 784));
816        assert_eq!(scaled_size(800, 600), (800, 600));
817        assert_eq!(scaled_size(1568, 100), (1568, 100));
818    }
819
820    #[test]
821    fn an_image_point_maps_to_the_middle_of_its_pixels_on_the_screen() {
822        // The image is half the window's size: pixel 0 covers screen x 100..102.
823        assert_eq!(to_screen(&look(), look().rect, 0, 0), Ok((101, 51)));
824        assert_eq!(to_screen(&look(), look().rect, 500, 250), Ok((1101, 551)));
825        assert_eq!(to_screen(&look(), look().rect, 999, 499), Ok((2099, 1049)));
826    }
827
828    #[test]
829    fn a_moved_or_resized_window_is_refused() {
830        let l = look();
831        let moved = Rect { x: 101, ..l.rect };
832        assert!(to_screen(&l, moved, 10, 10).unwrap_err().contains("look again"));
833        let resized = Rect { w: 1999, ..l.rect };
834        assert!(to_screen(&l, resized, 10, 10).unwrap_err().contains("look again"));
835    }
836
837    #[test]
838    fn a_point_outside_the_image_is_refused() {
839        let l = look();
840        for (x, y) in [(-1, 0), (0, -1), (1000, 0), (0, 500), (5000, 5000)] {
841            assert!(to_screen(&l, l.rect, x, y).unwrap_err().contains("outside"), "({x},{y})");
842        }
843    }
844
845    #[test]
846    fn absolute_coordinates_span_the_virtual_screen() {
847        assert_eq!(to_absolute(0, 0, 0, 0, 1920, 1080), (0, 0));
848        assert_eq!(to_absolute(1919, 1079, 0, 0, 1920, 1080), (65535, 65535));
849        // A second monitor to the left makes the origin negative.
850        assert_eq!(to_absolute(-1920, 0, -1920, 0, 3840, 1080), (0, 0));
851        assert_eq!(to_absolute(1919, 0, -1920, 0, 3840, 1080), (65535, 0));
852        // Outside the screen clamps.
853        assert_eq!(to_absolute(-50, 5000, 0, 0, 1920, 1080), (0, 65535));
854    }
855
856    #[test]
857    fn chords_are_read_with_modifiers_first() {
858        assert_eq!(parse_keys("ctrl+s"), Ok(Chord { modifiers: vec![VK_CONTROL], key: 0x53 }));
859        assert_eq!(
860            parse_keys("Ctrl + Shift + F5"),
861            Ok(Chord { modifiers: vec![VK_CONTROL, VK_SHIFT], key: 0x74 })
862        );
863        assert_eq!(parse_keys("enter"), Ok(Chord { modifiers: vec![], key: 0x0D }));
864        assert_eq!(parse_keys("alt+left"), Ok(Chord { modifiers: vec![VK_MENU], key: 0x25 }));
865        assert_eq!(parse_keys("7"), Ok(Chord { modifiers: vec![], key: 0x37 }));
866    }
867
868    #[test]
869    fn the_windows_key_and_unknown_keys_are_refused() {
870        for spec in ["win+r", "cmd+c", "meta+x", "super+e"] {
871            assert!(parse_keys(spec).unwrap_err().contains("not allowed"), "{spec}");
872        }
873        assert!(parse_keys("").is_err());
874        assert!(parse_keys("ctrl+").is_err());
875        assert!(parse_keys("f13").is_err());
876        assert!(parse_keys("hyper+a").unwrap_err().contains("unknown modifier"));
877        assert!(parse_keys("ctrl+banana").unwrap_err().contains("unknown key"));
878    }
879
880    #[test]
881    fn typed_text_is_limited() {
882        assert!(check_text("hello\nworld\t!").is_ok());
883        assert!(check_text("").is_err());
884        assert!(check_text(&"a".repeat(501)).unwrap_err().contains("501"));
885        assert!(check_text(&"a".repeat(500)).is_ok());
886        assert!(check_text("a\u{1b}b").unwrap_err().contains("control"));
887    }
888
889    #[test]
890    fn a_drag_starts_and_ends_exactly_where_it_was_told() {
891        let path = drag_path((100, 100), &[], (400, 100));
892        assert_eq!(path.first(), Some(&(100, 100)));
893        assert_eq!(path.last(), Some(&(400, 100)));
894        // 300 px in steps of about 12 px, never a jump.
895        assert!(path.len() > 20, "{}", path.len());
896        assert!(path.windows(2).all(|w| (w[1].0 - w[0].0).abs() <= 13), "{path:?}");
897        // Moves only go forward along a straight leg.
898        assert!(path.windows(2).all(|w| w[1].0 >= w[0].0));
899    }
900
901    #[test]
902    fn a_short_drag_still_moves_in_several_steps() {
903        let path = drag_path((10, 10), &[], (14, 10));
904        assert!(path.len() >= 5, "{path:?}");
905        assert_eq!(path.last(), Some(&(14, 10)));
906    }
907
908    #[test]
909    fn a_drag_passes_through_each_waypoint_in_order() {
910        let path = drag_path((0, 0), &[(100, 0), (100, 100)], (0, 100));
911        let at = |p: (i32, i32)| path.iter().position(|q| *q == p).unwrap_or_else(|| panic!("{p:?} not on {path:?}"));
912        assert!(at((100, 0)) < at((100, 100)));
913        assert!(at((100, 100)) < at((0, 100)));
914        assert_eq!(path.last(), Some(&(0, 100)));
915    }
916
917    #[test]
918    fn a_long_drag_is_capped_but_keeps_every_stop() {
919        let via = [(5000, 0), (5000, 5000), (0, 5000), (0, 0), (5000, 5000), (1, 1), (4000, 40), (2, 2)];
920        let path = drag_path((0, 0), &via, (9000, 9000));
921        assert!(path.len() <= MAX_DRAG_MOVES + 1, "{}", path.len());
922        for stop in via {
923            assert!(path.contains(&stop), "{stop:?} missing");
924        }
925        assert_eq!(path.last(), Some(&(9000, 9000)));
926    }
927
928    #[test]
929    fn a_drag_may_hold_ctrl_alt_and_shift_only() {
930        assert_eq!(parse_hold("ctrl"), Ok(vec![VK_CONTROL]));
931        assert_eq!(parse_hold("Ctrl + Shift"), Ok(vec![VK_CONTROL, VK_SHIFT]));
932        assert_eq!(parse_hold("alt+alt"), Ok(vec![VK_MENU]));
933        assert_eq!(parse_hold(""), Ok(vec![]));
934        assert!(parse_hold("win").unwrap_err().contains("not allowed"));
935        assert!(parse_hold("ctrl+cmd").unwrap_err().contains("not allowed"));
936        assert!(parse_hold("ctrl+a").unwrap_err().contains("unknown key to hold"));
937    }
938
939    /// Run a drag against a recorder that fails at its `fail_at`th step (counting from 0).
940    fn record_drag(points: &[(i32, i32)], mods: &[u16], fail_at: Option<usize>) -> (Result<(), String>, Vec<DragStep>) {
941        let mut steps = Vec::new();
942        let mut n = 0usize;
943        let r = run_drag(points, mods, &mut |s| {
944            let this = n;
945            n += 1;
946            // Only the steps of the drag itself can fail; the cleanup is tried regardless.
947            if fail_at == Some(this) {
948                return Err("input refused".into());
949            }
950            steps.push(s);
951            Ok(())
952        });
953        (r, steps)
954    }
955
956    #[test]
957    fn a_drag_presses_moves_and_lets_go_once() {
958        let (r, steps) = record_drag(&[(1, 1), (5, 5), (9, 9)], &[VK_SHIFT], None);
959        assert_eq!(r, Ok(()));
960        assert_eq!(steps.first(), Some(&DragStep::Move(1, 1)));
961        assert_eq!(steps.iter().filter(|s| **s == DragStep::ButtonDown).count(), 1);
962        assert_eq!(steps.iter().filter(|s| **s == DragStep::ButtonUp).count(), 1);
963        // The release is at the last point and the drop pause comes first.
964        let up = steps.iter().position(|s| *s == DragStep::ButtonUp).unwrap();
965        assert_eq!(steps[up - 3], DragStep::Move(9, 9));
966        assert!(matches!(steps[up - 1], DragStep::Pause(ms) if ms >= 100));
967        // The modifier goes down before the press and up after the release.
968        let down = steps.iter().position(|s| *s == DragStep::ButtonDown).unwrap();
969        assert!(steps.iter().position(|s| *s == DragStep::KeyDown(VK_SHIFT)).unwrap() < down);
970        assert!(steps.iter().position(|s| *s == DragStep::KeyUp(VK_SHIFT)).unwrap() > up);
971    }
972
973    #[test]
974    fn a_drag_that_fails_after_the_press_still_lets_go_of_everything() {
975        let points = [(1, 1), (5, 5), (9, 9)];
976        let mods = [VK_CONTROL, VK_SHIFT];
977        // Fail at each step in turn: after the press, whatever was pressed is released.
978        let (_, clean) = record_drag(&points, &mods, None);
979        // The last steps are the modifiers coming up; only the drag proper can fail with an error.
980        for fail_at in 0..clean.len() - mods.len() {
981            let (r, steps) = record_drag(&points, &mods, Some(fail_at));
982            assert_eq!(r, Err("input refused".into()), "fail_at {fail_at}");
983            let downs = steps.iter().filter(|s| **s == DragStep::ButtonDown).count();
984            let ups = steps.iter().filter(|s| **s == DragStep::ButtonUp).count();
985            assert_eq!(downs, ups, "a button was left held when step {fail_at} failed: {steps:?}");
986            for m in mods {
987                let d = steps.iter().filter(|s| **s == DragStep::KeyDown(m)).count();
988                let u = steps.iter().filter(|s| **s == DragStep::KeyUp(m)).count();
989                assert_eq!(d, u, "{m:#x} was left held when step {fail_at} failed: {steps:?}");
990            }
991        }
992    }
993
994    #[test]
995    fn modifiers_are_let_go_in_reverse_after_the_button() {
996        let (r, steps) = record_drag(&[(0, 0), (3, 3)], &[VK_CONTROL, VK_SHIFT], Some(7));
997        assert!(r.is_err());
998        let tail: Vec<DragStep> = steps.iter().rev().take(3).rev().copied().collect();
999        assert_eq!(tail, vec![DragStep::ButtonUp, DragStep::KeyUp(VK_SHIFT), DragStep::KeyUp(VK_CONTROL)], "{steps:?}");
1000    }
1001
1002    #[test]
1003    fn a_drag_with_no_points_does_nothing() {
1004        let (r, steps) = record_drag(&[], &[VK_CONTROL], None);
1005        assert!(r.is_err());
1006        assert!(steps.is_empty());
1007    }
1008
1009    #[test]
1010    fn looks_are_remembered_per_window() {
1011        let (first, before) = remember_look(7001, look());
1012        assert_eq!((first.n, before), (1, None));
1013        assert_eq!(last_look(7001), Some(first));
1014        assert_eq!(last_look(7002), None);
1015        // The next look of the same window is the second, and knows the first.
1016        let (second, before) = remember_look(7001, Look { image_h: 600, ..look() });
1017        assert_eq!(second.n, 2);
1018        assert_eq!(before, Some(first));
1019        assert_eq!(last_look(7001), Some(second));
1020    }
1021
1022    #[test]
1023    fn coordinates_from_an_older_look_are_refused_and_say_which_is_latest() {
1024        let latest = Look { n: 3, ..look() };
1025        assert_eq!(check_of_look(&latest, 3), Ok(()));
1026        let e = check_of_look(&latest, 2).unwrap_err();
1027        assert!(e.contains("look #2") && e.contains("latest look at this window is #3") && e.contains("1000×500"), "{e}");
1028    }
1029
1030    #[test]
1031    fn a_look_says_its_scale_and_when_the_size_changed() {
1032        let a = Look { n: 1, ..look() };
1033        let said = describe_scale(&a, None);
1034        assert!(said.contains("look #1") && said.contains("1000×500") && said.contains("2000×1000") && said.contains("scale 2.00"), "{said}");
1035        assert!(!said.contains("stale"));
1036        let b = Look { n: 2, image_h: 540, ..look() };
1037        let said = describe_scale(&b, Some(&a));
1038        assert!(said.contains("changed since look #1 (1000×500)") && said.contains("stale"), "{said}");
1039        assert!(!describe_scale(&b, Some(&Look { n: 1, ..b })).contains("stale"));
1040    }
1041
1042    #[test]
1043    fn a_region_must_be_inside_the_look_and_big_enough() {
1044        let l = Look { n: 4, ..look() };
1045        assert_eq!(check_region(&l, 10, 20, 100, 50), Ok(Region { x: 10, y: 20, w: 100, h: 50 }));
1046        assert_eq!(check_region(&l, 900, 450, 100, 50), Ok(Region { x: 900, y: 450, w: 100, h: 50 }));
1047        assert!(check_region(&l, 901, 450, 100, 50).unwrap_err().contains("not inside look #4"));
1048        assert!(check_region(&l, -1, 0, 100, 50).is_err());
1049        assert!(check_region(&l, 0, 0, 7, 50).unwrap_err().contains("at least 8"));
1050        // Huge numbers from the caller are outside the image, never an overflow.
1051        assert!(check_region(&l, i64::MAX, 0, 8, 8).unwrap_err().contains("not inside"));
1052        assert!(check_region(&l, 0, i64::MAX, 8, 8).unwrap_err().contains("not inside"));
1053        assert!(check_region(&l, 0, 0, i64::MAX, 8).unwrap_err().contains("not inside"));
1054        assert!(check_region(&l, i64::MAX, i64::MAX, i64::MAX, i64::MAX).is_err());
1055    }
1056
1057    #[test]
1058    fn a_small_region_is_enlarged_up_to_four_times_and_a_large_one_not_at_all() {
1059        assert_eq!(zoom_for(100, 50), MAX_ZOOM);
1060        assert_eq!(zoom_for(1568, 800), 1.0);
1061        assert_eq!(zoom_for(2000, 1000), 1.0);
1062        assert!((zoom_for(784, 100) - 2.0).abs() < 1e-9);
1063    }
1064}
1065
1066/// A real drag, with the real mouse: a throwaway window with a slider and a
1067/// canvas, driven by `win::drag`. It takes the pointer and the screen for a few
1068/// seconds, so it is ignored by default; run it by hand on a machine nobody is
1069/// working at:
1070/// `cargo test -p agentmux-mcp real_drag -- --ignored --nocapture`.
1071#[cfg(all(test, windows))]
1072mod real_input {
1073    use super::*;
1074    use serde_json::Value;
1075    use std::path::Path;
1076    use std::process::{Child, Command};
1077    use std::time::{Duration, Instant};
1078
1079    use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_CONTROL, VK_LBUTTON};
1080
1081    /// A form with a slider (0 to 100) and a white canvas. It writes where they are
1082    /// (`ready.json`, in physical screen pixels) and what happened to them
1083    /// (`result.json`, after each press, release and slider change).
1084    const FORM: &str = r##"
1085param($dir)
1086Add-Type -TypeDefinition 'using System.Runtime.InteropServices; public class Dpi { [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); }'
1087[Dpi]::SetProcessDPIAware() | Out-Null
1088Add-Type -AssemblyName System.Windows.Forms
1089$f = New-Object Windows.Forms.Form
1090$f.StartPosition = 'Manual'; $f.Location = New-Object Drawing.Point(80, 80); $f.Size = New-Object Drawing.Size(640, 360); $f.TopMost = $true
1091$tb = New-Object Windows.Forms.TrackBar
1092$tb.Minimum = 0; $tb.Maximum = 100; $tb.Value = 0; $tb.Location = New-Object Drawing.Point(20, 20); $tb.Size = New-Object Drawing.Size(560, 45)
1093$p = New-Object Windows.Forms.Panel
1094$p.Location = New-Object Drawing.Point(20, 100); $p.Size = New-Object Drawing.Size(560, 180); $p.BackColor = [Drawing.Color]::White
1095$f.Controls.Add($tb); $f.Controls.Add($p)
1096$s = @{ slider = 0; downs = 0; ups = 0; moves = 0; ctrl_at_down = $false; first = @(0, 0); last = @(0, 0) }
1097function Save { ($s | ConvertTo-Json -Compress) | Set-Content -Path (Join-Path $dir 'result.json') -Encoding ASCII }
1098$tb.add_ValueChanged({ $s.slider = $tb.Value; Save })
1099$p.add_MouseDown({ param($o, $e) $s.downs++; $s.ctrl_at_down = ([Windows.Forms.Control]::ModifierKeys -band [Windows.Forms.Keys]::Control) -ne 0; $s.first = @($e.X, $e.Y); Save })
1100$p.add_MouseMove({ param($o, $e) if ($s.downs -gt $s.ups) { $s.moves++; $s.last = @($e.X, $e.Y) } })
1101$p.add_MouseUp({ param($o, $e) $s.ups++; $s.last = @($e.X, $e.Y); Save })
1102$f.add_Shown({
1103  $f.Activate()
1104  $a = $tb.PointToScreen((New-Object Drawing.Point(0, 0))); $b = $p.PointToScreen((New-Object Drawing.Point(0, 0)))
1105  $r = @{ slider = @($a.X, $a.Y, $tb.Width, $tb.Height); canvas = @($b.X, $b.Y, $p.Width, $p.Height) }
1106  ($r | ConvertTo-Json -Compress) | Set-Content -Path (Join-Path $dir 'ready.json') -Encoding ASCII
1107})
1108[Windows.Forms.Application]::Run($f)
1109"##;
1110
1111    struct Form(Child);
1112    impl Drop for Form {
1113        fn drop(&mut self) {
1114            let _ = self.0.kill();
1115            let _ = self.0.wait();
1116        }
1117    }
1118
1119    fn wait_for_json(path: &Path, secs: u64) -> Value {
1120        let end = Instant::now() + Duration::from_secs(secs);
1121        while Instant::now() < end {
1122            if let Ok(text) = std::fs::read_to_string(path) {
1123                if let Ok(v) = serde_json::from_str::<Value>(text.trim_start_matches('\u{feff}')) {
1124                    return v;
1125                }
1126            }
1127            std::thread::sleep(Duration::from_millis(100));
1128        }
1129        panic!("{} did not appear", path.display());
1130    }
1131
1132    /// What the form recorded, once it has had time to see the last event.
1133    fn settled_result(dir: &Path) -> Value {
1134        wait_for_json(&dir.join("result.json"), 5);
1135        std::thread::sleep(Duration::from_millis(700));
1136        wait_for_json(&dir.join("result.json"), 5)
1137    }
1138
1139    fn rect(v: &Value, key: &str) -> (i32, i32, i32, i32) {
1140        let a = v[key].as_array().unwrap_or_else(|| panic!("{key} missing in {v}"));
1141        let n = |i: usize| a[i].as_i64().unwrap() as i32;
1142        (n(0), n(1), n(2), n(3))
1143    }
1144
1145    fn down(vk: u16) -> bool {
1146        unsafe { GetAsyncKeyState(vk as i32) as u16 & 0x8000 != 0 }
1147    }
1148
1149    #[test]
1150    #[ignore = "takes the real mouse and screen for a few seconds; run by hand"]
1151    fn real_drag_moves_a_slider_and_draws_on_a_canvas() {
1152        win::ensure_dpi_aware();
1153        let dir = std::env::temp_dir().join(format!("am-real-drag-{}", std::process::id()));
1154        std::fs::create_dir_all(&dir).unwrap();
1155        let script = dir.join("form.ps1");
1156        std::fs::write(&script, FORM).unwrap();
1157        let child = Command::new("powershell")
1158            .args(["-NoProfile", "-STA", "-ExecutionPolicy", "Bypass", "-File"])
1159            .arg(&script)
1160            .arg(&dir)
1161            .spawn()
1162            .expect("start powershell");
1163        let _form = Form(child);
1164        let ready = wait_for_json(&dir.join("ready.json"), 30);
1165        std::thread::sleep(Duration::from_millis(800));
1166
1167        // The slider: press on its thumb (at the left end) and drag to the right end.
1168        let (sx, sy, sw, sh) = rect(&ready, "slider");
1169        let from = (sx + 14, sy + sh / 3);
1170        let to = (sx + sw - 14, sy + sh / 3);
1171        win::drag(&drag_path(from, &[], to), "left", &[]).expect("drag the slider");
1172        let r = settled_result(&dir);
1173        assert!(r["slider"].as_i64().unwrap() >= 90, "the slider only reached {}: {r}", r["slider"]);
1174        assert!(!down(VK_LBUTTON as u16), "the left button is still held");
1175
1176        // The canvas: a drag through a waypoint, holding ctrl.
1177        let _ = std::fs::remove_file(dir.join("result.json"));
1178        let (cx, cy, cw, ch) = rect(&ready, "canvas");
1179        let start = (cx + 30, cy + 30);
1180        let mid = (cx + cw / 2, cy + ch - 30);
1181        let end = (cx + cw - 30, cy + 30);
1182        win::drag(&drag_path(start, &[mid], end), "left", &[0x11]).expect("drag on the canvas");
1183        let r = settled_result(&dir);
1184        assert_eq!(r["downs"].as_i64(), Some(1), "{r}");
1185        assert_eq!(r["ups"].as_i64(), Some(1), "{r}");
1186        assert!(r["moves"].as_i64().unwrap() >= 20, "{r}");
1187        assert_eq!(r["ctrl_at_down"].as_bool(), Some(true), "ctrl was not held at the press: {r}");
1188        let last = (r["last"][0].as_i64().unwrap(), r["last"][1].as_i64().unwrap());
1189        assert!((last.0 - (cw as i64 - 30)).abs() <= 3 && (last.1 - 30).abs() <= 3, "released at {last:?}: {r}");
1190        assert!(!down(VK_LBUTTON as u16), "the left button is still held");
1191        assert!(!down(VK_CONTROL as u16), "ctrl is still held");
1192        let _ = std::fs::remove_dir_all(&dir);
1193    }
1194}