use crate::{
Bounds, FocusId, PaintIndex, Pixels, Point, PrepaintStateIndex, Window, point,
window::a11y::{A11y, A11yActionListener, A11yNodeBuilder, A11ySubtreeBuilder},
};
use accesskit::{Action, NodeId};
use collections::FxHashMap;
use std::{mem, ops::Range, rc::Rc};
#[derive(Default)]
pub(crate) struct SyntheticParent {
expected_children: Option<Vec<NodeId>>,
}
impl SyntheticParent {
#[inline]
pub(crate) fn leaf(parent: &mut Self, id: NodeId, pushed: bool) {
if pushed && let Some(children) = &mut parent.expected_children {
children.push(id);
}
}
pub(crate) fn lend(parent: &mut Self, nodes: &mut A11yNodeBuilder) {
if parent.expected_children.is_none()
&& let Some(node) = nodes.current_node_mut()
{
parent.expected_children = Some(node.children().to_vec());
}
}
}
pub(crate) fn finish_synthetic_children(builder: A11ySubtreeBuilder) {
let Some(expected) = builder.fast.expected_children else {
return;
};
let changed = builder
.nodes
.current_node_mut()
.is_some_and(|node| node.children() != expected);
builder.nodes.fast.preserve_next_pop = changed;
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Op {
Push(NodeId),
Leaf(usize),
Pop(usize, bool),
Focusable(NodeId, FocusId),
ActiveDescendant(NodeId),
}
#[derive(Default)]
pub(crate) struct A11yLog {
recording: bool,
previous_recorded: bool,
diverged: bool,
ops: Vec<Op>,
previous_ops: Vec<Op>,
actions: Vec<(NodeId, Action)>,
previous_actions: Vec<(NodeId, Action, usize)>,
previous_listeners: FxHashMap<NodeId, Vec<Option<(Action, A11yActionListener)>>>,
previous_bounds: FxHashMap<NodeId, Bounds<Pixels>>,
#[cfg(debug_assertions)]
previous_info: FxHashMap<NodeId, crate::window::a11y::debug::NodeDebugInfo>,
replay_open: Vec<bool>,
preserve_next_pop: bool,
}
impl A11yLog {
#[inline]
pub(crate) fn push(log: &mut Self, id: NodeId) {
if log.recording {
log.ops.push(Op::Push(id));
}
}
#[inline]
pub(crate) fn leaf(log: &mut Self, at: usize) {
if log.recording {
log.ops.push(Op::Leaf(at));
}
}
#[inline]
pub(crate) fn pop(log: &mut Self, at: usize) {
let preserve_children = mem::take(&mut log.preserve_next_pop);
if log.recording {
log.ops.push(Op::Pop(at, preserve_children));
}
}
#[inline]
pub(crate) fn focusable(log: &mut Self, node: NodeId, focus: FocusId) {
if log.recording {
log.ops.push(Op::Focusable(node, focus));
}
}
#[inline]
pub(crate) fn active_descendant(log: &mut Self, node: NodeId) {
if log.recording {
log.ops.push(Op::ActiveDescendant(node));
}
}
#[inline]
pub(crate) fn action(log: &mut Self, node: NodeId, action: Action) {
if log.recording {
log.actions.push((node, action));
}
}
pub(crate) fn end_frame(log: &mut Self) {
mem::swap(&mut log.ops, &mut log.previous_ops);
log.ops.clear();
}
pub(crate) fn new_frame(log: &mut Self) {
log.previous_recorded = log.recording && !mem::take(&mut log.diverged);
log.recording = false;
}
}
pub(crate) fn begin_frame(a11y: &mut A11y) {
let log = &mut a11y.nodes.fast;
log.recording = true;
log.replay_open.clear();
log.ops.clear();
mem::swap(&mut log.previous_bounds, &mut a11y.node_bounds);
let mut counts: FxHashMap<NodeId, usize> = FxHashMap::default();
log.previous_actions.clear();
for (node, action) in log.actions.drain(..) {
let count = counts.entry(node).or_default();
log.previous_actions.push((node, action, *count));
*count += 1;
}
log.previous_listeners = mem::take(&mut a11y.action_listeners)
.into_iter()
.map(|(node, listeners)| (node, listeners.into_iter().map(Some).collect()))
.collect();
#[cfg(debug_assertions)]
{
log.previous_info = mem::take(&mut a11y.nodes.node_info);
}
}
pub(crate) struct A11yCheckpoint {
all_nodes: usize,
depth: usize,
children: usize,
focus: Option<NodeId>,
active_descendant: Option<NodeId>,
}
pub(crate) fn checkpoint(window: &Window) -> A11yCheckpoint {
let nodes = &window.a11y.nodes;
A11yCheckpoint {
all_nodes: nodes.all_nodes.len(),
depth: nodes.ids_stack.len(),
children: nodes
.nodes_stack
.last()
.map_or(0, |node| node.children().len()),
focus: nodes.focus,
active_descendant: nodes.active_descendant,
}
}
pub(crate) fn rollback(window: &mut Window, checkpoint: A11yCheckpoint, ops_index: usize) {
let nodes = &mut window.a11y.nodes;
let depth = checkpoint.depth.min(nodes.ids_stack.len());
for id in nodes.ids_stack.drain(depth..) {
nodes.seen_ids.remove(&id);
#[cfg(debug_assertions)]
nodes.node_info.remove(&id);
}
nodes.nodes_stack.truncate(depth);
let all_nodes = checkpoint.all_nodes.min(nodes.all_nodes.len());
for (id, _) in nodes.all_nodes.drain(all_nodes..) {
nodes.seen_ids.remove(&id);
#[cfg(debug_assertions)]
nodes.node_info.remove(&id);
}
if let Some(parent) = nodes.nodes_stack.last_mut()
&& parent.children().len() > checkpoint.children
{
let children = parent.children()[..checkpoint.children].to_vec();
parent.set_children(children);
}
nodes.focus = checkpoint.focus;
nodes.active_descendant = checkpoint.active_descendant;
nodes.fast.ops.truncate(ops_index);
}
#[inline]
pub(crate) fn ops_index(window: &Window) -> usize {
window.a11y.nodes.fast.ops.len()
}
#[inline]
pub(crate) fn actions_index(window: &Window) -> usize {
window.a11y.nodes.fast.actions.len()
}
#[inline]
pub(crate) fn stale(a11y: &A11y) -> bool {
a11y.is_active() && !a11y.nodes.fast.previous_recorded
}
struct Source<'a> {
ops: &'a [Op],
nodes: &'a [(NodeId, accesskit::Node)],
bounds: &'a FxHashMap<NodeId, Bounds<Pixels>>,
#[cfg(debug_assertions)]
info: &'a FxHashMap<NodeId, crate::window::a11y::debug::NodeDebugInfo>,
}
#[inline]
pub(crate) fn reuse_prepaint(window: &mut Window, range: &Range<PrepaintStateIndex>) {
let ops = range.start.fast_a11y_index..range.end.fast_a11y_index;
if ops.is_empty() || !window.a11y.is_active() {
return;
}
reuse_ops(window, ops);
}
#[inline(never)]
fn reuse_ops(window: &mut Window, range: Range<usize>) {
let log = &mut window.a11y.nodes.fast;
if !log.previous_recorded {
debug_assert!(
false,
"drew again from a frame that logged no accessibility"
);
return;
}
let ops = mem::take(&mut log.previous_ops);
let bounds = mem::take(&mut log.previous_bounds);
#[cfg(debug_assertions)]
let info = mem::take(&mut log.previous_info);
let update = window.a11y.debug.last_tree_update.take();
if let Some(ops_range) = ops.get(range) {
let source = Source {
ops: ops_range,
nodes: update.as_ref().map_or(&[], |update| &update.nodes),
bounds: &bounds,
#[cfg(debug_assertions)]
info: &info,
};
replay(window, &source, Point::default());
} else {
debug_assert!(
false,
"a stretch reaches past last frame's accessibility log"
);
}
window.a11y.debug.last_tree_update = update;
let log = &mut window.a11y.nodes.fast;
log.previous_ops = ops;
log.previous_bounds = bounds;
#[cfg(debug_assertions)]
{
log.previous_info = info;
}
}
fn replay(window: &mut Window, source: &Source, delta: Point<Pixels>) {
let scale = window.scale_factor();
let shift = (delta != Point::default())
.then(|| ((delta.x.0 * scale) as f64, (delta.y.0 * scale) as f64));
let moved = |node: &accesskit::Node| {
let mut node = node.clone();
if let Some((dx, dy)) = shift
&& let Some(rect) = node.bounds()
{
node.set_bounds(accesskit::Rect {
x0: rect.x0 + dx,
y0: rect.y0 + dy,
x1: rect.x1 + dx,
y1: rect.y1 + dy,
});
}
node
};
let logged = window.a11y.nodes.fast.ops.len();
for op in source.ops {
match *op {
Op::Push(id) => {
let pushed = window.a11y.nodes.push(id, accesskit::Node::default());
window.a11y.nodes.fast.replay_open.push(pushed);
if pushed {
if let Some(bounds) = source.bounds.get(&id) {
let bounds = Bounds::new(bounds.origin + delta, bounds.size);
window.a11y.node_bounds.insert(id, bounds);
}
#[cfg(debug_assertions)]
if let Some(info) = source.info.get(&id) {
window.a11y.nodes.record_node_info(id, info.clone());
}
}
}
Op::Leaf(at) => {
let Some((id, node)) = source.nodes.get(at) else {
debug_assert!(false, "a leaf missing from last frame's tree");
continue;
};
let _pushed = window.a11y.nodes.push_leaf(*id, moved(node));
#[cfg(debug_assertions)]
if _pushed && let Some(info) = source.info.get(id) {
window.a11y.nodes.record_node_info(*id, info.clone());
}
}
Op::Pop(at, preserve_children) => {
if window.a11y.nodes.fast.replay_open.pop() != Some(true) {
continue;
}
let mut node = match source.nodes.get(at) {
Some((_, node)) => moved(node),
None => {
debug_assert!(false, "a node missing from last frame's tree");
accesskit::Node::default()
}
};
if let Some(open) = window.a11y.nodes.nodes_stack.last_mut() {
if !preserve_children && open.children() != node.children() {
if open.children().is_empty() {
node.clear_children();
} else {
node.set_children(open.children().to_vec());
}
}
*open = node;
}
window.a11y.nodes.fast.preserve_next_pop = preserve_children;
window.a11y.nodes.pop();
}
Op::Focusable(node, focus) => {
window.a11y.set_focusable(node, focus);
if focus.is_focused(window) {
window.a11y.set_focus(node);
}
}
Op::ActiveDescendant(node) => window.a11y.set_active_descendant(node),
}
}
let log = &mut window.a11y.nodes.fast;
log.diverged |= log.ops.len() - logged != source.ops.len();
}
#[inline]
pub(crate) fn reuse_paint(window: &mut Window, range: &Range<PaintIndex>) {
let actions = range.start.fast.a11y_actions..range.end.fast.a11y_actions;
if actions.is_empty() || !window.a11y.is_active() {
return;
}
reuse_actions(window, actions);
}
#[inline(never)]
fn reuse_actions(window: &mut Window, range: Range<usize>) {
let a11y = &mut window.a11y;
let log = &mut a11y.nodes.fast;
let Some(actions) = log.previous_actions.get(range) else {
debug_assert!(
false,
"a stretch reaches past last frame's action listeners"
);
return;
};
for &(node, action, index) in actions {
let listener = log
.previous_listeners
.get_mut(&node)
.and_then(|listeners| listeners.get_mut(index))
.and_then(Option::take);
log.actions.push((node, action));
if let Some(listener) = listener {
a11y.action_listeners
.entry(node)
.or_default()
.push(listener);
}
}
}
pub(crate) struct A11yStretch {
ops: Vec<Op>,
nodes: Vec<(NodeId, accesskit::Node)>,
bounds: FxHashMap<NodeId, Bounds<Pixels>>,
#[cfg(debug_assertions)]
info: FxHashMap<NodeId, crate::window::a11y::debug::NodeDebugInfo>,
placed_synthetic: bool,
}
pub(crate) fn capture(
window: &Window,
range: &Range<PrepaintStateIndex>,
) -> Option<Rc<A11yStretch>> {
if !window.a11y.is_active() {
return None;
}
let builder = &window.a11y.nodes;
let ops = builder
.fast
.ops
.get(range.start.fast_a11y_index..range.end.fast_a11y_index)?;
let mut stretch = A11yStretch {
ops: Vec::with_capacity(ops.len()),
nodes: Vec::new(),
bounds: FxHashMap::default(),
#[cfg(debug_assertions)]
info: FxHashMap::default(),
placed_synthetic: false,
};
for op in ops {
let op = match *op {
Op::Leaf(at) | Op::Pop(at, _) => {
let node = builder.all_nodes.get(at)?.clone();
let local = stretch.nodes.len();
#[cfg(debug_assertions)]
if matches!(op, Op::Leaf(_))
&& let Some(info) = builder.node_info.get(&node.0)
{
stretch.info.insert(node.0, info.clone());
}
stretch.placed_synthetic |= matches!(op, Op::Leaf(_)) && node.1.bounds().is_some();
stretch.nodes.push(node);
if let Op::Pop(_, preserve_children) = *op {
Op::Pop(local, preserve_children)
} else {
Op::Leaf(local)
}
}
Op::Push(id) => {
if let Some(bounds) = window.a11y.node_bounds.get(&id) {
stretch.bounds.insert(id, *bounds);
}
#[cfg(debug_assertions)]
if let Some(info) = builder.node_info.get(&id) {
stretch.info.insert(id, info.clone());
}
Op::Push(id)
}
other => other,
};
stretch.ops.push(op);
}
Some(Rc::new(stretch))
}
pub(crate) fn carry(window: &mut Window, stretch: Option<&A11yStretch>, delta: Point<Pixels>) {
let Some(stretch) = stretch else {
return;
};
if !window.a11y.is_active() {
return;
}
let source = Source {
ops: &stretch.ops,
nodes: &stretch.nodes,
bounds: &stretch.bounds,
#[cfg(debug_assertions)]
info: &stretch.info,
};
replay(window, &source, delta);
}
#[inline]
pub(crate) fn layer_needs_repaint(window: &Window, stretch: Option<&A11yStretch>) -> bool {
window.a11y.is_active() && stretch.is_none_or(|stretch| stretch.placed_synthetic)
}
#[cfg(test)]
impl Window {
pub(crate) fn set_a11y_active_for_tests(&mut self, active: bool) {
crate::fast::a11y::set_active_flag(&self.a11y, active);
self.refresh();
}
}
#[inline]
pub(crate) fn new_frame(window: &mut Window) {
#[cfg(any(test, feature = "test-support"))]
if forced_by_env() {
set_active_flag(&window.a11y, true);
}
A11yLog::new_frame(&mut window.a11y.nodes.fast);
}
#[cfg(any(test, feature = "test-support"))]
fn forced_by_env() -> bool {
static FORCED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*FORCED.get_or_init(|| std::env::var("GPUI_A11Y_ACTIVE").is_ok_and(|value| value == "1"))
}
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn set_active_flag(a11y: &A11y, active: bool) {
a11y.active_flag
.store(active, std::sync::atomic::Ordering::SeqCst);
}
#[cfg(test)]
pub(crate) fn last_tree(window: &Window) -> Option<&accesskit::TreeUpdate> {
window.a11y.debug.last_tree_update.as_ref()
}
pub(crate) fn debug_tree_json(window: &Window) -> Option<String> {
let tab_stop_count = window
.a11y
.nodes
.fast
.recording
.then(|| window.rendered_frame.tab_stops.tab_stop_count());
window.a11y.debug.to_json(tab_stop_count)
}
pub(crate) struct CapturedAt(jiff::Timestamp);
impl CapturedAt {
pub(crate) fn now() -> Self {
Self(jiff::Timestamp::now())
}
#[cfg(test)]
pub(crate) fn from_timestamp(timestamp: jiff::Timestamp) -> Self {
Self(timestamp)
}
pub(crate) fn to_rfc3339(&self) -> String {
self.to_rfc3339_in(jiff::tz::TimeZone::system())
}
pub(crate) fn to_rfc3339_in(&self, time_zone: jiff::tz::TimeZone) -> String {
self.0
.to_zoned_datetime(time_zone)
.strftime("%Y-%m-%dT%H:%M:%S%.3f%:z")
.to_string()
}
}
pub(crate) fn click_position(window: &Window, node: accesskit::NodeId) -> Option<Point<Pixels>> {
let bounds = window.a11y.node_bounds.get(&node).copied()?;
let frame = &window.rendered_frame;
let Some(hitbox) = frame
.hitboxes
.iter()
.rev()
.find(|hitbox| hitbox.bounds == bounds)
else {
let center = bounds.center();
let window = Bounds::new(Point::default(), window.viewport_size());
return window.contains(¢er).then_some(center);
};
let visible = bounds.intersect(&hitbox.content_mask.bounds);
if visible.size.width <= Pixels::ZERO || visible.size.height <= Pixels::ZERO {
return None;
}
let fractions: [f32; 3] = [0.5, 1. / 6., 5. / 6.];
let candidates = std::iter::once((0.5_f32, 0.5_f32)).chain(
fractions
.iter()
.flat_map(|y| fractions.iter().map(move |x| (*x, *y)))
.skip(1),
);
candidates
.map(|(x, y)| {
point(
visible.origin.x + visible.size.width * x,
visible.origin.y + visible.size.height * y,
)
})
.find(|position| {
let hit_test = frame.hit_test(*position);
hit_test.ids[..hit_test.hover_hitbox_count].contains(&hitbox.id)
})
}