Skip to content

Commit 620973c

Browse files
committed
fix(example): add window fallback and CG init to 02_window_capture
- Fallback to any visible window if Safari not found - Add CoreGraphics initialization to prevent crashes
1 parent 94eb9ad commit 620973c

1 file changed

Lines changed: 33 additions & 3 deletions

File tree

examples/02_window_capture.rs

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,14 @@ use screencapturekit::prelude::*;
1010
use std::sync::atomic::{AtomicUsize, Ordering};
1111
use std::sync::Arc;
1212

13+
// Initialize CoreGraphics to prevent CGS_REQUIRE_INIT crashes
14+
fn init_cg() {
15+
extern "C" {
16+
fn sc_initialize_core_graphics();
17+
}
18+
unsafe { sc_initialize_core_graphics() }
19+
}
20+
1321
struct FrameHandler {
1422
count: Arc<AtomicUsize>,
1523
}
@@ -21,6 +29,7 @@ impl SCStreamOutputTrait for FrameHandler {
2129
}
2230

2331
fn main() -> Result<(), Box<dyn std::error::Error>> {
32+
init_cg();
2433
println!("🪟 Window Capture\n");
2534

2635
// 1. Get available content
@@ -45,16 +54,37 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
4554
);
4655
}
4756

48-
// 3. Find a window (example: Safari)
57+
// 3. Find a window - prefer Safari, but fallback to any visible window
4958
let window = windows
5059
.iter()
5160
.find(|w| {
5261
w.owning_application()
5362
.is_some_and(|app| app.application_name().contains("Safari"))
5463
})
55-
.ok_or("Safari window not found. Try another app.")?;
64+
.or_else(|| {
65+
// Fallback: find any on-screen window with a title
66+
windows.iter().find(|w| {
67+
w.is_on_screen()
68+
&& w.frame().width > 100.0
69+
&& w.frame().height > 100.0
70+
&& w.title().is_some_and(|t| !t.is_empty())
71+
})
72+
})
73+
.or_else(|| {
74+
// Last resort: any on-screen window
75+
windows.iter().find(|w| w.is_on_screen())
76+
})
77+
.ok_or("No suitable window found")?;
5678

57-
println!("\nCapturing: {}\n", window.title().unwrap_or_default());
79+
let app_name = window
80+
.owning_application()
81+
.map(|app| app.application_name())
82+
.unwrap_or_default();
83+
println!(
84+
"\nCapturing: {} - {}\n",
85+
app_name,
86+
window.title().unwrap_or_default()
87+
);
5888

5989
// 4. Create window filter
6090
let filter = SCContentFilter::builder().window(window).build();

0 commit comments

Comments
 (0)