From 0f17181dab9d67550f45820fbecc82b1b03e5741 Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:23:26 +0530 Subject: [PATCH] android rust --- CHANGELOG.md | 2 + bindings/rust/Cargo.lock | 7 ++ bindings/rust/blenderui-sys/src/lib.rs | 5 ++ bindings/rust/blenderui/Cargo.toml | 4 + bindings/rust/blenderui/src/android.rs | 76 +++++++++++++++++++ bindings/rust/blenderui/src/lib.rs | 21 +++++ bindings/rust/blenderui/src/window.rs | 16 +++- docs/android.md | 30 +++++++- gpu/intern/gpu_fonts.c | 6 ++ kit/include/BUI_kit.h | 12 ++- kit/intern/kit_core.c | 12 +++ kit/intern/kit_intern.h | 1 + kit/intern/kit_window_android.c | 34 +++++++++ platform/android/CMakeLists.txt | 4 +- platform/android/build.py | 62 ++++++++++++--- platform/android/rust/src/lib.rs | 11 ++- showcase/Cargo.lock | 7 ++ website/src/content/docs/concepts/android.mdx | 14 +++- 18 files changed, 299 insertions(+), 25 deletions(-) create mode 100644 bindings/rust/blenderui/src/android.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 50c2a0c9..c4eba8db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to **blenderui** (BUI). The format follows ## [Unreleased] ### Added +- **Android: real apps in Rust.** `blenderui::android_main!(run)` writes the entry point the NativeActivity shell calls, so the app crate has no `unsafe`; before `run` it gives the activity's JNI handles to `ndk-context` (cpal and other crates that call into Java need them) and sends stdout, stderr and panics to logcat (tag `bui`). The kit points `HOME` at the app's files folder and `XDG_CACHE_HOME` / `TMPDIR` at its cache folder on attach (`dirs::cache_dir()` worked nowhere), and `BK_android_activity()` gives the `ANativeActivity *`. `build.py` takes `--label`, `--package` and `--permission` (repeatable: `INTERNET` for an app that goes online) and links the system libraries the Rust staticlib needs (rustc's `native-static-libs`, through `cargo rustc`, so dependencies don't build again): an app that plays sound through cpal links AAudio. Characters Roboto lacks come from the phone's Noto fonts (`/system/fonts`, `/product/fonts` in the font folders). SpotiTube's Android build is the first app that uses it. +- **Back on Android walks back through an app's screens.** `App::prevent_default()` in a key listener marks the key as taken (`BK_key_taken` in C, for any binding that sees raw key events): `BK_key` returns 1 and nothing else acts on it. Back is the key `Escape`, so a listener that closes a screen on it keeps the app open, and only a Back that nothing took finishes the activity. - **WebAssembly frames copy twice as fast.** The kit's pixels become the canvas's RGBA bytes in a loop the compiler vectorizes: a 1280 x 800 redraw drops from about 10 ms to 5 ms under Node.js. `examples/wasm/bench.mjs` times it. - **WebAssembly: a blenderui app in a web page.** `blenderui-web` (new crate) with `blenderui_web::export!` and `js/bui-web.js` runs a blenderui app compiled to `wasm32-wasip1` in a ``: BUI's C kit is built for WebAssembly (`platform/wasm/wasi.cmake`, clang and wasi-libc, no threads or exceptions; `blenderui-sys` drives it), `Application::start` keeps a headless application alive for a host that has no event loop of its own, `App::frame_if_needed`, `App::window_ids` and `App::set_canvas_size` give it frames, `python platform/wasm/build.py CRATE` builds the module and writes the page (`--fetch-sysroot` downloads the WASI sysroot, `--serve` serves it). The counter (`examples/wasm/counter`) is a 4.2 MB module (1.6 MB gzipped) that renders, counts clicks and takes typing in Microsoft Edge and under Node.js (`examples/wasm/smoke.mjs`). Software raster, one thread, the primary pointer button, wheel and keyboard; see docs/wasm.md for the limits. The page script cancels a press the browser cancels (`pointercancel`, lost capture: `bui_pointer_cancel`, which ends it with no motion and no release, so a dragged slider goes back as on Escape, nothing is clicked and the next press is not a double click), releases one whose primary button went up during a chord, and pins an unstyled canvas's CSS size (not while it has no layout, `display: none`, so `fit` follows its CSS once shown); ratios below 1 (page zoom out) are kept; the no-flag error detection covers `log(a, b)` and `smoothstep`. `App::shutdown` (also on drop) frees an application a host started, `App::set_canvas_size` takes the pixel ratio, and `Application::start` windows animate on the real clock. The page script ignores non-primary buttons and pointers, scrolls the right way, keeps the canvas's CSS size at the logical size and stops (and reports) on a trap. The build script needs clang 21 or newer (the sysroot's libc++ does not compile with clang 19), extracts the sysroot atomically and finds the `.wasm` through cargo. A few portability fixes in the C and Rust sources came with it (`try`/`catch` in Blender's containers compile out without exceptions, the expression evaluator works out its floating-point error flags where the platform has none, FreeType's rasterizer splits a band on a full cell pool without `longjmp`, the image loader decodes inline without worker threads, `blenderui-vlist` builds for 32-bit targets without positional file reads). - **A title bar you draw.** With `WindowDecorations::Client`, mark the parts of your bar with `window_control_area(WindowControlArea::Drag | Min | Max | Close)` (gpui's API) or CSS `app-region` (`drag`, `no-drag`, and `minimize`, `maximize`, `close`; `-webkit-app-region` too). A drag area moves the window and a double click maximizes it; anything in it that takes clicks stays the app's. On Windows the window keeps the system's resize edges, Aero Snap, shadow and rounded corners, and Windows 11 shows its snap layouts over the maximize button: the kit asks the app's new `hit_test` window callback from `WM_NCHITTEST`, as Windows Terminal does. On X11, Wayland and macOS the window has no frame and a press on a drag area starts the window manager's move (`_NET_WM_MOVERESIZE`, `xdg_toplevel_move`, `performWindowDragWithEvent`), with no resize edges yet; the window manager takes the pointer, so the press clicks nothing (the same for `start_window_move` and `"move"` everywhere). `start_window_move` from a press listener ends the press there, since its release never comes: nothing stays pressed or `:active`, and a scrollbar drag lets go. The `Min`, `Max` and `Close` areas work on any element, form controls such as `button()` included. New on `Window`: `minimize_window`, `zoom_window`, `is_maximized`, `start_window_move`, `remove_window`; closing from the Close area, `remove_window` (in a listener or a `WindowHandle::update`) or `App::close_window` (a close hook closing another window too) runs the `on_window_closed` hooks once, as a close by the user does. In C: `BK_window_wm(win, "override", 2, 0)`, `"move"`, and `BKWindowCallbacks.hit_test`; X11 and Wayland now answer `wm_get("state")` with maximized. Example: `cargo run --example titlebar`. diff --git a/bindings/rust/Cargo.lock b/bindings/rust/Cargo.lock index 344efe08..5d86821b 100644 --- a/bindings/rust/Cargo.lock +++ b/bindings/rust/Cargo.lock @@ -45,6 +45,7 @@ dependencies = [ "blenderui-tailwind", "blenderui-vlist", "foldhash", + "ndk-context", "paste", "png", "smallvec", @@ -325,6 +326,12 @@ dependencies = [ "libloading", ] +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + [[package]] name = "once_cell" version = "1.21.4" diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs index 75ca9f84..c0821d06 100644 --- a/bindings/rust/blenderui-sys/src/lib.rs +++ b/bindings/rust/blenderui-sys/src/lib.rs @@ -462,6 +462,8 @@ unsafe extern "C" { -> c_int; pub fn BK_key(ctx: *mut BKContext, text: *const c_char, keysym: *const c_char, mods: c_int) -> c_int; + pub fn BK_key_taken(ctx: *mut BKContext); + pub fn BK_key_release(ctx: *mut BKContext, keysym: *const c_char, mods: c_int) -> c_int; pub fn BK_button(ctx: *mut BKContext, x: c_int, y: c_int, button: c_int, release: c_int, mods: c_int) -> c_int; @@ -500,6 +502,9 @@ unsafe extern "C" { pub fn BK_window_set_keep_alive(on: c_int); pub fn BK_window_pump() -> c_int; pub fn BK_window_quit(); + /// Android: the running `ANativeActivity *`, null while none runs. + #[cfg(target_os = "android")] + pub fn BK_android_activity() -> *mut c_void; // raster + text (gpu/) pub fn BUI_raster_create(width: c_int, height: c_int) -> *mut BuiRaster; diff --git a/bindings/rust/blenderui/Cargo.toml b/bindings/rust/blenderui/Cargo.toml index 1a273cbf..b7127911 100644 --- a/bindings/rust/blenderui/Cargo.toml +++ b/bindings/rust/blenderui/Cargo.toml @@ -26,6 +26,10 @@ paste = "1" foldhash = { version = "0.2", default-features = false } smallvec = { version = "1", features = ["union", "const_generics"] } +[target.'cfg(target_os = "android")'.dependencies] +# the activity's JNI handles for crates that call into Java (android::run sets them) +ndk-context = "0.1" + [features] # Draw text with Windows' native GDI engine (system fonts) instead of the # default portable engine (embedded Inter, like Blender; Slug on the GPU). diff --git a/bindings/rust/blenderui/src/android.rs b/bindings/rust/blenderui/src/android.rs new file mode 100644 index 00000000..a452a2c4 --- /dev/null +++ b/bindings/rust/blenderui/src/android.rs @@ -0,0 +1,76 @@ +//! Android: the entry point of a Rust app ([`android_main!`](crate::android_main)). +//! +//! The NativeActivity shell (platform/android/bui_android.c) calls `bui_app_main`; the macro +//! defines it, so an app's code has no `unsafe` and nothing Android-specific. Before the app runs: +//! +//! - **JNI**: the activity's Java VM and object are given to `ndk-context`, which crates that call +//! into Java read (cpal lists sound devices through it; without it they panic). +//! - **Logs**: stdout and stderr go to logcat (tag `bui`), panics included, so `println!` and +//! `eprintln!` are seen with `adb logcat -s bui`. +//! - **Folders**: the kit already pointed HOME, XDG_CACHE_HOME and TMPDIR at the app's own +//! folders (BK_android_attach), so `dirs::cache_dir()` and `std::env::temp_dir()` work. + +use std::ffi::{CString, c_char, c_int, c_void}; +use std::io::{BufRead, BufReader}; +use std::os::fd::IntoRawFd; +use std::sync::Once; + +use crate::sys; + +/// The head of NDK's `ANativeActivity` (android/native_activity.h): the fields read here. +#[repr(C)] +struct ActivityHead { + callbacks: *mut c_void, + vm: *mut c_void, + env: *mut c_void, + clazz: *mut c_void, +} + +/// logcat's priority of an info line (android/log.h `ANDROID_LOG_INFO`). +const LOG_INFO: c_int = 4; + +unsafe extern "C" { + fn __android_log_write(prio: c_int, tag: *const c_char, text: *const c_char) -> c_int; + fn dup2(old: c_int, new: c_int) -> c_int; +} + +/// Runs the app `main` inside the running activity: what `bui_app_main` does. Called by +/// [`android_main!`](crate::android_main); an app doesn't call it. +pub fn run(main: fn()) { + logs_to_logcat(); + // SAFETY: the shell attached the activity (BK_android_attach) before it called bui_app_main. + let activity = unsafe { sys::BK_android_activity() }.cast::(); + if activity.is_null() { + main(); + return; + } + // SAFETY: a live ANativeActivity: its VM and object stay valid until bui_app_main returns, and + // the context is released below, before they go (a relaunch sets it again). + unsafe { ndk_context::initialize_android_context((*activity).vm, (*activity).clazz) }; + main(); + // SAFETY: set above, on this thread. + unsafe { ndk_context::release_android_context() }; +} + +/// Sends stdout and stderr to logcat, a line at a time, once per process. +fn logs_to_logcat() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| { + let Ok((reader, writer)) = std::io::pipe() else { return }; + let fd = writer.into_raw_fd(); // kept open: it is stdout and stderr from now on + // SAFETY: plain descriptors; 1 and 2 now write into the pipe. + unsafe { + dup2(fd, 1); + dup2(fd, 2); + } + let _ = std::thread::Builder::new().name("bui-logcat".into()).spawn(move || { + let tag = c"bui"; + for line in BufReader::new(reader).lines().map_while(Result::ok) { + if let Ok(text) = CString::new(line) { + // SAFETY: two C strings that live through the call. + unsafe { __android_log_write(LOG_INFO, tag.as_ptr(), text.as_ptr()) }; + } + } + }); + }); +} diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rs index e523fbb3..d4c2cf1b 100644 --- a/bindings/rust/blenderui/src/lib.rs +++ b/bindings/rust/blenderui/src/lib.rs @@ -96,6 +96,27 @@ pub use blenderui_macros::rsx as view; /// `Option` fields and `children`, and names missing required ones. pub use blenderui_macros::Props; +#[cfg(target_os = "android")] +pub mod android; + +/// Defines the Android entry point of the app: `blenderui::android_main!(my_app::run);` in the +/// app's `staticlib` crate, where `run` is a `fn()` that runs an [`Application`](crate::prelude::Application) +/// (the same function a desktop `main` calls). `platform/android/build.py --rust CRATE` links it +/// into the APK. +/// +/// The function the NativeActivity shell calls must have an unmangled name, which only `unsafe` +/// code may give; the macro writes it, so the app's own code stays `unsafe`-free. +#[macro_export] +macro_rules! android_main { + ($main:path) => { + #[cfg(target_os = "android")] + #[unsafe(no_mangle)] + pub extern "C" fn bui_app_main() { + $crate::android::run($main); + } + }; +} + pub mod anim; pub mod motion; pub mod calc; diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs index bd88f536..77e11f66 100644 --- a/bindings/rust/blenderui/src/window.rs +++ b/bindings/rust/blenderui/src/window.rs @@ -395,6 +395,8 @@ pub struct App { real_clock: bool, globals: HashMap>, pub(crate) propagate: bool, + /// A key listener acted on the key ([`App::prevent_default`]). + default_prevented: bool, /// Work sent from other threads ([`UiSender`]). remote: Option<(std::sync::mpsc::Sender, std::sync::mpsc::Receiver)>, /// Called when the user closes a window. @@ -452,7 +454,7 @@ impl App { fn create(headless: bool, real_clock: bool) -> App { crate::motion::start_clock(real_clock); App { windows: Vec::new(), entities: Vec::new(), headless, real_clock, globals: HashMap::new(), propagate: true, - remote: None, close_hooks: Vec::new(), closed_later: None, + default_prevented: false, remote: None, close_hooks: Vec::new(), closed_later: None, activation_hooks: Vec::new(), notified: 0, shutdown_later: false } } @@ -627,6 +629,13 @@ impl App { self.propagate = false; } + /// In a key listener: the app acted on the key, so the system doesn't (as a browser's + /// `preventDefault`). On Android, Back is the key `Escape`: a listener that closes something on + /// it calls this, and only a Back nothing took finishes the app. + pub fn prevent_default(&mut self) { + self.default_prevented = true; + } + /// Activate the app (no-op: windows come to the front when shown). pub fn activate(&mut self, _ignoring_other_apps: bool) {} @@ -2406,7 +2415,12 @@ impl Window { "pageup" => -1.0, _ => 0.0, }; + app.default_prevented = false; self.emit(app, target, &KeyDownEvent { keystroke: ks }, |l| l.key_down.iter().collect()); + if std::mem::take(&mut app.default_prevented) && !self.ctx.is_null() { + // SAFETY: the live context; the kit is delivering this key (BK_key) now. + unsafe { sys::BK_key_taken(self.ctx) }; + } if page != 0.0 { self.scroll_page(page); } diff --git a/docs/android.md b/docs/android.md index cc0e93d7..d97cd22f 100644 --- a/docs/android.md +++ b/docs/android.md @@ -16,8 +16,13 @@ python platform/android/build.py --lua examples/android # a Lua app (the python platform/android/build.py --rust platform/android/rust # a Rust app (a staticlib crate) python platform/android/build.py --js app.jsx # a JavaScript app: React, Vue or Svelte on QuickJS python platform/android/build.py --imgui [app.cpp] # a Dear ImGui app (C++) +python platform/android/build.py --rust app/android --label MyApp --package com.me.app --permission INTERNET ``` +`--label` names the app on the phone (and the APK file), `--package` is its id (default `org.bui.app`), +and each `--permission` adds one (`INTERNET` for an app that goes online; a bare name means +`android.permission.NAME`). + Needs the Android SDK (`ANDROID_HOME`; build-tools, platform 34), an NDK (the newest in the SDK, or `ANDROID_NDK_HOME`), CMake, a JDK for `keytool`, and for Rust `cargo` with the Android targets (`rustup target add aarch64-linux-android x86_64-linux-android`). The APK is signed with @@ -27,7 +32,7 @@ Needs the Android SDK (`ANDROID_HOME`; build-tools, platform 34), an NDK (the ne | Language | You write | Run it | | --- | --- | --- | -| **Rust** | an ordinary `blenderui` app in a `staticlib` crate with `#[unsafe(no_mangle)] pub extern "C" fn bui_app_main() { Application::new().run(...) }` (`platform/android/rust`) | `--rust CRATE` | +| **Rust** | an ordinary `blenderui` app in a `staticlib` crate with `blenderui::android_main!(run);`, where `run` is the `fn()` a desktop `main` would call (`platform/android/rust`) | `--rust CRATE` | | **Lua** | an ordinary BUI Lua script, `assets/main.lua`, ending in `bui.open{root=...}` or `bui.Window(...)` + `bui.run()`; `require` finds your other `.lua` files and `bui.lua` in the APK | `--lua DIR` | | **JavaScript** | an ordinary `@blender-ui/native`, React, Vue or Svelte app (`.js`, `.jsx`, `.vue`, `.svelte`); it is bundled into one script (`bui bundle`, needs Bun) and runs on QuickJS (`bindings/rust/blenderui-qjs`, the engine `bui build` embeds), as `assets/main.js`; `console.log` goes to logcat (tag `bui-js`) | `--js ENTRY` | | **Dear ImGui** | an ordinary ImGui frame function in a C++ file with `bui_app_main` (`ImGui_ImplBUI_CreateApp` / `RunApp`; `platform/android/imgui_app.cpp`), plus `BK_window_wm(win, "touch_drag", 1, 0)` so a drag is ImGui's (sliders, window moves) | `--imgui [FILE]` | @@ -42,7 +47,21 @@ when it is fetched, a frame costs O(visible rows)). The emulator runs it at abou For Rust the staticlib carries its own copy of the kit (`blenderui-sys` builds it for the target), so the app crate sets the kit's features itself (see its `Cargo.toml`: no GPU, ImGui or extra image -formats). +formats). The system libraries the staticlib needs (rustc's `native-static-libs`: `aaudio` for a +crate that plays sound, ...) are linked into the shared library for it. + +`android_main!` writes the unmangled entry point (so the app has no `unsafe`) and, before the app +runs: + +- gives the activity's JNI handles to `ndk-context`, which crates that call into Java read (cpal + lists sound devices through it; without it they panic); +- sends stdout and stderr to logcat, panics included: `adb logcat -s bui`; +- and the kit has pointed `HOME` at the app's files folder and `XDG_CACHE_HOME` / `TMPDIR` at its + cache folder, so `dirs::cache_dir()`, `dirs::home_dir()` and `std::env::temp_dir()` are folders the + app may write. + +A real app is SpotiTube-sized: a library crate shared with the desktop `main`, plus a small +`staticlib` crate whose whole source is the `android_main!` line. ## Behavior @@ -59,6 +78,10 @@ formats). touch in the 20 dp strip at the right edge of a custom or canvas node is the app's press and drag (a list's scrollbar thumb), so a huge list can be dragged to any place. Two fingers always scroll. `BK_window_wm(win, "touch_drag", 1, 0)` gives the drags of custom and canvas nodes to the app instead (a paint app); by default they scroll. +- **Back.** The Back key is the key `Escape`. It closes a popup or leaves a text field first; a Rust + key listener that acts on it calls `app.prevent_default()` (C bindings: `BK_key_taken`), and only a + Back nothing took finishes the activity. An app with screens of its own walks back through them + this way. - **Keyboard.** The soft keyboard opens while a text field or area is being edited (through the input method manager: the activity's view is not a text editor, so `ANativeActivity_showSoftInput` is ignored by current Android). Keys arrive as key events (`KeyEvent.getUnicodeChar`), so typing, @@ -80,7 +103,8 @@ formats). Inter is left out of the build (`BUI_NO_INTER`, 0.8 MB). The shell registers the system's fonts (`platform/android/fonts.c`: Roboto and Droid Sans Mono from `/system/fonts` as the families `sans` and -`mono`). To use your own, call `BUI_text_add_font(family, flags, data, len)` with the font's bytes +`mono`). Characters Roboto lacks (Hangul, kana, Han, Thai, Indic, symbols) come from the phone's Noto +fonts in `/system/fonts`, by the per-glyph fallback every platform has. To use your own, call `BUI_text_add_font(family, flags, data, len)` with the font's bytes (from `BK_android_assets()` or a file) and select it with `BK_set_font(family)`, as on any platform. ## Size diff --git a/gpu/intern/gpu_fonts.c b/gpu/intern/gpu_fonts.c index de68c070..250d2b67 100644 --- a/gpu/intern/gpu_fonts.c +++ b/gpu/intern/gpu_fonts.c @@ -54,6 +54,12 @@ int gpu_font_dirs(char dirs[][GPU_FONT_PATH], int max) if (home && n < max) { snprintf(dirs[n++], GPU_FONT_PATH, "%s/Library/Fonts", home); } +#elif defined(__ANDROID__) + /* the system's Noto set (CJK, Thai, Indic, symbols ...) and a vendor's extra fonts */ + static const char *droid[] = {"/system/fonts", "/product/fonts"}; + for (int i = 0; i < 2 && n < max; i++) { + snprintf(dirs[n++], GPU_FONT_PATH, "%s", droid[i]); + } #else static const char *nix[] = { "/usr/share/fonts/truetype/dejavu", "/usr/share/fonts/dejavu", diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.h index 0aa0da21..cec0b962 100644 --- a/kit/include/BUI_kit.h +++ b/kit/include/BUI_kit.h @@ -827,6 +827,10 @@ int BK_scroll(BKContext *ctx, int x, int y, float dx, float dy, int mods); * (BK_EV_WHEEL) carry the pixels in `b`. */ int BK_scroll_px(BKContext *ctx, int x, int y, float dx, float dy, int mods); int BK_key(BKContext *ctx, const char *text, const char *keysym, int mods); +/* Called by a binding while it handles a key's raw event (BK_EV_KEY) when it acted on the key: + * BK_key then returns 1 and no widget or shortcut sees the key. A host acts on a key BK_key + * returned 0 for (Android's Back key finishes the activity). */ +void BK_key_taken(BKContext *ctx); int BK_context_menu(BKContext *ctx, int x, int y, int mods); /* -- Input methods (IME) ------------------------------------------------------ @@ -981,10 +985,16 @@ void BK_window_set_keep_alive(int on); * callbacks and starts a new run (a relaunch after Back reuses the process); BK_window_supported() * is 1 from then on. `android_main` calls BK_android_detach before it returns (the glue then frees * the app): a BK_window_wake from another thread does nothing from then on. BK_android_assets is - * the APK's `AAssetManager *` (the assets/ folder). */ + * the APK's `AAssetManager *` (the assets/ folder). BK_android_activity is the `ANativeActivity *` + * (its `vm` and `clazz` are what JNI code needs), NULL while no activity runs. + * + * Attaching points HOME at the app's private files folder, XDG_CACHE_HOME and TMPDIR at its cache + * folder (which the system may clear), so code that asks for the usual folders (Rust's `dirs`) + * gets folders the app may write. Variables already set are left alone. */ void BK_android_attach(void *android_app); void BK_android_detach(void); void *BK_android_assets(void); +void *BK_android_activity(void); #endif /* One of Blender's widgets drawn straight into a raster, outside any BKContext: the same diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c index 949dc7b3..590c4c49 100644 --- a/kit/intern/kit_core.c +++ b/kit/intern/kit_core.c @@ -3224,12 +3224,17 @@ static int in_BK_key(BKContext *ctx, const char *text, const char *keysym, int m e.keysym = keysym ? keysym : ""; snprintf(ctx->key_held, sizeof(ctx->key_held), "%s", e.keysym); ctx->interaction++; + ctx->key_taken = 0; for (BKNode *n = ctx->focus ? ctx->focus : ctx->hover; n; n = n->parent) { if (n->flags & NF_EVENTS) { /* Tk/Qt key bindings see the key first */ bk_event(n, BK_EV_KEY, mods, &e); break; } } + if (ctx->key_taken) { /* the host's binding acted on it: nothing else does */ + ctx->key_taken = 0; + return 1; + } if (ctx->modal) { if (bk_keysym_is(e.keysym, "Escape")) { bk_end_modal(ctx); @@ -3851,6 +3856,13 @@ int BK_key(BKContext *ctx, const char *text, const char *keysym, int mods) INPUT_ENTRY(in_BK_key(ctx, text, keysym, mods)); } +void BK_key_taken(BKContext *ctx) +{ + if (ctx) { + ctx->key_taken = 1; + } +} + int BK_scroll(BKContext *ctx, int x, int y, float dx, float dy, int mods) { BKNode *t = BK_IS_CUSTOM(ctx->grab) ? ctx->grab : (ctx->modal ? NULL : hit_all(ctx, x, y)); diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h index bb0c3c98..4b4ab268 100644 --- a/kit/intern/kit_intern.h +++ b/kit/intern/kit_intern.h @@ -625,6 +625,7 @@ struct BKContext { int ungrab_x, ungrab_y; /* where a continuous drag puts the pointer back */ int press_button; /* the button that started the grab (1, 2, 3) */ char key_held[32]; /* wmWindow.pie_event_type_last: the key down now, "" = none */ + int key_taken; /* the host acted on the key's raw event (BK_key_taken) */ bool has_ungrab; bool has_skip; int pointer_x, pointer_y; diff --git a/kit/intern/kit_window_android.c b/kit/intern/kit_window_android.c index 9335de82..6079b72f 100644 --- a/kit/intern/kit_window_android.c +++ b/kit/intern/kit_window_android.c @@ -27,11 +27,13 @@ # include # include # include +# include # include # include # include # include # include +# include # include # include "GPU_raster.h" @@ -774,6 +776,32 @@ static void on_cmd(struct android_app *app, int32_t cmd) } } +/* `name` = `path` unless the variable is set. */ +static void env_default(const char *name, const char *path) +{ + if (path && path[0]) { + setenv(name, path, 0); + } +} + +/* The app's folders as the usual variables: HOME = files/, the cache = cache/ beside it. */ +static void app_folders(const ANativeActivity *activity) +{ + const char *files = activity->internalDataPath; + env_default("HOME", files); + const char *slash = files ? strrchr(files, '/') : NULL; + if (!slash) { + return; + } + char cache[PATH_MAX]; + if (snprintf(cache, sizeof(cache), "%.*s/cache", (int)(slash - files), files) >= (int)sizeof(cache)) { + return; + } + mkdir(cache, 0700); /* the system makes it with the app; it may be cleared */ + env_default("XDG_CACHE_HOME", cache); + env_default("TMPDIR", cache); +} + void BK_android_attach(void *android_app) { /* A new activity: the process (and these) may outlive the last one, which Back finished. */ @@ -784,6 +812,7 @@ void BK_android_attach(void *android_app) g_app = (struct android_app *)android_app; g_app->onAppCmd = on_cmd; g_app->onInputEvent = on_input; + app_folders(g_app->activity); pthread_mutex_lock(&g_wake_lock); g_looper = g_app->looper; pthread_mutex_unlock(&g_wake_lock); @@ -802,6 +831,11 @@ void *BK_android_assets(void) return g_app ? (void *)g_app->activity->assetManager : NULL; } +void *BK_android_activity(void) +{ + return g_app ? (void *)g_app->activity : NULL; +} + /* -- the loop ----------------------------------------------------------------------------------- */ static int open_windows(void) diff --git a/platform/android/CMakeLists.txt b/platform/android/CMakeLists.txt index 477b5f38..a8d2f202 100644 --- a/platform/android/CMakeLists.txt +++ b/platform/android/CMakeLists.txt @@ -10,6 +10,7 @@ set(BUI_ANDROID_APP "demo" CACHE STRING "demo, lua, rust or imgui") set(BUI_ANDROID_IMGUI_SRC "${CMAKE_CURRENT_SOURCE_DIR}/imgui_app.cpp" CACHE FILEPATH "the Dear ImGui app (BUI_ANDROID_APP=imgui): a .cpp defining bui_app_main") set(BUI_ANDROID_RUST_LIB "" CACHE FILEPATH "libXXX.a of the Rust app (BUI_ANDROID_APP=rust)") +set(BUI_ANDROID_RUST_LINK "" CACHE STRING "system libraries the Rust app needs (names, ;-separated)") set(_glue "${CMAKE_ANDROID_NDK}/sources/android/native_app_glue") add_library(bui_app SHARED bui_android.c fonts.c ${_glue}/android_native_app_glue.c) @@ -42,7 +43,8 @@ elseif(BUI_ANDROID_APP STREQUAL "rust") # kit is not linked again; only its headers (the shell and fonts.c use them) and libc++ are needed target_include_directories(bui_app PRIVATE ${BUI_SOURCE_DIR}/kit/include ${BUI_SOURCE_DIR}/gpu/include) set_target_properties(bui_app PROPERTIES LINKER_LANGUAGE CXX) - target_link_libraries(bui_app PRIVATE "${BUI_ANDROID_RUST_LIB}") + # the system libraries the staticlib needs (rustc's native-static-libs: aaudio for sound, ...) + target_link_libraries(bui_app PRIVATE "${BUI_ANDROID_RUST_LIB}" ${BUI_ANDROID_RUST_LINK}) else() message(FATAL_ERROR "BUI_ANDROID_APP must be demo, lua, rust or imgui") endif() diff --git a/platform/android/build.py b/platform/android/build.py index 53ae55e1..cda05f92 100644 --- a/platform/android/build.py +++ b/platform/android/build.py @@ -8,6 +8,7 @@ python platform/android/build.py --rust platform/android/rust # a Rust app (a staticlib crate) python platform/android/build.py --js app.jsx # a JavaScript app (React, Vue, Svelte): QuickJS + the bundle python platform/android/build.py --imgui [app.cpp] # a Dear ImGui app (C++; the default is the demo in imgui_app.cpp) + python platform/android/build.py --rust app/android --label MyApp --package com.me.app --permission INTERNET ANDROID_HOME / ANDROID_SDK_ROOT (else the usual per-user SDK folder) locates the SDK; the NDK is the newest one in it (or ANDROID_NDK_HOME). @@ -83,8 +84,22 @@ def staticlib(messages, manifest): return found +def native_libs(rendered): + """The system libraries the staticlib needs, from rustc's note (`native-static-libs: -llog + -ldl ...`, rendered by cargo on stderr), as names for CMake: a staticlib doesn't carry them, so + the shared library links them.""" + libs = [] + for line in rendered.splitlines(): + _, found, rest = line.partition("native-static-libs:") + if found: + libs = [w[2:] for w in rest.split() if w.startswith("-l")] + # in order, once each; Bionic's libc has pthread and rt in it, and the NDK has no stubs for them + return [lib for lib in dict.fromkeys(libs) if lib not in ("pthread", "rt")] + + def build_rust(crate, ndk, abi, make): - """cargo builds the app's staticlib (and, through blenderui-sys, the kit) for one ABI.""" + """cargo builds the app's staticlib (and, through blenderui-sys, the kit) for one ABI; gives + the library and the system libraries it needs.""" triple = RUST_TARGETS[abi] # the cmake crate reads the toolchain file from the environment; `make` is found on PATH. CC / # CXX / AR name the NDK's clang so the crate passes clang's flags, not the host compiler's @@ -106,11 +121,14 @@ def build_rust(crate, ndk, abi, make): env.setdefault("LIBCLANG_PATH", llvm if os.name == "nt" else os.path.normpath(os.path.join(llvm, "..", "lib"))) env.update(**{"BINDGEN_EXTRA_CLANG_ARGS_" + var: shlex.quote("--sysroot=" + sysroot.replace("\\", "/"))}) manifest = os.path.abspath(os.path.join(crate, "Cargo.toml")) - cmd = ["cargo", "build", "--release", "--lib", "--target", triple, "--manifest-path", manifest, - "--message-format=json-render-diagnostics"] + # `cargo rustc`: the note flag reaches the app crate alone, so no dependency builds again + cmd = ["cargo", "rustc", "--release", "--lib", "--target", triple, "--manifest-path", manifest, + "--message-format=json-render-diagnostics", "--", "--print=native-static-libs"] print("+", " ".join(cmd)) - done = subprocess.run(cmd, env=env, check=True, stdout=subprocess.PIPE, text=True) - return staticlib(done.stdout, manifest) + done = subprocess.run(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + sys.stderr.write(done.stderr) # cargo's progress and the diagnostics, as they would have shown + done.check_returncode() + return staticlib(done.stdout, manifest), native_libs(done.stderr) def build_abi(ndk, abi, out, app_args, rust=None): @@ -121,7 +139,9 @@ def build_abi(ndk, abi, out, app_args, rust=None): make = os.path.join(ndk, "prebuilt", host, "bin", "make" + exe) bdir = os.path.join(out, abi) if rust: - app_args = ["-DBUI_ANDROID_APP=rust", "-DBUI_ANDROID_RUST_LIB=" + build_rust(rust, ndk, abi, make).replace("\\", "/")] + lib, libs = build_rust(rust, ndk, abi, make) + app_args = ["-DBUI_ANDROID_APP=rust", "-DBUI_ANDROID_RUST_LIB=" + lib.replace("\\", "/"), + "-DBUI_ANDROID_RUST_LINK=" + ";".join(libs)] args = ["cmake", "-S", ROOT, "-B", bdir, "-G", "Unix Makefiles", "-DCMAKE_MAKE_PROGRAM=" + make.replace("\\", "/"), "-DCMAKE_TOOLCHAIN_FILE=" + os.path.join(ndk, "build", "cmake", "android.toolchain.cmake").replace("\\", "/"), @@ -144,14 +164,28 @@ def keystore(out): return path -def apk(root_sdk, libs, out, assets): +def manifest(out, package, label, permissions): + """The shell's AndroidManifest.xml with the app's package, name and permissions.""" + with open(os.path.join(ROOT, "platform", "android", "AndroidManifest.xml"), encoding="utf-8") as f: + text = f.read() + text = text.replace('package="org.bui.app"', 'package="%s"' % package) + text = text.replace('android:label="BUI"', 'android:label="%s"' % label) + uses = "".join(' \n' % (p if "." in p else "android.permission." + p) + for p in permissions) + text = text.replace(" @@ -126,10 +133,11 @@ Python, Qt, tkinter and D need their runtime on the device and are not available - **Damage driven.** The thread sleeps until a touch, key, timer or frame request, and only the damaged rectangles are converted and locked. An idle app uses no CPU. - **Scale.** A CSS pixel is a dp, as in Chrome on Android. - **Touch.** One finger is the pointer and a tap is a click. A drag that starts on a widget that drags (sliders, text, scrollbars) drags it; anywhere else it scrolls, following the finger exactly and carrying on after it lifts with the deceleration of iOS's scroll views. A touch at the right edge of a custom node drags the app's scrollbar, so a list of millions of rows can be dragged to any place. Two fingers always scroll. +- **Back.** The Back key arrives as `Escape`. A key listener that closes something on it calls `app.prevent_default()`; only a Back that nothing took closes the app, so an app walks back through its own screens. - **Keyboard.** It opens while a text field is edited (through the input method manager, since the activity's view is not a text editor); keys arrive as key events. Predictive keyboards and IME composition are not wired up yet. - **Lifecycle.** One activity: launching the app while it runs brings it back, and after Back finishes it the next launch runs `bui_app_main` again from a fresh start, even in the same process. A Lua script that fails shows its error on screen, also after it opened its window. - **Big lists.** The Rust demo scrolls a list of 10 million rows and a chat of 100 000 messages (`blenderui::vlist`): only the rows in view exist, so a frame costs the visible rows, not the list. -- **Fonts.** The system's Roboto is used (Inter is left out, 0.8 MB). Register your own with `BUI_text_add_font` and select it with `BK_set_font`. +- **Fonts.** The system's Roboto is used (Inter is left out, 0.8 MB), and characters it lacks (Hangul, kana, Han, Thai, Indic) come from the phone's Noto fonts. Register your own with `BUI_text_add_font` (Rust: `blenderui::add_font`) and select it with `BK_set_font` or `font-family`. - **Size.** About 1.1 MB per ABI for the C demo, 1.4 MB with Lua and 2.0 MB with Rust (arm64-v8a).