@@ -2,13 +2,14 @@ use std::sync::OnceLock;
22
33use android_activity:: {
44 input:: { InputEvent , KeyAction , KeyEvent , KeyMapChar , MotionAction } ,
5- ndk, ndk_sys , AndroidApp , InputStatus , MainEvent , OnCreateState , PollEvent ,
5+ ndk, AndroidApp , InputStatus , MainEvent , OnCreateState , PollEvent ,
66} ;
77use jni:: {
88 objects:: { JObject , JString } ,
99 refs:: Global ,
1010 vm:: JavaVM ,
1111} ;
12+ use ndk:: hardware_buffer_format:: HardwareBufferFormat ;
1213use tracing:: { error, info} ;
1314
1415jni:: bind_java_type! { Context => "android.content.Context" }
@@ -176,6 +177,16 @@ fn android_main(app: AndroidApp) {
176177 }
177178 MainEvent :: InitWindow { .. } => {
178179 native_window = app. native_window ( ) ;
180+ if let Some ( nw) = & native_window {
181+ // Set the backing buffer to a known format (without changing
182+ // the size) so that we can safely draw to it in dummy_render().
183+ nw. set_buffers_geometry (
184+ 0 ,
185+ 0 ,
186+ Some ( HardwareBufferFormat :: R8G8B8A8_UNORM ) ,
187+ )
188+ . unwrap ( )
189+ }
179190 redraw_pending = true ;
180191 }
181192 MainEvent :: TerminateWindow { .. } => {
@@ -401,16 +412,23 @@ fn character_map_and_combine_key(
401412/// responsive, otherwise it will stop delivering input
402413/// events to us.
403414fn dummy_render ( native_window : & ndk:: native_window:: NativeWindow ) {
404- unsafe {
405- let mut buf: ndk_sys:: ANativeWindow_Buffer = std:: mem:: zeroed ( ) ;
406- let mut rect: ndk_sys:: ARect = std:: mem:: zeroed ( ) ;
407- ndk_sys:: ANativeWindow_lock (
408- native_window. ptr ( ) . as_ptr ( ) as _ ,
409- & mut buf as _ ,
410- & mut rect as _ ,
411- ) ;
412- // Note: we don't try and touch the buffer since that
413- // also requires us to handle various buffer formats
414- ndk_sys:: ANativeWindow_unlockAndPost ( native_window. ptr ( ) . as_ptr ( ) as _ ) ;
415+ let mut lock = native_window. lock ( None ) . unwrap ( ) ;
416+ let ( w, h) = ( lock. width ( ) , lock. height ( ) ) ;
417+
418+ assert_eq ! (
419+ lock. format( ) ,
420+ HardwareBufferFormat :: R8G8B8A8_UNORM ,
421+ "Expected the buffer format to be R8G8B8A8_UNORM since we set that in `InitWindow` handling"
422+ ) ;
423+
424+ for ( y, line) in lock. lines ( ) . unwrap ( ) . enumerate ( ) {
425+ let r = y * 255 / h;
426+ for ( x, pixels) in line. chunks_mut ( 4 ) . enumerate ( ) {
427+ let g = x * 255 / w;
428+ pixels[ 0 ] . write ( r as u8 ) ;
429+ pixels[ 1 ] . write ( g as u8 ) ;
430+ pixels[ 2 ] . write ( 0 ) ;
431+ pixels[ 3 ] . write ( 255 ) ;
432+ }
415433 }
416434}
0 commit comments