forgewright 0.2.0

Standalone UI automation — CDP for browsers, UIA for Windows desktop apps
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
// dual_capture.rs — Dual window capture for visual debug
//
// Captures two windows simultaneously (e.g., game + debug console)
// and saves them as separate BMP files. Uses GetWindowRect for window
// geometry, GDI BitBlt for pixel capture.
//
// Windows-only module — requires Win32 window enumeration and GDI capture.

#![cfg(target_os = "windows")]

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use windows::Win32::Foundation::{BOOL, HWND, LPARAM, RECT, TRUE};
use windows::Win32::Graphics::Gdi::{
    BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject,
    GetDC, GetDIBits, ReleaseDC, SelectObject,
    BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, SRCCOPY,
};
use windows::Win32::UI::WindowsAndMessaging::{
    EnumWindows, GetWindowRect, GetWindowTextLengthW, GetWindowTextW,
    IsWindowVisible,
};

// ═══ TYPES ═══════════════════════════════════════════════════════════════════

/// Configuration for a dual capture operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DualCaptureConfig {
    /// Title substring for the primary window (e.g., game window).
    pub primary_title: String,
    /// Title substring for the secondary window (e.g., debug console).
    pub secondary_title: String,
    /// Output directory for captured images.
    pub output_dir: PathBuf,
    /// Optional resize dimensions (width, height). None = original size.
    pub resize: Option<(u32, u32)>,
}

/// Result of capturing a single window.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindowCapture {
    /// Path where the BMP was saved.
    pub path: PathBuf,
    /// Window title that was matched.
    pub title: String,
    /// Captured width in pixels.
    pub width: u32,
    /// Captured height in pixels.
    pub height: u32,
}

/// Result of a dual capture operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DualCaptureResult {
    /// Primary window capture (None if window not found).
    pub primary: Option<WindowCapture>,
    /// Secondary window capture (None if window not found).
    pub secondary: Option<WindowCapture>,
    /// Error message if primary window not found.
    pub primary_error: Option<String>,
    /// Error message if secondary window not found.
    pub secondary_error: Option<String>,
}

/// A discovered window with its handle and title.
struct FoundWindow {
    hwnd: HWND,
    title: String,
}

// ═══ WINDOW FINDING ══════════════════════════════════════════════════════════

/// Find all visible windows whose title contains the given substring
/// (case-insensitive).
fn find_windows_by_title(substring: &str) -> Vec<FoundWindow> {
    struct EnumState {
        pattern: String,
        results: Vec<FoundWindow>,
    }

    let mut state = EnumState {
        pattern: substring.to_lowercase(),
        results: Vec::new(),
    };

    unsafe extern "system" fn callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
        let state = &mut *(lparam.0 as *mut EnumState);
        if !IsWindowVisible(hwnd).as_bool() {
            return TRUE;
        }
        let len = GetWindowTextLengthW(hwnd);
        if len <= 0 {
            return TRUE;
        }
        let mut buf = vec![0u16; (len + 1) as usize];
        let actual = GetWindowTextW(hwnd, &mut buf);
        if actual > 0 {
            let title = String::from_utf16_lossy(&buf[..actual as usize]);
            if title.to_lowercase().contains(&state.pattern) {
                state.results.push(FoundWindow { hwnd, title });
            }
        }
        TRUE
    }

    unsafe {
        let _ = EnumWindows(
            Some(callback),
            LPARAM(&mut state as *mut EnumState as isize),
        );
    }

    state.results
}

/// List all visible windows. Returns a Vec of window titles.
pub fn list_visible_windows() -> Vec<String> {
    struct EnumState {
        titles: Vec<String>,
    }

    let mut state = EnumState {
        titles: Vec::new(),
    };

    unsafe extern "system" fn callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
        let state = &mut *(lparam.0 as *mut EnumState);
        if !IsWindowVisible(hwnd).as_bool() {
            return TRUE;
        }
        let len = GetWindowTextLengthW(hwnd);
        if len <= 0 {
            return TRUE;
        }
        let mut buf = vec![0u16; (len + 1) as usize];
        let actual = GetWindowTextW(hwnd, &mut buf);
        if actual > 0 {
            let title = String::from_utf16_lossy(&buf[..actual as usize]);
            if !title.trim().is_empty() {
                state.titles.push(title);
            }
        }
        TRUE
    }

    unsafe {
        let _ = EnumWindows(
            Some(callback),
            LPARAM(&mut state as *mut EnumState as isize),
        );
    }

    state.titles
}

// ═══ WINDOW RECT ═════════════════════════════════════════════════════════════

/// Get the window rectangle via GetWindowRect.
/// Returns None if the window is too small (< 10x10).
fn get_window_bounds(hwnd: HWND) -> Option<RECT> {
    let mut rect = RECT::default();
    let ok = unsafe { GetWindowRect(hwnd, &mut rect) };
    if ok.is_ok() {
        let w = rect.right - rect.left;
        let h = rect.bottom - rect.top;
        if w >= 10 && h >= 10 {
            return Some(rect);
        }
    }
    None
}

// ═══ GDI CAPTURE ═════════════════════════════════════════════════════════════

/// Capture a window region via GDI BitBlt and save as 24-bit BMP.
fn capture_window_to_bmp(hwnd: HWND, rect: &RECT, path: &Path) -> Result<(u32, u32), String> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).ok();
    }

    let w = rect.right - rect.left;
    let h = rect.bottom - rect.top;
    if w <= 0 || h <= 0 {
        return Err(format!("window too small: {}x{}", w, h));
    }

    unsafe {
        let hdc_screen = GetDC(None);
        let hdc_mem = CreateCompatibleDC(hdc_screen);
        let bmp = CreateCompatibleBitmap(hdc_screen, w, h);
        let old = SelectObject(hdc_mem, bmp);

        let _ = BitBlt(hdc_mem, 0, 0, w, h, hdc_screen, rect.left, rect.top, SRCCOPY);

        let row_bytes = ((w * 3 + 3) / 4) * 4;
        let pixel_size = (row_bytes * h) as usize;
        let mut pixels = vec![0u8; pixel_size];
        let mut bmi = BITMAPINFO {
            bmiHeader: BITMAPINFOHEADER {
                biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
                biWidth: w,
                biHeight: h,
                biPlanes: 1,
                biBitCount: 24,
                biCompression: BI_RGB.0 as u32,
                biSizeImage: pixel_size as u32,
                ..Default::default()
            },
            ..Default::default()
        };
        GetDIBits(
            hdc_mem, bmp, 0, h as u32,
            Some(pixels.as_mut_ptr() as _),
            &mut bmi, DIB_RGB_COLORS,
        );

        SelectObject(hdc_mem, old);
        let _ = DeleteObject(bmp);
        let _ = DeleteDC(hdc_mem);
        ReleaseDC(None, hdc_screen);

        // Write BMP file
        let file_size = 54 + pixel_size as u32;
        let mut buf = Vec::with_capacity(file_size as usize);
        buf.extend_from_slice(b"BM");
        buf.extend_from_slice(&file_size.to_le_bytes());
        buf.extend_from_slice(&[0u8; 4]);
        buf.extend_from_slice(&54u32.to_le_bytes());
        buf.extend_from_slice(&40u32.to_le_bytes());
        buf.extend_from_slice(&w.to_le_bytes());
        buf.extend_from_slice(&h.to_le_bytes());
        buf.extend_from_slice(&1u16.to_le_bytes());
        buf.extend_from_slice(&24u16.to_le_bytes());
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&(pixel_size as u32).to_le_bytes());
        buf.extend_from_slice(&2835u32.to_le_bytes());
        buf.extend_from_slice(&2835u32.to_le_bytes());
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&0u32.to_le_bytes());
        buf.extend_from_slice(&pixels);

        std::fs::write(path, &buf).map_err(|e| e.to_string())?;
        Ok((w as u32, h as u32))
    }
}

// ═══ SINGLE WINDOW CAPTURE ═══════════════════════════════════════════════════

/// Capture a single window by title substring.
fn capture_by_title(
    title_substring: &str,
    output_path: &Path,
) -> Result<WindowCapture, String> {
    let windows = find_windows_by_title(title_substring);
    if windows.is_empty() {
        return Err(format!("no window matching '{}'", title_substring));
    }

    let found = &windows[0];
    let rect = get_window_bounds(found.hwnd)
        .ok_or_else(|| format!("window '{}' too small or invisible", found.title))?;

    let (w, h) = capture_window_to_bmp(found.hwnd, &rect, output_path)?;

    Ok(WindowCapture {
        path: output_path.to_path_buf(),
        title: found.title.clone(),
        width: w,
        height: h,
    })
}

// ═══ DUAL CAPTURE ════════════════════════════════════════════════════════════

/// Capture two windows simultaneously and save as separate BMP files.
///
/// Finds each window by title substring, captures via GDI BitBlt,
/// and saves as 24-bit BGR bottom-up BMP (compatible with `bridge::decode_bmp`).
///
/// Returns a `DualCaptureResult` with both captures (or error messages
/// for windows that couldn't be found/captured).
pub fn dual_capture(config: &DualCaptureConfig) -> DualCaptureResult {
    std::fs::create_dir_all(&config.output_dir).ok();

    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let primary_path = config.output_dir.join(format!("primary_{}.bmp", ts));
    let (primary, primary_error) = match capture_by_title(&config.primary_title, &primary_path) {
        Ok(cap) => (Some(cap), None),
        Err(e) => (None, Some(e)),
    };

    let secondary_path = config.output_dir.join(format!("secondary_{}.bmp", ts));
    let (secondary, secondary_error) =
        match capture_by_title(&config.secondary_title, &secondary_path) {
            Ok(cap) => (Some(cap), None),
            Err(e) => (None, Some(e)),
        };

    DualCaptureResult {
        primary,
        secondary,
        primary_error,
        secondary_error,
    }
}

/// Dual capture with JSON output (for CLI integration).
pub fn dual_capture_json(config: &DualCaptureConfig) -> Value {
    let result = dual_capture(config);

    let primary_json = match &result.primary {
        Some(cap) => json!({
            "path": cap.path.to_string_lossy(),
            "title": cap.title,
            "width": cap.width,
            "height": cap.height,
        }),
        None => json!({
            "error": result.primary_error.as_deref().unwrap_or("unknown error"),
        }),
    };

    let secondary_json = match &result.secondary {
        Some(cap) => json!({
            "path": cap.path.to_string_lossy(),
            "title": cap.title,
            "width": cap.width,
            "height": cap.height,
        }),
        None => json!({
            "error": result.secondary_error.as_deref().unwrap_or("unknown error"),
        }),
    };

    json!({
        "primary": primary_json,
        "secondary": secondary_json,
    })
}

// ═══ TESTS ═══════════════════════════════════════════════════════════════════

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

    #[test]
    fn list_windows_returns_vec() {
        let titles = list_visible_windows();
        // On any Windows desktop there should be windows; headless CI may have none
        let _ = titles.len();
    }

    #[test]
    fn find_windows_nonexistent_returns_empty() {
        let results = find_windows_by_title("__nonexistent_window_title_12345__");
        assert!(results.is_empty());
    }

    #[test]
    fn dual_capture_config_serde_roundtrip() {
        let config = DualCaptureConfig {
            primary_title: "App A".to_string(),
            secondary_title: "App B".to_string(),
            output_dir: PathBuf::from("screenshots"),
            resize: Some((640, 360)),
        };
        let json_str = serde_json::to_string(&config).unwrap();
        let decoded: DualCaptureConfig = serde_json::from_str(&json_str).unwrap();
        assert_eq!(decoded.primary_title, "App A");
        assert_eq!(decoded.secondary_title, "App B");
        assert_eq!(decoded.resize, Some((640, 360)));
    }

    #[test]
    fn dual_capture_missing_windows_returns_errors() {
        let config = DualCaptureConfig {
            primary_title: "__no_such_window_primary__".to_string(),
            secondary_title: "__no_such_window_secondary__".to_string(),
            output_dir: PathBuf::from("test_output_dual"),
            resize: None,
        };
        let result = dual_capture(&config);
        assert!(result.primary.is_none());
        assert!(result.secondary.is_none());
        assert!(result.primary_error.is_some());
        assert!(result.secondary_error.is_some());
    }

    #[test]
    fn dual_capture_json_structure() {
        let config = DualCaptureConfig {
            primary_title: "__no_such_window__".to_string(),
            secondary_title: "__no_such_window__".to_string(),
            output_dir: PathBuf::from("test_output_dual"),
            resize: None,
        };
        let json = dual_capture_json(&config);
        assert!(json.get("primary").is_some());
        assert!(json.get("secondary").is_some());
        assert!(json["primary"].get("error").is_some());
        assert!(json["secondary"].get("error").is_some());
    }
}