Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/native/android.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,11 @@ impl MainThreadState {
},
Message::SurfaceChanged { width, height } => {
{
let density = unsafe { query_display_density() };
let mut d = crate::native_display().lock().unwrap();
d.screen_width = width as _;
d.screen_height = height as _;
d.dpi_scale = density;
}
self.event_handler.resize_event(width as _, height as _);
}
Expand Down Expand Up @@ -323,6 +325,56 @@ pub unsafe fn attach_jni_env() -> *mut ndk_sys::JNIEnv {
env
}

/// `Resources.getDisplayMetrics().density` — 1.0 = mdpi, 2.0 = xhdpi,
/// etc. Returns 1.0 on any JNI hiccup.
unsafe fn query_display_density() -> f32 {
if VM.is_null() || ACTIVITY.is_null() {
return 1.0;
}
let env = attach_jni_env();
if env.is_null() {
return 1.0;
}

let resources = ndk_utils::call_object_method!(
env,
ACTIVITY,
"getResources",
"()Landroid/content/res/Resources;"
);
if resources.is_null() {
return 1.0;
}

let metrics = ndk_utils::call_object_method!(
env,
resources,
"getDisplayMetrics",
"()Landroid/util/DisplayMetrics;"
);
if metrics.is_null() {
return 1.0;
}

let get_object_class = (**env).GetObjectClass.unwrap();
let get_field_id = (**env).GetFieldID.unwrap();
let get_float_field = (**env).GetFloatField.unwrap();

let metrics_class = get_object_class(env, metrics);
let density_field = get_field_id(
env,
metrics_class,
b"density\0".as_ptr() as _,
b"F\0".as_ptr() as _,
);
if density_field.is_null() {
return 1.0;
}

let density = get_float_field(env, metrics, density_field);
if density > 0.0 { density } else { 1.0 }
}

pub struct AndroidClipboard {}
impl AndroidClipboard {
pub fn new() -> AndroidClipboard {
Expand Down Expand Up @@ -454,9 +506,11 @@ where

let clipboard = Box::new(AndroidClipboard::new());
let tx_fn = Box::new(move |req| tx.send(Message::Request(req)).unwrap());
let density = query_display_density();
crate::set_or_replace_display(NativeDisplayData {
high_dpi: conf.high_dpi,
blocking_event_loop: conf.platform.blocking_event_loop,
dpi_scale: density,
..NativeDisplayData::new(screen_width as _, screen_height as _, tx_fn, clipboard)
});

Expand Down
Loading