| 1 |
use crate::common::*; |
| 2 |
use std::io::{Error, ErrorKind}; |
| 3 |
use std::path::PathBuf; |
| 4 |
|
| 5 |
pub const USE_AUTHOR: bool = false; |
| 6 |
|
| 7 |
impl From<jni::errors::Error> for AppDirsError { |
| 8 |
fn from(error: jni::errors::Error) -> Self { |
| 9 |
AppDirsError::Io(Error::new(ErrorKind::Other, error)) |
| 10 |
} |
| 11 |
} |
| 12 |
|
| 13 |
fn get_jni_app_dir( |
| 14 |
context: &jni::objects::JObject<'_>, |
| 15 |
env: &jni::JNIEnv<'_>, |
| 16 |
method: &str, |
| 17 |
has_string_argument: bool, |
| 18 |
) -> Result<String, AppDirsError> { |
| 19 |
let dir = if has_string_argument { |
| 20 |
env.call_method( |
| 21 |
*context, |
| 22 |
method, |
| 23 |
"(Ljava/lang/String;)Ljava/io/File;", |
| 24 |
&[jni::objects::JValue::Void], |
| 25 |
) |
| 26 |
} else { |
| 27 |
env.call_method(*context, method, "()Ljava/io/File;", &[]) |
| 28 |
}?; |
| 29 |
let dir = match dir { |
| 30 |
jni::objects::JValue::Object(o) => o, |
| 31 |
_ => { |
| 32 |
return Err(AppDirsError::Io(Error::new( |
| 33 |
ErrorKind::Other, |
| 34 |
"dir is not `JObject`", |
| 35 |
))) |
| 36 |
}, |
| 37 |
}; |
| 38 |
|
| 39 |
let path_string = env.call_method(dir, "getPath", "()Ljava/lang/String;", &[])?; |
| 40 |
let path_string = match path_string { |
| 41 |
jni::objects::JValue::Object(o) => jni::objects::JString::from(o), |
| 42 |
_ => { |
| 43 |
return Err(AppDirsError::Io(Error::new( |
| 44 |
ErrorKind::Other, |
| 45 |
"path_string is not `JObject`", |
| 46 |
))) |
| 47 |
}, |
| 48 |
}; |
| 49 |
|
| 50 |
Ok(env.get_string(path_string)?.into()) |
| 51 |
} |
| 52 |
|
| 53 |
pub fn get_app_dir(t: AppDataType) -> Result<PathBuf, AppDirsError> { |
| 54 |
let android_context = ndk_context::android_context(); |
| 55 |
let vm = unsafe { jni::JavaVM::from_raw(android_context.vm().cast()) }?; |
| 56 |
let env = vm.attach_current_thread()?; |
| 57 |
let context = jni::objects::JObject::from(android_context.context().cast()); |
| 58 |
|
| 59 |
let path_string = match t { |
| 60 |
AppDataType::UserConfig => get_jni_app_dir(&context, &env, "getDataDir", false)?, |
| 61 |
AppDataType::UserData => get_jni_app_dir(&context, &env, "getFilesDir", false)?, |
| 62 |
AppDataType::UserCache => get_jni_app_dir(&context, &env, "getCacheDir", false)?, |
| 63 |
AppDataType::SharedData | AppDataType::SharedConfig => { |
| 64 |
get_jni_app_dir(&context, &env, "getExternalFilesDir", true)? |
| 65 |
}, |
| 66 |
|
| 67 |
}; |
| 68 |
|
| 69 |
Ok(PathBuf::from(path_string)) |
| 70 |
} |