use crate::android_jni::{self as jni, Env, Native, Obj, Value};
use crate::android_sys::*;
use crate::android_text::SystemText;
use crate::event::{Button, Event, Key, Mods};
use crate::geom::{Size, pt};
use crate::platform::{Clipboard, Window};
use crate::preferences::Preferences;
use crate::surface::Surface;
use crate::ui::Ui;
use std::cell::{Cell, RefCell};
use std::ffi::{CStr, c_char, c_int, c_void};
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
use std::time::{Duration, Instant};
const BACK: i32 = 4;
const DEL: i32 = 67;
const FORWARD_DEL: i32 = 112;
pub(crate) enum Heard {
Event(Event),
Other(Box<dyn FnOnce(&mut Ui) -> bool>),
Back,
Looks,
Redraw,
}
struct Shell {
activity: *mut Activity,
window: *mut c_void,
queue: *mut c_void,
view: Obj,
classes: [Obj; 3],
insets: [i32; 4],
resumed: bool,
typing: bool,
password: bool,
composing: usize,
buttons: i32,
finger: Option<i32>,
scale: f32,
}
thread_local! {
static SHELL: RefCell<Shell> = const { RefCell::new(Shell {
activity: std::ptr::null_mut(),
window: std::ptr::null_mut(),
queue: std::ptr::null_mut(),
view: std::ptr::null_mut(),
classes: [std::ptr::null_mut(); 3],
insets: [0; 4],
resumed: false,
typing: false,
password: false,
composing: 0,
buttons: 0,
finger: None,
scale: 1.0,
}) };
static HEARD: RefCell<Vec<Heard>> = const { RefCell::new(Vec::new()) };
static HOST: RefCell<Option<Box<dyn Turns>>> = const { RefCell::new(None) };
static TURNING: Cell<bool> = const { Cell::new(false) };
}
static TIMER: AtomicI32 = AtomicI32::new(-1);
static PIPE: AtomicI32 = AtomicI32::new(-1);
static WOKEN: AtomicBool = AtomicBool::new(false);
static LAST_ACTIVITY: std::sync::atomic::AtomicPtr<c_void> = std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
#[derive(Clone, Copy, Debug, Default)]
pub struct Waker;
impl Waker {
pub fn wake(&self) {
let end = PIPE.load(Ordering::SeqCst);
if end < 0 || WOKEN.swap(true, Ordering::SeqCst) {
return;
}
if unsafe { write(end, [1u8].as_ptr().cast(), 1) } != 1 {
WOKEN.store(false, Ordering::SeqCst);
}
}
}
pub(crate) fn heard(what: Heard) {
HEARD.with_borrow_mut(|heard| heard.push(what));
}
pub(crate) fn kick() {
if TURNING.get() {
return arm(Some(Duration::ZERO));
}
TURNING.set(true);
let patience = HOST.with_borrow_mut(|host| host.as_mut().map(|host| host.turn()));
TURNING.set(false);
arm(patience.flatten());
}
fn arm(wait: Option<Duration>) {
let timer = TIMER.load(Ordering::SeqCst);
let wait = if HEARD.with_borrow(|heard| heard.is_empty()) { wait } else { Some(Duration::ZERO) };
let value = wait.map_or([0, 0], |wait| [wait.as_secs() as i64, i64::from(wait.subsec_nanos().max(u32::from(wait.is_zero())))]);
unsafe { timerfd_settime(timer, 0, &TimerSpec { interval: [0, 0], value }, std::ptr::null_mut()) };
}
fn env() -> Env {
jni::env().unwrap_or(Env(std::ptr::null_mut()))
}
pub(crate) fn activity() -> Obj {
SHELL.with_borrow(|shell| if shell.activity.is_null() { std::ptr::null_mut() } else { unsafe { (*shell.activity).clazz } })
}
pub(crate) fn classes() -> [Obj; 3] {
SHELL.with_borrow(|shell| shell.classes)
}
pub(crate) fn view() -> (Obj, f32, [i32; 4]) {
SHELL.with_borrow(|shell| (shell.view, shell.scale, shell.insets))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ANativeActivity_onCreate(activity: *mut Activity, _saved: *mut c_void, _saved_size: usize) {
let callbacks = unsafe {
jni::set_main(Env((*activity).env), (*activity).vm);
&mut *(*activity).callbacks
};
callbacks.on_resume = Some(on_resume);
callbacks.on_pause = Some(on_pause);
callbacks.on_destroy = Some(on_destroy);
callbacks.on_window_focus_changed = Some(on_focus);
callbacks.on_native_window_created = Some(on_window_created);
callbacks.on_native_window_resized = Some(on_window_resized);
callbacks.on_native_window_redraw_needed = Some(on_redraw_needed);
callbacks.on_native_window_destroyed = Some(on_window_destroyed);
callbacks.on_input_queue_created = Some(on_queue_created);
callbacks.on_input_queue_destroyed = Some(on_queue_destroyed);
callbacks.on_configuration_changed = Some(on_configuration_changed);
callbacks.on_save_instance_state = Some(on_save);
SHELL.with_borrow_mut(|shell| shell.activity = activity);
let own = unsafe { (*activity).clazz };
LAST_ACTIVITY.store(env().global(own), Ordering::SeqCst);
start_once(activity);
make_view();
let open = HOST.with_borrow(|host| host.as_ref().is_some_and(|host| !host.done()));
if open {
heard(Heard::Looks);
return kick();
}
HOST.set(None);
call_android_main();
}
fn start_once(activity: *mut Activity) {
static STARTED: AtomicBool = AtomicBool::new(false);
if STARTED.swap(true, Ordering::SeqCst) {
return;
}
unsafe {
let own = CStr::from_ptr((*activity).internal_data_path).to_string_lossy().into_owned();
std::env::set_var("HOME", &own);
std::env::set_var("XDG_CONFIG_HOME", &own);
std::env::set_var("TMPDIR", std::path::Path::new(&own).join("tmp"));
let _ = std::fs::create_dir_all(std::path::Path::new(&own).join("tmp"));
let timer = timerfd_create(MONOTONIC, NONBLOCK | CLOEXEC);
let mut ends = [-1; 2];
pipe2(&mut ends, NONBLOCK | CLOEXEC);
TIMER.store(timer, Ordering::SeqCst);
PIPE.store(ends[1], Ordering::SeqCst);
let looper = ALooper_forThread();
ALooper_addFd(looper, timer, LOOPER_CALLBACK, LOOPER_INPUT, on_readable, std::ptr::null_mut());
ALooper_addFd(looper, ends[0], LOOPER_CALLBACK, LOOPER_INPUT, on_readable, std::ptr::null_mut());
}
}
extern "C" fn on_readable(fd: c_int, _events: c_int, _: *mut c_void) -> c_int {
let mut bytes = [0u8; 64];
while unsafe { read(fd, bytes.as_mut_ptr().cast(), bytes.len()) } > 0 {}
if fd != TIMER.load(Ordering::SeqCst) {
WOKEN.store(false, Ordering::SeqCst);
heard(Heard::Other(Box::new(|_| true)));
}
kick();
1
}
fn call_android_main() {
unsafe {
let mut info = DlInfo { fname: std::ptr::null(), fbase: std::ptr::null_mut(), sname: std::ptr::null(), saddr: std::ptr::null_mut() };
let here = call_android_main as *const c_void;
let library = if dladdr(here, &mut info) != 0 { dlopen(info.fname, 2 | 4) } else { std::ptr::null_mut() };
let main = if library.is_null() { std::ptr::null_mut() } else { dlsym(library, c"android_main".as_ptr()) };
if main.is_null() {
return log("taut: the app has no `android_main` (see the module `android`).");
}
let main: extern "C" fn() = std::mem::transmute(main);
main();
}
}
#[repr(C)]
struct DlInfo {
fname: *const c_char,
fbase: *mut c_void,
sname: *const c_char,
saddr: *mut c_void,
}
unsafe extern "C" {
fn dladdr(address: *const c_void, info: *mut DlInfo) -> c_int;
fn dlopen(name: *const c_char, flags: c_int) -> *mut c_void;
fn dlsym(library: *mut c_void, name: *const c_char) -> *mut c_void;
}
fn make_view() {
let (env, activity) = (env(), activity());
let classes = SHELL.with_borrow(|shell| shell.classes);
let classes = if classes[0].is_null() { jni::load_classes(env, activity).filter(|classes| register(env, classes)) } else { Some(classes) };
let Some(classes) = classes else { return log("taut: Android refused the library's classes: no soft keyboard, insets or screen readers.") };
let view = env.frame(|| {
let view = env.new_object(classes[0], c"(Landroid/content/Context;)V", &[Value::obj(activity)]);
env.call(view, c"setFocusable", c"(Z)V", &[Value::bool(true)]);
env.call(view, c"setFocusableInTouchMode", c"(Z)V", &[Value::bool(true)]);
env.call(view, c"setImportantForAccessibility", c"(I)V", &[Value::int(1)]);
let place = env.new_named(c"android/view/ViewGroup$LayoutParams", c"(II)V", &[Value::int(-1), Value::int(-1)]);
env.call(activity, c"addContentView", c"(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", &[Value::obj(view), Value::obj(place)]);
env.call(view, c"requestFocus", c"()Z", &[]);
env.global(view)
});
SHELL.with_borrow_mut(|shell| (shell.view, shell.classes) = (view, classes));
}
fn register(env: Env, classes: &[Obj; 3]) -> bool {
let native = |name: &'static CStr, signature: &'static CStr, function: *const c_void| Native { name: name.as_ptr(), signature: signature.as_ptr(), function };
let host = [
native(c"getAccessibilityNodeProvider", c"()Landroid/view/accessibility/AccessibilityNodeProvider;", crate::android_access::provider as *const c_void),
native(c"onCreateInputConnection", c"(Landroid/view/inputmethod/EditorInfo;)Landroid/view/inputmethod/InputConnection;", connection as *const c_void),
native(c"onCheckIsTextEditor", c"()Z", is_text_editor as *const c_void),
native(c"onApplyWindowInsets", c"(Landroid/view/WindowInsets;)Landroid/view/WindowInsets;", insets_applied as *const c_void),
];
let typing = [
native(c"commitText", c"(Ljava/lang/CharSequence;I)Z", commit_text as *const c_void),
native(c"setComposingText", c"(Ljava/lang/CharSequence;I)Z", set_composing_text as *const c_void),
native(c"finishComposingText", c"()Z", finish_composing_text as *const c_void),
native(c"deleteSurroundingText", c"(II)Z", delete_surrounding_text as *const c_void),
native(c"performEditorAction", c"(I)Z", editor_action as *const c_void),
];
env.register(classes[0], &host) && env.register(classes[1], &crate::android_access::natives()) && env.register(classes[2], &typing)
}
extern "C" fn on_resume(_: *mut Activity) {
SHELL.with_borrow_mut(|shell| shell.resumed = true);
heard(Heard::Event(Event::Minimized(false)));
heard(Heard::Redraw);
kick();
}
extern "C" fn on_pause(_: *mut Activity) {
SHELL.with_borrow_mut(|shell| shell.resumed = false);
heard(Heard::Event(Event::Minimized(true)));
kick();
}
extern "C" fn on_focus(_: *mut Activity, focused: c_int) {
heard(Heard::Event(Event::Focused(focused != 0)));
kick();
}
extern "C" fn on_destroy(_: *mut Activity) {
let done = HOST.with_borrow(|host| host.as_ref().is_none_or(|host| host.done()));
if done && !TURNING.get() {
HOST.set(None);
}
SHELL.with_borrow_mut(|shell| (shell.activity, shell.view, shell.typing, shell.composing) = (std::ptr::null_mut(), std::ptr::null_mut(), false, 0));
crate::android_access::forget();
}
extern "C" fn on_save(_: *mut Activity, size: *mut usize) -> *mut c_void {
unsafe { *size = 0 };
std::ptr::null_mut()
}
extern "C" fn on_window_created(_: *mut Activity, window: *mut c_void) {
unsafe {
ANativeWindow_acquire(window);
ANativeWindow_setBuffersGeometry(window, 0, 0, RGBA_8888);
}
SHELL.with_borrow_mut(|shell| shell.window = window);
heard(Heard::Looks);
heard(Heard::Redraw);
kick();
}
extern "C" fn on_window_resized(_: *mut Activity, _: *mut c_void) {
heard(Heard::Looks);
kick();
}
extern "C" fn on_redraw_needed(_: *mut Activity, _: *mut c_void) {
heard(Heard::Looks);
heard(Heard::Redraw);
kick();
}
extern "C" fn on_window_destroyed(_: *mut Activity, window: *mut c_void) {
SHELL.with_borrow_mut(|shell| shell.window = std::ptr::null_mut());
unsafe { ANativeWindow_release(window) };
}
extern "C" fn on_queue_created(_: *mut Activity, queue: *mut c_void) {
unsafe { AInputQueue_attachLooper(queue, ALooper_forThread(), 1, on_input, queue) };
SHELL.with_borrow_mut(|shell| shell.queue = queue);
}
extern "C" fn on_queue_destroyed(_: *mut Activity, queue: *mut c_void) {
unsafe { AInputQueue_detachLooper(queue) };
SHELL.with_borrow_mut(|shell| shell.queue = std::ptr::null_mut());
}
extern "C" fn on_configuration_changed(_: *mut Activity) {
heard(Heard::Looks);
kick();
}
extern "C" fn on_input(_: c_int, _: c_int, queue: *mut c_void) -> c_int {
let mut event = std::ptr::null_mut();
while unsafe { AInputQueue_getEvent(queue, &mut event) } >= 0 {
if unsafe { AInputQueue_preDispatchEvent(queue, event) } != 0 {
continue;
}
let handled = input(event);
unsafe { AInputQueue_finishEvent(queue, event, c_int::from(handled)) };
}
kick();
1
}
fn input(event: *mut c_void) -> bool {
match unsafe { AInputEvent_getType(event) } {
KEY_EVENT => key(event),
MOTION_EVENT => motion(event),
_ => false,
}
}
fn mods_of(meta: i32) -> Mods {
Mods { ctrl: meta & META_CTRL != 0, shift: meta & META_SHIFT != 0, alt: meta & META_ALT != 0 }
}
fn key_of(code: i32) -> Option<Key> {
Some(match code {
66 | 160 => Key::Enter,
111 => Key::Escape,
61 => Key::Tab,
DEL => Key::Backspace,
FORWARD_DEL => Key::Delete,
21 => Key::Left,
22 => Key::Right,
19 => Key::Up,
20 => Key::Down,
122 => Key::Home,
123 => Key::End,
92 => Key::PageUp,
93 => Key::PageDown,
62 => Key::Space,
82 => Key::Menu,
131..=142 => Key::F((code - 130) as u8),
29..=54 => Key::Char((b'a' + (code - 29) as u8) as char),
7..=16 => Key::Char((b'0' + (code - 7) as u8) as char),
_ => return None,
})
}
fn typed_by(event: *const c_void, code: i32, meta: i32) -> Option<char> {
let env = env();
let device = unsafe { AInputEvent_getDeviceId(event) };
let typed = env.frame(|| {
let map = env.call_static(c"android/view/KeyCharacterMap", c"load", c"(I)Landroid/view/KeyCharacterMap;", &[Value::int(device)]).object();
env.call(map, c"get", c"(II)I", &[Value::int(code), Value::int(meta)]).as_int()
});
char::from_u32(typed as u32 & 0x7fff_ffff).filter(|letter| *letter != '\0' && !letter.is_control())
}
fn key(event: *mut c_void) -> bool {
let (action, code, meta) = unsafe { (AKeyEvent_getAction(event), AKeyEvent_getKeyCode(event), AKeyEvent_getMetaState(event)) };
if code == BACK {
if action == KEY_UP {
heard(Heard::Back);
}
return true;
}
let (key, mods) = (key_of(code), mods_of(meta));
if action == KEY_UP {
key.into_iter().for_each(|key| heard(Heard::Event(Event::KeyUp(key))));
return key.is_some();
}
let text = if action == KEY_DOWN && !mods.ctrl { typed_by(event, code, meta) } else { None };
if action == KEY_DOWN {
key.into_iter().for_each(|key| heard(Heard::Event(Event::Key(key, mods))));
text.into_iter().for_each(|text| heard(Heard::Event(Event::Text(text.to_string()))));
}
key.is_some() || text.is_some()
}
fn place_of(event: *const c_void, n: usize) -> crate::geom::Point {
let (scale, insets) = SHELL.with_borrow(|shell| (shell.scale, shell.insets));
let (x, y) = unsafe { (AMotionEvent_getX(event, n), AMotionEvent_getY(event, n)) };
pt((x - insets[0] as f32) / scale, (y - insets[1] as f32) / scale)
}
fn motion(event: *mut c_void) -> bool {
let (action, tool, buttons) = unsafe { (AMotionEvent_getAction(event), AMotionEvent_getToolType(event, 0), AMotionEvent_getButtonState(event)) };
let (what, nth) = (action & 0xff, (action >> 8 & 0xff) as usize);
match tool {
MOUSE => mouse(event, what, buttons),
FINGER if matches!(what, HOVER_ENTER | HOVER_MOVE | HOVER_EXIT) => crate::android_access::hover(place_of(event, 0), what == HOVER_EXIT),
STYLUS | ERASER => pen(event, what, tool == ERASER),
_ if cfg!(feature = "touch") => fingers(event, what, nth),
_ => finger_as_mouse(event, what, nth),
}
true
}
fn mouse(event: *mut c_void, what: i32, buttons: i32) {
let place = place_of(event, 0);
match what {
HOVER_EXIT => return heard(Heard::Event(Event::Leave)),
SCROLL => unsafe {
let (across, down) = (AMotionEvent_getAxisValue(event, AXIS_HSCROLL, 0), AMotionEvent_getAxisValue(event, AXIS_VSCROLL, 0));
heard(Heard::Event(Event::Move(place)));
if mods_of(AMotionEvent_getMetaState(event)).ctrl {
return heard(Heard::Event(Event::Zoom(crate::touch::wheel_zoom(down))));
}
return heard(Heard::Event(Event::Wheel(across * 48.0, -down * 48.0)));
},
_ => heard(Heard::Event(Event::Move(place))),
}
let mods = mods_of(unsafe { AMotionEvent_getMetaState(event) });
let was = SHELL.with_borrow_mut(|shell| std::mem::replace(&mut shell.buttons, buttons));
for (bit, button) in [(PRIMARY, Button::Left), (SECONDARY, Button::Right), (TERTIARY, Button::Middle)] {
match (was & bit != 0, buttons & bit != 0) {
(false, true) => heard(Heard::Event(Event::Press(button, mods))),
(true, false) => heard(Heard::Event(Event::Release(button))),
_ => {}
}
}
}
fn pen(event: *mut c_void, what: i32, eraser: bool) {
let place = place_of(event, 0);
heard(Heard::Event(Event::Move(place)));
if cfg!(feature = "touch") {
let pressure = unsafe { AMotionEvent_getAxisValue(event, AXIS_PRESSURE, 0) };
let touching = matches!(what, DOWN | MOVE);
let stylus = crate::touch::Stylus { pressure: if touching { pressure.clamp(0.0, 1.0) } else { 0.0 }, eraser, touching, ..Default::default() };
heard(Heard::Event(Event::Stylus(Some(stylus))));
}
match what {
DOWN => heard(Heard::Event(Event::Press(Button::Left, Mods::NONE))),
UP | CANCEL => heard(Heard::Event(Event::Release(Button::Left))),
HOVER_EXIT => heard(Heard::Event(Event::Leave)),
_ => {}
}
}
fn fingers(event: *mut c_void, what: i32, nth: usize) {
use crate::touch::{Touch, TouchPhase};
let count = unsafe { AMotionEvent_getPointerCount(event) };
let id = |n: usize| unsafe { AMotionEvent_getPointerId(event, n) } as u32;
let one = |n: usize, phase| heard(Heard::Event(Event::Touch(Touch { id: id(n), position: place_of(event, n), phase })));
match what {
DOWN | POINTER_DOWN => one(nth, TouchPhase::Down),
UP | POINTER_UP => one(nth, TouchPhase::Up),
MOVE => (0..count).for_each(|n| one(n, TouchPhase::Move)),
CANCEL => (0..count).for_each(|n| one(n, TouchPhase::Cancel)),
_ => {}
}
}
fn finger_as_mouse(event: *mut c_void, what: i32, nth: usize) {
let id = unsafe { AMotionEvent_getPointerId(event, nth) };
let mouse = SHELL.with_borrow_mut(|shell| {
shell.finger = shell.finger.or((what == DOWN).then_some(id));
shell.finger
});
let Some(mouse) = mouse else { return };
let at = (0..unsafe { AMotionEvent_getPointerCount(event) }).find(|n| unsafe { AMotionEvent_getPointerId(event, *n) } == mouse).unwrap_or(0);
heard(Heard::Event(Event::Move(place_of(event, at))));
match what {
DOWN => heard(Heard::Event(Event::Press(Button::Left, Mods::NONE))),
UP | CANCEL => {
heard(Heard::Event(Event::Release(Button::Left)));
heard(Heard::Event(Event::Leave));
SHELL.with_borrow_mut(|shell| shell.finger = None);
}
POINTER_UP if id == mouse => {
heard(Heard::Event(Event::Release(Button::Left)));
SHELL.with_borrow_mut(|shell| shell.finger = None);
}
_ => {}
}
}
extern "C" fn is_text_editor(_: Env, _: Obj) -> u8 {
SHELL.with_borrow(|shell| u8::from(shell.typing))
}
extern "C" fn connection(env: Env, view: Obj, info: Obj) -> Obj {
let (password, class) = SHELL.with_borrow(|shell| (shell.password, shell.classes[2]));
env.set_int_field(info, c"inputType", if password { 0x81 } else { 0x8001 });
env.set_int_field(info, c"imeOptions", 0x1200_0000);
SHELL.with_borrow_mut(|shell| shell.composing = 0);
env.new_object(class, c"(Landroid/view/View;Z)V", &[Value::obj(view), Value::bool(false)])
}
extern "C" fn insets_applied(env: Env, view: Obj, insets: Obj) -> Obj {
let root = env.call(view, c"getRootWindowInsets", c"()Landroid/view/WindowInsets;", &[]).object();
let kept = jni::insets_of(env, if root.is_null() { insets } else { root });
env.drop_local(root);
let changed = SHELL.with_borrow_mut(|shell| std::mem::replace(&mut shell.insets, kept) != kept);
if changed {
heard(Heard::Looks);
heard(Heard::Redraw);
kick();
}
insets
}
fn type_over(text: Option<String>, composing: bool) {
let Some(text) = text else { return };
let before = SHELL.with_borrow_mut(|shell| std::mem::replace(&mut shell.composing, if composing { text.chars().count() } else { 0 }));
(0..before).for_each(|_| heard(Heard::Event(Event::Key(Key::Backspace, Mods::NONE))));
if !text.is_empty() {
heard(Heard::Event(Event::Text(text)));
}
kick();
}
extern "C" fn commit_text(env: Env, _: Obj, text: Obj, _: c_int) -> u8 {
type_over(env.text(text), false);
1
}
extern "C" fn set_composing_text(env: Env, _: Obj, text: Obj, _: c_int) -> u8 {
type_over(env.text(text), true);
1
}
extern "C" fn finish_composing_text(_: Env, _: Obj) -> u8 {
SHELL.with_borrow_mut(|shell| shell.composing = 0);
1
}
extern "C" fn delete_surrounding_text(_: Env, _: Obj, before: c_int, after: c_int) -> u8 {
SHELL.with_borrow_mut(|shell| shell.composing = 0);
(0..before).for_each(|_| heard(Heard::Event(Event::Key(Key::Backspace, Mods::NONE))));
(0..after).for_each(|_| heard(Heard::Event(Event::Key(Key::Delete, Mods::NONE))));
kick();
1
}
extern "C" fn editor_action(_: Env, _: Obj, _: c_int) -> u8 {
SHELL.with_borrow_mut(|shell| shell.composing = 0);
heard(Heard::Event(Event::Key(Key::Enter, Mods::NONE)));
kick();
1
}
trait Turns {
fn turn(&mut self) -> Option<Duration>;
fn done(&self) -> bool;
}
struct Host<App> {
app: App,
ui: Ui,
surface: Surface,
rerun: bool,
done: bool,
whole: bool,
start: Instant,
pixels: [i32; 2],
typed_in: Option<crate::id::Id>,
pressed: bool,
}
impl<App: FnMut(&mut Ui)> Turns for Host<App> {
fn turn(&mut self) -> Option<Duration> {
self.ui.set_time(self.start.elapsed());
self.rerun |= self.ui.wake_in() == Some(Duration::ZERO);
for what in HEARD.with_borrow_mut(std::mem::take) {
self.take(what);
}
self.listen();
if self.rerun && !self.done && self.pixels[0] > 0 {
self.describe();
}
self.draw();
if self.rerun { Some(Duration::ZERO) } else { self.ui.wake_in() }
}
fn done(&self) -> bool {
self.done
}
}
impl<App: FnMut(&mut Ui)> Host<App> {
fn take(&mut self, what: Heard) {
match what {
Heard::Event(event) => {
self.pressed |= matches!(event, Event::Press(..) | Event::Touch(crate::touch::Touch { phase: crate::touch::TouchPhase::Up, .. }));
self.rerun |= self.ui.event(event);
}
Heard::Other(work) => self.rerun |= work(&mut self.ui),
Heard::Looks => self.measure(),
Heard::Redraw => self.whole = true,
Heard::Back if self.ui.popup_anchor().is_some() => self.rerun |= self.ui.event(Event::Key(Key::Escape, Mods::NONE)),
Heard::Back => {
self.ui.request_close();
self.rerun = true;
}
}
}
fn measure(&mut self) {
let (window, insets) = SHELL.with_borrow(|shell| (shell.window, shell.insets));
if activity().is_null() {
return;
}
let display = jni::display(env(), activity());
let scale = if display.density > 0.0 { display.density } else { 1.0 };
SHELL.with_borrow_mut(|shell| shell.scale = scale);
let preferences = Preferences { dark: display.dark, accent: display.accent.map(crate::color::Color), reduced_motion: display.still, text_scale: display.text_scale, ..Preferences::default() };
self.rerun |= self.ui.set_preferences(preferences);
if window.is_null() {
return;
}
self.pixels = unsafe { [ANativeWindow_getWidth(window), ANativeWindow_getHeight(window)] };
let inner = [(self.pixels[0] - insets[0] - insets[2]).max(1), (self.pixels[1] - insets[1] - insets[3]).max(1)];
let size = Size { w: inner[0] as f32 / scale, h: inner[1] as f32 / scale };
if (size, scale) != (self.ui.size(), self.ui.scale()) {
self.ui.resize(size, scale);
(self.rerun, self.whole) = (true, true);
let [width, height] = self.pixels;
let accent = display.accent.unwrap_or(0);
log(&format!(
"window {width} {height} insets {} {} {} {} scale {scale} dark {} accent {accent:08x} text {} still {}",
insets[0],
insets[1],
insets[2],
insets[3],
u8::from(display.dark),
display.text_scale,
u8::from(display.still)
));
}
}
fn listen(&mut self) {
if !self.ui.listening && crate::android_access::asked() {
self.ui.set_screen_reader(true);
self.rerun = true;
}
}
fn describe(&mut self) {
self.ui.run(&mut self.app);
let closes = self.ui.take_closing() == Some(Ok(()));
(self.rerun, self.done) = (false, self.done || closes || self.ui.quitting());
let (_, _, _) = (self.ui.take_minimize(), self.ui.take_maximized(), self.ui.take_full_screen());
self.keyboard();
if self.ui.listening {
crate::android_access::keep(&self.ui);
}
let activity = SHELL.with_borrow(|shell| shell.activity);
if self.done && !activity.is_null() {
unsafe { ANativeActivity_finish(activity) };
}
}
fn keyboard(&mut self) {
let now = self.ui.ime_area().map(|_| self.ui.focus());
let (was, pressed) = (std::mem::replace(&mut self.typed_in, now), std::mem::take(&mut self.pressed));
let password = self.ui.password_focused();
let view = SHELL.with_borrow_mut(|shell| {
(shell.typing, shell.password) = (now.is_some(), password);
shell.view
});
if (was != now || pressed && now.is_some()) && !view.is_null() {
jni::soft_keyboard(env(), activity(), view, now.is_some(), was.is_some() && now.is_some() && was != now);
}
}
fn draw(&mut self) {
let (window, resumed, insets) = SHELL.with_borrow(|shell| (shell.window, shell.resumed, shell.insets));
if self.ui.size().w <= 0.0 {
return;
}
let changed = self.surface.update(&mut self.ui);
self.ui.changed();
if window.is_null() || !resumed || (changed.is_empty() && !self.whole) {
return;
}
let whole = std::mem::take(&mut self.whole);
let mut dirty = if whole { [0, 0, self.pixels[0], self.pixels[1]] } else { bounds(&changed, insets) };
let mut buffer = WindowBuffer { width: 0, height: 0, stride: 0, format: 0, bits: std::ptr::null_mut(), reserved: [0; 6] };
unsafe {
if ANativeWindow_lock(window, &mut buffer, &mut dirty) != 0 || buffer.bits.is_null() {
return;
}
let rows = std::slice::from_raw_parts_mut(buffer.bits.cast::<u32>(), (buffer.stride * buffer.height) as usize);
copy_out(&self.surface, rows, &buffer, dirty, insets, self.ui.theme.bg.0);
ANativeWindow_unlockAndPost(window);
}
}
}
fn bounds(changed: &[[usize; 4]], insets: [i32; 4]) -> [i32; 4] {
let start = [i32::MAX, i32::MAX, 0, 0];
let [left, top, right, bottom] = changed.iter().fold(start, |all, [l, t, r, b]| [all[0].min(*l as i32), all[1].min(*t as i32), all[2].max(*r as i32), all[3].max(*b as i32)]);
[left + insets[0], top + insets[1], right + insets[0], bottom + insets[1]]
}
fn copy_out(surface: &Surface, rows: &mut [u32], buffer: &WindowBuffer, dirty: [i32; 4], insets: [i32; 4], bg: u32) {
let swap = |pixel: u32| 0xff00_0000 | pixel & 0x0000_ff00 | pixel >> 16 & 0xff | (pixel & 0xff) << 16;
let [left, top] = [dirty[0].max(0), dirty[1].max(0)];
let [right, bottom] = [dirty[2].min(buffer.width), dirty[3].min(buffer.height)];
for y in top..bottom {
let row = &mut rows[(y * buffer.stride) as usize..][..buffer.width as usize];
let inside = (y - insets[1]) as usize;
let from = surface.pixels.get(inside.wrapping_mul(surface.width)..).filter(|_| y >= insets[1] && inside < surface.height).unwrap_or_default();
for x in left..right {
let column = (x - insets[0]) as usize;
let pixel = if x >= insets[0] && column < surface.width { from.get(column).copied().unwrap_or(bg) } else { bg };
row[x as usize] = swap(pixel);
}
}
}
pub fn run(window: Window, app: impl FnMut(&mut Ui) + 'static) {
let _ = window;
if activity().is_null() {
return log("taut: on Android, `run` is called from `android_main`, on the main thread.");
}
let text: Box<dyn crate::text::TextSystem> = match SystemText::new() {
Some(text) => Box::new(text),
None => Box::new(crate::text::BuiltInFont),
};
let ui = Ui::new(text, Box::new(SystemClipboard));
let host = Host { app, ui, surface: Surface::default(), rerun: true, done: false, whole: true, start: Instant::now(), pixels: [0, 0], typed_in: None, pressed: false };
HOST.set(Some(Box::new(host)));
heard(Heard::Looks);
kick();
}
struct SystemClipboard;
impl Clipboard for SystemClipboard {
fn get(&mut self) -> Option<String> {
jni::clipboard_text(env(), activity())
}
fn set(&mut self, text: &str) {
jni::set_clipboard_text(env(), activity(), text);
}
}
pub(crate) fn open_link(link: &str) -> bool {
jni::open_link(LAST_ACTIVITY.load(Ordering::SeqCst), link)
}
pub(crate) fn vulkan_loader() -> *mut c_void {
unsafe {
let library = dlopen(c"libvulkan.so".as_ptr(), 2);
if library.is_null() { library } else { dlsym(library, c"vkGetInstanceProcAddr".as_ptr()) }
}
}