android-activity 0.6.1

Glue for building Rust applications on Android with NativeActivity or GameActivity
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! This 'glue' layer acts as an IPC shim between the JVM main thread and the Rust
//! main thread. Notifying Rust of lifecycle events from the JVM and handling
//! synchronization between the two threads.

use std::{
    ops::Deref,
    panic::catch_unwind,
    ptr::{self, NonNull},
    sync::{Arc, Condvar, Mutex, Weak},
};

use jni::{objects::JObject, refs::Global, vm::AttachConfig};
use ndk::{configuration::Configuration, input_queue::InputQueue, native_window::NativeWindow};

use crate::{
    init::{init_android_main_thread, init_java_main_thread_on_create},
    util::{abort_on_panic, log_panic},
    ConfigurationRef,
};

use super::{AndroidApp, Rect};

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum AppCmd {
    InputQueueChanged = 0,
    InitWindow = 1,
    TermWindow = 2,
    WindowResized = 3,
    WindowRedrawNeeded = 4,
    ContentRectChanged = 5,
    GainedFocus = 6,
    LostFocus = 7,
    ConfigChanged = 8,
    LowMemory = 9,
    Start = 10,
    Resume = 11,
    SaveState = 12,
    Pause = 13,
    Stop = 14,
    Destroy = 15,
}
impl TryFrom<i8> for AppCmd {
    type Error = ();

    fn try_from(value: i8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(AppCmd::InputQueueChanged),
            1 => Ok(AppCmd::InitWindow),
            2 => Ok(AppCmd::TermWindow),
            3 => Ok(AppCmd::WindowResized),
            4 => Ok(AppCmd::WindowRedrawNeeded),
            5 => Ok(AppCmd::ContentRectChanged),
            6 => Ok(AppCmd::GainedFocus),
            7 => Ok(AppCmd::LostFocus),
            8 => Ok(AppCmd::ConfigChanged),
            9 => Ok(AppCmd::LowMemory),
            10 => Ok(AppCmd::Start),
            11 => Ok(AppCmd::Resume),
            12 => Ok(AppCmd::SaveState),
            13 => Ok(AppCmd::Pause),
            14 => Ok(AppCmd::Stop),
            15 => Ok(AppCmd::Destroy),
            _ => Err(()),
        }
    }
}

#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum State {
    Init,
    Start,
    Resume,
    Pause,
    Stop,
}

#[derive(Debug)]
pub struct WaitableNativeActivityState {
    pub mutex: Mutex<NativeActivityState>,
    pub cond: Condvar,
}

// SAFETY: ndk::NativeActivity is also SendSync.
unsafe impl Send for WaitableNativeActivityState {}
unsafe impl Sync for WaitableNativeActivityState {}

#[derive(Debug, Clone)]
pub struct NativeActivityGlue {
    pub inner: Arc<WaitableNativeActivityState>,
}

impl Deref for NativeActivityGlue {
    type Target = WaitableNativeActivityState;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl NativeActivityGlue {
    pub fn new(
        activity: *mut ndk_sys::ANativeActivity,
        saved_state: *const libc::c_void,
        saved_state_size: libc::size_t,
    ) -> Self {
        let glue = Self {
            inner: Arc::new(WaitableNativeActivityState::new(
                activity,
                saved_state,
                saved_state_size,
            )),
        };

        let weak_ref = Arc::downgrade(&glue.inner);
        let weak_ptr = Weak::into_raw(weak_ref);
        unsafe {
            (*activity).instance = weak_ptr as *mut _;

            (*(*activity).callbacks).onDestroy = Some(on_destroy);
            (*(*activity).callbacks).onStart = Some(on_start);
            (*(*activity).callbacks).onResume = Some(on_resume);
            (*(*activity).callbacks).onSaveInstanceState = Some(on_save_instance_state);
            (*(*activity).callbacks).onPause = Some(on_pause);
            (*(*activity).callbacks).onStop = Some(on_stop);
            (*(*activity).callbacks).onConfigurationChanged = Some(on_configuration_changed);
            (*(*activity).callbacks).onLowMemory = Some(on_low_memory);
            (*(*activity).callbacks).onWindowFocusChanged = Some(on_window_focus_changed);
            (*(*activity).callbacks).onNativeWindowCreated = Some(on_native_window_created);
            (*(*activity).callbacks).onNativeWindowResized = Some(on_native_window_resized);
            (*(*activity).callbacks).onNativeWindowRedrawNeeded =
                Some(on_native_window_redraw_needed);
            (*(*activity).callbacks).onNativeWindowDestroyed = Some(on_native_window_destroyed);
            (*(*activity).callbacks).onInputQueueCreated = Some(on_input_queue_created);
            (*(*activity).callbacks).onInputQueueDestroyed = Some(on_input_queue_destroyed);
            (*(*activity).callbacks).onContentRectChanged = Some(on_content_rect_changed);
        }

        glue
    }

    /// Returns the file descriptor that needs to be polled by the Rust main thread
    /// for events/commands from the JVM thread
    pub fn cmd_read_fd(&self) -> libc::c_int {
        self.mutex.lock().unwrap().msg_read
    }

    /// For the Rust main thread to read a single pending command sent from the JVM main thread
    pub fn read_cmd(&self) -> Option<AppCmd> {
        self.inner.mutex.lock().unwrap().read_cmd()
    }

    /// For the Rust main thread to get an [`InputQueue`] that wraps the AInputQueue pointer
    /// we have and at the same time ensure that the input queue is attached to the given looper.
    ///
    /// NB: it's expected that the input queue is detached as soon as we know there is new
    /// input (knowing the app will be notified) and only re-attached when the application
    /// reads the input (to avoid lots of redundant wake ups)
    pub fn looper_attached_input_queue(
        &self,
        looper: *mut ndk_sys::ALooper,
        ident: libc::c_int,
    ) -> Option<InputQueue> {
        let mut guard = self.mutex.lock().unwrap();

        if guard.input_queue.is_null() {
            return None;
        }

        unsafe {
            // Reattach the input queue to the looper so future input will again deliver an
            // `InputAvailable` event.
            guard.attach_input_queue_to_looper(looper, ident);
            Some(InputQueue::from_ptr(NonNull::new_unchecked(
                guard.input_queue,
            )))
        }
    }

    pub fn detach_input_queue_from_looper(&self) {
        unsafe {
            self.inner
                .mutex
                .lock()
                .unwrap()
                .detach_input_queue_from_looper();
        }
    }

    pub fn config(&self) -> ConfigurationRef {
        self.mutex.lock().unwrap().config.clone()
    }

    pub fn content_rect(&self) -> Rect {
        self.mutex.lock().unwrap().content_rect.into()
    }
}

/// The status of the native thread that's created to run
/// `android_main`
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum NativeThreadState {
    /// The `android_main` thread hasn't been created yet
    Init,
    /// The `android_main` thread has been spawned and started running
    Running,
    /// The `android_main` thread has finished
    Stopped,
}

#[derive(Debug)]
pub struct NativeActivityState {
    /// Set as soon as the Java main thread notifies us of an `onDestroyed`
    /// callback.
    pub destroyed: bool,

    /// The `ANativeActivity` associated with the NativeActivity instance
    ///
    /// # Safety
    ///
    /// This pointer will be reset to `null` when the NativeActivity is
    /// destroyed.
    ///
    /// Keep in mind that `NativeActivityState` is ref-counted and can
    /// potentially out-last an `onDestroy` callback where we may reset this to
    /// be a null pointer!
    ///
    /// For example:
    /// - An application could put an `AndroidApp` into a global `'static` and
    ///   keep it alive beyond `android_main`
    /// - An application could schedule a callback to run on the Java main
    ///   thread with an `AndroidApp` clone and by the time it runs then the
    ///   associated `ANativeActivity` could have been destroyed.
    pub activity: *mut ndk_sys::ANativeActivity,

    pub msg_read: libc::c_int,
    pub msg_write: libc::c_int,
    pub config: ConfigurationRef,
    pub saved_state: Vec<u8>,
    pub input_queue: *mut ndk_sys::AInputQueue,
    pub window: Option<NativeWindow>,
    pub content_rect: ndk_sys::ARect,
    pub activity_state: State,
    pub destroy_requested: bool,
    pub thread_state: NativeThreadState,
    pub app_has_saved_state: bool,

    pub pending_input_queue: *mut ndk_sys::AInputQueue,
    pub pending_window: Option<NativeWindow>,
}

impl NativeActivityState {
    pub fn read_cmd(&mut self) -> Option<AppCmd> {
        let mut cmd_i: i8 = 0;
        loop {
            match unsafe { libc::read(self.msg_read, &mut cmd_i as *mut _ as *mut _, 1) } {
                1 => {
                    let cmd = AppCmd::try_from(cmd_i);
                    return match cmd {
                        Ok(cmd) => Some(cmd),
                        Err(_) => {
                            log::error!("Spurious, unknown NativeActivityGlue cmd: {}", cmd_i);
                            None
                        }
                    };
                }
                -1 => {
                    let err = std::io::Error::last_os_error();
                    if err.kind() != std::io::ErrorKind::Interrupted {
                        log::error!("Failure reading NativeActivityGlue cmd: {}", err);
                        return None;
                    }
                }
                count => {
                    log::error!(
                        "Spurious read of {count} bytes while reading NativeActivityGlue cmd"
                    );
                    return None;
                }
            }
        }
    }

    fn write_cmd(&mut self, cmd: AppCmd) {
        let cmd = cmd as i8;
        loop {
            match unsafe { libc::write(self.msg_write, &cmd as *const _ as *const _, 1) } {
                1 => break,
                -1 => {
                    let err = std::io::Error::last_os_error();
                    if err.kind() != std::io::ErrorKind::Interrupted {
                        log::error!("Failure writing NativeActivityGlue cmd: {}", err);
                        return;
                    }
                }
                count => {
                    log::error!(
                        "Spurious write of {count} bytes while writing NativeActivityGlue cmd"
                    );
                    return;
                }
            }
        }
    }

    pub unsafe fn attach_input_queue_to_looper(
        &mut self,
        looper: *mut ndk_sys::ALooper,
        ident: libc::c_int,
    ) {
        if !self.input_queue.is_null() {
            log::trace!("Attaching input queue to looper");
            ndk_sys::AInputQueue_attachLooper(
                self.input_queue,
                looper,
                ident,
                None,
                ptr::null_mut(),
            );
        }
    }

    pub unsafe fn detach_input_queue_from_looper(&mut self) {
        if !self.input_queue.is_null() {
            log::trace!("Detaching input queue from looper");
            ndk_sys::AInputQueue_detachLooper(self.input_queue);
        }
    }
}

impl Drop for WaitableNativeActivityState {
    fn drop(&mut self) {
        log::info!("WaitableNativeActivityState::drop!");
        unsafe {
            let mut guard = self.mutex.lock().unwrap();
            guard.detach_input_queue_from_looper();
        }
    }
}

impl WaitableNativeActivityState {
    ///////////////////////////////
    // Java-side callback handling
    ///////////////////////////////

    pub fn new(
        activity: *mut ndk_sys::ANativeActivity,
        saved_state_in: *const libc::c_void,
        saved_state_size: libc::size_t,
    ) -> Self {
        let mut msgpipe: [libc::c_int; 2] = [-1, -1];
        unsafe {
            if libc::pipe(msgpipe.as_mut_ptr()) != 0 {
                panic!(
                    "could not create  Rust <-> Java IPC pipe: {}",
                    std::io::Error::last_os_error()
                );
            }
        }

        let saved_state = if saved_state_in.is_null() {
            Vec::new()
        } else {
            unsafe { std::slice::from_raw_parts(saved_state_in as *const u8, saved_state_size) }
                .to_vec()
        };

        let config = unsafe {
            let config = ndk_sys::AConfiguration_new();
            ndk_sys::AConfiguration_fromAssetManager(config, (*activity).assetManager);

            let config = super::ConfigurationRef::new(Configuration::from_ptr(
                NonNull::new_unchecked(config),
            ));
            log::trace!("Config: {:#?}", config);
            config
        };

        Self {
            mutex: Mutex::new(NativeActivityState {
                activity,
                msg_read: msgpipe[0],
                msg_write: msgpipe[1],
                config,
                saved_state,
                input_queue: ptr::null_mut(),
                window: None,
                content_rect: Rect::empty().into(),
                activity_state: State::Init,
                destroy_requested: false,
                thread_state: NativeThreadState::Init,
                app_has_saved_state: false,
                destroyed: false,
                pending_input_queue: ptr::null_mut(),
                pending_window: None,
            }),
            cond: Condvar::new(),
        }
    }

    pub fn notify_destroyed(&self) {
        let mut guard = self.mutex.lock().unwrap();
        guard.destroyed = true;

        unsafe {
            guard.write_cmd(AppCmd::Destroy);
            while guard.thread_state != NativeThreadState::Stopped {
                guard = self.cond.wait(guard).unwrap();
            }

            libc::close(guard.msg_read);
            guard.msg_read = -1;
            libc::close(guard.msg_write);
            guard.msg_write = -1;

            // The last thing that `NativeActivity` `onDestroy` does is to call a
            // native method (`unloadNativeCode`) which will `delete` the
            // `ANativeActivity` instance.
            guard.activity = ptr::null_mut();
        }
    }

    pub fn notify_config_changed(&self) {
        let mut guard = self.mutex.lock().unwrap();
        guard.write_cmd(AppCmd::ConfigChanged);
    }

    pub fn notify_low_memory(&self) {
        let mut guard = self.mutex.lock().unwrap();
        guard.write_cmd(AppCmd::LowMemory);
    }

    pub fn notify_focus_changed(&self, focused: bool) {
        let mut guard = self.mutex.lock().unwrap();
        guard.write_cmd(if focused {
            AppCmd::GainedFocus
        } else {
            AppCmd::LostFocus
        });
    }

    pub fn notify_window_resized(&self, native_window: *mut ndk_sys::ANativeWindow) {
        let mut guard = self.mutex.lock().unwrap();
        // set_window always syncs .pending_window back to .window before returning. This callback
        // from Android can never arrive at an interim state, and validates that Android:
        // 1. Only provides resizes in between onNativeWindowCreated and onNativeWindowDestroyed;
        // 2. Doesn't call it on a bogus window pointer that we don't know about.
        debug_assert_eq!(guard.window.as_ref().unwrap().ptr().as_ptr(), native_window);
        guard.write_cmd(AppCmd::WindowResized);
    }

    pub fn notify_window_redraw_needed(&self, native_window: *mut ndk_sys::ANativeWindow) {
        let mut guard = self.mutex.lock().unwrap();
        // set_window always syncs .pending_window back to .window before returning. This callback
        // from Android can never arrive at an interim state, and validates that Android:
        // 1. Only provides resizes in between onNativeWindowCreated and onNativeWindowDestroyed;
        // 2. Doesn't call it on a bogus window pointer that we don't know about.
        debug_assert_eq!(guard.window.as_ref().unwrap().ptr().as_ptr(), native_window);
        guard.write_cmd(AppCmd::WindowRedrawNeeded);
    }

    unsafe fn set_input(&self, input_queue: *mut ndk_sys::AInputQueue) {
        let mut guard = self.mutex.lock().unwrap();

        // The pending_input_queue state should only be set while in this method, and since
        // it doesn't allow re-entrance and is cleared before returning then we expect
        // this to be null
        debug_assert!(
            guard.pending_input_queue.is_null(),
            "InputQueue update clash"
        );

        guard.pending_input_queue = input_queue;
        guard.write_cmd(AppCmd::InputQueueChanged);
        while guard.thread_state == NativeThreadState::Running
            && guard.input_queue != guard.pending_input_queue
        {
            guard = self.cond.wait(guard).unwrap();
        }
        guard.pending_input_queue = ptr::null_mut();
    }

    unsafe fn set_window(&self, window: Option<NativeWindow>) {
        let mut guard = self.mutex.lock().unwrap();

        // The pending_window state should only be set while in this method, and since
        // it doesn't allow re-entrance and is cleared before returning then we expect
        // this to be None
        debug_assert!(guard.pending_window.is_none(), "NativeWindow update clash");

        if guard.window.is_some() {
            guard.write_cmd(AppCmd::TermWindow);
        }
        guard.pending_window = window;
        if guard.pending_window.is_some() {
            guard.write_cmd(AppCmd::InitWindow);
        }
        while guard.thread_state == NativeThreadState::Running
            && guard.window != guard.pending_window
        {
            guard = self.cond.wait(guard).unwrap();
        }
        guard.pending_window = None;
    }

    unsafe fn set_content_rect(&self, rect: *const ndk_sys::ARect) {
        let mut guard = self.mutex.lock().unwrap();
        guard.content_rect = *rect;
        guard.write_cmd(AppCmd::ContentRectChanged);
    }

    unsafe fn set_activity_state(&self, state: State) {
        let mut guard = self.mutex.lock().unwrap();

        let cmd = match state {
            State::Init => panic!("Can't explicitly transition into 'init' state"),
            State::Start => AppCmd::Start,
            State::Resume => AppCmd::Resume,
            State::Pause => AppCmd::Pause,
            State::Stop => AppCmd::Stop,
        };
        guard.write_cmd(cmd);

        while guard.thread_state == NativeThreadState::Running && guard.activity_state != state {
            guard = self.cond.wait(guard).unwrap();
        }
    }

    fn request_save_state(&self) -> (*mut libc::c_void, libc::size_t) {
        let mut guard = self.mutex.lock().unwrap();

        // The state_saved flag should only be set while in this method, and since
        // it doesn't allow re-entrance and is cleared before returning then we expect
        // this to be None
        debug_assert!(!guard.app_has_saved_state, "SaveState request clash");
        guard.write_cmd(AppCmd::SaveState);
        while guard.thread_state == NativeThreadState::Running && !guard.app_has_saved_state {
            guard = self.cond.wait(guard).unwrap();
        }
        guard.app_has_saved_state = false;

        // `ANativeActivity` explicitly documents that it expects save state to be
        // given via a `malloc()` allocated pointer since it will automatically
        // `free()` the state after it has been converted to a buffer for the JVM.
        if !guard.saved_state.is_empty() {
            let saved_state_size = guard.saved_state.len();
            let saved_state_src_ptr = guard.saved_state.as_ptr();
            unsafe {
                let saved_state = libc::malloc(saved_state_size);
                assert!(
                    !saved_state.is_null(),
                    "Failed to allocate {} bytes for restoring saved application state",
                    saved_state_size
                );
                libc::memcpy(saved_state, saved_state_src_ptr as _, saved_state_size);
                (saved_state, saved_state_size)
            }
        } else {
            (ptr::null_mut(), 0)
        }
    }

    pub fn saved_state(&self) -> Option<Vec<u8>> {
        let guard = self.mutex.lock().unwrap();
        if !guard.saved_state.is_empty() {
            Some(guard.saved_state.clone())
        } else {
            None
        }
    }

    pub fn set_saved_state(&self, state: &[u8]) {
        let mut guard = self.mutex.lock().unwrap();

        guard.saved_state.clear();
        guard.saved_state.extend_from_slice(state);
    }

    ////////////////////////////
    // Rust-side event loop
    ////////////////////////////

    pub fn notify_main_thread_running(&self) {
        let mut guard = self.mutex.lock().unwrap();
        guard.thread_state = NativeThreadState::Running;
        self.cond.notify_one();
    }

    pub fn notify_main_thread_stopped_running(&self) {
        let mut guard = self.mutex.lock().unwrap();
        guard.thread_state = NativeThreadState::Stopped;
        // Notify all waiters to unblock any Android callbacks that would otherwise be waiting
        // indefinitely for the now-stopped (!) main thread.
        self.cond.notify_all();
    }

    pub unsafe fn pre_exec_cmd(
        &self,
        cmd: AppCmd,
        looper: *mut ndk_sys::ALooper,
        input_queue_ident: libc::c_int,
    ) {
        log::trace!("Pre: AppCmd::{:#?}", cmd);
        match cmd {
            AppCmd::InputQueueChanged => {
                let mut guard = self.mutex.lock().unwrap();
                guard.detach_input_queue_from_looper();
                guard.input_queue = guard.pending_input_queue;
                if !guard.input_queue.is_null() {
                    guard.attach_input_queue_to_looper(looper, input_queue_ident);
                }
                self.cond.notify_one();
            }
            AppCmd::InitWindow => {
                let mut guard = self.mutex.lock().unwrap();
                guard.window = guard.pending_window.clone();
                self.cond.notify_one();
            }
            AppCmd::Resume | AppCmd::Start | AppCmd::Pause | AppCmd::Stop => {
                let mut guard = self.mutex.lock().unwrap();
                guard.activity_state = match cmd {
                    AppCmd::Start => State::Start,
                    AppCmd::Pause => State::Pause,
                    AppCmd::Resume => State::Resume,
                    AppCmd::Stop => State::Stop,
                    _ => unreachable!(),
                };
                self.cond.notify_one();
            }
            AppCmd::ConfigChanged => {
                let guard = self.mutex.lock().unwrap();
                let config = ndk_sys::AConfiguration_new();
                ndk_sys::AConfiguration_fromAssetManager(config, (*guard.activity).assetManager);
                let config = Configuration::from_ptr(NonNull::new_unchecked(config));
                guard.config.replace(config);
                log::debug!("Config: {:#?}", guard.config);
            }
            AppCmd::Destroy => {
                let mut guard = self.mutex.lock().unwrap();
                guard.destroy_requested = true;
            }
            _ => {}
        }
    }

    pub unsafe fn post_exec_cmd(&self, cmd: AppCmd) {
        log::trace!("Post: AppCmd::{:#?}", cmd);
        match cmd {
            AppCmd::TermWindow => {
                let mut guard = self.mutex.lock().unwrap();
                guard.window = None;
                self.cond.notify_one();
            }
            AppCmd::SaveState => {
                let mut guard = self.mutex.lock().unwrap();
                guard.app_has_saved_state = true;
                self.cond.notify_one();
            }
            _ => {}
        }
    }
}

extern "Rust" {
    pub fn android_main(app: AndroidApp);
}

unsafe fn try_with_waitable_activity_ref(
    activity: *mut ndk_sys::ANativeActivity,
    closure: impl FnOnce(Arc<WaitableNativeActivityState>),
) {
    assert!(!(*activity).instance.is_null());
    let weak_ptr: *const WaitableNativeActivityState = (*activity).instance.cast();
    let weak_ref = Weak::from_raw(weak_ptr);
    let maybe_upgraded = weak_ref.upgrade();

    // Make sure we don't Drop the Weak reference (even if we failed to upgrade it
    // and also considering the possibility that we unwind due to a panic in `closure()`)
    // (The raw weak pointer associated with activity->instance must remain valid
    //  until `on_destroy` is called).
    let _ = weak_ref.into_raw();

    if let Some(waitable_activity) = maybe_upgraded {
        closure(waitable_activity);
    } else {
        log::error!("Ignoring spurious JVM callback after last activity reference was dropped!")
    }
}

unsafe extern "C" fn on_destroy(activity: *mut ndk_sys::ANativeActivity) {
    abort_on_panic(|| {
        log::debug!("Destroy: {:p}\n", activity);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.notify_destroyed()
        });

        // Once we return from here the `ANativeActivity` will be deleted via an
        // `unloadNativeCode` native method and so we can't get any more
        // callbacks and we can release the `Weak<WaitableNativeActivityState>`
        // reference we have associated with `activity->instance`

        assert!(!(*activity).instance.is_null());
        let weak_ptr: *const WaitableNativeActivityState = (*activity).instance.cast();
        let _drop_weak_ref = Weak::from_raw(weak_ptr);
        (*activity).instance = std::ptr::null_mut();
    })
}

unsafe extern "C" fn on_start(activity: *mut ndk_sys::ANativeActivity) {
    abort_on_panic(|| {
        log::debug!("Start: {:p}\n", activity);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.set_activity_state(State::Start);
        });
    })
}

unsafe extern "C" fn on_resume(activity: *mut ndk_sys::ANativeActivity) {
    abort_on_panic(|| {
        log::debug!("Resume: {:p}\n", activity);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.set_activity_state(State::Resume);
        });
    })
}

unsafe extern "C" fn on_save_instance_state(
    activity: *mut ndk_sys::ANativeActivity,
    out_len: *mut usize,
) -> *mut libc::c_void {
    abort_on_panic(|| {
        log::debug!("SaveInstanceState: {:p}\n", activity);
        *out_len = 0;
        let mut ret = ptr::null_mut();
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            let (state, len) = waitable_activity.request_save_state();
            *out_len = len;
            ret = state
        });

        log::debug!("Saved state = {:p}, len = {}", ret, *out_len);
        ret
    })
}

unsafe extern "C" fn on_pause(activity: *mut ndk_sys::ANativeActivity) {
    abort_on_panic(|| {
        log::debug!("Pause: {:p}\n", activity);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.set_activity_state(State::Pause);
        });
    })
}

unsafe extern "C" fn on_stop(activity: *mut ndk_sys::ANativeActivity) {
    abort_on_panic(|| {
        log::debug!("Stop: {:p}\n", activity);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.set_activity_state(State::Stop);
        });
    })
}

unsafe extern "C" fn on_configuration_changed(activity: *mut ndk_sys::ANativeActivity) {
    abort_on_panic(|| {
        log::debug!("ConfigurationChanged: {:p}\n", activity);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.notify_config_changed();
        });
    })
}

unsafe extern "C" fn on_low_memory(activity: *mut ndk_sys::ANativeActivity) {
    abort_on_panic(|| {
        log::debug!("LowMemory: {:p}\n", activity);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.notify_low_memory();
        });
    })
}

unsafe extern "C" fn on_window_focus_changed(
    activity: *mut ndk_sys::ANativeActivity,
    focused: libc::c_int,
) {
    abort_on_panic(|| {
        log::debug!("WindowFocusChanged: {:p} -- {}\n", activity, focused);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.notify_focus_changed(focused != 0);
        });
    })
}

unsafe extern "C" fn on_native_window_created(
    activity: *mut ndk_sys::ANativeActivity,
    window: *mut ndk_sys::ANativeWindow,
) {
    abort_on_panic(|| {
        log::debug!("NativeWindowCreated: {:p} -- {:p}\n", activity, window);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            // Use clone_from_ptr to acquire additional ownership on the NativeWindow,
            // which will unconditionally be _release()'d on Drop.
            let window = NativeWindow::clone_from_ptr(NonNull::new_unchecked(window));
            waitable_activity.set_window(Some(window));
        });
    })
}

unsafe extern "C" fn on_native_window_resized(
    activity: *mut ndk_sys::ANativeActivity,
    window: *mut ndk_sys::ANativeWindow,
) {
    log::debug!("NativeWindowResized: {:p} -- {:p}\n", activity, window);
    try_with_waitable_activity_ref(activity, |waitable_activity| {
        waitable_activity.notify_window_resized(window);
    });
}

unsafe extern "C" fn on_native_window_redraw_needed(
    activity: *mut ndk_sys::ANativeActivity,
    window: *mut ndk_sys::ANativeWindow,
) {
    log::debug!("NativeWindowRedrawNeeded: {:p} -- {:p}\n", activity, window);
    try_with_waitable_activity_ref(activity, |waitable_activity| {
        waitable_activity.notify_window_redraw_needed(window)
    });
}

unsafe extern "C" fn on_native_window_destroyed(
    activity: *mut ndk_sys::ANativeActivity,
    window: *mut ndk_sys::ANativeWindow,
) {
    abort_on_panic(|| {
        log::debug!("NativeWindowDestroyed: {:p} -- {:p}\n", activity, window);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.set_window(None);
        });
    })
}

unsafe extern "C" fn on_input_queue_created(
    activity: *mut ndk_sys::ANativeActivity,
    queue: *mut ndk_sys::AInputQueue,
) {
    abort_on_panic(|| {
        log::debug!("InputQueueCreated: {:p} -- {:p}\n", activity, queue);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.set_input(queue);
        });
    })
}

unsafe extern "C" fn on_input_queue_destroyed(
    activity: *mut ndk_sys::ANativeActivity,
    queue: *mut ndk_sys::AInputQueue,
) {
    abort_on_panic(|| {
        log::debug!("InputQueueDestroyed: {:p} -- {:p}\n", activity, queue);
        try_with_waitable_activity_ref(activity, |waitable_activity| {
            waitable_activity.set_input(ptr::null_mut());
        });
    })
}

unsafe extern "C" fn on_content_rect_changed(
    activity: *mut ndk_sys::ANativeActivity,
    rect: *const ndk_sys::ARect,
) {
    log::debug!("ContentRectChanged: {:p} -- {:p}\n", activity, rect);
    try_with_waitable_activity_ref(activity, |waitable_activity| {
        waitable_activity.set_content_rect(rect)
    });
}

/// This is the native entrypoint for our cdylib library that `ANativeActivity` will look for via `dlsym`
#[no_mangle]
extern "C" fn ANativeActivity_onCreate(
    activity: *mut ndk_sys::ANativeActivity,
    saved_state: *const libc::c_void,
    saved_state_size: libc::size_t,
) {
    abort_on_panic(|| {
        let main_looper =
            ndk::looper::ForeignLooper::for_thread().expect("Failed to get Java main looper");

        let (jvm, jni_activity) = unsafe {
            let jvm: *mut jni::sys::JavaVM = (*activity).vm.cast();
            let jni_activity: jni::sys::jobject = (*activity).clazz as _; // Completely bogus name; this is the _instance_ not class pointer
            (jni::JavaVM::from_raw(jvm), jni_activity)
        };
        unsafe {
            let saved_state = if !saved_state.is_null() && saved_state_size > 0 {
                std::slice::from_raw_parts(saved_state.cast(), saved_state_size)
            } else {
                &[]
            };
            init_java_main_thread_on_create(jvm, jni_activity as _, saved_state);
        };

        // Conceptually we associate a glue reference with the JVM main thread, and another
        // reference with the Rust main thread
        let jvm_glue = NativeActivityGlue::new(activity, saved_state, saved_state_size);

        let rust_glue = jvm_glue.clone();
        // Let us Send the NativeActivity pointer to the Rust main() thread without a wrapper type
        let activity_ptr: libc::intptr_t = activity as _;

        // Note: we drop the thread handle which will detach the thread
        std::thread::spawn(move || {
            let activity: *mut ndk_sys::ANativeActivity = activity_ptr as *mut _;
            rust_glue_entry(rust_glue, activity, main_looper);
        });

        // Wait for thread to start.
        let mut guard = jvm_glue.mutex.lock().unwrap();

        // Don't specifically wait for `Running` just in case `android_main` returns
        // immediately and the state is set to `Stopped`
        while guard.thread_state == NativeThreadState::Init {
            guard = jvm_glue.cond.wait(guard).unwrap();
        }
    })
}

fn rust_glue_entry(
    rust_glue: NativeActivityGlue,
    activity: *mut ndk_sys::ANativeActivity,
    main_looper: ndk::looper::ForeignLooper,
) {
    abort_on_panic(|| {
        let (jvm, jni_activity) = unsafe {
            let jvm: *mut jni::sys::JavaVM = (*activity).vm.cast();
            let jni_activity: jni::sys::jobject = (*activity).clazz as _; // Completely bogus name; this is the _instance_ not class pointer
            (jni::JavaVM::from_raw(jvm), jni_activity)
        };
        // Note: At this point we can assume jni::JavaVM::singleton is initialized

        // Since this is a newly spawned thread then the JVM hasn't been attached to the
        // thread yet.
        //
        // For compatibility we attach before calling the applications main function to
        // allow it to assume the thread is attached before making JNI calls.
        jvm.attach_current_thread_with_config(
            || AttachConfig::new().thread_name(jni::jni_str!("android_main")),
            Some(16),
            |env| -> jni::errors::Result<()> {
                // SAFETY: We know jni_activity is a valid JNI global ref to an Activity instance
                // that will remain valid until `onDestroy` is handled (not possible until we start
                // `android_main()`).
                let jni_activity = unsafe { env.as_cast_raw::<Global<JObject>>(&jni_activity)? };

                let (app_asset_manager, main_callbacks) =
                    match init_android_main_thread(&jvm, &jni_activity, &main_looper) {
                        Ok((asset_manager, callbacks)) => (asset_manager, callbacks),
                        Err(err) => {
                            eprintln!(
                            "Failed to name Java thread and set thread context class loader: {err}"
                        );
                            return Err(err);
                        }
                    };

                let app = AndroidApp::new(
                    jvm.clone(),
                    main_looper,
                    main_callbacks,
                    app_asset_manager,
                    rust_glue.clone(),
                    &jni_activity,
                );

                rust_glue.notify_main_thread_running();

                unsafe {
                    // We want to specifically catch any panic from the application's android_main
                    // so we can finish + destroy the Activity gracefully via the JVM
                    catch_unwind(|| {
                        // XXX: If we were in control of the Java Activity subclass then
                        // we could potentially run the android_main function via a Java native method
                        // springboard (e.g. call an Activity subclass method that calls a jni native
                        // method that then just calls android_main()) that would make sure there was
                        // a Java frame at the base of our call stack which would then be recognised
                        // when calling FindClass to lookup a suitable classLoader, instead of
                        // defaulting to the system loader. Without this then it's difficult for native
                        // code to look up non-standard Java classes.
                        android_main(app);
                    })
                    .unwrap_or_else(log_panic);

                    // Let JVM know that our Activity can be destroyed before detaching from the JVM
                    //
                    // "Note that this method can be called from any thread; it will send a message
                    //  to the main thread of the process where the Java finish call will take place"
                    ndk_sys::ANativeActivity_finish(activity);
                }

                rust_glue.notify_main_thread_stopped_running();

                Ok(())
            },
        )
        .expect("Failed to attach thread to JVM");
    })
}