use std::{
cell::{Cell, RefCell},
ffi::c_void,
ptr::NonNull,
rc::Rc,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
use cranpose_app_shell::{AppShell, PlatformFrameDriver, PointerSource};
use cranpose_platform_android::AndroidPlatform;
use cranpose_render_wgpu::{DeviceLostHandler, PresentOutcome, PublishOutcome, WgpuRenderer};
use cranpose_ui::{Point, Size};
use ndk::native_window::NativeWindow;
use super::{
configuration::{read_android_configuration, refresh_android_configuration},
display_timing::{DisplayTimingObserver, DisplayedFrame},
host_window_requests::{
PendingHostWindowSizeRequest, confirm_android_host_window_request,
dispatch_android_surface_size_request, dispatch_registered_android_surface_size_request,
},
input::{AndroidInput, PendingInput, dispatch_pending_inputs},
jni::{clear_pending_android_jni_exception, with_android_activity_env},
keyboard::{self, AndroidSoftKeyboard, dispatch_android_ime_event},
overlay_window,
pipeline_cache::{keep_pipeline_cache, name_pipeline_cache_file, seed_pipeline_cache},
shell_creation::share_gpu_context,
surface::{AndroidSurfaceError, create_android_wgpu_surface},
text_input,
};
use crate::{
android_host_window,
app_launcher::{AndroidGpuBackend, AppSettings},
frame_pacer::FramePacer,
wgpu_surface::{
PresentStep, SurfaceFrame, current_surface_texture, present_initial_placeholder_frame,
surface_present_step,
},
};
pub(super) struct GpuResources {
surface: Option<wgpu::Surface<'static>>,
native_window_ptr: Option<NonNull<c_void>>,
pub(super) adapter: Arc<wgpu::Adapter>,
pub(super) device: Arc<wgpu::Device>,
pub(super) queue: Arc<wgpu::Queue>,
surface_format: wgpu::TextureFormat,
backend: wgpu::Backend,
config: wgpu::SurfaceConfiguration,
_native_window: Option<NativeWindow>,
surface_dirty: bool,
}
impl GpuResources {
fn has_surface(&self) -> bool {
self.native_window_ptr.is_some()
}
fn gpu_target(&self) -> cranpose_render_wgpu::GpuTarget {
cranpose_render_wgpu::GpuTarget {
device: Arc::clone(&self.device),
queue: Arc::clone(&self.queue),
surface_format: self.surface_format,
adapter_backend: self.backend,
adapter_downlevel: self.adapter.get_downlevel_capabilities().flags,
}
}
}
pub(crate) fn android_platform_env() -> Rc<crate::platform_env::PlatformEnvironment> {
crate::thread_state::with(|state| {
Rc::clone(
state
.android_platform_env
.get_or_init(crate::platform_env::PlatformEnvironment::new),
)
})
}
fn set_android_ime_density(density: f32) {
crate::thread_state::with(|state| state.android_ime_density.set(density.max(f32::EPSILON)));
}
pub(super) fn set_android_ime_bottom_px(bottom_px: i32) {
let density = crate::thread_state::with(|state| state.android_ime_density.get());
let bottom = (bottom_px.max(0) as f32) / density;
let insets = cranpose_ui::EdgeInsets {
bottom,
..cranpose_ui::EdgeInsets::default()
};
android_platform_env().set_ime_insets(insets);
}
fn drain_accessibility_activations(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for virtual_id in super::accessibility::drain_activations() {
if let Some((node_id, canvas_key)) = elements.identity(virtual_id) {
shell.accessibility_activate(node_id, canvas_key);
}
}
}
fn drain_accessibility_focus(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for virtual_id in super::accessibility::drain_focus_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
shell.accessibility_reveal(node_id);
}
}
fn drain_accessibility_custom_actions(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for (virtual_id, action_index) in super::accessibility::drain_custom_actions() {
let Some((node_id, canvas_key)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::perform_custom_action(root, node_id, canvas_key, action_index)
});
}
}
fn drain_accessibility_values(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for (virtual_id, value) in super::accessibility::drain_value_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::set_progress(root, node_id, value)
});
}
}
fn drain_accessibility_texts(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for (virtual_id, text) in super::accessibility::drain_text_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::set_text(root, node_id, &text)
});
}
}
fn drain_accessibility_selections(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for (virtual_id, start, end) in super::accessibility::drain_selection_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::set_text_selection_utf16(root, node_id, start, end)
});
}
}
fn drain_accessibility_expansions(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for (virtual_id, open) in super::accessibility::drain_expand_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::set_expanded(root, node_id, open)
});
}
}
fn drain_accessibility_dismissals(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for virtual_id in super::accessibility::drain_dismiss_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::dismiss(root, node_id)
});
}
}
fn drain_accessibility_long_clicks(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for virtual_id in super::accessibility::drain_long_click_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::long_click(root, node_id)
});
}
}
fn drain_accessibility_scrolls(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for (virtual_id, forward) in super::accessibility::drain_scroll_requests() {
let Some(element) = elements.element(virtual_id) else {
continue;
};
let (dx, dy) = crate::accessibility::page_delta(element, forward);
let node_id = element.node_id;
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::scroll_by(root, node_id, dx, dy)
});
}
}
fn drain_accessibility_jumps(
shell: &mut AppShell<WgpuRenderer>,
elements: &crate::accessibility::AccessibilitySnapshot,
) {
for (virtual_id, index) in super::accessibility::drain_jump_requests() {
let Some((node_id, _)) = elements.identity(virtual_id) else {
continue;
};
crate::accessibility::run_reader_action(shell, |root| {
crate::accessibility::scroll_to_index(root, node_id, index)
});
}
}
struct AndroidFrameDriver {
need_frame: Arc<AtomicBool>,
app_waker: android_activity::AndroidAppWaker,
loop_thread: std::thread::ThreadId,
next_deadline: Cell<Option<Instant>>,
clock_anchor: (i64, Instant),
last_frame_timestamp: Cell<Option<i64>>,
vsync_available: Cell<bool>,
displayed_tx: std::sync::mpsc::Sender<DisplayedFrame>,
displayed_rx: std::sync::mpsc::Receiver<DisplayedFrame>,
}
impl AndroidFrameDriver {
fn new(app_waker: android_activity::AndroidAppWaker) -> Self {
let (displayed_tx, displayed_rx) = std::sync::mpsc::channel();
Self {
need_frame: Arc::new(AtomicBool::new(false)),
app_waker,
loop_thread: std::thread::current().id(),
next_deadline: Cell::new(None),
clock_anchor: (super::frame_telemetry::monotonic_nanos(), Instant::now()),
last_frame_timestamp: Cell::new(None),
vsync_available: Cell::new(true),
displayed_tx,
displayed_rx,
}
}
fn display_timing_observer(
&self,
device: &Arc<wgpu::Device>,
) -> Option<Box<dyn cranpose_render_wgpu::PresentObserver>> {
let observer = DisplayTimingObserver::new(Arc::clone(device), self.displayed_tx.clone())?;
Some(Box::new(observer))
}
fn pace_displayed_frames(
&self,
pacer: &mut FramePacer,
telemetry: &mut super::frame_telemetry::AndroidFrameTelemetry,
) {
for frame in self.displayed_rx.try_iter() {
pacer.record_shown(frame.shown_ns, frame.queued_behind, vsync_period_ns());
pacer.record_present_margin(frame.queued_behind, frame.present_margin_ns);
pacer.record_present_return_to_display(frame.present_returned_ns, frame.shown_ns);
telemetry.note_shown(
frame.shown_ns - frame.present_returned_ns,
frame.queued_behind,
frame.present_margin_ns,
);
}
}
fn raise_frame_request(
need_frame: &AtomicBool,
app_waker: &android_activity::AndroidAppWaker,
loop_thread: std::thread::ThreadId,
) {
need_frame.store(true, Ordering::Relaxed);
if std::thread::current().id() != loop_thread {
app_waker.wake();
}
}
fn frame_waker(&self) -> impl Fn() + Send + Sync + 'static {
let need_frame = Arc::clone(&self.need_frame);
let app_waker = self.app_waker.clone();
let loop_thread = self.loop_thread;
move || Self::raise_frame_request(&need_frame, &app_waker, loop_thread)
}
fn vsync_waker(&self) -> impl Fn() + Send + Sync + 'static {
let need_frame = Arc::clone(&self.need_frame);
let app_waker = self.app_waker.clone();
move || {
need_frame.store(true, Ordering::Relaxed);
app_waker.wake();
}
}
fn frame_requested(&self) -> bool {
self.need_frame.load(Ordering::Relaxed)
}
fn take_frame_request(&self) -> bool {
self.need_frame.swap(false, Ordering::Relaxed)
}
fn deadline_timeout(&self) -> Option<Duration> {
self.next_deadline.get().map(duration_until_frame_deadline)
}
fn request_vsync(&self) -> bool {
let available = super::vsync::request_wake_at_next_vsync();
self.vsync_available.set(available);
available
}
fn schedule_frame(&self, shell: &AppShell<WgpuRenderer>) {
let schedule = shell.schedule_platform_frame(self);
if schedule.needs_frame {
self.request_vsync();
} else if shell.needs_update_without_frame() {
self.clear_wake();
self.request_frame();
}
}
fn fallback_frame_timestamp(&self, now_ns: i64) -> i64 {
let period = vsync_period_ns();
let elapsed = now_ns.saturating_sub(self.clock_anchor.0).max(0);
self.clock_anchor
.0
.saturating_add(elapsed / period * period)
}
fn dispatch_vsync(&self, shell: &mut AppShell<WgpuRenderer>) {
shell.run_pending_tasks();
let timestamp = if self.vsync_available.get() {
super::vsync::last_vsync_ns()
} else {
self.fallback_frame_timestamp(super::frame_telemetry::monotonic_nanos())
};
if timestamp <= 0
|| self
.last_frame_timestamp
.get()
.is_some_and(|last| timestamp <= last)
{
return;
}
let Some(delta) = timestamp.checked_sub(self.clock_anchor.0) else {
return;
};
let duration = Duration::from_nanos(delta.unsigned_abs());
let instant = if delta >= 0 {
self.clock_anchor.1.checked_add(duration)
} else {
self.clock_anchor.1.checked_sub(duration)
};
if let Some(instant) = instant {
self.last_frame_timestamp.set(Some(timestamp));
shell.dispatch_frame_at(instant);
self.schedule_frame(shell);
}
}
}
impl PlatformFrameDriver for AndroidFrameDriver {
fn request_frame(&self) {
Self::raise_frame_request(&self.need_frame, &self.app_waker, self.loop_thread);
}
fn request_wake_at(&self, deadline: Instant) {
self.next_deadline.set(Some(deadline));
}
fn clear_wake(&self) {
self.next_deadline.set(None);
}
}
const OFFSCREEN_UPDATE_PERIOD: Duration = Duration::from_millis(16);
const IDLE_PREFETCH_MARGIN: Duration = Duration::from_millis(1);
fn update_offscreen(
shell: Option<&mut AppShell<WgpuRenderer>>,
host_window_registry: &Rc<android_host_window::AndroidHostWindowRegistry>,
pending_ui: bool,
next_update: Option<Instant>,
) -> Option<Instant> {
let due = next_update.is_some_and(|at| at <= Instant::now());
if !pending_ui && !due {
return next_update;
}
if let Some(shell) = shell
&& shell.needs_update()
{
android_host_window::with_android_host_window_registry(host_window_registry, || {
shell.update_without_frame()
});
}
pending_ui.then(|| Instant::now() + OFFSCREEN_UPDATE_PERIOD)
}
fn start_pending_frame(
resources: &GpuResources,
shell: &mut AppShell<WgpuRenderer>,
pacer: &mut FramePacer,
) -> (bool, bool) {
let on_screen = resources.has_surface();
if resources.surface_dirty || shell.needs_redraw() {
pacer.note_visual_work();
}
let frame_due = on_screen
&& (resources.surface_dirty || shell.needs_update_without_frame())
&& shell.renderer().has_frame_credit();
let frame_starts = frame_due
&& pacer.begin_frame(
super::frame_telemetry::monotonic_nanos(),
super::vsync::last_vsync_ns(),
vsync_period_ns(),
);
(frame_starts, frame_due && !frame_starts)
}
fn wait_for_pending_frame(
pacer: &FramePacer,
driver: &AndroidFrameDriver,
mut shell: Option<&mut AppShell<WgpuRenderer>>,
idle_timeout: Option<Duration>,
) -> Option<Duration> {
let slot_open = pacer.slot_open(
super::frame_telemetry::monotonic_nanos(),
super::vsync::last_vsync_ns(),
vsync_period_ns(),
);
let has_update = shell
.as_ref()
.is_some_and(|shell| shell.needs_update_without_frame());
let starts_now = slot_open
&& has_update
&& shell
.as_mut()
.is_some_and(|shell| shell.renderer().has_frame_credit());
if starts_now {
return Some(Duration::ZERO);
}
let fallback_timeout = if driver.request_vsync() {
None
} else {
let now = super::frame_telemetry::monotonic_nanos();
Some(duration_until_ns(
now,
driver
.fallback_frame_timestamp(now)
.saturating_add(vsync_period_ns()),
))
};
let lead_timeout = (has_update && !slot_open)
.then(|| lead_wake_timeout(pacer))
.flatten();
let wait = earliest_android_poll_timeout(
earliest_android_poll_timeout(lead_timeout, idle_timeout),
fallback_timeout,
);
match shell {
Some(shell) => prefetch_while_waiting(shell, wait, slot_open),
None => wait,
}
}
fn prefetch_while_waiting(
shell: &mut AppShell<WgpuRenderer>,
wait: Option<Duration>,
slot_open: bool,
) -> Option<Duration> {
let now_ns = super::frame_telemetry::monotonic_nanos();
let period_ns = vsync_period_ns();
let frame_bound =
crate::vsync_period::next_vsync_ns(now_ns, super::vsync::last_vsync_ns(), period_ns)
.map(|vsync_ns| duration_until_ns(now_ns, vsync_ns + i64::from(slot_open) * period_ns));
let Some(idle) = earliest_android_poll_timeout(wait, frame_bound) else {
return wait;
};
if idle <= IDLE_PREFETCH_MARGIN {
return wait;
}
let now = Instant::now();
shell.run_idle_prefetch(Some(now + idle - IDLE_PREFETCH_MARGIN), |renderer| {
slot_open && renderer.frame_credit_returned()
});
wait.map(|wait| (now + wait).saturating_duration_since(Instant::now()))
}
fn duration_until_frame_deadline(deadline: Instant) -> Duration {
deadline
.checked_duration_since(Instant::now())
.unwrap_or(Duration::ZERO)
}
fn earliest_android_poll_timeout(
first: Option<Duration>,
second: Option<Duration>,
) -> Option<Duration> {
match (first, second) {
(Some(first), Some(second)) => Some(first.min(second)),
(Some(duration), None) | (None, Some(duration)) => Some(duration),
(None, None) => None,
}
}
fn get_display_density(app: &android_activity::AndroidApp) -> f32 {
let config = app.config();
let density_dpi = config.density();
density_dpi.map_or(2.0, |dpi| dpi as f32 / 160.0)
}
fn sync_ime_session(
ime_session: &keyboard::AndroidImeSession,
shell: Option<&mut AppShell<WgpuRenderer>>,
android_platform: &AndroidPlatform,
) {
let Some(shell) = shell.filter(|_| ime_session.is_active()) else {
return;
};
ime_session.sync_editor_state(shell.ime_editor_state());
ime_session.sync_field_bounds(
shell
.ime_field_bounds()
.map(|bounds| android_platform.physical_rect(bounds)),
);
}
fn surface_inset_px(app: &android_activity::AndroidApp) -> (f64, f64) {
let Some(window) = app.native_window() else {
return (0.0, 0.0);
};
let buffer_w = window.width() as f64;
let buffer_h = window.height() as f64;
let content = app.content_rect();
let frame_w = content.right as f64;
let frame_h = content.bottom as f64;
if frame_w <= 0.0 || frame_h <= 0.0 || frame_w > buffer_w || frame_h > buffer_h {
return (0.0, 0.0);
}
(
((buffer_w - frame_w) / 2.0).max(0.0),
((buffer_h - frame_h) / 2.0).max(0.0),
)
}
fn update_android_platform_geometry(
app: &android_activity::AndroidApp,
android_platform: &mut AndroidPlatform,
) -> f32 {
let density = get_display_density(app);
android_platform.set_scale_factor(density as f64);
let (offset_x, offset_y) = surface_inset_px(app);
android_platform.set_input_surface_offset_px(offset_x, offset_y);
density
}
fn update_android_shell_geometry(
shell: &mut AppShell<WgpuRenderer>,
density: f32,
host_window_registry: &android_host_window::AndroidHostWindowRegistry,
) -> Option<Size> {
shell.set_density(density);
shell.set_font_scale_curve(super::font_scale::font_scale_curve());
shell.set_rotary_scroll_factor(crate::android_input::android_rotary_scroll_factor(density));
let (width, height) = shell.buffer_size();
if width > 0 && height > 0 {
let width_dp = width as f32 / density;
let height_dp = height as f32 / density;
shell.set_viewport(width_dp, height_dp);
let actual = Size::new(width_dp, height_dp);
cranpose_services::publish_host_surface_size(
cranpose_services::host_surface::HostSurfaceSize {
width: width_dp,
height: height_dp,
scale: density,
},
);
android_host_window::sync_android_host_window_actual_size(host_window_registry, actual);
Some(actual)
} else {
None
}
}
fn resize_android_surface(
resources: &mut GpuResources,
shell: &mut AppShell<WgpuRenderer>,
width: u32,
height: u32,
present_thread: bool,
) {
if (resources.config.width, resources.config.height) == (width, height) {
return;
}
resources.config.width = width;
resources.config.height = height;
if present_thread {
if let Some(thread) = shell.renderer().present_thread() {
thread.reconfigure(resources.config.clone());
}
resources.surface_dirty = true;
} else if let Some(surface) = resources.surface.as_ref() {
surface.configure(&resources.device, &resources.config);
}
}
fn apply_initialized_android_rendering(
gpu_resources: &mut Option<GpuResources>,
current_host_window_size: &mut Size,
resources: GpuResources,
actual_size: Option<Size>,
) {
if let Some(actual_size) = actual_size {
*current_host_window_size = actual_size;
}
*gpu_resources = Some(resources);
}
fn render_once(
resources: &mut GpuResources,
shell: &mut AppShell<WgpuRenderer>,
telemetry: &mut super::frame_telemetry::AndroidFrameTelemetry,
timings: &mut super::frame_telemetry::FrameTimings,
) -> bool {
let Some(surface) = resources.surface.as_ref() else {
telemetry.note_idle_iteration();
return false;
};
match current_surface_texture(surface, "android") {
SurfaceFrame::Ready(frame) => {
timings.after_acquire_ns = super::frame_telemetry::monotonic_nanos();
let size = shell.buffer_size();
if let Err(e) = crate::wgpu_surface::render_surface_frame(
shell.renderer(),
&frame,
resources.config.format,
size,
) {
log::error!("Render error: {e:?}");
}
timings.after_render_ns = telemetry.now();
shell.renderer().present(frame);
timings.after_present_ns = super::frame_telemetry::monotonic_nanos();
telemetry.record_frame(timings);
resources.surface_dirty = false;
false
}
SurfaceFrame::Reconfigure => {
telemetry.note_idle_iteration();
let (width, height) = shell.buffer_size();
resources.config.width = width;
resources.config.height = height;
surface.configure(&resources.device, &resources.config);
resources.surface_dirty = true;
shell.mark_dirty();
false
}
SurfaceFrame::Skip => {
telemetry.note_idle_iteration();
resources.surface_dirty = true;
false
}
}
}
fn drain_present_returns_into_loop(
shell: &mut AppShell<WgpuRenderer>,
gpu_resources: &mut Option<GpuResources>,
telemetry: &mut super::frame_telemetry::AndroidFrameTelemetry,
pending_present_timings: &mut Vec<(u64, super::frame_telemetry::FrameTimings)>,
) -> Option<PresentedFrame> {
let mut presented = false;
let mut refused = false;
let mut frame_started_at_ns = 0i64;
let mut presented_at_ns = 0i64;
let mut work_ns = None;
shell
.renderer()
.drain_present_returns_with(&mut |frame_id, outcome, timings| {
let producer_timings = pending_present_timings
.iter()
.position(|(id, _)| *id == frame_id)
.map(|index| pending_present_timings.remove(index).1);
match outcome {
PresentOutcome::Presented => {
presented = true;
presented_at_ns = timings.after_present_ns;
if let Some(mut frame_timings) = producer_timings {
frame_started_at_ns = frame_timings.iteration_start_ns;
frame_timings.after_acquire_ns = timings.after_acquire_ns;
frame_timings.after_render_ns = timings.after_render_ns;
frame_timings.after_present_ns = timings.after_present_ns;
telemetry.record_frame(&frame_timings);
work_ns = frame_timings.work_ns();
}
}
PresentOutcome::Unchanged => telemetry.note_idle_iteration(),
PresentOutcome::Cancelled(_) | PresentOutcome::NotRun => {
refused = true;
telemetry.note_idle_iteration();
}
}
});
if let Some(resources) = gpu_resources.as_mut()
&& (presented || refused)
{
resources.surface_dirty = refused;
}
presented.then(|| {
let now = Instant::now();
let now_ns = telemetry.now();
let instant_at = |timestamp_ns: i64| {
let age_ns = now_ns.saturating_sub(timestamp_ns);
if timestamp_ns > 0 && age_ns > 0 {
now.checked_sub(Duration::from_nanos(age_ns as u64))
.unwrap_or(now)
} else {
now
}
};
let frame_finished_at = instant_at(presented_at_ns);
let frame_started_at = if frame_started_at_ns > 0 {
instant_at(frame_started_at_ns).min(frame_finished_at)
} else {
frame_finished_at
};
PresentedFrame {
started_at: frame_started_at,
finished_at: frame_finished_at,
work_ns,
}
})
}
struct PresentedFrame {
started_at: Instant,
finished_at: Instant,
work_ns: Option<i64>,
}
fn record_presented_frame(
shell: Option<&mut AppShell<WgpuRenderer>>,
frame_started_at: Instant,
frame_finished_at: Instant,
) {
if let Some(shell) = shell {
shell.record_presented_frame(frame_started_at, frame_finished_at);
}
}
struct AndroidGpuSetup {
resources: GpuResources,
surface: Option<wgpu::Surface<'static>>,
renderer_needs_init: bool,
}
struct AndroidWgpuContext {
instance: wgpu::Instance,
backend: AndroidGpuBackend,
}
impl AndroidWgpuContext {
fn new(backend: AndroidGpuBackend) -> Self {
let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle();
descriptor.backends = backend.wgpu_backends();
descriptor.flags = wgpu::InstanceFlags::empty();
Self {
instance: wgpu::Instance::new(descriptor),
backend,
}
}
}
fn init_gpu_threaded_for_android(
renderer: &mut WgpuRenderer,
resources: &GpuResources,
frame_driver: &AndroidFrameDriver,
) -> Result<(), AndroidSurfaceError> {
renderer
.init_gpu_threaded(
resources.gpu_target(),
Arc::new(frame_driver.frame_waker()),
Some(Arc::new(super::frame_telemetry::monotonic_nanos)),
frame_driver.display_timing_observer(&resources.device),
)
.map_err(|error| AndroidSurfaceError::PresentRuntime(format!("{error:?}")))
}
pub(super) struct ShellInputs<'a, F> {
pub(super) content: &'a Rc<RefCell<F>>,
pub(super) gpu: &'a Rc<RefCell<Option<crate::GpuContext>>>,
pub(super) settings: &'a AppSettings,
frame_driver: &'a AndroidFrameDriver,
pub(super) host_window_registry: &'a Rc<android_host_window::AndroidHostWindowRegistry>,
present_thread: bool,
}
#[derive(Clone)]
struct WindowTarget {
ptr: NonNull<c_void>,
owner: Option<NativeWindow>,
width: u32,
height: u32,
density: f32,
}
fn recover_lost_device<F>(
app: &android_activity::AndroidApp,
device_loss: &mut crate::gpu_loss::LossSignal,
wgpu_context: &mut AndroidWgpuContext,
(gpu_resources, app_shell): (
&mut Option<GpuResources>,
&mut Option<AppShell<WgpuRenderer>>,
),
inputs: &ShellInputs<'_, F>,
) where
F: FnMut() + 'static,
{
if !device_loss.take_loss() {
return;
}
if !device_loss.begin_recovery() {
log::error!("[gpu-device] the device keeps getting lost without a frame; finishing");
super::finish::finish_activity(app);
return;
}
let Some(lost) = gpu_resources.as_mut() else {
return;
};
let (window, owner) = (lost.native_window_ptr, lost._native_window.take());
let (width, height) = (lost.config.width, lost.config.height);
drop_android_surface(gpu_resources, app_shell, inputs.present_thread);
*gpu_resources = None;
let Some(window) = window else {
return;
};
let density = get_display_density(app);
let window = WindowTarget {
ptr: window,
owner,
width,
height,
density,
};
match initialize_android_rendering_with_backend_fallback(
wgpu_context,
None,
app_shell,
inputs,
window,
&device_loss.handler(super::services::wake_native_loop),
) {
Ok((resources, _)) => {
log::warn!("[gpu-device] opened a new device after the last one was lost");
*gpu_resources = Some(resources);
}
Err(error) => log::error!("[gpu-device] no new device after a loss: {error}"),
}
}
fn drop_android_surface(
gpu_resources: &mut Option<GpuResources>,
app_shell: &mut Option<AppShell<WgpuRenderer>>,
present_thread: bool,
) {
match (gpu_resources.as_mut(), app_shell.as_mut()) {
(Some(resources), Some(shell)) => {
if present_thread && let Some(thread) = shell.renderer().present_thread() {
thread.drop_surface();
}
resources.surface = None;
resources.native_window_ptr = None;
resources._native_window = None;
resources.surface_dirty = true;
}
_ => {
*gpu_resources = None;
}
}
}
fn hand_surface_to_present_thread(renderer: &mut WgpuRenderer, setup: &mut AndroidGpuSetup) {
if let Some(thread) = renderer.present_thread() {
let config = setup.resources.config.clone();
match setup.surface.take() {
Some(surface) => thread.replace_surface(surface, config),
None => thread.reconfigure(config),
};
}
setup.resources.surface_dirty = true;
}
fn initialize_android_rendering<F>(
instance: &wgpu::Instance,
existing_resources: Option<GpuResources>,
app_shell: &mut Option<AppShell<WgpuRenderer>>,
inputs: &ShellInputs<'_, F>,
window: WindowTarget,
device_lost: &DeviceLostHandler,
) -> Result<(GpuResources, Option<Size>), AndroidSurfaceError>
where
F: FnMut() + 'static,
{
let (frame_driver, present_thread) = (inputs.frame_driver, inputs.present_thread);
let (width, height, density) = (window.width, window.height, window.density);
let mut setup = create_android_gpu_resources(
instance,
existing_resources,
window.ptr,
window.owner,
width,
height,
)?;
share_gpu_context(inputs.gpu, instance, &setup.resources, app_shell.as_mut());
let mut surface_handed = false;
if app_shell.is_none() {
let fonts = inputs.settings.resolve_fonts();
let mut renderer = WgpuRenderer::with_text_fonts(fonts);
renderer.set_device_lost_handler(Arc::clone(device_lost));
if present_thread {
init_gpu_threaded_for_android(&mut renderer, &setup.resources, frame_driver)?;
hand_surface_to_present_thread(&mut renderer, &mut setup);
surface_handed = true;
} else {
renderer.init_gpu(setup.resources.gpu_target());
}
let shell = super::shell_creation::create(renderer, inputs, width, height, density);
*app_shell = Some(shell);
if let Some(shell) = app_shell {
shell.set_frame_waker(frame_driver.frame_waker());
}
log::info!("App shell created");
} else if setup.renderer_needs_init {
if let Some(shell) = app_shell {
shell
.renderer()
.set_device_lost_handler(Arc::clone(device_lost));
if present_thread {
init_gpu_threaded_for_android(shell.renderer(), &setup.resources, frame_driver)?;
} else {
shell.renderer().init_gpu(setup.resources.gpu_target());
}
log::info!("Renderer reinitialized with new Android GPU pipeline resources");
}
} else {
log::debug!("Reused Android WGPU device and renderer resources for surface update");
}
if present_thread {
if let Some(shell) = app_shell.as_mut() {
if !surface_handed {
hand_surface_to_present_thread(shell.renderer(), &mut setup);
}
shell.mark_dirty();
}
} else {
match setup.surface.take() {
Some(surface) => {
surface.configure(&setup.resources.device, &setup.resources.config);
present_initial_placeholder_frame(
&surface,
&setup.resources.device,
&setup.resources.queue,
setup.resources.surface_format,
"android initial present",
);
setup.resources.surface = Some(surface);
}
None => {
if let Some(surface) = setup.resources.surface.as_ref() {
surface.configure(&setup.resources.device, &setup.resources.config);
}
}
}
if let Some(shell) = app_shell.as_mut() {
setup.resources.surface_dirty = true;
shell.mark_dirty();
}
}
if let Some(shell) = app_shell {
shell.set_density(density);
set_android_ime_density(density);
}
let actual_size = app_shell.as_mut().and_then(|shell| {
shell.set_buffer_size(width, height);
update_android_shell_geometry(shell, density, inputs.host_window_registry)
});
Ok((setup.resources, actual_size))
}
fn initialize_android_rendering_with_backend_fallback<F>(
wgpu_context: &mut AndroidWgpuContext,
existing_resources: Option<GpuResources>,
app_shell: &mut Option<AppShell<WgpuRenderer>>,
inputs: &ShellInputs<'_, F>,
window: WindowTarget,
device_lost: &DeviceLostHandler,
) -> Result<(GpuResources, Option<Size>), AndroidSurfaceError>
where
F: FnMut() + 'static,
{
if existing_resources.is_some() || wgpu_context.backend == AndroidGpuBackend::OpenGlEs {
return initialize_android_rendering(
&wgpu_context.instance,
existing_resources,
app_shell,
inputs,
window,
device_lost,
);
}
match initialize_android_rendering(
&wgpu_context.instance,
None,
app_shell,
inputs,
window.clone(),
device_lost,
) {
Err(AndroidSurfaceError::RequestAdapter(error)) => {
log::warn!("No compatible Vulkan adapter ({error}); retrying with a fresh GL instance");
*wgpu_context = AndroidWgpuContext::new(AndroidGpuBackend::OpenGlEs);
initialize_android_rendering(
&wgpu_context.instance,
None,
app_shell,
inputs,
window,
device_lost,
)
}
result => result,
}
}
fn create_android_gpu_resources(
instance: &wgpu::Instance,
existing_resources: Option<GpuResources>,
native_window_ptr: NonNull<c_void>,
native_window_owner: Option<NativeWindow>,
width: u32,
height: u32,
) -> Result<AndroidGpuSetup, AndroidSurfaceError> {
if let Some(mut resources) = existing_resources {
if resources.native_window_ptr == Some(native_window_ptr) {
resources.config.width = width;
resources.config.height = height;
if let Some(native_window_owner) = native_window_owner {
resources._native_window = Some(native_window_owner);
}
return Ok(AndroidGpuSetup {
resources,
surface: None,
renderer_needs_init: false,
});
}
return create_android_gpu_resources_for_existing_device(
instance,
&resources,
native_window_ptr,
native_window_owner,
width,
height,
);
}
let surface = create_android_wgpu_surface(instance, native_window_ptr)?;
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
apply_limit_buckets: false,
}))?;
let adapter_info = adapter.get_info();
log::info!("Found adapter: {:?}", adapter_info.backend);
let adapter = Arc::new(adapter);
name_pipeline_cache_file(&adapter_info);
seed_pipeline_cache();
let (device, queue) = super::device::request_device(&adapter)?;
let device = Arc::new(device);
let queue = Arc::new(queue);
let config = create_android_surface_config(&surface, &adapter, width, height)?;
Ok(AndroidGpuSetup {
resources: GpuResources {
surface: None,
native_window_ptr: Some(native_window_ptr),
adapter,
device,
queue,
surface_format: crate::surface_format::display_surface_view_format(config.format),
backend: adapter_info.backend,
config,
_native_window: native_window_owner,
surface_dirty: true,
},
surface: Some(surface),
renderer_needs_init: true,
})
}
fn create_android_gpu_resources_for_existing_device(
instance: &wgpu::Instance,
existing: &GpuResources,
native_window_ptr: NonNull<c_void>,
native_window_owner: Option<NativeWindow>,
width: u32,
height: u32,
) -> Result<AndroidGpuSetup, AndroidSurfaceError> {
let surface = create_android_wgpu_surface(instance, native_window_ptr)?;
let config = create_android_surface_config(&surface, &existing.adapter, width, height)?;
let renderer_needs_init = crate::surface_format::display_surface_view_format(config.format)
!= existing.surface_format;
Ok(AndroidGpuSetup {
resources: GpuResources {
surface: None,
native_window_ptr: Some(native_window_ptr),
adapter: Arc::clone(&existing.adapter),
device: Arc::clone(&existing.device),
queue: Arc::clone(&existing.queue),
surface_format: crate::surface_format::display_surface_view_format(config.format),
backend: existing.backend,
config,
_native_window: native_window_owner,
surface_dirty: true,
},
surface: Some(surface),
renderer_needs_init,
})
}
fn frame_pacing(level: Option<crate::frame_pacer::Level>) -> super::frame_telemetry::FramePacing {
use super::frame_telemetry::FramePacing;
match level {
None => FramePacing::Unreported,
Some(crate::frame_pacer::Level::Shallow) => FramePacing::Shallow,
Some(crate::frame_pacer::Level::Buffered) => FramePacing::Buffered,
Some(crate::frame_pacer::Level::Unpaced) => FramePacing::Unpaced,
}
}
fn vsync_period_ns() -> i64 {
match super::frame_telemetry::vsync_period_ns() {
reported if reported > 0 => reported,
_ => super::vsync::observed_vsync_period_ns().unwrap_or(16_666_667),
}
}
fn lead_wake_timeout(pacer: &FramePacer) -> Option<Duration> {
let now_ns = super::frame_telemetry::monotonic_nanos();
pacer
.lead_wake_ns(now_ns, super::vsync::last_vsync_ns(), vsync_period_ns())
.map(|wake_ns| duration_until_ns(now_ns, wake_ns))
}
fn duration_until_ns(now_ns: i64, at_ns: i64) -> Duration {
Duration::from_nanos(u64::try_from(at_ns.saturating_sub(now_ns)).unwrap_or(0))
}
fn android_frame_latency(requested: Option<&str>) -> u32 {
requested
.and_then(|value| value.trim().parse::<u32>().ok())
.filter(|latency| (1..=3).contains(latency))
.unwrap_or(3)
}
#[cfg(test)]
#[path = "tests/event_loop_frame_latency_tests.rs"]
mod frame_latency_tests;
fn create_android_surface_config(
surface: &wgpu::Surface<'static>,
adapter: &wgpu::Adapter,
width: u32,
height: u32,
) -> Result<wgpu::SurfaceConfiguration, AndroidSurfaceError> {
let surface_caps = surface.get_capabilities(adapter);
let surface_format =
crate::surface_format::select_display_surface_format(&surface_caps.formats)
.ok_or(AndroidSurfaceError::NoSurfaceFormat)?;
let alpha_mode = surface_caps
.alpha_modes
.first()
.copied()
.ok_or(AndroidSurfaceError::NoAlphaMode)?;
let present_mode = crate::present_mode::select_android_present_mode(&surface_caps);
let desired_maximum_frame_latency = android_frame_latency(
super::frame_telemetry::system_property("debug.cranpose.frame_latency").as_deref(),
);
let config = crate::wgpu_surface::root_surface_config(
&surface_caps,
surface_format,
(width, height),
present_mode,
alpha_mode,
desired_maximum_frame_latency,
);
log::info!(
"Android surface: formats {:?}, usages {:?} (configured {:?}), supported present modes {:?}, selected {:?}, desired_maximum_frame_latency {}",
surface_caps.formats,
surface_caps.usages,
config.usage,
surface_caps.present_modes,
present_mode,
desired_maximum_frame_latency,
);
Ok(config)
}
fn android_activity_in_multi_window_mode(app: &android_activity::AndroidApp) -> bool {
use jni::{jni_sig, jni_str};
with_android_activity_env(app, |env, activity| {
env.call_method(
&activity,
jni_str!("isInMultiWindowMode"),
jni_sig!("()Z"),
&[],
)
.and_then(jni::JValueOwned::z)
.map_err(|error| {
clear_pending_android_jni_exception(env);
format!("failed to query Android multi-window mode: {error}")
})
})
.unwrap_or_else(|error| {
log::warn!("{error}");
false
})
}
pub(crate) const DEFAULT_LOG_TAG: &str = "Cranpose";
pub(crate) fn init_logging(tag: &str) {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(log::LevelFilter::Info)
.with_tag(tag)
.with_filter(
android_logger::FilterBuilder::new()
.filter_level(log::LevelFilter::Info)
.filter_module("wgpu_core", log::LevelFilter::Warn)
.filter_module("wgpu_hal", log::LevelFilter::Warn)
.filter_module("naga", log::LevelFilter::Warn)
.filter_module("android_activity::activity_impl", log::LevelFilter::Off)
.build(),
),
);
}
pub fn run(
app: android_activity::AndroidApp,
settings: AppSettings,
content: impl FnMut() + 'static,
) {
use android_activity::{MainEvent, PollEvent};
super::process::start_for_activity(&app, &settings);
super::pipeline_update::note_app_launched();
super::frame_telemetry::seed_env_from_system_properties();
cranpose_render_wgpu::pin_current_thread_to_fast_cores("producer");
keep_pipeline_cache(&app);
let present_thread = super::present_thread::presents_on_thread();
if present_thread {
log::info!("[present-runtime] threaded present enabled");
}
super::services::register_all(&app, &settings);
read_android_configuration(&app);
super::font_scale::refresh_font_scale(&app);
super::app_info::install_app_info(&app);
let content = Rc::new(RefCell::new(content));
let mut app_shell: Option<AppShell<WgpuRenderer>> = None;
#[cfg(feature = "webview")]
let mut webviews = crate::webview_host::WebViews::default();
let mut accessibility_elements = crate::accessibility::AccessibilitySnapshot::default();
let mut accessibility_wire = super::accessibility_wire::AccessibilityWire::default();
let mut accessibility_watch = crate::accessibility::TreeWatch::default();
let mut accessibility_policy =
crate::accessibility_publish_policy::AccessibilityPublishPolicy::new();
log::info!("Starting Compose Android Application");
let android_frame_driver = AndroidFrameDriver::new(app.create_waker());
let mut frame_rate_voter = super::frame_rate::FrameRateVoter::default();
let mut frame_work_hints = super::perf_hint::FrameWorkHints::default();
let mut frame_rate_boost = cranpose_app_shell::FrameRateBoost::default();
super::vsync::install_waker(android_frame_driver.vsync_waker());
super::accessibility::set_waker(app.create_waker());
let host_window_registry = Rc::new(android_host_window::AndroidHostWindowRegistry::default());
let shell_inputs = ShellInputs {
content: &content,
gpu: &Rc::default(),
settings: &settings,
frame_driver: &android_frame_driver,
host_window_registry: &host_window_registry,
present_thread,
};
let overlay_event_queue = Arc::new(overlay_window::AndroidOverlayEventQueue::default());
let ime_event_queue = Arc::new(text_input::AndroidImeEventQueue::new());
ime_event_queue.set_waker(app.create_waker());
let ime_session = keyboard::AndroidImeSession::new(app.clone(), Arc::clone(&ime_event_queue));
let should_exit = Arc::new(AtomicBool::new(false));
let mut wgpu_context = AndroidWgpuContext::new(
settings.android_gpu_backend.with_override(
std::env::var("CRANPOSE_ANDROID_GPU_BACKEND")
.ok()
.as_deref(),
),
);
let mut android_platform = AndroidPlatform::new();
let mut current_host_window_size = Size::ZERO;
let mut device_loss = crate::gpu_loss::LossSignal::default();
let mut device_loss_drill = crate::gpu_loss::LossDrill::from_launch_args(
&device_loss,
super::services::wake_native_loop,
);
let mut initial_host_window_size = settings.initial_size_explicit.then(|| {
Size::new(
settings.initial_width as f32,
settings.initial_height as f32,
)
});
let mut last_dispatched_host_window_request =
None::<(android_host_window::AndroidHostWindowState, u64, u64)>;
let mut pending_host_window_confirmation = None::<PendingHostWindowSizeRequest>;
let mut overlay_window_options = settings.android_overlay_window;
let mut overlay_window_requested = false;
let mut gpu_resources: Option<GpuResources> = None;
let mut input = AndroidInput::new(app.clone());
let mut soft_keyboard_installed = false;
let mut next_offscreen_update: Option<Instant> = None;
let mut frame_telemetry =
super::frame_telemetry::AndroidFrameTelemetry::from_system_properties();
super::frame_telemetry::start_vsync_probe_if_enabled();
const MAX_EXIT_ATTEMPTS: u32 = 3;
let mut exit_attempts = 0u32;
let mut frame_pacer = FramePacer::default();
let mut frame_waits_for_vsync = false;
let mut pending_present_timings =
Vec::<(u64, super::frame_telemetry::FrameTimings)>::with_capacity(2);
loop {
let mut frame_timings = super::frame_telemetry::FrameTimings {
iteration_start_ns: frame_telemetry.now(),
..Default::default()
};
let drained_presented = match app_shell.as_mut() {
Some(shell) => drain_present_returns_into_loop(
shell,
&mut gpu_resources,
&mut frame_telemetry,
&mut pending_present_timings,
),
None => None,
};
android_frame_driver.pace_displayed_frames(&mut frame_pacer, &mut frame_telemetry);
recover_lost_device(
&app,
&mut device_loss,
&mut wgpu_context,
(&mut gpu_resources, &mut app_shell),
&shell_inputs,
);
let pending_confirmation_timeout = pending_host_window_confirmation.map(|pending| {
android_host_window::HOST_WINDOW_CONFIRMATION_TIMEOUT
.checked_sub(pending.requested_at.elapsed())
.unwrap_or(Duration::ZERO)
});
let no_surface = gpu_resources
.as_ref()
.is_none_or(|resources| !resources.has_surface());
match app_shell.as_ref() {
Some(shell) if !no_surface => {
android_frame_driver.schedule_frame(shell);
}
_ => android_frame_driver.clear_wake(),
}
let frame_deadline_timeout = android_frame_driver.deadline_timeout();
let offscreen = no_surface && cranpose_services::background_active();
if !offscreen {
next_offscreen_update = None;
}
let offscreen_pending_ui =
offscreen && app_shell.as_ref().is_some_and(AppShell::has_pending_ui);
let offscreen_timeout = next_offscreen_update.map(duration_until_frame_deadline);
let accessibility_flush_timeout = accessibility_policy
.wake_deadline()
.map(|deadline| deadline.saturating_duration_since(Instant::now()));
let idle_timeout = match no_surface {
true => earliest_android_poll_timeout(pending_confirmation_timeout, offscreen_timeout),
false => earliest_android_poll_timeout(
earliest_android_poll_timeout(pending_confirmation_timeout, frame_deadline_timeout),
accessibility_flush_timeout,
),
};
if let Some(shell) = app_shell.as_ref() {
let preference = shell.frame_rate_preference();
let producing_frames = android_frame_driver.frame_requested();
let boosted = frame_rate_boost.boosted(Instant::now());
let panel_max = match preference {
cranpose_app_shell::FrameRatePreference::Auto if boosted => {
super::frame_rate::panel_max_refresh_rate(&app)
}
_ => None,
};
frame_rate_voter.apply(
&app,
preference.desired_rate_hz(producing_frames, boosted, panel_max),
);
}
let poll_duration = if !input.pending.is_empty() {
Some(Duration::ZERO)
} else if no_surface {
match offscreen_pending_ui {
true => Some(Duration::ZERO),
false => idle_timeout,
}
} else if android_frame_driver.frame_requested() || frame_waits_for_vsync {
wait_for_pending_frame(
&frame_pacer,
&android_frame_driver,
app_shell.as_mut(),
idle_timeout,
)
} else {
idle_timeout
};
app.poll_events(super::poll::poll_timeout(poll_duration), |event| {
if let PollEvent::Main(main_event) = event {
match main_event {
MainEvent::InitWindow { .. } => {
log::info!("Window initialized, setting up rendering");
if let Some(options) = overlay_window_options {
let density =
update_android_platform_geometry(&app, &mut android_platform);
android_platform.set_input_surface_offset_px(0.0, 0.0);
if !overlay_window_requested {
match overlay_window::show_android_overlay_window(
&app,
options,
density,
&overlay_event_queue,
) {
Ok(()) => {
overlay_window_requested = true;
log::info!(
"Requested Android overlay surface {}x{} dp at ({}, {})",
options.width,
options.height,
options.x,
options.y
);
}
Err(error) => {
overlay_window_options = None;
log::warn!(
"Android overlay surface unavailable; waiting for activity surface fallback: {error}"
);
}
}
}
}
if overlay_window_options.is_none()
&& let Some(native_window) = app.native_window() {
let width = native_window.width() as u32;
let height = native_window.height() as u32;
let density =
update_android_platform_geometry(&app, &mut android_platform);
let (input_offset_x, input_offset_y) =
android_platform.input_surface_offset_px();
log::info!(
"Display density: {density:.2}x, input surface offset: ({input_offset_x:.1}, {input_offset_y:.1}) px"
);
match initialize_android_rendering_with_backend_fallback(
&mut wgpu_context,
gpu_resources.take(),
&mut app_shell,
&shell_inputs,
WindowTarget {
ptr: native_window.ptr().cast(),
owner: None,
width,
height,
density,
},
&device_loss.handler(super::services::wake_native_loop),
) {
Ok((resources, actual_size)) => {
if let Some(actual_size) = actual_size {
current_host_window_size = actual_size;
}
let width_dp = current_host_window_size.width;
let height_dp = current_host_window_size.height;
log::info!(
"Set viewport to {width_dp:.1}x{height_dp:.1} dp ({width}x{height} px at {density:.2}x density)"
);
if let Some(requested) = initial_host_window_size.take() {
if !android_activity_in_multi_window_mode(&app) {
log::info!(
"Ignoring initial window size {:.1}x{:.1} dp: fullscreen Android activities keep the display-sized edge-to-edge surface; size requests apply in multi-window/freeform modes",
requested.width,
requested.height
);
} else {
match dispatch_android_surface_size_request(
&app,
requested,
Point::ZERO,
density,
None,
) {
Ok(()) => {
pending_host_window_confirmation =
Some(PendingHostWindowSizeRequest {
state: None,
requested,
requested_at: Instant::now(),
});
log::info!(
"Requested initial Android host-window size {:.1}x{:.1} dp",
requested.width,
requested.height
);
}
Err(error) => {
log::warn!(
"Initial Android host-window size request failed: {error}"
);
}
}
}
}
gpu_resources = Some(resources);
log::info!("Rendering initialized successfully");
}
Err(error) => {
log::error!("Android rendering initialization failed: {error}");
}
}
}
}
MainEvent::TerminateWindow { .. } => {
log::info!("Window terminated");
if overlay_window_options.is_none() {
drop_android_surface(
&mut gpu_resources,
&mut app_shell,
present_thread,
);
}
}
MainEvent::WindowResized { .. } => {
if overlay_window_options.is_none()
&& let Some(native_window) = app.native_window() {
let width = native_window.width() as u32;
let height = native_window.height() as u32;
let density =
update_android_platform_geometry(&app, &mut android_platform);
let (input_offset_x, input_offset_y) =
android_platform.input_surface_offset_px();
log::info!(
"Window resized to {width}x{height} at {density:.2}x density with input surface offset ({input_offset_x:.1}, {input_offset_y:.1}) px"
);
if let (Some(resources), Some(shell)) =
(&mut gpu_resources, &mut app_shell)
&& width > 0 && height > 0 {
resize_android_surface(
resources,
shell,
width,
height,
present_thread,
);
shell.set_buffer_size(width, height);
if let Some(actual_size) =
update_android_shell_geometry(
shell,
density,
&host_window_registry,
)
{
current_host_window_size = actual_size;
}
}
}
}
MainEvent::ContentRectChanged { .. } => {
let density = update_android_platform_geometry(&app, &mut android_platform);
if overlay_window_options.is_some() {
android_platform.set_input_surface_offset_px(0.0, 0.0);
}
let (input_offset_x, input_offset_y) =
android_platform.input_surface_offset_px();
log::info!(
"Content rect changed; input surface offset: ({input_offset_x:.1}, {input_offset_y:.1}) px at {density:.2}x density"
);
if let Some(shell) = &mut app_shell
&& let Some(actual_size) =
update_android_shell_geometry(shell, density, &host_window_registry)
{
current_host_window_size = actual_size;
}
}
MainEvent::RedrawNeeded { .. } => {
if let Some(shell) = &mut app_shell {
shell.mark_dirty();
}
}
MainEvent::Pause => {
log::info!("App paused");
cranpose_services::dispatch_lifecycle_state(
cranpose_services::LifecycleState::Paused,
);
if let Some(shell) = &mut app_shell {
shell.notify_app_paused();
}
ime_session.ensure_hidden();
}
MainEvent::Resume { .. } => {
log::info!("App resumed");
cranpose_services::dispatch_lifecycle_state(
cranpose_services::LifecycleState::Resumed,
);
let reopened = app_shell
.as_mut()
.is_some_and(AppShell::notify_app_resumed);
if !reopened {
ime_session.ensure_hidden();
}
}
MainEvent::Start => {
log::info!("App started");
cranpose_services::dispatch_lifecycle_state(
cranpose_services::LifecycleState::Started,
);
}
MainEvent::Stop => {
log::info!("App stopped");
cranpose_services::dispatch_lifecycle_state(
cranpose_services::LifecycleState::Stopped,
);
}
MainEvent::SaveState { .. } => {
log::info!("Save state requested");
}
MainEvent::Destroy => {
log::info!("App destroy requested, will exit after this event");
cranpose_services::dispatch_lifecycle_state(
cranpose_services::LifecycleState::Destroyed,
);
if overlay_window_options.is_some() {
overlay_window::hide_android_overlay_window(&app);
}
should_exit.store(true, Ordering::Relaxed);
}
MainEvent::InputAvailable => input.drain(
&app,
&android_platform,
app_shell.as_mut(),
&mut frame_rate_boost,
),
MainEvent::ConfigChanged { .. } => {
refresh_android_configuration(&app, &mut app_shell);
}
_ => {}
}
}
});
frame_timings.after_poll_ns = frame_telemetry.now();
for event in overlay_window::drain_android_overlay_window_events(&overlay_event_queue) {
match event {
overlay_window::AndroidOverlayWindowEvent::CreateFailed(message) => {
log::warn!("Android overlay surface failed: {message}");
overlay_window_options = None;
if let Some(native_window) = app.native_window() {
let width = native_window.width() as u32;
let height = native_window.height() as u32;
if width > 0 && height > 0 {
let density =
update_android_platform_geometry(&app, &mut android_platform);
match initialize_android_rendering_with_backend_fallback(
&mut wgpu_context,
gpu_resources.take(),
&mut app_shell,
&shell_inputs,
WindowTarget {
ptr: native_window.ptr().cast(),
owner: None,
width,
height,
density,
},
&device_loss.handler(super::services::wake_native_loop),
) {
Ok((resources, actual_size)) => {
apply_initialized_android_rendering(
&mut gpu_resources,
&mut current_host_window_size,
resources,
actual_size,
);
}
Err(error) => {
log::error!(
"Android activity surface fallback initialization failed: {error}"
);
}
}
}
}
}
overlay_window::AndroidOverlayWindowEvent::SurfaceChanged {
native_window,
width,
height,
} => {
if width > 0 && height > 0 {
let density = get_display_density(&app);
android_platform.set_scale_factor(density as f64);
android_platform.set_input_surface_offset_px(0.0, 0.0);
if let Some(shell) = app_shell.as_mut() {
shell.set_density(density);
}
let native_window_ptr = native_window.ptr().cast();
match initialize_android_rendering_with_backend_fallback(
&mut wgpu_context,
gpu_resources.take(),
&mut app_shell,
&shell_inputs,
WindowTarget {
ptr: native_window_ptr,
owner: Some(native_window),
width,
height,
density,
},
&device_loss.handler(super::services::wake_native_loop),
) {
Ok((resources, actual_size)) => {
apply_initialized_android_rendering(
&mut gpu_resources,
&mut current_host_window_size,
resources,
actual_size,
);
log::info!(
"Android overlay surface ready at {width}x{height} px ({density:.2}x density)"
);
}
Err(error) => {
log::error!(
"Android overlay surface initialization failed: {error}"
);
}
}
}
}
overlay_window::AndroidOverlayWindowEvent::SurfaceDestroyed => {
if overlay_window_options.is_some() {
drop_android_surface(&mut gpu_resources, &mut app_shell, present_thread);
}
}
overlay_window::AndroidOverlayWindowEvent::Pointer { action, x, y } => {
let logical = android_platform.pointer_position(x as f64, y as f64);
match action {
overlay_window::AndroidOverlayPointerAction::Down => {
input.pending.push(PendingInput::PointerDown(
logical.x,
logical.y,
None,
PointerSource::Touch,
));
}
overlay_window::AndroidOverlayPointerAction::Up => {
input.pending.push(PendingInput::PointerUp(
logical.x,
logical.y,
None,
PointerSource::Touch,
));
}
overlay_window::AndroidOverlayPointerAction::Cancel => {
input.pending.push(PendingInput::PointerCancel);
}
overlay_window::AndroidOverlayPointerAction::Move => {
input.pending.push(PendingInput::PointerMove(
logical.x,
logical.y,
None,
PointerSource::Touch,
));
}
}
}
}
}
if !soft_keyboard_installed && let Some(shell) = &mut app_shell {
shell.set_platform_text_input(Rc::new(AndroidSoftKeyboard::new(Rc::clone(
&ime_session,
))));
soft_keyboard_installed = true;
log::info!("Android soft keyboard focus hook installed");
let clipboard_app = app.clone();
shell.app_context().enter(move || {
cranpose_ui::clipboard_session::set_platform_clipboard(Rc::new(
super::services::AndroidClipboard { app: clipboard_app },
));
});
if !shell.notify_app_resumed() {
ime_session.ensure_hidden();
log::info!("No focused field at launch; ensured soft keyboard hidden");
}
}
if let Some(shell) = &mut app_shell {
drain_accessibility_activations(shell, &accessibility_elements);
drain_accessibility_custom_actions(shell, &accessibility_elements);
drain_accessibility_focus(shell, &accessibility_elements);
drain_accessibility_values(shell, &accessibility_elements);
drain_accessibility_texts(shell, &accessibility_elements);
drain_accessibility_selections(shell, &accessibility_elements);
drain_accessibility_scrolls(shell, &accessibility_elements);
drain_accessibility_jumps(shell, &accessibility_elements);
drain_accessibility_expansions(shell, &accessibility_elements);
drain_accessibility_dismissals(shell, &accessibility_elements);
drain_accessibility_long_clicks(shell, &accessibility_elements);
for event in ime_event_queue.drain() {
dispatch_android_ime_event(shell, event);
}
}
super::services::apply_pending_platform_signals(get_display_density(&app), &mut app_shell);
if !input.pending.is_empty()
&& let Some(shell) = &mut app_shell
{
frame_rate_boost.note_input(Instant::now());
dispatch_pending_inputs(&app, shell, &mut input.pending);
}
sync_ime_session(&ime_session, app_shell.as_mut(), &android_platform);
android_frame_driver.take_frame_request();
confirm_android_host_window_request(
&mut pending_host_window_confirmation,
current_host_window_size,
);
if cranpose_services::exit_requested() && exit_attempts < MAX_EXIT_ATTEMPTS {
exit_attempts += 1;
log::info!("App requested exit; finishing the activity");
if super::finish::finish_activity(&app) {
let _ = cranpose_services::take_exit_request();
} else if exit_attempts == MAX_EXIT_ATTEMPTS {
log::error!(
"giving up on the app's exit request after {MAX_EXIT_ATTEMPTS} attempts; \
the activity is still up"
);
let _ = cranpose_services::take_exit_request();
}
}
if should_exit.load(Ordering::Relaxed) {
log::info!("Exiting cleanly after Destroy event");
break;
}
if offscreen {
next_offscreen_update = update_offscreen(
app_shell.as_mut(),
&host_window_registry,
offscreen_pending_ui,
next_offscreen_update,
);
}
let mut frame_started_at: Option<Instant> = None;
#[cfg(feature = "webview")]
webviews.dispatch(&android_platform_env().native_views);
frame_waits_for_vsync = false;
if let (Some(resources), Some(shell)) = (&mut gpu_resources, &mut app_shell) {
frame_timings.work_start_ns = super::frame_telemetry::monotonic_nanos();
if resources.has_surface() {
android_host_window::with_android_host_window_registry(
&host_window_registry,
|| {
android_frame_driver.dispatch_vsync(shell);
},
);
}
let (frame_starts, waits_for_vsync) =
start_pending_frame(resources, shell, &mut frame_pacer);
frame_waits_for_vsync = waits_for_vsync;
if frame_starts {
frame_timings.pacing = frame_pacing(frame_pacer.current_level());
frame_timings.lead_ns = frame_pacer.current_lead_ns(vsync_period_ns());
frame_started_at = Some(Instant::now());
let update_result = android_host_window::with_android_host_window_registry(
&host_window_registry,
|| shell.update_without_frame(),
);
frame_rate_boost.note_frame(update_result, Instant::now());
#[cfg(feature = "webview")]
super::webview::sync(
&mut webviews,
&android_platform_env().native_views,
shell,
&app,
);
frame_timings.after_update_ns = frame_telemetry.now();
dispatch_registered_android_surface_size_request(
&app,
&host_window_registry,
android_platform.scale_factor(),
overlay_window_options,
&mut last_dispatched_host_window_request,
&mut pending_host_window_confirmation,
);
frame_timings.after_sync_ns = frame_telemetry.now();
if let PresentStep::Present = surface_present_step(
resources.surface_dirty,
update_result.visual_changed,
&mut shell.primary(),
) {
if present_thread {
let (width, height) = shell.buffer_size();
match shell.renderer().publish_frame(width, height) {
PublishOutcome::Published => {
frame_timings.handed_off_ns =
super::frame_telemetry::monotonic_nanos();
pending_present_timings.push((
shell.renderer().last_published_frame_id(),
frame_timings,
));
}
PublishOutcome::NoGraph | PublishOutcome::NoCredit => {
frame_pacer.note_empty_frame(
super::frame_telemetry::monotonic_nanos(),
super::vsync::last_vsync_ns(),
vsync_period_ns(),
);
frame_telemetry.note_idle_iteration();
}
}
} else {
frame_timings.handed_off_ns = super::frame_telemetry::monotonic_nanos();
if render_once(resources, shell, &mut frame_telemetry, &mut frame_timings) {
break;
}
}
} else {
frame_pacer.note_empty_frame(
super::frame_telemetry::monotonic_nanos(),
super::vsync::last_vsync_ns(),
vsync_period_ns(),
);
frame_telemetry.note_idle_iteration();
}
} else {
frame_telemetry.note_idle_iteration();
}
if let Err(error) = super::accessibility::sync(
&app,
shell,
android_platform.scale_factor(),
&mut accessibility_elements,
&mut accessibility_wire,
&mut accessibility_watch,
&mut accessibility_policy,
) {
log::warn!("{error}");
}
} else {
frame_telemetry.note_idle_iteration();
}
let presented = if frame_timings.after_present_ns != 0 {
let finished_at = Instant::now();
Some(PresentedFrame {
started_at: frame_started_at.unwrap_or(finished_at),
finished_at,
work_ns: frame_timings.work_ns(),
})
} else {
drained_presented
};
if let Some(frame) = presented {
device_loss.presented();
device_loss_drill.presented();
if let Some(work_ns) = frame.work_ns {
let present_thread = app_shell
.as_mut()
.and_then(|shell| shell.renderer().present_thread_id());
frame_work_hints.report(work_ns, vsync_period_ns(), present_thread);
}
record_presented_frame(app_shell.as_mut(), frame.started_at, frame.finished_at);
}
}
if let Some(shell) = app_shell.as_mut() {
shell.renderer().shutdown_present_runtime();
}
}