feat(client): redesign native UI, themes, settings and avatars

Separate conversation drafts and voice view state, add native settings and restricted CSS themes, implement validated avatar cropping, and refresh dependencies with documented desktop compatibility backports.
This commit is contained in:
Loki 2026-10-24 14:23:48 +02:00
parent 44d284a568
commit 8e5ab56611
Signed by: boba
GPG key ID: 253067914055423B
276 changed files with 53546 additions and 3399 deletions

271
patches/accesskit_unix/src/adapter.rs vendored Normal file
View file

@ -0,0 +1,271 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit::{ActionHandler, ActivationHandler, DeactivationHandler, Rect, TreeUpdate};
use accesskit_atspi_common::{
ActionHandlerNoMut, ActionHandlerWrapper, Adapter as AdapterImpl, AdapterCallback, CacheEvent,
Event, NodeId, PlatformNode, WindowBounds, next_adapter_id,
};
#[cfg(not(feature = "tokio"))]
use async_channel::Sender;
use atspi::InterfaceSet;
use std::fmt::{Debug, Formatter};
use std::sync::{Arc, Mutex};
#[cfg(feature = "tokio")]
use tokio::sync::mpsc::UnboundedSender as Sender;
use crate::context::{get_or_init_app_context, get_or_init_messages};
pub(crate) struct Callback {
messages: Sender<Message>,
}
impl Callback {
pub(crate) fn new() -> Self {
let messages = get_or_init_messages();
Self { messages }
}
fn send_message(&self, message: Message) {
#[cfg(not(feature = "tokio"))]
let _ = self.messages.try_send(message);
#[cfg(feature = "tokio")]
let _ = self.messages.send(message);
}
}
impl AdapterCallback for Callback {
fn register_interfaces(&self, adapter: &AdapterImpl, id: NodeId, interfaces: InterfaceSet) {
let node = adapter.platform_node(id);
self.send_message(Message::RegisterInterfaces { node, interfaces });
}
fn unregister_interfaces(&self, adapter: &AdapterImpl, id: NodeId, interfaces: InterfaceSet) {
self.send_message(Message::UnregisterInterfaces {
adapter_id: adapter.id(),
node_id: id,
interfaces,
})
}
fn emit_event(&self, adapter: &AdapterImpl, event: Event) {
match event {
Event::Cache(CacheEvent::Added(id)) => {
let node = adapter.platform_node(id);
self.send_message(Message::EmitCacheAdd { node });
}
Event::Cache(CacheEvent::Removed(id)) => {
self.send_message(Message::EmitCacheRemove {
adapter_id: adapter.id(),
node_id: id,
});
}
event => {
self.send_message(Message::EmitEvent {
adapter_id: adapter.id(),
event,
});
}
}
}
}
pub(crate) enum AdapterState {
Inactive {
is_window_focused: bool,
root_window_bounds: WindowBounds,
action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>,
},
Pending {
is_window_focused: bool,
root_window_bounds: WindowBounds,
action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>,
},
Active(AdapterImpl),
}
impl Debug for AdapterState {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
AdapterState::Inactive {
is_window_focused,
root_window_bounds,
action_handler: _,
} => f
.debug_struct("Inactive")
.field("is_window_focused", is_window_focused)
.field("root_window_bounds", root_window_bounds)
.field("action_handler", &"ActionHandler")
.finish(),
AdapterState::Pending {
is_window_focused,
root_window_bounds,
action_handler: _,
} => f
.debug_struct("Pending")
.field("is_window_focused", is_window_focused)
.field("root_window_bounds", root_window_bounds)
.field("action_handler", &"ActionHandler")
.finish(),
AdapterState::Active(r#impl) => f.debug_tuple("Active").field(r#impl).finish(),
}
}
}
#[derive(Debug)]
pub struct Adapter {
messages: Sender<Message>,
id: usize,
state: Arc<Mutex<AdapterState>>,
}
impl Adapter {
/// Create a new Unix adapter.
///
/// All of the handlers will always be called from another thread.
pub fn new(
activation_handler: impl 'static + ActivationHandler + Send,
action_handler: impl 'static + ActionHandler + Send,
deactivation_handler: impl 'static + DeactivationHandler + Send,
) -> Self {
let id = next_adapter_id();
let messages = get_or_init_messages();
let state = Arc::new(Mutex::new(AdapterState::Inactive {
is_window_focused: false,
root_window_bounds: Default::default(),
action_handler: Arc::new(ActionHandlerWrapper::new(action_handler)),
}));
let adapter = Self {
id,
messages,
state: Arc::clone(&state),
};
adapter.send_message(Message::AddAdapter {
id,
activation_handler: Box::new(activation_handler),
deactivation_handler: Box::new(deactivation_handler),
state,
});
adapter
}
pub(crate) fn send_message(&self, message: Message) {
#[cfg(not(feature = "tokio"))]
let _ = self.messages.try_send(message);
#[cfg(feature = "tokio")]
let _ = self.messages.send(message);
}
/// Set the bounds of the top-level window. The outer bounds contain any
/// window decoration and borders.
///
/// # Caveats
///
/// Since an application can not get the position of its window under
/// Wayland, calling this method only makes sense under X11.
pub fn set_root_window_bounds(&mut self, outer: Rect, inner: Rect) {
let new_bounds = WindowBounds::new(outer, inner);
let mut state = self.state.lock().unwrap();
match &mut *state {
AdapterState::Inactive {
root_window_bounds, ..
} => {
*root_window_bounds = new_bounds;
}
AdapterState::Pending {
root_window_bounds, ..
} => {
*root_window_bounds = new_bounds;
}
AdapterState::Active(r#impl) => r#impl.set_root_window_bounds(new_bounds),
}
}
/// If and only if the tree has been initialized, call the provided function
/// and apply the resulting update. Note: If the caller's implementation of
/// [`ActivationHandler::request_initial_tree`] initially returned `None`,
/// the [`TreeUpdate`] returned by the provided function must contain
/// a full tree.
pub fn update_if_active(&mut self, update_factory: impl FnOnce() -> TreeUpdate) {
let mut state = self.state.lock().unwrap();
match &mut *state {
AdapterState::Inactive { .. } => (),
AdapterState::Pending {
is_window_focused,
root_window_bounds,
action_handler,
} => {
let initial_state = update_factory();
let r#impl = AdapterImpl::with_wrapped_action_handler(
self.id,
get_or_init_app_context(),
Callback::new(),
initial_state,
*is_window_focused,
*root_window_bounds,
Arc::clone(action_handler),
);
*state = AdapterState::Active(r#impl);
}
AdapterState::Active(r#impl) => r#impl.update(update_factory()),
}
}
/// Update the tree state based on whether the window is focused.
pub fn update_window_focus_state(&mut self, is_focused: bool) {
let mut state = self.state.lock().unwrap();
match &mut *state {
AdapterState::Inactive {
is_window_focused, ..
} => {
*is_window_focused = is_focused;
}
AdapterState::Pending {
is_window_focused, ..
} => {
*is_window_focused = is_focused;
}
AdapterState::Active(r#impl) => r#impl.update_window_focus_state(is_focused),
}
}
}
impl Drop for Adapter {
fn drop(&mut self) {
self.send_message(Message::RemoveAdapter { id: self.id });
}
}
pub(crate) enum Message {
AddAdapter {
id: usize,
activation_handler: Box<dyn ActivationHandler + Send>,
deactivation_handler: Box<dyn DeactivationHandler + Send>,
state: Arc<Mutex<AdapterState>>,
},
RemoveAdapter {
id: usize,
},
RegisterInterfaces {
node: PlatformNode,
interfaces: InterfaceSet,
},
UnregisterInterfaces {
adapter_id: usize,
node_id: NodeId,
interfaces: InterfaceSet,
},
EmitEvent {
adapter_id: usize,
event: Event,
},
EmitCacheAdd {
node: PlatformNode,
},
EmitCacheRemove {
adapter_id: usize,
node_id: NodeId,
},
}

461
patches/accesskit_unix/src/atspi/bus.rs vendored Normal file
View file

@ -0,0 +1,461 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use crate::{
atspi::{ObjectId, cache_path, interfaces::*},
context::get_or_init_app_context,
};
use accesskit_atspi_common::{
NodeId, NodeIdOrRoot, ObjectEvent, PlatformNode, PlatformRoot, Property, WindowEvent,
};
use atspi::{
Interface, InterfaceSet, ObjectRefOwned,
events::EventBodyBorrowed,
proxy::{bus::BusProxy, socket::SocketProxy},
};
use std::{
env::var,
sync::{Arc, OnceLock},
};
use zbus::{
Address, Connection, Result,
connection::Builder,
names::{BusName, InterfaceName, MemberName, OwnedUniqueName},
wire::{Str, Variant as Value},
};
pub(crate) struct Bus {
conn: Connection,
socket_proxy: SocketProxy<'static>,
desktop: Arc<OnceLock<ObjectRefOwned>>,
}
impl Bus {
pub(crate) async fn new(
session_bus: &Connection,
) -> zbus::Result<Self> {
let address = match var("AT_SPI_BUS_ADDRESS") {
Ok(address) if !address.is_empty() => address,
_ => BusProxy::new(session_bus).await?.get_address().await?,
};
let address: Address = address.as_str().try_into()?;
// zbus 6 selects and drives its maintained default runtime.
let conn = Builder::address(address).build().await?;
let socket_proxy = SocketProxy::new(&conn).await?;
let mut bus = Bus {
conn,
socket_proxy,
desktop: Arc::new(OnceLock::new()),
};
bus.register_root_node().await?;
Ok(bus)
}
fn unique_name(&self) -> &OwnedUniqueName {
self.conn.unique_name().unwrap()
}
async fn register_root_node(&mut self) -> Result<()> {
let node = PlatformRoot::new(get_or_init_app_context());
let path = ObjectId::Root.path();
if self
.conn
.object_server()
.at(path.clone(), ApplicationInterface(node.clone()))
.await?
.is_none()
{
let desktop = self
.socket_proxy
.embed(&(self.unique_name().as_str(), ObjectId::Root.path().into()))
.await?;
let _ = self.desktop.set(desktop);
self.conn
.object_server()
.at(
path,
RootAccessibleInterface::new(
self.unique_name().to_owned(),
node.clone(),
Arc::clone(&self.desktop),
),
)
.await?;
self.conn
.object_server()
.at(
cache_path(),
CacheInterface::new(
self.unique_name().to_owned(),
node,
Arc::clone(&self.desktop),
),
)
.await?;
}
Ok(())
}
pub(crate) async fn register_interfaces(
&self,
node: PlatformNode,
new_interfaces: InterfaceSet,
) -> zbus::Result<()> {
let path = ObjectId::from(&node).path();
let bus_name = self.unique_name().to_owned();
if new_interfaces.contains(Interface::Accessible) {
self.register_interface(
&path,
NodeAccessibleInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Action) {
self.register_interface(&path, ActionInterface::new(node.clone()))
.await?;
}
if new_interfaces.contains(Interface::Component) {
self.register_interface(
&path,
ComponentInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Hyperlink) {
self.register_interface(
&path,
HyperlinkInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Selection) {
self.register_interface(
&path,
SelectionInterface::new(bus_name.clone(), node.clone()),
)
.await?;
}
if new_interfaces.contains(Interface::Text) {
self.register_interface(&path, TextInterface::new(node.clone()))
.await?;
}
if new_interfaces.contains(Interface::Value) {
self.register_interface(&path, ValueInterface::new(node.clone()))
.await?;
}
Ok(())
}
async fn register_interface<T>(&self, path: &str, interface: T) -> Result<bool>
where
T: zbus::object_server::Interface,
{
map_or_ignoring_recoverable_error(
self.conn.object_server().at(path, interface).await,
false,
|result| result.is_none(),
)
}
pub(crate) async fn unregister_interfaces(
&self,
adapter_id: usize,
node_id: NodeId,
old_interfaces: InterfaceSet,
) -> zbus::Result<()> {
let path = ObjectId::Node {
adapter: adapter_id,
node: node_id,
}
.path();
if old_interfaces.contains(Interface::Accessible) {
self.unregister_interface::<NodeAccessibleInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Action) {
self.unregister_interface::<ActionInterface>(&path).await?;
}
if old_interfaces.contains(Interface::Component) {
self.unregister_interface::<ComponentInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Hyperlink) {
self.unregister_interface::<HyperlinkInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Selection) {
self.unregister_interface::<SelectionInterface>(&path)
.await?;
}
if old_interfaces.contains(Interface::Text) {
self.unregister_interface::<TextInterface>(&path).await?;
}
if old_interfaces.contains(Interface::Value) {
self.unregister_interface::<ValueInterface>(&path).await?;
}
Ok(())
}
async fn unregister_interface<T>(&self, path: &str) -> Result<bool>
where
T: zbus::object_server::Interface,
{
map_or_ignoring_recoverable_error(
self.conn.object_server().remove::<T, _>(path).await,
false,
|result| result,
)
}
pub(crate) async fn emit_object_event(
&self,
adapter_id: usize,
target: NodeIdOrRoot,
event: ObjectEvent,
) -> Result<()> {
let target = match target {
NodeIdOrRoot::Node(node) => ObjectId::Node {
adapter: adapter_id,
node,
},
NodeIdOrRoot::Root => ObjectId::Root,
};
let interface = "org.a11y.atspi.Event.Object";
let signal = match event {
ObjectEvent::ActiveDescendantChanged(_) => "ActiveDescendantChanged",
ObjectEvent::Announcement(_, _) => "Announcement",
ObjectEvent::BoundsChanged(_) => "BoundsChanged",
ObjectEvent::CaretMoved(_) => "TextCaretMoved",
ObjectEvent::ChildAdded(_, _) | ObjectEvent::ChildRemoved(_) => "ChildrenChanged",
ObjectEvent::PropertyChanged(_) => "PropertyChange",
ObjectEvent::SelectionChanged => "SelectionChanged",
ObjectEvent::StateChanged(_, _) => "StateChanged",
ObjectEvent::TextInserted { .. } | ObjectEvent::TextRemoved { .. } => "TextChanged",
ObjectEvent::TextSelectionChanged => "TextSelectionChanged",
};
match event {
ObjectEvent::ActiveDescendantChanged(child) => {
let child = ObjectId::Node {
adapter: adapter_id,
node: child,
};
let mut body = EventBodyBorrowed::default();
body.any_data = child.to_address(self.unique_name().inner()).into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::Announcement(message, politeness) => {
let mut body = EventBodyBorrowed::default();
body.detail1 = politeness as i32;
body.any_data = message.into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::BoundsChanged(bounds) => {
let mut body = EventBodyBorrowed::default();
body.any_data = Value::from(bounds);
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::CaretMoved(offset) => {
let mut body = EventBodyBorrowed::default();
body.detail1 = offset;
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::ChildAdded(index, child) => {
let child = ObjectId::Node {
adapter: adapter_id,
node: child,
};
let mut body = EventBodyBorrowed::default();
body.kind = "add";
body.detail1 = index as i32;
body.any_data = child.to_address(self.unique_name().inner()).into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::ChildRemoved(child) => {
let child = ObjectId::Node {
adapter: adapter_id,
node: child,
};
let mut body = EventBodyBorrowed::default();
body.kind = "remove";
body.detail1 = -1;
body.any_data = child.to_address(self.unique_name().inner()).into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::PropertyChanged(property) => {
let mut body = EventBodyBorrowed::default();
body.kind = match property {
Property::Name(_) => "accessible-name",
Property::Description(_) => "accessible-description",
Property::Parent(_) => "accessible-parent",
Property::Role(_) => "accessible-role",
Property::Value(_) => "accessible-value",
};
body.any_data = match property {
Property::Name(value) => Str::from(value).into(),
Property::Description(value) => Str::from(value).into(),
Property::Parent(parent) => {
let parent = match parent {
NodeIdOrRoot::Node(node) => ObjectId::Node {
adapter: adapter_id,
node,
},
NodeIdOrRoot::Root => ObjectId::Root,
};
parent.to_address(self.unique_name().inner()).into()
}
Property::Role(value) => Value::U32(value as u32),
Property::Value(value) => Value::F64(value),
};
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::SelectionChanged => {
self.emit_event(target, interface, signal, EventBodyBorrowed::default())
.await
}
ObjectEvent::StateChanged(state, value) => {
let mut body = EventBodyBorrowed::default();
body.kind = state.to_static_str();
body.detail1 = value as i32;
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::TextInserted {
start_index,
length,
content,
} => {
let mut body = EventBodyBorrowed::default();
body.kind = "insert";
body.detail1 = start_index;
body.detail2 = length;
body.any_data = content.into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::TextRemoved {
start_index,
length,
content,
} => {
let mut body = EventBodyBorrowed::default();
body.kind = "delete";
body.detail1 = start_index;
body.detail2 = length;
body.any_data = content.into();
self.emit_event(target, interface, signal, body).await
}
ObjectEvent::TextSelectionChanged => {
self.emit_event(target, interface, signal, EventBodyBorrowed::default())
.await
}
}
}
pub(crate) async fn emit_window_event(
&self,
adapter_id: usize,
target: NodeId,
window_name: String,
event: WindowEvent,
) -> Result<()> {
let target = ObjectId::Node {
adapter: adapter_id,
node: target,
};
let signal = match event {
WindowEvent::Activated => "Activate",
WindowEvent::Deactivated => "Deactivate",
};
let mut body = EventBodyBorrowed::default();
body.any_data = window_name.into();
self.emit_event(target, "org.a11y.atspi.Event.Window", signal, body)
.await
}
pub(crate) async fn emit_cache_add(&self, node: PlatformNode) -> Result<()> {
let Ok(item) = cache_item_for_node(self.unique_name().inner(), &node) else {
return Ok(());
};
self.emit_cache_signal("AddAccessible", &item).await
}
pub(crate) async fn emit_cache_remove(&self, adapter_id: usize, node_id: NodeId) -> Result<()> {
let reference = object_ref(
self.unique_name().inner(),
ObjectId::Node {
adapter: adapter_id,
node: node_id,
},
);
self.emit_cache_signal("RemoveAccessible", &reference).await
}
async fn emit_cache_signal<B>(&self, signal_name: &str, body: &B) -> Result<()>
where
B: serde::Serialize + zbus::wire::DynamicType,
{
map_or_ignoring_recoverable_error(
self.conn
.emit_signal(
Option::<BusName>::None,
cache_path(),
InterfaceName::from_str_unchecked("org.a11y.atspi.Cache"),
MemberName::from_str_unchecked(signal_name),
body,
)
.await,
(),
|_| (),
)
}
async fn emit_event(
&self,
target: ObjectId,
interface: &str,
signal_name: &str,
body: EventBodyBorrowed<'_>,
) -> Result<()> {
map_or_ignoring_recoverable_error(
self.conn
.emit_signal(
Option::<BusName>::None,
target.path(),
InterfaceName::from_str_unchecked(interface),
MemberName::from_str_unchecked(signal_name),
&body,
)
.await,
(),
|_| (),
)
}
}
pub(crate) fn zbus_error_is_unrecoverable(error: &zbus::Error) -> bool {
matches!(
error,
zbus::Error::InterfaceExists(..) | zbus::Error::MissingParameter(..)
)
}
pub(crate) fn map_or_ignoring_recoverable_error<T, U, F>(
result: zbus::Result<T>,
default: U,
f: F,
) -> zbus::Result<U>
where
F: FnOnce(T) -> U,
{
match result {
Ok(result) => Ok(f(result)),
Err(error) if zbus_error_is_unrecoverable(&error) => Err(error),
Err(_) => Ok(default),
}
}

View file

@ -0,0 +1,246 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use std::{
collections::HashMap,
sync::{Arc, OnceLock},
};
use accesskit_atspi_common::{NodeIdOrRoot, PlatformNode, PlatformRoot};
use atspi::{InterfaceSet, ObjectRefOwned, RelationType, Role, StateSet};
use zbus::{fdo, interface, names::OwnedUniqueName};
use super::map_root_error;
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct NodeAccessibleInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl NodeAccessibleInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Accessible")]
impl NodeAccessibleInterface {
#[zbus(property)]
fn name(&self) -> fdo::Result<String> {
self.node.name().map_err(self.map_error())
}
#[zbus(property)]
fn description(&self) -> fdo::Result<String> {
self.node.description().map_err(self.map_error())
}
#[zbus(property)]
fn parent(&self) -> fdo::Result<OwnedObjectAddress> {
self.node.parent().map_err(self.map_error()).map(|parent| {
match parent {
NodeIdOrRoot::Node(node) => ObjectId::Node {
adapter: self.node.adapter_id(),
node,
},
NodeIdOrRoot::Root => ObjectId::Root,
}
.to_address(self.bus_name.inner())
})
}
#[zbus(property)]
fn child_count(&self) -> fdo::Result<i32> {
self.node.child_count().map_err(self.map_error())
}
#[zbus(property)]
fn locale(&self) -> &str {
""
}
#[zbus(property)]
fn accessible_id(&self) -> fdo::Result<String> {
self.node.accessible_id().map_err(self.map_error())
}
fn get_child_at_index(&self, index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let index = index
.try_into()
.map_err(|_| fdo::Error::InvalidArgs("Index can't be negative.".into()))?;
let child = self
.node
.child_at_index(index)
.map_err(self.map_error())?
.map(|child| ObjectId::Node {
adapter: self.node.adapter_id(),
node: child,
});
Ok(super::optional_object_address(&self.bus_name, child))
}
fn get_children(&self) -> fdo::Result<Vec<OwnedObjectAddress>> {
self.node
.map_children(|child| {
ObjectId::Node {
adapter: self.node.adapter_id(),
node: child,
}
.to_address(self.bus_name.inner())
})
.map_err(self.map_error())
}
fn get_index_in_parent(&self) -> fdo::Result<i32> {
self.node.index_in_parent().map_err(self.map_error())
}
fn get_relation_set(&self) -> fdo::Result<Vec<(RelationType, Vec<OwnedObjectAddress>)>> {
self.node
.relation_set(|relation| {
ObjectId::Node {
adapter: self.node.adapter_id(),
node: relation,
}
.to_address(self.bus_name.inner())
})
.map(|set| {
set.into_iter()
.collect::<Vec<(RelationType, Vec<OwnedObjectAddress>)>>()
})
.map_err(self.map_error())
}
fn get_role(&self) -> fdo::Result<Role> {
self.node.role().map_err(self.map_error())
}
fn get_localized_role_name(&self) -> fdo::Result<String> {
self.node.localized_role_name().map_err(self.map_error())
}
fn get_state(&self) -> StateSet {
self.node.state()
}
fn get_attributes(&self) -> fdo::Result<HashMap<&str, String>> {
self.node.attributes().map_err(self.map_error())
}
fn get_application(&self) -> (OwnedObjectAddress,) {
(ObjectId::Root.to_address(self.bus_name.inner()),)
}
fn get_interfaces(&self) -> fdo::Result<InterfaceSet> {
self.node.interfaces().map_err(self.map_error())
}
}
pub(crate) struct RootAccessibleInterface {
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
}
impl RootAccessibleInterface {
pub fn new(
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
) -> Self {
Self {
bus_name,
root,
desktop,
}
}
}
#[interface(name = "org.a11y.atspi.Accessible")]
impl RootAccessibleInterface {
#[zbus(property)]
fn name(&self) -> fdo::Result<String> {
self.root.name().map_err(map_root_error)
}
#[zbus(property)]
fn description(&self) -> fdo::Result<String> {
self.root.description().map_err(map_root_error)
}
#[zbus(property)]
fn parent(&self) -> OwnedObjectAddress {
self.desktop
.get()
.cloned()
.unwrap_or_default()
.into_inner()
.into()
}
#[zbus(property)]
fn child_count(&self) -> fdo::Result<i32> {
self.root.child_count().map_err(map_root_error)
}
#[zbus(property)]
fn locale(&self) -> &str {
""
}
#[zbus(property)]
fn accessible_id(&self) -> &str {
""
}
fn get_child_at_index(&self, index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let index = index
.try_into()
.map_err(|_| fdo::Error::InvalidArgs("Index can't be negative.".into()))?;
let child = self
.root
.child_id_at_index(index)
.map_err(map_root_error)?
.map(|(adapter, node)| ObjectId::Node { adapter, node });
Ok(super::optional_object_address(&self.bus_name, child))
}
fn get_children(&self) -> fdo::Result<Vec<OwnedObjectAddress>> {
self.root
.map_child_ids(|(adapter, node)| {
ObjectId::Node { adapter, node }.to_address(self.bus_name.inner())
})
.map_err(map_root_error)
}
fn get_index_in_parent(&self) -> i32 {
self.root.index_in_parent()
}
fn get_relation_set(&self) -> Vec<(RelationType, Vec<OwnedObjectAddress>)> {
Vec::new()
}
fn get_role(&self) -> Role {
self.root.role()
}
fn get_state(&self) -> StateSet {
self.root.state()
}
fn get_application(&self) -> (OwnedObjectAddress,) {
(ObjectId::Root.to_address(self.bus_name.inner()),)
}
fn get_interfaces(&self) -> InterfaceSet {
self.root.interfaces()
}
}

View file

@ -0,0 +1,51 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{Action, PlatformNode};
use zbus::{fdo, interface};
pub(crate) struct ActionInterface(PlatformNode);
impl ActionInterface {
pub fn new(node: PlatformNode) -> Self {
Self(node)
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.0, error)
}
}
#[interface(name = "org.a11y.atspi.Action")]
impl ActionInterface {
#[zbus(property)]
fn n_actions(&self) -> fdo::Result<i32> {
self.0.n_actions().map_err(self.map_error())
}
fn get_description(&self, _index: i32) -> &str {
""
}
fn get_name(&self, index: i32) -> fdo::Result<String> {
self.0.action_name(index).map_err(self.map_error())
}
fn get_localized_name(&self, index: i32) -> fdo::Result<String> {
self.0.action_name(index).map_err(self.map_error())
}
fn get_key_binding(&self, _index: i32) -> &str {
""
}
fn get_actions(&self) -> fdo::Result<Vec<Action>> {
self.0.actions().map_err(self.map_error())
}
fn do_action(&self, index: i32) -> fdo::Result<bool> {
self.0.do_action(index).map_err(self.map_error())
}
}

View file

@ -0,0 +1,39 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformRoot;
use zbus::{fdo, interface};
use super::map_root_error;
pub(crate) struct ApplicationInterface(pub PlatformRoot);
#[interface(name = "org.a11y.atspi.Application")]
impl ApplicationInterface {
#[zbus(property)]
fn toolkit_name(&self) -> fdo::Result<String> {
self.0.toolkit_name().map_err(map_root_error)
}
#[zbus(property)]
fn version(&self) -> fdo::Result<String> {
self.0.toolkit_version().map_err(map_root_error)
}
#[zbus(property)]
fn atspi_version(&self) -> &str {
"2.1"
}
#[zbus(property)]
fn id(&self) -> fdo::Result<i32> {
self.0.id().map_err(map_root_error)
}
#[zbus(property)]
fn set_id(&mut self, id: i32) -> fdo::Result<()> {
self.0.set_id(id).map_err(map_root_error)
}
}

View file

@ -0,0 +1,314 @@
// Copyright 2026 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{CacheNode, Error, NodeIdOrRoot, PlatformNode, PlatformRoot};
use atspi::{CacheItem, ObjectRef, ObjectRefOwned};
use std::sync::{Arc, OnceLock};
use zbus::{
fdo, interface,
names::{OwnedUniqueName, UniqueName},
};
use super::map_root_error;
use crate::atspi::ObjectId;
pub(crate) fn object_ref(bus_name: &UniqueName, id: ObjectId) -> ObjectRefOwned {
ObjectRef::new_owned(bus_name.to_owned(), id.path())
}
pub(crate) fn cache_item_for_node(
bus_name: &UniqueName,
node: &PlatformNode,
) -> Result<CacheItem, Error> {
Ok(cache_item(bus_name, node.cache_node()?))
}
fn cache_item(bus_name: &UniqueName, node: CacheNode) -> CacheItem {
let parent = match node.parent {
NodeIdOrRoot::Root => ObjectId::Root,
NodeIdOrRoot::Node(node_id) => ObjectId::Node {
adapter: node.adapter_id,
node: node_id,
},
};
CacheItem {
object: object_ref(
bus_name,
ObjectId::Node {
adapter: node.adapter_id,
node: node.id,
},
),
app: object_ref(bus_name, ObjectId::Root),
parent: object_ref(bus_name, parent),
index: node.index_in_parent,
children: node.child_count,
ifaces: node.interfaces,
short_name: node.name,
role: node.role,
name: node.description,
states: node.states,
}
}
fn application_cache_item(
bus_name: &UniqueName,
root: &PlatformRoot,
desktop: ObjectRefOwned,
) -> Result<CacheItem, Error> {
Ok(CacheItem {
object: object_ref(bus_name, ObjectId::Root),
app: object_ref(bus_name, ObjectId::Root),
parent: desktop,
index: root.index_in_parent(),
children: root.child_count()?,
ifaces: root.interfaces(),
short_name: root.name()?,
role: root.role(),
name: root.description()?,
states: root.state(),
})
}
pub(crate) struct CacheInterface {
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
}
impl CacheInterface {
pub fn new(
bus_name: OwnedUniqueName,
root: PlatformRoot,
desktop: Arc<OnceLock<ObjectRefOwned>>,
) -> Self {
Self {
bus_name,
root,
desktop,
}
}
fn items(&self) -> Result<Vec<CacheItem>, Error> {
let bus_name = self.bus_name.inner();
let descendants: Vec<CacheItem> = self
.root
.map_descendant_cache_nodes(|node| cache_item(bus_name, node))?;
let desktop = self.desktop.get().cloned().unwrap_or_default();
let mut items = Vec::with_capacity(descendants.len() + 1);
items.push(application_cache_item(bus_name, &self.root, desktop)?);
items.extend(descendants);
Ok(items)
}
}
#[interface(name = "org.a11y.atspi.Cache")]
impl CacheInterface {
fn get_items(&self) -> fdo::Result<Vec<CacheItem>> {
self.items().map_err(map_root_error)
}
}
#[cfg(test)]
mod tests {
use super::{CacheInterface, object_ref};
use crate::atspi::ObjectId;
use accesskit::{
ActionHandler, ActionRequest, Node, NodeId as LocalNodeId, Role, Tree, TreeId, TreeUpdate,
};
use accesskit_atspi_common::{
Adapter, AdapterCallback, AppContext, Event, NodeId, PlatformRoot, WindowBounds,
};
use atspi::{Interface, ObjectRefOwned, Role as AtspiRole};
use std::sync::{Arc, OnceLock};
use zbus::names::{OwnedUniqueName, UniqueName};
struct NoOpActionHandler;
impl ActionHandler for NoOpActionHandler {
fn do_action(&mut self, _request: ActionRequest) {}
}
struct NoOpCallback;
impl AdapterCallback for NoOpCallback {
fn register_interfaces(&self, _: &Adapter, _: NodeId, _: atspi::InterfaceSet) {}
fn unregister_interfaces(&self, _: &Adapter, _: NodeId, _: atspi::InterfaceSet) {}
fn emit_event(&self, _: &Adapter, _: Event) {}
}
fn with_children(role: Role, children: &[LocalNodeId]) -> Node {
let mut node = Node::new(role);
node.set_children(children.to_vec());
node
}
const BUS_NAME: &str = ":1.0";
fn root_for(update: TreeUpdate) -> (Adapter, PlatformRoot) {
let app_context = AppContext::new(None);
let adapter = Adapter::new(
&app_context,
NoOpCallback,
update,
false,
WindowBounds::default(),
NoOpActionHandler,
);
let root = adapter.platform_root();
(adapter, root)
}
fn bus_name() -> OwnedUniqueName {
OwnedUniqueName::try_from(BUS_NAME).unwrap()
}
fn cache(update: TreeUpdate) -> (Adapter, CacheInterface) {
let (adapter, root) = root_for(update);
let desktop = Arc::new(OnceLock::new());
desktop.set(desktop_ref()).unwrap();
(adapter, CacheInterface::new(bus_name(), root, desktop))
}
fn window_with_button() -> TreeUpdate {
TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1)]),
),
(LocalNodeId(1), Node::new(Role::Button)),
],
tree: Some(Tree::new(LocalNodeId(0))),
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
}
}
fn root_ref() -> ObjectRefOwned {
object_ref(
&UniqueName::from_static_str_unchecked(BUS_NAME),
ObjectId::Root,
)
}
fn desktop_ref() -> ObjectRefOwned {
ObjectRefOwned::from_static_str_unchecked(":1.1", "/org/a11y/atspi/accessible/root")
}
#[test]
fn get_items_prepends_application_root() {
let (_adapter, iface) = cache(window_with_button());
let items = iface.items().unwrap();
let [app, _window, _button] = items.as_slice() else {
panic!("expected application root, window, and button");
};
assert_eq!(app.object, root_ref());
assert_eq!(app.app, root_ref());
assert_eq!(app.parent, desktop_ref());
assert_eq!(app.index, -1);
assert_eq!(app.children, 1);
assert_eq!(app.role, AtspiRole::Application);
assert!(app.ifaces.contains(Interface::Application));
}
#[test]
fn top_window_parent_is_application_root() {
let (_adapter, iface) = cache(window_with_button());
let items = iface.items().unwrap();
let [_app, window, _button] = items.as_slice() else {
panic!("expected application root, window, and button");
};
assert_eq!(window.parent, root_ref());
assert_eq!(window.index, 0);
assert!(
window
.object
.path_as_str()
.starts_with("/org/a11y/atspi/accessible/")
);
assert_eq!(window.object.name_as_str(), Some(BUS_NAME));
}
#[test]
fn filtered_child_excluded_from_items_and_counts() {
let mut hidden = Node::new(Role::Button);
hidden.set_hidden();
let update = TreeUpdate {
nodes: vec![
(
LocalNodeId(0),
with_children(Role::Window, &[LocalNodeId(1), LocalNodeId(2)]),
),
(LocalNodeId(1), Node::new(Role::Button)),
(LocalNodeId(2), hidden),
],
tree: Some(Tree::new(LocalNodeId(0))),
tree_id: TreeId::ROOT,
focus: LocalNodeId(0),
};
let (_adapter, iface) = cache(update);
let items = iface.items().unwrap();
let [app_root, window, _visible_button] = items.as_slice() else {
panic!("expected application root, window, and visible button only");
};
assert_eq!(app_root.children, 1);
assert_eq!(window.children, 1);
}
#[test]
fn object_ref_encodes_bus_name_and_node_path() {
let (_adapter, root) = root_for(window_with_button());
let (adapter_id, node_id) = root.child_id_at_index(0).unwrap().unwrap();
let expected_path = ObjectId::Node {
adapter: adapter_id,
node: node_id,
}
.path();
let reference = object_ref(
&UniqueName::from_static_str_unchecked(BUS_NAME),
ObjectId::Node {
adapter: adapter_id,
node: node_id,
},
);
assert_eq!(reference.name_as_str(), Some(BUS_NAME));
assert_eq!(reference.path_as_str(), expected_path.as_str());
}
#[test]
fn multi_adapter_windows_have_distinct_indices() {
let app_context = AppContext::new(None);
let _a0 = Adapter::new(
&app_context,
NoOpCallback,
window_with_button(),
false,
WindowBounds::default(),
NoOpActionHandler,
);
let _a1 = Adapter::new(
&app_context,
NoOpCallback,
window_with_button(),
false,
WindowBounds::default(),
NoOpActionHandler,
);
let iface = CacheInterface::new(
bus_name(),
PlatformRoot::new(&app_context),
Arc::new(OnceLock::new()),
);
let items = iface.items().unwrap();
let app_root = &items[0];
assert_eq!(app_root.children, 2);
let windows = items.iter().filter(|item| item.parent == root_ref());
let mut window_indices: Vec<i32> = windows.map(|item| item.index).collect();
window_indices.sort();
assert_eq!(window_indices, vec![0, 1]);
}
}

View file

@ -0,0 +1,76 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{PlatformNode, Rect};
use atspi::{CoordType, Layer, ScrollType};
use zbus::{fdo, interface, names::OwnedUniqueName};
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct ComponentInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl ComponentInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Component")]
impl ComponentInterface {
fn contains(&self, x: i32, y: i32, coord_type: CoordType) -> fdo::Result<bool> {
self.node
.contains(x, y, coord_type)
.map_err(self.map_error())
}
fn get_accessible_at_point(
&self,
x: i32,
y: i32,
coord_type: CoordType,
) -> fdo::Result<(OwnedObjectAddress,)> {
let accessible = self
.node
.accessible_at_point(x, y, coord_type)
.map_err(self.map_error())?
.map(|node| ObjectId::Node {
adapter: self.node.adapter_id(),
node,
});
Ok(super::optional_object_address(&self.bus_name, accessible))
}
fn get_extents(&self, coord_type: CoordType) -> fdo::Result<(Rect,)> {
self.node
.extents(coord_type)
.map(|rect| (rect,))
.map_err(self.map_error())
}
fn get_layer(&self) -> fdo::Result<Layer> {
self.node.layer().map_err(self.map_error())
}
fn grab_focus(&self) -> fdo::Result<bool> {
self.node.grab_focus().map_err(self.map_error())
}
fn scroll_to(&self, scroll_type: ScrollType) -> fdo::Result<bool> {
self.node.scroll_to(scroll_type).map_err(self.map_error())
}
fn scroll_to_point(&self, coord_type: CoordType, x: i32, y: i32) -> fdo::Result<bool> {
self.node
.scroll_to_point(coord_type, x, y)
.map_err(self.map_error())
}
}

View file

@ -0,0 +1,63 @@
// Copyright 2026 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformNode;
use zbus::{fdo, interface, names::OwnedUniqueName};
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct HyperlinkInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl HyperlinkInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Hyperlink")]
impl HyperlinkInterface {
#[zbus(property)]
fn n_anchors(&self) -> fdo::Result<i32> {
self.node.n_anchors().map_err(self.map_error())
}
#[zbus(property)]
fn start_index(&self) -> fdo::Result<i32> {
self.node.hyperlink_start_index().map_err(self.map_error())
}
#[zbus(property)]
fn end_index(&self) -> fdo::Result<i32> {
self.node.hyperlink_end_index().map_err(self.map_error())
}
fn get_object(&self, index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let object = self
.node
.hyperlink_object(index)
.map_err(self.map_error())?
.map(|node| ObjectId::Node {
adapter: self.node.adapter_id(),
node,
});
Ok(super::optional_object_address(&self.bus_name, object))
}
#[zbus(name = "GetURI")]
fn get_uri(&self, index: i32) -> fdo::Result<String> {
self.node.uri(index).map_err(self.map_error())
}
fn is_valid(&self) -> fdo::Result<bool> {
self.node.hyperlink_is_valid().map_err(self.map_error())
}
}

View file

@ -0,0 +1,41 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
mod accessible;
mod action;
mod application;
mod cache;
mod component;
mod hyperlink;
mod selection;
mod text;
mod value;
use crate::atspi::{ObjectId, OwnedObjectAddress};
use zbus::{fdo, names::UniqueName};
fn map_root_error(error: accesskit_atspi_common::Error) -> fdo::Error {
crate::util::map_error(ObjectId::Root, error)
}
fn optional_object_address(
bus_name: &UniqueName,
object_id: Option<ObjectId>,
) -> (OwnedObjectAddress,) {
match object_id {
Some(id) => (id.to_address(bus_name),),
None => (OwnedObjectAddress::null(),),
}
}
pub(crate) use accessible::*;
pub(crate) use action::*;
pub(crate) use application::*;
pub(crate) use cache::*;
pub(crate) use component::*;
pub(crate) use hyperlink::*;
pub(crate) use selection::*;
pub(crate) use text::*;
pub(crate) use value::*;

View file

@ -0,0 +1,82 @@
// Copyright 2024 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformNode;
use zbus::{fdo, interface, names::OwnedUniqueName};
use crate::atspi::{ObjectId, OwnedObjectAddress};
pub(crate) struct SelectionInterface {
bus_name: OwnedUniqueName,
node: PlatformNode,
}
impl SelectionInterface {
pub fn new(bus_name: OwnedUniqueName, node: PlatformNode) -> Self {
Self { bus_name, node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Selection")]
impl SelectionInterface {
#[zbus(property)]
fn n_selected_children(&self) -> fdo::Result<i32> {
self.node.n_selected_children().map_err(self.map_error())
}
fn get_selected_child(&self, selected_child_index: i32) -> fdo::Result<(OwnedObjectAddress,)> {
let child = self
.node
.selected_child(map_child_index(selected_child_index)?)
.map_err(self.map_error())?
.map(|child| ObjectId::Node {
adapter: self.node.adapter_id(),
node: child,
});
Ok(super::optional_object_address(&self.bus_name, child))
}
fn select_child(&self, child_index: i32) -> fdo::Result<bool> {
self.node
.select_child(map_child_index(child_index)?)
.map_err(self.map_error())
}
fn deselect_selected_child(&self, selected_child_index: i32) -> fdo::Result<bool> {
self.node
.deselect_selected_child(map_child_index(selected_child_index)?)
.map_err(self.map_error())
}
fn is_child_selected(&self, child_index: i32) -> fdo::Result<bool> {
self.node
.is_child_selected(map_child_index(child_index)?)
.map_err(self.map_error())
}
fn select_all(&self) -> fdo::Result<bool> {
self.node.select_all().map_err(self.map_error())
}
fn clear_selection(&self) -> fdo::Result<bool> {
self.node.clear_selection().map_err(self.map_error())
}
fn deselect_child(&self, child_index: i32) -> fdo::Result<bool> {
self.node
.deselect_child(map_child_index(child_index)?)
.map_err(self.map_error())
}
}
fn map_child_index(index: i32) -> fdo::Result<usize> {
index
.try_into()
.map_err(|_| fdo::Error::InvalidArgs("Index can't be negative.".into()))
}

View file

@ -0,0 +1,163 @@
// Copyright 2024 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{PlatformNode, Rect};
use atspi::{CoordType, Granularity, ScrollType};
use std::collections::HashMap;
use zbus::{fdo, interface};
pub(crate) struct TextInterface {
node: PlatformNode,
}
impl TextInterface {
pub fn new(node: PlatformNode) -> Self {
Self { node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Text")]
impl TextInterface {
#[zbus(property)]
fn character_count(&self) -> fdo::Result<i32> {
self.node.character_count().map_err(self.map_error())
}
#[zbus(property)]
fn caret_offset(&self) -> fdo::Result<i32> {
self.node.caret_offset().map_err(self.map_error())
}
fn get_string_at_offset(
&self,
offset: i32,
granularity: Granularity,
) -> fdo::Result<(String, i32, i32)> {
self.node
.string_at_offset(offset, granularity)
.map_err(self.map_error())
}
fn get_text(&self, start_offset: i32, end_offset: i32) -> fdo::Result<String> {
self.node
.text(start_offset, end_offset)
.map_err(self.map_error())
}
fn set_caret_offset(&self, offset: i32) -> fdo::Result<bool> {
self.node.set_caret_offset(offset).map_err(self.map_error())
}
fn get_attribute_value(&self, offset: i32, attribute_name: &str) -> fdo::Result<String> {
self.node
.text_attribute_value(offset, attribute_name)
.map_err(self.map_error())
}
fn get_attributes(
&self,
offset: i32,
) -> fdo::Result<(HashMap<&'static str, String>, i32, i32)> {
self.node.text_attributes(offset).map_err(self.map_error())
}
fn get_default_attributes(&self) -> fdo::Result<HashMap<&'static str, String>> {
self.node
.default_text_attributes()
.map_err(self.map_error())
}
fn get_character_extents(&self, offset: i32, coord_type: CoordType) -> fdo::Result<Rect> {
self.node
.character_extents(offset, coord_type)
.map_err(self.map_error())
}
fn get_offset_at_point(&self, x: i32, y: i32, coord_type: CoordType) -> fdo::Result<i32> {
self.node
.offset_at_point(x, y, coord_type)
.map_err(self.map_error())
}
fn get_n_selections(&self) -> fdo::Result<i32> {
self.node.n_selections().map_err(self.map_error())
}
fn get_selection(&self, selection_num: i32) -> fdo::Result<(i32, i32)> {
self.node.selection(selection_num).map_err(self.map_error())
}
fn add_selection(&self, start_offset: i32, end_offset: i32) -> fdo::Result<bool> {
self.node
.add_selection(start_offset, end_offset)
.map_err(self.map_error())
}
fn remove_selection(&self, selection_num: i32) -> fdo::Result<bool> {
self.node
.remove_selection(selection_num)
.map_err(self.map_error())
}
fn set_selection(
&self,
selection_num: i32,
start_offset: i32,
end_offset: i32,
) -> fdo::Result<bool> {
self.node
.set_selection(selection_num, start_offset, end_offset)
.map_err(self.map_error())
}
fn get_range_extents(
&self,
start_offset: i32,
end_offset: i32,
coord_type: CoordType,
) -> fdo::Result<Rect> {
self.node
.range_extents(start_offset, end_offset, coord_type)
.map_err(self.map_error())
}
fn get_attribute_run(
&self,
offset: i32,
include_defaults: bool,
) -> fdo::Result<(HashMap<&'static str, String>, i32, i32)> {
self.node
.text_attribute_run(offset, include_defaults)
.map_err(self.map_error())
}
fn scroll_substring_to(
&self,
start_offset: i32,
end_offset: i32,
scroll_type: ScrollType,
) -> fdo::Result<bool> {
self.node
.scroll_substring_to(start_offset, end_offset, scroll_type)
.map_err(self.map_error())
}
fn scroll_substring_to_point(
&self,
start_offset: i32,
end_offset: i32,
coord_type: CoordType,
x: i32,
y: i32,
) -> fdo::Result<bool> {
self.node
.scroll_substring_to_point(start_offset, end_offset, coord_type, x, y)
.map_err(self.map_error())
}
}

View file

@ -0,0 +1,49 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::PlatformNode;
use zbus::{fdo, interface};
pub(crate) struct ValueInterface {
node: PlatformNode,
}
impl ValueInterface {
pub fn new(node: PlatformNode) -> Self {
Self { node }
}
fn map_error(&self) -> impl '_ + FnOnce(accesskit_atspi_common::Error) -> fdo::Error {
|error| crate::util::map_error_from_node(&self.node, error)
}
}
#[interface(name = "org.a11y.atspi.Value")]
impl ValueInterface {
#[zbus(property)]
fn minimum_value(&self) -> fdo::Result<f64> {
self.node.minimum_value().map_err(self.map_error())
}
#[zbus(property)]
fn maximum_value(&self) -> fdo::Result<f64> {
self.node.maximum_value().map_err(self.map_error())
}
#[zbus(property)]
fn minimum_increment(&self) -> fdo::Result<f64> {
self.node.minimum_increment().map_err(self.map_error())
}
#[zbus(property)]
fn current_value(&self) -> fdo::Result<f64> {
self.node.current_value().map_err(self.map_error())
}
#[zbus(property)]
fn set_current_value(&mut self, value: f64) -> fdo::Result<()> {
self.node.set_current_value(value).map_err(self.map_error())
}
}

13
patches/accesskit_unix/src/atspi/mod.rs vendored Normal file
View file

@ -0,0 +1,13 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
mod bus;
pub(crate) mod interfaces;
mod object_address;
mod object_id;
pub(crate) use bus::*;
pub(crate) use object_address::OwnedObjectAddress;
pub(crate) use object_id::{ObjectId, cache_path};

View file

@ -0,0 +1,45 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use atspi::ObjectRef;
use serde::{Deserialize, Serialize};
use zbus::{
names::UniqueName,
wire::{ObjectPath, OwnedObjectPath, OwnedVariant as OwnedValue, Type, Variant as Value},
};
// https://gnome.pages.gitlab.gnome.org/at-spi2-core/libatspi/const.DBUS_PATH_NULL.html
const NULL_PATH: &str = "/org/a11y/atspi/null";
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, OwnedValue, Type, Value)]
pub(crate) struct OwnedObjectAddress {
bus_name: String,
path: OwnedObjectPath,
}
impl OwnedObjectAddress {
pub(crate) fn new(bus_name: &UniqueName, path: OwnedObjectPath) -> Self {
Self {
bus_name: bus_name.to_string(),
path,
}
}
pub(crate) fn null() -> Self {
Self {
bus_name: String::new(),
path: ObjectPath::from_str_unchecked(NULL_PATH).into(),
}
}
}
impl<'a> From<ObjectRef<'a>> for OwnedObjectAddress {
fn from(object: ObjectRef<'a>) -> Self {
Self {
bus_name: object.name().map(|s| s.to_string()).unwrap_or_default(),
path: object.path().to_owned().into(),
}
}
}

View file

@ -0,0 +1,79 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use crate::atspi::OwnedObjectAddress;
use accesskit_atspi_common::{NodeId, PlatformNode};
use serde::{Serialize, Serializer};
use zbus::{
names::UniqueName,
wire::{ObjectPath, OwnedObjectPath, Signature, Structure, Type},
};
const ACCESSIBLE_PATH_PREFIX: &str = "/org/a11y/atspi/accessible/";
const ROOT_PATH: &str = "/org/a11y/atspi/accessible/root";
const CACHE_PATH: &str = "/org/a11y/atspi/cache";
pub(crate) fn cache_path() -> OwnedObjectPath {
ObjectPath::from_str_unchecked(CACHE_PATH).into()
}
#[derive(Debug, PartialEq)]
pub(crate) enum ObjectId {
Root,
Node { adapter: usize, node: NodeId },
}
impl ObjectId {
pub(crate) fn to_address(&self, bus_name: &UniqueName) -> OwnedObjectAddress {
OwnedObjectAddress::new(bus_name, self.path())
}
pub(crate) fn path(&self) -> OwnedObjectPath {
match self {
Self::Root => ObjectPath::from_str_unchecked(ROOT_PATH),
Self::Node { adapter, node } => ObjectPath::from_string_unchecked(format!(
"{}{}/{}",
ACCESSIBLE_PATH_PREFIX,
adapter,
u128::from(*node)
)),
}
.into()
}
}
impl Serialize for ObjectId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Root => serializer.serialize_str("root"),
Self::Node { node, .. } => serializer.serialize_str(&u128::from(*node).to_string()),
}
}
}
impl Type for ObjectId {
const SIGNATURE: &'static Signature = <&str>::SIGNATURE;
}
impl From<ObjectId> for Structure<'_> {
fn from(id: ObjectId) -> Self {
Self::from((match id {
ObjectId::Root => "root".into(),
ObjectId::Node { node, .. } => u128::from(node).to_string(),
},))
}
}
impl From<&PlatformNode> for ObjectId {
fn from(node: &PlatformNode) -> Self {
Self::Node {
adapter: node.adapter_id(),
node: node.id(),
}
}
}

283
patches/accesskit_unix/src/context.rs vendored Normal file
View file

@ -0,0 +1,283 @@
// Copyright 2023 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit::{ActivationHandler, DeactivationHandler};
use accesskit_atspi_common::{Adapter as AdapterImpl, AppContext, Event};
#[cfg(not(feature = "tokio"))]
use async_channel::{Receiver, Sender};
use atspi::proxy::bus::StatusProxy;
#[cfg(not(feature = "tokio"))]
use futures_util::{StreamExt, pin_mut as pin, select};
use std::{
sync::{Arc, Mutex, OnceLock, RwLock},
thread,
};
#[cfg(feature = "tokio")]
use tokio::{
pin, select,
sync::mpsc::{UnboundedReceiver as Receiver, UnboundedSender as Sender},
};
#[cfg(feature = "tokio")]
use tokio_stream::{StreamExt, wrappers::UnboundedReceiverStream};
use zbus::{Connection, connection::Builder, proxy::PropertyChanged};
use crate::{
adapter::{AdapterState, Callback, Message},
atspi::{Bus, map_or_ignoring_recoverable_error, zbus_error_is_unrecoverable},
util::block_on,
};
static APP_CONTEXT: OnceLock<Arc<RwLock<AppContext>>> = OnceLock::new();
static MESSAGES: OnceLock<Sender<Message>> = OnceLock::new();
fn app_name() -> Option<String> {
std::env::current_exe().ok().and_then(|path| {
path.file_name()
.map(|name| name.to_string_lossy().to_string())
})
}
pub(crate) fn get_or_init_app_context<'a>() -> &'a Arc<RwLock<AppContext>> {
APP_CONTEXT.get_or_init(|| AppContext::new(app_name()))
}
pub(crate) fn get_or_init_messages() -> Sender<Message> {
MESSAGES
.get_or_init(|| {
#[cfg(not(feature = "tokio"))]
let (tx, rx) = async_channel::unbounded();
#[cfg(feature = "tokio")]
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
thread::spawn(|| {
// zbus 6's default runtime drives its connection tasks itself.
// Only this AccessKit event loop remains on our dedicated thread.
block_on(async {
if let Ok(session_bus) = Builder::session().build().await {
if let Err(error) = run_event_loop(session_bus, rx).await {
if zbus_error_is_unrecoverable(&error) {
panic!("Accessibility event loop failed: {error}");
}
}
}
})
});
tx
})
.clone()
}
struct AdapterEntry {
id: usize,
activation_handler: Box<dyn ActivationHandler>,
deactivation_handler: Box<dyn DeactivationHandler>,
state: Arc<Mutex<AdapterState>>,
}
fn activate_adapter(entry: &mut AdapterEntry) {
let mut state = entry.state.lock().unwrap();
if let AdapterState::Inactive {
is_window_focused,
root_window_bounds,
action_handler,
} = &*state
{
*state = match entry.activation_handler.request_initial_tree() {
Some(initial_state) => {
let r#impl = AdapterImpl::with_wrapped_action_handler(
entry.id,
get_or_init_app_context(),
Callback::new(),
initial_state,
*is_window_focused,
*root_window_bounds,
Arc::clone(action_handler),
);
AdapterState::Active(r#impl)
}
None => AdapterState::Pending {
is_window_focused: *is_window_focused,
root_window_bounds: *root_window_bounds,
action_handler: Arc::clone(action_handler),
},
};
}
}
fn deactivate_adapter(entry: &mut AdapterEntry) {
let mut state = entry.state.lock().unwrap();
match &*state {
AdapterState::Inactive { .. } => (),
AdapterState::Pending {
is_window_focused,
root_window_bounds,
action_handler,
} => {
*state = AdapterState::Inactive {
is_window_focused: *is_window_focused,
root_window_bounds: *root_window_bounds,
action_handler: Arc::clone(action_handler),
};
drop(state);
entry.deactivation_handler.deactivate_accessibility();
}
AdapterState::Active(r#impl) => {
*state = AdapterState::Inactive {
is_window_focused: r#impl.is_window_focused(),
root_window_bounds: r#impl.root_window_bounds(),
action_handler: r#impl.wrapped_action_handler(),
};
drop(state);
entry.deactivation_handler.deactivate_accessibility();
}
}
}
async fn bus_after_status_change(
change: Option<PropertyChanged<'_, bool>>,
session_bus: &Connection,
) -> zbus::Result<Option<Bus>> {
let enabled = match change {
Some(change) => change.get().await?,
None => false,
};
if enabled {
map_or_ignoring_recoverable_error(Bus::new(session_bus).await, None, Some)
} else {
Ok(None)
}
}
fn sync_adapters(adapters: &mut [AdapterEntry], atspi_bus: &Option<Bus>) {
let active = atspi_bus.is_some();
for entry in adapters {
if active {
activate_adapter(entry);
} else {
deactivate_adapter(entry);
}
}
}
async fn run_event_loop(
session_bus: Connection,
rx: Receiver<Message>,
) -> zbus::Result<()> {
let status = StatusProxy::new(&session_bus).await?;
let changes = status.receive_is_enabled_changed().await.fuse();
pin!(changes);
#[cfg(not(feature = "tokio"))]
let messages = rx.fuse();
#[cfg(feature = "tokio")]
let messages = UnboundedReceiverStream::new(rx).fuse();
pin!(messages);
let mut atspi_bus = None;
let mut adapters: Vec<AdapterEntry> = Vec::new();
loop {
select! {
change = changes.next() => {
atspi_bus = bus_after_status_change(change, &session_bus).await?;
sync_adapters(&mut adapters, &atspi_bus);
}
message = messages.next() => {
if let Some(message) = message {
process_adapter_message(&atspi_bus, &mut adapters, message).await?;
}
}
}
}
}
async fn process_adapter_message(
atspi_bus: &Option<Bus>,
adapters: &mut Vec<AdapterEntry>,
message: Message,
) -> zbus::Result<()> {
match message {
Message::AddAdapter {
id,
activation_handler,
deactivation_handler,
state,
} => {
adapters.push(AdapterEntry {
id,
activation_handler,
deactivation_handler,
state,
});
if atspi_bus.is_some() {
let entry = adapters.last_mut().unwrap();
activate_adapter(entry);
}
}
Message::RemoveAdapter { id } => {
if let Ok(index) = adapters.binary_search_by(|entry| entry.id.cmp(&id)) {
adapters.remove(index);
}
}
Message::RegisterInterfaces { node, interfaces } => {
if let Some(bus) = atspi_bus {
bus.register_interfaces(node, interfaces).await?
}
}
Message::UnregisterInterfaces {
adapter_id,
node_id,
interfaces,
} => {
if let Some(bus) = atspi_bus {
bus.unregister_interfaces(adapter_id, node_id, interfaces)
.await?
}
}
Message::EmitEvent {
adapter_id,
event: Event::Object { target, event },
} => {
if let Some(bus) = atspi_bus {
bus.emit_object_event(adapter_id, target, event).await?
}
}
Message::EmitEvent {
adapter_id,
event:
Event::Window {
target,
name,
event,
},
} => {
if let Some(bus) = atspi_bus {
bus.emit_window_event(adapter_id, target, name, event)
.await?;
}
}
Message::EmitEvent {
event: Event::Cache(_),
..
} => unreachable!("cache events are sent as EmitCacheAdd/EmitCacheRemove"),
Message::EmitCacheAdd { node } => {
if let Some(bus) = atspi_bus {
bus.emit_cache_add(node).await?;
}
}
Message::EmitCacheRemove {
adapter_id,
node_id,
} => {
if let Some(bus) = atspi_bus {
bus.emit_cache_remove(adapter_id, node_id).await?;
}
}
}
Ok(())
}

158
patches/accesskit_unix/src/executor.rs vendored Normal file
View file

@ -0,0 +1,158 @@
// Copyright 2024 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
// Derived from zbus.
// Copyright 2024 Zeeshan Ali Khan.
// Licensed under the MIT license (found in the LICENSE-MIT file).
#[cfg(not(feature = "tokio"))]
use async_executor::Executor as AsyncExecutor;
#[cfg(not(feature = "tokio"))]
use async_task::Task as AsyncTask;
#[cfg(feature = "tokio")]
use std::marker::PhantomData;
#[cfg(not(feature = "tokio"))]
use std::sync::Arc;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
#[cfg(feature = "tokio")]
use tokio::task::JoinHandle;
/// A wrapper around the underlying runtime/executor.
///
/// This is used to run asynchronous tasks internally and allows integration with various runtimes.
/// See [`crate::Connection::executor`] for an example of integration with external runtimes.
///
/// **Note:** You can (and should) completely ignore this type when building with `tokio` feature
/// enabled.
#[cfg(not(feature = "tokio"))]
#[derive(Debug, Clone)]
pub(crate) struct Executor<'a> {
executor: Arc<AsyncExecutor<'a>>,
}
#[cfg(feature = "tokio")]
#[derive(Debug, Clone)]
pub(crate) struct Executor<'a> {
phantom: PhantomData<&'a ()>,
}
impl Executor<'_> {
/// Spawns a task onto the executor.
pub(crate) fn spawn<T: Send + 'static>(
&self,
future: impl Future<Output = T> + Send + 'static,
#[allow(unused)] name: &str,
) -> Task<T> {
#[cfg(not(feature = "tokio"))]
{
Task(Some(self.executor.spawn(future)))
}
#[cfg(feature = "tokio")]
{
Task(Some(tokio::task::spawn(future)))
}
}
/// Create a new `Executor`.
pub(crate) fn new() -> Self {
#[cfg(not(feature = "tokio"))]
{
Self {
executor: Arc::new(AsyncExecutor::new()),
}
}
#[cfg(feature = "tokio")]
{
Self {
phantom: PhantomData,
}
}
}
/// Runs the executor until the given future completes.
///
/// With `tokio` feature enabled, it just awaits on the `future`.
pub(crate) async fn run<T>(&self, future: impl Future<Output = T>) -> T {
#[cfg(not(feature = "tokio"))]
{
self.executor.run(future).await
}
#[cfg(feature = "tokio")]
{
future.await
}
}
}
/// A wrapper around the task API of the underlying runtime/executor.
///
/// This follows the semantics of `async_task::Task` on drop:
///
/// * it will be cancelled, rather than detached. For detaching, use the `detach` method.
/// * errors from the task cancellation will will be ignored. If you need to know about task errors,
/// convert the task to a `FallibleTask` using the `fallible` method.
#[cfg(not(feature = "tokio"))]
#[derive(Debug)]
pub(crate) struct Task<T>(Option<AsyncTask<T>>);
#[cfg(feature = "tokio")]
#[derive(Debug)]
pub(crate) struct Task<T>(Option<JoinHandle<T>>);
impl<T> Task<T> {
/// Detaches the task to let it keep running in the background.
#[allow(unused_mut)]
#[allow(unused)]
pub(crate) fn detach(mut self) {
#[cfg(not(feature = "tokio"))]
{
self.0.take().expect("async_task::Task is none").detach()
}
#[cfg(feature = "tokio")]
{
self.0.take().expect("tokio::task::JoinHandle is none");
}
}
}
impl<T> Drop for Task<T> {
fn drop(&mut self) {
#[cfg(feature = "tokio")]
{
if let Some(join_handle) = self.0.take() {
join_handle.abort();
}
}
}
}
impl<T> Future for Task<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[cfg(not(feature = "tokio"))]
{
Pin::new(&mut self.get_mut().0.as_mut().expect("async_task::Task is none")).poll(cx)
}
#[cfg(feature = "tokio")]
{
Pin::new(
&mut self
.get_mut()
.0
.as_mut()
.expect("tokio::task::JoinHandle is none"),
)
.poll(cx)
.map(|r| r.expect("tokio::task::JoinHandle error"))
}
}
}

26
patches/accesskit_unix/src/lib.rs vendored Normal file
View file

@ -0,0 +1,26 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
/// ## Compatibility with async runtimes
///
/// While this crate's API is purely blocking, it internally spawns asynchronous tasks on an executor.
///
/// - If you use tokio, make sure to enable the `tokio` feature of this crate.
/// - If you use another async runtime or if you don't use one at all, the default feature will suit your needs.
#[cfg(all(not(feature = "async-io"), not(feature = "tokio")))]
compile_error!("Either \"async-io\" (default) or \"tokio\" feature must be enabled.");
#[cfg(all(feature = "async-io", feature = "tokio"))]
compile_error!(
"Both \"async-io\" (default) and \"tokio\" features cannot be enabled at the same time."
);
mod adapter;
mod atspi;
mod context;
mod util;
pub use adapter::Adapter;

42
patches/accesskit_unix/src/util.rs vendored Normal file
View file

@ -0,0 +1,42 @@
// Copyright 2022 The AccessKit Authors. All rights reserved.
// Licensed under the Apache License, Version 2.0 (found in
// the LICENSE-APACHE file) or the MIT license (found in
// the LICENSE-MIT file), at your option.
use accesskit_atspi_common::{Error as InternalError, PlatformNode};
use zbus::fdo::Error as FdoError;
use crate::atspi::ObjectId;
#[cfg(not(feature = "tokio"))]
pub(crate) fn block_on<F: std::future::Future>(future: F) -> F::Output {
futures_lite::future::block_on(future)
}
#[cfg(feature = "tokio")]
pub(crate) fn block_on<F: std::future::Future>(future: F) -> F::Output {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.build()
.expect("launch of single-threaded tokio runtime");
runtime.block_on(future)
}
pub(crate) fn map_error(source: ObjectId, error: InternalError) -> FdoError {
match error {
InternalError::Defunct | InternalError::UnsupportedInterface => {
FdoError::UnknownObject(source.path().to_string())
}
InternalError::TooManyChildren => FdoError::Failed("Too many children.".into()),
InternalError::IndexOutOfRange => FdoError::Failed("Index is too big.".into()),
InternalError::TooManyCharacters => FdoError::Failed("Too many characters.".into()),
InternalError::UnsupportedTextGranularity => {
FdoError::Failed("Unsupported text granularity.".into())
}
}
}
pub(crate) fn map_error_from_node(source: &PlatformNode, error: InternalError) -> FdoError {
map_error(ObjectId::from(source), error)
}