use std::sync::mpsc::{SendError, SyncSender, sync_channel};
use std::time::Duration;
use accesskit_android::InjectingAdapter;
use accesskit_android::jni::objects::JObject;
use accesskit_android::jni::{JNIEnv, JavaVM};
use android_activity::AndroidApp;
use platform_accesskit::accesskit::{ActionHandler, ActionRequest, ActivationHandler, TreeUpdate};
use platform_accesskit::{PublishedTree, WindowFrame};
use platform_core::{EventHandler, Window};
use winit::event_loop::EventLoopProxy;
use crate::platform::UserEvent;
pub(crate) enum AccessRequest {
InitialTree(SyncSender<TreeUpdate>),
Action(ActionRequest),
}
pub(crate) struct Accessibility {
vm: JavaVM,
adapter: InjectingAdapter,
asked: bool,
tree: PublishedTree,
}
const LOCAL_REFERENCES: i32 = 16;
const INITIAL_TREE_WAIT: Duration = Duration::from_millis(500);
impl Accessibility {
pub(crate) fn attach(app: &AndroidApp, proxy: EventLoopProxy<UserEvent>) -> Option<Self> {
if !loads_in_memory_dex() {
tracing::warn!(
"the device predates API 26 or names no level, so no screen reader can read this window"
);
return None;
}
let vm = unsafe { JavaVM::from_raw(app.vm_as_ptr().cast()) }
.inspect_err(|error| tracing::warn!(%error, "the Java VM is unreachable"))
.ok()?;
let adapter = vm
.get_env()
.and_then(|mut env| {
env.with_local_frame(LOCAL_REFERENCES, |env| {
let activity = unsafe { JObject::from_raw(app.activity_as_ptr().cast()) };
let host = decor_view(env, &activity)?;
Ok(InjectingAdapter::new(
env,
&host,
Forward(proxy.clone()),
Forward(proxy),
))
})
})
.inspect_err(|error| tracing::warn!(%error, "the activity's decor view is unreachable"))
.ok()?;
Some(Self {
vm,
adapter,
asked: false,
tree: PublishedTree::default(),
})
}
pub(crate) fn answer<W: Window>(
&mut self,
request: AccessRequest,
handler: &mut impl EventHandler<W>,
window: WindowFrame,
) {
match request {
AccessRequest::InitialTree(reader) => {
self.asked = true;
self.hand_over(handler, window, |adapter, build| {
if let Err(SendError(update)) = reader.send(build()) {
adapter.update_if_active(|| update);
}
});
}
AccessRequest::Action(request) => {
let Some((id, action)) = self.tree.requested_action(&request) else {
return;
};
handler.on_accessibility_action(id, action);
self.publish(handler, window);
}
}
}
pub(crate) fn publish<W: Window>(
&mut self,
handler: &impl EventHandler<W>,
window: WindowFrame,
) {
if !self.asked {
return;
}
self.hand_over(handler, window, |adapter, build| {
adapter.update_if_active(build)
});
}
fn hand_over<W: Window>(
&mut self,
handler: &impl EventHandler<W>,
window: WindowFrame,
deliver: impl for<'b> FnOnce(&mut InjectingAdapter, Box<dyn FnOnce() -> TreeUpdate + 'b>),
) {
let adapter = &mut self.adapter;
let tree = &mut self.tree;
let published = self.vm.get_env().and_then(|mut env| {
env.with_local_frame(LOCAL_REFERENCES, |_| {
tree.publish(
|| (handler.accessibility(), handler.root_language()),
window,
|build| deliver(adapter, build),
);
Ok::<_, accesskit_android::jni::errors::Error>(())
})
});
if let Err(error) = published {
tracing::warn!(%error, "the tree could not be published");
}
}
}
fn decor_view<'local>(
env: &mut JNIEnv<'local>,
activity: &JObject,
) -> accesskit_android::jni::errors::Result<JObject<'local>> {
let window = env
.call_method(activity, "getWindow", "()Landroid/view/Window;", &[])?
.l()?;
env.call_method(&window, "getDecorView", "()Landroid/view/View;", &[])?
.l()
}
fn loads_in_memory_dex() -> bool {
crate::sys_prop::read_sys_prop("ro.build.version.sdk")
.and_then(|level| level.parse::<u32>().ok())
.is_some_and(|level| level >= 26)
}
struct Forward(EventLoopProxy<UserEvent>);
impl ActivationHandler for Forward {
fn request_initial_tree(&mut self) -> Option<TreeUpdate> {
let (reader, tree) = sync_channel(0);
self.0
.send_event(UserEvent::Accessibility(AccessRequest::InitialTree(reader)))
.ok()?;
tree.recv_timeout(INITIAL_TREE_WAIT).ok()
}
}
impl ActionHandler for Forward {
fn do_action(&mut self, request: ActionRequest) {
let _ = self
.0
.send_event(UserEvent::Accessibility(AccessRequest::Action(request)));
}
}