@@ -2,7 +2,8 @@ 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:: { hardware_buffer_format:: HardwareBufferFormat , native_window:: NativeWindow } ,
6+ AndroidApp , InputStatus , MainEvent , OnCreateState , PollEvent ,
67} ;
78use jni:: {
89 objects:: { JObject , JString } ,
@@ -140,7 +141,7 @@ fn android_main(app: AndroidApp) {
140141
141142 let mut quit = false ;
142143 let mut redraw_pending = true ;
143- let mut native_window: Option < ndk :: native_window :: NativeWindow > = None ;
144+ let mut native_window = None ;
144145
145146 let mut combining_accent = None ;
146147
@@ -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,17 +412,24 @@ fn character_map_and_combine_key(
401412/// convince Android that we're drawing something and are
402413/// responsive, otherwise it will stop delivering input
403414/// events to us.
404- fn dummy_render ( native_window : & ndk:: native_window:: NativeWindow ) {
405- unsafe {
406- let mut buf: ndk_sys:: ANativeWindow_Buffer = std:: mem:: zeroed ( ) ;
407- let mut rect: ndk_sys:: ARect = std:: mem:: zeroed ( ) ;
408- ndk_sys:: ANativeWindow_lock (
409- native_window. ptr ( ) . as_ptr ( ) as _ ,
410- & mut buf as _ ,
411- & mut rect as _ ,
412- ) ;
413- // Note: we don't try and touch the buffer since that
414- // also requires us to handle various buffer formats
415- ndk_sys:: ANativeWindow_unlockAndPost ( native_window. ptr ( ) . as_ptr ( ) as _ ) ;
415+ fn dummy_render ( native_window : & NativeWindow ) {
416+ let mut lock = native_window. lock ( None ) . unwrap ( ) ;
417+ let ( w, h) = ( lock. width ( ) , lock. height ( ) ) ;
418+
419+ assert_eq ! (
420+ lock. format( ) ,
421+ HardwareBufferFormat :: R8G8B8A8_UNORM ,
422+ "Expected the buffer format to be R8G8B8A8_UNORM since we set that in `InitWindow` handling"
423+ ) ;
424+
425+ for ( y, line) in lock. lines ( ) . unwrap ( ) . enumerate ( ) {
426+ let r = y * 255 / h;
427+ for ( x, pixels) in line. chunks_mut ( 4 ) . enumerate ( ) {
428+ let g = x * 255 / w;
429+ pixels[ 0 ] . write ( r as u8 ) ;
430+ pixels[ 1 ] . write ( g as u8 ) ;
431+ pixels[ 2 ] . write ( 0 ) ;
432+ pixels[ 3 ] . write ( 255 ) ;
433+ }
416434 }
417435}
0 commit comments