From 63a8ea646979f9f5f9c216fb8c2bfc5476591117 Mon Sep 17 00:00:00 2001 From: Marijn Suijten Date: Thu, 12 May 2022 13:54:13 +0200 Subject: [PATCH] ndk/native_window: Add bindings to convert to and from Java `Surface` representation `ANativeWindow` is the C counterpart to the `android.view.Surface` object in Java, and has these functions available to convert between the C and Java (JNI representation) variant of it. --- ndk/src/native_window.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/ndk/src/native_window.rs b/ndk/src/native_window.rs index 2cbdaf2d..d14a6907 100644 --- a/ndk/src/native_window.rs +++ b/ndk/src/native_window.rs @@ -1,4 +1,6 @@ //! Bindings for [`ffi::ANativeWindow`] + +use jni_sys::{jobject, JNIEnv}; use std::ptr::NonNull; #[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] @@ -45,9 +47,7 @@ impl NativeWindow { pub fn ptr(&self) -> NonNull { self.ptr } -} -impl NativeWindow { pub fn height(&self) -> i32 { unsafe { ffi::ANativeWindow_getHeight(self.ptr.as_ptr()) } } @@ -55,4 +55,27 @@ impl NativeWindow { pub fn width(&self) -> i32 { unsafe { ffi::ANativeWindow_getWidth(self.ptr.as_ptr()) } } + + /// Return the [`NativeWindow`] associated with a JNI [`android.view.Surface`] pointer. + /// + /// # Safety + /// By calling this function, you assert that `env` is a valid pointer to a [`JNIEnv`] and + /// `surface` is a valid pointer to an [`android.view.Surface`]. + /// + /// [`android.view.Surface`]: https://developer.android.com/reference/android/view/Surface + pub unsafe fn from_surface(env: *mut JNIEnv, surface: jobject) -> Option { + let ptr = ffi::ANativeWindow_fromSurface(env, surface); + Some(Self::from_ptr(NonNull::new(ptr)?)) + } + + /// Return a JNI [`android.view.Surface`] pointer derived from this [`NativeWindow`]. + /// + /// # Safety + /// By calling this function, you assert that `env` is a valid pointer to a [`JNIEnv`]. + /// + /// [`android.view.Surface`]: https://developer.android.com/reference/android/view/Surface + #[cfg(feature = "api-level-26")] + pub unsafe fn to_surface(&self, env: *mut JNIEnv) -> jobject { + ffi::ANativeWindow_toSurface(env, self.ptr().as_ptr()) + } }