1use crate::windowing::registry::{
2 self, COSMIC_WAYLAND_BACKEND, GNOME_SHELL_EXTENSION_BACKEND, GNOME_SHELL_INTROSPECT_BACKEND,
3 HYPRLAND_BACKEND, I3_BACKEND, KWIN_BACKEND, LABWC_BACKEND, NIRI_BACKEND, UMBRIEL_BACKEND,
4 WLR_FOREIGN_TOPLEVEL_BACKEND, X11_BACKEND,
5};
6use crate::ydotool;
7use schemars::JsonSchema;
8use serde::Serialize;
9use std::{
10 collections::{BTreeMap, HashMap},
11 env, fs,
12 fs::OpenOptions,
13 os::unix::fs::MetadataExt,
14 path::{Path, PathBuf},
15 process::Command,
16 sync::Mutex,
17};
18
19const DESKTOP_ENV_KEYS: &[&str] = &[
20 "DBUS_SESSION_BUS_ADDRESS",
21 "DESKTOP_SESSION",
22 "DISPLAY",
23 "HYPRLAND_INSTANCE_SIGNATURE",
24 "NIRI_SOCKET",
25 "UMBRIEL_SOCKET",
26 "XAUTHORITY",
27 "YDOTOOL_SOCKET",
28 "XDG_SESSION_DESKTOP",
29 "WAYLAND_DISPLAY",
30 "XDG_CURRENT_DESKTOP",
31 "XDG_RUNTIME_DIR",
32 "XDG_SESSION_TYPE",
33];
34const FORCE_YDOTOOL_KEYBOARD_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_YDOTOOL_KEYBOARD"];
35const FORCE_YDOTOOL_POINTER_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_YDOTOOL_POINTER"];
36const FORCE_XDOTOOL_KEYBOARD_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_XDOTOOL_KEYBOARD"];
37const FORCE_PORTAL_KEYBOARD_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_PORTAL_KEYBOARD"];
38const FORCE_PORTAL_POINTER_ENV_KEYS: &[&str] = &["COMPUTER_USE_LINUX_FORCE_PORTAL_POINTER"];
39const PORTAL_DEVICE_KEYBOARD: u32 = 1;
40const PORTAL_DEVICE_POINTER: u32 = 2;
41const PORTAL_SOURCE_MONITOR: u32 = 1;
42const SCREENCAST_CURSOR_MODE_VERSION: u32 = 2;
44const REMOTE_DESKTOP_KEYBOARD_METHODS: &[&str] = &[
45 "CreateSession",
46 "SelectDevices",
47 "Start",
48 "NotifyKeyboardKeycode",
49 "NotifyKeyboardKeysym",
50];
51const REMOTE_DESKTOP_POINTER_METHODS: &[&str] = &[
52 "CreateSession",
53 "SelectDevices",
54 "Start",
55 "NotifyPointerMotionAbsolute",
56 "NotifyPointerButton",
57 "NotifyPointerAxisDiscrete",
58];
59const SCREENCAST_POINTER_METHODS: &[&str] = &["SelectSources"];
60const SCREENSHOT_PORTAL_METHODS: &[&str] = &["Screenshot"];
64const SCREENCAST_PORTAL_METHODS: &[&str] = &["CreateSession", "SelectSources", "Start"];
65const INPUT_CAPTURE_PORTAL_METHODS: &[&str] = &["GetZones", "Enable", "ConnectToEIS"];
66
67#[derive(Debug, Clone, Serialize, JsonSchema)]
68pub struct DoctorReport {
69 pub platform: PlatformReport,
70 pub portals: PortalReport,
71 pub accessibility: AccessibilityReport,
72 pub windowing: WindowingReport,
73 pub input: InputReport,
74 pub readiness: ReadinessReport,
75 pub capabilities: CapabilityMap,
79}
80
81#[derive(Debug, Clone, Serialize, JsonSchema)]
82pub struct CapabilityMap {
83 pub input: Vec<String>,
85 pub screenshot: Vec<String>,
87 pub window_control: Vec<String>,
89 pub accessibility: Vec<String>,
91 pub isolation: Vec<String>,
93 pub preferred: PreferredBackends,
95}
96
97#[derive(Debug, Clone, Serialize, JsonSchema)]
98pub struct PreferredBackends {
99 pub input: Option<String>,
100 pub screenshot: Option<String>,
101 pub window_control: Option<String>,
102}
103
104#[derive(Debug, Clone, Serialize, JsonSchema)]
105pub struct PlatformReport {
106 pub os: String,
107 pub arch: String,
108 pub desktop_session: Option<String>,
109 pub xdg_session_type: Option<String>,
110 pub xdg_current_desktop: Option<String>,
111 pub wayland_display: Option<String>,
112 pub display: Option<String>,
113 pub xauthority: Option<String>,
114 pub dbus_session_bus_address: Option<String>,
115 pub xdg_runtime_dir: Option<String>,
116 pub gnome_shell_version: Check,
117 pub gnome_screenshot: Check,
118 pub x11_display: Check,
121}
122
123#[derive(Debug, Clone, Serialize, JsonSchema)]
124pub struct PortalReport {
125 pub desktop_portal: Check,
126 pub remote_desktop: Check,
127 pub remote_desktop_keyboard: Check,
128 pub screencast: Check,
129 pub screenshot: Check,
130 pub input_capture: Check,
131 pub mutter_remote_desktop: Check,
132 pub mutter_screencast: Check,
133}
134
135#[derive(Debug, Clone, Serialize, JsonSchema)]
136pub struct AccessibilityReport {
137 pub at_spi_bus: Check,
138 pub toolkit_accessibility: Check,
139 pub at_spi_enabled: Check,
140 pub screen_reader_enabled: Check,
141 pub forced_toolkit_bridge: bool,
142}
143
144#[derive(Debug, Clone, Serialize, JsonSchema)]
145pub struct WindowingReport {
146 pub gnome_shell_introspect: Check,
147 pub computer_use_linux_gnome_shell_extension: Check,
148 pub cosmic_helper: Check,
149 pub kwin: Check,
150 pub hyprland: Check,
151 pub niri: Check,
152 pub backends: BTreeMap<String, Check>,
153 pub can_list_windows: bool,
154 pub can_focus_apps: bool,
155 pub can_focus_windows: bool,
156 pub note: String,
157}
158
159#[derive(Debug, Clone, Serialize, JsonSchema)]
160pub struct InputReport {
161 pub ydotool: Check,
162 pub ydotoold: Check,
163 pub ydotool_socket: Check,
164 pub uinput: Check,
165 pub xdotool: Check,
168 pub wtype: Check,
170 pub pixelflux: Check,
172}
173
174#[derive(Debug, Clone, Serialize, JsonSchema)]
175pub struct ReadinessReport {
176 pub can_register_mcp_tools: bool,
177 pub can_build_accessibility_tree: bool,
178 pub can_query_windows: bool,
179 pub can_focus_apps: bool,
180 pub can_focus_windows: bool,
181 pub can_send_development_input: bool,
182 pub can_capture_screenshots: bool,
185 pub screenshot_capture_status: ScreenshotCaptureStatus,
186 pub recommended_next_step: String,
187 pub blockers: Vec<String>,
188 pub warnings: Vec<String>,
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
193#[serde(rename_all = "snake_case")]
194pub enum ScreenshotCaptureStatus {
195 Unavailable,
197 Unverified,
199 Verified,
201 Failed,
203}
204
205const SCREENSHOT_UNAVAILABLE: &str = "No screenshot route was detected: GNOME Shell is absent, the XDG portal does not export org.freedesktop.portal.Screenshot, this is not a native X11 session, and gnome-screenshot is not installed. get_app_state and screenshot return no image; element-aware actions from the accessibility tree still work.";
206const SCREENSHOT_UNVERIFIED: &str = "Screenshot routes were detected, but capture is unverified. Doctor does not take a screenshot or check screenshot consent. GNOME Shell can reject callers, and a portal may require consent for the caller's app ID. Call screenshot or get_app_state to verify capture.";
207const SCREENSHOT_MISSING_GNOME_FALLBACK: &str = "gnome-screenshot is not installed. On GNOME it provides a fallback when Shell or portal calls are denied; install it or inspect the desktop portal logs and screenshot permissions for the actual caller.";
208const SCREENSHOT_FAILED: &str = "Screenshot capture failed for this request. Inspect screenshot_error for the full backend errors; accessibility-tree actions still work.";
209const SCREENSHOT_FAILED_NEXT_STEP: &str = "Inspect screenshot_error and the desktop portal logs for the failed capture. On GNOME, gnome-screenshot can provide a fallback when Shell or portal calls are denied.";
210const READY_NEXT_STEP: &str = "Computer Use is ready: AT-SPI tree support, window targeting, and a Linux input backend are available.";
211
212impl ReadinessReport {
213 pub(crate) fn record_screenshot_result(&mut self, succeeded: bool) {
215 self.can_capture_screenshots = succeeded;
216 self.screenshot_capture_status = if succeeded {
217 ScreenshotCaptureStatus::Verified
218 } else {
219 ScreenshotCaptureStatus::Failed
220 };
221 self.warnings.retain(|warning| {
222 warning != SCREENSHOT_UNVERIFIED && warning != SCREENSHOT_MISSING_GNOME_FALLBACK
223 });
224 self.blockers
225 .retain(|blocker| blocker != SCREENSHOT_UNAVAILABLE && blocker != SCREENSHOT_FAILED);
226 if !succeeded {
227 self.blockers.push(SCREENSHOT_FAILED.to_string());
228 }
229 if self.can_build_accessibility_tree
230 && self.can_query_windows
231 && self.can_focus_windows
232 && self.can_send_development_input
233 {
234 self.recommended_next_step = if succeeded {
235 READY_NEXT_STEP
236 } else {
237 SCREENSHOT_FAILED_NEXT_STEP
238 }
239 .to_string();
240 }
241 }
242}
243
244#[derive(Debug, Clone, Serialize, JsonSchema)]
245pub struct SetupReport {
246 pub before: DoctorReport,
247 pub accessibility_command: Check,
248 pub after: DoctorReport,
249 pub changed_accessibility: bool,
250 pub requires_target_app_restart: bool,
251 pub message: String,
252}
253
254#[derive(Debug, Clone, Serialize, JsonSchema)]
255pub struct Check {
256 pub ok: bool,
257 pub detail: String,
258}
259
260impl Check {
261 fn ok(detail: impl Into<String>) -> Self {
262 Self {
263 ok: true,
264 detail: detail.into(),
265 }
266 }
267
268 fn fail(detail: impl Into<String>) -> Self {
269 Self {
270 ok: false,
271 detail: detail.into(),
272 }
273 }
274}
275
276pub fn doctor_report() -> DoctorReport {
277 hydrate_session_bus_env();
278
279 let platform = platform_report();
280 let portals = portal_report();
281 let accessibility = accessibility_report();
282 let windowing = windowing_report(&platform);
283 let input = input_report();
284 let readiness = readiness_report_with_portal_keyboard(
285 &platform,
286 &portals.remote_desktop_keyboard,
287 &accessibility,
288 &windowing,
289 &input,
290 !screenshot_backends(&platform, &portals, &input).is_empty(),
291 );
292
293 let capabilities = capability_map_with_portal_keyboard(
294 &platform,
295 &portals,
296 &portals.remote_desktop_keyboard,
297 &accessibility,
298 &windowing,
299 &input,
300 );
301
302 DoctorReport {
303 platform,
304 portals,
305 accessibility,
306 windowing,
307 input,
308 readiness,
309 capabilities,
310 }
311}
312
313#[cfg(test)]
316fn capability_map(
317 platform: &PlatformReport,
318 portals: &PortalReport,
319 accessibility: &AccessibilityReport,
320 windowing: &WindowingReport,
321 input: &InputReport,
322) -> CapabilityMap {
323 capability_map_with_portal_keyboard(
324 platform,
325 portals,
326 &portals.remote_desktop,
327 accessibility,
328 windowing,
329 input,
330 )
331}
332
333fn capability_map_with_portal_keyboard(
334 platform: &PlatformReport,
335 portals: &PortalReport,
336 remote_desktop_keyboard: &Check,
337 accessibility: &AccessibilityReport,
338 windowing: &WindowingReport,
339 input: &InputReport,
340) -> CapabilityMap {
341 let mut input_backends = Vec::new();
342 if input.pixelflux.ok {
343 input_backends.push("pixelflux".to_string());
344 }
345 if input.uinput.ok && platform_is_wayland(platform) && !is_cosmic_wayland_platform(platform) {
347 input_backends.push("abs_pointer".to_string());
348 }
349 let force_ydotool = env_flag_enabled_any(FORCE_YDOTOOL_KEYBOARD_ENV_KEYS);
350 let force_xdotool = env_flag_enabled_any(FORCE_XDOTOOL_KEYBOARD_ENV_KEYS);
351 let force_portal_keyboard = env_flag_enabled_any(FORCE_PORTAL_KEYBOARD_ENV_KEYS);
352 let portal_pointer_available = portal_pointer_input_available(platform, portals);
353 let portal_keyboard_available =
354 portal_keyboard_input_available(platform, remote_desktop_keyboard);
355 let portal_available = portal_pointer_available || portal_keyboard_available;
356 let portal_forced_for_all_input = portal_pointer_available
357 && portal_keyboard_available
358 && force_portal_for_all_input(
359 env_flag_enabled_any(FORCE_PORTAL_POINTER_ENV_KEYS),
360 env_flag_enabled_any(FORCE_PORTAL_KEYBOARD_ENV_KEYS),
361 env_flag_enabled_any(FORCE_YDOTOOL_POINTER_ENV_KEYS),
362 force_ydotool,
363 );
364 if should_advertise_xdotool(platform, input, force_ydotool, force_xdotool) {
365 input_backends.push("xdotool".to_string());
366 }
367 if should_advertise_wtype(
368 platform,
369 input,
370 force_ydotool,
371 force_xdotool,
372 force_portal_keyboard,
373 ) {
374 input_backends.push("wtype".to_string());
375 }
376 let portal_first = portal_forced_for_all_input
377 || (is_cosmic_wayland_platform(platform)
378 && portal_pointer_available
379 && !env_flag_enabled_any(FORCE_YDOTOOL_POINTER_ENV_KEYS));
380 if portal_available && portal_first {
381 input_backends.push("portal".to_string());
382 }
383 if input.ydotool.ok && input.ydotool_socket.ok {
384 input_backends.push("ydotool".to_string());
385 }
386 if portal_available && !portal_first {
387 input_backends.push("portal".to_string());
388 }
389
390 let screenshot_backends = screenshot_backends(platform, portals, input);
391
392 let mut window_backends = Vec::new();
393 let x11_available = windowing
394 .backends
395 .get(X11_BACKEND)
396 .is_some_and(|check| check.ok);
397 let prefer_x11_over_introspect = windowing.gnome_shell_introspect.ok
398 && x11_available
399 && registry::backend_can_exact_focus(X11_BACKEND);
400 if windowing.computer_use_linux_gnome_shell_extension.ok {
401 window_backends.push("gnome_shell_extension".to_string());
402 }
403 if prefer_x11_over_introspect {
404 window_backends.push(X11_BACKEND.to_string());
405 }
406 if windowing.gnome_shell_introspect.ok {
407 window_backends.push("gnome_introspect".to_string());
408 }
409 if windowing.cosmic_helper.ok {
410 window_backends.push("cosmic".to_string());
411 }
412 if windowing.kwin.ok {
413 window_backends.push("kwin".to_string());
414 }
415 if windowing.hyprland.ok {
416 window_backends.push("hyprland".to_string());
417 }
418 if windowing.niri.ok {
419 window_backends.push(NIRI_BACKEND.to_string());
420 }
421 for backend in [
425 UMBRIEL_BACKEND,
426 I3_BACKEND,
427 LABWC_BACKEND,
428 WLR_FOREIGN_TOPLEVEL_BACKEND,
429 ] {
430 if windowing
431 .backends
432 .get(backend)
433 .is_some_and(|check| check.ok)
434 {
435 window_backends.push(backend.to_string());
436 }
437 }
438 if x11_available && !prefer_x11_over_introspect {
439 window_backends.push(X11_BACKEND.to_string());
440 }
441
442 let mut accessibility_backends = Vec::new();
443 if can_build_accessibility_tree(accessibility) {
444 accessibility_backends.push("at_spi".to_string());
445 }
446
447 let mut isolation = vec!["shared".to_string()];
451 if platform.gnome_shell_version.ok {
452 isolation.push("headless_gnome".to_string());
453 }
454
455 let preferred = PreferredBackends {
456 input: input_backends.first().cloned(),
457 screenshot: screenshot_backends.first().cloned(),
458 window_control: window_backends.first().cloned(),
459 };
460
461 CapabilityMap {
462 input: input_backends,
463 screenshot: screenshot_backends,
464 window_control: window_backends,
465 accessibility: accessibility_backends,
466 isolation,
467 preferred,
468 }
469}
470
471pub fn hydrate_session_bus_env() {
472 static HYDRATED_ENV: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);
473 let mut hydrated = HYDRATED_ENV
474 .lock()
475 .unwrap_or_else(|error| error.into_inner());
476 let current = desktop_environment();
477 if hydrated.as_ref() == Some(¤t) {
478 return;
479 }
480 hydrate_common_command_path();
481 hydrate_desktop_env_from_process_tree();
482 let systemd_discovery_succeeded = hydrate_desktop_env_from_systemd_user();
483
484 if env_var("XDG_RUNTIME_DIR").is_none() {
485 if let Some(runtime) = xdg_runtime_dir() {
486 if runtime.exists() {
487 env::set_var("XDG_RUNTIME_DIR", runtime);
488 }
489 }
490 }
491
492 if env_var("DBUS_SESSION_BUS_ADDRESS").is_none() {
493 if let Some(runtime) = xdg_runtime_dir() {
494 let bus = runtime.join("bus");
495 if bus.exists() {
496 env::set_var(
497 "DBUS_SESSION_BUS_ADDRESS",
498 format!("unix:path={}", bus.display()),
499 );
500 }
501 }
502 }
503 let current = desktop_environment();
504 if systemd_discovery_succeeded
505 && current.contains_key("DBUS_SESSION_BUS_ADDRESS")
506 && current.contains_key("XDG_RUNTIME_DIR")
507 && current.contains_key("XDG_CURRENT_DESKTOP")
508 && current.contains_key("XDG_SESSION_TYPE")
509 && process_env_has_graphical_display(¤t)
510 {
511 *hydrated = Some(current);
512 }
513}
514
515fn desktop_environment() -> HashMap<String, String> {
516 DESKTOP_ENV_KEYS
517 .iter()
518 .copied()
519 .chain(["PATH"])
520 .filter_map(|key| env_var(key).map(|value| (key.to_string(), value)))
521 .collect()
522}
523
524fn hydrate_common_command_path() {
525 let mut entries = env::var_os("PATH")
526 .map(|path| env::split_paths(&path).collect::<Vec<_>>())
527 .unwrap_or_default();
528 for path in [
529 "/run/current-system/sw/bin",
530 "/usr/local/bin",
531 "/usr/bin",
532 "/bin",
533 ] {
534 let path = PathBuf::from(path);
535 if path.exists() && !entries.iter().any(|entry| entry == &path) {
536 entries.push(path);
537 }
538 }
539 if let Ok(path) = env::join_paths(entries) {
540 env::set_var("PATH", path);
541 }
542}
543
544fn hydrate_desktop_env_from_process_tree() {
545 for process_env in desktop_process_environments() {
546 hydrate_desktop_env_from_map(&process_env);
547
548 if DESKTOP_ENV_KEYS.iter().all(|key| env_var(key).is_some()) {
549 break;
550 }
551 }
552}
553
554fn hydrate_desktop_env_from_systemd_user() -> bool {
555 let mut command = Command::new("systemctl");
556 command.args(["--user", "show-environment"]);
557 let Ok(output) =
558 crate::command_runner::output_blocking(&mut command, "read systemd user environment")
559 else {
560 return false;
561 };
562 if !output.status.success() {
563 return false;
564 }
565 let env_map = parse_line_environment(&output.stdout);
566 hydrate_desktop_env_from_map(&env_map);
567 true
568}
569
570fn hydrate_desktop_env_from_map(process_env: &HashMap<String, String>) {
571 let current_env = DESKTOP_ENV_KEYS
572 .iter()
573 .filter_map(|key| env_var(key).map(|value| ((*key).to_string(), value)))
574 .collect();
575 for (key, value) in desktop_env_hydration_updates(¤t_env, process_env) {
576 env::set_var(key, value);
577 }
578}
579
580fn desktop_env_hydration_updates(
581 current_env: &HashMap<String, String>,
582 source_env: &HashMap<String, String>,
583) -> Vec<(&'static str, String)> {
584 let preserve_native_x11 = current_env
588 .get("XDG_SESSION_TYPE")
589 .is_some_and(|value| value.trim().eq_ignore_ascii_case("x11"))
590 && current_env
591 .get("DISPLAY")
592 .is_some_and(|value| !value.trim().is_empty())
593 && current_env
594 .get("WAYLAND_DISPLAY")
595 .is_none_or(|value| value.trim().is_empty());
596
597 DESKTOP_ENV_KEYS
598 .iter()
599 .filter_map(|key| {
600 if current_env
601 .get(*key)
602 .is_some_and(|value| !value.trim().is_empty())
603 || preserve_native_x11 && *key == "WAYLAND_DISPLAY"
604 {
605 return None;
606 }
607 source_env
608 .get(*key)
609 .filter(|value| !value.trim().is_empty())
610 .map(|value| (*key, value.clone()))
611 })
612 .collect()
613}
614
615fn desktop_process_environments() -> Vec<HashMap<String, String>> {
616 let mut environments = Vec::new();
617 let mut visited_pids = Vec::new();
618 let mut pid = parent_pid("self");
619
620 for _ in 0..8 {
621 let Some(current_pid) = pid else {
622 break;
623 };
624 if current_pid <= 1 {
625 break;
626 }
627
628 visited_pids.push(current_pid);
629 if let Some(process_env) = read_process_environ(current_pid) {
630 environments.push(process_env);
631 }
632 pid = parent_pid(¤t_pid.to_string());
633 }
634
635 if !visited_pids.contains(&1) && process_owner_matches_current_user(1) {
636 if let Some(process_env) = read_process_environ(1).filter(process_env_has_graphical_display)
637 {
638 environments.push(process_env);
639 }
640 }
641
642 environments
643}
644
645fn parent_pid(pid: &str) -> Option<u32> {
646 let status = fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
647 parse_parent_pid(&status)
648}
649
650fn parse_parent_pid(status: &str) -> Option<u32> {
651 status.lines().find_map(|line| {
652 let value = line.strip_prefix("PPid:")?.trim();
653 value.parse::<u32>().ok()
654 })
655}
656
657fn read_process_environ(pid: u32) -> Option<HashMap<String, String>> {
658 let bytes = fs::read(format!("/proc/{pid}/environ")).ok()?;
659 Some(parse_environ(&bytes))
660}
661
662fn process_owner_matches_current_user(pid: u32) -> bool {
663 let Some(current_uid) = user_id().and_then(|uid| uid.parse::<u32>().ok()) else {
664 return false;
665 };
666 fs::metadata(format!("/proc/{pid}"))
667 .ok()
668 .is_some_and(|metadata| metadata.uid() == current_uid)
669}
670
671fn process_env_has_graphical_display(process_env: &HashMap<String, String>) -> bool {
672 process_env
673 .get("DISPLAY")
674 .or_else(|| process_env.get("WAYLAND_DISPLAY"))
675 .is_some_and(|value| !value.trim().is_empty())
676}
677
678fn parse_environ(bytes: &[u8]) -> HashMap<String, String> {
679 bytes
680 .split(|byte| *byte == 0)
681 .filter_map(|entry| {
682 if entry.is_empty() {
683 return None;
684 }
685 let split = entry.iter().position(|byte| *byte == b'=')?;
686 let (key, value) = entry.split_at(split);
687 let value = &value[1..];
688 let key = std::str::from_utf8(key).ok()?.to_string();
689 let value = std::str::from_utf8(value).ok()?.to_string();
690 Some((key, value))
691 })
692 .collect()
693}
694
695fn parse_line_environment(bytes: &[u8]) -> HashMap<String, String> {
696 bytes
697 .split(|byte| *byte == b'\n')
698 .filter_map(|entry| {
699 if entry.is_empty() {
700 return None;
701 }
702 let split = entry.iter().position(|byte| *byte == b'=')?;
703 let (key, value) = entry.split_at(split);
704 let value = &value[1..];
705 let key = std::str::from_utf8(key).ok()?.to_string();
706 let value = std::str::from_utf8(value).ok()?.to_string();
707 Some((key, value))
708 })
709 .collect()
710}
711
712pub fn setup_accessibility_report() -> SetupReport {
713 hydrate_session_bus_env();
714
715 let before = doctor_report();
716 let accessibility_command =
717 enable_accessibility(&before.accessibility, command_check_with_session_bus);
718 let after = doctor_report();
719 let before_ready = before.readiness.can_build_accessibility_tree;
720 let after_ready = after.readiness.can_build_accessibility_tree;
721 let saved_before = check_detail_contains_true(&before.accessibility.toolkit_accessibility);
722 let saved_after = check_detail_contains_true(&after.accessibility.toolkit_accessibility);
723 let changed_accessibility = after_ready && saved_after && (!before_ready || !saved_before);
724 let requires_target_app_restart = changed_accessibility;
725 let message = if after_ready && !saved_after {
726 "AT-SPI is available at runtime, but toolkit-accessibility could not be verified as enabled in GSettings. Newly launched apps may have no accessibility tree. Check accessibility_command and the saved setting; other accessibility tools can change it."
727 } else if after_ready {
728 if changed_accessibility {
729 "AT-SPI accessibility is enabled. Restart already-running target apps if their AT-SPI tree is still empty."
730 } else {
731 "AT-SPI accessibility is ready."
732 }
733 } else {
734 "Could not enable AT-SPI accessibility automatically. Check the accessibility_command detail and enable org.a11y.Status IsEnabled or org.gnome.desktop.interface toolkit-accessibility manually."
735 }
736 .to_string();
737
738 SetupReport {
739 before,
740 accessibility_command,
741 after,
742 changed_accessibility,
743 requires_target_app_restart,
744 message,
745 }
746}
747
748fn enable_accessibility(
751 before: &AccessibilityReport,
752 mut run: impl FnMut(&str, &[&str]) -> Check,
753) -> Check {
754 let setting = if check_detail_contains_true(&before.toolkit_accessibility) {
755 before.toolkit_accessibility.clone()
756 } else {
757 let write = run(
758 "gsettings",
759 &[
760 "set",
761 "org.gnome.desktop.interface",
762 "toolkit-accessibility",
763 "true",
764 ],
765 );
766 let read = run(
767 "gsettings",
768 &[
769 "get",
770 "org.gnome.desktop.interface",
771 "toolkit-accessibility",
772 ],
773 );
774 if !check_detail_contains_true(&read) {
775 let runtime = run(
776 "busctl",
777 &[
778 "--user",
779 "set-property",
780 "org.a11y.Bus",
781 "/org/a11y/bus",
782 "org.a11y.Status",
783 "IsEnabled",
784 "b",
785 "true",
786 ],
787 );
788 return Check::fail(format!(
789 "Saved toolkit-accessibility was not verified: {}; write: {}; runtime fallback: {}",
790 read.detail, write.detail, runtime.detail
791 ));
792 }
793 read
794 };
795 if !can_build_accessibility_tree(before) {
796 let runtime = run(
797 "busctl",
798 &[
799 "--user",
800 "set-property",
801 "org.a11y.Bus",
802 "/org/a11y/bus",
803 "org.a11y.Status",
804 "IsEnabled",
805 "b",
806 "true",
807 ],
808 );
809 return Check::ok(format!(
810 "Saved toolkit-accessibility verified: {}; runtime request: {}",
811 setting.detail, runtime.detail
812 ));
813 }
814 Check::ok("Saved toolkit-accessibility is enabled; runtime AT-SPI is available")
815}
816
817fn platform_report() -> PlatformReport {
818 PlatformReport {
819 os: std::env::consts::OS.to_string(),
820 arch: std::env::consts::ARCH.to_string(),
821 desktop_session: env_var("DESKTOP_SESSION"),
822 xdg_session_type: env_var("XDG_SESSION_TYPE"),
823 xdg_current_desktop: env_var("XDG_CURRENT_DESKTOP"),
824 wayland_display: env_var("WAYLAND_DISPLAY"),
825 display: env_var("DISPLAY"),
826 xauthority: env_var("XAUTHORITY"),
827 dbus_session_bus_address: dbus_session_address(),
828 xdg_runtime_dir: xdg_runtime_dir().map(|path| path.display().to_string()),
829 gnome_shell_version: command_check("gnome-shell", &["--version"]),
830 gnome_screenshot: command_check("gnome-screenshot", &["--version"]),
831 x11_display: x11_display_check(),
832 }
833}
834
835fn x11_display_check() -> Check {
836 if !crate::x11_display::is_native_x11_session() {
837 return Check::fail("not a native X11 session");
838 }
839 match crate::x11_display::X11Display::connect().map(|display| display.describe()) {
842 Ok(detail) => Check::ok(detail),
843 Err(error) => Check::fail(format!("{error:#}")),
844 }
845}
846
847fn portal_report() -> PortalReport {
848 let (remote_desktop, remote_desktop_keyboard, screencast) = remote_desktop_portal_checks();
849 PortalReport {
850 remote_desktop_keyboard,
851 desktop_portal: bus_name_check("org.freedesktop.portal.Desktop"),
852 remote_desktop,
853 screencast,
854 screenshot: portal_interface_methods_check(
855 "org.freedesktop.portal.Screenshot",
856 SCREENSHOT_PORTAL_METHODS,
857 ),
858 input_capture: portal_interface_methods_check(
859 "org.freedesktop.portal.InputCapture",
860 INPUT_CAPTURE_PORTAL_METHODS,
861 ),
862 mutter_remote_desktop: bus_name_check("org.gnome.Mutter.RemoteDesktop"),
863 mutter_screencast: bus_name_check("org.gnome.Mutter.ScreenCast"),
864 }
865}
866
867fn accessibility_report() -> AccessibilityReport {
868 AccessibilityReport {
869 at_spi_bus: atspi_bus_address_check(),
870 toolkit_accessibility: command_check_with_session_bus(
871 "gsettings",
872 &[
873 "get",
874 "org.gnome.desktop.interface",
875 "toolkit-accessibility",
876 ],
877 ),
878 at_spi_enabled: at_spi_enabled_check(),
879 screen_reader_enabled: screen_reader_enabled_check(),
880 forced_toolkit_bridge: toolkit_bridge_forced(),
881 }
882}
883
884fn windowing_report(platform: &PlatformReport) -> WindowingReport {
885 let probes = registry::probe_backends();
886 let backend_check = |id: &str| {
887 probes
888 .iter()
889 .find(|probe| probe.id == id)
890 .map(check_from_backend_probe)
891 .unwrap_or_else(|| Check::fail("backend probe did not run"))
892 };
893 let gnome_shell_introspect = backend_check(GNOME_SHELL_INTROSPECT_BACKEND);
894 let computer_use_linux_gnome_shell_extension = backend_check(GNOME_SHELL_EXTENSION_BACKEND);
895 let cosmic_helper = backend_check(COSMIC_WAYLAND_BACKEND);
896 let kwin = backend_check(KWIN_BACKEND);
897 let hyprland = backend_check(HYPRLAND_BACKEND);
898 let niri = backend_check(NIRI_BACKEND);
899 let backends = probes
900 .iter()
901 .map(|probe| (probe.id.to_string(), check_from_backend_probe(probe)))
902 .collect::<BTreeMap<_, _>>();
903 let can_list_windows = probes.iter().any(|probe| probe.can_list_windows);
904 let can_focus_apps = probes.iter().any(|probe| probe.can_focus_apps);
905 let can_focus_windows = probes.iter().any(|probe| probe.can_focus_windows);
906 let note = if can_list_windows {
907 if !can_focus_windows {
908 "A window listing backend is available for list_windows, but focused-window and targeted-input verification are unavailable (for example wmctrl is present but xprop is missing on X11)."
909 } else if cosmic_helper.ok && is_cosmic_wayland_platform(platform) {
910 "A COSMIC Wayland window backend is available for list_windows, focused_window, and targeted input verification."
911 } else if kwin.ok {
912 "A KWin/Plasma window backend is available for list_windows, focused_window, and targeted input verification."
913 } else if hyprland.ok {
914 "A Hyprland window backend is available for list_windows, focused_window, and targeted input verification."
915 } else if niri.ok {
916 "A niri window backend is available for list_windows, focused_window, and targeted input verification."
917 } else {
918 "A window listing backend is available for list_windows, focused_window, and targeted input verification."
919 }
920 } else {
921 "Window listing is unavailable or denied. Computer Use can still use screenshots, AT-SPI, and global ydotool input, but targeted window input cannot be verified. On GNOME, run setup_window_targeting to install the optional GNOME Shell extension backend. On COSMIC, ensure the bundled COSMIC helper is present and can connect to the session. On KDE/Plasma, ensure KWin exposes org.kde.KWin scripting on the session bus. On Hyprland, ensure hyprctl is available in the session. On niri, ensure the session exposes NIRI_SOCKET so the niri IPC socket is reachable. On labwc, the session socket labwc.sock lists windows. On other wlroots compositors, zwlr_foreign_toplevel_manager_v1 lists windows."
922 }
923 .to_string();
924
925 WindowingReport {
926 gnome_shell_introspect,
927 computer_use_linux_gnome_shell_extension,
928 cosmic_helper,
929 kwin,
930 hyprland,
931 niri,
932 backends,
933 can_list_windows,
934 can_focus_apps,
935 can_focus_windows,
936 note,
937 }
938}
939
940fn check_from_backend_probe(probe: ®istry::BackendProbe) -> Check {
941 if probe.ok {
942 Check::ok(probe.detail.clone())
943 } else {
944 Check::fail(probe.detail.clone())
945 }
946}
947
948fn pixelflux_check() -> Check {
949 let Some(config) = crate::pixelflux::PixelfluxConfig::from_env() else {
950 return Check::fail("PIXELFLUX_CU is not set");
951 };
952 let port = config.port;
953 let probed = std::thread::spawn(move || {
954 let runtime = tokio::runtime::Builder::new_current_thread()
955 .enable_all()
956 .build()
957 .ok()?;
958 runtime.block_on(crate::pixelflux::probe(&config)).ok()
959 })
960 .join();
961 match probed {
962 Ok(Some(())) => Check::ok(port.to_string()),
963 _ => Check::fail(format!("{port} unreachable")),
964 }
965}
966
967fn input_report() -> InputReport {
968 InputReport {
969 ydotool: match ydotool::ensure_supported() {
970 Ok(support) => Check::ok(support.detail),
971 Err(detail) => Check::fail(detail),
972 },
973 ydotoold: process_check("ydotoold"),
974 ydotool_socket: ydotool_socket_check(),
975 uinput: read_write_path_check(Path::new("/dev/uinput")),
976 xdotool: command_path_check("xdotool"),
977 wtype: command_path_check("wtype"),
978 pixelflux: pixelflux_check(),
979 }
980}
981
982#[cfg(test)]
983fn readiness_report(
984 platform: &PlatformReport,
985 portals: &PortalReport,
986 accessibility: &AccessibilityReport,
987 windowing: &WindowingReport,
988 input: &InputReport,
989) -> ReadinessReport {
990 readiness_report_with_portal_keyboard(
991 platform,
992 &portals.remote_desktop,
993 accessibility,
994 windowing,
995 input,
996 !screenshot_backends(platform, portals, input).is_empty(),
997 )
998}
999
1000fn screenshot_backends(
1003 platform: &PlatformReport,
1004 portals: &PortalReport,
1005 input: &InputReport,
1006) -> Vec<String> {
1007 let mut backends = Vec::new();
1008 if input.pixelflux.ok {
1009 backends.push("pixelflux".to_string());
1010 }
1011 if platform.gnome_shell_version.ok {
1012 backends.push("gnome_shell".to_string());
1013 }
1014 if portals.screenshot.ok {
1015 backends.push("portal".to_string());
1016 }
1017 if platform.x11_display.ok {
1018 backends.push("x11".to_string());
1019 }
1020 if platform.gnome_screenshot.ok {
1022 backends.push("gnome_screenshot".to_string());
1023 }
1024 backends
1025}
1026
1027fn readiness_report_with_portal_keyboard(
1028 platform: &PlatformReport,
1029 remote_desktop_keyboard: &Check,
1030 accessibility: &AccessibilityReport,
1031 windowing: &WindowingReport,
1032 input: &InputReport,
1033 screenshot_routes_detected: bool,
1034) -> ReadinessReport {
1035 let mut blockers = Vec::new();
1036 let mut warnings = Vec::new();
1037 let can_build_accessibility_tree = can_build_accessibility_tree(accessibility);
1038 let can_query_windows = windowing.can_list_windows;
1039 let can_focus_apps = windowing.can_focus_apps;
1040 let can_focus_windows = windowing.can_focus_windows;
1041 let can_send_development_input =
1042 can_send_development_input(platform, remote_desktop_keyboard, input);
1043
1044 if let Some(blocker) =
1045 atspi_disabled_blocker(accessibility, accessibility.forced_toolkit_bridge)
1046 {
1047 blockers.push(blocker);
1048 }
1049
1050 if !can_query_windows {
1051 blockers.push(if is_cosmic_wayland_platform(platform) {
1052 "COSMIC Wayland window introspection is unavailable; targeted window focus and verification will be disabled.".to_string()
1053 } else {
1054 "Window introspection is unavailable; targeted window focus and verification will be disabled."
1055 .to_string()
1056 });
1057 }
1058
1059 if can_query_windows && !can_focus_windows {
1060 blockers.push(
1061 "Exact window activation is unavailable; app-level focus may work, but window_id/title/terminal-targeted input cannot be verified."
1062 .to_string(),
1063 );
1064 }
1065
1066 if !can_send_development_input {
1067 blockers.push(
1068 "Development keyboard input is unavailable; enable XDG RemoteDesktop portal input or install wtype on compatible Wayland compositors, install xdotool with DISPLAY on X11, or use ydotool with a connectable ydotoold socket. Read/write /dev/uinput alone provides only absolute pointer input."
1069 .to_string(),
1070 );
1071 }
1072
1073 if screenshot_routes_detected {
1074 warnings.push(SCREENSHOT_UNVERIFIED.to_string());
1075 if platform.gnome_shell_version.ok && !platform.gnome_screenshot.ok {
1076 warnings.push(SCREENSHOT_MISSING_GNOME_FALLBACK.to_string());
1077 }
1078 } else {
1079 blockers.push(SCREENSHOT_UNAVAILABLE.to_string());
1080 }
1081
1082 let recommended_next_step = if !can_build_accessibility_tree {
1083 "Run setup_accessibility to enable AT-SPI accessibility before element-aware actions."
1084 .to_string()
1085 } else if !can_query_windows {
1086 format!(
1087 "Enable a supported window backend before using targeted keyboard input: {}",
1088 registry::descriptors()
1089 .iter()
1090 .map(|descriptor| descriptor.missing_hint)
1091 .collect::<Vec<_>>()
1092 .join(" ")
1093 )
1094 } else if !can_focus_windows {
1095 "Enable an exact-focus window backend before using window_id, title, or terminal-targeted input.".to_string()
1096 } else if !can_send_development_input {
1097 "Enable a keyboard-capable input backend: enable the XDG RemoteDesktop portal or install wtype on compatible Wayland compositors, install xdotool for X11, or start ydotoold with a socket accessible to this desktop user."
1098 .to_string()
1099 } else if !screenshot_routes_detected {
1100 "Enable a screenshot route: install an XDG desktop portal backend that implements Screenshot for this desktop, or install gnome-screenshot. Accessibility-tree actions work meanwhile."
1101 .to_string()
1102 } else {
1103 "AT-SPI tree support, window targeting, and a Linux input backend are available. Call screenshot or get_app_state to verify screenshot capture."
1104 .to_string()
1105 };
1106
1107 ReadinessReport {
1108 can_register_mcp_tools: true,
1109 can_build_accessibility_tree,
1110 can_query_windows,
1111 can_focus_apps,
1112 can_focus_windows,
1113 can_send_development_input,
1114 can_capture_screenshots: false,
1115 screenshot_capture_status: if screenshot_routes_detected {
1116 ScreenshotCaptureStatus::Unverified
1117 } else {
1118 ScreenshotCaptureStatus::Unavailable
1119 },
1120 recommended_next_step,
1121 blockers,
1122 warnings,
1123 }
1124}
1125
1126fn can_send_development_input(
1127 platform: &PlatformReport,
1128 remote_desktop_keyboard: &Check,
1129 input: &InputReport,
1130) -> bool {
1131 let force_ydotool = env_flag_enabled_any(FORCE_YDOTOOL_KEYBOARD_ENV_KEYS);
1132 let force_xdotool = env_flag_enabled_any(FORCE_XDOTOOL_KEYBOARD_ENV_KEYS);
1133 input.pixelflux.ok
1134 || portal_keyboard_input_available(platform, remote_desktop_keyboard)
1135 || platform_is_wayland(platform)
1136 && wtype_compatible_wayland_desktop(platform.xdg_current_desktop.as_deref())
1137 && input.wtype.ok
1138 && !force_ydotool
1139 || should_advertise_xdotool(platform, input, force_ydotool, force_xdotool)
1140 || input.ydotool.ok && input.ydotool_socket.ok
1141}
1142
1143fn portal_pointer_input_available(platform: &PlatformReport, portals: &PortalReport) -> bool {
1144 platform_is_wayland(platform) && portals.remote_desktop.ok
1145}
1146
1147fn portal_keyboard_input_available(
1148 platform: &PlatformReport,
1149 remote_desktop_keyboard: &Check,
1150) -> bool {
1151 platform_is_wayland(platform) && remote_desktop_keyboard.ok
1152}
1153
1154fn is_cosmic_wayland_platform(platform: &PlatformReport) -> bool {
1155 platform
1156 .xdg_current_desktop
1157 .as_deref()
1158 .is_some_and(|desktop| desktop.to_ascii_lowercase().contains("cosmic"))
1159 && platform.xdg_session_type.as_deref() == Some("wayland")
1160}
1161
1162pub(crate) fn can_build_accessibility_tree_now() -> bool {
1163 hydrate_session_bus_env();
1164 let accessibility = accessibility_report();
1165 can_build_accessibility_tree(&accessibility)
1166}
1167
1168fn can_build_accessibility_tree(accessibility: &AccessibilityReport) -> bool {
1169 accessibility_tree_ready(accessibility, accessibility.forced_toolkit_bridge)
1170}
1171
1172fn accessibility_tree_ready(accessibility: &AccessibilityReport, forced_bridge: bool) -> bool {
1173 accessibility.at_spi_bus.ok
1174 && (forced_bridge
1175 || check_detail_contains_true(&accessibility.at_spi_enabled)
1176 || check_detail_contains_true(&accessibility.toolkit_accessibility))
1177}
1178
1179fn atspi_disabled_blocker(
1180 accessibility: &AccessibilityReport,
1181 forced_bridge: bool,
1182) -> Option<String> {
1183 if accessibility_tree_ready(accessibility, forced_bridge) {
1184 None
1185 } else {
1186 Some(
1187 "AT-SPI accessibility is disabled; enable org.a11y.Status IsEnabled or org.gnome.desktop.interface toolkit-accessibility for tree extraction."
1188 .to_string(),
1189 )
1190 }
1191}
1192
1193fn toolkit_bridge_forced() -> bool {
1194 if toolkit_bridge_forced_by_env(env_var) {
1195 return true;
1196 }
1197 let compositor = compositor_environ();
1198 toolkit_bridge_forced_by_env(|key| {
1199 env_var(key).or_else(|| compositor.as_ref().and_then(|vars| vars.get(key).cloned()))
1200 })
1201}
1202
1203fn toolkit_bridge_forced_by_env(vars: impl Fn(&str) -> Option<String>) -> bool {
1204 vars("QT_LINUX_ACCESSIBILITY_ALWAYS_ON").is_some_and(|value| value == "1")
1205 || vars("GTK_MODULES").is_some_and(|value| value.contains("atk-bridge"))
1206}
1207
1208fn compositor_environ() -> Option<HashMap<String, String>> {
1209 let pid = crate::windowing::wayland_session::compositor_pid()?;
1212 read_process_environ(pid)
1213}
1214
1215fn check_detail_contains_true(check: &Check) -> bool {
1216 check.ok && check.detail.to_ascii_lowercase().contains("true")
1217}
1218
1219fn env_var(key: &str) -> Option<String> {
1220 env::var(key).ok().filter(|value| !value.trim().is_empty())
1221}
1222
1223fn xdg_runtime_dir() -> Option<PathBuf> {
1224 if let Some(value) = env_var("XDG_RUNTIME_DIR") {
1225 return Some(PathBuf::from(value));
1226 }
1227 user_id().map(|uid| PathBuf::from(format!("/run/user/{uid}")))
1228}
1229
1230fn dbus_session_address() -> Option<String> {
1231 if let Some(value) = env_var("DBUS_SESSION_BUS_ADDRESS") {
1232 return Some(value);
1233 }
1234 xdg_runtime_dir()
1235 .map(|runtime| format!("unix:path={}", runtime.join("bus").display()))
1236 .filter(|address| {
1237 address
1238 .strip_prefix("unix:path=")
1239 .is_some_and(|p| Path::new(p).exists())
1240 })
1241}
1242
1243fn ydotool_socket_check() -> Check {
1244 match ydotool::connectable_socket_path() {
1245 Ok(path) => Check::ok(format!("connectable: {}", path.display())),
1246 Err(detail) => Check::fail(format!("no trusted connectable ydotool socket ({detail})")),
1247 }
1248}
1249
1250fn user_id() -> Option<String> {
1251 let mut command = Command::new("id");
1252 command.arg("-u");
1253 let output = crate::command_runner::output_blocking(&mut command, "query user id").ok()?;
1254 output
1255 .status
1256 .success()
1257 .then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
1258 .filter(|value| !value.is_empty())
1259}
1260
1261fn command_path_check(command: &str) -> Check {
1262 command_check("sh", &["-c", &format!("command -v {command}")])
1263}
1264
1265fn platform_is_wayland(platform: &PlatformReport) -> bool {
1266 match platform.xdg_session_type.as_deref() {
1267 Some(value) => value.eq_ignore_ascii_case("wayland"),
1268 None => platform
1269 .wayland_display
1270 .as_deref()
1271 .is_some_and(|display| !display.trim().is_empty()),
1272 }
1273}
1274
1275pub(crate) fn wtype_compatible_wayland_desktop(desktop: Option<&str>) -> bool {
1276 desktop.is_none_or(|desktop| {
1277 let desktop = desktop.to_ascii_lowercase();
1278 !["gnome", "kde", "plasma", "cosmic"]
1279 .iter()
1280 .any(|known_incompatible| desktop.contains(known_incompatible))
1281 })
1282}
1283
1284fn should_advertise_wtype(
1285 platform: &PlatformReport,
1286 input: &InputReport,
1287 force_ydotool: bool,
1288 force_xdotool: bool,
1289 force_portal_keyboard: bool,
1290) -> bool {
1291 platform_is_wayland(platform)
1294 && wtype_compatible_wayland_desktop(platform.xdg_current_desktop.as_deref())
1295 && input.wtype.ok
1296 && !force_ydotool
1297 && !should_advertise_xdotool(platform, input, force_ydotool, force_xdotool)
1298 && !force_portal_keyboard
1299}
1300
1301fn should_advertise_xdotool(
1302 platform: &PlatformReport,
1303 input: &InputReport,
1304 force_ydotool: bool,
1305 force_xdotool: bool,
1306) -> bool {
1307 !force_ydotool
1308 && input.xdotool.ok
1309 && platform
1310 .display
1311 .as_deref()
1312 .is_some_and(|display| !display.trim().is_empty())
1313 && (force_xdotool || !platform_is_wayland(platform))
1314}
1315
1316fn env_flag_enabled_any(keys: &[&str]) -> bool {
1317 keys.iter()
1318 .any(|key| env::var(key).ok().as_deref() == Some("1"))
1319}
1320
1321fn force_portal_for_all_input(
1322 force_portal_pointer: bool,
1323 force_portal_keyboard: bool,
1324 force_ydotool_pointer: bool,
1325 force_ydotool_keyboard: bool,
1326) -> bool {
1327 force_portal_pointer
1328 && force_portal_keyboard
1329 && !force_ydotool_pointer
1330 && !force_ydotool_keyboard
1331}
1332
1333fn process_check(process_name: &str) -> Check {
1334 command_check("pgrep", &["-a", process_name])
1335}
1336
1337#[cfg(test)]
1338fn socket_connect_check(path: &Path) -> Check {
1339 match socket_connect_result(path) {
1340 Ok(()) => Check::ok(format!("connectable: {}", path.display())),
1341 Err(detail) => Check::fail(detail),
1342 }
1343}
1344
1345#[cfg(test)]
1346fn socket_connect_result(path: &Path) -> std::result::Result<(), String> {
1347 if !path.exists() {
1348 return Err(format!("missing: {}", path.display()));
1349 }
1350
1351 std::os::unix::net::UnixDatagram::unbound()
1352 .and_then(|socket| socket.connect(path))
1353 .map_err(|error| format!("{}: datagram: {error}", path.display()))
1354}
1355
1356fn read_write_path_check(path: &Path) -> Check {
1357 if !path.exists() {
1358 return Check::fail(format!("missing: {}", path.display()));
1359 }
1360
1361 match OpenOptions::new().read(true).write(true).open(path) {
1362 Ok(_) => Check::ok(format!("read/write: {}", path.display())),
1363 Err(error) => Check::fail(format!("{}: {error}", path.display())),
1364 }
1365}
1366
1367fn bus_name_check(name: &str) -> Check {
1368 command_check_with_session_bus("busctl", &["--user", "status", name])
1369}
1370
1371fn portal_interface_check(interface: &str) -> Check {
1372 command_check_with_session_bus(
1373 "busctl",
1374 &[
1375 "--user",
1376 "introspect",
1377 "org.freedesktop.portal.Desktop",
1378 "/org/freedesktop/portal/desktop",
1379 interface,
1380 ],
1381 )
1382}
1383
1384fn portal_interface_methods_check(interface: &str, methods: &[&str]) -> Check {
1386 require_busctl_methods(portal_interface_check(interface), interface, methods)
1387}
1388
1389fn require_busctl_methods(introspection: Check, interface: &str, methods: &[&str]) -> Check {
1390 if !introspection.ok {
1391 return introspection;
1392 }
1393 let missing = missing_busctl_methods(&introspection, methods);
1394 if missing.is_empty() {
1395 return introspection;
1396 }
1397 if !busctl_introspection_has_members(&introspection.detail) {
1398 return Check::fail(format!(
1399 "{interface} is not exported by the portal (introspection listed no members)"
1400 ));
1401 }
1402 Check::fail(format!(
1403 "{interface} is missing required methods: {}",
1404 missing.join(", ")
1405 ))
1406}
1407
1408fn busctl_introspection_has_members(detail: &str) -> bool {
1409 detail
1410 .lines()
1411 .any(|line| line.trim_start().starts_with('.'))
1412}
1413
1414fn remote_desktop_portal_checks() -> (Check, Check, Check) {
1415 let introspection = portal_interface_check("org.freedesktop.portal.RemoteDesktop");
1416 let screencast = portal_interface_methods_check(
1417 "org.freedesktop.portal.ScreenCast",
1418 SCREENCAST_PORTAL_METHODS,
1419 );
1420 if !introspection.ok {
1421 return (introspection.clone(), introspection, screencast);
1422 }
1423
1424 let available_device_types = command_check_with_session_bus(
1425 "busctl",
1426 &[
1427 "--user",
1428 "get-property",
1429 "org.freedesktop.portal.Desktop",
1430 "/org/freedesktop/portal/desktop",
1431 "org.freedesktop.portal.RemoteDesktop",
1432 "AvailableDeviceTypes",
1433 ],
1434 );
1435 let available_source_types = command_check_with_session_bus(
1436 "busctl",
1437 &[
1438 "--user",
1439 "get-property",
1440 "org.freedesktop.portal.Desktop",
1441 "/org/freedesktop/portal/desktop",
1442 "org.freedesktop.portal.ScreenCast",
1443 "AvailableSourceTypes",
1444 ],
1445 );
1446 let screencast_version = command_check_with_session_bus(
1447 "busctl",
1448 &[
1449 "--user",
1450 "get-property",
1451 "org.freedesktop.portal.Desktop",
1452 "/org/freedesktop/portal/desktop",
1453 "org.freedesktop.portal.ScreenCast",
1454 "version",
1455 ],
1456 );
1457 let available_cursor_modes = command_check_with_session_bus(
1458 "busctl",
1459 &[
1460 "--user",
1461 "get-property",
1462 "org.freedesktop.portal.Desktop",
1463 "/org/freedesktop/portal/desktop",
1464 "org.freedesktop.portal.ScreenCast",
1465 "AvailableCursorModes",
1466 ],
1467 );
1468 let pointer = remote_desktop_pointer_check_from(
1469 &introspection,
1470 &screencast,
1471 &available_device_types,
1472 &available_source_types,
1473 &screencast_version,
1474 &available_cursor_modes,
1475 );
1476 let keyboard = remote_desktop_keyboard_check_from(&introspection, &available_device_types);
1477 (pointer, keyboard, screencast)
1478}
1479
1480fn remote_desktop_pointer_check_from(
1481 introspection: &Check,
1482 screencast: &Check,
1483 available_device_types: &Check,
1484 available_source_types: &Check,
1485 screencast_version: &Check,
1486 available_cursor_modes: &Check,
1487) -> Check {
1488 if !introspection.ok {
1489 return Check::fail(introspection.detail.clone());
1490 }
1491 let missing_methods = missing_busctl_methods(introspection, REMOTE_DESKTOP_POINTER_METHODS);
1492 if !missing_methods.is_empty() {
1493 return Check::fail(format!(
1494 "RemoteDesktop interface is missing required pointer methods: {}",
1495 missing_methods.join(", ")
1496 ));
1497 }
1498
1499 if !screencast.ok {
1500 return Check::fail(format!(
1501 "ScreenCast interface is unavailable for portal pointer input: {}",
1502 screencast.detail
1503 ));
1504 }
1505 let missing_screencast_methods = missing_busctl_methods(screencast, SCREENCAST_POINTER_METHODS);
1506 if !missing_screencast_methods.is_empty() {
1507 return Check::fail(format!(
1508 "ScreenCast interface is missing required pointer methods: {}",
1509 missing_screencast_methods.join(", ")
1510 ));
1511 }
1512
1513 let device_types = match remote_desktop_device_types(available_device_types) {
1514 Ok(device_types) => device_types,
1515 Err(detail) => return Check::fail(detail),
1516 };
1517 if device_types & PORTAL_DEVICE_POINTER == 0 {
1518 return Check::fail(format!(
1519 "RemoteDesktop AvailableDeviceTypes={device_types} does not include pointer input"
1520 ));
1521 }
1522
1523 let source_types = match screencast_source_types(available_source_types) {
1524 Ok(source_types) => source_types,
1525 Err(detail) => return Check::fail(detail),
1526 };
1527 if source_types & PORTAL_SOURCE_MONITOR == 0 {
1528 return Check::fail(format!(
1529 "ScreenCast AvailableSourceTypes={source_types} does not include monitor sources"
1530 ));
1531 }
1532
1533 let version = match screencast_version_number(screencast_version) {
1534 Ok(version) => version,
1535 Err(detail) => return Check::fail(detail),
1536 };
1537 if version >= SCREENCAST_CURSOR_MODE_VERSION {
1538 let cursor_modes = match screencast_cursor_modes(available_cursor_modes) {
1539 Ok(cursor_modes) => cursor_modes,
1540 Err(detail) => return Check::fail(detail),
1541 };
1542 if cursor_modes & crate::remote_desktop::CURSOR_MODE_HIDDEN == 0 {
1543 return Check::fail(format!(
1544 "ScreenCast AvailableCursorModes={cursor_modes} does not include hidden cursor mode"
1545 ));
1546 }
1547
1548 return Check::ok(format!(
1549 "pointer-capable RemoteDesktop portal (AvailableDeviceTypes={device_types}, AvailableSourceTypes={source_types}, ScreenCast version={version}, AvailableCursorModes={cursor_modes})"
1550 ));
1551 }
1552
1553 Check::ok(format!(
1554 "pointer-capable RemoteDesktop portal (AvailableDeviceTypes={device_types}, AvailableSourceTypes={source_types}, ScreenCast version={version}, hidden cursor mode is the interface default)"
1555 ))
1556}
1557
1558fn screencast_version_number(screencast_version: &Check) -> Result<u32, String> {
1559 if !screencast_version.ok {
1560 return Err(format!(
1561 "ScreenCast version is unavailable: {}",
1562 screencast_version.detail
1563 ));
1564 }
1565 parse_busctl_u32_property(&screencast_version.detail).ok_or_else(|| {
1566 format!(
1567 "ScreenCast version has an unexpected value: {}",
1568 screencast_version.detail
1569 )
1570 })
1571}
1572
1573fn screencast_cursor_modes(available_cursor_modes: &Check) -> Result<u32, String> {
1574 if !available_cursor_modes.ok {
1575 return Err(format!(
1576 "ScreenCast AvailableCursorModes is unavailable: {}",
1577 available_cursor_modes.detail
1578 ));
1579 }
1580 parse_busctl_u32_property(&available_cursor_modes.detail).ok_or_else(|| {
1581 format!(
1582 "ScreenCast AvailableCursorModes has an unexpected value: {}",
1583 available_cursor_modes.detail
1584 )
1585 })
1586}
1587
1588fn remote_desktop_keyboard_check_from(
1589 introspection: &Check,
1590 available_device_types: &Check,
1591) -> Check {
1592 if !introspection.ok {
1593 return Check::fail(introspection.detail.clone());
1594 }
1595
1596 let missing_methods = missing_busctl_methods(introspection, REMOTE_DESKTOP_KEYBOARD_METHODS);
1597 if !missing_methods.is_empty() {
1598 return Check::fail(format!(
1599 "RemoteDesktop interface is missing required keyboard methods: {}",
1600 missing_methods.join(", ")
1601 ));
1602 }
1603
1604 let device_types = match remote_desktop_device_types(available_device_types) {
1605 Ok(device_types) => device_types,
1606 Err(detail) => return Check::fail(detail),
1607 };
1608 if device_types & PORTAL_DEVICE_KEYBOARD == 0 {
1609 return Check::fail(format!(
1610 "RemoteDesktop AvailableDeviceTypes={device_types} does not include keyboard input"
1611 ));
1612 }
1613
1614 Check::ok(format!(
1615 "keyboard-capable RemoteDesktop portal (AvailableDeviceTypes={device_types})"
1616 ))
1617}
1618
1619fn missing_busctl_methods<'a>(introspection: &Check, methods: &'a [&'a str]) -> Vec<&'a str> {
1620 methods
1621 .iter()
1622 .copied()
1623 .filter(|method| !busctl_introspection_has_method(&introspection.detail, method))
1624 .collect()
1625}
1626
1627fn remote_desktop_device_types(available_device_types: &Check) -> Result<u32, String> {
1628 if !available_device_types.ok {
1629 return Err(format!(
1630 "RemoteDesktop AvailableDeviceTypes is unavailable: {}",
1631 available_device_types.detail
1632 ));
1633 }
1634 parse_busctl_u32_property(&available_device_types.detail).ok_or_else(|| {
1635 format!(
1636 "RemoteDesktop AvailableDeviceTypes has an unexpected value: {}",
1637 available_device_types.detail
1638 )
1639 })
1640}
1641
1642fn screencast_source_types(available_source_types: &Check) -> Result<u32, String> {
1643 if !available_source_types.ok {
1644 return Err(format!(
1645 "ScreenCast AvailableSourceTypes is unavailable: {}",
1646 available_source_types.detail
1647 ));
1648 }
1649 parse_busctl_u32_property(&available_source_types.detail).ok_or_else(|| {
1650 format!(
1651 "ScreenCast AvailableSourceTypes has an unexpected value: {}",
1652 available_source_types.detail
1653 )
1654 })
1655}
1656
1657fn busctl_introspection_has_method(detail: &str, method: &str) -> bool {
1658 detail.lines().any(|line| {
1659 let mut fields = line.split_whitespace();
1660 fields
1661 .next()
1662 .is_some_and(|name| name.trim_start_matches('.') == method)
1663 && fields.next() == Some("method")
1664 })
1665}
1666
1667fn parse_busctl_u32_property(detail: &str) -> Option<u32> {
1668 let mut fields = detail.split_whitespace();
1669 if fields.next()? != "u" {
1670 return None;
1671 }
1672 let value = fields.next()?;
1673 value
1674 .strip_prefix("0x")
1675 .map(|hex| u32::from_str_radix(hex, 16).ok())
1676 .unwrap_or_else(|| value.parse().ok())
1677}
1678
1679fn atspi_bus_address_check() -> Check {
1680 let busctl = command_check_with_session_bus(
1681 "busctl",
1682 &[
1683 "--user",
1684 "call",
1685 "org.a11y.Bus",
1686 "/org/a11y/bus",
1687 "org.a11y.Bus",
1688 "GetAddress",
1689 ],
1690 );
1691 if busctl.ok {
1692 return busctl;
1693 }
1694
1695 gdbus_call_check(
1696 "org.a11y.Bus",
1697 "/org/a11y/bus",
1698 "org.a11y.Bus.GetAddress",
1699 &[],
1700 )
1701}
1702
1703fn atspi_status_property_check(property: &str) -> Check {
1704 let busctl = command_check_with_session_bus(
1705 "busctl",
1706 &[
1707 "--user",
1708 "get-property",
1709 "org.a11y.Bus",
1710 "/org/a11y/bus",
1711 "org.a11y.Status",
1712 property,
1713 ],
1714 );
1715 if busctl.ok {
1716 return busctl;
1717 }
1718
1719 gdbus_call_check(
1720 "org.a11y.Bus",
1721 "/org/a11y/bus",
1722 "org.freedesktop.DBus.Properties.Get",
1723 &["org.a11y.Status", property],
1724 )
1725}
1726
1727fn at_spi_enabled_check() -> Check {
1729 describe_bool(
1730 atspi_status_property_check("IsEnabled"),
1731 "AT-SPI IsEnabled is true",
1732 "AT-SPI IsEnabled is false",
1733 )
1734}
1735
1736fn screen_reader_enabled_check() -> Check {
1738 let mut check = atspi_status_property_check("ScreenReaderEnabled");
1739 if !check.ok {
1740 check = command_check_with_session_bus(
1741 "gsettings",
1742 &[
1743 "get",
1744 "org.gnome.desktop.a11y.applications",
1745 "screen-reader-enabled",
1746 ],
1747 );
1748 }
1749 describe_bool(check, "Screen reader is on", "Screen reader is off")
1750}
1751
1752fn describe_bool(check: Check, on: &str, off: &str) -> Check {
1754 let detail = check.detail.to_ascii_lowercase();
1755 match (check.ok, detail.contains("true"), detail.contains("false")) {
1756 (true, true, false) => Check::ok(on),
1757 (true, false, true) => Check::ok(off),
1758 _ => check,
1759 }
1760}
1761
1762fn gdbus_call_check(destination: &str, object_path: &str, method: &str, args: &[&str]) -> Check {
1763 let mut command_args = vec![
1764 "call",
1765 "--session",
1766 "--dest",
1767 destination,
1768 "--object-path",
1769 object_path,
1770 "--method",
1771 method,
1772 ];
1773 command_args.extend_from_slice(args);
1774 command_check_with_session_bus("gdbus", &command_args)
1775}
1776
1777fn command_check(command: &str, args: &[&str]) -> Check {
1778 run_command(command, args, false)
1779}
1780
1781fn command_check_with_session_bus(command: &str, args: &[&str]) -> Check {
1782 run_command(command, args, true)
1783}
1784
1785fn run_command(command: &str, args: &[&str], with_session_bus: bool) -> Check {
1786 let mut cmd = Command::new(command);
1787 cmd.args(args);
1788
1789 if with_session_bus {
1790 if let Some(address) = dbus_session_address() {
1791 cmd.env("DBUS_SESSION_BUS_ADDRESS", address);
1792 }
1793 if let Some(runtime) = xdg_runtime_dir() {
1794 cmd.env("XDG_RUNTIME_DIR", runtime);
1795 }
1796 }
1797
1798 match crate::command_runner::output_blocking(&mut cmd, &format!("run diagnostic {command}")) {
1802 Ok(output) if output.status.success() => {
1803 let detail = String::from_utf8_lossy(&output.stdout).trim().to_string();
1804 Check::ok(if detail.is_empty() {
1805 "ok".into()
1806 } else {
1807 detail
1808 })
1809 }
1810 Ok(output) => {
1811 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
1812 let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
1813 let detail = if !stderr.is_empty() { stderr } else { stdout };
1814 Check::fail(if detail.is_empty() {
1815 format!("exit status {}", output.status)
1816 } else {
1817 detail
1818 })
1819 }
1820 Err(error) => Check::fail(format!("{error:#}")),
1821 }
1822}
1823
1824#[cfg(test)]
1825pub(crate) mod tests {
1826 use super::*;
1827
1828 pub(crate) fn doctor_report_fixture(
1831 accessibility_enabled: bool,
1832 windows_available: bool,
1833 ) -> DoctorReport {
1834 let platform = platform_report();
1835 let portals = portal_report(Check::fail("missing"));
1836 let accessibility = accessibility_report(
1837 Check::ok("bus"),
1838 Check::ok(accessibility_enabled.to_string()),
1839 );
1840 let windowing = windowing_report(windows_available, windows_available);
1841 let input = input_report(true);
1842 DoctorReport {
1843 readiness: readiness_report(&platform, &portals, &accessibility, &windowing, &input),
1844 capabilities: capability_map(&platform, &portals, &accessibility, &windowing, &input),
1845 platform,
1846 portals,
1847 accessibility,
1848 windowing,
1849 input,
1850 }
1851 }
1852
1853 #[test]
1854 fn describe_bool_reads_busctl_gdbus_and_gsettings_output() {
1855 for (raw, expected) in [("b true", "on"), ("(<false>,)", "off"), ("false", "off")] {
1856 assert_eq!(describe_bool(Check::ok(raw), "on", "off").detail, expected);
1857 }
1858 let failed = describe_bool(Check::fail("no such property"), "on", "off");
1859 assert!(!failed.ok);
1860 assert_eq!(failed.detail, "no such property");
1861 }
1862
1863 #[test]
1864 fn diagnostic_command_timeout_reaps_the_hung_process() {
1865 use std::time::{Duration, Instant};
1866
1867 let pid_path = std::env::temp_dir().join(format!(
1868 "cul-diagnostic-timeout-{}-{}.pid",
1869 std::process::id(),
1870 getrandom::u64().unwrap()
1871 ));
1872 let started = Instant::now();
1873 let result = run_command(
1874 "/bin/sh",
1875 &[
1876 "-c",
1877 "printf '%s' \"$$\" > \"$1\"; exec /bin/sleep 60",
1878 "diagnostic-timeout-test",
1879 pid_path.to_str().unwrap(),
1880 ],
1881 false,
1882 );
1883 let elapsed = started.elapsed();
1884 let pid = fs::read_to_string(&pid_path);
1885 let _ = fs::remove_file(&pid_path);
1886 let pid: u32 = pid.expect("fixture must record its pid").parse().unwrap();
1887
1888 assert!(!result.ok, "hung diagnostic must fail");
1889 assert!(result.detail.contains("timed out after 2000 ms"));
1890 assert!(elapsed < Duration::from_secs(4), "took {elapsed:?}");
1891 assert!(
1892 !Path::new(&format!("/proc/{pid}")).exists(),
1893 "diagnostic child must be killed and reaped before returning"
1894 );
1895 }
1896
1897 #[test]
1898 fn diagnostic_spawn_failure_keeps_the_os_cause() {
1899 let path = std::env::temp_dir().join(format!(
1900 "cul-missing-diagnostic-{}-{}",
1901 std::process::id(),
1902 getrandom::u64().unwrap()
1903 ));
1904 let result = run_command(path.to_str().unwrap(), &[], false);
1905 assert!(!result.ok);
1906 assert!(result.detail.contains("failed to run diagnostic"));
1907 assert!(result.detail.contains("os error 2"));
1908 }
1909
1910 #[test]
1911 fn setup_repairs_saved_key_even_when_runtime_is_ready() {
1912 let mut before = accessibility_report(Check::ok("bus"), Check::ok("false"));
1913 before.at_spi_enabled = Check::ok("b true");
1914 let mut calls = Vec::new();
1915 let result = enable_accessibility(&before, |program, args| {
1916 calls.push((program.to_string(), args.join(" ")));
1917 Check::ok(if args[0] == "get" { "true" } else { "" })
1918 });
1919 assert!(result.ok);
1920 assert_eq!(
1921 calls,
1922 vec![
1923 (
1924 "gsettings".into(),
1925 "set org.gnome.desktop.interface toolkit-accessibility true".into()
1926 ),
1927 (
1928 "gsettings".into(),
1929 "get org.gnome.desktop.interface toolkit-accessibility".into()
1930 ),
1931 ]
1932 );
1933 }
1934
1935 #[test]
1936 fn setup_does_not_claim_saved_success_from_command_exit_status() {
1937 let before = accessibility_report(Check::ok("bus"), Check::ok("false"));
1938 let mut calls = Vec::new();
1939 let result = enable_accessibility(&before, |program, args| {
1940 calls.push(program.to_string());
1941 Check::ok(if args[0] == "get" {
1942 "false"
1943 } else {
1944 "exit status 0"
1945 })
1946 });
1947 assert!(!result.ok);
1948 assert!(result.detail.contains("not verified"));
1949 assert_eq!(calls, ["gsettings", "gsettings", "busctl"]);
1950 }
1951
1952 #[test]
1953 fn setup_preserves_enabled_settings_without_writing() {
1954 let before = accessibility_report(Check::ok("bus"), Check::ok("true"));
1955 let result = enable_accessibility(&before, |_, _| panic!("already enabled"));
1956 assert!(result.ok);
1957 }
1958
1959 fn platform_report() -> PlatformReport {
1960 PlatformReport {
1961 os: "linux".to_string(),
1962 arch: "x86_64".to_string(),
1963 desktop_session: None,
1964 xdg_session_type: Some("wayland".to_string()),
1965 xdg_current_desktop: Some("GNOME".to_string()),
1966 wayland_display: Some("wayland-0".to_string()),
1967 display: Some(":0".to_string()),
1968 xauthority: Some("/run/user/1000/Xauthority".to_string()),
1969 dbus_session_bus_address: Some("unix:path=/run/user/1000/bus".to_string()),
1970 xdg_runtime_dir: Some("/run/user/1000".to_string()),
1971 gnome_shell_version: Check::ok("GNOME Shell 46.0"),
1972 gnome_screenshot: Check::ok("gnome-screenshot 41.0"),
1973 x11_display: Check::fail("not a native X11 session"),
1974 }
1975 }
1976
1977 fn portal_report(remote_desktop: Check) -> PortalReport {
1978 PortalReport {
1979 remote_desktop_keyboard: remote_desktop.clone(),
1980 desktop_portal: Check::ok("ok"),
1981 remote_desktop,
1982 screencast: Check::fail("missing"),
1983 screenshot: Check::fail("missing"),
1984 input_capture: Check::fail("missing"),
1985 mutter_remote_desktop: Check::fail("missing"),
1986 mutter_screencast: Check::fail("missing"),
1987 }
1988 }
1989
1990 fn accessibility_report(
1991 at_spi_bus: Check,
1992 toolkit_accessibility: Check,
1993 ) -> AccessibilityReport {
1994 AccessibilityReport {
1995 at_spi_bus,
1996 toolkit_accessibility,
1997 at_spi_enabled: Check::fail("(<false>,)"),
1998 screen_reader_enabled: Check::fail("(<false>,)"),
1999 forced_toolkit_bridge: false,
2000 }
2001 }
2002 #[test]
2003 fn bus_reachable_and_forced_bridge_is_enabled() {
2004 let enabled = accessibility_report(Check::ok("bus"), Check::fail("false"));
2005 assert!(accessibility_tree_ready(&enabled, true));
2006 assert!(atspi_disabled_blocker(&enabled, true).is_none());
2007 let down = accessibility_report(Check::fail("no bus"), Check::fail("false"));
2008 assert!(!accessibility_tree_ready(&down, true));
2009 assert!(
2010 atspi_disabled_blocker(&down, true).is_some_and(|blocker| blocker.contains("disabled"))
2011 );
2012 assert!(toolkit_bridge_forced_by_env(|key| {
2013 (key == "QT_LINUX_ACCESSIBILITY_ALWAYS_ON").then(|| "1".to_string())
2014 }));
2015 assert!(toolkit_bridge_forced_by_env(|key| {
2016 (key == "GTK_MODULES").then(|| "gail:atk-bridge".to_string())
2017 }));
2018 assert!(!toolkit_bridge_forced_by_env(|_| None));
2019 }
2020
2021 fn windowing_report(can_list_windows: bool, can_focus_windows: bool) -> WindowingReport {
2022 WindowingReport {
2023 gnome_shell_introspect: if can_list_windows {
2024 Check::ok("ok")
2025 } else {
2026 Check::fail("denied")
2027 },
2028 computer_use_linux_gnome_shell_extension: if can_focus_windows {
2029 Check::ok("ok")
2030 } else {
2031 Check::fail("missing")
2032 },
2033 cosmic_helper: Check::fail("missing"),
2034 kwin: Check::fail("not a KWin session"),
2035 hyprland: Check::fail("not a Hyprland session"),
2036 niri: Check::fail("not a niri session"),
2037 backends: BTreeMap::new(),
2038 can_list_windows,
2039 can_focus_apps: true,
2040 can_focus_windows,
2041 note: String::new(),
2042 }
2043 }
2044
2045 fn input_report(can_send_input: bool) -> InputReport {
2046 let check = if can_send_input {
2047 Check::ok("ok")
2048 } else {
2049 Check::fail("missing")
2050 };
2051 input_report_parts(check.clone(), check.clone(), check.clone(), check)
2052 }
2053
2054 fn input_report_parts(
2055 ydotool: Check,
2056 ydotoold: Check,
2057 ydotool_socket: Check,
2058 uinput: Check,
2059 ) -> InputReport {
2060 InputReport {
2061 ydotool,
2062 ydotoold,
2063 ydotool_socket,
2064 uinput,
2065 xdotool: Check::fail("missing xdotool"),
2066 wtype: Check::fail("missing wtype"),
2067 pixelflux: Check::fail("PIXELFLUX_CU is not set"),
2068 }
2069 }
2070
2071 #[test]
2072 fn accessibility_tree_requires_reachable_at_spi_bus() {
2073 let report = accessibility_report(Check::fail("permission denied"), Check::ok("true"));
2074
2075 assert!(!can_build_accessibility_tree(&report));
2076 }
2077
2078 #[test]
2079 fn accessibility_tree_is_ready_when_bus_and_toolkit_are_ready() {
2080 let report = accessibility_report(
2081 Check::ok("('unix:path=/run/user/1000/at-spi/bus',)"),
2082 Check::ok("true"),
2083 );
2084
2085 assert!(can_build_accessibility_tree(&report));
2086 }
2087
2088 #[test]
2089 fn capability_map_advertises_only_a_buildable_accessibility_tree() {
2090 let platform = platform_report();
2091 let portals = portal_report(Check::fail("missing"));
2092 let windowing = windowing_report(false, false);
2093 let input = input_report(false);
2094
2095 for accessibility in [
2096 accessibility_report(Check::fail("permission denied"), Check::ok("true")),
2097 accessibility_report(
2098 Check::ok("('unix:path=/run/user/1000/at-spi/bus',)"),
2099 Check::ok("false"),
2100 ),
2101 ] {
2102 let capabilities =
2103 capability_map(&platform, &portals, &accessibility, &windowing, &input);
2104 assert!(capabilities.accessibility.is_empty());
2105 }
2106 }
2107
2108 #[test]
2109 fn parses_parent_pid_from_proc_status() {
2110 let status = "Name:\ttest\nPid:\t42\nPPid:\t7\n";
2111
2112 assert_eq!(parse_parent_pid(status), Some(7));
2113 }
2114
2115 #[test]
2116 fn parses_nul_separated_process_environment() {
2117 let environment = parse_environ(
2118 b"DISPLAY=:0\0WAYLAND_DISPLAY=wayland-0\0EMPTY=\0NO_EQUALS\0XDG_SESSION_TYPE=wayland\0",
2119 );
2120
2121 assert_eq!(environment.get("DISPLAY").map(String::as_str), Some(":0"));
2122 assert_eq!(
2123 environment.get("WAYLAND_DISPLAY").map(String::as_str),
2124 Some("wayland-0")
2125 );
2126 assert_eq!(environment.get("EMPTY").map(String::as_str), Some(""));
2127 assert!(!environment.contains_key("NO_EQUALS"));
2128 }
2129
2130 #[test]
2131 fn desktop_env_hydration_includes_xauthority() {
2132 assert!(DESKTOP_ENV_KEYS.contains(&"XAUTHORITY"));
2133 }
2134
2135 #[test]
2136 fn desktop_env_hydration_preserves_explicit_native_x11() {
2137 let current_env = HashMap::from([
2138 ("DISPLAY".to_string(), ":90".to_string()),
2139 ("XDG_SESSION_TYPE".to_string(), "x11".to_string()),
2140 ]);
2141 let host_env = HashMap::from([
2142 ("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string()),
2143 (
2144 "XDG_CURRENT_DESKTOP".to_string(),
2145 "ubuntu:GNOME".to_string(),
2146 ),
2147 ]);
2148
2149 let updates = desktop_env_hydration_updates(¤t_env, &host_env);
2150
2151 assert!(!updates.iter().any(|(key, _)| *key == "WAYLAND_DISPLAY"));
2152 assert!(updates
2153 .iter()
2154 .any(|(key, value)| { *key == "XDG_CURRENT_DESKTOP" && value == "ubuntu:GNOME" }));
2155 }
2156
2157 #[test]
2158 fn desktop_env_hydration_still_imports_wayland_for_incomplete_sessions() {
2159 let current_env = HashMap::new();
2160 let host_env = HashMap::from([("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string())]);
2161
2162 let updates = desktop_env_hydration_updates(¤t_env, &host_env);
2163
2164 assert!(updates
2165 .iter()
2166 .any(|(key, value)| *key == "WAYLAND_DISPLAY" && value == "wayland-0"));
2167 }
2168
2169 #[test]
2170 fn graphical_process_env_requires_display() {
2171 let with_display = HashMap::from([("DISPLAY".to_string(), ":0".to_string())]);
2172 let with_wayland =
2173 HashMap::from([("WAYLAND_DISPLAY".to_string(), "wayland-0".to_string())]);
2174 let without_display = HashMap::from([("XAUTHORITY".to_string(), "/tmp/xauth".to_string())]);
2175
2176 assert!(process_env_has_graphical_display(&with_display));
2177 assert!(process_env_has_graphical_display(&with_wayland));
2178 assert!(!process_env_has_graphical_display(&without_display));
2179 }
2180
2181 #[test]
2182 fn capabilities_prefer_xdotool_before_ydotool_on_x11() {
2183 let mut platform = platform_report();
2184 platform.xdg_session_type = Some("x11".to_string());
2185 platform.wayland_display = None;
2186 platform.display = Some(":0".to_string());
2187 let input = InputReport {
2188 ydotool: Check::ok("ydotool"),
2189 ydotoold: Check::ok("ydotoold"),
2190 ydotool_socket: Check::ok("connectable"),
2191 uinput: Check::fail("missing"),
2192 xdotool: Check::ok("xdotool"),
2193 wtype: Check::fail("missing wtype"),
2194 pixelflux: Check::fail("PIXELFLUX_CU is not set"),
2195 };
2196
2197 let capabilities = capability_map(
2198 &platform,
2199 &portal_report(Check::fail("missing")),
2200 &accessibility_report(Check::fail("missing"), Check::fail("missing")),
2201 &windowing_report(false, false),
2202 &input,
2203 );
2204
2205 assert_eq!(capabilities.input, ["xdotool", "ydotool"]);
2206 assert_eq!(capabilities.preferred.input.as_deref(), Some("xdotool"));
2207 }
2208
2209 #[test]
2210 fn pixelflux_only_desktop_is_input_ready() {
2211 let platform = platform_report();
2212 let mut input = input_report(false);
2213 input.pixelflux = Check::ok("loopback port 8080");
2214 assert!(can_send_development_input(
2215 &platform,
2216 &Check::fail("missing portal"),
2217 &input,
2218 ));
2219 }
2220
2221 #[test]
2222 fn x11_diagnostics_ignore_portal_and_accept_xdotool() {
2223 let mut platform = platform_report();
2224 platform.xdg_session_type = Some("x11".to_string());
2225 platform.wayland_display = None;
2226 platform.display = Some(":0".to_string());
2227 let portals = portal_report(Check::ok("org.freedesktop.portal.RemoteDesktop"));
2228 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2229 let windowing = windowing_report(true, true);
2230 let mut input = input_report(false);
2231 input.xdotool = Check::ok("xdotool");
2232
2233 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2234 let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2235
2236 assert_eq!(capabilities.input, ["xdotool"]);
2237 assert_eq!(capabilities.preferred.input.as_deref(), Some("xdotool"));
2238 assert!(readiness.can_send_development_input);
2239 }
2240
2241 #[test]
2242 fn wayland_diagnostics_advertise_wtype_without_portal_or_ydotool() {
2243 let mut platform = platform_report();
2244 platform.xdg_session_type = Some("wayland".to_string());
2245 platform.xdg_current_desktop = Some("Hyprland".to_string());
2246 platform.wayland_display = Some("wayland-0".to_string());
2247 let portals = portal_report(Check::fail("missing"));
2248 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2249 let windowing = windowing_report(true, true);
2250 let mut input = input_report(false);
2251 input.wtype = Check::ok("wtype");
2252
2253 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2254 let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2255
2256 assert_eq!(capabilities.input, ["wtype"]);
2257 assert_eq!(capabilities.preferred.input.as_deref(), Some("wtype"));
2258 assert!(readiness.can_send_development_input);
2259 }
2260
2261 #[test]
2262 fn wtype_excludes_known_incompatible_wayland_desktops() {
2263 assert!(wtype_compatible_wayland_desktop(Some("Hyprland")));
2264 assert!(wtype_compatible_wayland_desktop(Some("sway")));
2265 assert!(wtype_compatible_wayland_desktop(None));
2266 assert!(!wtype_compatible_wayland_desktop(Some("GNOME")));
2267 assert!(!wtype_compatible_wayland_desktop(Some("KDE;Plasma")));
2268 assert!(!wtype_compatible_wayland_desktop(Some("COSMIC")));
2269 }
2270
2271 #[test]
2272 fn wayland_diagnostics_prefer_ydotool_before_portal() {
2273 let platform = platform_report();
2274 let portals = portal_report(Check::ok("org.freedesktop.portal.RemoteDesktop"));
2275 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2276 let windowing = windowing_report(true, true);
2277 let input = input_report_parts(
2278 Check::ok("ydotool"),
2279 Check::ok("ydotoold"),
2280 Check::ok("connectable"),
2281 Check::fail("missing uinput"),
2282 );
2283
2284 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2285
2286 assert_eq!(capabilities.input, ["ydotool", "portal"]);
2287 assert_eq!(capabilities.preferred.input.as_deref(), Some("ydotool"));
2288 }
2289
2290 #[test]
2291 fn writable_uinput_advertises_abs_pointer_first() {
2292 let platform = platform_report();
2293 let portals = portal_report(Check::fail("missing"));
2294 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2295 let windowing = windowing_report(true, true);
2296 let input = input_report_parts(
2297 Check::ok("ydotool"),
2298 Check::ok("ydotoold"),
2299 Check::ok("connectable"),
2300 Check::ok("read/write: /dev/uinput"),
2301 );
2302
2303 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2304
2305 assert_eq!(capabilities.input, ["abs_pointer", "ydotool"]);
2306 }
2307
2308 #[test]
2309 fn portal_force_order_requires_both_input_modalities() {
2310 assert!(force_portal_for_all_input(true, true, false, false));
2311 assert!(!force_portal_for_all_input(true, false, false, false));
2312 assert!(!force_portal_for_all_input(true, true, true, false));
2313 assert!(!force_portal_for_all_input(true, true, false, true));
2314 }
2315
2316 fn remote_desktop_runtime_introspection() -> Check {
2317 Check::ok(
2318 "NAME TYPE SIGNATURE RESULT/VALUE FLAGS\n\
2319 .CreateSession method a{sv} o -\n\
2320 .SelectDevices method oa{sv} o -\n\
2321 .Start method osa{sv} o -\n\
2322 .NotifyPointerMotionAbsolute method oa{sv}udd - -\n\
2323 .NotifyPointerButton method oa{sv}iu - -\n\
2324 .NotifyPointerAxisDiscrete method oa{sv}ui - -\n\
2325 .NotifyKeyboardKeycode method ouu - -\n\
2326 .NotifyKeyboardKeysym method ouu - -\n\
2327 .AvailableDeviceTypes property u 3 emits-change",
2328 )
2329 }
2330
2331 fn screencast_runtime_introspection() -> Check {
2332 Check::ok(
2333 "NAME TYPE SIGNATURE RESULT/VALUE FLAGS\n\
2334 .SelectSources method oa{sv} o -",
2335 )
2336 }
2337
2338 #[test]
2339 fn cosmic_prefers_per_monitor_portal_over_uinput_and_ydotool() {
2340 let mut platform = platform_report();
2341 platform.xdg_session_type = Some("wayland".to_string());
2342 platform.xdg_current_desktop = Some("COSMIC".to_string());
2343 let input = input_report_parts(
2344 Check::ok("ydotool"),
2345 Check::ok("socket"),
2346 Check::ok("socket"),
2347 Check::ok("uinput"),
2348 );
2349 let capabilities = capability_map(
2350 &platform,
2351 &portal_report(Check::ok("portal")),
2352 &accessibility_report(Check::ok("bus"), Check::ok("true")),
2353 &windowing_report(true, true),
2354 &input,
2355 );
2356 assert_eq!(capabilities.preferred.input.as_deref(), Some("portal"));
2357 assert!(!capabilities
2358 .input
2359 .iter()
2360 .any(|backend| backend == "abs_pointer"));
2361 }
2362
2363 #[test]
2364 fn remote_desktop_portal_rejects_header_only_introspection() {
2365 let introspection = Check::ok("NAME TYPE SIGNATURE RESULT/VALUE FLAGS");
2366 let available_device_types = Check::ok("u 3");
2367 let pointer = remote_desktop_pointer_check_from(
2368 &introspection,
2369 &screencast_runtime_introspection(),
2370 &available_device_types,
2371 &Check::ok("u 1"),
2372 &Check::ok("u 2"),
2373 &Check::ok("u 2"),
2374 );
2375 let keyboard = remote_desktop_keyboard_check_from(&introspection, &available_device_types);
2376
2377 assert!(!pointer.ok);
2378 assert!(pointer.detail.contains("CreateSession"));
2379 assert!(pointer.detail.contains("NotifyPointerButton"));
2380 assert!(!keyboard.ok);
2381 assert!(keyboard.detail.contains("NotifyKeyboardKeysym"));
2382
2383 let input = input_report_parts(
2384 Check::ok("ydotool"),
2385 Check::ok("ydotoold"),
2386 Check::fail("no connectable ydotool socket"),
2387 Check::ok("read/write: /dev/uinput"),
2388 );
2389 let platform = platform_report();
2390 let portals = portal_report(pointer);
2391 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2392 let windowing = windowing_report(true, true);
2393 let capabilities = capability_map_with_portal_keyboard(
2394 &platform,
2395 &portals,
2396 &keyboard,
2397 &accessibility,
2398 &windowing,
2399 &input,
2400 );
2401 let readiness = readiness_report_with_portal_keyboard(
2402 &platform,
2403 &keyboard,
2404 &accessibility,
2405 &windowing,
2406 &input,
2407 true,
2408 );
2409
2410 assert!(!capabilities.input.iter().any(|backend| backend == "portal"));
2411 assert!(!readiness.can_send_development_input);
2412 }
2413
2414 #[test]
2415 fn keyboard_only_portal_remains_advertised_without_pointer_capability() {
2416 let platform = platform_report();
2417 let keyboard = remote_desktop_keyboard_check_from(
2418 &remote_desktop_runtime_introspection(),
2419 &Check::ok("u 1"),
2420 );
2421 let portals = portal_report(Check::fail(
2422 "ScreenCast AvailableSourceTypes=2 does not include monitor sources",
2423 ));
2424 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2425 let windowing = windowing_report(true, true);
2426 let input = input_report_parts(
2427 Check::fail("missing ydotool"),
2428 Check::fail("ydotoold not running"),
2429 Check::fail("no connectable ydotool socket"),
2430 Check::fail("/dev/uinput: Permission denied"),
2431 );
2432
2433 let capabilities = capability_map_with_portal_keyboard(
2434 &platform,
2435 &portals,
2436 &keyboard,
2437 &accessibility,
2438 &windowing,
2439 &input,
2440 );
2441 let readiness = readiness_report_with_portal_keyboard(
2442 &platform,
2443 &keyboard,
2444 &accessibility,
2445 &windowing,
2446 &input,
2447 true,
2448 );
2449
2450 assert!(!portals.remote_desktop.ok);
2451 assert_eq!(capabilities.input, ["portal"]);
2452 assert_eq!(capabilities.preferred.input.as_deref(), Some("portal"));
2453 assert!(readiness.can_send_development_input);
2454 }
2455
2456 #[test]
2457 fn remote_desktop_pointer_rejects_missing_screencast_contract() {
2458 let check = remote_desktop_pointer_check_from(
2459 &remote_desktop_runtime_introspection(),
2460 &Check::ok("NAME TYPE SIGNATURE RESULT/VALUE FLAGS"),
2461 &Check::ok("u 2"),
2462 &Check::ok("u 1"),
2463 &Check::ok("u 2"),
2464 &Check::ok("u 2"),
2465 );
2466
2467 assert!(!check.ok);
2468 assert!(check.detail.contains("SelectSources"));
2469 }
2470
2471 #[test]
2472 fn remote_desktop_pointer_rejects_missing_monitor_source_type() {
2473 let check = remote_desktop_pointer_check_from(
2474 &remote_desktop_runtime_introspection(),
2475 &screencast_runtime_introspection(),
2476 &Check::ok("u 2"),
2477 &Check::ok("u 2"),
2478 &Check::ok("u 2"),
2479 &Check::ok("u 2"),
2480 );
2481
2482 assert!(!check.ok);
2483 assert!(check.detail.contains("does not include monitor sources"));
2484 }
2485
2486 #[test]
2487 fn remote_desktop_portal_rejects_missing_keyboard_device_type() {
2488 let check = remote_desktop_keyboard_check_from(
2489 &remote_desktop_runtime_introspection(),
2490 &Check::ok("u 2"),
2491 );
2492
2493 assert!(!check.ok);
2494 assert!(check.detail.contains("does not include keyboard input"));
2495 }
2496
2497 #[test]
2498 fn remote_desktop_portal_accepts_runtime_keyboard_contract() {
2499 let check = remote_desktop_keyboard_check_from(
2500 &remote_desktop_runtime_introspection(),
2501 &Check::ok("u 3"),
2502 );
2503
2504 assert!(check.ok);
2505 assert!(check.detail.contains("AvailableDeviceTypes=3"));
2506 }
2507
2508 #[test]
2509 fn pointer_only_portal_remains_advertised_without_keyboard_readiness() {
2510 let platform = platform_report();
2511 let available_device_types = Check::ok("u 2");
2512 let pointer = remote_desktop_pointer_check_from(
2513 &remote_desktop_runtime_introspection(),
2514 &screencast_runtime_introspection(),
2515 &available_device_types,
2516 &Check::ok("u 1"),
2517 &Check::ok("u 2"),
2518 &Check::ok("u 1"),
2519 );
2520 let keyboard = remote_desktop_keyboard_check_from(
2521 &remote_desktop_runtime_introspection(),
2522 &available_device_types,
2523 );
2524 let portals = portal_report(pointer);
2525 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2526 let windowing = windowing_report(true, true);
2527 let input = input_report_parts(
2528 Check::fail("missing ydotool"),
2529 Check::fail("ydotoold not running"),
2530 Check::fail("no connectable ydotool socket"),
2531 Check::fail("/dev/uinput: Permission denied"),
2532 );
2533
2534 let capabilities = capability_map_with_portal_keyboard(
2535 &platform,
2536 &portals,
2537 &keyboard,
2538 &accessibility,
2539 &windowing,
2540 &input,
2541 );
2542 let readiness = readiness_report_with_portal_keyboard(
2543 &platform,
2544 &keyboard,
2545 &accessibility_report(Check::ok("bus"), Check::ok("true")),
2546 &windowing_report(true, true),
2547 &input,
2548 true,
2549 );
2550
2551 assert!(portals.remote_desktop.ok);
2552 assert!(capabilities.input.iter().any(|backend| backend == "portal"));
2553 assert!(!readiness.can_send_development_input);
2554 }
2555
2556 #[test]
2557 fn capabilities_require_display_to_advertise_xdotool() {
2558 let mut platform = platform_report();
2559 platform.xdg_session_type = Some("x11".to_string());
2560 platform.wayland_display = None;
2561 platform.display = None;
2562 let input = InputReport {
2563 ydotool: Check::ok("ydotool"),
2564 ydotoold: Check::ok("ydotoold"),
2565 ydotool_socket: Check::ok("connectable"),
2566 uinput: Check::fail("missing"),
2567 xdotool: Check::ok("xdotool"),
2568 wtype: Check::fail("missing wtype"),
2569 pixelflux: Check::fail("PIXELFLUX_CU is not set"),
2570 };
2571
2572 let capabilities = capability_map(
2573 &platform,
2574 &portal_report(Check::fail("missing")),
2575 &accessibility_report(Check::fail("missing"), Check::fail("missing")),
2576 &windowing_report(false, false),
2577 &input,
2578 );
2579
2580 assert_eq!(capabilities.input, ["ydotool"]);
2581 assert_eq!(capabilities.preferred.input.as_deref(), Some("ydotool"));
2582 }
2583
2584 #[test]
2585 fn xdotool_diagnostics_force_precedence_matches_runtime() {
2586 let mut platform = platform_report();
2587 platform.xdg_session_type = Some("wayland".to_string());
2588 platform.display = Some(":0".to_string());
2589 let mut input = input_report(false);
2590 input.xdotool = Check::ok("xdotool");
2591
2592 assert!(should_advertise_xdotool(&platform, &input, false, true));
2593 assert!(!should_advertise_xdotool(&platform, &input, true, true));
2594 }
2595
2596 #[test]
2597 fn parses_systemd_show_environment_output() {
2598 let environment = parse_line_environment(
2599 b"DISPLAY=:0\nHYPRLAND_INSTANCE_SIGNATURE=abc\nNO_EQUALS\nYDOTOOL_SOCKET=/run/ydotoold/socket\n",
2600 );
2601
2602 assert_eq!(environment.get("DISPLAY").map(String::as_str), Some(":0"));
2603 assert_eq!(
2604 environment
2605 .get("HYPRLAND_INSTANCE_SIGNATURE")
2606 .map(String::as_str),
2607 Some("abc")
2608 );
2609 assert_eq!(
2610 environment.get("YDOTOOL_SOCKET").map(String::as_str),
2611 Some("/run/ydotoold/socket")
2612 );
2613 assert!(!environment.contains_key("NO_EQUALS"));
2614 }
2615
2616 #[test]
2617 fn readiness_requires_exact_window_focus_for_targeted_input() {
2618 let platform = platform_report();
2619 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2620 let windowing = windowing_report(true, false);
2621 let input = input_report(true);
2622
2623 let mut readiness = readiness_report(
2624 &platform,
2625 &portal_report(Check::fail("missing")),
2626 &accessibility,
2627 &windowing,
2628 &input,
2629 );
2630
2631 readiness.record_screenshot_result(true);
2632 assert!(readiness.can_capture_screenshots);
2633
2634 assert!(readiness.can_query_windows);
2635 assert!(!readiness.can_focus_windows);
2636 assert!(readiness
2637 .recommended_next_step
2638 .contains("exact-focus window backend"));
2639 assert!(readiness
2640 .blockers
2641 .iter()
2642 .any(|blocker| blocker.contains("Exact window activation")));
2643 }
2644
2645 #[test]
2646 fn header_only_introspection_is_not_an_exported_interface() {
2647 let header_only = Check::ok("NAME TYPE SIGNATURE RESULT/VALUE FLAGS");
2649
2650 let check = require_busctl_methods(
2651 header_only,
2652 "org.freedesktop.portal.Screenshot",
2653 SCREENSHOT_PORTAL_METHODS,
2654 );
2655
2656 assert!(!check.ok);
2657 assert!(check.detail.contains("is not exported by the portal"));
2658 }
2659
2660 #[test]
2661 fn portal_interface_must_export_every_required_method() {
2662 let partial = Check::ok(
2663 "NAME TYPE SIGNATURE RESULT/VALUE FLAGS\n.PickColor method sa{sv} o -\n.version property u 2 emits-change",
2664 );
2665 let check = require_busctl_methods(
2666 partial,
2667 "org.freedesktop.portal.Screenshot",
2668 SCREENSHOT_PORTAL_METHODS,
2669 );
2670 assert!(!check.ok);
2671 assert!(check
2672 .detail
2673 .contains("missing required methods: Screenshot"));
2674
2675 let full = Check::ok(
2676 "NAME TYPE SIGNATURE RESULT/VALUE FLAGS\n.PickColor method sa{sv} o -\n.Screenshot method sa{sv} o -",
2677 );
2678 assert!(
2679 require_busctl_methods(
2680 full,
2681 "org.freedesktop.portal.Screenshot",
2682 SCREENSHOT_PORTAL_METHODS
2683 )
2684 .ok
2685 );
2686
2687 let failed = Check::fail("busctl: No such interface");
2688 let passthrough = require_busctl_methods(
2689 failed,
2690 "org.freedesktop.portal.Screenshot",
2691 SCREENSHOT_PORTAL_METHODS,
2692 );
2693 assert!(!passthrough.ok);
2694 assert_eq!(passthrough.detail, "busctl: No such interface");
2695 }
2696
2697 #[test]
2698 fn readiness_blocks_when_no_screenshot_route_is_detected() {
2699 let mut platform = platform_report();
2700 platform.gnome_shell_version = Check::fail("No such file or directory (os error 2)");
2701 platform.gnome_screenshot = Check::fail("No such file or directory (os error 2)");
2702 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2703 let windowing = windowing_report(true, true);
2704 let input = input_report(true);
2705 let portals = portal_report(Check::fail("missing"));
2706
2707 let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2708
2709 assert!(!readiness.can_capture_screenshots);
2710 assert_eq!(
2711 readiness.screenshot_capture_status,
2712 ScreenshotCaptureStatus::Unavailable
2713 );
2714 assert!(readiness.warnings.is_empty());
2715 assert!(readiness
2716 .blockers
2717 .iter()
2718 .any(|blocker| blocker.contains("No screenshot route was detected")));
2719 assert!(readiness
2720 .recommended_next_step
2721 .contains("Enable a screenshot route"));
2722 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2723 assert!(capabilities.screenshot.is_empty());
2724 assert_eq!(capabilities.preferred.screenshot, None);
2725 }
2726
2727 #[test]
2728 fn native_x11_display_is_a_screenshot_route_ahead_of_gnome_screenshot() {
2729 let mut platform = platform_report();
2730 platform.gnome_shell_version = Check::fail("missing");
2731 platform.x11_display = Check::ok("native X11 root window 2880x1920, depth 24");
2732 let portals = portal_report(Check::fail("missing"));
2733 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2734 let windowing = windowing_report(true, true);
2735 let input = input_report(true);
2736
2737 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2738 let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2739
2740 assert_eq!(capabilities.screenshot, ["x11", "gnome_screenshot"]);
2741 assert_eq!(capabilities.preferred.screenshot.as_deref(), Some("x11"));
2742 assert!(!readiness.can_capture_screenshots);
2743 assert_eq!(
2744 readiness.screenshot_capture_status,
2745 ScreenshotCaptureStatus::Unverified
2746 );
2747 assert!(readiness.blockers.is_empty());
2748 }
2749
2750 #[test]
2751 fn screenshot_route_detection_is_not_capture_verification() {
2752 let mut platform = platform_report();
2753 platform.gnome_shell_version = Check::fail("missing");
2754 platform.gnome_screenshot = Check::fail("missing");
2755 let mut portals = portal_report(Check::fail("missing"));
2756 portals.screenshot = Check::ok(".Screenshot method sa{sv} o -");
2757 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2758 let windowing = windowing_report(true, true);
2759 let input = input_report(true);
2760
2761 let mut readiness =
2762 readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2763 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2764
2765 assert!(!readiness.can_capture_screenshots);
2766 assert_eq!(
2767 readiness.screenshot_capture_status,
2768 ScreenshotCaptureStatus::Unverified
2769 );
2770 assert_eq!(readiness.warnings, [SCREENSHOT_UNVERIFIED]);
2771 assert!(readiness.blockers.is_empty());
2772 assert_eq!(capabilities.screenshot, ["portal"]);
2773
2774 readiness.record_screenshot_result(false);
2775 assert!(!readiness.can_capture_screenshots);
2776 assert_eq!(
2777 readiness.screenshot_capture_status,
2778 ScreenshotCaptureStatus::Failed
2779 );
2780 assert_eq!(readiness.blockers, [SCREENSHOT_FAILED]);
2781 assert!(readiness.warnings.is_empty());
2782 assert_eq!(readiness.recommended_next_step, SCREENSHOT_FAILED_NEXT_STEP);
2783
2784 readiness.record_screenshot_result(true);
2785 assert!(readiness.can_capture_screenshots);
2786 assert_eq!(
2787 readiness.screenshot_capture_status,
2788 ScreenshotCaptureStatus::Verified
2789 );
2790 assert!(readiness.blockers.is_empty());
2791 assert_eq!(readiness.recommended_next_step, READY_NEXT_STEP);
2792 }
2793
2794 #[test]
2795 fn readiness_treats_kwin_as_full_window_backend() {
2796 let platform = platform_report();
2797 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2798 let mut windowing = windowing_report(false, false);
2799 windowing.kwin = Check::ok("KWin scripting is available");
2800 windowing.can_list_windows = true;
2801 windowing.can_focus_apps = true;
2802 windowing.can_focus_windows = true;
2803 let input = input_report(true);
2804
2805 let readiness = readiness_report(
2806 &platform,
2807 &portal_report(Check::fail("missing")),
2808 &accessibility,
2809 &windowing,
2810 &input,
2811 );
2812
2813 assert!(readiness.can_query_windows);
2814 assert!(readiness.can_focus_apps);
2815 assert!(readiness.can_focus_windows);
2816 assert!(readiness.blockers.is_empty());
2817 }
2818
2819 #[test]
2820 fn readiness_message_mentions_generic_window_targeting() {
2821 let platform = platform_report();
2822 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2823 let windowing = windowing_report(true, true);
2824 let input = input_report(true);
2825
2826 let readiness = readiness_report(
2827 &platform,
2828 &portal_report(Check::fail("missing")),
2829 &accessibility,
2830 &windowing,
2831 &input,
2832 );
2833
2834 assert!(readiness.blockers.is_empty());
2835 assert!(readiness
2836 .recommended_next_step
2837 .contains("AT-SPI tree support"));
2838 assert!(readiness.recommended_next_step.contains("window targeting"));
2839 assert!(!readiness
2840 .recommended_next_step
2841 .contains("GNOME window targeting"));
2842 }
2843
2844 #[test]
2845 fn readiness_accepts_connectable_ydotool_socket_without_direct_uinput_access() {
2846 let platform = platform_report();
2847 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2848 let windowing = windowing_report(true, true);
2849 let input = input_report_parts(
2850 Check::ok("ydotool"),
2851 Check::ok("ydotoold"),
2852 Check::ok("connectable: /tmp/.ydotool_socket"),
2853 Check::fail("/dev/uinput: Permission denied"),
2854 );
2855
2856 let readiness = readiness_report(
2857 &platform,
2858 &portal_report(Check::fail("missing")),
2859 &accessibility,
2860 &windowing,
2861 &input,
2862 );
2863
2864 assert!(readiness.can_send_development_input);
2865 assert!(readiness.blockers.is_empty());
2866 }
2867
2868 #[test]
2869 fn readiness_uses_connectable_ydotool_socket_when_process_probe_fails() {
2870 let platform = platform_report();
2871 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2872 let windowing = windowing_report(true, true);
2873 let input = input_report_parts(
2874 Check::ok("ydotool"),
2875 Check::fail("ydotoold process name not found"),
2876 Check::ok("connectable: /run/user/1000/.ydotool_socket"),
2877 Check::fail("/dev/uinput: Permission denied"),
2878 );
2879 let portals = portal_report(Check::fail("missing"));
2880
2881 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
2882 let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
2883
2884 assert!(capabilities
2885 .input
2886 .iter()
2887 .any(|backend| backend == "ydotool"));
2888 assert!(readiness.can_send_development_input);
2889 }
2890
2891 #[test]
2892 fn wayland_readiness_rejects_pointer_only_uinput_without_keyboard_backend() {
2893 let platform = platform_report();
2894 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2895 let windowing = windowing_report(true, true);
2896 let input = input_report_parts(
2897 Check::ok("ydotool"),
2898 Check::fail("ydotoold not running"),
2899 Check::fail("no connectable ydotool socket"),
2900 Check::ok("read/write: /dev/uinput"),
2901 );
2902
2903 let readiness = readiness_report(
2904 &platform,
2905 &portal_report(Check::fail("missing")),
2906 &accessibility,
2907 &windowing,
2908 &input,
2909 );
2910
2911 assert!(!readiness.can_send_development_input);
2912 assert!(readiness
2913 .blockers
2914 .iter()
2915 .any(|blocker| blocker.contains("absolute pointer input")));
2916 assert!(readiness
2917 .recommended_next_step
2918 .contains("keyboard-capable input backend"));
2919 }
2920
2921 #[test]
2922 fn x11_readiness_rejects_pointer_only_uinput_without_keyboard_backend() {
2923 let mut platform = platform_report();
2924 platform.xdg_session_type = Some("x11".to_string());
2925 platform.wayland_display = None;
2926 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2927 let windowing = windowing_report(true, true);
2928 let input = input_report_parts(
2929 Check::fail("missing ydotool"),
2930 Check::fail("ydotoold not running"),
2931 Check::fail("no connectable ydotool socket"),
2932 Check::ok("read/write: /dev/uinput"),
2933 );
2934
2935 let readiness = readiness_report(
2936 &platform,
2937 &portal_report(Check::fail("missing")),
2938 &accessibility,
2939 &windowing,
2940 &input,
2941 );
2942
2943 assert!(!readiness.can_send_development_input);
2944 }
2945
2946 #[test]
2947 fn readiness_accepts_remote_desktop_portal_without_local_input_backend() {
2948 let platform = platform_report();
2949 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2950 let windowing = windowing_report(true, true);
2951 let input = input_report_parts(
2952 Check::fail("missing ydotool"),
2953 Check::fail("ydotoold not running"),
2954 Check::fail("no connectable ydotool socket"),
2955 Check::fail("/dev/uinput: Permission denied"),
2956 );
2957
2958 let readiness = readiness_report(
2959 &platform,
2960 &portal_report(Check::ok("org.freedesktop.portal.RemoteDesktop")),
2961 &accessibility,
2962 &windowing,
2963 &input,
2964 );
2965
2966 assert!(readiness.can_send_development_input);
2967 assert!(readiness.blockers.is_empty());
2968 }
2969
2970 #[test]
2971 fn readiness_rejects_inaccessible_ydotool_paths() {
2972 let platform = platform_report();
2973 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
2974 let windowing = windowing_report(true, true);
2975 let input = input_report_parts(
2976 Check::ok("ydotool"),
2977 Check::ok("ydotoold"),
2978 Check::fail("/tmp/.ydotool_socket: Permission denied"),
2979 Check::fail("/dev/uinput: Permission denied"),
2980 );
2981
2982 let readiness = readiness_report(
2983 &platform,
2984 &portal_report(Check::fail("missing")),
2985 &accessibility,
2986 &windowing,
2987 &input,
2988 );
2989
2990 assert!(!readiness.can_send_development_input);
2991 assert!(readiness
2992 .recommended_next_step
2993 .contains("Enable a keyboard-capable input backend"));
2994 assert!(readiness
2995 .blockers
2996 .iter()
2997 .any(|blocker| blocker.contains("Development keyboard input is unavailable")));
2998 }
2999
3000 #[test]
3001 fn capability_map_rejects_incompatible_ydotool_with_live_daemon() {
3002 let platform = platform_report();
3003 let portals = portal_report(Check::fail("missing"));
3004 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
3005 let windowing = windowing_report(true, true);
3006 let input = input_report_parts(
3007 Check::fail("unsupported legacy ydotool CLI"),
3008 Check::ok("ydotoold"),
3009 Check::ok("connectable socket"),
3010 Check::fail("/dev/uinput: Permission denied"),
3011 );
3012
3013 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
3014 let readiness = readiness_report(&platform, &portals, &accessibility, &windowing, &input);
3015
3016 assert!(!capabilities
3017 .input
3018 .iter()
3019 .any(|backend| backend == "ydotool"));
3020 assert!(!readiness.can_send_development_input);
3021 }
3022
3023 #[test]
3024 fn ydotool_socket_check_rejects_legacy_stream_socket() {
3025 let dir = crate::test_sockets::socket_fixture(
3026 &format!("cul-diag-stream-{}", std::process::id()),
3027 "ydotool.sock",
3028 );
3029 let _ = std::fs::remove_dir_all(&dir);
3030 std::fs::create_dir_all(&dir).expect("create temp diagnostics dir");
3031 let socket = dir.join("ydotool.sock");
3032 let listener =
3033 std::os::unix::net::UnixListener::bind(&socket).expect("bind temp diagnostics socket");
3034
3035 let check = socket_connect_check(&socket);
3036
3037 assert!(!check.ok, "{check:?}");
3038 drop(listener);
3039 let _ = std::fs::remove_dir_all(&dir);
3040 }
3041
3042 #[test]
3043 fn ydotool_socket_check_accepts_datagram_socket() {
3044 let dir = crate::test_sockets::socket_fixture(
3045 &format!("cul-diag-dgram-{}", std::process::id()),
3046 "ydotool.sock",
3047 );
3048 let _ = std::fs::remove_dir_all(&dir);
3049 std::fs::create_dir_all(&dir).expect("create temp diagnostics dir");
3050 let socket = dir.join("ydotool.sock");
3051 let datagram =
3052 std::os::unix::net::UnixDatagram::bind(&socket).expect("bind temp datagram socket");
3053
3054 let check = socket_connect_check(&socket);
3055
3056 assert!(check.ok, "{check:?}");
3057 drop(datagram);
3058 let _ = std::fs::remove_dir_all(&dir);
3059 }
3060
3061 #[test]
3062 fn readiness_reports_cosmic_window_blocker_on_cosmic() {
3063 let mut platform = platform_report();
3064 platform.xdg_current_desktop = Some("COSMIC".to_string());
3065 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
3066 let windowing = windowing_report(false, false);
3067 let input = input_report(true);
3068
3069 let readiness = readiness_report(
3070 &platform,
3071 &portal_report(Check::fail("missing")),
3072 &accessibility,
3073 &windowing,
3074 &input,
3075 );
3076
3077 assert!(readiness
3078 .blockers
3079 .iter()
3080 .any(|blocker| blocker.contains("COSMIC Wayland window introspection")));
3081 }
3082
3083 #[test]
3084 fn desktop_env_hydration_imports_the_niri_socket() {
3085 let current_env = HashMap::new();
3086 let session_env = HashMap::from([(
3087 "NIRI_SOCKET".to_string(),
3088 "/run/user/1000/niri.wayland-1.42.sock".to_string(),
3089 )]);
3090
3091 let updates = desktop_env_hydration_updates(¤t_env, &session_env);
3092
3093 assert!(updates.iter().any(|(key, value)| {
3094 *key == "NIRI_SOCKET" && value == "/run/user/1000/niri.wayland-1.42.sock"
3095 }));
3096 }
3097
3098 #[test]
3099 fn wtype_capability_honors_keyboard_backend_overrides() {
3100 let mut platform = platform_report();
3101 platform.xdg_session_type = Some("wayland".to_string());
3102 platform.xdg_current_desktop = Some("Hyprland".to_string());
3103 platform.wayland_display = Some("wayland-0".to_string());
3104 let mut input = input_report(false);
3105 input.wtype = Check::ok("wtype");
3106
3107 assert!(should_advertise_wtype(
3108 &platform, &input, false, false, false
3109 ));
3110 assert!(!should_advertise_wtype(
3111 &platform, &input, true, false, false
3112 ));
3113 assert!(!should_advertise_wtype(
3114 &platform, &input, false, false, true
3115 ));
3116
3117 assert!(should_advertise_wtype(
3120 &platform, &input, false, true, false
3121 ));
3122 input.xdotool = Check::ok("xdotool");
3123 assert!(!should_advertise_wtype(
3124 &platform, &input, false, true, false
3125 ));
3126 platform.display = None;
3127 assert!(should_advertise_wtype(
3128 &platform, &input, false, true, false
3129 ));
3130 }
3131
3132 #[test]
3133 fn remote_desktop_pointer_rejects_missing_hidden_cursor_mode() {
3134 let check = remote_desktop_pointer_check_from(
3135 &remote_desktop_runtime_introspection(),
3136 &screencast_runtime_introspection(),
3137 &Check::ok("u 2"),
3138 &Check::ok("u 1"),
3139 &Check::ok("u 2"),
3140 &Check::ok("u 2"),
3141 );
3142
3143 assert!(!check.ok);
3144 assert!(check.detail.contains("does not include hidden cursor mode"));
3145 }
3146
3147 #[test]
3148 fn remote_desktop_pointer_accepts_screencast_v1_default_hidden_cursor() {
3149 let check = remote_desktop_pointer_check_from(
3150 &remote_desktop_runtime_introspection(),
3151 &screencast_runtime_introspection(),
3152 &Check::ok("u 2"),
3153 &Check::ok("u 1"),
3154 &Check::ok("u 1"),
3155 &Check::fail("AvailableCursorModes is not available on ScreenCast v1"),
3156 );
3157
3158 assert!(check.ok);
3159 assert!(check
3160 .detail
3161 .contains("hidden cursor mode is the interface default"));
3162 }
3163
3164 #[test]
3165 fn capability_map_reports_niri_window_control() {
3166 let platform = platform_report();
3167 let portals = portal_report(Check::fail("missing"));
3168 let accessibility = accessibility_report(Check::ok("bus"), Check::ok("true"));
3169 let mut windowing = windowing_report(false, false);
3170 windowing.niri = Check::ok("niri msg returned windows");
3171 let input = input_report(false);
3172
3173 let capabilities = capability_map(&platform, &portals, &accessibility, &windowing, &input);
3174
3175 assert_eq!(capabilities.window_control, vec![NIRI_BACKEND]);
3176 assert_eq!(
3177 capabilities.preferred.window_control.as_deref(),
3178 Some(NIRI_BACKEND)
3179 );
3180 }
3181}