telar-platform-android 0.1.2

Android platform backend for Telar, built on android-activity.
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
use android_activity::AndroidApp;
use platform_core::{
    Event, EventHandler, Platform, PlatformError, PointerButton, PointerSource, ScrollDelta,
    Window, WindowConfig,
};

// ANativeWindow_setFrameRate is API 30+ and may live in libnativewindow.so on some OEM devices rather than libandroid.so, so resolve it at runtime to avoid a hard dlopen failure on devices where the NDK stub does not match the runtime library.
#[cfg(target_os = "android")]
unsafe fn try_set_frame_rate(window: *mut std::ffi::c_void, fps: f32) {
    unsafe extern "C" {
        fn dlsym(
            handle: *mut core::ffi::c_void,
            symbol: *const core::ffi::c_char,
        ) -> *mut core::ffi::c_void;
    }
    let sym = unsafe {
        dlsym(
            core::ptr::null_mut(),
            b"ANativeWindow_setFrameRate\0".as_ptr() as _,
        )
    };
    if sym.is_null() {
        return;
    }
    let f: unsafe extern "C" fn(*mut core::ffi::c_void, f32, i8) -> i32 =
        unsafe { core::mem::transmute(sym) };
    unsafe { f(window, fps, 0) };
}

// AChoreographer is API 24+ (Android 7.0). Resolved at runtime via dlsym to avoid hard-linking failures on older NDK stubs or OEM variants.
#[cfg(target_os = "android")]
mod choreographer {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    // Opaque handle — AChoreographer is not meant to be constructed, only passed through.
    #[repr(C)]
    pub struct AChoreographer {
        _opaque: [u8; 0],
    }

    pub type FrameCallbackFn =
        unsafe extern "C" fn(frame_time_ns: i64, data: *mut core::ffi::c_void);

    // Resolve AChoreographer_getInstance at runtime; returns null on pre-API-24 devices.
    unsafe fn instance_fn() -> Option<unsafe extern "C" fn() -> *mut AChoreographer> {
        unsafe extern "C" {
            fn dlsym(
                handle: *mut core::ffi::c_void,
                symbol: *const core::ffi::c_char,
            ) -> *mut core::ffi::c_void;
        }
        let sym = unsafe {
            dlsym(
                core::ptr::null_mut(),
                b"AChoreographer_getInstance\0".as_ptr() as _,
            )
        };
        if sym.is_null() {
            None
        } else {
            Some(unsafe { core::mem::transmute(sym) })
        }
    }

    unsafe fn post_callback_fn()
    -> Option<unsafe extern "C" fn(*mut AChoreographer, FrameCallbackFn, *mut core::ffi::c_void)>
    {
        unsafe extern "C" {
            fn dlsym(
                handle: *mut core::ffi::c_void,
                symbol: *const core::ffi::c_char,
            ) -> *mut core::ffi::c_void;
        }
        let sym = unsafe {
            dlsym(
                core::ptr::null_mut(),
                b"AChoreographer_postFrameCallback\0".as_ptr() as _,
            )
        };
        if sym.is_null() {
            None
        } else {
            Some(unsafe { core::mem::transmute(sym) })
        }
    }

    // The frame callback: wakes the event loop via the proxy pointer stored in `data`, then clears the pending flag so about_to_wait can re-register on the next animation request.
    pub unsafe extern "C" fn frame_callback(_frame_time_ns: i64, data: *mut core::ffi::c_void) {
        let cb_data = unsafe { &*(data as *const VsyncCallbackData) };
        // Clear pending first so about_to_wait sees the frame was delivered.
        cb_data.is_pending.store(false, Ordering::Release);
        // Wake the winit event loop. Ignore errors — the loop may have already exited.
        let _ = cb_data.proxy.send_event(());
    }

    // Heap-allocated state shared between the runner and the vsync callback. The pointer lives for the full duration of the AndroidRunner.
    pub struct VsyncCallbackData {
        pub is_pending: Arc<AtomicBool>,
        pub proxy: winit::event_loop::EventLoopProxy<()>,
    }

    pub struct Choreographer {
        // Cached instance pointer; valid for the lifetime of the Looper thread (i.e. the main thread).
        instance: *mut AChoreographer,
        // Stable heap allocation passed as `data` to every postFrameCallback call.
        pub callback_data: Box<VsyncCallbackData>,
    }

    // The instance pointer is obtained on the main thread and only used there, so Send is safe here.
    unsafe impl Send for Choreographer {}

    impl Choreographer {
        // Returns None if AChoreographer is not available on this device/API level.
        pub fn new(
            proxy: winit::event_loop::EventLoopProxy<()>,
            pending: Arc<AtomicBool>,
        ) -> Option<Self> {
            let get_instance = unsafe { instance_fn()? };
            let instance = unsafe { get_instance() };
            if instance.is_null() {
                return None;
            }
            Some(Self {
                instance,
                callback_data: Box::new(VsyncCallbackData {
                    is_pending: pending,
                    proxy,
                }),
            })
        }

        // Post a single vsync callback. No-op if the symbols are unavailable.
        pub fn request_vsync(&self) {
            let post = match unsafe { post_callback_fn() } {
                Some(f) => f,
                None => return,
            };
            // Pass a raw pointer into the stable Box allocation; the Box outlives all callbacks.
            let data_ptr =
                self.callback_data.as_ref() as *const VsyncCallbackData as *mut core::ffi::c_void;
            unsafe { post(self.instance, frame_callback, data_ptr) };
        }
    }
}

use winit::application::ApplicationHandler;
use winit::event::{ElementState, MouseScrollDelta, StartCause, Touch, TouchPhase, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::keyboard::Key as WinitKey;
use winit::platform::android::EventLoopBuilderExtAndroid;
use winit::window::{WindowAttributes, WindowId};

use platform_winit::WinitWindow as AndroidWindow;

pub struct AndroidPlatform {
    event_loop: EventLoop<()>,
}

impl AndroidPlatform {
    pub fn try_new(app: AndroidApp) -> Result<Self, PlatformError> {
        use tracing_subscriber::filter::LevelFilter;
        use tracing_subscriber::prelude::*;

        // Route tracing events (and `log` records bridged from winit/wgpu) to Android logcat under
        // the `rsx` tag. `try_init` is a no-op if a subscriber is already installed.
        let logcat = paranoid_android::layer("telar").with_filter(LevelFilter::DEBUG);
        tracing_subscriber::registry().with(logcat).try_init().ok();

        let event_loop = EventLoop::builder()
            .with_android_app(app)
            .build()
            .map_err(|e| PlatformError(e.to_string()))?;
        Ok(Self { event_loop })
    }
}

struct AndroidRunner<H: EventHandler<AndroidWindow>> {
    handler: H,
    window: Option<AndroidWindow>,
    config: WindowConfig,
    scale_factor: f64,
    modifiers: platform_core::ModifiersState,
    cursor_position: (f64, f64),
    // Last position of an active touch finger, used to emit Scrolled deltas from drag gestures.
    last_touch_pos: Option<(f64, f64, u64)>,
    #[cfg(target_os = "android")]
    choreographer: Option<choreographer::Choreographer>,
    #[cfg(target_os = "android")]
    is_animation_pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl<H: EventHandler<AndroidWindow>> ApplicationHandler<()> for AndroidRunner<H> {
    fn new_events(&mut self, _event_loop: &ActiveEventLoop, _cause: StartCause) {
        self.handler.new_events();
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        if let Some(_d) = self.handler.about_to_wait() {
            #[cfg(target_os = "android")]
            {
                // On Android, use Choreographer vsync callbacks instead of WaitUntil wall-clock timers. This aligns frame wakeups to vsync edges, eliminating jank at any refresh rate (60/90/120 Hz).
                let already_pending = self
                    .is_animation_pending
                    .swap(true, std::sync::atomic::Ordering::AcqRel);
                if !already_pending {
                    if let Some(chore) = &self.choreographer {
                        chore.request_vsync();
                    } else if let Some(window) = &self.window {
                        // Fallback when Choreographer is unavailable (pre-API-24): request an immediate redraw and rely on WaitUntil.
                        window.request_redraw();
                        event_loop.set_control_flow(ControlFlow::WaitUntil(
                            std::time::Instant::now() + _d,
                        ));
                        return;
                    }
                }
                event_loop.set_control_flow(ControlFlow::Wait);
            }
            #[cfg(not(target_os = "android"))]
            {
                event_loop.set_control_flow(ControlFlow::WaitUntil(std::time::Instant::now() + _d));
            }
        } else {
            event_loop.set_control_flow(ControlFlow::Wait);
        }
    }

    // about_to_wait handles frame scheduling; user_event fires when the vsync callback wakes the loop.
    fn user_event(&mut self, _event_loop: &ActiveEventLoop, _event: ()) {
        if let Some(window) = &self.window {
            window.request_redraw();
        }
    }

    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        let attrs = WindowAttributes::default()
            .with_title(self.config.title.as_str())
            .with_inner_size(winit::dpi::LogicalSize::new(
                self.config.width,
                self.config.height,
            ));
        use std::sync::Arc;
        match event_loop.create_window(attrs) {
            Ok(w) => {
                // ScaleFactorChanged may not fire on first resume, so seed scale_factor here.
                self.scale_factor = w.scale_factor();
                #[cfg(target_os = "android")]
                {
                    use raw_window_handle::{HasWindowHandle, RawWindowHandle};
                    if let Ok(handle) = w.window_handle() {
                        if let RawWindowHandle::AndroidNdk(android_handle) = handle.as_raw() {
                            unsafe {
                                try_set_frame_rate(android_handle.a_native_window.as_ptr(), 60.0);
                            }
                        }
                    }
                }
                let window = AndroidWindow(Arc::new(w));
                if !self.handler.on_resume(&window) {
                    event_loop.exit();
                    return;
                }
                window.request_redraw();
                self.window = Some(window);
            }
            Err(e) => tracing::error!(error = %e, "failed to create window"),
        }
    }

    fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
        self.handler.on_suspend();
        // On Android the native window is destroyed on suspend; drop our reference so it can be recreated on resume.
        self.window = None;
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
        let Some(window) = &self.window else { return };
        match event {
            WindowEvent::CloseRequested => {
                self.handler.on_event(Event::WindowCloseRequested, window);
                event_loop.exit();
            }
            WindowEvent::Resized(size) => {
                self.handler.on_event(
                    Event::WindowResized {
                        width: (size.width as f64 / self.scale_factor).round() as u32,
                        height: (size.height as f64 / self.scale_factor).round() as u32,
                    },
                    window,
                );
                window.request_redraw();
            }
            WindowEvent::RedrawRequested => {
                self.handler.on_redraw(window);
            }
            WindowEvent::Touch(Touch {
                phase,
                location,
                id,
                ..
            }) => {
                let x = location.x / self.scale_factor;
                let y = location.y / self.scale_factor;
                let source = PointerSource::Touch { id };
                match phase {
                    TouchPhase::Started => {
                        self.last_touch_pos = Some((x, y, id));
                        self.handler.on_event(
                            Event::PointerPressed {
                                x,
                                y,
                                button: PointerButton::Primary,
                                source,
                            },
                            window,
                        );
                    }
                    TouchPhase::Moved => {
                        if let Some((lx, ly, lid)) = self.last_touch_pos {
                            if lid == id {
                                let dx = x - lx;
                                let dy = y - ly;
                                self.handler.on_event(
                                    Event::Scrolled {
                                        delta: platform_core::ScrollDelta::Pixels {
                                            x: dx as f32,
                                            y: dy as f32,
                                        },
                                    },
                                    window,
                                );
                            }
                        }
                        self.last_touch_pos = Some((x, y, id));
                        self.handler
                            .on_event(Event::PointerMoved { x, y, source }, window);
                    }
                    TouchPhase::Ended | TouchPhase::Cancelled => {
                        self.last_touch_pos = None;
                        self.handler.on_event(
                            Event::PointerReleased {
                                x,
                                y,
                                button: PointerButton::Primary,
                                source,
                            },
                            window,
                        );
                    }
                }
            }
            WindowEvent::Focused(is_focused) => {
                self.handler
                    .on_event(Event::FocusChanged { is_focused }, window);
            }
            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                self.scale_factor = scale_factor;
                self.handler
                    .on_event(Event::ScaleFactorChanged { scale_factor }, window);
            }
            WindowEvent::ModifiersChanged(mods) => {
                self.modifiers = platform_winit::map_modifiers(&mods);
            }
            WindowEvent::KeyboardInput { event, .. } => {
                let key = match &event.logical_key {
                    WinitKey::Character(c) => {
                        if let Some(ch) = c.as_str().chars().next() {
                            platform_core::Key::Char(ch)
                        } else {
                            return;
                        }
                    }
                    WinitKey::Named(named) => {
                        let Some(nk) = platform_winit::map_named_key(*named) else {
                            return;
                        };
                        platform_core::Key::Named(nk)
                    }
                    _ => return,
                };
                let modifiers = self.modifiers;
                let ev = match event.state {
                    ElementState::Pressed => platform_core::Event::KeyPressed { key, modifiers },
                    ElementState::Released => platform_core::Event::KeyReleased { key, modifiers },
                };
                self.handler.on_event(ev, window);
            }
            WindowEvent::CursorMoved { position, .. } => {
                let lx = position.x / self.scale_factor;
                let ly = position.y / self.scale_factor;
                self.cursor_position = (lx, ly);
                self.handler.on_event(
                    Event::PointerMoved {
                        x: lx,
                        y: ly,
                        source: PointerSource::Mouse,
                    },
                    window,
                );
            }
            WindowEvent::MouseInput { state, button, .. } => {
                let Some(btn) = platform_winit::map_mouse_button(button) else {
                    return;
                };
                let (x, y) = self.cursor_position;
                let ev = match state {
                    ElementState::Pressed => Event::PointerPressed {
                        x,
                        y,
                        button: btn,
                        source: PointerSource::Mouse,
                    },
                    ElementState::Released => Event::PointerReleased {
                        x,
                        y,
                        button: btn,
                        source: PointerSource::Mouse,
                    },
                };
                self.handler.on_event(ev, window);
            }
            WindowEvent::CursorEntered { .. } => {
                self.handler.on_event(Event::CursorEntered, window);
            }
            WindowEvent::CursorLeft { .. } => {
                self.handler.on_event(Event::CursorLeft, window);
            }
            WindowEvent::MouseWheel { delta, .. } => {
                let scroll_delta = match delta {
                    MouseScrollDelta::LineDelta(x, y) => ScrollDelta::Lines { x, y },
                    MouseScrollDelta::PixelDelta(pos) => ScrollDelta::Pixels {
                        x: (pos.x / self.scale_factor) as f32,
                        y: (pos.y / self.scale_factor) as f32,
                    },
                };
                self.handler.on_event(
                    Event::Scrolled {
                        delta: scroll_delta,
                    },
                    window,
                );
            }
            _ => {}
        }
    }
}

impl Platform for AndroidPlatform {
    type Window = AndroidWindow;

    fn run<H: EventHandler<Self::Window>>(
        self,
        config: WindowConfig,
        handler: H,
    ) -> Result<(), PlatformError> {
        #[cfg(target_os = "android")]
        let animation_pending = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));

        #[cfg(target_os = "android")]
        let choreographer = choreographer::Choreographer::new(
            self.event_loop.create_proxy(),
            animation_pending.clone(),
        );

        let mut runner = AndroidRunner {
            handler,
            window: None,
            config,
            scale_factor: 1.0,
            modifiers: platform_core::ModifiersState::default(),
            cursor_position: (0.0, 0.0),
            last_touch_pos: None,
            #[cfg(target_os = "android")]
            choreographer,
            #[cfg(target_os = "android")]
            is_animation_pending: animation_pending,
        };
        self.event_loop
            .run_app(&mut runner)
            .map_err(|e| PlatformError(e.to_string()))
    }
}