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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#![cfg(any(feature = "native-activity", doc))]
use std::ptr;
use std::ptr::NonNull;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use log::{error, info, trace};
use ndk_sys::ALooper_wake;
use ndk_sys::{ALooper, ALooper_pollAll};
use ndk::asset::AssetManager;
use ndk::native_window::NativeWindow;
use crate::{
util, AndroidApp, ConfigurationRef, InputStatus, MainEvent, PollEvent, Rect, WindowManagerFlags,
};
pub mod input;
mod glue;
use self::glue::NativeActivityGlue;
pub const LOOPER_ID_MAIN: libc::c_int = 1;
pub const LOOPER_ID_INPUT: libc::c_int = 2;
#[derive(Debug)]
pub struct StateSaver<'a> {
app: &'a AndroidAppInner,
}
impl<'a> StateSaver<'a> {
pub fn store(&self, state: &'a [u8]) {
self.app.native_activity.set_saved_state(state);
}
}
#[derive(Debug)]
pub struct StateLoader<'a> {
app: &'a AndroidAppInner,
}
impl<'a> StateLoader<'a> {
pub fn load(&self) -> Option<Vec<u8>> {
self.app.native_activity.saved_state()
}
}
#[derive(Clone)]
pub struct AndroidAppWaker {
looper: NonNull<ALooper>,
}
unsafe impl Send for AndroidAppWaker {}
unsafe impl Sync for AndroidAppWaker {}
impl AndroidAppWaker {
pub fn wake(&self) {
unsafe {
ALooper_wake(self.looper.as_ptr());
}
}
}
impl AndroidApp {
pub(crate) fn new(native_activity: NativeActivityGlue) -> Self {
let app = Self {
inner: Arc::new(RwLock::new(AndroidAppInner {
native_activity,
looper: Looper {
ptr: ptr::null_mut(),
},
})),
};
{
let mut guard = app.inner.write().unwrap();
let main_fd = guard.native_activity.cmd_read_fd();
unsafe {
guard.looper.ptr = ndk_sys::ALooper_prepare(
ndk_sys::ALOOPER_PREPARE_ALLOW_NON_CALLBACKS as libc::c_int,
);
ndk_sys::ALooper_addFd(
guard.looper.ptr,
main_fd,
LOOPER_ID_MAIN,
ndk_sys::ALOOPER_EVENT_INPUT as libc::c_int,
None,
ptr::null_mut(),
);
}
}
app
}
}
#[derive(Debug)]
struct Looper {
pub ptr: *mut ALooper,
}
unsafe impl Send for Looper {}
unsafe impl Sync for Looper {}
#[derive(Debug)]
pub(crate) struct AndroidAppInner {
pub(crate) native_activity: NativeActivityGlue,
looper: Looper,
}
impl AndroidAppInner {
pub(crate) fn native_activity(&self) -> *const ndk_sys::ANativeActivity {
self.native_activity.activity
}
pub(crate) fn looper(&self) -> *mut ndk_sys::ALooper {
self.looper.ptr
}
pub fn native_window(&self) -> Option<NativeWindow> {
self.native_activity.mutex.lock().unwrap().window.clone()
}
pub fn poll_events<F>(&self, timeout: Option<Duration>, mut callback: F)
where
F: FnMut(PollEvent),
{
trace!("poll_events");
unsafe {
let mut fd: i32 = 0;
let mut events: i32 = 0;
let mut source: *mut core::ffi::c_void = ptr::null_mut();
let timeout_milliseconds = if let Some(timeout) = timeout {
timeout.as_millis() as i32
} else {
-1
};
info!("Calling ALooper_pollAll, timeout = {timeout_milliseconds}");
assert!(
!ndk_sys::ALooper_forThread().is_null(),
"Application tried to poll events from non-main thread"
);
let id = ALooper_pollAll(
timeout_milliseconds,
&mut fd,
&mut events,
&mut source as *mut *mut core::ffi::c_void,
);
info!("pollAll id = {id}");
match id {
ndk_sys::ALOOPER_POLL_WAKE => {
trace!("ALooper_pollAll returned POLL_WAKE");
callback(PollEvent::Wake);
}
ndk_sys::ALOOPER_POLL_CALLBACK => {
error!("Spurious ALOOPER_POLL_CALLBACK from ALopper_pollAll() (ignored)");
}
ndk_sys::ALOOPER_POLL_TIMEOUT => {
trace!("ALooper_pollAll returned POLL_TIMEOUT");
callback(PollEvent::Timeout);
}
ndk_sys::ALOOPER_POLL_ERROR => {
panic!("ALooper_pollAll returned POLL_ERROR");
}
id if id >= 0 => {
match id {
LOOPER_ID_MAIN => {
trace!("ALooper_pollAll returned ID_MAIN");
if let Some(ipc_cmd) = self.native_activity.read_cmd() {
let main_cmd = match ipc_cmd {
glue::AppCmd::InputQueueChanged => None,
glue::AppCmd::InitWindow => Some(MainEvent::InitWindow {}),
glue::AppCmd::TermWindow => Some(MainEvent::TerminateWindow {}),
glue::AppCmd::WindowResized => {
Some(MainEvent::WindowResized {})
}
glue::AppCmd::WindowRedrawNeeded => {
Some(MainEvent::RedrawNeeded {})
}
glue::AppCmd::ContentRectChanged => {
Some(MainEvent::ContentRectChanged {})
}
glue::AppCmd::GainedFocus => Some(MainEvent::GainedFocus),
glue::AppCmd::LostFocus => Some(MainEvent::LostFocus),
glue::AppCmd::ConfigChanged => {
Some(MainEvent::ConfigChanged {})
}
glue::AppCmd::LowMemory => Some(MainEvent::LowMemory),
glue::AppCmd::Start => Some(MainEvent::Start),
glue::AppCmd::Resume => Some(MainEvent::Resume {
loader: StateLoader { app: self },
}),
glue::AppCmd::SaveState => Some(MainEvent::SaveState {
saver: StateSaver { app: self },
}),
glue::AppCmd::Pause => Some(MainEvent::Pause),
glue::AppCmd::Stop => Some(MainEvent::Stop),
glue::AppCmd::Destroy => Some(MainEvent::Destroy),
};
trace!("Calling pre_exec_cmd({ipc_cmd:#?})");
self.native_activity.pre_exec_cmd(
ipc_cmd,
self.looper(),
LOOPER_ID_INPUT,
);
if let Some(main_cmd) = main_cmd {
trace!("Invoking callback for ID_MAIN command = {main_cmd:?}");
callback(PollEvent::Main(main_cmd));
}
trace!("Calling post_exec_cmd({ipc_cmd:#?})");
self.native_activity.post_exec_cmd(ipc_cmd);
}
}
LOOPER_ID_INPUT => {
trace!("ALooper_pollAll returned ID_INPUT");
self.native_activity.detach_input_queue_from_looper();
callback(PollEvent::Main(MainEvent::InputAvailable))
}
_ => {
error!("Ignoring spurious ALooper event source: id = {id}, fd = {fd}, events = {events:?}, data = {source:?}");
}
}
}
_ => {
error!("Spurious ALooper_pollAll return value {id} (ignored)");
}
}
}
}
pub fn create_waker(&self) -> AndroidAppWaker {
unsafe {
AndroidAppWaker {
looper: NonNull::new_unchecked(self.looper.ptr),
}
}
}
pub fn config(&self) -> ConfigurationRef {
self.native_activity.config()
}
pub fn content_rect(&self) -> Rect {
self.native_activity.content_rect()
}
pub fn asset_manager(&self) -> AssetManager {
unsafe {
let activity_ptr = self.native_activity.activity;
let am_ptr = NonNull::new_unchecked((*activity_ptr).assetManager);
AssetManager::from_ptr(am_ptr)
}
}
pub fn set_window_flags(
&self,
add_flags: WindowManagerFlags,
remove_flags: WindowManagerFlags,
) {
let na = self.native_activity();
let na_mut = na as *mut ndk_sys::ANativeActivity;
unsafe {
ndk_sys::ANativeActivity_setWindowFlags(
na_mut.cast(),
add_flags.bits(),
remove_flags.bits(),
);
}
}
pub fn show_soft_input(&self, show_implicit: bool) {
let na = self.native_activity();
unsafe {
let flags = if show_implicit {
ndk_sys::ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT
} else {
0
};
ndk_sys::ANativeActivity_showSoftInput(na as *mut _, flags);
}
}
pub fn hide_soft_input(&self, hide_implicit_only: bool) {
let na = self.native_activity();
unsafe {
let flags = if hide_implicit_only {
ndk_sys::ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY
} else {
0
};
ndk_sys::ANativeActivity_hideSoftInput(na as *mut _, flags);
}
}
pub fn enable_motion_axis(&self, _axis: input::Axis) {
}
pub fn disable_motion_axis(&self, _axis: input::Axis) {
}
pub fn input_events<F>(&self, mut callback: F)
where
F: FnMut(&input::InputEvent) -> InputStatus,
{
let queue = self
.native_activity
.looper_attached_input_queue(self.looper(), LOOPER_ID_INPUT);
let queue = match queue {
Some(queue) => queue,
None => return,
};
while let Ok(Some(event)) = queue.get_event() {
if let Some(ndk_event) = queue.pre_dispatch(event) {
let event = match ndk_event {
ndk::event::InputEvent::MotionEvent(e) => {
input::InputEvent::MotionEvent(input::MotionEvent::new(e))
}
ndk::event::InputEvent::KeyEvent(e) => {
input::InputEvent::KeyEvent(input::KeyEvent::new(e))
}
};
let handled = callback(&event);
let ndk_event = match event {
input::InputEvent::MotionEvent(e) => {
ndk::event::InputEvent::MotionEvent(e.into_ndk_event())
}
input::InputEvent::KeyEvent(e) => {
ndk::event::InputEvent::KeyEvent(e.into_ndk_event())
}
};
queue.finish_event(ndk_event, matches!(handled, InputStatus::Handled));
}
}
}
pub fn internal_data_path(&self) -> Option<std::path::PathBuf> {
let na = self.native_activity();
unsafe { util::try_get_path_from_ptr((*na).internalDataPath) }
}
pub fn external_data_path(&self) -> Option<std::path::PathBuf> {
let na = self.native_activity();
unsafe { util::try_get_path_from_ptr((*na).externalDataPath) }
}
pub fn obb_path(&self) -> Option<std::path::PathBuf> {
let na = self.native_activity();
unsafe { util::try_get_path_from_ptr((*na).obbPath) }
}
}