|
1 | 1 | use std::sync::OnceLock; |
2 | 2 |
|
3 | 3 | use android_activity::{ |
4 | | - AndroidApp, InputStatus, MainEvent, OnCreateState, PollEvent, |
5 | 4 | input::{InputEvent, KeyAction, KeyEvent, KeyMapChar, MotionAction}, |
6 | | - ndk, ndk_sys, |
| 5 | + ndk, ndk_sys, AndroidApp, InputStatus, MainEvent, OnCreateState, PollEvent, |
7 | 6 | }; |
8 | 7 | use jni::{ |
9 | 8 | objects::{JObject, JString}, |
10 | 9 | refs::Global, |
11 | 10 | vm::JavaVM, |
12 | 11 | }; |
| 12 | +use ndk::native_window::HardwareBufferFormat; |
13 | 13 | use tracing::{error, info}; |
14 | 14 |
|
15 | 15 | jni::bind_java_type! { Context => "android.content.Context" } |
@@ -177,6 +177,16 @@ fn android_main(app: AndroidApp) { |
177 | 177 | } |
178 | 178 | MainEvent::InitWindow { .. } => { |
179 | 179 | 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 | + } |
180 | 190 | redraw_pending = true; |
181 | 191 | } |
182 | 192 | MainEvent::TerminateWindow { .. } => { |
@@ -402,16 +412,15 @@ fn character_map_and_combine_key( |
402 | 412 | /// responsive, otherwise it will stop delivering input |
403 | 413 | /// events to us. |
404 | 414 | 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 | + let mut lock = native_window.lock(None).unwrap(); |
| 416 | + let (w, h) = (lock.width(), lock.height()); |
| 417 | + |
| 418 | + for (y, line) in lock.lines().unwrap().enumerate() { |
| 419 | + let r = y * 255 / h; |
| 420 | + for (x, pixels) in line.chunks_mut(4).enumerate() { |
| 421 | + let g = x * 255 / w; |
| 422 | + pixels[0].write(r as u8); |
| 423 | + pixels[1].write(g as u8); |
| 424 | + } |
416 | 425 | } |
417 | 426 | } |
0 commit comments