Run Android on Kryon's NativeActivity host without raylib

Kryon's android_run owns NativeActivity lifecycle, touch, IME, density
and software presentation; Werkzeug draws each frame through
ProjectFrame and wraps android_main to save its apps on exit. Werkzeug's
own android_jni.zi is replaced by kryon/android_jni.

The NDK build links kryon_android_codecs (WebP and AVIF) instead of
raylib and compiles Kryon's APK fopen reader. APK files are read through
that reader, and an Android image cache keeps decoded pixels within a
fixed budget for the Pixmap renderer. Java text is converted through
explicit UTF-8, so NUL and supplementary characters survive. While an
EditText is editing, hardware keys go to it instead of the native queue.

RAYLIB_DIR is gone from the Makefile, the Gradle environment and the
release workflow.

Local tests (on the final tree of this series, published pins, no local
overrides, through build-queue): make test including ziran fmt --check,
gui-smoke, gui-test, gallery-gui-test and web-smoke on private displays.
Not run on these pins: the private-emulator Android gate. On an earlier
pin the x86_64 APK built and validated and android-input-test passed
until Entity's add-node page, which needs Kryon's density damage fix
(78af4090); it runs with the next Kryon pin update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
waoziandClaude Opus 5.5 committed 2026-11-17 01:10:41 -03:00
1 parent 1b283cb00b
commit d047174079
17 files changed
+433 -575

No files matched your search

-1
View File
@@ -149,7 +149,6 @@ jobs:
chmod +x droid/gradlew
export KRYON_DIR="$(./scripts/ziran.sh pkg path Kryon --locked)"
export ZIRAN_ROOT="$(./scripts/ziran.sh pkg path ziran --locked)"
export RAYLIB_DIR="$(./scripts/ziran.sh pkg path raylib --locked)/src"
export LIBOQS_DIR="$(./scripts/ziran.sh pkg path liboqs --locked)"
export MONOCYPHER_DIR="$(./scripts/ziran.sh pkg path monocypher --locked)"
./droid/gradlew -p droid assembleRelease \
+5 -6
View File
@@ -2,11 +2,10 @@
ZIRAN ?= ./scripts/ziran.sh
# Gradle invokes make again for portable bundles. Inherited environment
# variables otherwise export these shell-derived paths while resolving them.
unexport ZIRAN_ROOT KRYON_DIR RAYLIB_DIR MINGCUTE_DIR LIBOQS_DIR MONOCYPHER_DIR QRCODE_DIR WORKBOOK_DIR ENTITY_DIR APPS_DIR AUTH_DIR CRYPTO_DIR
unexport ZIRAN_ROOT KRYON_DIR MINGCUTE_DIR LIBOQS_DIR MONOCYPHER_DIR QRCODE_DIR WORKBOOK_DIR ENTITY_DIR APPS_DIR AUTH_DIR CRYPTO_DIR
# Local overrides refer to the real root repositories. Published builds
# require the exact versions recorded in the committed lock.
LOCK_FLAGS := $(if $(wildcard ziran.local.toml),,--locked)
RAYLIB_DIR = $(shell $(ZIRAN) pkg path raylib $(LOCK_FLAGS))/src
# Package resolution may build its compiler. Do not pass this make's target
# overrides or jobserver descriptors to that independent package build.
PACKAGE_ZIRAN = env -u MAKEFLAGS -u MFLAGS -u MAKEOVERRIDES $(ZIRAN)
@@ -203,22 +202,22 @@ web-smoke: site
# CMake emits JNI and foreign ABI types separately for each Android ABI.
android-debug: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-universal-debug.apk build/werk-android-debug.apk
python3 scripts/android_apk_check.py build/werk-android-debug.apk
cp droid/app/build/outputs/apk/debug/app-arm64-v8a-debug.apk build/werk-android-arm64-v8a-debug.apk
cp droid/app/build/outputs/apk/debug/app-armeabi-v7a-debug.apk build/werk-android-armeabi-v7a-debug.apk
android-emulator: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleDebug -Pabi=x86_64 $(GRADLE_ARGS)
mkdir -p build
cp droid/app/build/outputs/apk/debug/app-debug.apk build/werk-android-emulator.apk
python3 scripts/android_apk_check.py build/werk-android-emulator.apk
android-release: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew assembleRelease -Pabi=$(ANDROID_ABIS) -PsplitApks=true $(GRADLE_ARGS)
.PHONY: android-bundle
android-bundle: portable-apps
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" RAYLIB_DIR="$(RAYLIB_DIR)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew bundleRelease -Pabi=$(ANDROID_ABIS) $(GRADLE_ARGS)
cd droid && env WERK_ZIRAN_COMMAND="$(ZIRAN)" KRYON_DIR="$(KRYON_DIR)" ZIRAN_ROOT="$(ZIRAN_ROOT)" LIBOQS_DIR="$(LIBOQS_DIR)" MONOCYPHER_DIR="$(MONOCYPHER_DIR)" ./gradlew bundleRelease -Pabi=$(ANDROID_ABIS) $(GRADLE_ARGS)
cp droid/app/build/outputs/bundle/release/app-release.aab build/werk-$(shell cat VERSION).aab
.PHONY: android-fdroid
# F-Droid compares this source build with the signed upstream release.
+2 -2
View File
@@ -103,14 +103,14 @@ tasks.named('preBuild').configure { dependsOn prepareFonts }
// The tool apps are portable bundles, built once for every ABI.
def makeApps = tasks.register('makeApps', Exec) {
workingDir '../..'
workingDir rootProject.file('..')
if (System.getenv('WERK_ZIRAN_COMMAND')) {
environment 'ZIRAN', System.getenv('WERK_ZIRAN_COMMAND')
}
commandLine 'make', 'portable-apps'
}
def kryonSource = providers.environmentVariable('KRYON_DIR').orElse(providers.exec {
workingDir '../..'
workingDir rootProject.file('..')
commandLine (System.getenv('WERK_ZIRAN_COMMAND') ?: rootProject.file('../scripts/ziran.sh').absolutePath), 'pkg', 'path', 'kryon'
}.standardOutput.asText.map { it.trim() })
// Entity owns the account policy; Kryon supplies the shared Android consent UI.
+27 -21
View File
@@ -1,20 +1,20 @@
cmake_minimum_required(VERSION 3.22)
project(Werkzeug C)
project(Werkzeug C ASM)
get_filename_component(REPO_ROOT "${CMAKE_CURRENT_LIST_DIR}/../../../../.." ABSOLUTE)
set(ZIRAN "${REPO_ROOT}/scripts/ziran.sh")
if(DEFINED ENV{WERK_ZIRAN_COMMAND} AND NOT "$ENV{WERK_ZIRAN_COMMAND}" STREQUAL "")
get_filename_component(ZIRAN "$ENV{WERK_ZIRAN_COMMAND}" ABSOLUTE BASE_DIR "${REPO_ROOT}")
endif()
set(GENERATED "${CMAKE_BINARY_DIR}/ziran")
set(DEFINES --define ANDROID_BUILD)
set(DEFINES --define ANDROID_BUILD --target-os android)
if(ANDROID_ABI STREQUAL "arm64-v8a")
list(APPEND DEFINES --define __aarch64__)
list(APPEND DEFINES --define __aarch64__ --target-cpu arm64)
elseif(ANDROID_ABI STREQUAL "armeabi-v7a")
list(APPEND DEFINES --define __arm__)
list(APPEND DEFINES --define __arm__ --target-cpu none)
elseif(ANDROID_ABI STREQUAL "x86_64")
list(APPEND DEFINES --define __x86_64__)
list(APPEND DEFINES --define __x86_64__ --target-cpu x64)
elseif(ANDROID_ABI STREQUAL "x86")
list(APPEND DEFINES --define __i386__)
list(APPEND DEFINES --define __i386__ --target-cpu none)
else()
message(FATAL_ERROR "Unsupported Android ABI: ${ANDROID_ABI}")
endif()
@@ -37,7 +37,6 @@ function(werk_package variable package suffix)
endfunction()
werk_package(KRYON_DIR kryon "")
werk_package(ZIRAN_ROOT ziran "")
werk_package(RAYLIB_DIR raylib "/src")
werk_package(WEBP_DIR libwebp "")
werk_package(AVIF_DIR libavif "")
werk_package(AOM_DIR libaom "")
@@ -45,13 +44,14 @@ werk_package(LIBOQS_DIR liboqs "")
werk_package(MONOCYPHER_DIR monocypher "")
werk_package(WORKBOOK_DIR workbook "")
file(GLOB_RECURSE SOURCE_INPUTS CONFIGURE_DEPENDS
"${REPO_ROOT}/src/*.zi" "${WORKBOOK_DIR}/src/*.zi" "${KRYON_DIR}/src/*.zi" "${ZIRAN_ROOT}/std/*.zi")
"${REPO_ROOT}/src/*.zi" "${REPO_ROOT}/apps/gallery/*.zi" "${WORKBOOK_DIR}/src/*.zi" "${KRYON_DIR}/src/*.zi" "${ZIRAN_ROOT}/std/*.zi")
list(APPEND SOURCE_INPUTS "${REPO_ROOT}/ziran.toml" "${REPO_ROOT}/ziran.lock" "${REPO_ROOT}/scripts/runtime_cache.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${SOURCE_INPUTS})
file(REMOVE_RECURSE "${GENERATED}")
execute_process(COMMAND "${ZIRAN}" build --project ${LOCK_FLAGS} ${DEFINES}
# Native linker callbacks are reached through raylib, outside Zi's entry
# graph. Keep them as the shared Android source generator does.
# NativeActivity and JNI callbacks are native linker roots.
--target=c --no-main -o "${GENERATED}" src/android_main.zi
"${KRYON_DIR}/src/backend/android_fopen.zi"
WORKING_DIRECTORY "${REPO_ROOT}" COMMAND_ERROR_IS_FATAL ANY)
file(GLOB GENERATED_SOURCES CONFIGURE_DEPENDS "${GENERATED}/*.c")
# Kryon's Android glue compiles its thread configurator with the same zi2c.
@@ -61,16 +61,20 @@ foreach(candidate "${ZIRAN_ROOT}/build/bin/zi2c" "${REPO_ROOT}/build/ziran-boots
endif()
endforeach()
include("${KRYON_DIR}/cmake/KryonAndroid.cmake")
kryon_android_raylib("${RAYLIB_DIR}" "${WEBP_DIR}" "${AVIF_DIR}" "${AOM_DIR}")
kryon_android_codecs("${WEBP_DIR}" "${AVIF_DIR}" "${AOM_DIR}")
# The portable runtime that runs the app bundles, built from the locked Ziran
# for this ABI.
set(BUNDLE_RUNTIME_DIR "${CMAKE_BINARY_DIR}/bundle-runtime")
execute_process(COMMAND python3 "${REPO_ROOT}/scripts/runtime_cache.py" "${ZIRAN_ROOT}" "${BUNDLE_RUNTIME_DIR}"
COMMAND_ERROR_IS_FATAL ANY)
execute_process(COMMAND make -C "${ZIRAN_ROOT}" BOOTSTRAP=1 "BUILD_DIR=${BUNDLE_RUNTIME_DIR}"
# Use the host's installed GNU Make, including an SDK-provided executable.
# All code generators run on the host; only runtime objects target the ABI.
find_program(WERK_MAKE_COMMAND NAMES make gmake REQUIRED)
execute_process(COMMAND "${WERK_MAKE_COMMAND}" -j4 -C "${ZIRAN_ROOT}"
"BUILD_DIR=${BUNDLE_RUNTIME_DIR}"
"CC=${CMAKE_C_COMPILER} --target=${CMAKE_C_COMPILER_TARGET} --sysroot=${CMAKE_SYSROOT}"
"AR=${CMAKE_AR}" "OBJCOPY=${CMAKE_OBJCOPY}" "CFLAGS=-O2 -fPIC"
"FRAMEFLAGS=-Wframe-larger-than=16384" "${BUNDLE_RUNTIME_DIR}/libziran.a"
"AR=${CMAKE_AR}" "OBJCOPY=${CMAKE_OBJCOPY}"
"GEN_ZI2C=${ZIRAN_ROOT}/build/bin/zi2c"
"CFLAGS=-O2 -fPIC" "FRAMEFLAGS=-Wframe-larger-than=16384"
"${BUNDLE_RUNTIME_DIR}/libziran.a"
COMMAND_ERROR_IS_FATAL ANY)
# Account sync: liboqs for ML-DSA-44 account keys, Monocypher for the rest.
set(OQS_BUILD_ONLY_LIB ON CACHE BOOL "" FORCE)
@@ -89,15 +93,17 @@ set_source_files_properties("${GENERATED}/android_glue.c"
PROPERTIES COMPILE_OPTIONS "-fvisibility=default")
add_library(main SHARED ${GENERATED_SOURCES}
"${MONOCYPHER_DIR}/src/monocypher.c" "${MONOCYPHER_DIR}/src/optional/monocypher-ed25519.c")
target_include_directories(main PRIVATE "${GENERATED}" "${ZIRAN_ROOT}/include"
target_compile_options(main PRIVATE "-iquote${GENERATED}")
target_include_directories(main PRIVATE "${ZIRAN_ROOT}/include"
"${MONOCYPHER_DIR}/src" "${MONOCYPHER_DIR}/src/optional")
target_link_libraries(main oqs)
target_link_libraries(main PRIVATE oqs z kryon_android_codecs)
kryon_android_app(main)
target_link_libraries(main "${BUNDLE_RUNTIME_DIR}/libziran.a")
target_link_options(main PRIVATE -Wl,--wrap=pthread_attr_init)
# Save hosted documents after the canonical NativeActivity loop returns.
target_link_options(main PRIVATE -Wl,--wrap=android_main)
target_link_libraries(main PRIVATE "${BUNDLE_RUNTIME_DIR}/libziran.a")
# Linker build IDs include debug-path differences even after stripping. The
# installed code is identical; omit this note for reproducible signed APKs.
# https://f-droid.org/docs/Reproducible_Builds/#ndk-build-id
target_link_options(main PRIVATE -Wl,--build-id=none)
# Werkzeug has no handwritten native sources; every app translation unit above is
# generated from .zi for this ABI. raylib and the NDK own native_app_glue.
# generated from .zi for this ABI. Kryon and the NDK own native_app_glue.
+76 -68
View File
@@ -1,6 +1,6 @@
// NativeActivity, AndroidKeyStore, and device authentication are called
// directly through JNI. No application Java or C implementation is needed.
#import "android_jni"
#import "kryon/android_jni"
#import "std/c_string"
#import "std/byte_text_linux"
#import "std/text_buffer"
@@ -38,7 +38,7 @@ secure_deadline: float64;
secure_master: [1024]u8;
AndroidInitialize :: () -> bool {
path := ActivityInternalDataPath()
path := AndroidInternalDataPath()
if path == null || ChangeDirectory(path) != 0 {
return false
}
@@ -68,7 +68,7 @@ AndroidInitialize :: () -> bool {
AndroidKeyboard :: (visible: bool) {
if visible == keyboard_visible { return }
app := NativeApp()
app := JniGetAndroidApp()
if app == null || app.activity == null { return }
keyboard_visible = visible
if visible { ShowKeyboard(app.activity, cast(u32)0) }
@@ -102,50 +102,58 @@ Method :: (env: *JniEnv, object: *void, name: string, signature: string, static:
if !JniOk(env) { return null }
return result
}
// Use Java's explicit UTF-8 conversion. JNI's NewStringUTF uses modified
// UTF-8 and cannot preserve NUL and supplementary characters from our fields.
TextObject :: (env: *JniEnv, value: string) -> *void {
text: [4096]u16
count: s32 = 0; index: s32 = 0
while index < cast(s32)value.count {
decoded := Decode(value, index)
codepoint := decoded.value
if count + 2 >= 4096 { return null }
if codepoint <= cast(u32)65535 { text[count] = cast(u16)codepoint; count += 1 }
else {
codepoint -= cast(u32)65536
text[count] = cast(u16)(cast(u32)55296 + (codepoint >> cast(u32)10))
text[count + 1] = cast(u16)(cast(u32)56320 + (codepoint & cast(u32)1023))
count += 2
}
index = decoded.after
if value.count > 16384 { return null }
bytes := env.functions.NewByteArray(env, cast(s32)value.count)
if !JniOk(env) || bytes == null { return null }
defer { env.functions.DeleteLocalRef(env, bytes) }
if value.count > 0 {
descriptor := cast(*TextDescriptor)(*value)
env.functions.SetByteArrayRegion(env, bytes, 0, cast(s32)value.count, descriptor.data)
if !JniOk(env) { return null }
}
return env.functions.NewString(env, *text[0], count)
type := Class(env, "java/lang/String")
if type == null { return null }
defer { env.functions.DeleteLocalRef(env, type) }
// Constructors are instance methods even though NewObjectA receives a class.
label: [16]u8; signature: [48]u8
unused CopyCString("<init>", label[:])
unused CopyCString("([BLjava/lang/String;)V", signature[:])
method := env.functions.GetMethodID(env, type, *label[0], *signature[0])
if !JniOk(env) || method == null { return null }
encoding_bytes: [8]u8
unused CopyCString("UTF-8", encoding_bytes[:])
encoding := AndroidJniString(env, *encoding_bytes[0])
if !JniOk(env) || encoding == null { return null }
defer { env.functions.DeleteLocalRef(env, encoding) }
arguments: [2]JniValue = .[ArgumentObject(bytes), ArgumentObject(encoding)]
result := env.functions.NewObjectA(env, type, method, *arguments[0])
if !JniOk(env) { return null }
return result
}
CopyJavaText :: (env: *JniEnv, value: *void, output: []u8) -> s32 {
if value == null || output.count == 0 { return -1 }
count := env.functions.GetStringLength(env, value)
chars := env.functions.GetStringChars(env, value, null)
if chars == null { return -1 }
index: s32 = 0; used: s32 = 0
while index < count {
codepoint := cast(u32)chars[index]
if codepoint >= cast(u32)55296 && codepoint <= cast(u32)56319 && index + 1 < count {
low := cast(u32)chars[index + 1]
if low >= cast(u32)56320 && low <= cast(u32)57343 {
codepoint = cast(u32)65536 + ((codepoint - cast(u32)55296) << cast(u32)10) + low - cast(u32)56320
index += 1
}
}
next := TypedTextAppend(output[0:output.count - 1], used, cast(s32)codepoint)
if next == used { used = -1; break }
used = next; index += 1
}
if used >= 0 { output[used] = cast(u8)0 }
env.functions.ReleaseStringChars(env, value, chars)
return used
encoding_bytes: [8]u8
unused CopyCString("UTF-8", encoding_bytes[:])
encoding := AndroidJniString(env, *encoding_bytes[0])
if !JniOk(env) || encoding == null { return -1 }
defer { env.functions.DeleteLocalRef(env, encoding) }
arguments: [1]JniValue = .[ArgumentObject(encoding)]
bytes := ObjectCall(env, value, "getBytes", "(Ljava/lang/String;)[B", arguments[:])
if bytes == null { return -1 }
defer { env.functions.DeleteLocalRef(env, bytes) }
count := env.functions.GetArrayLength(env, bytes)
if !JniOk(env) || count < 0 || cast(s64)count >= output.count { return -1 }
if count > 0 { env.functions.GetByteArrayRegion(env, bytes, 0, count, *output[0]) }
if !JniOk(env) { return -1 }
output[count] = 0
return count
}
ArgumentObject :: (reference: *void) -> JniValue { return JniValue.{cast(u64)cast(usize)reference} }
ArgumentInteger :: (integer: s32) -> JniValue { return JniValue.{cast(u64)cast(u32)integer} }
ArgumentBool :: (boolean: bool) -> JniValue { return JniValue.{cast(u64)boolean} }
ArgumentObject :: (reference: *void) -> JniValue { return JniValue.{.reference = reference} }
ArgumentInteger :: (integer: s32) -> JniValue { return JniValue.{.integer = integer} }
ArgumentBool :: (boolean: bool) -> JniValue { return JniValue.{.boolean = cast(u8)boolean} }
ObjectCall :: (env: *JniEnv, object: *void, name: string, signature: string, arguments: []JniValue) -> *void {
method := Method(env, object, name, signature, false)
if method == null { return null }
@@ -186,7 +194,7 @@ BoolCall :: (env: *JniEnv, object: *void, name: string, signature: string, argum
}
NoArguments :: () -> [1]JniValue { result: [1]JniValue; return result }
Service :: (session: *ActivityJniSession, name: string) -> *void {
Service :: (session: *AndroidJniSession, name: string) -> *void {
args: [1]JniValue
args[0] = ArgumentObject(TextObject(session.env, name))
return ObjectCall(session.env, session.activity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;", args[:])
@@ -196,8 +204,8 @@ AndroidReadPreference :: (name: string, output: []u8) -> s32 {
prefix := ".kryon_pass_"
if name.count <= prefix.count + 4 || name[0:cast(s32)prefix.count] != prefix { return -1 }
key := name[cast(s32)prefix.count:cast(s32)name.count - 4]
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return -1 }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return -1 }
env := session.env
args: [2]JniValue
args[0] = ArgumentObject(TextObject(env, "pass_preferences_pass")); args[1] = ArgumentInteger(0)
@@ -208,17 +216,17 @@ AndroidReadPreference :: (name: string, output: []u8) -> s32 {
if value != null && env.functions.ExceptionCheck(env) == cast(u8)0 {
count = CopyJavaText(env, value, output)
}
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
return count
}
AndroidSecureAvailable :: () -> bool {
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return false }
args := NoArguments()
keyguard := Service(*session, "keyguard")
available := BoolCall(session.env, keyguard, "isDeviceSecure", "()Z", args[:])
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
return available
}
AndroidSecureSaved :: () -> bool {
@@ -272,7 +280,7 @@ CreateKey :: (env: *JniEnv) -> bool {
return key != null && env.functions.ExceptionCheck(env) == cast(u8)0
}
ConfirmDevice :: (session: *ActivityJniSession) -> bool {
ConfirmDevice :: (session: *AndroidJniSession) -> bool {
keyguard := Service(session, "keyguard")
args: [2]JniValue
args[0] = ArgumentObject(TextObject(session.env, "Werkzeug"))
@@ -285,12 +293,12 @@ ConfirmDevice :: (session: *ActivityJniSession) -> bool {
AndroidSecureRequest :: (master: string, save: bool) -> bool {
if secure_pending != 0 || !AndroidSecureAvailable() { return false }
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return false }
ok: bool = true
if save { ok = CopyCString(master, secure_master[:]) && CreateKey(session.env) }
if ok { ok = ConfirmDevice(*session) }
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
if !ok { secure_master = .{}; return false }
secure_pending = ifx save then 1 else 2
secure_deadline = Now() + 60.0
@@ -308,7 +316,7 @@ Unhex :: (byte: u8) -> s32 {
return -1
}
TrySecure :: (session: *ActivityJniSession, output: []u8) -> s32 {
TrySecure :: (session: *AndroidJniSession, output: []u8) -> s32 {
env := session.env
key_store := KeyStore(env)
args: [3]JniValue
@@ -379,12 +387,12 @@ AndroidSecurePoll :: (output: []u8) -> s32 {
if secure_pending == 0 { return 0 }
result: s32 = 3
if Now() < secure_deadline {
session: ActivityJniSession
if activity_jni_attach(*session) != 0 {
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) != 0 {
result = TrySecure(*session, output)
// Unauthenticated key use is expected while the system prompt is open.
if session.env.functions.ExceptionCheck(session.env) != cast(u8)0 { session.env.functions.ExceptionClear(session.env) }
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
}
}
if result == 2 || result == 3 { secure_pending = 0; secure_master = .{} }
@@ -392,32 +400,32 @@ AndroidSecurePoll :: (output: []u8) -> s32 {
}
AndroidSecureForget :: () -> bool {
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return false }
args: [1]JniValue
args[0] = ArgumentObject(TextObject(session.env, "pass_master_ziran"))
ok := VoidCall(session.env, KeyStore(session.env), "deleteEntry", "(Ljava/lang/String;)V", args[:])
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
secure_pending = 0; secure_master = .{}
return WriteStore(SECURE_FILE, "") && ok
}
AndroidClipboardWrite :: (value: string) -> bool {
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return false }
args: [2]JniValue
args[0] = ArgumentObject(TextObject(session.env, "Werkzeug"))
args[1] = ArgumentObject(TextObject(session.env, value))
clip := StaticCall(session.env, "android/content/ClipData", "newPlainText", "(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Landroid/content/ClipData;", args[:])
args[0] = ArgumentObject(clip)
ok := VoidCall(session.env, Service(*session, "clipboard"), "setPrimaryClip", "(Landroid/content/ClipData;)V", args[:])
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
return ok
}
AndroidClipboardRead :: (output: []u8) -> string {
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return "" }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return "" }
args := NoArguments()
clip := ObjectCall(session.env, Service(*session, "clipboard"), "getPrimaryClip", "()Landroid/content/ClipData;", args[:])
args[0] = ArgumentInteger(0)
@@ -429,14 +437,14 @@ AndroidClipboardRead :: (output: []u8) -> string {
if string != null && session.env.functions.ExceptionCheck(session.env) == cast(u8)0 {
copied = CopyJavaText(session.env, string, output) >= 0
}
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
if copied { return TextUntilNul(output) }
return ""
}
AndroidDark :: () -> bool {
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return false }
env := session.env
args := NoArguments()
resources := ObjectCall(env, session.activity, "getResources", "()Landroid/content/res/Resources;", args[:])
@@ -446,6 +454,6 @@ AndroidDark :: () -> bool {
field := env.functions.GetFieldID(env, Class(env, "android/content/res/Configuration"), *name[0], *signature[0])
dark: bool
if config != null && field != null { dark = (env.functions.GetIntField(env, config, field) & 48) == 32 }
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
return dark
}
+9 -9
View File
@@ -2,7 +2,7 @@
// Ziran through RegisterNatives. The class has no app behavior or Java source.
// DEX layout: https://source.android.com/docs/core/runtime/dex-format
#import "android"
#import "android_jni"
#import "kryon/android_jni"
#import "c_string"
#import "byte_text_linux"
#import "text_buffer"
@@ -119,7 +119,7 @@ DexSeal :: (env: *JniEnv, bytes: []u8, length: s32) -> s32 {
DexClass :: (env: *JniEnv, bytes: []u8, length: s32, filename: string, name: string) -> *void {
if length <= 0 || length > bytes.count || length > 4096 || !SafeName(filename) { return null }
path: [1024]u8
base := TextFromCString(ActivityInternalDataPath())
base := TextFromCString(AndroidInternalDataPath())
if PathJoin(path[:], base, filename) == "" { return null }
mode: [3]u8
unused CopyCString("rb", mode[:])
@@ -152,7 +152,7 @@ DexClass :: (env: *JniEnv, bytes: []u8, length: s32, filename: string, name: str
if !ok { return null }
}
empty := NoArguments()
parent := ObjectCall(env, NativeApp().activity.activity, "getClassLoader", "()Ljava/lang/ClassLoader;", empty[:])
parent := ObjectCall(env, JniGetAndroidApp().activity.activity, "getClassLoader", "()Ljava/lang/ClassLoader;", empty[:])
args: [4]JniValue
args[0] = ArgumentObject(TextObject(env, TextUntilNul(path[:])))
args[1] = ArgumentObject(TextObject(env, base)); args[2] = ArgumentObject(null); args[3] = ArgumentObject(parent)
@@ -167,8 +167,8 @@ UiRun :: (env: *JniEnv, task: *void) {
}
UiInitialize :: () -> bool {
if ui_task != null { return true }
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return false }
env := session.env
bytes: [512]u8
length := DexRunnable(env, bytes[:])
@@ -185,7 +185,7 @@ UiInitialize :: () -> bool {
constructor := env.functions.GetMethodID(env, klass, *ClassConstructorName()[0], *descriptor[0])
if constructor != null { ui_task = env.functions.NewGlobalRef(env, env.functions.NewObjectA(env, klass, constructor, *empty[0])) }
}
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
return ui_task != null
}
constructor_name: [7]u8;
@@ -198,12 +198,12 @@ UiSchedule :: (callback: UiCallback) -> bool {
if ui_pending { UiUnlock(); return false }
ui_pending = true; ui_callback = callback
UiUnlock()
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { UiLock(); ui_pending = false; UiUnlock(); return false }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { UiLock(); ui_pending = false; UiUnlock(); return false }
args: [1]JniValue
args[0] = ArgumentObject(ui_task)
ok := VoidCall(session.env, session.activity, "runOnUiThread", "(Ljava/lang/Runnable;)V", args[:])
activity_jni_detach(*session)
AndroidJniDetachCurrent(*session)
if !ok { UiLock(); ui_pending = false; UiUnlock() }
return ok
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Like UiTask, its only bytecode is a constructor; all behavior is native.
// Identifier tables and map entries follow Android's DEX 035 format.
#import "android"
#import "android_jni"
#import "kryon/android_jni"
Dex :: #import "android_dispatch";
Uleb :: (bytes: []u8, at: *s32, value: u32) {
+5 -5
View File
@@ -1,7 +1,7 @@
// Android document transfers are asynchronous and use the system chooser.
// The chooser grants one URI; bundles see only their private document name.
#import "android"
#import "android_jni"
#import "kryon/android_jni"
#import "android_dispatch"
#import "android_document_dex"
#import "files"
@@ -65,7 +65,7 @@ DocumentOpenUi :: (env: *JniEnv, task: *void) {
fragment := DocumentFragment(env)
if fragment == null { document_state = 5; unused JniOk(env); return }
empty := NoArguments()
activity := NativeApp().activity.activity
activity := JniGetAndroidApp().activity.activity
manager := ObjectCall(env, activity, "getFragmentManager", "()Landroid/app/FragmentManager;", empty[:])
transaction := ObjectCall(env, manager, "beginTransaction", "()Landroid/app/FragmentTransaction;", empty[:])
args: [2]JniValue
@@ -91,9 +91,9 @@ DocumentOpenUi :: (env: *JniEnv, task: *void) {
}
DocumentCopy :: (files: *AppFiles, name: string, save: bool, intent: *void) -> bool {
session: ActivityJniSession
if activity_jni_attach(*session) == 0 { return false }
defer { activity_jni_detach(*session) }
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return false }
defer { AndroidJniDetachCurrent(*session) }
env := session.env
defer { env.functions.DeleteGlobalRef(env, intent) }
empty := NoArguments()
-1
View File
@@ -1,7 +1,6 @@
// Android loads this entry before Entity registers the shared consent natives.
Handoff :: #import "entity/account_handoff";
HandoffJni :: #import "kryon/android_jni";
#program_export
JNI_OnLoad :: (vm: *HandoffJni.JniVm, reserved: *void) -> s32 {
unused reserved
+184
View File
@@ -0,0 +1,184 @@
// NativeActivity's Pixmap renderer borrows decoded pixels. Keep a bounded
// host cache for approved APK assets and local Gallery files, with small
// thumbnails and the original resolution for the viewer.
#import "android"
#import "kryon/android_jni"
#import "kryon/pixmap"
#import "std/c_string"
#import "std/text_buffer"
ImageEntry :: struct { path: [256]u8; pixels: *u32; count: s64; touched: s64 }
images: [96]ImageEntry;
image_clock: s64;
image_pixels: s64;
image_path: [256]u8;
PIXEL_BUDGET :: 48000000
SLOT_BASE :: 512
image_libc :: #system_library "c";
PixelsAllocate :: (count: usize, size: usize) -> *u8 #foreign image_libc "calloc";
PixelsRelease :: (memory: *void) #foreign image_libc "free";
PixelView :: struct { data: *u32; length: s64 }
Pixels :: (pointer: *u32, count: s64) -> []u32 {
result: []u32
view := cast(*PixelView)(*result)
view.data = pointer; view.length = count
return result
}
Orient :: (input: *u32, width: s32, height: s32, orientation: s32) -> *u32 {
if orientation <= 1 || orientation > 8 { return input }
output := cast(*u32)PixelsAllocate(cast(usize)(cast(s64)width * height), 4)
if output == null { PixelsRelease(cast(*void)input); return null }
output_width := ifx orientation >= 5 then height else width
for y: cast(s32)0..height - 1 {
for x: cast(s32)0..width - 1 {
tx := x; ty := y
if orientation == 2 { tx = width - 1 - x }
if orientation == 3 { tx = width - 1 - x; ty = height - 1 - y }
if orientation == 4 { ty = height - 1 - y }
if orientation == 5 { tx = y; ty = x }
if orientation == 6 { tx = height - 1 - y; ty = x }
if orientation == 7 { tx = height - 1 - y; ty = width - 1 - x }
if orientation == 8 { tx = y; ty = width - 1 - x }
output[cast(s64)ty * output_width + tx] = input[cast(s64)y * width + x]
}
}
PixelsRelease(cast(*void)input)
return output
}
Drop :: (at: s32) {
PixmapClearImage(SLOT_BASE + at)
if images[at].pixels != null { PixelsRelease(cast(*void)images[at].pixels) }
image_pixels -= images[at].count
images[at] = .{}
}
Forget :: (path: string) {
for at: cast(s32)0..95 {
matches: bool
{
name := TextUntilNul(images[at].path[:])
matches = name == path || (name.count == path.count + 8 && name[:path.count] == path && name[path.count:] == ".preview")
}
if matches { Drop(at) }
}
}
SetOption :: (env: *JniEnv, options: *void, name: string, value: s32, boolean: bool = false) -> bool {
args: [2]JniValue
args[0] = ArgumentObject(TextObject(env, name))
klass := env.functions.GetObjectClass(env, options)
field := ObjectCall(env, klass, "getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", args[:])
if field == null { return false }
args[0] = ArgumentObject(options); args[1] = ArgumentInteger(value)
if boolean { return VoidCall(env, field, "setBoolean", "(Ljava/lang/Object;Z)V", args[:]) }
return VoidCall(env, field, "setInt", "(Ljava/lang/Object;I)V", args[:])
}
Option :: (env: *JniEnv, options: *void, name: string) -> s32 {
label: [32]u8; signature: [2]u8
if !CopyCString(name, label[:]) || !CopyCString("I", signature[:]) { return 0 }
klass := env.functions.GetObjectClass(env, options)
field := env.functions.GetFieldID(env, klass, *label[0], *signature[0])
if !JniOk(env) || field == null { return 0 }
return env.functions.GetIntField(env, options, field)
}
Decode :: (env: *JniEnv, path: string, options: *void) -> *void {
args: [3]JniValue
args[0] = ArgumentObject(TextObject(env, path))
stream: *void
if path.count > 0 && path[0] == #char "/" {
stream = NewObject(env, "java/io/FileInputStream", "(Ljava/lang/String;)V", args[:])
} else {
empty := NoArguments()
assets := ObjectCall(env, JniGetAndroidApp().activity.activity, "getAssets", "()Landroid/content/res/AssetManager;", empty[:])
stream = ObjectCall(env, assets, "open", "(Ljava/lang/String;)Ljava/io/InputStream;", args[:])
}
if stream == null { return null }
empty := NoArguments()
defer { unused VoidCall(env, stream, "close", "()V", empty[:]) }
args[0] = ArgumentObject(stream); args[1] = ArgumentObject(null); args[2] = ArgumentObject(options)
return StaticCall(env, "android/graphics/BitmapFactory", "decodeStream", "(Ljava/io/InputStream;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;", args[:])
}
// Returns a stable renderer path. Callers retain their own path allowlist.
Prepare :: (path: string, preview: bool = false) -> string {
if path == "" || path.count + 8 >= 256 || !CopyCString(path, image_path[:]) { return path }
if preview {
suffix := ".preview"
for at: 0..7 { image_path[path.count + at] = suffix[at] }
image_path[path.count + 8] = cast(u8)0
}
name := TextUntilNul(image_path[:])
image_clock += 1
for at: cast(s32)0..95 {
if TextUntilNul(images[at].path[:]) == name { images[at].touched = image_clock; return name }
}
session: AndroidJniSession
if AndroidJniAttachCurrent(*session) == 0 { return name }
defer { AndroidJniDetachCurrent(*session) }
env := session.env
empty := NoArguments()
options := NewObject(env, "android/graphics/BitmapFactory$Options", "()V", empty[:])
if options == null || !SetOption(env, options, "inJustDecodeBounds", 1, true) { return name }
unused Decode(env, path, options)
width := Option(env, options, "outWidth"); height := Option(env, options, "outHeight")
if width <= 0 || height <= 0 || cast(s64)width * height > 32000000 { return name }
sample: s32 = 1
if preview { while width / sample > 256 || height / sample > 256 { sample *= 2 } }
if !SetOption(env, options, "inJustDecodeBounds", 0, true) || !SetOption(env, options, "inSampleSize", sample) { return name }
bitmap := Decode(env, path, options)
if bitmap == null { return name }
defer { unused VoidCall(env, bitmap, "recycle", "()V", empty[:]) }
width_method := Method(env, bitmap, "getWidth", "()I", false)
height_method := Method(env, bitmap, "getHeight", "()I", false)
if width_method == null || height_method == null { return name }
width = env.functions.CallIntMethodA(env, bitmap, width_method, *empty[0])
height = env.functions.CallIntMethodA(env, bitmap, height_method, *empty[0])
count := cast(s64)width * height
if width <= 0 || height <= 0 || count > 32000000 || !JniOk(env) { return name }
slot: s32 = -1
while slot < 0 || image_pixels + count > PIXEL_BUDGET {
oldest: s32 = -1
for at: cast(s32)0..95 {
if images[at].pixels != null && (oldest < 0 || images[at].touched < images[oldest].touched) { oldest = at }
if images[at].pixels == null { slot = at }
}
if slot >= 0 && image_pixels + count <= PIXEL_BUDGET { break }
Drop(oldest)
slot = oldest
}
pixels := cast(*u32)PixelsAllocate(cast(usize)count, 4)
if pixels == null { return name }
good := false
defer { if !good { PixelsRelease(cast(*void)pixels) } }
array := env.functions.NewIntArray(env, cast(s32)count)
if !JniOk(env) || array == null { return name }
args: [7]JniValue = .[ArgumentObject(array), ArgumentInteger(0), ArgumentInteger(width), ArgumentInteger(0), ArgumentInteger(0), ArgumentInteger(width), ArgumentInteger(height)]
if !VoidCall(env, bitmap, "getPixels", "([IIIIIII)V", args[:]) { return name }
env.functions.GetIntArrayRegion(env, array, 0, cast(s32)count, cast(*s32)pixels)
if !JniOk(env) { return name }
orientation: s32 = 1
if path.count > 0 && path[0] == #char "/" {
exif_args: [2]JniValue
exif_args[0] = ArgumentObject(TextObject(env, path))
exif := NewObject(env, "android/media/ExifInterface", "(Ljava/lang/String;)V", exif_args[:])
if exif != null {
exif_args[0] = ArgumentObject(TextObject(env, "Orientation")); exif_args[1] = ArgumentInteger(1)
method := Method(env, exif, "getAttributeInt", "(Ljava/lang/String;I)I", false)
if method != null { orientation = env.functions.CallIntMethodA(env, exif, method, *exif_args[0]) }
unused JniOk(env)
}
}
pixels = Orient(pixels, width, height, orientation)
if pixels == null { good = true; return name }
if orientation >= 5 && orientation <= 8 { swap := width; width = height; height = swap }
if !PixmapSetImage(SLOT_BASE + slot, name, width, height, Pixels(pixels, count)) { return name }
unused CopyCString(name, images[slot].path[:])
images[slot].pixels = pixels; images[slot].count = count; images[slot].touched = image_clock
image_pixels += count; good = true
return name
}
+34 -6
View File
@@ -2,7 +2,7 @@
// Kryon continues to own the visible fields and editing decisions. All view
// access runs on Android's UI thread through the generated native Runnable.
#import "android"
#import "android_jni"
#import "kryon/android_jni"
#import "android_dispatch"
#import "std/c_string"
#import "std/text_buffer"
@@ -26,6 +26,25 @@ input_dirty: bool;
selection_dirty: bool;
input_available: bool;
input_secure: bool;
native_input: AndroidInputHandler;
editor_android :: #system_library "android";
EditorEventType :: (event: *void) -> s32 #foreign editor_android "AInputEvent_getType";
EditorKeyCode :: (event: *void) -> s32 #foreign editor_android "AKeyEvent_getKeyCode";
// NativeActivity offers hardware keys to its native queue before the focused
// framework view. While EditText owns editing, leave those keys unhandled so
// Android delivers letters, selection and deletion to that same editor.
// Back and all pointer events retain Kryon's navigation and touch handling.
AndroidEditorInput :: (app: *void, event: *void) -> s32 {
if event != null && EditorEventType(event) == 1 && EditorKeyCode(event) != 4 {
UiLock()
editing := input_field >= 0 && input_field == requested_field
UiUnlock()
if editing { return 0 }
}
if native_input != null { return native_input(app, event) }
return 0
}
IntegerCall :: (env: *JniEnv, object: *void, name: string, signature: string, arguments: []JniValue) -> s32 {
method := Method(env, object, name, signature, false)
@@ -52,7 +71,7 @@ Utf8Position :: (value: string, units: s32) -> s32 {
}
UiInputCreate :: (env: *JniEnv) -> bool {
args: [2]JniValue
args[0] = ArgumentObject(NativeApp().activity.activity)
args[0] = ArgumentObject(JniGetAndroidApp().activity.activity)
view := NewObject(env, "android/widget/EditText", "(Landroid/content/Context;)V", args[:])
if view == null { return false }
input_view = env.functions.NewGlobalRef(env, view)
@@ -68,7 +87,7 @@ UiInputCreate :: (env: *JniEnv) -> bool {
args[0] = ArgumentInteger(1); args[1] = ArgumentInteger(1)
layout := NewObject(env, "android/widget/FrameLayout$LayoutParams", "(II)V", args[:])
empty := NoArguments()
window := ObjectCall(env, NativeApp().activity.activity, "getWindow", "()Landroid/view/Window;", empty[:])
window := ObjectCall(env, JniGetAndroidApp().activity.activity, "getWindow", "()Landroid/view/Window;", empty[:])
decor := ObjectCall(env, window, "getDecorView", "()Landroid/view/View;", empty[:])
args[0] = ArgumentObject(view); args[1] = ArgumentObject(layout)
return VoidCall(env, decor, "addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", args[:])
@@ -104,8 +123,8 @@ UiInputSync :: (env: *JniEnv, task: *void) {
}
if changed {
BoolCall(env, input_view, "requestFocus", "()Z", empty[:])
session: ActivityJniSession
session.env = env; session.activity = NativeApp().activity.activity
session: AndroidJniSession
session.env = env; session.activity = JniGetAndroidApp().activity.activity
manager := Service(*session, "input_method")
args[0] = ArgumentObject(input_view); args[1] = ArgumentInteger(0)
BoolCall(env, manager, "showSoftInput", "(Landroid/view/View;I)Z", args[:])
@@ -128,6 +147,11 @@ UiInputSync :: (env: *JniEnv, task: *void) {
}
AndroidTextInitialize :: () -> bool {
input_available = UiInitialize()
app := JniGetAndroidApp()
if input_available && app != null {
native_input = app.input_callback
app.input_callback = AndroidEditorInput
}
return input_available
}
AndroidTextRead :: (id: s32, output: []u8) -> AndroidTextSelection {
@@ -156,6 +180,10 @@ AndroidTextSubmit :: (id: s32, value: string, cursor: s32, anchor: s32, secure:
}
AndroidTextHide :: () {
if !input_available { return }
UiLock(); requested_field = -1; requested_value = .{}; UiUnlock()
UiLock()
active := input_field >= 0 || requested_field >= 0
requested_field = -1; requested_value = .{}
UiUnlock()
if !active { return }
UiSchedule(UiInputSync)
}
-309
View File
@@ -1,309 +0,0 @@
// JNI uses a stable, indexed function table. These declarations mirror the
// Android NDK JNI 1.6 ABI; calls use the A variants with explicit jvalue arrays.
#import "c_string"
// jvalue occupies one eight-byte slot on every Android ABI. Android's
// supported ABIs are little endian, so references and 32-bit scalars occupy
// the low bits without requiring a pointer-containing source union.
JniValue :: struct {
bits: u64
}
#assert size_of(JniValue) == 8
JniEnv :: struct {
functions: *JniFunctions
}
JniVm :: struct {
functions: *JniVmFunctions
}
JniFindClassFn :: #type (*JniEnv, *u8) -> *void #c_call;
JniExceptionDescribeFn :: #type (*JniEnv) -> void #c_call;
JniExceptionClearFn :: #type (*JniEnv) -> void #c_call;
JniPushLocalFrameFn :: #type (*JniEnv, s32) -> s32 #c_call;
JniPopLocalFrameFn :: #type (*JniEnv, *void) -> *void #c_call;
JniNewGlobalRefFn :: #type (*JniEnv, *void) -> *void #c_call;
JniDeleteGlobalRefFn :: #type (*JniEnv, *void) -> void #c_call;
JniDeleteLocalRefFn :: #type (*JniEnv, *void) -> void #c_call;
JniGetObjectClassFn :: #type (*JniEnv, *void) -> *void #c_call;
JniGetMethodIDFn :: #type (*JniEnv, *void, *u8, *u8) -> *void #c_call;
JniCallObjectMethodAFn :: #type (*JniEnv, *void, *void, *JniValue) -> *void #c_call;
JniCallBooleanMethodAFn :: #type (*JniEnv, *void, *void, *JniValue) -> u8 #c_call;
JniCallIntMethodAFn :: #type (*JniEnv, *void, *void, *JniValue) -> s32 #c_call;
JniCallVoidMethodAFn :: #type (*JniEnv, *void, *void, *JniValue) -> void #c_call;
JniGetStaticMethodIDFn :: #type (*JniEnv, *void, *u8, *u8) -> *void #c_call;
JniCallStaticVoidMethodAFn :: #type (*JniEnv, *void, *void, *JniValue) -> void #c_call;
JniNewStringUTFFn :: #type (*JniEnv, *u8) -> *void #c_call;
JniNewStringFn :: #type (*JniEnv, *u16, s32) -> *void #c_call;
JniStringLengthFn :: #type (*JniEnv, *void) -> s32 #c_call;
JniStringCharsFn :: #type (*JniEnv, *void, *u8) -> *u16 #c_call;
JniReleaseStringCharsFn :: #type (*JniEnv, *void, *u16) -> void #c_call;
JniGetStringUTFCharsFn :: #type (*JniEnv, *void, *u8) -> *u8 #c_call;
JniReleaseStringUTFCharsFn :: #type (*JniEnv, *void, *u8) -> void #c_call;
JniGetArrayLengthFn :: #type (*JniEnv, *void) -> s32 #c_call;
JniGetObjectArrayElementFn :: #type (*JniEnv, *void, s32) -> *void #c_call;
JniNewByteArrayFn :: #type (*JniEnv, s32) -> *void #c_call;
JniGetByteArrayRegionFn :: #type (*JniEnv, *void, s32, s32, *u8) -> void #c_call;
JniSetByteArrayRegionFn :: #type (*JniEnv, *void, s32, s32, *u8) -> void #c_call;
JniRegisterNativesFn :: #type (*JniEnv, *void, *void, s32) -> s32 #c_call;
JniGetJavaVMFn :: #type (*JniEnv, **JniVm) -> s32 #c_call;
JniExceptionCheckFn :: #type (*JniEnv) -> u8 #c_call;
JniNewObjectAFn :: #type (*JniEnv, *void, *void, *JniValue) -> *void #c_call;
JniCallStaticObjectMethodAFn :: #type (*JniEnv, *void, *void, *JniValue) -> *void #c_call;
JniGetStaticFieldIDFn :: #type (*JniEnv, *void, *u8, *u8) -> *void #c_call;
JniGetStaticObjectFieldFn :: #type (*JniEnv, *void, *void) -> *void #c_call;
JniGetStaticIntFieldFn :: #type (*JniEnv, *void, *void) -> s32 #c_call;
JniGetFieldIDFn :: #type (*JniEnv, *void, *u8, *u8) -> *void #c_call;
JniGetIntFieldFn :: #type (*JniEnv, *void, *void) -> s32 #c_call;
JniFunctions :: struct {
reserved_0: [6]*void
FindClass: JniFindClassFn
reserved_7: [9]*void
ExceptionDescribe: JniExceptionDescribeFn
ExceptionClear: JniExceptionClearFn
reserved_18: [1]*void
PushLocalFrame: JniPushLocalFrameFn
PopLocalFrame: JniPopLocalFrameFn
NewGlobalRef: JniNewGlobalRefFn
DeleteGlobalRef: JniDeleteGlobalRefFn
DeleteLocalRef: JniDeleteLocalRefFn
reserved_24: [6]*void
NewObjectA: JniNewObjectAFn
GetObjectClass: JniGetObjectClassFn
reserved_32: [1]*void
GetMethodID: JniGetMethodIDFn
reserved_34: [2]*void
CallObjectMethodA: JniCallObjectMethodAFn
reserved_37: [2]*void
CallBooleanMethodA: JniCallBooleanMethodAFn
reserved_40: [11]*void
CallIntMethodA: JniCallIntMethodAFn
reserved_52: [11]*void
CallVoidMethodA: JniCallVoidMethodAFn
reserved_64: [30]*void
GetFieldID: JniGetFieldIDFn
reserved_95: [5]*void
GetIntField: JniGetIntFieldFn
reserved_101: [12]*void
GetStaticMethodID: JniGetStaticMethodIDFn
reserved_114: [2]*void
CallStaticObjectMethodA: JniCallStaticObjectMethodAFn
reserved_117: [26]*void
CallStaticVoidMethodA: JniCallStaticVoidMethodAFn
GetStaticFieldID: JniGetStaticFieldIDFn
GetStaticObjectField: JniGetStaticObjectFieldFn
reserved_146: [4]*void
GetStaticIntField: JniGetStaticIntFieldFn
reserved_151: [12]*void
NewString: JniNewStringFn
GetStringLength: JniStringLengthFn
GetStringChars: JniStringCharsFn
ReleaseStringChars: JniReleaseStringCharsFn
NewStringUTF: JniNewStringUTFFn
reserved_168: [1]*void
GetStringUTFChars: JniGetStringUTFCharsFn
ReleaseStringUTFChars: JniReleaseStringUTFCharsFn
GetArrayLength: JniGetArrayLengthFn
reserved_172: [1]*void
GetObjectArrayElement: JniGetObjectArrayElementFn
reserved_174: [2]*void
NewByteArray: JniNewByteArrayFn
reserved_177: [23]*void
GetByteArrayRegion: JniGetByteArrayRegionFn
reserved_201: [7]*void
SetByteArrayRegion: JniSetByteArrayRegionFn
reserved_209: [6]*void
RegisterNatives: JniRegisterNativesFn
reserved_216: [3]*void
GetJavaVM: JniGetJavaVMFn
reserved_220: [8]*void
ExceptionCheck: JniExceptionCheckFn
}
JniAttachFn :: #type (*JniVm, **JniEnv, *void) -> s32 #c_call;
JniDetachFn :: #type (*JniVm) -> s32 #c_call;
JniGetEnvFn :: #type (*JniVm, **JniEnv, s32) -> s32 #c_call;
JniVmFunctions :: struct {
reserved: [4]*void
AttachCurrentThread: JniAttachFn
DetachCurrentThread: JniDetachFn
GetEnv: JniGetEnvFn
}
NativeActivity :: struct {
callbacks: *void
vm: *JniVm
env: *JniEnv
activity: *void
internal_data_path: *u8
external_data_path: *u8
}
NativeAndroidApp :: struct {
userdata: *void
command_callback: *void
input_callback: *void
activity: *NativeActivity
}
ActivityJniSession :: struct {
vm: *JniVm
env: *JniEnv
activity: *void
attached: s32
}
#if #defined(ANDROID_BUILD) || #defined(PLATFORM_ANDROID) || #defined(__ANDROID__) {
raylib :: #system_library "raylib";
JniGetAndroidApp :: () -> *NativeAndroidApp #foreign raylib "GetAndroidApp";
}
JniVersion :: 0x00010006
JniAttach :: (session: *ActivityJniSession, vm: *JniVm,
activity: *void) -> bool {
if session == null || vm == null || activity == null {
return false
}
session.vm = vm
session.activity = activity
session.env = null
session.attached = 0
result := vm.functions.GetEnv(vm, *session.env, JniVersion)
if result == -2 {
if vm.functions.AttachCurrentThread(vm, *session.env, null) != 0 ||
session.env == null {
return false
}
session.attached = 1
} else if result != 0 || session.env == null {
return false
}
if session.env.functions.PushLocalFrame(session.env, 32) != 0 {
if session.env.functions.ExceptionCheck(session.env) != 0 {
session.env.functions.ExceptionDescribe(session.env)
session.env.functions.ExceptionClear(session.env)
}
if session.attached != 0 {
vm.functions.DetachCurrentThread(vm)
}
session.vm = null
session.env = null
session.activity = null
session.attached = 0
return false
}
return true
}
#program_export
activity_jni_attach :: (session: *ActivityJniSession) -> s32 {
if session == null {
return 0
}
session.vm = null
session.env = null
session.activity = null
session.attached = 0
#if #defined(ANDROID_BUILD) || #defined(PLATFORM_ANDROID) || #defined(__ANDROID__) {
app := JniGetAndroidApp()
if app == null || app.activity == null {
return 0
}
if JniAttach(session, app.activity.vm, app.activity.activity) {
return 1
}
}
return 0
}
#program_export
activity_jni_detach :: (session: *ActivityJniSession) {
if session == null || session.env == null {
return
}
env := session.env
if env.functions.ExceptionCheck(env) != 0 {
env.functions.ExceptionDescribe(env)
env.functions.ExceptionClear(env)
}
env.functions.PopLocalFrame(env, null)
if session.attached != 0 {
session.vm.functions.DetachCurrentThread(session.vm)
}
session.vm = null
session.env = null
session.activity = null
session.attached = 0
}
JniMethod :: (session: *ActivityJniSession, name: string,
signature: string) -> *void {
env := session.env
klass := env.functions.GetObjectClass(env, session.activity)
if klass == null {
return null
}
method_name: [96]u8
method_signature: [192]u8
if !CopyCString(name, method_name[:]) ||
!CopyCString(signature, method_signature[:]) {
return null
}
return env.functions.GetMethodID(env, klass, *method_name[0],
*method_signature[0])
}
JniString :: (env: *JniEnv, value: *u8) -> *void {
empty: [1]u8
if value == null {
value = *empty[0]
}
return env.functions.NewStringUTF(env, value)
}
JniCallVoid :: (session: *ActivityJniSession, name: string,
text: *u8) -> bool {
signature := "()V"
if text != null {
signature = "(Ljava/lang/String;)V"
}
method := JniMethod(session, name, signature)
if method == null {
return false
}
env := session.env
arguments: [1]JniValue
if text != null {
arguments[0].bits = cast(u64)cast(usize)JniString(env, text)
if arguments[0].bits == cast(u64)0 {
return false
}
}
env.functions.CallVoidMethodA(env, session.activity, method,
*arguments[0])
return env.functions.ExceptionCheck(env) == 0
}
ActivityInternalDataPath :: () -> *u8 {
#if #defined(ANDROID_BUILD) || #defined(PLATFORM_ANDROID) || #defined(__ANDROID__) {
app := JniGetAndroidApp()
if app != null && app.activity != null {
return app.activity.internal_data_path
}
}
return null
}
NativeApp :: () -> *NativeAndroidApp {
#if #defined(ANDROID_BUILD) {
return JniGetAndroidApp()
}
return null
}
+42 -134
View File
@@ -1,151 +1,59 @@
// Kryon owns NativeActivity lifecycle, touch input and software presentation.
#import "kryon/android_run"
#import "kryon/session"
#import "kryon/android_jni"
#import "kryon/geometry"
#import "kryon/android_device"
#import "kryon/android_surface"
#import "werk"
#import "apps"
#import "profile"
#import "platform"
#import "android"
#import "android_input"
#import "android_fields"
#import "std/c_string"
#import "AndroidSurface"
#import "AndroidDevice"
Render :: #import "Raylib";
using UI :: #import "Widgets";
#import "Frame"
#import "android_glue";
#import "android_glue"
raylib :: #system_library "raylib";
InitWindow :: (width: s32, height: s32, title: *u8) #foreign raylib "InitWindow";
IsWindowReady :: () -> bool #foreign raylib "IsWindowReady";
SetTargetFPS :: (fps: s32) #foreign raylib "SetTargetFPS";
log_library :: #system_library "log";
WriteLog :: (priority: s32, tag: *u8, message: *u8) -> s32 #foreign log_library "__android_log_write";
android_started: bool;
android_configuration :: #system_library "android";
ConfigurationDensity :: (configuration: *void) -> s32 #foreign android_configuration "AConfiguration_getDensity";
Report :: (message: string) {
tag: [16]u8
text: [128]u8
if CopyCString("Werkzeug", tag[:]) && CopyCString(message, text[:]) {
unused WriteLog(6, *tag[0], *text[0])
}
// Werkzeug's framework editor owns soft-input visibility for its fields.
#program_export
SetPlatformTextKeyboardVisible :: (session: Session, visible: bool) {
unused session
AndroidKeyboard(visible || WerkKeyboard())
}
// The NDK glue creates the rendering thread. Kryon's owned parser values
// need more room than Android's small default pthread stack.
libc :: #system_library "libc";
AttributeInit :: #type (*void) -> s32 #c_call;
RealAttributesInit :: (attributes: *void) -> s32 #foreign libc "__real_pthread_attr_init";
SetThreadStack :: (attributes: *void, size: usize) -> s32 #foreign libc "pthread_attr_setstacksize";
#program_export "__wrap_pthread_attr_init"
NativeThreadAttributes :: (attributes: *void) -> s32 {
status := RealAttributesInit(attributes)
if status != 0 {
return status
#program_export "ProjectFrame"
WerkAndroidFrame :: (session: Session, viewport: Rectangle) -> s32 {
if !android_started {
if !AndroidInitialize() || !AndroidTextInitialize() { return 1 }
SetAndroidViewportPolicy(AndroidViewportPolicyResizeForIme())
app := JniGetAndroidApp()
if app != null && app.configuration != null {
density := ConfigurationDensity(app.configuration)
if density > 0 && density < 65534 {
AndroidNativeSetDensity(null, null, cast(float32)density / 160.0)
}
}
WerkStart()
android_started = true
}
return SetThreadStack(attributes, cast(usize)16777216)
}
WerkAndroidFrame :: struct { session: Session; ok: bool }
ComposeAndroidFrame :: (argument: *void) {
frame := cast(*WerkAndroidFrame)argument
session := frame.session
ok := true
width: s32
height: s32
SyncAndroidSurfaceSize(*width, *height)
// Keeps the app clear of the navigation bar and the keyboard.
PollAndroidWindowInsets()
zoom := cast(float32)width / 390.0
if zoom < 1.0 {
zoom = 1.0
}
Render.RaylibSetZoom(zoom)
viewport: AndroidViewport
ResolveAndroidViewport(width, height, AndroidViewportPolicyResizeForIme(), *viewport)
bounds := Rectangle.{cast(float32)viewport.x / zoom, cast(float32)viewport.y / zoom,
cast(float32)viewport.width / zoom, cast(float32)viewport.height / zoom}
KeyboardModifiersSend(session, Render.RaylibModifiers())
key := Render.RaylibPressedKey()
if key != 0 {
KeyboardSend(session, key)
}
codepoint := Render.RaylibTypedCodepoint()
while codepoint != 0 {
TypedCodepointSend(session, codepoint)
codepoint = Render.RaylibTypedCodepoint()
}
Render.BeginRaylibFrame()
ClearAndroidFrame(viewport, ThemePalette().background, zoom)
pointer := Render.PollPointer()
TreePointerUpdate(session, pointer)
TreeSecondaryPointerUpdate(session, Render.PollSecondaryPointer())
PointerWheelSend(session, pointer.x, pointer.y, Render.RaylibWheelMove())
AndroidFieldsBegin()
ok = BeginFrame(session, cast(u64)1, bounds) == FrameStatus.FrameOk
if !ok {
Report("Could not begin frame")
}
if ok {
ok = WerkFrame(session, bounds) == 0
if !ok {
Report("Could not compose frame")
}
}
if ok {
ok = EndFrame(session) == FrameStatus.FrameOk
if !ok {
Report("Could not commit frame")
}
}
status := WerkFrame(session, viewport)
AndroidFieldsEnd()
ShowKeyboard(WerkKeyboard())
ok = Render.EndRaylibFrame() && ok
if !ok {
Report("Could not present frame")
}
frame.ok = ok
AndroidKeyboard(WerkKeyboard())
return status
}
#program_export
main :: () -> s32 {
thread_adapter: AttributeInit = NativeThreadAttributes
unused thread_adapter
title: [16]u8
unused CopyCString("Werkzeug", title[:])
InitWindow(0, 0, *title[0])
if !IsWindowReady() {
return 1
}
if !AndroidInitialize() || !AndroidTextInitialize() {
Render.CloseRaylib()
return 1
}
SetTargetFPS(60)
// Android's own interface font where Android names it (Android 10 and
// newer), otherwise the Noto Sans that Inbe uses, from the APK.
font := Render.LoadSystemTypeface("sans-serif") ||
Render.LoadTypefaceFile("sans-serif", "fonts/ui.ttf", null, 0)
if !font || !Render.SelectTypeface("sans-serif") {
Report("Could not load a font")
}
SetAndroidViewportPolicy(AndroidViewportPolicyResizeForIme())
session := SessionOpen()
if !SessionValid(session) {
Render.CloseRaylib()
return 1
}
WerkStart()
ok: bool = true
while ok && Render.PollRaylib() {
frame := WerkAndroidFrame.{.session = session}
ok = Render.RunRaylibAppFrame(ComposeAndroidFrame, cast(*void)*frame) && frame.ok
}
Render.CloseRaylibAppFrames()
ok = SaveApps() && ok
ShowKeyboard(false)
CloseSession(session)
Render.CloseRaylib()
if ok {
return 0
}
return 1
main :: () -> s32 { return AndroidRunMain() }
// Retain the existing save-on-exit behavior around Kryon's lifecycle owner.
android_entry :: #system_library "android_entry";
AndroidMain :: (app: *NativeAndroidApp) #foreign android_entry "__real_android_main";
#program_export "__wrap_android_main"
WerkAndroidMain :: (app: *NativeAndroidApp) {
AndroidMain(app)
if android_started { unused SaveApps() }
}
+9 -1
View File
@@ -36,6 +36,7 @@ TextField :: #import "kryon/text_field";
#if #defined(ANDROID_BUILD) {
#import "android_fields"
#import "android_documents"
AndroidImages :: #import "android_images";
}
Spreadsheet :: #import "workbook/service";
@@ -476,6 +477,13 @@ AppCall :: (context: *void, module: *u8, function: *u8,
}
// Images an app draws come from its own unpacked assets.
AppAssetResolve :: (path: string) -> string {
#if #defined(ANDROID_BUILD) {
unused AndroidImages.Prepare(path)
}
return path
}
AssetAllowed :: (path: string) -> bool {
// Widgets without an image ask with an empty path.
if path == "" {
@@ -644,7 +652,7 @@ RunApp :: (index: s32, view: AppView) -> bool {
app.portable.area_input.composition_event = view.input.composition_event
app.portable.area_input.now_seconds = SteadyClock()
running = index
WidgetHostBegin(view.session, AssetAllowed)
WidgetHostBegin(view.session, AssetAllowed, AppAssetResolve)
ran := AppContextRun(*app.portable, APP_FRAME)
app_keyboard = app.portable.keyboard
WidgetHostEnd()
+8 -1
View File
@@ -1,3 +1,6 @@
#if #defined(ANDROID_BUILD) {
HomeRaster :: #import "android_images";
}
TextField :: #import "kryon/text_field";
Image :: #import "kryon/image";
Button :: #import "kryon/button";
@@ -274,7 +277,11 @@ HomeAssetResolve :: (path: string) -> string {
name: [96]u8
file := HomeArtwork(tool, name[:])
// The host's own file, without the portable assets/ prefix.
return AssetPath(home_artwork_files[tool][:], file[7:file.count])
resolved := AssetPath(home_artwork_files[tool][:], file[7:file.count])
#if #defined(ANDROID_BUILD) {
unused HomeRaster.Prepare(resolved)
}
return resolved
}
HomeCards :: (context: *void, indices: []s32, bounds: Rectangle,
+22 -10
View File
@@ -14,10 +14,16 @@
#if #defined(ANDROID_BUILD) {
#import "android"
#import "android_jni"
#import "kryon/android_jni"
#import "android_input"
raylib_files :: #system_library "raylib";
LoadFileData :: (name: *u8, size: *s32) -> *u8 #foreign raylib_files "LoadFileData";
apk_files :: #system_library "c";
ApkFileOpen :: (name: *u8, mode: *u8) -> *void #foreign apk_files "fopen";
ApkFileSeek :: (file: *void, offset: isize, whence: s32) -> s32 #foreign apk_files "fseek";
ApkFileTell :: (file: *void) -> isize #foreign apk_files "ftell";
ApkFileRead :: (data: *u8, size: usize, count: usize, file: *void) -> usize #foreign apk_files "fread";
ApkFileClose :: (file: *void) -> s32 #foreign apk_files "fclose";
ApkAllocate :: (size: usize) -> *u8 #foreign apk_files "malloc";
ApkRelease :: (data: *u8) #foreign apk_files "free";
} else #if #defined(PLATFORM_WEB) {
#import "browser_storage"
} else {
@@ -70,7 +76,7 @@ UserRoot :: (output: []u8, variable: string, fallback: string) -> string {
DataRoot :: () -> string {
if data_root[0] == cast(u8)0 {
#if #defined(ANDROID_BUILD) {
internal := ActivityInternalDataPath()
internal := AndroidInternalDataPath()
if internal != null {
// Android aliases /data/user/0 and /data/data. Resolve the
// trusted activity root before enforcing private file paths.
@@ -175,12 +181,18 @@ ProfilePicturesPath :: () -> string {
ReadBundle :: (path: string) -> (bytes: string, found: bool) {
#if #defined(ANDROID_BUILD) {
name: [PATH_LIMIT]u8
size: s32 = 0
if !CopyCString(path, name[:]) {
return "", false
}
data := LoadFileData(*name[0], *size)
if data == null || size <= 0 {
if !CopyCString(path, name[:]) { return "", false }
mode: [3]u8 = .[cast(u8)114, cast(u8)98, 0]
file := ApkFileOpen(*name[0], *mode[0])
if file == null { return "", false }
defer { unused ApkFileClose(file) }
if ApkFileSeek(file, 0, 2) != 0 { return "", false }
size := ApkFileTell(file)
if size <= 0 || size > 67108864 || ApkFileSeek(file, 0, 0) != 0 { return "", false }
data := ApkAllocate(cast(usize)size)
if data == null { return "", false }
if ApkFileRead(data, 1, cast(usize)size, file) != cast(usize)size {
ApkRelease(data)
return "", false
}
return TextFromBytes(BytesFromPointer(data, cast(u64)size)), true
+9
View File
@@ -1,3 +1,6 @@
#if #defined(ANDROID_BUILD) {
ProfileRaster :: #import "android_images";
}
Image :: #import "kryon/image";
#import "kryon/geometry"
// The Werkzeug profile: a name and picture, and the appearance every app
@@ -263,6 +266,9 @@ SaveProfile :: () -> bool {
PictureImage :: (picture: s32, bounds: Rectangle) -> Image.Props {
image: Image.Props
image.asset_path = ProfilePicturesPath()
#if #defined(ANDROID_BUILD) {
unused ProfileRaster.Prepare(image.asset_path)
}
image.alt_text = "Profile picture"
image.bounds = bounds
image.source = Rectangle.{cast(float32)((picture % 5) * 64), cast(float32)((picture / 5) * 64), 64.0, 64.0}
@@ -287,6 +293,9 @@ ProfileImage :: (bounds: Rectangle) -> Image.Props {
asset := ProfileEntity.EntityAbstractPictureAsset(Clamp(profile.abstract_picture, 0, 2))
path := PathJoin(abstract_picture_path[:], folder, asset)
if path != "" && PathExists(path) {
#if #defined(ANDROID_BUILD) {
unused ProfileRaster.Prepare(path)
}
image: Image.Props
image.asset_path = path
image.alt_text = "Profile picture"