| 1 | //! Opt-in headless observation built exclusively on public GPUI APIs. |
| 2 | //! |
| 3 | //! Native accessibility properties are read automatically. Applications register |
| 4 | //! identified GPUI elements with `.test_support()`, without supplying test-only state. |
| 5 | use gpui::{ |
| 6 | App, Bounds, Element, ElementId, FocusHandle, GlobalElementId, Hitbox, InspectorElementId, |
| 7 | InteractiveElement, IntoElement, LayoutId, Pixels, SharedString, Visibility, Window, px, |
| 8 | }; |
| 9 | use std::{ |
| 10 | cell::RefCell, |
| 11 | collections::HashMap, |
| 12 | fmt, |
| 13 | rc::{Rc, Weak}, |
| 14 | }; |
| 15 | |
| 16 | /// Owned facts from the last paint of an observed element. |
| 17 | #[derive(Clone)] |
| 18 | pub struct ElementSnapshot { |
| 19 | role: Option<gpui::Role>, |
| 20 | path: Vec<ElementId>, |
| 21 | checked: Option<bool>, |
| 22 | indeterminate: Option<bool>, |
| 23 | selected: Option<bool>, |
| 24 | expanded: Option<bool>, |
| 25 | value: Option<SharedString>, |
| 26 | bounds: Bounds<Pixels>, |
| 27 | visible: bool, |
| 28 | focused: Option<bool>, |
| 29 | focus_action: bool, |
| 30 | disabled: Option<bool>, |
| 31 | label: Option<SharedString>, |
| 32 | } |
| 33 | impl fmt::Debug for ElementSnapshot { |
| 34 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 35 | struct BindingMissed; |
| 36 | impl fmt::Debug for BindingMissed { |
| 37 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 38 | f.write_str("<binding missed>") |
| 39 | } |
| 40 | } |
| 41 | let focused: &dyn fmt::Debug = if self.focused.is_none() && self.focus_action { |
| 42 | &BindingMissed |
| 43 | } else { |
| 44 | &self.focused |
| 45 | }; |
| 46 | f.debug_struct("ElementSnapshot") |
| 47 | .field("role", &self.role) |
| 48 | .field("path", &self.path) |
| 49 | .field("checked", &self.checked) |
| 50 | .field("indeterminate", &self.indeterminate) |
| 51 | .field("selected", &self.selected) |
| 52 | .field("expanded", &self.expanded) |
| 53 | .field("value", &self.value) |
| 54 | .field("bounds", &self.bounds) |
| 55 | .field("visible", &self.visible) |
| 56 | .field("focused", focused) |
| 57 | .field("focus_action", &self.focus_action) |
| 58 | .field("disabled", &self.disabled) |
| 59 | .field("label", &self.label) |
| 60 | .finish() |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | impl ElementSnapshot { |
| 65 | pub fn role(&self) -> Option<gpui::Role> { |
| 66 | self.role |
| 67 | } |
| 68 | pub fn path(&self) -> &[ElementId] { |
| 69 | &self.path |
| 70 | } |
| 71 | pub fn checked(&self) -> Option<bool> { |
| 72 | self.checked |
| 73 | } |
| 74 | pub fn indeterminate(&self) -> Option<bool> { |
| 75 | self.indeterminate |
| 76 | } |
| 77 | pub fn selected(&self) -> Option<bool> { |
| 78 | self.selected |
| 79 | } |
| 80 | pub fn expanded(&self) -> Option<bool> { |
| 81 | self.expanded |
| 82 | } |
| 83 | /// The native accessibility value, not rendered text or pixels. |
| 84 | pub fn value(&self) -> Option<&str> { |
| 85 | self.value.as_deref() |
| 86 | } |
| 87 | |
| 88 | pub fn bounds(&self) -> Bounds<Pixels> { |
| 89 | self.bounds |
| 90 | } |
| 91 | pub fn visible(&self) -> bool { |
| 92 | self.visible |
| 93 | } |
| 94 | /// Whether the tracked focus scope contains the current keyboard focus. |
| 95 | /// `None` means no focus binding or native focus capability was observed. |
| 96 | /// Panics if the native element advertises `Action::Focus` but its binding was missed. |
| 97 | /// Custom elements omitting that action cannot be diagnosed and may return `None`. |
| 98 | pub fn focused(&self) -> Option<bool> { |
| 99 | assert!( |
| 100 | self.focused.is_some() || !self.focus_action, |
| 101 | "focus binding was not observed for {:?}; use .test_support().track_focus(&handle). GPUI does not expose pre-existing or implicit focus handles", |
| 102 | self.path |
| 103 | ); |
| 104 | self.focused |
| 105 | } |
| 106 | /// `None` means the native element does not expose a disabled flag. |
| 107 | /// Absence is not evidence that a control accepts input. |
| 108 | pub fn disabled(&self) -> Option<bool> { |
| 109 | self.disabled |
| 110 | } |
| 111 | /// The accessibility label; it can intentionally differ from visible text. |
| 112 | pub fn label(&self) -> Option<&str> { |
| 113 | self.label.as_deref() |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // Each Window owns a distinct Arc<WindowTextSystem>, stable even during initial |
| 118 | // drawing before the Window itself is boxed. Its identity distinguishes equal |
| 119 | // WindowIds in different Apps. Entries never own a Window or a view. |
| 120 | type WindowKey = usize; |
| 121 | type Registry = HashMap<WindowKey, HashMap<GlobalElementId, Weak<Registration>>>; |
| 122 | thread_local! { static REGISTRY: RefCell<Registry> = RefCell::new(HashMap::new()); } |
| 123 | |
| 124 | #[doc(hidden)] |
| 125 | pub struct Registration { |
| 126 | window: WindowKey, |
| 127 | global_id: GlobalElementId, |
| 128 | facts: RefCell<ElementSnapshot>, |
| 129 | } |
| 130 | impl Drop for Registration { |
| 131 | fn drop(&mut self) { |
| 132 | let _ = REGISTRY.try_with(|registry| { |
| 133 | if let Ok(mut registry) = registry.try_borrow_mut() { |
| 134 | if let Some(entries) = registry.get_mut(&self.window) { |
| 135 | entries.remove(&self.global_id); |
| 136 | if entries.is_empty() { |
| 137 | registry.remove(&self.window); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | }); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /// Internal lookup used by Kit's testing API. Scope follows GPUI's element path. |
| 146 | #[doc(hidden)] |
| 147 | pub fn find(window: &Window, scope: &[ElementId], id: &ElementId) -> Option<ElementSnapshot> { |
| 148 | REGISTRY.with(|registry| { |
| 149 | let registry = registry.borrow(); |
| 150 | let entries = registry.get(&(std::sync::Arc::as_ptr(window.text_system()) as usize))?; |
| 151 | let matches: Vec<_> = entries |
| 152 | .values() |
| 153 | .filter_map(Weak::upgrade) |
| 154 | .filter(|entry| { |
| 155 | entry.global_id.len() > scope.len() |
| 156 | && entry.global_id.starts_with(scope) |
| 157 | && entry.global_id.last() == Some(id) |
| 158 | }) |
| 159 | .collect(); |
| 160 | assert!( |
| 161 | matches.len() <= 1, |
| 162 | "ambiguous ElementId {id:?}; use within(...) to select a scope. Matches: {:?}", |
| 163 | matches |
| 164 | .iter() |
| 165 | .map(|entry| &entry.global_id) |
| 166 | .collect::<Vec<_>>() |
| 167 | ); |
| 168 | matches.first().map(|entry| entry.facts.borrow().clone()) |
| 169 | }) |
| 170 | } |
| 171 | |
| 172 | #[doc(hidden)] |
| 173 | pub fn snapshots(window: &Window) -> Vec<ElementSnapshot> { |
| 174 | REGISTRY.with(|registry| { |
| 175 | registry |
| 176 | .borrow() |
| 177 | .get(&(std::sync::Arc::as_ptr(window.text_system()) as usize)) |
| 178 | .map(|entries| { |
| 179 | entries |
| 180 | .values() |
| 181 | .filter_map(Weak::upgrade) |
| 182 | .map(|entry| entry.facts.borrow().clone()) |
| 183 | .collect() |
| 184 | }) |
| 185 | .unwrap_or_default() |
| 186 | }) |
| 187 | } |
| 188 | |
| 189 | /// Internal focus membership check; unsupported bindings are not evidence of focus. |
| 190 | #[doc(hidden)] |
| 191 | pub fn has_observed_focus(window: &Window, scope: &[ElementId]) -> bool { |
| 192 | snapshots(window) |
| 193 | .iter() |
| 194 | .any(|element| element.path.starts_with(scope) && element.focused == Some(true)) |
| 195 | } |
| 196 | |
| 197 | /// Resolves a scope even when only its descendants are observed. |
| 198 | #[doc(hidden)] |
| 199 | pub fn scope(window: &Window, parent: &[ElementId], id: &ElementId) -> Vec<ElementId> { |
| 200 | let mut paths = std::collections::HashSet::new(); |
| 201 | for snapshot in snapshots(window) { |
| 202 | if !snapshot.path.starts_with(parent) { |
| 203 | continue; |
| 204 | } |
| 205 | for index in parent.len()..snapshot.path.len() { |
| 206 | if &snapshot.path[index] == id { |
| 207 | paths.insert(snapshot.path[..=index].to_vec()); |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | assert_eq!( |
| 212 | paths.len(), |
| 213 | 1, |
| 214 | "expected one scope {id:?} below {parent:?}, found {}. Registered paths: {}", |
| 215 | paths.len(), |
| 216 | registered_paths(window) |
| 217 | ); |
| 218 | paths.into_iter().next().unwrap() |
| 219 | } |
| 220 | |
| 221 | #[doc(hidden)] |
| 222 | pub fn registered_paths(window: &Window) -> String { |
| 223 | let mut paths: Vec<_> = snapshots(window) |
| 224 | .iter() |
| 225 | .map(|entry| format!("{:?}", entry.path)) |
| 226 | .collect(); |
| 227 | paths.sort(); |
| 228 | if paths.is_empty() { |
| 229 | "<none; draw a frame and observe elements>".into() |
| 230 | } else { |
| 231 | paths.join(", ") |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | /// Transparent forwarding element. Its registration is owned by GPUI element |
| 236 | /// state, so normal state cleanup and cached-view replay determine its lifetime. |
| 237 | pub struct Observed<E> { |
| 238 | inner: E, |
| 239 | focus: Option<FocusHandle>, |
| 240 | } |
| 241 | impl<E: Element> Observed<E> { |
| 242 | /// Repeated observation keeps one registration and the same native identity. |
| 243 | pub fn test_support(self) -> Self { |
| 244 | self |
| 245 | } |
| 246 | |
| 247 | /// Changes the native identity while keeping observation outside GPUI's |
| 248 | /// stateful wrapper, so later focus bindings still reach this element. |
| 249 | pub fn id(self, id: impl Into<ElementId>) -> Observed<gpui::Stateful<E>> |
| 250 | where |
| 251 | E: InteractiveElement, |
| 252 | { |
| 253 | Observed { |
| 254 | inner: self.inner.id(id), |
| 255 | focus: self.focus, |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | pub(crate) fn new(inner: E) -> Self { |
| 260 | assert!( |
| 261 | Element::id(&inner).is_some(), |
| 262 | "test_support requires an existing ElementId" |
| 263 | ); |
| 264 | Self { inner, focus: None } |
| 265 | } |
| 266 | } |
| 267 | impl<E: Element<PrepaintState = Option<Hitbox>> + InteractiveElement> IntoElement for Observed<E> { |
| 268 | type Element = Self; |
| 269 | fn into_element(self) -> Self { |
| 270 | self |
| 271 | } |
| 272 | } |
| 273 | impl<E: Element<PrepaintState = Option<Hitbox>> + InteractiveElement> Element for Observed<E> { |
| 274 | type RequestLayoutState = E::RequestLayoutState; |
| 275 | type PrepaintState = (Option<Hitbox>, Rc<Registration>); |
| 276 | fn id(&self) -> Option<ElementId> { |
| 277 | Element::id(&self.inner) |
| 278 | } |
| 279 | fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { |
| 280 | self.inner.source_location() |
| 281 | } |
| 282 | fn request_layout( |
| 283 | &mut self, |
| 284 | id: Option<&GlobalElementId>, |
| 285 | inspector: Option<&InspectorElementId>, |
| 286 | window: &mut Window, |
| 287 | cx: &mut App, |
| 288 | ) -> (LayoutId, Self::RequestLayoutState) { |
| 289 | self.inner.request_layout(id, inspector, window, cx) |
| 290 | } |
| 291 | fn prepaint( |
| 292 | &mut self, |
| 293 | id: Option<&GlobalElementId>, |
| 294 | inspector: Option<&InspectorElementId>, |
| 295 | bounds: Bounds<Pixels>, |
| 296 | layout: &mut Self::RequestLayoutState, |
| 297 | window: &mut Window, |
| 298 | cx: &mut App, |
| 299 | ) -> Self::PrepaintState { |
| 300 | let global_id = id.expect("observed elements have an ID"); |
| 301 | let role = self.inner.a11y_role(); |
| 302 | let mut node = gpui::accesskit::Node::new(role.unwrap_or(gpui::Role::Unknown)); |
| 303 | self.inner.write_a11y_info(&mut node); |
| 304 | let toggled = node.toggled(); |
| 305 | let facts = ElementSnapshot { |
| 306 | role, |
| 307 | path: global_id.to_vec(), |
| 308 | checked: toggled.map(|value| value == gpui::accesskit::Toggled::True), |
| 309 | indeterminate: toggled.map(|value| value == gpui::accesskit::Toggled::Mixed), |
| 310 | selected: node.is_selected(), |
| 311 | expanded: node.is_expanded(), |
| 312 | value: node.value().map(|value| value.to_owned().into()), |
| 313 | bounds, |
| 314 | visible: false, |
| 315 | focused: None, |
| 316 | focus_action: node.supports_action(gpui::accesskit::Action::Focus), |
| 317 | disabled: node.is_disabled().then_some(true), |
| 318 | label: node.label().map(|label| label.to_owned().into()), |
| 319 | }; |
| 320 | let registration = |
| 321 | window.with_element_state(global_id, |state: Option<Rc<Registration>>, window| { |
| 322 | let registration = state.unwrap_or_else(|| { |
| 323 | Rc::new(Registration { |
| 324 | window: std::sync::Arc::as_ptr(window.text_system()) as usize, |
| 325 | global_id: global_id.clone(), |
| 326 | facts: RefCell::new(facts.clone()), |
| 327 | }) |
| 328 | }); |
| 329 | *registration.facts.borrow_mut() = facts; |
| 330 | REGISTRY.with(|registry| { |
| 331 | registry |
| 332 | .borrow_mut() |
| 333 | .entry(registration.window) |
| 334 | .or_default() |
| 335 | .insert(global_id.clone(), Rc::downgrade(®istration)); |
| 336 | }); |
| 337 | (registration.clone(), registration) |
| 338 | }); |
| 339 | ( |
| 340 | self.inner |
| 341 | .prepaint(id, inspector, bounds, layout, window, cx), |
| 342 | registration, |
| 343 | ) |
| 344 | } |
| 345 | fn paint( |
| 346 | &mut self, |
| 347 | id: Option<&GlobalElementId>, |
| 348 | inspector: Option<&InspectorElementId>, |
| 349 | bounds: Bounds<Pixels>, |
| 350 | layout: &mut Self::RequestLayoutState, |
| 351 | paint: &mut Self::PrepaintState, |
| 352 | window: &mut Window, |
| 353 | cx: &mut App, |
| 354 | ) { |
| 355 | let style = self |
| 356 | .inner |
| 357 | .interactivity() |
| 358 | .compute_style(id, paint.0.as_ref(), window, cx); |
| 359 | let clipped = bounds |
| 360 | .intersect(&window.content_mask().bounds) |
| 361 | .intersect(&Bounds::new(Default::default(), window.viewport_size())); |
| 362 | { |
| 363 | let mut facts = paint.1.facts.borrow_mut(); |
| 364 | facts.visible = style.visibility != Visibility::Hidden |
| 365 | && style.opacity.unwrap_or(1.) > 0. |
| 366 | && clipped.size.width > px(0.) |
| 367 | && clipped.size.height > px(0.); |
| 368 | facts.focused = self |
| 369 | .focus |
| 370 | .as_ref() |
| 371 | .map(|focus| focus.contains_focused(window, cx)); |
| 372 | } |
| 373 | self.inner |
| 374 | .paint(id, inspector, bounds, layout, &mut paint.0, window, cx); |
| 375 | } |
| 376 | fn a11y_role(&self) -> Option<gpui::Role> { |
| 377 | self.inner.a11y_role() |
| 378 | } |
| 379 | fn write_a11y_info(&self, node: &mut gpui::accesskit::Node) { |
| 380 | self.inner.write_a11y_info(node); |
| 381 | } |
| 382 | fn a11y_synthetic_children( |
| 383 | &mut self, |
| 384 | paint: &mut Self::PrepaintState, |
| 385 | builder: &mut gpui::A11ySubtreeBuilder, |
| 386 | ) { |
| 387 | self.inner.a11y_synthetic_children(&mut paint.0, builder); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | impl<E: Element<PrepaintState = Option<Hitbox>> + InteractiveElement + gpui::Styled> gpui::Styled |
| 392 | for Observed<E> |
| 393 | { |
| 394 | fn style(&mut self) -> &mut gpui::StyleRefinement { |
| 395 | self.inner.style() |
| 396 | } |
| 397 | } |
| 398 | impl<E: Element<PrepaintState = Option<Hitbox>> + InteractiveElement> InteractiveElement |
| 399 | for Observed<E> |
| 400 | { |
| 401 | fn interactivity(&mut self) -> &mut gpui::Interactivity { |
| 402 | self.inner.interactivity() |
| 403 | } |
| 404 | fn track_focus(mut self, focus: &FocusHandle) -> Self { |
| 405 | self.focus = Some(focus.clone()); |
| 406 | self.inner = self.inner.track_focus(focus); |
| 407 | self |
| 408 | } |
| 409 | } |
| 410 | impl<E: Element<PrepaintState = Option<Hitbox>> + InteractiveElement + gpui::ParentElement> |
| 411 | gpui::ParentElement for Observed<E> |
| 412 | { |
| 413 | fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) { |
| 414 | self.inner.extend(elements); |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | impl<E: Element<PrepaintState = Option<Hitbox>> + gpui::StatefulInteractiveElement> |
| 419 | gpui::StatefulInteractiveElement for Observed<E> |
| 420 | { |
| 421 | } |