diff --git a/android/.gitignore b/android/.gitignore
index c6f6a0ab..a769cf7e 100644
--- a/android/.gitignore
+++ b/android/.gitignore
@@ -1,6 +1,7 @@
zig-cache
*.apk
*.keystore
+.vscode
.build_config
zig-out
*.apk.idsig
diff --git a/android/LICENCE b/android/LICENCE
new file mode 100644
index 00000000..fe2f6f59
--- /dev/null
+++ b/android/LICENCE
@@ -0,0 +1,7 @@
+Copyright (c) 2020 Felix "xq" Queißner
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/android/README.md b/android/README.md
index 7873863b..82e23cd5 100644
--- a/android/README.md
+++ b/android/README.md
@@ -47,8 +47,13 @@ There are convenience options with `zig build push` (installs the app on a conne
Install the [`sdkmanager`](https://developer.android.com/studio/command-line/sdkmanager) and invoke the following command line:
```
-sdkmanager --install "platforms;android-21" # Min version: Android 5
-sdkmanager --install "build-tools;33.0.0"
+# Android Platforms for your target Android version
+# Min version: Android 5
+sdkmanager --install "platforms;android-21"
+# you can install other versions as well
+# remember to set it like `zig build -Dandroid=android99`
+
+sdkmanager --install "build-tools;33.0.1"
sdkmanager --install "ndk;25.1.8937393"
zig build keystore install run
```
diff --git a/android/Sdk.zig b/android/Sdk.zig
index eb654497..998db6b1 100644
--- a/android/Sdk.zig
+++ b/android/Sdk.zig
@@ -45,6 +45,13 @@ folders: UserConfig,
versions: ToolchainVersions,
+launch_using: ADBLaunchMethod = .monkey,
+
+pub const ADBLaunchMethod = enum {
+ monkey,
+ am,
+};
+
/// Initializes the android SDK.
/// It requires some input on which versions of the tool chains should be used
pub fn init(b: *Builder, user_config: ?UserConfig, toolchains: ToolchainVersions) *Sdk {
@@ -55,7 +62,13 @@ pub fn init(b: *Builder, user_config: ?UserConfig, toolchains: ToolchainVersions
const zipalign = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", toolchains.build_tools_version, "zipalign" ++ exe }) catch unreachable;
const aapt = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", toolchains.build_tools_version, "aapt" ++ exe }) catch unreachable;
- const adb = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "platform-tools", "adb" ++ exe }) catch unreachable;
+ const adb = blk1: {
+ const adb_sdk = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "platform-tools", "adb" ++ exe }) catch unreachable;
+ if (!auto_detect.fileExists(adb_sdk)) {
+ break :blk1 auto_detect.findProgramPath(b.allocator, "adb") orelse @panic("No adb found");
+ }
+ break :blk1 adb_sdk;
+ };
const apksigner = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", toolchains.build_tools_version, "apksigner" ++ exe }) catch unreachable;
const keytool = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.java_home, "bin", "keytool" ++ exe }) catch unreachable;
@@ -96,7 +109,7 @@ pub fn init(b: *Builder, user_config: ?UserConfig, toolchains: ToolchainVersions
}
pub const ToolchainVersions = struct {
- build_tools_version: []const u8 = "33.0.0",
+ build_tools_version: []const u8 = "33.0.1",
ndk_version: []const u8 = "25.1.8937393",
};
@@ -194,8 +207,6 @@ pub const AppConfig = struct {
},
libraries: []const []const u8 = &app_libs,
-
- packages: []const std.build.Pkg = &.{},
};
/// One of the legal targets android can be built for.
@@ -448,9 +459,6 @@ pub fn createApp(
\\
, .{perm}) catch unreachable;
}
- writer.print(
- \\
- , .{ @enumToInt(app_config.target_version) }) catch unreachable;
if (app_config.fullscreen) {
writer.writeAll(
@@ -748,9 +756,6 @@ pub fn compileAppLibrary(
for (app_config.libraries) |lib| {
exe.linkSystemLibraryName(lib);
}
- for (app_config.packages) |package| {
- exe.addPackage(package);
- }
exe.setBuildMode(mode);
@@ -924,14 +929,25 @@ pub fn installApp(sdk: Sdk, apk_file: std.build.FileSource) *Step {
}
pub fn startApp(sdk: Sdk, package_name: []const u8) *Step {
- const step = sdk.b.addSystemCommand(&[_][]const u8{
- sdk.system_tools.adb,
- "shell",
- "am",
- "start",
- "-n",
- sdk.b.fmt("{s}/android.app.NativeActivity", .{package_name}),
- });
+ const command: []const []const u8 = switch (sdk.launch_using) {
+ .am => &.{
+ sdk.system_tools.adb,
+ "shell",
+ "am",
+ "start",
+ "-n",
+ sdk.b.fmt("{s}/android.app.NativeActivity", .{package_name}),
+ },
+ .monkey => &.{
+ sdk.system_tools.adb,
+ "shell",
+ "monkey",
+ "-p",
+ package_name,
+ "1",
+ },
+ };
+ const step = sdk.b.addSystemCommand(command);
return &step.step;
}
@@ -946,28 +962,33 @@ pub const KeyConfig = struct {
/// A build step that initializes a new key store from the given configuration.
/// `android_config.key_store` must be non-`null` as it is used to initialize the key store.
pub fn initKeystore(sdk: Sdk, key_store: KeyStore, key_config: KeyConfig) *Step {
- const step = sdk.b.addSystemCommand(&[_][]const u8{
- sdk.system_tools.keytool,
- "-genkey",
- "-v",
- "-keystore",
- key_store.file,
- "-alias",
- key_store.alias,
- "-keyalg",
- @tagName(key_config.key_algorithm),
- "-keysize",
- sdk.b.fmt("{d}", .{key_config.key_size}),
- "-validity",
- sdk.b.fmt("{d}", .{key_config.validity}),
- "-storepass",
- key_store.password,
- "-keypass",
- key_store.password,
- "-dname",
- key_config.distinguished_name,
- });
- return &step.step;
+ if (auto_detect.fileExists(key_store.file)) {
+ std.log.warn("keystore already exists: {s}", .{key_store.file});
+ return sdk.b.step("init_keystore_noop", "Do nothing, since key exists");
+ } else {
+ const step = sdk.b.addSystemCommand(&[_][]const u8{
+ sdk.system_tools.keytool,
+ "-genkey",
+ "-v",
+ "-keystore",
+ key_store.file,
+ "-alias",
+ key_store.alias,
+ "-keyalg",
+ @tagName(key_config.key_algorithm),
+ "-keysize",
+ sdk.b.fmt("{d}", .{key_config.key_size}),
+ "-validity",
+ sdk.b.fmt("{d}", .{key_config.validity}),
+ "-storepass",
+ key_store.password,
+ "-keypass",
+ key_store.password,
+ "-dname",
+ key_config.distinguished_name,
+ });
+ return &step.step;
+ }
}
const Builder = std.build.Builder;
@@ -1008,9 +1029,7 @@ const zig_targets = struct {
};
};
-const app_libs = [_][]const u8{
- "GLESv2", "EGL", "android", "log", "aaudio"
-};
+const app_libs = [_][]const u8{ "GLESv2", "EGL", "android", "log", "aaudio" };
const BuildOptionStep = struct {
const Self = @This();
diff --git a/android/build.zig b/android/build.zig
index a613ebb5..39724df6 100644
--- a/android/build.zig
+++ b/android/build.zig
@@ -49,7 +49,7 @@ pub fn build(b: *std.build.Builder) !void {
// This is a set of resources. It should at least contain a "mipmap/icon.png" resource that
// will provide the application icon.
.resources = &[_]Sdk.Resource{
- .{ .path = "mipmap/icon.png", .content = .{ .path = "example/icon.png" } },
+ .{ .path = "mipmap/icon.png", .content = .{ .path = "examples/icon.png" } },
},
.aaudio = aaudio,
@@ -66,9 +66,18 @@ pub fn build(b: *std.build.Builder) !void {
.libraries = libraries.items,
};
+ // Replace by your app's main file.
+ // Here this is some code to choose the example to run
+ const ExampleType = enum { egl, textview };
+ const example = b.option(ExampleType, "example", "Which example to run") orelse .egl;
+ const src = switch (example) {
+ .egl => "examples/egl/main.zig",
+ .textview => "examples/textview/main.zig",
+ };
+
const app = sdk.createApp(
"app-template.apk",
- "example/main.zig",
+ src,
config,
mode,
.{
diff --git a/android/build/auto-detect.zig b/android/build/auto-detect.zig
index 97f1a4fa..caaba020 100644
--- a/android/build/auto-detect.zig
+++ b/android/build/auto-detect.zig
@@ -378,7 +378,7 @@ pub fn findUserConfig(b: *Builder, versions: Sdk.ToolchainVersions) !UserConfig
return config;
}
-fn findProgramPath(allocator: std.mem.Allocator, program: []const u8) ?[]const u8 {
+pub fn findProgramPath(allocator: std.mem.Allocator, program: []const u8) ?[]const u8 {
const args: []const []const u8 = if (builtin.os.tag == .windows)
&[_][]const u8{ "where", program }
else
@@ -493,3 +493,12 @@ fn findProblemWithJdk(b: *Builder, path: []const u8) ?[]const u8 {
fn pathConcat(b: *Builder, left: []const u8, right: []const u8) []const u8 {
return std.fs.path.join(b.allocator, &[_][]const u8{ left, right }) catch unreachable;
}
+
+pub fn fileExists(path: []const u8) bool {
+ std.fs.cwd().access(path, .{}) catch |err| {
+ if (err == error.FileNotFound) return false;
+ std.log.debug("Cannot access {s}, {s}", .{ path, @errorName(err) });
+ return false;
+ };
+ return true;
+}
diff --git a/android/devshell.nix b/android/devshell.nix
new file mode 100644
index 00000000..8ab64bee
--- /dev/null
+++ b/android/devshell.nix
@@ -0,0 +1,37 @@
+{ pkgs }:
+
+with pkgs;
+
+# Configure your development environment.
+#
+# Documentation: https://github.com/numtide/devshell
+devshell.mkShell {
+ name = "android-project";
+ motd = ''
+ Entered the Android app development environment.
+ '';
+ env = [
+ {
+ name = "ANDROID_HOME";
+ value = "${android-sdk}/share/android-sdk";
+ }
+ {
+ name = "ANDROID_SDK_ROOT";
+ value = "${android-sdk}/share/android-sdk";
+ }
+ {
+ name = "ANDROID_NDK_ROOT";
+ value = "${android-sdk}/share/android-sdk/ndk";
+ }
+ {
+ name = "JAVA_HOME";
+ value = jdk11.home;
+ }
+ ];
+ packages = [
+ android-sdk
+ gradle
+ jdk11
+ zig
+ ];
+}
diff --git a/android/examples/egl/logo.stl b/android/examples/egl/logo.stl
new file mode 100644
index 00000000..851ab482
Binary files /dev/null and b/android/examples/egl/logo.stl differ
diff --git a/android/examples/egl/main.zig b/android/examples/egl/main.zig
new file mode 100644
index 00000000..c2f2ded9
--- /dev/null
+++ b/android/examples/egl/main.zig
@@ -0,0 +1,904 @@
+const std = @import("std");
+
+const android = @import("android");
+
+const audio = android.audio;
+pub const panic = android.panic;
+pub const log = android.log;
+
+const EGLContext = android.egl.EGLContext;
+const JNI = android.JNI;
+const c = android.egl.c;
+
+const app_log = std.log.scoped(.app);
+
+comptime {
+ _ = android.ANativeActivity_createFunc;
+}
+
+/// Entry point for our application.
+/// This struct provides the interface to the android support package.
+pub const AndroidApp = struct {
+ const Self = @This();
+
+ const TouchPoint = struct {
+ /// if null, then fade out
+ index: ?i32,
+ intensity: f32,
+ x: f32,
+ y: f32,
+ age: i64,
+ };
+
+ allocator: std.mem.Allocator,
+ activity: *android.ANativeActivity,
+
+ thread: ?std.Thread = null,
+ running: bool = true,
+
+ egl_lock: std.Thread.Mutex = .{},
+ egl: ?EGLContext = null,
+ egl_init: bool = true,
+
+ input_lock: std.Thread.Mutex = .{},
+ input: ?*android.AInputQueue = null,
+
+ config: ?*android.AConfiguration = null,
+
+ touch_points: [16]?TouchPoint = [1]?TouchPoint{null} ** 16,
+ screen_width: f32 = undefined,
+ screen_height: f32 = undefined,
+
+ // audio_engine: audio.AudioEngine = .{},
+ simple_synth: SimpleSynth = undefined,
+
+ /// This is the entry point which initializes a application
+ /// that has stored its previous state.
+ /// `stored_state` is that state, the memory is only valid for this function.
+ pub fn init(allocator: std.mem.Allocator, activity: *android.ANativeActivity, stored_state: ?[]const u8) !Self {
+ _ = stored_state;
+
+ return Self{
+ .allocator = allocator,
+ .activity = activity,
+ };
+ }
+
+ /// This function is called when the application is successfully initialized.
+ /// It should create a background thread that processes the events and runs until
+ /// the application gets destroyed.
+ pub fn start(self: *Self) !void {
+ self.thread = try std.Thread.spawn(.{}, mainLoop, .{self});
+ }
+
+ /// Uninitialize the application.
+ /// Don't forget to stop your background thread here!
+ pub fn deinit(self: *Self) void {
+ @atomicStore(bool, &self.running, false, .SeqCst);
+ if (self.thread) |thread| {
+ thread.join();
+ self.thread = null;
+ }
+ if (self.config) |config| {
+ android.AConfiguration_delete(config);
+ }
+ self.* = undefined;
+ }
+
+ pub fn onNativeWindowCreated(self: *Self, window: *android.ANativeWindow) void {
+ self.egl_lock.lock();
+ defer self.egl_lock.unlock();
+
+ if (self.egl) |*old| {
+ old.deinit();
+ }
+
+ self.screen_width = @intToFloat(f32, android.ANativeWindow_getWidth(window));
+ self.screen_height = @intToFloat(f32, android.ANativeWindow_getHeight(window));
+
+ self.egl = EGLContext.init(window, .gles2) catch |err| blk: {
+ app_log.err("Failed to initialize EGL for window: {}\n", .{err});
+ break :blk null;
+ };
+ self.egl_init = true;
+ }
+
+ pub fn onNativeWindowDestroyed(self: *Self, window: *android.ANativeWindow) void {
+ _ = window;
+ self.egl_lock.lock();
+ defer self.egl_lock.unlock();
+
+ if (self.egl) |*old| {
+ old.deinit();
+ }
+ self.egl = null;
+ }
+
+ pub fn onInputQueueCreated(self: *Self, input: *android.AInputQueue) void {
+ self.input_lock.lock();
+ defer self.input_lock.unlock();
+
+ self.input = input;
+ }
+
+ pub fn onInputQueueDestroyed(self: *Self, input: *android.AInputQueue) void {
+ _ = input;
+
+ self.input_lock.lock();
+ defer self.input_lock.unlock();
+
+ self.input = null;
+ }
+
+ fn printConfig(config: *android.AConfiguration) void {
+ var lang: [2]u8 = undefined;
+ var country: [2]u8 = undefined;
+
+ android.AConfiguration_getLanguage(config, &lang);
+ android.AConfiguration_getCountry(config, &country);
+
+ app_log.debug(
+ \\App Configuration:
+ \\ MCC: {}
+ \\ MNC: {}
+ \\ Language: {s}
+ \\ Country: {s}
+ \\ Orientation: {}
+ \\ Touchscreen: {}
+ \\ Density: {}
+ \\ Keyboard: {}
+ \\ Navigation: {}
+ \\ KeysHidden: {}
+ \\ NavHidden: {}
+ \\ SdkVersion: {}
+ \\ ScreenSize: {}
+ \\ ScreenLong: {}
+ \\ UiModeType: {}
+ \\ UiModeNight: {}
+ \\
+ , .{
+ android.AConfiguration_getMcc(config),
+ android.AConfiguration_getMnc(config),
+ &lang,
+ &country,
+ android.AConfiguration_getOrientation(config),
+ android.AConfiguration_getTouchscreen(config),
+ android.AConfiguration_getDensity(config),
+ android.AConfiguration_getKeyboard(config),
+ android.AConfiguration_getNavigation(config),
+ android.AConfiguration_getKeysHidden(config),
+ android.AConfiguration_getNavHidden(config),
+ android.AConfiguration_getSdkVersion(config),
+ android.AConfiguration_getScreenSize(config),
+ android.AConfiguration_getScreenLong(config),
+ android.AConfiguration_getUiModeType(config),
+ android.AConfiguration_getUiModeNight(config),
+ });
+ }
+
+ fn processKeyEvent(self: *Self, event: *android.AInputEvent) !bool {
+ const event_type = @intToEnum(android.AKeyEventActionType, android.AKeyEvent_getAction(event));
+ std.log.scoped(.input).debug(
+ \\Key Press Event: {}
+ \\ Flags: {}
+ \\ KeyCode: {}
+ \\ ScanCode: {}
+ \\ MetaState: {}
+ \\ RepeatCount: {}
+ \\ DownTime: {}
+ \\ EventTime: {}
+ \\
+ , .{
+ event_type,
+ android.AKeyEvent_getFlags(event),
+ android.AKeyEvent_getKeyCode(event),
+ android.AKeyEvent_getScanCode(event),
+ android.AKeyEvent_getMetaState(event),
+ android.AKeyEvent_getRepeatCount(event),
+ android.AKeyEvent_getDownTime(event),
+ android.AKeyEvent_getEventTime(event),
+ });
+
+ if (event_type == .AKEY_EVENT_ACTION_DOWN) {
+ var jni = JNI.init(self.activity);
+ defer jni.deinit();
+
+ var codepoint = jni.AndroidGetUnicodeChar(
+ android.AKeyEvent_getKeyCode(event),
+ android.AKeyEvent_getMetaState(event),
+ );
+ var buf: [8]u8 = undefined;
+
+ var len = std.unicode.utf8Encode(codepoint, &buf) catch 0;
+ var key_text = buf[0..len];
+
+ std.log.scoped(.input).info("Pressed key: '{s}' U+{X}", .{ key_text, codepoint });
+ }
+
+ return false;
+ }
+
+ fn insertPoint(self: *Self, point: TouchPoint) void {
+ std.debug.assert(point.index != null);
+ var oldest: *TouchPoint = undefined;
+
+ if (point.index) |index| {
+ self.simple_synth.oscillators[@intCast(usize, index)].setWaveOn(true);
+ }
+
+ for (self.touch_points) |*opt, i| {
+ if (opt.*) |*pt| {
+ if (pt.index != null and pt.index.? == point.index.?) {
+ pt.* = point;
+ return;
+ }
+
+ if (i == 0) {
+ oldest = pt;
+ } else {
+ if (pt.age < oldest.age) {
+ oldest = pt;
+ }
+ }
+ } else {
+ opt.* = point;
+ return;
+ }
+ }
+ oldest.* = point;
+ }
+
+ fn processMotionEvent(self: *Self, event: *android.AInputEvent) !bool {
+ const event_type = @intToEnum(android.AMotionEventActionType, android.AMotionEvent_getAction(event));
+
+ {
+ var jni = JNI.init(self.activity);
+ defer jni.deinit();
+
+ // Show/Hide keyboard
+ // _ = jni.AndroidDisplayKeyboard(true);
+
+ // this allows you to send the app in the background
+ // const success = jni.AndroidSendToBack(true);
+ // _ = success;
+ // std.log.scoped(.input).debug("SendToBack() = {}\n", .{success});
+
+ // This is a demo on how to request permissions:
+ if (event_type == .AMOTION_EVENT_ACTION_UP) {
+ if (!JNI.AndroidHasPermissions(&jni, "android.permission.RECORD_AUDIO")) {
+ JNI.AndroidRequestAppPermissions(&jni, "android.permission.RECORD_AUDIO");
+ }
+ }
+ }
+
+ std.log.scoped(.input).debug(
+ \\Motion Event {}
+ \\ Flags: {}
+ \\ MetaState: {}
+ \\ ButtonState: {}
+ \\ EdgeFlags: {}
+ \\ DownTime: {}
+ \\ EventTime: {}
+ \\ XOffset: {}
+ \\ YOffset: {}
+ \\ XPrecision: {}
+ \\ YPrecision: {}
+ \\ PointerCount: {}
+ \\
+ , .{
+ event_type,
+ android.AMotionEvent_getFlags(event),
+ android.AMotionEvent_getMetaState(event),
+ android.AMotionEvent_getButtonState(event),
+ android.AMotionEvent_getEdgeFlags(event),
+ android.AMotionEvent_getDownTime(event),
+ android.AMotionEvent_getEventTime(event),
+ android.AMotionEvent_getXOffset(event),
+ android.AMotionEvent_getYOffset(event),
+ android.AMotionEvent_getXPrecision(event),
+ android.AMotionEvent_getYPrecision(event),
+ android.AMotionEvent_getPointerCount(event),
+ });
+
+ var i: usize = 0;
+ var cnt = android.AMotionEvent_getPointerCount(event);
+ while (i < cnt) : (i += 1) {
+ std.log.scoped(.input).debug(
+ \\Pointer {}:
+ \\ PointerId: {}
+ \\ ToolType: {}
+ \\ RawX: {d}
+ \\ RawY: {d}
+ \\ X: {d}
+ \\ Y: {d}
+ \\ Pressure: {}
+ \\ Size: {}
+ \\ TouchMajor: {}
+ \\ TouchMinor: {}
+ \\ ToolMajor: {}
+ \\ ToolMinor: {}
+ \\ Orientation: {}
+ \\
+ , .{
+ i,
+ android.AMotionEvent_getPointerId(event, i),
+ android.AMotionEvent_getToolType(event, i),
+ android.AMotionEvent_getRawX(event, i),
+ android.AMotionEvent_getRawY(event, i),
+ android.AMotionEvent_getX(event, i),
+ android.AMotionEvent_getY(event, i),
+ android.AMotionEvent_getPressure(event, i),
+ android.AMotionEvent_getSize(event, i),
+ android.AMotionEvent_getTouchMajor(event, i),
+ android.AMotionEvent_getTouchMinor(event, i),
+ android.AMotionEvent_getToolMajor(event, i),
+ android.AMotionEvent_getToolMinor(event, i),
+ android.AMotionEvent_getOrientation(event, i),
+ });
+
+ self.insertPoint(TouchPoint{
+ .x = android.AMotionEvent_getX(event, i),
+ .y = android.AMotionEvent_getY(event, i),
+ .index = android.AMotionEvent_getPointerId(event, i),
+ .age = android.AMotionEvent_getEventTime(event),
+ .intensity = 1.0,
+ });
+ }
+
+ return false;
+ }
+
+ fn mainLoop(self: *Self) !void {
+ // This code somehow crashes yet. Needs more investigations
+ var jni = JNI.init(self.activity);
+ defer jni.deinit();
+
+ // Must be called from main thread…
+ _ = jni.AndroidMakeFullscreen();
+
+ var loop: usize = 0;
+ app_log.info("mainLoop() started\n", .{});
+
+ self.config = blk: {
+ var cfg = android.AConfiguration_new() orelse return error.OutOfMemory;
+ android.AConfiguration_fromAssetManager(cfg, self.activity.assetManager);
+ break :blk cfg;
+ };
+
+ if (self.config) |cfg| {
+ printConfig(cfg);
+ }
+
+ // Audio
+ self.simple_synth = SimpleSynth.init();
+
+ try audio.init();
+
+ var output_stream = try audio.getOutputStream(self.allocator, .{
+ .sample_format = .Int16,
+ .callback = SimpleSynth.audioCallback,
+ .user_data = &self.simple_synth,
+ });
+ defer {
+ output_stream.stop();
+ output_stream.deinit();
+ }
+
+ try output_stream.start();
+
+ // Graphics
+ const GLuint = c.GLuint;
+
+ var touch_program: GLuint = undefined;
+ var shaded_program: GLuint = undefined;
+
+ var uPos: c.GLint = undefined;
+ var uAspect: c.GLint = undefined;
+ var uIntensity: c.GLint = undefined;
+
+ var vPosition: c.GLuint = undefined;
+
+ var uTransform: c.GLint = undefined;
+
+ var mesh_vPosition: c.GLuint = undefined;
+ var mesh_vNormal: c.GLuint = undefined;
+
+ var touch_buffer: c.GLuint = undefined;
+ var mesh_buffer: c.GLuint = undefined;
+
+ const vVertices = [_]c.GLfloat{
+ 0.0, 0.0,
+ 1.0, 0.0,
+ 0.0, 1.0,
+ 1.0, 1.0,
+ };
+
+ while (@atomicLoad(bool, &self.running, .SeqCst)) {
+
+ // Input process
+ {
+ // we lock the handle of our input so we don't have a race condition
+ self.input_lock.lock();
+ defer self.input_lock.unlock();
+ if (self.input) |input| {
+ var event: ?*android.AInputEvent = undefined;
+ while (android.AInputQueue_getEvent(input, &event) >= 0) {
+ std.debug.assert(event != null);
+ if (android.AInputQueue_preDispatchEvent(input, event) != 0) {
+ continue;
+ }
+
+ const event_type = @intToEnum(android.AInputEventType, android.AInputEvent_getType(event));
+ const handled = switch (event_type) {
+ .AINPUT_EVENT_TYPE_KEY => try self.processKeyEvent(event.?),
+ .AINPUT_EVENT_TYPE_MOTION => try self.processMotionEvent(event.?),
+ else => blk: {
+ std.log.scoped(.input).debug("Unhandled input event type ({})\n", .{event_type});
+ break :blk false;
+ },
+ };
+
+ // if (app.onInputEvent != NULL)
+ // handled = app.onInputEvent(app, event);
+ android.AInputQueue_finishEvent(input, event, if (handled) @as(c_int, 1) else @as(c_int, 0));
+ }
+ }
+ }
+
+ // Render process
+ {
+ // same for the EGL context
+ self.egl_lock.lock();
+ defer self.egl_lock.unlock();
+ if (self.egl) |egl| {
+ try egl.makeCurrent();
+
+ if (self.egl_init) {
+ enableDebug();
+ app_log.info(
+ \\GL Vendor: {s}
+ \\GL Renderer: {s}
+ \\GL Version: {s}
+ \\GL Extensions: {s}
+ \\
+ , .{
+ std.mem.span(c.glGetString(c.GL_VENDOR)),
+ std.mem.span(c.glGetString(c.GL_RENDERER)),
+ std.mem.span(c.glGetString(c.GL_VERSION)),
+ std.mem.span(c.glGetString(c.GL_EXTENSIONS)),
+ });
+
+ touch_program = c.glCreateProgram();
+ {
+ var ps = c.glCreateShader(c.GL_VERTEX_SHADER);
+ var fs = c.glCreateShader(c.GL_FRAGMENT_SHADER);
+
+ var ps_code =
+ \\attribute vec2 vPosition;
+ \\varying vec2 uv;
+ \\void main() {
+ \\ uv = vPosition;
+ \\ gl_Position = vec4(2.0 * uv - 1.0, 0.0, 1.0);
+ \\}
+ \\
+ ;
+ var fs_code =
+ \\varying highp vec2 uv;
+ \\uniform highp vec2 uPos;
+ \\uniform highp float uAspect;
+ \\uniform highp float uIntensity;
+ \\void main() {
+ \\ highp vec2 rel = uv - uPos;
+ \\ rel.x *= uAspect;
+ \\ gl_FragColor = vec4(vec3(pow(uIntensity * clamp(1.0 - 10.0 * length(rel), 0.0, 1.0), 2.2)), 1.0);
+ \\}
+ \\
+ ;
+
+ c.glShaderSource(ps, 1, @ptrCast([*c]const [*c]const u8, &ps_code), null);
+ c.glShaderSource(fs, 1, @ptrCast([*c]const [*c]const u8, &fs_code), null);
+
+ c.glCompileShader(ps);
+ c.glCompileShader(fs);
+
+ glCheckError(ps);
+ glCheckError(fs);
+
+ c.glAttachShader(touch_program, ps);
+ c.glAttachShader(touch_program, fs);
+
+ glShaderInfoLog(ps);
+ glShaderInfoLog(fs);
+
+ c.glBindAttribLocation(touch_program, 0, "vPosition");
+ c.glLinkProgram(touch_program);
+
+ glCheckError(touch_program);
+
+ c.glDetachShader(touch_program, ps);
+ c.glDetachShader(touch_program, fs);
+
+ glProgramInfoLog(touch_program);
+ }
+
+ // Get uniform locations
+ uPos = c.glGetUniformLocation(touch_program, "uPos");
+ uAspect = c.glGetUniformLocation(touch_program, "uAspect");
+ uIntensity = c.glGetUniformLocation(touch_program, "uIntensity");
+
+ // Get attrib locations
+ const vPosition_res = c.glGetAttribLocation(touch_program, "vPosition");
+ app_log.info("vPosition: {}", .{vPosition_res});
+ vPosition = @intCast(c.GLuint, vPosition_res);
+
+ // Bind the vertices to the buffer
+ c.glGenBuffers(1, &touch_buffer);
+ c.glBindBuffer(c.GL_ARRAY_BUFFER, touch_buffer);
+ c.glBufferData(c.GL_ARRAY_BUFFER, @intCast(isize, vVertices[0..].len * @sizeOf(c.GLfloat)), vVertices[0..], c.GL_STATIC_DRAW);
+
+ shaded_program = c.glCreateProgram();
+ {
+ var ps = c.glCreateShader(c.GL_VERTEX_SHADER);
+ var fs = c.glCreateShader(c.GL_FRAGMENT_SHADER);
+
+ var ps_code =
+ \\#version 100
+ \\attribute vec3 vPosition;
+ \\attribute vec3 vNormal;
+ \\uniform mat4 uTransform;
+ \\varying vec3 normal;
+ \\void main() {
+ \\ normal = mat3(uTransform) * vNormal;
+ \\ gl_Position = uTransform * vec4(vPosition, 1.0);
+ \\}
+ \\
+ ;
+ var fs_code =
+ \\#version 100
+ \\varying highp vec3 normal;
+ \\void main() {
+ \\ highp vec3 base_color = vec3(0.968,0.643,0.113); // #F7A41D
+ \\ highp vec3 ldir = normalize(vec3(0.3, 0.4, 2.0));
+ \\ highp float l = 0.3 + 0.8 * clamp(-dot(normal, ldir), 0.0, 1.0);
+ \\ gl_FragColor = vec4(l * base_color,1);
+ \\}
+ \\
+ ;
+
+ c.glShaderSource(ps, 1, @ptrCast([*c]const [*c]const u8, &ps_code), null);
+ c.glShaderSource(fs, 1, @ptrCast([*c]const [*c]const u8, &fs_code), null);
+
+ c.glCompileShader(ps);
+ c.glCompileShader(fs);
+
+ glShaderInfoLog(ps);
+ glShaderInfoLog(fs);
+
+ c.glAttachShader(shaded_program, ps);
+ c.glAttachShader(shaded_program, fs);
+
+ c.glBindAttribLocation(shaded_program, 0, "vPosition");
+ c.glBindAttribLocation(shaded_program, 1, "vNormal");
+ c.glLinkProgram(shaded_program);
+
+ c.glDetachShader(shaded_program, ps);
+ c.glDetachShader(shaded_program, fs);
+
+ glProgramInfoLog(shaded_program);
+ }
+
+ uTransform = c.glGetUniformLocation(shaded_program, "uTransform");
+
+ // Get attrib locations
+ const mesh_vPosition_res = c.glGetAttribLocation(shaded_program, "vPosition");
+ app_log.info("mesh_vPosition: {}", .{mesh_vPosition_res});
+ mesh_vPosition = @intCast(c.GLuint, mesh_vPosition_res);
+ const mesh_vNormal_res = c.glGetAttribLocation(shaded_program, "vNormal");
+ app_log.info("mesh_vNormal: {}", .{mesh_vNormal_res});
+ mesh_vNormal = @intCast(c.GLuint, mesh_vNormal_res);
+
+ // Bind the vertices to the buffer
+ c.glGenBuffers(1, &mesh_buffer);
+ c.glBindBuffer(c.GL_ARRAY_BUFFER, mesh_buffer);
+ c.glBufferData(c.GL_ARRAY_BUFFER, @intCast(isize, mesh.len * @sizeOf(MeshVertex)), &mesh, c.GL_STATIC_DRAW);
+
+ self.egl_init = false;
+ }
+
+ const t = @intToFloat(f32, loop) / 100.0;
+
+ // Clear the screen
+ c.glClearColor(
+ 0.5 + 0.5 * @sin(t + 0.0),
+ 0.5 + 0.5 * @sin(t + 1.0),
+ 0.5 + 0.5 * @sin(t + 2.0),
+ 1.0,
+ );
+ c.glClear(c.GL_COLOR_BUFFER_BIT);
+
+ // -- Start touch display code
+ c.glUseProgram(touch_program);
+
+ c.glBindBuffer(c.GL_ARRAY_BUFFER, touch_buffer);
+
+ c.glEnableVertexAttribArray(vPosition);
+ c.glVertexAttribPointer(vPosition, 2, c.GL_FLOAT, c.GL_FALSE, 0, @intToPtr(?*anyopaque, 0));
+
+ // c.glDisableVertexAttribArray(1);
+
+ c.glDisable(c.GL_DEPTH_TEST);
+ c.glEnable(c.GL_BLEND);
+ c.glBlendFunc(c.GL_ONE, c.GL_ONE);
+ c.glBlendEquation(c.GL_FUNC_ADD);
+
+ for (self.touch_points) |*pt| {
+ if (pt.*) |*point| {
+ c.glUniform1f(uAspect, self.screen_width / self.screen_height);
+ c.glUniform2f(uPos, point.x / self.screen_width, 1.0 - point.y / self.screen_height);
+ c.glUniform1f(uIntensity, point.intensity);
+ c.glDrawArrays(c.GL_TRIANGLE_STRIP, 0, 4);
+
+ point.intensity -= 0.05;
+ if (point.intensity <= 0.0) {
+ if (point.index) |index| {
+ self.simple_synth.oscillators[@intCast(usize, index)].setWaveOn(false);
+ }
+ pt.* = null;
+ }
+ }
+ }
+ glDrainErrors();
+
+ // -- Start 3d zig logo code
+ c.glBindBuffer(c.GL_ARRAY_BUFFER, mesh_buffer);
+ c.glEnableVertexAttribArray(mesh_vPosition);
+ c.glVertexAttribPointer(mesh_vPosition, 3, c.GL_FLOAT, c.GL_FALSE, @sizeOf(MeshVertex), @intToPtr(?*anyopaque, @offsetOf(MeshVertex, "pos")));
+
+ c.glEnableVertexAttribArray(mesh_vNormal);
+ c.glVertexAttribPointer(mesh_vNormal, 3, c.GL_FLOAT, c.GL_FALSE, @sizeOf(MeshVertex), @intToPtr(?*anyopaque, @offsetOf(MeshVertex, "normal")));
+
+ c.glUseProgram(shaded_program);
+
+ c.glClearDepthf(1.0);
+ c.glClear(c.GL_DEPTH_BUFFER_BIT);
+
+ c.glDisable(c.GL_BLEND);
+ c.glEnable(c.GL_DEPTH_TEST);
+
+ var matrix = [4][4]f32{
+ [4]f32{ 1, 0, 0, 0 },
+ [4]f32{ 0, 1, 0, 0 },
+ [4]f32{ 0, 0, 1, 0 },
+ [4]f32{ 0, 0, 0, 1 },
+ };
+
+ matrix[1][1] = self.screen_width / self.screen_height;
+
+ matrix[0][0] = @sin(t);
+ matrix[2][0] = @cos(t);
+ matrix[0][2] = @cos(t);
+ matrix[2][2] = -@sin(t);
+
+ c.glUniformMatrix4fv(uTransform, 1, c.GL_FALSE, @ptrCast([*]const f32, &matrix));
+
+ c.glDrawArrays(c.GL_TRIANGLES, 0, mesh.len);
+
+ glDrainErrors();
+
+ try egl.swapBuffers();
+ }
+ }
+ loop += 1;
+
+ std.time.sleep(10 * std.time.ns_per_ms);
+ }
+ app_log.info("mainLoop() finished\n", .{});
+ }
+};
+
+const MeshVertex = extern struct {
+ pos: Vector4,
+ normal: Vector4,
+};
+
+const Vector4 = extern struct {
+ x: f32,
+ y: f32,
+ z: f32,
+ w: f32 = 1.0,
+
+ fn readFromSlice(slice: []const u8) Vector4 {
+ return Vector4{
+ .x = @bitCast(f32, std.mem.readIntLittle(u32, slice[0..4])),
+ .y = @bitCast(f32, std.mem.readIntLittle(u32, slice[4..8])),
+ .z = @bitCast(f32, std.mem.readIntLittle(u32, slice[8..12])),
+ .w = 1.0,
+ };
+ }
+};
+
+const mesh = blk: {
+ const stl_data = @embedFile("logo.stl");
+
+ const count = std.mem.readIntLittle(u32, stl_data[80..][0..4]);
+
+ var slice: []const u8 = stl_data[84..];
+
+ var array: [3 * count]MeshVertex = undefined;
+ var index: usize = 0;
+
+ @setEvalBranchQuota(10_000);
+
+ while (index < count) : (index += 1) {
+ const normal = Vector4.readFromSlice(slice[0..]);
+ const v1 = Vector4.readFromSlice(slice[12..]);
+ const v2 = Vector4.readFromSlice(slice[24..]);
+ const v3 = Vector4.readFromSlice(slice[36..]);
+ const attrib_count = std.mem.readIntLittle(u16, slice[48..50]);
+
+ array[3 * index + 0] = MeshVertex{
+ .pos = v1,
+ .normal = normal,
+ };
+ array[3 * index + 1] = MeshVertex{
+ .pos = v2,
+ .normal = normal,
+ };
+ array[3 * index + 2] = MeshVertex{
+ .pos = v3,
+ .normal = normal,
+ };
+
+ slice = slice[50 + attrib_count ..];
+ }
+
+ break :blk array;
+};
+
+pub fn glProgramInfoLog(program: c.GLuint) void {
+ var buffer: [4096]u8 = undefined;
+ var size: c.GLsizei = undefined;
+ c.glGetProgramInfoLog(program, 4096, &size, &buffer);
+ if (size == 0) return;
+ app_log.info("{s}", .{buffer[0..@intCast(usize, size)]});
+}
+
+pub fn glShaderInfoLog(shader: c.GLuint) void {
+ var buffer: [4096]u8 = undefined;
+ var size: c.GLsizei = undefined;
+ c.glGetShaderInfoLog(shader, 4096, &size, &buffer);
+ if (size == 0) return;
+ app_log.info("{s}", .{buffer[0..@intCast(usize, size)]});
+}
+
+pub fn glCheckError(res: i64) void {
+ switch (res) {
+ c.GL_INVALID_ENUM => app_log.err("GL error code {}: Invalid enum", .{res}),
+ c.GL_INVALID_VALUE => app_log.err("GL error code {}: Invalid value", .{res}),
+ c.GL_INVALID_OPERATION => app_log.err("GL error code {}: Invalid operation", .{res}),
+ // c.GL_STACK_OVERFLOW => app_log.err("GL error code {}: Stack overflow", .{res}),
+ // c.GL_STACK_UNDERFLOW => app_log.err("GL error code {}: Stack underflow", .{res}),
+ c.GL_OUT_OF_MEMORY => app_log.err("GL error code {}: Out of memory", .{res}),
+ // c.GL_TABLE_TOO_LARGE => app_log.err("GL error code {}: Table too large", .{res}),
+ c.GL_NO_ERROR => {},
+ else => {},
+ }
+}
+
+pub fn glDrainErrors() void {
+ var res = c.glGetError();
+ while (res != c.GL_NO_ERROR) : (res = c.glGetError()) {
+ glCheckError(res);
+ }
+}
+
+pub fn enableDebug() void {
+ const extensions = std.mem.span(c.glGetString(c.GL_EXTENSIONS));
+ if (std.mem.indexOf(u8, extensions, "GL_KHR_debug") != null) {
+ c.glEnable(c.GL_DEBUG_OUTPUT_KHR);
+ c.glEnable(c.GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR);
+
+ const glDebugMessageControl = @ptrCast(c.PFNGLDEBUGMESSAGECONTROLKHRPROC, c.eglGetProcAddress("glDebugMessageControl")).?;
+ glDebugMessageControl(c.GL_DONT_CARE, c.GL_DONT_CARE, c.GL_DEBUG_SEVERITY_NOTIFICATION_KHR, 0, null, c.GL_TRUE);
+
+ const glDebugMessageCallback = @ptrCast(c.PFNGLDEBUGMESSAGECALLBACKKHRPROC, c.eglGetProcAddress("glDebugMessageCallback")).?;
+ glDebugMessageCallback(debugMessageCallback, null);
+ } else {
+ app_log.err("Debug is not supported.", .{});
+ }
+}
+
+pub fn debugMessageCallback(
+ source: c.GLenum,
+ logtype: c.GLenum,
+ id: c.GLuint,
+ severity: c.GLenum,
+ length: c.GLsizei,
+ message_c: ?[*]const c.GLchar,
+ user_param: ?*const anyopaque,
+) callconv(.C) void {
+ _ = user_param;
+ const message = message: {
+ if (message_c) |message_ptr| {
+ break :message if (length > 0) message_ptr[0..@intCast(usize, length)] else "";
+ } else {
+ break :message "";
+ }
+ };
+ const logtype_str = switch (logtype) {
+ c.GL_DEBUG_TYPE_ERROR_KHR => "Error",
+ c.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR => "Deprecated Behavior",
+ c.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR => "Undefined Behavior",
+ c.GL_DEBUG_TYPE_PORTABILITY_KHR => "Portability",
+ c.GL_DEBUG_TYPE_PERFORMANCE_KHR => "Performance",
+ c.GL_DEBUG_TYPE_OTHER_KHR => "Other",
+ c.GL_DEBUG_TYPE_MARKER_KHR => "Marker",
+ else => "Unknown/invalid type",
+ };
+ app_log.err("source = {}, type = {s}, id = {}, severity = {}, message = {s}", .{ source, logtype_str, id, severity, message });
+}
+
+const Oscillator = struct {
+ isWaveOn: bool = false,
+ phase: f64 = 0.0,
+ phaseIncrement: f64 = 0,
+ frequency: f64 = 440,
+ amplitude: f64 = 0.1,
+
+ fn setWaveOn(self: *@This(), isWaveOn: bool) void {
+ @atomicStore(bool, &self.isWaveOn, isWaveOn, .SeqCst);
+ }
+
+ fn setSampleRate(self: *@This(), sample_rate: i32) void {
+ self.phaseIncrement = (std.math.tau * self.frequency) / @intToFloat(f64, sample_rate);
+ }
+
+ fn renderf32(self: *@This(), audio_data: []f32) void {
+ if (!@atomicLoad(bool, &self.isWaveOn, .SeqCst)) self.phase = 0;
+
+ for (audio_data) |*frame| {
+ if (@atomicLoad(bool, &self.isWaveOn, .SeqCst)) {
+ frame.* += @floatCast(f32, std.math.sin(self.phase) * self.amplitude);
+ self.phase += self.phaseIncrement;
+ if (self.phase > std.math.tau) self.phase -= std.math.tau;
+ }
+ }
+ }
+
+ fn renderi16(self: *@This(), audio_data: []i16) void {
+ if (!@atomicLoad(bool, &self.isWaveOn, .SeqCst)) self.phase = 0;
+
+ for (audio_data) |*frame| {
+ if (@atomicLoad(bool, &self.isWaveOn, .SeqCst)) {
+ frame.* +|= @floatToInt(i16, @floatCast(f32, std.math.sin(self.phase) * self.amplitude) * std.math.maxInt(i16));
+ self.phase += self.phaseIncrement;
+ if (self.phase > std.math.tau) self.phase -= std.math.tau;
+ }
+ }
+ }
+};
+
+const SimpleSynth = struct {
+ oscillators: [10]Oscillator = [1]Oscillator{.{}} ** 10,
+
+ fn init() SimpleSynth {
+ var synth = SimpleSynth{};
+ for (synth.oscillators) |*osc, index| {
+ osc.* = Oscillator{
+ .frequency = audio.midiToFreq(49 + index * 3),
+ .amplitude = audio.dBToAmplitude(-@intToFloat(f64, index) - 15),
+ };
+ }
+ return synth;
+ }
+
+ fn audioCallback(stream: audio.StreamLayout, user_data: *anyopaque) void {
+ var synth = @ptrCast(*SimpleSynth, @alignCast(@alignOf(SimpleSynth), user_data));
+ std.debug.assert(stream.buffer == .Int16);
+
+ for (synth.oscillators) |*osc| {
+ osc.setSampleRate(@intCast(i32, stream.sample_rate));
+ osc.renderi16(stream.buffer.Int16);
+ }
+ }
+};
diff --git a/android/examples/icon.png b/android/examples/icon.png
new file mode 100644
index 00000000..7ea4bd87
Binary files /dev/null and b/android/examples/icon.png differ
diff --git a/android/examples/textview/main.zig b/android/examples/textview/main.zig
new file mode 100644
index 00000000..adb32eac
--- /dev/null
+++ b/android/examples/textview/main.zig
@@ -0,0 +1,178 @@
+const std = @import("std");
+
+const android = @import("android");
+
+const audio = android.audio;
+pub const panic = android.panic;
+pub const log = android.log;
+
+const EGLContext = android.egl.EGLContext;
+const JNI = android.JNI;
+const c = android.egl.c;
+
+const app_log = std.log.scoped(.app);
+comptime {
+ _ = android.ANativeActivity_createFunc;
+ _ = @import("root").log;
+}
+
+pub const AndroidApp = struct {
+ allocator: std.mem.Allocator,
+ activity: *android.ANativeActivity,
+ thread: ?std.Thread = null,
+ running: bool = true,
+
+ // The JNIEnv of the UI thread
+ uiJni: JNI = undefined,
+ // The JNIEnv of the app thread
+ mainJni: JNI = undefined,
+
+ // This is needed because to run a callback on the UI thread Looper you must
+ // react to a fd change, so we use a pipe to force it
+ pipe: [2]std.os.fd_t = undefined,
+ // This is used with futexes so that runOnUiThread waits until the callback is completed
+ // before returning.
+ uiThreadCondition: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0),
+ uiThreadLooper: *android.ALooper = undefined,
+ uiThreadId: std.Thread.Id = undefined,
+
+ pub fn init(allocator: std.mem.Allocator, activity: *android.ANativeActivity, stored_state: ?[]const u8) !AndroidApp {
+ _ = stored_state;
+
+ return AndroidApp{
+ .allocator = allocator,
+ .activity = activity,
+ };
+ }
+
+ pub fn start(self: *AndroidApp) !void {
+ // Initialize the variables we need to execute functions on the UI thread
+ self.uiThreadLooper = android.ALooper_forThread().?;
+ self.uiThreadId = std.Thread.getCurrentId();
+ self.pipe = try std.os.pipe();
+ android.ALooper_acquire(self.uiThreadLooper);
+
+ var jni = JNI.init(self.activity);
+ self.uiJni = jni;
+
+ // Get the window object attached to our activity
+ const activityClass = jni.findClass("android/app/NativeActivity");
+ const getWindow = jni.invokeJni(.GetMethodID, .{ activityClass, "getWindow", "()Landroid/view/Window;" });
+ const activityWindow = jni.invokeJni(.CallObjectMethod, .{ self.activity.clazz, getWindow });
+ const WindowClass = jni.findClass("android/view/Window");
+
+ // This disables the surface handler set by default by android.view.NativeActivity
+ // This way we let the content view do the drawing instead of us.
+ const takeSurface = jni.invokeJni(.GetMethodID, .{ WindowClass, "takeSurface", "(Landroid/view/SurfaceHolder$Callback2;)V" });
+ jni.invokeJni(.CallVoidMethod, .{
+ activityWindow,
+ takeSurface,
+ @as(android.jobject, null),
+ });
+
+ // Do the same but with the input queue. This allows the content view to handle input.
+ const takeInputQueue = jni.invokeJni(.GetMethodID, .{ WindowClass, "takeInputQueue", "(Landroid/view/InputQueue$Callback;)V" });
+ jni.invokeJni(.CallVoidMethod, .{
+ activityWindow,
+ takeInputQueue,
+ @as(android.jobject, null),
+ });
+ self.thread = try std.Thread.spawn(.{}, mainLoop, .{self});
+ }
+
+ /// Run the given function on the Android UI thread. This is necessary for manipulating the view hierarchy.
+ /// Note: this function is not thread-safe, but could be made so simply using a mutex
+ pub fn runOnUiThread(self: *AndroidApp, comptime func: anytype, args: anytype) !void {
+ if (std.Thread.getCurrentId() == self.uiThreadId) {
+ // runOnUiThread has been called from the UI thread.
+ @call(.auto, func, args);
+ return;
+ }
+
+ const Args = @TypeOf(args);
+ const allocator = self.allocator;
+
+ const Data = struct {
+ args: Args,
+ self: *AndroidApp
+ };
+
+ const data_ptr = try allocator.create(Data);
+ data_ptr.* = .{ .args = args, .self = self };
+ errdefer allocator.destroy(data_ptr);
+
+ const Instance = struct {
+ fn callback(_: c_int, _: c_int, data: ?*anyopaque) callconv(.C) c_int {
+ const data_struct = @ptrCast(*Data, @alignCast(@alignOf(Data), data.?));
+ const self_ptr = data_struct.self;
+ defer self_ptr.allocator.destroy(data_struct);
+
+ @call(.auto, func, data_struct.args);
+ std.Thread.Futex.wake(&self_ptr.uiThreadCondition, 1);
+ return 0;
+ }
+ };
+
+ const result = android.ALooper_addFd(self.uiThreadLooper,
+ self.pipe[0],
+ 0,
+ android.ALOOPER_EVENT_INPUT,
+ Instance.callback,
+ data_ptr,
+ );
+ std.debug.assert(try std.os.write(self.pipe[1], "hello") == 5);
+ if (result == -1) {
+ return error.LooperError;
+ }
+
+ std.Thread.Futex.wait(&self.uiThreadCondition, 0);
+ }
+
+ pub fn getJni(self: *AndroidApp) JNI {
+ return JNI.get(self.activity);
+ }
+
+ pub fn deinit(self: *AndroidApp) void {
+ @atomicStore(bool, &self.running, false, .SeqCst);
+ if (self.thread) |thread| {
+ thread.join();
+ self.thread = null;
+ }
+ android.ALooper_release(self.uiThreadLooper);
+ self.uiJni.deinit();
+ }
+
+ fn setAppContentView(self: *AndroidApp) void {
+ const jni = self.getJni();
+
+ // We create a new TextView..
+ std.log.warn("Creating android.widget.TextView", .{});
+ const TextView = jni.findClass("android/widget/TextView");
+ const textViewInit = jni.invokeJni(.GetMethodID, .{ TextView, "", "(Landroid/content/Context;)V" });
+ const textView = jni.invokeJni(.NewObject, .{ TextView, textViewInit, self.activity.clazz });
+
+ // .. and set its text to "Hello from Zig!"
+ const setText = jni.invokeJni(.GetMethodID, .{ TextView, "setText", "(Ljava/lang/CharSequence;)V" });
+ jni.invokeJni(.CallVoidMethod, .{ textView, setText, jni.newString("Hello from Zig!") });
+
+ // And then we use it as our content view!
+ std.log.err("Attempt to call NativeActivity.setContentView()", .{});
+ const activityClass = jni.findClass("android/app/NativeActivity");
+ const setContentView = jni.invokeJni(.GetMethodID, .{ activityClass, "setContentView", "(Landroid/view/View;)V" });
+ jni.invokeJni(.CallVoidMethod, .{
+ self.activity.clazz,
+ setContentView,
+ textView,
+ });
+ }
+
+ fn mainLoop(self: *AndroidApp) !void {
+ self.mainJni = JNI.init(self.activity);
+ defer self.mainJni.deinit();
+
+ try self.runOnUiThread(setAppContentView, .{ self });
+ while (self.running) {
+ std.time.sleep(1 * std.time.ns_per_s);
+ }
+ }
+};
diff --git a/android/flake.lock b/android/flake.lock
new file mode 100644
index 00000000..c7589b6f
--- /dev/null
+++ b/android/flake.lock
@@ -0,0 +1,221 @@
+{
+ "nodes": {
+ "android": {
+ "inputs": {
+ "devshell": "devshell",
+ "flake-utils": "flake-utils",
+ "nixpkgs": "nixpkgs"
+ },
+ "locked": {
+ "lastModified": 1671654171,
+ "narHash": "sha256-oWJLYZip4KRe0cv859DRnjokb6C4so7cc50ucQoFNac=",
+ "owner": "tadfisher",
+ "repo": "android-nixpkgs",
+ "rev": "068776b833f7cbd4e1796a71ba306296ecda1629",
+ "type": "github"
+ },
+ "original": {
+ "owner": "tadfisher",
+ "repo": "android-nixpkgs",
+ "type": "github"
+ }
+ },
+ "devshell": {
+ "inputs": {
+ "flake-utils": [
+ "android",
+ "nixpkgs"
+ ],
+ "nixpkgs": [
+ "android",
+ "nixpkgs"
+ ]
+ },
+ "locked": {
+ "lastModified": 1671489820,
+ "narHash": "sha256-qoei5HDJ8psd1YUPD7DhbHdhLIT9L2nadscp4Qk37uk=",
+ "owner": "numtide",
+ "repo": "devshell",
+ "rev": "5aa3a8039c68b4bf869327446590f4cdf90bb634",
+ "type": "github"
+ },
+ "original": {
+ "owner": "numtide",
+ "repo": "devshell",
+ "type": "github"
+ }
+ },
+ "devshell_2": {
+ "inputs": {
+ "flake-utils": "flake-utils_2",
+ "nixpkgs": "nixpkgs_2"
+ },
+ "locked": {
+ "lastModified": 1671489820,
+ "narHash": "sha256-qoei5HDJ8psd1YUPD7DhbHdhLIT9L2nadscp4Qk37uk=",
+ "owner": "numtide",
+ "repo": "devshell",
+ "rev": "5aa3a8039c68b4bf869327446590f4cdf90bb634",
+ "type": "github"
+ },
+ "original": {
+ "owner": "numtide",
+ "repo": "devshell",
+ "type": "github"
+ }
+ },
+ "flake-utils": {
+ "locked": {
+ "lastModified": 1667395993,
+ "narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
+ "type": "github"
+ },
+ "original": {
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "type": "github"
+ }
+ },
+ "flake-utils_2": {
+ "locked": {
+ "lastModified": 1642700792,
+ "narHash": "sha256-XqHrk7hFb+zBvRg6Ghl+AZDq03ov6OshJLiSWOoX5es=",
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "rev": "846b2ae0fc4cc943637d3d1def4454213e203cba",
+ "type": "github"
+ },
+ "original": {
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "type": "github"
+ }
+ },
+ "flake-utils_3": {
+ "locked": {
+ "lastModified": 1667395993,
+ "narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=",
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f",
+ "type": "github"
+ },
+ "original": {
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "type": "github"
+ }
+ },
+ "flake-utils_4": {
+ "locked": {
+ "lastModified": 1659877975,
+ "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=",
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0",
+ "type": "github"
+ },
+ "original": {
+ "owner": "numtide",
+ "repo": "flake-utils",
+ "type": "github"
+ }
+ },
+ "nixpkgs": {
+ "locked": {
+ "lastModified": 1671359686,
+ "narHash": "sha256-3MpC6yZo+Xn9cPordGz2/ii6IJpP2n8LE8e/ebUXLrs=",
+ "owner": "NixOS",
+ "repo": "nixpkgs",
+ "rev": "04f574a1c0fde90b51bf68198e2297ca4e7cccf4",
+ "type": "github"
+ },
+ "original": {
+ "owner": "NixOS",
+ "ref": "nixos-unstable",
+ "repo": "nixpkgs",
+ "type": "github"
+ }
+ },
+ "nixpkgs_2": {
+ "locked": {
+ "lastModified": 1643381941,
+ "narHash": "sha256-pHTwvnN4tTsEKkWlXQ8JMY423epos8wUOhthpwJjtpc=",
+ "owner": "NixOS",
+ "repo": "nixpkgs",
+ "rev": "5efc8ca954272c4376ac929f4c5ffefcc20551d5",
+ "type": "github"
+ },
+ "original": {
+ "owner": "NixOS",
+ "ref": "nixpkgs-unstable",
+ "repo": "nixpkgs",
+ "type": "github"
+ }
+ },
+ "nixpkgs_3": {
+ "locked": {
+ "lastModified": 1671653751,
+ "narHash": "sha256-YjhztZ2zana/WXhWKUzOdIrsoCd+edtum42X4U4ml4A=",
+ "owner": "NixOS",
+ "repo": "nixpkgs",
+ "rev": "6653a5a9320034a952fb39e310f1ff122bd0f12a",
+ "type": "github"
+ },
+ "original": {
+ "owner": "NixOS",
+ "repo": "nixpkgs",
+ "type": "github"
+ }
+ },
+ "nixpkgs_4": {
+ "locked": {
+ "lastModified": 1661151577,
+ "narHash": "sha256-++S0TuJtuz9IpqP8rKktWyHZKpgdyrzDFUXVY07MTRI=",
+ "owner": "NixOS",
+ "repo": "nixpkgs",
+ "rev": "54060e816971276da05970a983487a25810c38a7",
+ "type": "github"
+ },
+ "original": {
+ "owner": "NixOS",
+ "ref": "nixpkgs-unstable",
+ "repo": "nixpkgs",
+ "type": "github"
+ }
+ },
+ "root": {
+ "inputs": {
+ "android": "android",
+ "devshell": "devshell_2",
+ "flake-utils": "flake-utils_3",
+ "nixpkgs": "nixpkgs_3",
+ "zig": "zig"
+ }
+ },
+ "zig": {
+ "inputs": {
+ "flake-utils": "flake-utils_4",
+ "nixpkgs": "nixpkgs_4"
+ },
+ "locked": {
+ "lastModified": 1671624479,
+ "narHash": "sha256-cwQzVb+1X7aDCXExVwCzoAx9NYU4XYr0EQyOqigIw/g=",
+ "owner": "mitchellh",
+ "repo": "zig-overlay",
+ "rev": "dd83b3c67d8d8cc198cec4cefb5d0fac83dcd917",
+ "type": "github"
+ },
+ "original": {
+ "owner": "mitchellh",
+ "repo": "zig-overlay",
+ "type": "github"
+ }
+ }
+ },
+ "root": "root",
+ "version": 7
+}
diff --git a/android/flake.nix b/android/flake.nix
new file mode 100644
index 00000000..beac2e56
--- /dev/null
+++ b/android/flake.nix
@@ -0,0 +1,46 @@
+{
+ description = "My Android project";
+
+ inputs = {
+ nixpkgs.url = "github:NixOS/nixpkgs";
+ devshell.url = "github:numtide/devshell";
+ flake-utils.url = "github:numtide/flake-utils";
+ android.url = "github:tadfisher/android-nixpkgs";
+ zig.url = "github:mitchellh/zig-overlay";
+ };
+
+ outputs = { self, nixpkgs, devshell, flake-utils, android, zig }:
+ {
+ overlay = final: prev: {
+ inherit (self.packages.${final.system}) android-sdk zig;
+ };
+ }
+ //
+ flake-utils.lib.eachSystem [ "x86_64-linux" ] (system:
+ let
+ pkgs = import nixpkgs {
+ inherit system;
+ config.allowUnfree = true;
+ overlays = [
+ devshell.overlay
+ self.overlay
+ ];
+ };
+ in
+ {
+ packages = {
+ zig = zig.packages.${system}.master;
+ android-sdk = android.sdk.${system} (sdkPkgs: with sdkPkgs; [
+ # Useful packages for building and testing.
+ build-tools-33-0-1
+ cmdline-tools-latest
+ platform-tools
+ platforms-android-21
+ ndk-25-1-8937393
+ ]);
+ };
+
+ devShell = import ./devshell.nix { inherit pkgs; };
+ }
+ );
+}
diff --git a/android/src/jni.zig b/android/src/jni.zig
index 1f864fcb..161386a0 100644
--- a/android/src/jni.zig
+++ b/android/src/jni.zig
@@ -15,6 +15,7 @@ pub const JNI = struct {
return fromJniEnv(activity, env);
}
+ /// Get the JNIEnv associated with the current thread.
pub fn get(activity: *android.ANativeActivity) Self {
var env: *android.JNIEnv = undefined;
_ = activity.vm.*.GetEnv(activity.vm, @ptrCast(*?*anyopaque, &env), android.JNI_VERSION_1_6);
diff --git a/build_capy.zig b/build_capy.zig
index 0f67031f..d3c80e23 100644
--- a/build_capy.zig
+++ b/build_capy.zig
@@ -127,7 +127,6 @@ pub fn install(step: *std.build.LibExeObjStep, options: CapyBuildOptions) !void
},
// This is a list of native android apis to link against.
.libraries = libraries.items,
- .packages = &.{ },
//.fullscreen = true,
};