Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Say when macOS Screen Recording blocks a window picture, and stop picturing the wrong window (#1025)

adamsardo1a694a9d2d58
diff --git a/Cargo.lock b/Cargo.lock
index 24ac32f0..62f33728 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1332,6 +1332,7 @@ dependencies = [
"hex",
"log",
"nix 0.31.3",
+ "objc2-core-graphics",
"portable-pty",
"process-wrap",
"serde",
diff --git a/crates/engine/src/tools/window_tools.rs b/crates/engine/src/tools/window_tools.rs
index 5075e047..7c45fb89 100644
--- a/crates/engine/src/tools/window_tools.rs
+++ b/crates/engine/src/tools/window_tools.rs
@@ -16,6 +16,11 @@ mod process_tree;
/// Largest picture kept inline in the evidence (bigger ones are only written to `output`).
const MAX_INLINE: usize = 8 * 1024 * 1024;
+/// How much longer to look past `wait_secs` for a window that isn't there yet: a busy computer can
+/// make any program late, and one look decides nothing.
+const LATE_WINDOW: Duration = Duration::from_secs(10);
+/// Pause between those looks.
+const LOOK_AGAIN: Duration = Duration::from_millis(250);
/// Most UI elements saved to `ui_tree`.
const UI_TREE_NODES: usize = 1000;
@@ -75,6 +80,7 @@ fn native_window_capture(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,
if !craft_anything_platform::window::SUPPORTED {
return Err(craft_anything_platform::window::unsupported());
}
+ craft_anything_platform::window::check_can_see_windows()?;
let wait = Duration::from_secs(p.wait_secs.unwrap_or(8).clamp(1, 120));
let dir = p.working_directory.unwrap_or_else(|| p.program.parent().map(PathBuf::from).unwrap_or_default());
let cancel = ctx.cancel.clone();
@@ -99,15 +105,23 @@ fn native_window_capture(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,
std::thread::sleep(Duration::from_millis(200));
}
let name = p.program.file_stem().map(|s| s.to_string_lossy().into_owned());
- let shot = process_tree::capture(
- running.pid(),
- || process_tree::snapshot(&ctx.cancel),
- |pid| {
- if ctx.cancel.is_cancelled() {
- return Err(ToolError::cancelled());
- }
- craft_anything_platform::window::capture_window(pid, None)
+ let pid = running.pid();
+ let late_until = Instant::now() + LATE_WINDOW;
+ let shot = process_tree::keep_looking(
+ || {
+ process_tree::capture(
+ pid,
+ || process_tree::snapshot(&ctx.cancel),
+ |pid| {
+ if ctx.cancel.is_cancelled() {
+ return Err(ToolError::cancelled());
+ }
+ craft_anything_platform::window::capture_window(pid, None)
+ },
+ )
},
+ || Instant::now() < late_until && !ctx.cancel.is_cancelled() && !running.is_finished(),
+ LOOK_AGAIN,
)
// A launcher hands over to a program that isn't its child: last, its name finds the window.
.or_else(|e| match e.code {
diff --git a/crates/engine/src/tools/window_tools/process_tree.rs b/crates/engine/src/tools/window_tools/process_tree.rs
index 4bb3f122..51304da0 100644
--- a/crates/engine/src/tools/window_tools/process_tree.rs
+++ b/crates/engine/src/tools/window_tools/process_tree.rs
@@ -86,10 +86,59 @@ pub(super) fn capture<T>(
Err(missing)
}
+/// Look until something other than "no window yet" comes back, or `can_wait` says to stop.
+pub(super) fn keep_looking<T>(mut look: impl FnMut() -> Result<T, ToolError>, mut can_wait: impl FnMut() -> bool, pause: Duration) -> Result<T, ToolError> {
+ loop {
+ match look() {
+ Err(e) if e.code == ErrorCode::NotFound && can_wait() => std::thread::sleep(pause),
+ done => return done,
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn a_late_window_is_waited_for_but_not_forever_and_other_errors_end_it() {
+ let mut looks = 0;
+ let found = keep_looking(
+ || {
+ looks += 1;
+ if looks < 3 { Err(missing()) } else { Ok("picture") }
+ },
+ || true,
+ Duration::ZERO,
+ );
+ assert_eq!(found.unwrap(), "picture");
+ assert_eq!(looks, 3);
+
+ let mut waits = 0;
+ let gave_up = keep_looking::<()>(
+ || Err(missing()),
+ || {
+ waits += 1;
+ waits < 3
+ },
+ Duration::ZERO,
+ );
+ assert_eq!(gave_up.unwrap_err().code, ErrorCode::NotFound);
+ assert_eq!(waits, 3);
+
+ let mut looks = 0;
+ let denied = keep_looking::<()>(
+ || {
+ looks += 1;
+ Err(ToolError::new(ErrorCode::ProgramFailed, "denied"))
+ },
+ || true,
+ Duration::ZERO,
+ );
+ assert_eq!(denied.unwrap_err().message, "denied");
+ assert_eq!(looks, 1, "only a missing window is worth another look");
+ }
+
fn missing() -> ToolError {
ToolError::new(ErrorCode::NotFound, "No window")
}
diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml
index f12d6fd1..875719fe 100644
--- a/crates/platform/Cargo.toml
+++ b/crates/platform/Cargo.toml
@@ -26,6 +26,10 @@ vt100 = "0.16"
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
xcap = "0.9"
+# Whether Screen Recording is allowed (a safe call; xcap uses the same crate).
+[target.'cfg(target_os = "macos")'.dependencies]
+objc2-core-graphics = "0.3"
+
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31", default-features = false, features = ["signal", "process"] }
diff --git a/crates/platform/src/window.rs b/crates/platform/src/window.rs
index b85dc8bf..60606dca 100644
--- a/crates/platform/src/window.rs
+++ b/crates/platform/src/window.rs
@@ -23,6 +23,43 @@ pub struct WindowShot {
pub rgba: Vec<u8>,
}
+/// Whether this app may see other programs' windows. Without Screen Recording, macOS hides window
+/// names and the capture library skips those windows, so a program that opened one looks as if it
+/// hadn't. Ask before starting a program: nothing can be pictured, and starting it can have effects.
+pub fn check_can_see_windows() -> Result<(), ToolError> {
+ #[cfg(target_os = "macos")]
+ return permission_result(objc2_core_graphics::CGPreflightScreenCaptureAccess());
+ #[cfg(not(target_os = "macos"))]
+ Ok(())
+}
+
+#[cfg(target_os = "macos")]
+fn permission_result(allowed: bool) -> Result<(), ToolError> {
+ if allowed {
+ return Ok(());
+ }
+ Err(ToolError::new(ErrorCode::NoPermission, "The program wasn't started: this app can't see windows without Screen Recording permission.")
+ .with_remediation(
+ "Allow the app running Craft Anything in System Settings → Privacy & Security → Screen Recording, restart that app, then run this again.",
+ ))
+}
+
+/// Whether a window's owner is the program called `want` (lowercase): the name on its own or as
+/// whole words, so `win` never finds "Window Server". The system's own windows are never the
+/// program's, whatever it's called.
+#[cfg(any(windows, target_os = "macos"))]
+fn is_named(owner: &str, want: &str) -> bool {
+ let owner = owner.to_ascii_lowercase();
+ if want.is_empty() || owner == "window server" {
+ return false;
+ }
+ owner.match_indices(want).any(|(at, _)| {
+ let before = owner[..at].chars().next_back();
+ let after = owner[at + want.len()..].chars().next();
+ !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
+ })
+}
+
/// Picture the largest visible window that belongs to `pid`, or (when none does, as with a
/// launcher that starts the real program) to a process whose name matches `app_name`.
#[cfg(any(windows, target_os = "macos"))]
@@ -33,7 +70,7 @@ pub fn capture_window(pid: u32, app_name: Option<&str>) -> Result<WindowShot, To
let by_pid = windows.iter().filter(|w| usable(w) && w.pid().ok() == Some(pid)).max_by_key(|w| area(w));
let chosen = by_pid.or_else(|| {
let want = app_name?.to_ascii_lowercase();
- windows.iter().filter(|w| usable(w) && w.app_name().is_ok_and(|n| n.to_ascii_lowercase().contains(&want))).max_by_key(|w| area(w))
+ windows.iter().filter(|w| usable(w) && w.app_name().is_ok_and(|n| is_named(&n, &want))).max_by_key(|w| area(w))
});
let Some(w) = chosen else {
return Err(ToolError::new(ErrorCode::NotFound, "The program didn't show a window to picture.")
@@ -54,3 +91,30 @@ pub fn capture_window(pid: u32, app_name: Option<&str>) -> Result<WindowShot, To
pub fn capture_window(_pid: u32, _app_name: Option<&str>) -> Result<WindowShot, ToolError> {
Err(unsupported())
}
+
+#[cfg(all(test, any(windows, target_os = "macos")))]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_name_matches_whole_words_and_never_the_system() {
+ assert!(is_named("Game", "game"));
+ assert!(is_named("Game Launcher", "game"));
+ assert!(is_named("game.exe", "game"));
+ assert!(is_named("My Game Client", "my game"));
+ assert!(!is_named("Window Server", "win"), "the menu bar was pictured as a program called win");
+ assert!(!is_named("Window Server", "window"));
+ assert!(!is_named("Trunk", "run"));
+ assert!(!is_named("Game", ""));
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn a_missing_permission_says_where_to_allow_it() {
+ assert!(permission_result(true).is_ok());
+ let e = permission_result(false).unwrap_err();
+ assert_eq!(e.code, ErrorCode::NoPermission);
+ assert!(e.message.contains("wasn't started"));
+ assert!(e.remediation.as_deref().is_some_and(|r| r.contains("Screen Recording")), "{e:?}");
+ }
+}
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index e1194c82..2a09294e 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -740,6 +740,13 @@ Owner: open · Status: in progress
### R2.4 Runtime study for apps and games (with consent)
Owner: maintainers · Status: in progress
- [ ] UI tree on Linux (AT-SPI)
+- [x] `native_window_capture` on macOS: no Screen Recording is refused before the program starts
+ (it was "didn't show a window", which said to wait longer), and the name fallback matches
+ whole words and never the system, so `win` no longer pictures the menu bar
+- [x] `native_window_capture` keeps looking for up to 10 s past `wait_secs` when no window is there
+ yet, instead of deciding from one look; tried with a program that opens its window late
+- [ ] Close a pictured program politely before killing it: a helper it started through launchd
+ outlives the process group, and can stay running with the program's data files open
- [x] `apple_calls_observe`: the breakpoint callback is one valid line (it had a literal backslash
and `n` between statements, so lldb stopped before launching, #251), covers every breakpoint
instead of only the first, a failed lldb run is an error and not "0 calls", and names or