Skip to main content

accesskit_xplat/
lib.rs

1// Copyright 2022 The AccessKit Authors. All rights reserved.
2// Licensed under the Apache License, Version 2.0 (found in
3// the LICENSE-APACHE file).
4
5//! Cross-platform [AccessKit](github.com/AccessKit/accesskit) adapter similar to [accesskit_winit](https://docs.rs/accesskit_winit), but without depending on Winit.
6//! This allows this crate to be used with any version of Winit without needing a version of crate that matches the version of Winit
7//! that you are using (this is particularly helpful for beta or git versions of Winit that don't usually get an accesskit_winit release).
8//!
9//! **WARNING:** The AccessKit developers [have noted](https://github.com/AccessKit/accesskit/pull/656#issuecomment-3706315306) that the approaches used by both this crates and accesskit_winit may not be the
10//! optimal way to implement AccessKit, so use this crate at your own risk. But if you would otherwise be using accesskit_winit then
11//! this crate has no additional caveats (except that it requires little bit of extra boilerplate code.)
12//!
13//! ## Example usage
14//!
15//! Based on Winit `0.31.0-beta.2`'s `Window` and `WindowEvent` types but could be adapted for other versions of Winit.
16//!
17//! ```rust
18//! use accesskit::Rect;
19//! use accesskit_xplat::{Adapter, EventHandler, WindowEvent as AccessKitEvent};
20//! use raw_window_handle::HasWindowHandle;
21//! use std::sync::Arc;
22//! use winit_core::{
23//!     event::WindowEvent,
24//!     window::{Window, WindowId},
25//! };
26//!
27//! /// State of the accessibility node tree and platform adapter.
28//! pub struct AccessibilityState {
29//!     adapter: Adapter,
30//! }
31//!
32//! struct Handler {
33//!     window_id: WindowId,
34//!     // Whatever else you like here. Perhaps EventLoopProxy and/or a channel sender.
35//! }
36//! impl EventHandler for Handler {
37//!     fn handle_accesskit_event(&self, event: AccessKitEvent) {
38//!         // Your own custom event handling code
39//!     }
40//! }
41//!
42//! impl AccessibilityState {
43//!     pub fn new(window: &dyn Window) -> Self {
44//!         let window_id = window.id();
45//!         Self {
46//!             adapter: Adapter::with_combined_handler(
47//!                 // On Android, pass `&android_activity::AndroidApp` when creating the `Adapter`
48//!                 #[cfg(target_os = "android")]
49//!                 &crate::current_android_app(),
50//!                 // On all other platforms, pass `RawWindowHandle` when creating the `Adapter`
51//!                 #[cfg(not(target_os = "android"))]
52//!                 window.window_handle().unwrap().as_raw(),
53//!                 Arc::new(Handler { window_id }),
54//!             ),
55//!         }
56//!     }
57//!
58//!     /// Allows reacting to window events.
59//!     ///
60//!     /// This must be called whenever a new window event is received
61//!     /// and before it is handled by the application.
62//!     pub fn process_window_event(&mut self, window: &dyn Window, event: &WindowEvent) {
63//!         match event {
64//!             WindowEvent::Focused(is_focused) => {
65//!                 self.adapter.set_focus(*is_focused);
66//!             }
67//!             WindowEvent::Moved(_) | WindowEvent::SurfaceResized(_) => {
68//!                 let outer_position: (_, _) = window
69//!                     .outer_position()
70//!                     .unwrap_or_default()
71//!                     .cast::<f64>()
72//!                     .into();
73//!                 let outer_size: (_, _) = window.outer_size().cast::<f64>().into();
74//!                 let inner_position: (_, _) = window.surface_position().cast::<f64>().into();
75//!                 let inner_size: (_, _) = window.surface_size().cast::<f64>().into();
76//!
77//!                 self.adapter.set_window_bounds(
78//!                     Rect::from_origin_size(outer_position, outer_size),
79//!                     Rect::from_origin_size(inner_position, inner_size),
80//!                 )
81//!             }
82//!             _ => (),
83//!         }
84//!     }
85//! }
86//! ```
87//!
88//! ## Compatibility with async runtimes
89//!
90//! The following only applies on Linux/Unix:
91//!
92//! While this crate's API is purely blocking, it internally spawns asynchronous tasks on an executor.
93//!
94//! - If you use tokio, make sure to enable the `tokio` feature of this crate.
95//! - If you use another async runtime or if you don't use one at all, the default feature will suit your needs.
96
97#[cfg(all(
98    feature = "accesskit_unix",
99    any(
100        target_os = "linux",
101        target_os = "dragonfly",
102        target_os = "freebsd",
103        target_os = "netbsd",
104        target_os = "openbsd"
105    ),
106    not(feature = "async-io"),
107    not(feature = "tokio")
108))]
109compile_error!("Either \"async-io\" (default) or \"tokio\" feature must be enabled.");
110
111#[cfg(all(
112    feature = "accesskit_unix",
113    any(
114        target_os = "linux",
115        target_os = "dragonfly",
116        target_os = "freebsd",
117        target_os = "netbsd",
118        target_os = "openbsd"
119    ),
120    feature = "async-io",
121    feature = "tokio"
122))]
123compile_error!(
124    "Both \"async-io\" (default) and \"tokio\" features cannot be enabled at the same time."
125);
126
127use std::sync::Arc;
128
129use accesskit::{
130    ActionHandler, ActionRequest, ActivationHandler, DeactivationHandler, Rect, TreeUpdate,
131};
132
133#[cfg(target_os = "android")]
134use android_activity::AndroidApp;
135#[cfg(not(target_os = "android"))]
136use raw_window_handle::RawWindowHandle;
137
138mod platform_impl;
139
140#[derive(Clone, Debug, PartialEq)]
141pub enum WindowEvent {
142    InitialTreeRequested,
143    ActionRequested(ActionRequest),
144    AccessibilityDeactivated,
145}
146
147pub trait EventHandler: Send + Sync + 'static {
148    fn handle_accesskit_event(&self, event: WindowEvent);
149}
150
151#[derive(Clone)]
152struct CombinedHandler(Arc<dyn EventHandler>);
153
154impl ActivationHandler for CombinedHandler {
155    fn request_initial_tree(&mut self) -> Option<TreeUpdate> {
156        self.0
157            .handle_accesskit_event(WindowEvent::InitialTreeRequested);
158        None
159    }
160}
161impl DeactivationHandler for CombinedHandler {
162    fn deactivate_accessibility(&mut self) {
163        self.0
164            .handle_accesskit_event(WindowEvent::AccessibilityDeactivated);
165    }
166}
167impl ActionHandler for CombinedHandler {
168    fn do_action(&mut self, request: ActionRequest) {
169        self.0
170            .handle_accesskit_event(WindowEvent::ActionRequested(request));
171    }
172}
173
174pub struct Adapter {
175    inner: platform_impl::Adapter,
176}
177
178impl Adapter {
179    /// Creates a new AccessKit adapter for a winit window. This must be done
180    /// before the window is shown for the first time. This means that you must
181    /// use `WindowAttributes::with_visible` to make the window
182    /// initially invisible, then create the adapter, then show the window.
183    ///
184    /// Use this if you want to provide your own AccessKit handler callbacks
185    /// rather than dispatching requests through the winit event loop. This is
186    /// especially useful for the activation handler, because depending on
187    /// your application's architecture, implementing the handler directly may
188    /// allow you to return an initial tree synchronously, rather than requiring
189    /// some platform adapters to use a placeholder tree until you send
190    /// the first update. However, remember that each of these handlers may be
191    /// called on any thread, depending on the underlying platform adapter.
192    ///
193    /// # Panics
194    ///
195    /// Panics if the window is already visible.
196    pub fn with_split_handlers(
197        #[cfg(target_os = "android")] android_app: &AndroidApp,
198        #[cfg(not(target_os = "android"))] window_handle: RawWindowHandle,
199        activation_handler: impl 'static + ActivationHandler + Send,
200        action_handler: impl 'static + ActionHandler + Send,
201        deactivation_handler: impl 'static + DeactivationHandler + Send,
202    ) -> Self {
203        let inner = platform_impl::Adapter::new(
204            #[cfg(target_os = "android")]
205            android_app,
206            #[cfg(not(target_os = "android"))]
207            window_handle,
208            activation_handler,
209            action_handler,
210            deactivation_handler,
211        );
212        Self { inner }
213    }
214
215    pub fn with_combined_handler(
216        #[cfg(target_os = "android")] android_app: &AndroidApp,
217        #[cfg(not(target_os = "android"))] window_handle: RawWindowHandle,
218        handler: Arc<dyn EventHandler>,
219    ) -> Self {
220        let handler = CombinedHandler(handler);
221        let inner = platform_impl::Adapter::new(
222            #[cfg(target_os = "android")]
223            android_app,
224            #[cfg(not(target_os = "android"))]
225            window_handle,
226            handler.clone(),
227            handler.clone(),
228            handler,
229        );
230        Self { inner }
231    }
232
233    /// If and only if the tree has been initialized, call the provided function
234    /// and apply the resulting update. Note: If the caller's implementation of
235    /// [`ActivationHandler::request_initial_tree`] initially returned `None`,
236    /// then the [`TreeUpdate`] returned by the provided function must contain
237    /// a full tree.
238    pub fn update_if_active(&mut self, updater: impl FnOnce() -> TreeUpdate) {
239        self.inner.update_if_active(updater);
240    }
241
242    pub fn set_focus(&mut self, is_focused: bool) {
243        self.inner.set_focus(is_focused);
244    }
245
246    pub fn set_window_bounds(&mut self, outer_bounds: Rect, inner_bounds: Rect) {
247        self.inner.set_window_bounds(outer_bounds, inner_bounds);
248    }
249}