use std::ffi::c_void;
use std::sync::{Mutex, PoisonError};
use jni::JNIEnv;
use jni::objects::{GlobalRef, JObject, JString};
#[derive(Default)]
struct Published {
activity: bool,
application: bool,
kept: Option<GlobalRef>,
}
static PUBLISHED: Mutex<Published> = Mutex::new(Published {
activity: false,
application: false,
kept: None,
});
fn published() -> std::sync::MutexGuard<'static, Published> {
PUBLISHED.lock().unwrap_or_else(PoisonError::into_inner)
}
unsafe fn publish_application(vm: *mut c_void, context: *mut c_void) -> bool {
let mut published = published();
if published.activity || published.application {
return false;
}
unsafe { ndk_context::initialize_android_context(vm, context) };
published.application = true;
true
}
pub unsafe fn activity_started() {
published().activity = true;
}
pub fn activity_ended() {
published().activity = false;
}
pub fn provide_application_context(
env: &mut JNIEnv<'_>,
context: &JObject<'_>,
) -> Result<bool, String> {
{
let published = published();
if published.activity || published.application {
return Ok(false);
}
}
let application = env
.call_method(
context,
"getApplicationContext",
"()Landroid/content/Context;",
&[],
)
.and_then(jni::objects::JValueGen::l)
.map_err(|error| pending_exception(env).unwrap_or_else(|| error.to_string()))?;
let application = if application.is_null() {
env.new_global_ref(context)
} else {
env.new_global_ref(&application)
}
.map_err(|error| error.to_string())?;
let vm = env.get_java_vm().map_err(|error| error.to_string())?;
let raw = application.as_obj().as_raw().cast::<c_void>();
let made = unsafe { publish_application(vm.get_java_vm_pointer().cast(), raw) };
if made {
published().kept = Some(application);
}
Ok(made)
}
const NO_CONTEXT: &str = "this process has no Android context: the app has not published its \
application's, and no activity runs";
fn context() -> Result<ndk_context::AndroidContext, String> {
let published = published();
let context = (published.activity || published.application).then(ndk_context::android_context);
drop(published);
context.ok_or_else(|| NO_CONTEXT.to_owned())
}
pub fn with_activity<T>(
f: impl FnOnce(&mut JNIEnv<'_>, &JObject<'_>) -> jni::errors::Result<T>,
) -> Result<T, String> {
let published = context()?;
let vm = unsafe { jni::JavaVM::from_raw(published.vm().cast()) }.map_err(|e| e.to_string())?;
let context = published.context().cast::<jni::sys::_jobject>();
let mut env = vm
.attach_current_thread_permanently()
.map_err(|e| e.to_string())?;
let context = unsafe { JObject::from_raw(context) };
env.with_local_frame(16, |env| {
let result = f(env, &context);
let exception = pending_exception(env);
Ok::<_, jni::errors::Error>(match result {
Ok(value) => Ok(value),
Err(jni::errors::Error::JavaException) => {
Err(exception.unwrap_or_else(|| "a Java exception was thrown".to_string()))
}
Err(error) => Err(error.to_string()),
})
})
.map_err(|e| e.to_string())?
}
pub fn pending_exception(env: &mut JNIEnv<'_>) -> Option<String> {
if !env.exception_check().unwrap_or(false) {
return None;
}
let throwable = env.exception_occurred().ok();
let _ = env.exception_clear();
let throwable = throwable?;
let mut describe = |method: &str| -> Option<String> {
let text = env
.call_method(&throwable, method, "()Ljava/lang/String;", &[])
.and_then(jni::objects::JValueGen::l);
if env.exception_check().unwrap_or(false) {
let _ = env.exception_clear();
}
let text = text.ok()?;
if text.is_null() {
return None;
}
env.get_string(&JString::from(text)).ok().map(Into::into)
};
describe("getMessage").or_else(|| describe("toString"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_application_context_stays_under_the_activity() {
let called = std::cell::Cell::new(false);
let refused = with_activity(|_, _| {
called.set(true);
Ok(())
});
assert_eq!(refused, Err(NO_CONTEXT.to_owned()));
assert!(!called.get(), "nothing runs without a context");
let (vm, application) = (std::ptr::dangling_mut::<c_void>(), std::ptr::dangling_mut());
assert!(unsafe { publish_application(vm, application) });
let activity = std::ptr::without_provenance_mut::<c_void>(16);
assert!(!unsafe { publish_application(activity, activity) });
assert_eq!(
context().map(ndk_context::AndroidContext::context),
Ok(application)
);
unsafe {
ndk_context::initialize_android_context(activity, activity);
activity_started();
}
assert_eq!(
context().map(ndk_context::AndroidContext::context),
Ok(activity)
);
activity_ended();
unsafe { ndk_context::release_android_context() };
assert_eq!(
context().map(ndk_context::AndroidContext::context),
Ok(application)
);
}
}