Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

mobile: build the core for Android

RoversX5ad6d1106409
diff --git a/Cargo.lock b/Cargo.lock
index 2aacf7e4..ecde8f19 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7793,7 +7793,10 @@ dependencies = [
"bytemuck",
"codec",
"futures",
+ "jni-sys",
"log",
+ "ndk-sys",
+ "raw-window-handle",
"russh",
"serde",
"serde_json",
diff --git a/thinkterm-mobile/Cargo.toml b/thinkterm-mobile/Cargo.toml
index a34ac028..9188ddd7 100644
--- a/thinkterm-mobile/Cargo.toml
+++ b/thinkterm-mobile/Cargo.toml
@@ -39,3 +39,10 @@ uniffi = { workspace = true, features = ["cli"] }
wezterm-color-types.workspace = true
wezterm-term = { workspace = true, features = ["use_serde"] }
wgpu.workspace = true
+
+# The Android shell hands over a java.lang.Surface; the native window
+# behind it, and logcat, are NDK calls.
+[target.'cfg(target_os = "android")'.dependencies]
+jni-sys = "0.3"
+ndk-sys = "0.5"
+raw-window-handle.workspace = true
diff --git a/thinkterm-mobile/src/core.rs b/thinkterm-mobile/src/core.rs
index ee06c7a2..8c701132 100644
--- a/thinkterm-mobile/src/core.rs
+++ b/thinkterm-mobile/src/core.rs
@@ -1002,7 +1002,27 @@ impl State {
.context("creating the Metal surface")
}
- #[cfg(not(target_vendor = "apple"))]
+ /// `layer` is an `ANativeWindow*` the shell took from its Surface
+ /// (`NativeWindow.fromSurface`), which it keeps alive until after
+ /// `detach_surface`.
+ #[cfg(target_os = "android")]
+ fn surface_from_layer(&self, layer: usize) -> Result<wgpu::Surface<'static>> {
+ use raw_window_handle::{AndroidDisplayHandle, AndroidNdkWindowHandle, RawDisplayHandle, RawWindowHandle};
+ let Some(window) = std::ptr::NonNull::new(layer as *mut std::ffi::c_void) else {
+ anyhow::bail!("null window");
+ };
+ // SAFETY: the shell guarantees the window outlives the surface,
+ // dropping it only after `detach_surface` returned.
+ unsafe {
+ self.instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
+ raw_display_handle: RawDisplayHandle::Android(AndroidDisplayHandle::new()),
+ raw_window_handle: RawWindowHandle::AndroidNdk(AndroidNdkWindowHandle::new(window)),
+ })
+ }
+ .context("creating the Vulkan surface")
+ }
+
+ #[cfg(not(any(target_vendor = "apple", target_os = "android")))]
fn surface_from_layer(&self, _layer: usize) -> Result<wgpu::Surface<'static>> {
anyhow::bail!("no surface source on this platform yet")
}
diff --git a/thinkterm-mobile/src/lib.rs b/thinkterm-mobile/src/lib.rs
index 77e9914f..ab2bf599 100644
--- a/thinkterm-mobile/src/lib.rs
+++ b/thinkterm-mobile/src/lib.rs
@@ -61,8 +61,9 @@ pub trait Notify: Send + Sync {
fn on_preview(&self, pane: u32, rows: String);
}
-/// Rust's `log` output goes to stdout, which the simulator's console shows;
-/// a device build will want os_log instead.
+/// Rust's `log` output goes to stdout, which the simulator's console shows
+/// (a device build will want os_log instead); on Android, to logcat under
+/// the tag "thinkterm".
struct StdoutLogger;
impl log::Log for StdoutLogger {
@@ -70,24 +71,68 @@ impl log::Log for StdoutLogger {
metadata.level() <= log::Level::Info
}
fn log(&self, record: &log::Record) {
- if self.enabled(record.metadata()) {
- println!(
- "rust {} {}: {}",
- record.level(),
- record.target(),
- record.args()
- );
+ if !self.enabled(record.metadata()) {
+ return;
}
+ let line = format!("rust {} {}: {}", record.level(), record.target(), record.args());
+ #[cfg(target_os = "android")]
+ {
+ if let Ok(c) = std::ffi::CString::new(line) {
+ let prio = match record.level() {
+ log::Level::Error => ndk_sys::android_LogPriority::ANDROID_LOG_ERROR,
+ log::Level::Warn => ndk_sys::android_LogPriority::ANDROID_LOG_WARN,
+ _ => ndk_sys::android_LogPriority::ANDROID_LOG_INFO,
+ };
+ // SAFETY: both strings are NUL-terminated and outlive the call.
+ unsafe {
+ ndk_sys::__android_log_write(prio.0 as std::ffi::c_int, c"thinkterm".as_ptr(), c.as_ptr());
+ }
+ }
+ return;
+ }
+ #[allow(unreachable_code)]
+ println!("{line}");
}
fn flush(&self) {}
}
+/// The Android shell cannot reach an `ANativeWindow*` from Kotlin: these
+/// two JNI entry points do it for `com.roversx.thinkterm.NativeWindow`.
+/// `fromSurface` acquires a reference the shell releases with `release`
+/// after `detach_surface`.
+#[cfg(target_os = "android")]
+#[no_mangle]
+pub extern "C" fn Java_com_roversx_thinkterm_NativeWindow_fromSurface(
+ env: *mut jni_sys::JNIEnv,
+ _class: jni_sys::jclass,
+ surface: jni_sys::jobject,
+) -> jni_sys::jlong {
+ // SAFETY: the JVM hands over a live env and a Surface object.
+ unsafe { ndk_sys::ANativeWindow_fromSurface(env as *mut _, surface as *mut _) as jni_sys::jlong }
+}
+
+#[cfg(target_os = "android")]
+#[no_mangle]
+pub extern "C" fn Java_com_roversx_thinkterm_NativeWindow_release(
+ _env: *mut jni_sys::JNIEnv,
+ _class: jni_sys::jclass,
+ window: jni_sys::jlong,
+) {
+ if window != 0 {
+ // SAFETY: a pointer `fromSurface` returned, released once.
+ unsafe { ndk_sys::ANativeWindow_release(window as *mut _) }
+ }
+}
+
fn install_logger() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
static LOGGER: StdoutLogger = StdoutLogger;
let _ = log::set_logger(&LOGGER);
log::set_max_level(log::LevelFilter::Info);
+ // A panic on the core thread ends it silently otherwise: stderr
+ // goes nowhere on a phone.
+ std::panic::set_hook(Box::new(|info| log::error!("panic: {info}")));
});
}
diff --git a/thinkterm-mobile/uniffi.toml b/thinkterm-mobile/uniffi.toml
new file mode 100644
index 00000000..cc08652c
--- /dev/null
+++ b/thinkterm-mobile/uniffi.toml
@@ -0,0 +1,4 @@
+# The Kotlin bindings' package; the library is loaded by JNA under this name.
+[bindings.kotlin]
+package_name = "com.roversx.thinkterm.core"
+cdylib_name = "thinkterm_mobile"