1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
//! Android event loop implementation
//!
//! Wraps the android-activity event polling to implement the blinc_platform EventLoop trait.
use crate::window::AndroidWindow;
use blinc_platform::{
ControlFlow, Event, EventLoop, LifecycleEvent, PlatformError, Window, WindowEvent, WindowId,
};
#[cfg(target_os = "android")]
use android_activity::{AndroidApp, MainEvent, PollEvent};
#[cfg(target_os = "android")]
use ndk::looper::ForeignLooper;
#[cfg(target_os = "android")]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(target_os = "android")]
use std::sync::Arc;
#[cfg(target_os = "android")]
use std::time::Duration;
#[cfg(target_os = "android")]
use tracing::{debug, info, warn};
/// Proxy for waking up the event loop from another thread
///
/// Use this to request a redraw from a background animation thread.
/// Call `wake()` to send a wake-up signal to the event loop.
#[cfg(target_os = "android")]
#[derive(Clone)]
pub struct AndroidWakeProxy {
/// The looper to wake
looper: ForeignLooper,
/// Flag indicating a wake was requested
wake_requested: Arc<AtomicBool>,
}
#[cfg(target_os = "android")]
impl AndroidWakeProxy {
/// Create a new wake proxy for the current thread's looper
pub fn new() -> Option<Self> {
ForeignLooper::for_thread().map(|looper| Self {
looper,
wake_requested: Arc::new(AtomicBool::new(false)),
})
}
/// Wake up the event loop, causing it to process events and potentially redraw
pub fn wake(&self) {
self.wake_requested.store(true, Ordering::SeqCst);
self.looper.wake();
}
/// Check if a wake was requested and clear the flag
pub fn take_wake_request(&self) -> bool {
self.wake_requested.swap(false, Ordering::SeqCst)
}
}
/// Placeholder for non-Android builds
#[cfg(not(target_os = "android"))]
#[derive(Clone)]
pub struct AndroidWakeProxy;
#[cfg(not(target_os = "android"))]
impl AndroidWakeProxy {
/// Create a placeholder wake proxy
pub fn new() -> Option<Self> {
None
}
/// No-op wake for non-Android
pub fn wake(&self) {}
/// Always returns false on non-Android
pub fn take_wake_request(&self) -> bool {
false
}
}
/// Android event loop wrapping android-activity's polling
#[cfg(target_os = "android")]
pub struct AndroidEventLoop {
app: AndroidApp,
wake_proxy: Option<AndroidWakeProxy>,
}
#[cfg(target_os = "android")]
impl AndroidEventLoop {
/// Create a new Android event loop
pub fn new(app: AndroidApp) -> Self {
// Create wake proxy - this captures the current thread's looper
let wake_proxy = AndroidWakeProxy::new();
if wake_proxy.is_none() {
warn!("Failed to create AndroidWakeProxy - animations may not wake event loop");
}
Self { app, wake_proxy }
}
/// Get a wake proxy that can be used to wake up the event loop from another thread
///
/// This is useful for animation threads that need to request redraws.
/// Returns None if the looper couldn't be obtained (shouldn't happen in normal operation).
pub fn wake_proxy(&self) -> Option<AndroidWakeProxy> {
self.wake_proxy.clone()
}
}
#[cfg(target_os = "android")]
impl EventLoop for AndroidEventLoop {
type Window = AndroidWindow;
fn run<F>(self, mut handler: F) -> Result<(), PlatformError>
where
F: FnMut(Event, &Self::Window) -> ControlFlow + 'static,
{
let mut window: Option<AndroidWindow> = None;
let mut should_exit = false;
while !should_exit {
// Poll for events with 16ms timeout (~60fps)
self.app
.poll_events(Some(Duration::from_millis(16)), |event| {
if let PollEvent::Main(main_event) = event {
match main_event {
MainEvent::InitWindow { .. } => {
info!("Android: Native window initialized");
if let Some(native) = self.app.native_window() {
let w = native.width();
let h = native.height();
info!("Android: Window size {}x{}", w, h);
window = Some(AndroidWindow::new(native));
}
}
MainEvent::TerminateWindow { .. } => {
info!("Android: Native window terminated");
window = None;
}
MainEvent::WindowResized { .. } => {
if let Some(ref win) = window {
let (width, height) = win.size();
info!("Android: Window resized to {}x{}", width, height);
let flow = handler(
Event::Window(
WindowId::PRIMARY,
WindowEvent::Resized { width, height },
),
win,
);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
}
MainEvent::GainedFocus => {
debug!("Android: Gained focus");
if let Some(ref win) = window {
win.set_focused(true);
let flow = handler(
Event::Window(
WindowId::PRIMARY,
WindowEvent::Focused(true),
),
win,
);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
}
MainEvent::LostFocus => {
debug!("Android: Lost focus");
if let Some(ref win) = window {
win.set_focused(false);
let flow = handler(
Event::Window(
WindowId::PRIMARY,
WindowEvent::Focused(false),
),
win,
);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
}
MainEvent::Resume { .. } => {
info!("Android: Resumed");
if let Some(ref win) = window {
let flow =
handler(Event::Lifecycle(LifecycleEvent::Resumed), win);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
}
MainEvent::Pause => {
info!("Android: Paused");
if let Some(ref win) = window {
let flow =
handler(Event::Lifecycle(LifecycleEvent::Suspended), win);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
}
MainEvent::Destroy => {
info!("Android: Destroyed");
if let Some(ref win) = window {
win.set_running(false);
let flow = handler(
Event::Window(
WindowId::PRIMARY,
WindowEvent::CloseRequested,
),
win,
);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
should_exit = true;
}
MainEvent::LowMemory => {
warn!("Android: Low memory");
if let Some(ref win) = window {
let flow =
handler(Event::Lifecycle(LifecycleEvent::LowMemory), win);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
}
_ => {}
}
}
});
// Check if animation thread requested a wake
let wake_requested = self
.wake_proxy
.as_ref()
.map(|p| p.take_wake_request())
.unwrap_or(false);
// Frame tick when we have a focused window or a wake was requested
if let Some(ref win) = window {
if win.is_focused() || wake_requested {
let flow = handler(Event::Frame(WindowId::PRIMARY), win);
if flow == ControlFlow::Exit {
should_exit = true;
}
}
}
}
info!("Android: Event loop exiting");
Ok(())
}
}
/// Placeholder for non-Android builds
#[cfg(not(target_os = "android"))]
#[derive(Default)]
pub struct AndroidEventLoop {
_private: (),
}
#[cfg(not(target_os = "android"))]
impl AndroidEventLoop {
/// Create a placeholder event loop (for cross-compilation checks)
pub fn new() -> Self {
Self::default()
}
}
#[cfg(not(target_os = "android"))]
impl EventLoop for AndroidEventLoop {
type Window = AndroidWindow;
fn run<F>(self, _handler: F) -> Result<(), PlatformError>
where
F: FnMut(Event, &Self::Window) -> ControlFlow + 'static,
{
Err(PlatformError::Unsupported(
"Android platform only available on Android".to_string(),
))
}
}