cc-xcap 0.1.5

Forked from xcap, CC-XCap is a cross-platform screen capture library written in Rust, forked from xcap. It supports Linux (X11, Wayland), MacOS, and Windows. CC-XCap supports screenshot and video recording (WIP).
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
use std::ffi::c_void;

use image::RgbaImage;
use objc2_app_kit::NSWorkspace;
use objc2_core_foundation::CGSize;
use objc2_core_foundation::{
    CFBoolean, CFDictionary, CFNumber, CFNumberType, CFRetained, CFString, CGPoint, CGRect,
};
use objc2_core_graphics::{
    CGDisplayBounds, CGMainDisplayID, CGRectContainsPoint, CGRectIntersectsRect,
    CGRectMakeWithDictionaryRepresentation, CGWindowListCopyWindowInfo, CGWindowListOption,
};
use objc2_foundation::{NSNumber, NSString};

use crate::{XCapError, error::XCapResult};

use super::{capture::capture, impl_monitor::ImplMonitor};

#[derive(Debug, Clone)]
pub(crate) struct ImplWindow {
    pub window_id: u32,
    // 缓存属性,使用基本类型
    pid_inner: Option<u32>,
    app_name_inner: Option<String>,
    title_inner: Option<String>,
    x_inner: Option<i32>,
    y_inner: Option<i32>,
    width_inner: Option<u32>,
    height_inner: Option<u32>,
    is_on_screen_inner: Option<bool>,
    z_inner: Option<i32>,
}

unsafe impl Send for ImplWindow {}

fn get_cf_dictionary_get_value(
    cf_dictionary: &CFDictionary,
    key: &str,
) -> XCapResult<*const c_void> {
    unsafe {
        let cf_dictionary_key = CFString::from_str(key);
        let cf_dictionary_key_ref = cf_dictionary_key.as_ref() as *const CFString;

        let value = cf_dictionary.value(cf_dictionary_key_ref.cast());

        if value.is_null() {
            return Err(XCapError::new(format!(
                "Get CFDictionary {} value failed",
                key
            )));
        }

        Ok(value)
    }
}

fn get_cf_number_i32_value(cf_dictionary: &CFDictionary, key: &str) -> XCapResult<i32> {
    unsafe {
        let cf_number = get_cf_dictionary_get_value(cf_dictionary, key)? as *const CFNumber;

        let mut value: i32 = 0;
        let is_success =
            (*cf_number).value(CFNumberType::IntType, &mut value as *mut _ as *mut c_void);

        if !is_success {
            return Err(XCapError::new(format!(
                "Get {} CFNumberGetValue failed",
                key
            )));
        }

        Ok(value)
    }
}

fn get_cf_string_value(cf_dictionary: &CFDictionary, key: &str) -> XCapResult<String> {
    let value_ref = get_cf_dictionary_get_value(cf_dictionary, key)? as *const CFString;
    let value = unsafe { (*value_ref).to_string() };
    Ok(value)
}

fn get_cf_bool_value(cf_dictionary: &CFDictionary, key: &str) -> XCapResult<bool> {
    let value_ref = get_cf_dictionary_get_value(cf_dictionary, key)? as *const CFBoolean;

    Ok(unsafe { (*value_ref).value() })
}

fn get_window_cg_rect(window_cf_dictionary: &CFDictionary) -> XCapResult<CGRect> {
    unsafe {
        let window_bounds = get_cf_dictionary_get_value(window_cf_dictionary, "kCGWindowBounds")?
            as *const CFDictionary;

        let mut cg_rect = CGRect::default();

        let is_success =
            CGRectMakeWithDictionaryRepresentation(Some(&*window_bounds), &mut cg_rect);

        if !is_success {
            return Err(XCapError::new(
                "CGRectMakeWithDictionaryRepresentation failed",
            ));
        }

        Ok(cg_rect)
    }
}

fn get_window_id(window_cf_dictionary: &CFDictionary) -> XCapResult<u32> {
    let window_name = get_cf_string_value(window_cf_dictionary, "kCGWindowName")?;

    let window_owner_name = get_cf_string_value(window_cf_dictionary, "kCGWindowOwnerName")?;

    if window_name.eq("StatusIndicator") && window_owner_name.eq("Window Server") {
        return Err(XCapError::new("Window is StatusIndicator"));
    }

    let window_sharing_state =
        get_cf_number_i32_value(window_cf_dictionary, "kCGWindowSharingState")?;

    if window_sharing_state == 0 {
        return Err(XCapError::new("Window sharing state is 0"));
    }

    let window_id = get_cf_number_i32_value(window_cf_dictionary, "kCGWindowNumber")?;

    Ok(window_id as u32)
}

/**
 * 遍历所有窗口,找到指定窗口的 CFDictionary
 */
pub fn get_window_cf_dictionary(window_id: u32) -> XCapResult<CFRetained<CFDictionary>> {
    unsafe {
        // CGWindowListCopyWindowInfo 返回窗口顺序为从顶层到最底层
        // 即在前面的窗口在数组前面
        let cf_array = match CGWindowListCopyWindowInfo(
            CGWindowListOption::OptionAll | CGWindowListOption::ExcludeDesktopElements,
            0,
        ) {
            Some(cf_array) => cf_array,
            None => return Err(XCapError::new("Get window info failed")),
        };

        let windows_count = cf_array.count();

        for i in 0..windows_count {
            let window_cf_dictionary_ref = cf_array.value_at_index(i) as *const CFDictionary;

            if window_cf_dictionary_ref.is_null() {
                continue;
            }
            let window_cf_dictionary = &*window_cf_dictionary_ref;

            let current_window_id = match get_window_id(window_cf_dictionary) {
                Ok(val) => val,
                Err(_) => continue,
            };

            if current_window_id == window_id {
                let s = CFDictionary::new_copy(None, Some(window_cf_dictionary)).unwrap();
                return Ok(s);
            }
        }

        Err(XCapError::new("Window not found"))
    }
}

impl ImplWindow {
    // 从已取到的 CFDictionary 直接构造,避免重复调用 CGWindowListCopyWindowInfo
    fn from_cf_dictionary(window_id: u32, dict: &CFDictionary) -> ImplWindow {
        let pid = get_cf_number_i32_value(dict, "kCGWindowOwnerPID")
            .ok()
            .map(|p| p as u32);
        let app_name = get_cf_string_value(dict, "kCGWindowOwnerName").ok();
        let title = get_cf_string_value(dict, "kCGWindowName").ok();

        let cg_rect = get_window_cg_rect(dict).ok();
        let x = cg_rect.map(|r| r.origin.x as i32);
        let y = cg_rect.map(|r| r.origin.y as i32);
        let width = cg_rect.map(|r| r.size.width as u32);
        let height = cg_rect.map(|r| r.size.height as u32);

        let is_on_screen = get_cf_bool_value(dict, "kCGWindowIsOnscreen").ok();

        ImplWindow {
            window_id,
            pid_inner: pid,
            app_name_inner: app_name,
            title_inner: title,
            x_inner: x,
            y_inner: y,
            width_inner: width,
            height_inner: height,
            is_on_screen_inner: is_on_screen,
            z_inner: None, // z 值需要在整个窗口列表中计算,在构造函数中暂不计算
        }
    }

    pub fn all() -> XCapResult<Vec<ImplWindow>> {
        unsafe {
            let mut impl_window = Vec::new();

            // CGWindowListCopyWindowInfo 返回窗口顺序为从顶层到最底层
            // 即在前面的窗口在数组前面
            let cf_array = match CGWindowListCopyWindowInfo(
                CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements,
                0,
            ) {
                Some(cf_array) => cf_array,
                None => return Ok(impl_window),
            };

            let windows_count = cf_array.count();

            for i in 0..windows_count {
                let window_cf_dictionary_ref = cf_array.value_at_index(i) as *const CFDictionary;

                if window_cf_dictionary_ref.is_null() {
                    continue;
                }

                let window_cf_dictionary = &*window_cf_dictionary_ref;

                let window_id = match get_window_id(window_cf_dictionary) {
                    Ok(window_id) => window_id,
                    Err(_) => continue,
                };

                impl_window.push(ImplWindow::from_cf_dictionary(
                    window_id,
                    window_cf_dictionary,
                ));
            }

            Ok(impl_window)
        }
    }

    pub fn list_all() -> XCapResult<Vec<ImplWindow>> {
        unsafe {
            let mut impl_window = Vec::new();

            // CGWindowListCopyWindowInfo 返回窗口顺序为从顶层到最底层
            // 即在前面的窗口在数组前面
            let cf_array = match CGWindowListCopyWindowInfo(
                CGWindowListOption::OptionAll | CGWindowListOption::ExcludeDesktopElements,
                0,
            ) {
                Some(cf_array) => cf_array,
                None => return Ok(impl_window),
            };

            let windows_count = cf_array.count();

            for i in 0..windows_count {
                let window_cf_dictionary_ref = cf_array.value_at_index(i) as *const CFDictionary;

                if window_cf_dictionary_ref.is_null() {
                    continue;
                }

                let window_cf_dictionary = &*window_cf_dictionary_ref;

                let window_id = match get_window_id(window_cf_dictionary) {
                    Ok(window_id) => window_id,
                    Err(_) => continue,
                };

                impl_window.push(ImplWindow::from_cf_dictionary(
                    window_id,
                    window_cf_dictionary,
                ));
            }

            Ok(impl_window)
        }
    }
}

impl ImplWindow {
    pub fn id(&self) -> XCapResult<u32> {
        Ok(self.window_id)
    }

    pub fn pid(&self) -> XCapResult<u32> {
        // 优先使用缓存
        if let Some(pid) = self.pid_inner {
            return Ok(pid);
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        let pid = get_cf_number_i32_value(window_cf_dictionary.as_ref(), "kCGWindowOwnerPID")?;
        Ok(pid as u32)
    }

    pub fn app_name(&self) -> XCapResult<String> {
        // 优先使用缓存
        if let Some(ref app_name) = self.app_name_inner {
            return Ok(app_name.clone());
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        get_cf_string_value(window_cf_dictionary.as_ref(), "kCGWindowOwnerName")
    }

    pub fn title(&self) -> XCapResult<String> {
        // 优先使用缓存
        if let Some(ref title) = self.title_inner {
            return Ok(title.clone());
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        get_cf_string_value(window_cf_dictionary.as_ref(), "kCGWindowName")
    }

    pub fn current_monitor(&self) -> XCapResult<ImplMonitor> {
        // 优先使用缓存的坐标和尺寸来构建 cg_rect
        let cg_rect = if let (Some(x), Some(y), Some(width), Some(height)) = (
            self.x_inner,
            self.y_inner,
            self.width_inner,
            self.height_inner,
        ) {
            CGRect {
                origin: CGPoint {
                    x: x as f64,
                    y: y as f64,
                },
                size: CGSize {
                    width: width as f64,
                    height: height as f64,
                },
            }
        } else {
            // 缓存不存在,使用现有实现作为兜底
            let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
            get_window_cg_rect(window_cf_dictionary.as_ref())?
        };

        // 获取窗口中心点的坐标
        let window_center_x = cg_rect.origin.x + cg_rect.size.width / 2.0;
        let window_center_y = cg_rect.origin.y + cg_rect.size.height / 2.0;
        let cg_point = CGPoint {
            x: window_center_x,
            y: window_center_y,
        };

        let impl_monitors = ImplMonitor::all()?;
        let primary_monitor = ImplMonitor::new(unsafe { CGMainDisplayID() });

        let impl_monitor = impl_monitors
            .iter()
            .find(|impl_monitor| unsafe {
                let display_bounds = CGDisplayBounds(impl_monitor.cg_direct_display_id);
                CGRectContainsPoint(display_bounds, cg_point)
                    || CGRectIntersectsRect(display_bounds, cg_rect)
            })
            .unwrap_or(&primary_monitor);

        Ok(impl_monitor.to_owned())
    }

    pub fn x(&self) -> XCapResult<i32> {
        // 优先使用缓存
        if let Some(x) = self.x_inner {
            return Ok(x);
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        let cg_rect = get_window_cg_rect(window_cf_dictionary.as_ref())?;
        Ok(cg_rect.origin.x as i32)
    }

    pub fn y(&self) -> XCapResult<i32> {
        // 优先使用缓存
        if let Some(y) = self.y_inner {
            return Ok(y);
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        let cg_rect = get_window_cg_rect(window_cf_dictionary.as_ref())?;
        Ok(cg_rect.origin.y as i32)
    }

    pub fn z(&self) -> XCapResult<i32> {
        // 优先使用缓存
        if let Some(z) = self.z_inner {
            return Ok(z);
        }

        // 缓存不存在时,使用现有实现作为兜底
        unsafe {
            // CGWindowListCopyWindowInfo 返回窗口顺序为从顶层到最底层
            // 即在前面的窗口在数组前面
            let cf_array = match CGWindowListCopyWindowInfo(
                CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements,
                0,
            ) {
                Some(cf_array) => cf_array,
                None => return Err(XCapError::new("Get window list failed")),
            };

            let windows_count = cf_array.count();
            let mut z = windows_count as i32;

            for i in 0..windows_count {
                z -= 1;
                let window_cf_dictionary_ref = cf_array.value_at_index(i) as *const CFDictionary;

                if window_cf_dictionary_ref.is_null() {
                    continue;
                }

                let window_cf_dictionary = &*window_cf_dictionary_ref;

                let window_id = match get_window_id(window_cf_dictionary) {
                    Ok(window_id) => window_id,
                    Err(_) => continue,
                };

                if window_id == self.window_id {
                    break;
                }
            }

            Ok(z)
        }
    }

    pub fn width(&self) -> XCapResult<u32> {
        // 优先使用缓存
        if let Some(width) = self.width_inner {
            return Ok(width);
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        let cg_rect = get_window_cg_rect(window_cf_dictionary.as_ref())?;
        Ok(cg_rect.size.width as u32)
    }

    pub fn height(&self) -> XCapResult<u32> {
        // 优先使用缓存
        if let Some(height) = self.height_inner {
            return Ok(height);
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        let cg_rect = get_window_cg_rect(window_cf_dictionary.as_ref())?;
        Ok(cg_rect.size.height as u32)
    }

    pub fn is_minimized(&self) -> XCapResult<bool> {
        // 优先使用缓存
        if let Some(is_on_screen) = self.is_on_screen_inner {
            let is_maximized = self.is_maximized()?;
            return Ok(!is_on_screen && !is_maximized);
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        let is_on_screen = get_cf_bool_value(window_cf_dictionary.as_ref(), "kCGWindowIsOnscreen")
            .unwrap_or(false); // 如果无法获取,默认为 false
        let is_maximized = self.is_maximized()?;
        Ok(!is_on_screen && !is_maximized)
    }

    pub fn is_maximized(&self) -> XCapResult<bool> {
        // 优先使用缓存
        if let (Some(width), Some(height)) = (self.width_inner, self.height_inner) {
            let impl_monitor = self.current_monitor()?;
            let impl_monitor_width = impl_monitor.width()?;
            let impl_monitor_height = impl_monitor.height()?;

            let is_maximized = { width >= impl_monitor_width && height >= impl_monitor_height };

            return Ok(is_maximized);
        }

        // 缓存不存在时,使用现有实现作为兜底
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;
        let cg_rect = get_window_cg_rect(window_cf_dictionary.as_ref())?;
        let impl_monitor = self.current_monitor()?;
        let impl_monitor_width = impl_monitor.width()?;
        let impl_monitor_height = impl_monitor.height()?;

        let is_maximized = {
            cg_rect.size.width as u32 >= impl_monitor_width
                && cg_rect.size.height as u32 >= impl_monitor_height
        };

        Ok(is_maximized)
    }

    pub fn is_focused(&self) -> XCapResult<bool> {
        let pid_key = NSString::from_str("NSApplicationProcessIdentifier");

        unsafe {
            let workspace = NSWorkspace::sharedWorkspace();

            // activeApplication is deprecated, but the alternative, frontmostApplication,
            // returns the application in focus when the process started while activeApplication
            // returns a `NSDictionary` of application currently in focus, in real-time
            let active_app_dictionary = workspace.activeApplication();

            let active_app_pid = active_app_dictionary
                .and_then(|dict| dict.valueForKey(&pid_key))
                .and_then(|pid| pid.downcast::<NSNumber>().ok())
                .map(|pid| pid.intValue() as u32);

            if active_app_pid == self.pid().ok() {
                return Ok(true);
            }

            Ok(false)
        }
    }

    pub fn capture_image(&self) -> XCapResult<RgbaImage> {
        let window_cf_dictionary = get_window_cf_dictionary(self.window_id)?;

        let cg_rect = get_window_cg_rect(window_cf_dictionary.as_ref())?;

        capture(
            cg_rect,
            CGWindowListOption::OptionIncludingWindow,
            self.window_id,
        )
    }
    pub fn capture_thumbnail(&self) -> XCapResult<RgbaImage> {
        // 先获取原始图片
        let original_image = self.capture_image()?;

        // 计算缩略图尺寸
        let original_width = original_image.width() as f64;
        let original_height = original_image.height() as f64;
        let max_width = 200.0;

        // 计算缩放比例,保持宽高比
        let scale = if original_width > max_width {
            max_width / original_width
        } else {
            1.0 // 如果原图宽度小于等于200px,不缩放
        };

        let new_width = (original_width * scale) as u32;
        let new_height = (original_height * scale) as u32;

        // 使用 image crate 的 resize 功能
        let thumbnail = image::imageops::resize(
            &original_image,
            new_width,
            new_height,
            image::imageops::FilterType::Lanczos3,
        );

        Ok(thumbnail)
    }
}