crosswin 0.4.0

Async-friendly Windows primitives for Rust with process management, memory monitoring, and system operations.
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
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
use std::fmt;
use std::hash::{Hash, Hasher};
use crate::error::{CrosswinError, Result};

// ─── WindowInfo ───────────────────────────────────────────────────────────────

/// A snapshot of information about a top-level window.
///
/// `PartialEq` and `Hash` are keyed on the raw `hwnd` value.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WindowInfo {
    /// Raw HWND handle value.
    pub hwnd: u64,
    /// Window title text.
    pub title: String,
    /// Window class name.
    pub class_name: Option<String>,
    /// Width in screen pixels.
    pub width: Option<u32>,
    /// Height in screen pixels.
    pub height: Option<u32>,
    /// Left edge of the window in screen coordinates.
    pub x: Option<i32>,
    /// Top edge of the window in screen coordinates.
    pub y: Option<i32>,
    /// Whether the window is currently visible.
    pub is_visible: Option<bool>,
    /// PID of the process that owns this window.
    pub process_id: Option<u32>,
}

impl PartialEq for WindowInfo {
    fn eq(&self, other: &Self) -> bool {
        self.hwnd == other.hwnd
    }
}

impl Eq for WindowInfo {}

impl Hash for WindowInfo {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.hwnd.hash(state);
    }
}

impl fmt::Display for WindowInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[HWND:0x{:X}] \"{}\"", self.hwnd, self.title)?;
        if let (Some(w), Some(h)) = (self.width, self.height) {
            write!(f, " ({}×{}", w, h)?;
            if let (Some(x), Some(y)) = (self.x, self.y) {
                write!(f, " @ {},{}", x, y)?;
            }
            write!(f, ")")?;
        }
        if let Some(pid) = self.process_id {
            write!(f, "  PID={}", pid)?;
        }
        Ok(())
    }
}

// ─── Window ───────────────────────────────────────────────────────────────────

/// A handle to a window with operations.
///
/// Not `Clone` — use `Window::try_clone()` which validates the handle first.
#[derive(Debug)]
pub struct Window {
    hwnd: u64,
}

impl Window {
    /// Create a `Window` from a raw platform handle value.
    pub fn from_raw(hwnd: u64) -> Self {
        Self { hwnd }
    }

    /// Return the raw HWND value.
    pub fn hwnd(&self) -> u64 {
        self.hwnd
    }

    /// Returns `true` when the stored HWND is still a live window.
    pub fn is_valid(&self) -> bool {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::UI::WindowsAndMessaging::IsWindow;
            use windows::Win32::Foundation::HWND;
            unsafe { IsWindow(HWND(self.hwnd as isize)).as_bool() }
        }
        #[cfg(not(feature = "win32"))]
        {
            false
        }
    }

    /// Clone this handle only when the HWND is still valid.
    ///
    /// Returns `Err(CrosswinError::InvalidParameter)` if the window no longer
    /// exists.
    pub fn try_clone(&self) -> Result<Window> {
        if self.is_valid() {
            Ok(Window { hwnd: self.hwnd })
        } else {
            Err(CrosswinError::invalid_parameter(
                "hwnd",
                "Window handle is no longer valid",
            ))
        }
    }

    // ── Visibility ────────────────────────────────────────────────────────────

    /// Show the window.
    pub fn show(&self) -> Result<()> {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_SHOW};
            unsafe {
                let hwnd = windows::Win32::Foundation::HWND(self.hwnd as isize);
                let _ = ShowWindow(hwnd, SW_SHOW);
            }
            Ok(())
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }

    /// Hide the window.
    pub fn hide(&self) -> Result<()> {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_HIDE};
            unsafe {
                let hwnd = windows::Win32::Foundation::HWND(self.hwnd as isize);
                let _ = ShowWindow(hwnd, SW_HIDE);
            }
            Ok(())
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }

    /// Bring the window to the foreground.
    pub fn bring_to_front(&self) -> Result<()> {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::UI::WindowsAndMessaging::{
                BringWindowToTop, SetForegroundWindow,
            };
            use windows::Win32::Foundation::HWND;
            unsafe {
                let hwnd = HWND(self.hwnd as isize);
                let _ = SetForegroundWindow(hwnd);
                BringWindowToTop(hwnd).map_err(|e| CrosswinError::win32(
                    "BringWindowToTop",
                    e.code().0 as u32,
                    e.to_string(),
                ))?;
            }
            Ok(())
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }

    // ── Geometry ──────────────────────────────────────────────────────────────

    /// Move the window to (`x`, `y`) while preserving its size.
    pub fn move_to(&self, _x: i32, _y: i32) -> Result<()> {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::UI::WindowsAndMessaging::{
                SetWindowPos, SWP_NOSIZE, SWP_NOZORDER,
            };
            use windows::Win32::Foundation::HWND;
            unsafe {
                SetWindowPos(
                    HWND(self.hwnd as isize),
                    HWND(0),
                    _x, _y, 0, 0,
                    SWP_NOSIZE | SWP_NOZORDER,
                )
                .map_err(|e| CrosswinError::win32("SetWindowPos", e.code().0 as u32, e.to_string()))?;
            }
            Ok(())
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }

    /// Resize the window to `width` × `height` while preserving its position.
    pub fn resize(&self, _width: u32, _height: u32) -> Result<()> {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::UI::WindowsAndMessaging::{
                SetWindowPos, SWP_NOMOVE, SWP_NOZORDER,
            };
            use windows::Win32::Foundation::HWND;
            unsafe {
                SetWindowPos(
                    HWND(self.hwnd as isize),
                    HWND(0),
                    0, 0, _width as i32, _height as i32,
                    SWP_NOMOVE | SWP_NOZORDER,
                )
                .map_err(|e| CrosswinError::win32("SetWindowPos", e.code().0 as u32, e.to_string()))?;
            }
            Ok(())
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }

    /// Query the current top-left position of the window.
    pub fn position(&self) -> Result<(i32, i32)> {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::Foundation::{HWND, RECT};
            use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
            unsafe {
                let mut rect = RECT::default();
                GetWindowRect(HWND(self.hwnd as isize), &mut rect)
                    .map_err(|e| CrosswinError::win32("GetWindowRect", e.code().0 as u32, e.to_string()))?;
                Ok((rect.left, rect.top))
            }
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }

    /// Query the current size of the window.
    pub fn size(&self) -> Result<(u32, u32)> {
        #[cfg(feature = "win32")]
        {
            use windows::Win32::Foundation::{HWND, RECT};
            use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
            unsafe {
                let mut rect = RECT::default();
                GetWindowRect(HWND(self.hwnd as isize), &mut rect)
                    .map_err(|e| CrosswinError::win32("GetWindowRect", e.code().0 as u32, e.to_string()))?;
                Ok((
                    rect.right.saturating_sub(rect.left) as u32,
                    rect.bottom.saturating_sub(rect.top) as u32,
                ))
            }
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }

    // ── Text ──────────────────────────────────────────────────────────────────

    /// Set window title text.
    pub fn set_title(&self, _title: &str) -> Result<()> {
        #[cfg(feature = "win32")]
        {
            use windows::core::PCWSTR;
            use windows::Win32::UI::WindowsAndMessaging::SetWindowTextW;
            use widestring::U16CString;

            let wide = U16CString::from_str(_title).map_err(|e| {
                CrosswinError::invalid_parameter("title", format!("invalid unicode: {}", e))
            })?;
            unsafe {
                let hwnd = windows::Win32::Foundation::HWND(self.hwnd as isize);
                SetWindowTextW(hwnd, PCWSTR(wide.as_ptr()))
                    .map_err(|e| CrosswinError::win32("SetWindowTextW", e.code().0 as u32, e.to_string()))?;
            }
            Ok(())
        }
        #[cfg(not(feature = "win32"))]
        {
            Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
        }
    }
}

// ─── Free functions ───────────────────────────────────────────────────────────

/// Retrieve the title text for a window identified by its raw HWND.
pub fn get_window_text(_hwnd: u64) -> Result<String> {
    #[cfg(feature = "win32")]
    {
        use windows::Win32::Foundation::HWND;
        use windows::Win32::UI::WindowsAndMessaging::{GetWindowTextLengthW, GetWindowTextW};

        unsafe {
            let h = HWND(_hwnd as isize);
            let len = GetWindowTextLengthW(h);
            if len <= 0 {
                return Ok(String::new());
            }
            let mut buf: Vec<u16> = vec![0; (len + 1) as usize];
            let read = GetWindowTextW(h, &mut buf);
            if read > 0 {
                Ok(String::from_utf16_lossy(&buf[..read as usize]))
            } else {
                Ok(String::new())
            }
        }
    }
    #[cfg(not(feature = "win32"))]
    {
        let _ = _hwnd;
        Err(CrosswinError::invalid_parameter("platform", "Not supported on this platform"))
    }
}

/// List all top-level windows. Returns an empty `Vec` on non-Win32 builds.
pub async fn list_windows() -> Result<Vec<WindowInfo>> {
    #[cfg(feature = "win32")]
    {
        use windows::Win32::Foundation::{BOOL, HWND, LPARAM, RECT};
        use windows::Win32::UI::WindowsAndMessaging::{
            EnumWindows, GetClassNameW, GetWindowRect, GetWindowTextLengthW, GetWindowTextW,
            GetWindowThreadProcessId, IsWindowVisible,
        };

        unsafe extern "system" fn callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
            let vec_ptr = lparam.0 as *mut Vec<WindowInfo>;
            if vec_ptr.is_null() {
                return BOOL(1);
            }
            let list = &mut *vec_ptr;

            // Title
            let len = GetWindowTextLengthW(hwnd);
            let mut title = String::new();
            if len > 0 {
                let mut buf: Vec<u16> = vec![0; (len + 1) as usize];
                let read = GetWindowTextW(hwnd, &mut buf);
                if read > 0 {
                    title = String::from_utf16_lossy(&buf[..read as usize]);
                }
            }

            // Class name
            let mut class_buf: [u16; 256] = [0; 256];
            let class_len = GetClassNameW(hwnd, &mut class_buf);
            let class_name = if class_len > 0 {
                Some(String::from_utf16_lossy(&class_buf[..class_len as usize]))
            } else {
                None
            };

            // Rect
            let mut rect = RECT::default();
            let _ = GetWindowRect(hwnd, &mut rect);
            let width = rect.right.saturating_sub(rect.left) as u32;
            let height = rect.bottom.saturating_sub(rect.top) as u32;

            // Visibility
            let visible = IsWindowVisible(hwnd).as_bool();

            // Process ID
            let mut pid: u32 = 0;
            let _ = GetWindowThreadProcessId(hwnd, Some(&mut pid));

            list.push(WindowInfo {
                hwnd: hwnd.0 as u64,
                title,
                class_name,
                width: Some(width),
                height: Some(height),
                x: Some(rect.left),
                y: Some(rect.top),
                is_visible: Some(visible),
                process_id: Some(pid),
            });

            BOOL(1)
        }

        let mut list: Vec<WindowInfo> = Vec::new();
        let ptr = &mut list as *mut _ as isize;
        unsafe {
            let _ = EnumWindows(Some(callback), LPARAM(ptr));
        }
        Ok(list)
    }

    #[cfg(not(feature = "win32"))]
    {
        Ok(Vec::new())
    }
}

/// Find windows by title substring (case-insensitive).
pub async fn find_windows_by_title(title: &str) -> Result<Vec<WindowInfo>> {
    let all = list_windows().await?;
    let lower = title.to_lowercase();
    Ok(all.into_iter().filter(|w| w.title.to_lowercase().contains(&lower)).collect())
}

/// Find windows by class name (case-insensitive).
///
/// # Bug fix (v0.4.0)
/// Previously used a case-sensitive exact match; now normalises to lowercase
/// for consistency with `find_windows_by_title`.
pub async fn find_windows_by_class(class: &str) -> Result<Vec<WindowInfo>> {
    let all = list_windows().await?;
    let lower = class.to_lowercase();
    Ok(all
        .into_iter()
        .filter(|w| {
            w.class_name
                .as_deref()
                .map_or(false, |c| c.to_lowercase() == lower)
        })
        .collect())
}

/// Find windows owned by a specific process.
pub async fn find_windows_by_process(pid: u32) -> Result<Vec<WindowInfo>> {
    let all = list_windows().await?;
    Ok(all.into_iter().filter(|w| w.process_id == Some(pid)).collect())
}

// ─── WindowFilter ─────────────────────────────────────────────────────────────

/// Builder for filtering windows with multiple criteria.
///
/// ```rust,no_run
/// # use crosswin::windows::window::WindowFilter;
/// # #[tokio::main] async fn main() {
/// let results = WindowFilter::new()
///     .title_contains("Visual Studio")
///     .visible_only(true)
///     .min_width(800)
///     .list()
///     .await
///     .unwrap();
/// # }
/// ```
#[derive(Default, Debug, Clone)]
pub struct WindowFilter {
    title_contains: Option<String>,
    class_name: Option<String>,
    visible_only: Option<bool>,
    process_id: Option<u32>,
    min_width: Option<u32>,
    min_height: Option<u32>,
}

impl WindowFilter {
    /// Create a new, empty window filter.
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter by title substring (case-insensitive).
    pub fn title_contains<S: Into<String>>(mut self, s: S) -> Self {
        self.title_contains = Some(s.into().to_lowercase());
        self
    }

    /// Filter by exact class name (case-insensitive).
    pub fn class_name<S: Into<String>>(mut self, s: S) -> Self {
        self.class_name = Some(s.into().to_lowercase());
        self
    }

    /// When `true`, only include windows where `IsWindowVisible` returns `true`.
    pub fn visible_only(mut self, v: bool) -> Self {
        self.visible_only = Some(v);
        self
    }

    /// Only include windows owned by the given PID.
    pub fn process_id(mut self, pid: u32) -> Self {
        self.process_id = Some(pid);
        self
    }

    /// Only include windows at least this many pixels wide.
    pub fn min_width(mut self, w: u32) -> Self {
        self.min_width = Some(w);
        self
    }

    /// Only include windows at least this many pixels tall.
    pub fn min_height(mut self, h: u32) -> Self {
        self.min_height = Some(h);
        self
    }

    /// Execute the filter and return matching windows.
    pub async fn list(self) -> Result<Vec<WindowInfo>> {
        let all = list_windows().await?;
        Ok(all.into_iter().filter(|w| self.matches(w)).collect())
    }

    fn matches(&self, w: &WindowInfo) -> bool {
        if let Some(ref title) = self.title_contains {
            if !w.title.to_lowercase().contains(title) {
                return false;
            }
        }
        if let Some(ref class) = self.class_name {
            if !w.class_name.as_deref().map_or(false, |c| c.to_lowercase() == *class) {
                return false;
            }
        }
        if let Some(vis) = self.visible_only {
            if vis && !w.is_visible.unwrap_or(false) {
                return false;
            }
        }
        if let Some(pid) = self.process_id {
            if w.process_id != Some(pid) {
                return false;
            }
        }
        if let Some(min_w) = self.min_width {
            if w.width.map_or(true, |width| width < min_w) {
                return false;
            }
        }
        if let Some(min_h) = self.min_height {
            if w.height.map_or(true, |height| height < min_h) {
                return false;
            }
        }
        true
    }
}