hippox-drivers 0.3.3

🦛All indivisible atomic driver units in Hippox.
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Shared utilities for window control across platforms

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::ffi::c_void;

/// Window information structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindowInfo {
    pub id: u64,
    pub title: String,
    pub process_name: String,
    pub pid: u32,
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
    pub is_visible: bool,
    pub is_minimized: bool,
    pub is_maximized: bool,
}

/// Rectangle structure
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Rect {
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
}

impl Rect {
    pub fn new(x: i32, y: i32, width: u32, height: u32) -> Self {
        Self { x, y, width, height }
    }
}

/// Find window by title or process name
pub fn find_window(title: Option<&str>, process: Option<&str>) -> Result<u64> {
    let windows = list_windows()?;

    if let Some(title_match) = title {
        let title_lower = title_match.to_lowercase();
        if let Some(w) = windows
            .iter()
            .find(|w| w.title.to_lowercase().contains(&title_lower))
        {
            return Ok(w.id);
        }
    }

    if let Some(process_match) = process {
        let process_lower = process_match.to_lowercase();
        if let Some(w) = windows
            .iter()
            .find(|w| w.process_name.to_lowercase().contains(&process_lower))
        {
            return Ok(w.id);
        }
    }

    anyhow::bail!("Window not found: title={:?}, process={:?}", title, process)
}

// Helper function to convert u64 to HWND (Windows only)
#[cfg(target_os = "windows")]
pub fn u64_to_hwnd(id: u64) -> windows::Win32::Foundation::HWND {
    windows::Win32::Foundation::HWND(id as *mut c_void)
}

#[cfg(target_os = "windows")]
mod windows_impl {
    use super::*;
    use windows::Win32::Foundation::{BOOL, CloseHandle, HWND, LPARAM, RECT};
    use windows::Win32::System::ProcessStatus::GetModuleBaseNameW;
    use windows::Win32::System::Threading::{
        OpenProcess, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ,
    };
    use windows::Win32::UI::WindowsAndMessaging::*;
    pub fn list_windows() -> Result<Vec<WindowInfo>> {
        let mut windows: Vec<WindowInfo> = Vec::new();
        unsafe extern "system" fn enum_callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
            let windows_ptr = lparam.0 as *mut Vec<WindowInfo>;
            let windows = &mut *windows_ptr;
            if IsWindowVisible(hwnd).as_bool() {
                let mut title_buf = [0u16; 512];
                let len = GetWindowTextW(hwnd, &mut title_buf);
                let title = String::from_utf16_lossy(&title_buf[..len as usize]);
                let mut pid: u32 = 0;
                let _ = GetWindowThreadProcessId(hwnd, Some(&mut pid));
                let mut rect: RECT = std::mem::zeroed();
                let _ = GetWindowRect(hwnd, &mut rect);
                windows.push(WindowInfo {
                    id: hwnd.0 as u64,
                    title,
                    process_name: get_process_name(pid),
                    pid,
                    x: rect.left,
                    y: rect.top,
                    width: (rect.right - rect.left) as u32,
                    height: (rect.bottom - rect.top) as u32,
                    is_visible: true,
                    is_minimized: IsIconic(hwnd).as_bool(),
                    is_maximized: IsZoomed(hwnd).as_bool(),
                });
            }
            BOOL::from(true)
        }
        let mut windows_vec = windows;
        let lparam = LPARAM(&mut windows_vec as *mut Vec<WindowInfo> as isize);
        unsafe {
            let _ = EnumWindows(Some(enum_callback), lparam);
        }
        Ok(windows_vec)
    }

    fn get_process_name(pid: u32) -> String {
        unsafe {
            let handle_result =
                OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid);
            match handle_result {
                Ok(handle) => {
                    let mut name_buf = [0u16; 260];
                    let len = GetModuleBaseNameW(handle, None, &mut name_buf);
                    let _ = CloseHandle(handle);
                    String::from_utf16_lossy(&name_buf[..len as usize])
                }
                Err(_) => format!("[{}]", pid),
            }
        }
    }

    pub fn get_window_rect(window_id: u64) -> Result<Rect> {
        unsafe {
            let mut rect: RECT = std::mem::zeroed();
            let hwnd = u64_to_hwnd(window_id);
            let _ = GetWindowRect(hwnd, &mut rect);
            Ok(Rect {
                x: rect.left,
                y: rect.top,
                width: (rect.right - rect.left) as u32,
                height: (rect.bottom - rect.top) as u32,
            })
        }
    }

    pub fn set_window_pos(window_id: u64, x: i32, y: i32, width: u32, height: u32) -> Result<()> {
        unsafe {
            let hwnd = u64_to_hwnd(window_id);
            let _ = SetWindowPos(hwnd, None, x, y, width as i32, height as i32, SWP_NOZORDER);
        }
        Ok(())
    }

    pub fn show_window(window_id: u64, cmd: SHOW_WINDOW_CMD) -> Result<()> {
        unsafe {
            let hwnd = u64_to_hwnd(window_id);
            let _ = ShowWindow(hwnd, cmd);
        }
        Ok(())
    }

    pub fn close_window(window_id: u64) -> Result<()> {
        unsafe {
            let hwnd = u64_to_hwnd(window_id);
            let _ = PostMessageW(hwnd, WM_CLOSE, None, None);
        }
        Ok(())
    }

    pub fn kill_window(window_id: u64) -> Result<()> {
        unsafe {
            let hwnd = u64_to_hwnd(window_id);
            let mut pid: u32 = 0;
            let _ = GetWindowThreadProcessId(hwnd, Some(&mut pid));

            use windows::Win32::System::Threading::{
                OpenProcess, PROCESS_TERMINATE, TerminateProcess,
            };
            if let Ok(handle) = OpenProcess(PROCESS_TERMINATE, false, pid) {
                let _ = TerminateProcess(handle, 1);
                let _ = CloseHandle(handle);
            }
        }
        Ok(())
    }

    pub fn set_foreground_window(window_id: u64) -> Result<()> {
        unsafe {
            let hwnd = u64_to_hwnd(window_id);
            let _ = SetForegroundWindow(hwnd);
        }
        Ok(())
    }

    pub fn get_focus_window() -> Result<u64> {
        unsafe { Ok(GetForegroundWindow().0 as u64) }
    }
}

#[cfg(target_os = "macos")]
mod macos_impl {
    use super::*;
    use core_graphics::window::{
        CGWindow, CGWindowID, CGWindowListCopyWindowInfo, CGWindowListOption,
    };
    use std::collections::HashMap;

    pub fn list_windows() -> Result<Vec<WindowInfo>> {
        let mut windows = Vec::new();
        let window_info = unsafe {
            CGWindowListCopyWindowInfo(CGWindowListOption::kCGWindowListOptionAll, 0)
        };
        if let Some(info_array) = window_info {
            for window in info_array.iter() {
                let dict = window;
                let window_id: Option<u64> = dict.get("kCGWindowNumber").and_then(|v| v.as_u64());
                let title: String = dict
                    .get("kCGWindowName")
                    .and_then(|v| v.as_string())
                    .unwrap_or("")
                    .to_string();
                let pid: u32 = dict
                    .get("kCGWindowOwnerPID")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) as u32;
                let process_name: String = dict
                    .get("kCGWindowOwnerName")
                    .and_then(|v| v.as_string())
                    .unwrap_or("")
                    .to_string();
                let bounds = dict.get("kCGWindowBounds").and_then(|v| v.as_dictionary());
                let x: i32 = bounds
                    .and_then(|b| b.get("X"))
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0) as i32;
                let y: i32 = bounds
                    .and_then(|b| b.get("Y"))
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0) as i32;
                let width: u32 = bounds
                    .and_then(|b| b.get("Width"))
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0) as u32;
                let height: u32 = bounds
                    .and_then(|b| b.get("Height"))
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0) as u32;
                let is_visible: bool = dict
                    .get("kCGWindowIsOnscreen")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0) == 1;
                if let Some(id) = window_id {
                    windows.push(WindowInfo {
                        id,
                        title,
                        process_name,
                        pid,
                        x,
                        y,
                        width,
                        height,
                        is_visible,
                        is_minimized: false, // macOS: check via other API
                        is_maximized: false,
                    });
                }
            }
        }
        Ok(windows)
    }

    pub fn get_window_rect(window_id: u64) -> Result<Rect> {
        let windows = list_windows()?;
        let window = windows.iter().find(|w| w.id == window_id)
            .ok_or_else(|| anyhow::anyhow!("Window {} not found", window_id))?;
        Ok(Rect {
            x: window.x,
            y: window.y,
            width: window.width,
            height: window.height,
        })
    }

    pub fn set_window_pos(_window_id: u64, _x: i32, _y: i32, _width: u32, _height: u32) -> Result<()> {
        // TODO: Implement using AXUIElement
        anyhow::bail!("Window resize/move not implemented on macOS")
    }

    pub fn show_window(_window_id: u64, _cmd: u32) -> Result<()> {
        // TODO: Implement using AXUIElement
        anyhow::bail!("Show window not implemented on macOS")
    }

    pub fn close_window(_window_id: u64) -> Result<()> {
        // TODO: Implement using AXUIElement
        anyhow::bail!("Close window not implemented on macOS")
    }

    pub fn kill_window(window_id: u64) -> Result<()> {
        let windows = list_windows()?;
        let window = windows.iter().find(|w| w.id == window_id)
            .ok_or_else(|| anyhow::anyhow!("Window {} not found", window_id))?;
        
        use std::process::Command;
        Command::new("kill")
            .arg("-9")
            .arg(window.pid.to_string())
            .status()?;
        Ok(())
    }

    pub fn set_foreground_window(_window_id: u64) -> Result<()> {
        // TODO: Implement using AXUIElement
        anyhow::bail!("Set foreground window not implemented on macOS")
    }

    pub fn get_focus_window() -> Result<u64> {
        // Get frontmost window using NSWorkspace
        use objc2::runtime::AnyObject;
        use objc2::{class, msg_send, sel};
        
        let workspace = unsafe { msg_send![class!(NSWorkspace), sharedWorkspace] };
        let front_app: *mut AnyObject = unsafe { msg_send![workspace, frontmostApplication] };
        let pid: i32 = unsafe { msg_send![front_app, processIdentifier] };
        
        let windows = list_windows()?;
        if let Some(w) = windows.iter().find(|w| w.pid == pid as u32) {
            Ok(w.id)
        } else {
            Err(anyhow::anyhow!("No focused window found"))
        }
    }
}

#[cfg(target_os = "linux")]
mod linux_impl {
    use super::*;
    use std::process::Command;

    pub fn list_windows() -> Result<Vec<WindowInfo>> {
        // Use xdotool to list windows
        let output = Command::new("xdotool")
            .args(["search", "--name", ".*"])
            .output()?;
        
        let window_ids_str = String::from_utf8_lossy(&output.stdout);
        let window_ids: Vec<&str> = window_ids_str.trim().split('\n').collect();
        
        let mut windows = Vec::new();
        
        for (i, id_str) in window_ids.iter().enumerate() {
            if id_str.is_empty() {
                continue;
            }
            
            let id = id_str.parse::<u64>().unwrap_or(0);
            
            // Get window title
            let title_output = Command::new("xdotool")
                .args(["getwindowname", id_str])
                .output()
                .ok();
            let title = title_output
                .and_then(|o| String::from_utf8(o.stdout).ok())
                .unwrap_or_default()
                .trim()
                .to_string();
            
            // Get window geometry
            let geom_output = Command::new("xdotool")
                .args(["getwindowgeometry", id_str])
                .output()
                .ok();
            
            let mut x = 0;
            let mut y = 0;
            let mut width: u32 = 0;
            let mut height: u32 = 0;
            
            if let Some(output) = geom_output {
                let geom = String::from_utf8_lossy(&output.stdout);
                for line in geom.lines() {
                    if line.starts_with("Position:") {
                        let parts: Vec<&str> = line.split_whitespace().collect();
                        if parts.len() >= 2 {
                            let pos: Vec<&str> = parts[1].split(',').collect();
                            if pos.len() == 2 {
                                x = pos[0].parse().unwrap_or(0);
                                y = pos[1].parse().unwrap_or(0);
                            }
                        }
                    } else if line.starts_with("Geometry:") {
                        let parts: Vec<&str> = line.split_whitespace().collect();
                        if parts.len() >= 2 {
                            let geom: Vec<&str> = parts[1].split('x').collect();
                            if geom.len() == 2 {
                                width = geom[0].parse().unwrap_or(0);
                                height = geom[1].parse().unwrap_or(0);
                            }
                        }
                    }
                }
            }
            
            windows.push(WindowInfo {
                id,
                title,
                process_name: format!("window_{}", i),
                pid: 0,
                x,
                y,
                width,
                height,
                is_visible: true,
                is_minimized: false,
                is_maximized: false,
            });
        }
        
        Ok(windows)
    }

    pub fn get_window_rect(window_id: u64) -> Result<Rect> {
        let output = Command::new("xdotool")
            .args(["getwindowgeometry", &window_id.to_string()])
            .output()?;
        
        let geom = String::from_utf8_lossy(&output.stdout);
        let mut x = 0;
        let mut y = 0;
        let mut width: u32 = 0;
        let mut height: u32 = 0;
        
        for line in geom.lines() {
            if line.starts_with("Position:") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let pos: Vec<&str> = parts[1].split(',').collect();
                    if pos.len() == 2 {
                        x = pos[0].parse().unwrap_or(0);
                        y = pos[1].parse().unwrap_or(0);
                    }
                }
            } else if line.starts_with("Geometry:") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let geom: Vec<&str> = parts[1].split('x').collect();
                    if geom.len() == 2 {
                        width = geom[0].parse().unwrap_or(0);
                        height = geom[1].parse().unwrap_or(0);
                    }
                }
            }
        }
        
        Ok(Rect { x, y, width, height })
    }

    pub fn set_window_pos(window_id: u64, x: i32, y: i32, width: u32, height: u32) -> Result<()> {
        Command::new("xdotool")
            .args(["windowmove", &window_id.to_string(), &x.to_string(), &y.to_string()])
            .status()?;
        Command::new("xdotool")
            .args(["windowsize", &window_id.to_string(), &width.to_string(), &height.to_string()])
            .status()?;
        Ok(())
    }

    pub fn show_window(window_id: u64, cmd: u32) -> Result<()> {
        match cmd {
            3 | 9 => { // Maximize or Restore
                Command::new("xdotool")
                    .args(["windowactivate", &window_id.to_string()])
                    .status()?;
                // Try to maximize
                let _ = Command::new("xdotool")
                    .args(["windowsize", &window_id.to_string(), "100%", "100%"])
                    .status();
            }
            6 => { // Minimize
                Command::new("xdotool")
                    .args(["windowminimize", &window_id.to_string()])
                    .status()?;
            }
            _ => {}
        }
        Ok(())
    }

    pub fn close_window(window_id: u64) -> Result<()> {
        Command::new("xdotool")
            .args(["windowclose", &window_id.to_string()])
            .status()?;
        Ok(())
    }

    pub fn kill_window(window_id: u64) -> Result<()> {
        Command::new("xdotool")
            .args(["windowkill", &window_id.to_string()])
            .status()?;
        Ok(())
    }

    pub fn set_foreground_window(window_id: u64) -> Result<()> {
        Command::new("xdotool")
            .args(["windowactivate", &window_id.to_string()])
            .status()?;
        Ok(())
    }

    pub fn get_focus_window() -> Result<u64> {
        let output = Command::new("xdotool")
            .args(["getactivewindow"])
            .output()?;
        let id_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
        Ok(id_str.parse::<u64>().unwrap_or(0))
    }
}

#[cfg(target_os = "windows")]
pub use windows_impl::*;
#[cfg(target_os = "macos")]
pub use macos_impl::*;
#[cfg(target_os = "linux")]
pub use linux_impl::*;

pub fn list_windows() -> Result<Vec<WindowInfo>> {
    #[cfg(target_os = "windows")]
    return windows_impl::list_windows();
    #[cfg(target_os = "macos")]
    return macos_impl::list_windows();
    #[cfg(target_os = "linux")]
    return linux_impl::list_windows();
}

pub fn get_window_rect(window_id: u64) -> Result<Rect> {
    #[cfg(target_os = "windows")]
    return windows_impl::get_window_rect(window_id);
    #[cfg(target_os = "macos")]
    return macos_impl::get_window_rect(window_id);
    #[cfg(target_os = "linux")]
    return linux_impl::get_window_rect(window_id);
}

pub fn set_window_pos(window_id: u64, x: i32, y: i32, width: u32, height: u32) -> Result<()> {
    #[cfg(target_os = "windows")]
    return windows_impl::set_window_pos(window_id, x, y, width, height);
    #[cfg(target_os = "macos")]
    return macos_impl::set_window_pos(window_id, x, y, width, height);
    #[cfg(target_os = "linux")]
    return linux_impl::set_window_pos(window_id, x, y, width, height);
}

pub fn show_window(window_id: u64, cmd: u32) -> Result<()> {
    #[cfg(target_os = "windows")]
    {
        use windows::Win32::UI::WindowsAndMessaging::SHOW_WINDOW_CMD;
        let cmd_i32 = cmd.try_into()
            .map_err(|_| anyhow::anyhow!("Invalid SHOW_WINDOW_CMD value: {}", cmd))?;
        return windows_impl::show_window(window_id, SHOW_WINDOW_CMD(cmd_i32));
    }
    #[cfg(target_os = "macos")]
    return macos_impl::show_window(window_id, cmd);
    #[cfg(target_os = "linux")]
    return linux_impl::show_window(window_id, cmd);
}

pub fn close_window(window_id: u64) -> Result<()> {
    #[cfg(target_os = "windows")]
    return windows_impl::close_window(window_id);
    #[cfg(target_os = "macos")]
    return macos_impl::close_window(window_id);
    #[cfg(target_os = "linux")]
    return linux_impl::close_window(window_id);
}

pub fn kill_window(window_id: u64) -> Result<()> {
    #[cfg(target_os = "windows")]
    return windows_impl::kill_window(window_id);
    #[cfg(target_os = "macos")]
    return macos_impl::kill_window(window_id);
    #[cfg(target_os = "linux")]
    return linux_impl::kill_window(window_id);
}

pub fn set_foreground_window(window_id: u64) -> Result<()> {
    #[cfg(target_os = "windows")]
    return windows_impl::set_foreground_window(window_id);
    #[cfg(target_os = "macos")]
    return macos_impl::set_foreground_window(window_id);
    #[cfg(target_os = "linux")]
    return linux_impl::set_foreground_window(window_id);
}

pub fn get_focus_window() -> Result<u64> {
    #[cfg(target_os = "windows")]
    return windows_impl::get_focus_window();
    #[cfg(target_os = "macos")]
    return macos_impl::get_focus_window();
    #[cfg(target_os = "linux")]
    return linux_impl::get_focus_window();
}