Skip to content

Commit

Permalink
ndk/native_window: Add bindings to convert to and from Java Surface
Browse files Browse the repository at this point in the history
… representation (#272)

`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.
  • Loading branch information
MarijnS95 authored May 14, 2022
1 parent 7cabf63 commit d18e809
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions ndk/src/native_window.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//! Bindings for [`ffi::ANativeWindow`]

use jni_sys::{jobject, JNIEnv};
use std::ptr::NonNull;

#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
Expand Down Expand Up @@ -45,14 +47,35 @@ impl NativeWindow {
pub fn ptr(&self) -> NonNull<ffi::ANativeWindow> {
self.ptr
}
}

impl NativeWindow {
pub fn height(&self) -> i32 {
unsafe { ffi::ANativeWindow_getHeight(self.ptr.as_ptr()) }
}

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<Self> {
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())
}
}

0 comments on commit d18e809

Please sign in to comment.