Remove redundant game-activity + native-activity crates

This commit is contained in:
Robert Bragg
2022-07-03 21:19:14 +01:00
parent 86a4ba1662
commit 12aa17ee42
41 changed files with 1 additions and 81484 deletions
+1 -2
View File
@@ -1,7 +1,6 @@
[workspace]
members = [
"native-activity",
"game-activity"
"android-activity"
]
exclude = [
-10
View File
@@ -1,10 +0,0 @@
/target
Cargo.lock
# Added by cargo
#
# already existing elements were commented out
#/target
#Cargo.lock
-30
View File
@@ -1,30 +0,0 @@
[package]
name = "game-activity"
version = "0.1.0"
edition = "2021"
keywords = ["android", "ndk"]
readme = "../README.md"
license = "MIT OR Apache-2.0"
[dependencies]
log = "0.4"
jni-sys = "0.3"
ndk = { version = "0.6" }
ndk-sys = { version = "0.3" }
ndk-context = { version = "0.1" }
android-properties = "0.2"
lazy_static = "1.4.0"
num_enum = "0.5"
bitflags = "1.3"
libc = "0.2.84"
[build-dependencies]
cc = { version = "1.0", features = ["parallel"] }
[package.metadata.docs.rs]
targets = [
"aarch64-linux-android",
"armv7-linux-androideabi",
"i686-linux-android",
"x86_64-linux-android",
]
-12
View File
@@ -1,12 +0,0 @@
The third-party glue code, from the Android Game Development Kit, under the csrc/ directory
is covered by the Apache 2.0 license only:
Apache License, Version 2.0 (docs/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
All other code is dual-licensed under either
* MIT License (docs/LICENSE-MIT or http://opensource.org/licenses/MIT)
* Apache License, Version 2.0 (docs/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
at your option.
-208
View File
@@ -1,208 +0,0 @@
This crate provides a "glue" layer for building native Rust applications on Android based on the Android Game Development Kit's [`GameActivity`](https://developer.android.com/games/agdk/integrate-game-activity) class.
This serves a similar purpose to [`android_native_app_glue.c`](https://android.googlesource.com/platform/development/+/4948c163663ecc343c97e4c2a2139234f1d3273f/ndk/sources/android/native_app_glue) for `C/C++` applications but instead of being based on the `NativeActivity` class, this is instead based on `GameActivity` that itself is is based on [`AppCompatActivity`](https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity)
This abstraction builds directly on the native glue layer provided by the [AGDK](https://developer.android.com/games/agdk) project so that it's practical to keep in sync with any upstream fixes.
The general way in which it works internally is to spawn a dedicated thread for the main function of your Rust application and uses IPC via a pipe to marshal events from Java (such as lifecycle events) to the native application.
Here's a minimal illustration of an Android main function and main loop based on this crate _(for portability then real applications would probably use winit which would handle some of this internally)_:
```rust
#[no_mangle]
extern "C" fn android_main() {
android_logger::init_once(
Config::default().with_min_level(Level::Trace)
);
let mut quit = false;
let mut redraw_pending = true;
let mut render_state: Option<()> = Default::default();
let app = game_activity::android_app();
while !quit {
app.poll_events(Some(Duration::from_millis(500)) /* timeout */, |event| {
match event {
PollEvent::Wake => { trace!("Early wake up"); },
PollEvent::Timeout => {
trace!("Timed out");
// Real app would probably rely on vblank sync via graphics API...
redraw_pending = true;
},
PollEvent::Main(main_event) => {
trace!("Main event: {:?}", main_event);
match main_event {
MainEvent::SaveState { saver, .. } => {
let state = serde_json::to_vec(&AppState { uri: format!("foo://bar") }).unwrap();
saver.store(&state);
},
MainEvent::Pause => {},
MainEvent::Resume { loader, .. } => {
if let Some(state) = loader.load() {
let _state: AppState = serde_json::from_slice(&state).unwrap();
}
},
MainEvent::InitWindow { .. } => {
render_state = Some(());
redraw_pending = true;
},
MainEvent::TerminateWindow { .. } => {
render_state = None;
}
MainEvent::WindowResized { .. } => { redraw_pending = true; },
MainEvent::RedrawNeeded { ..} => { redraw_pending = true; },
MainEvent::LowMemory => {},
MainEvent::Destroy => { quit = true },
_ => { /* ... */}
}
},
_ => {}
}
if redraw_pending {
if let Some(_rs) = render_state {
redraw_pending = false;
// Handle input
if let Some(buf) = app.swap_input_buffers() {
for motion in buf.motion_events_iter() {
trace!("Motion Event: {motion:?}")
}
for key in buf.key_events_iter() {
trace!("Key Event: {key:?}")
}
}
// Render...
}
}
});
}
}
```
# Motivations
1. Firstly I'd like to write a cross-platform UI (in egui) to test a Rust Bluetooth library I've been working on.
2. Secondly I saw that Bevy's Android support needs some tlc currently ([#86](https://github.com/bevyengine/bevy/issues/86))
3. I wanted an excuse to poke at some of the backend details for winit and see how it works with wgpu - since I'm a low-level graphics and windowing system person that likes Rust :-D
For the Bluetooth library I notably can't directly use `NativeActivity` since I have to subclass Activity to be able to get callbacks for the result of Intents due to how Android's Companion API works. Theoretically I could subclass `NativeActivity` in Java but for testing so far I have an application that is based on [`AppCompatActivity`](https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity) which I'm inclined to keep as a base if possible. For example `AppCompatActivity` offers a better solution for receiving Intent results from another activity that doesn't require subclassing the Activity further and this API/solution simply isn't available based on `NativeActivity` or even a custom subclass.
Although I've worked with `NativeActivity` a decent amount in the past I've only recently had to venture into needing more features than NativeActivity can support directly. From seeing how developers tend to create the Activity class for non-native development (I'm not experienced with Java/Kotlin programming on Android) it looks like [`AppCompatActivity`](https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity) along with [Jetpack](https://developer.android.com/jetpack) libraries offer a much more comprehensive foundation for developing Android applications than being based directly on `Activity`, like `NativeActivity`. I think it stands to reason that native Rust (and hybrid) applications on Android should be able to leverage the same foundations that modern Android apps have - at least as an option for times when `NativeActivity` isn't enough.
I recently discovered Google's [Android Game Development Kit](https://developer.android.com/games/agdk) project which aims to offer a more comprehensive native development experience for game developers. The project provides native bindings that make it easier to handle text input and IME handling, as well as supporting game controllers and other fiddly details that could be particularly useful for game engines like Bevy. One of the components they provide is a [`GameActivity`](https://developer.android.com/games/agdk/integrate-game-activity) class that is essentially a modern alternative to `NativeActivity` that's based on `AppCompatActivity`. This basically just sounded ideal here and so I started looking at whether it would be feasible to create an alternative to `ndk-glue` that would support building Rust apps based on `GameActivity` along with an updated backend for winit.
# Compatibility
The original intent was to copy the API of [ndk-glue](https://github.com/rust-windowing/android-ndk-rs) for the sake of being able to use with [winit](https://github.com/rust-windowing/winit) (unmodified) but as I progressed I found that wasn't going to be realistic / practical.
In particular the way in which the glue layer needs to synchronize with the Java main thread with pre- and post- processing surrounding the handling of lifecycle events led to a different `poll_events()` API.
The existing Android backend for winit also appeared to have a rather complex event polling scheme which I was keen to simplify and make more comparable to the Linux mio/epoll based backend where there would be a very clear, single place where the mainloop would block waiting for events.
When I went further and added support for saving and restoring application state I found that it worked nicely to expose this via a transient `StateSaver` and `StateLoader` that's passed as part of the `SaveState` and `Resume` events, which was also a further change compared to `ndk-glue`.
This crate does integrate with `ndk-context` like `ndk-glue` does so that other crates that just need access to the JVM and/or Activity object from Rust can work in the same way.
Input handling is notably different between `NativeActivity` (which is based on `AInputQueue`) and `GameActivity` that does its own double buffering of key and motion events. As much as possible this crate provides an API that is compatible (the `MotionEvent` and `KeyEvent` APIs are almost identical) but it doesn't track any motion history data automatically and provides a different `swap_input_buffers` API for reading events. As an optimization `GameActivity` minimizes what axis are captured for pointer events and so there are also additional APIs exposed for applications to explicitly opt-in to additional axis values.
# Why not pure Rust?
One of the appeals (imho) of the AGDK project was that they are maintaining native Android libraries that look like they could be generally useful for native Rust apps (especially game engines) and even though they are C/C++ libraries that could theoretically be re-written in pure Rust it seems more worthwhile / practical to first try and leverage these libraries directly before considering whether it makes sense to re-implement any of them.
This crate uses the upstream glue layer written in C/C++ and provides a small Rust API on top for ergonomics. This way it's hopefully practical to keep in sync with upstream changes and bug fixes and to benefit from upstream testing.
The C/C++ GameActivity / android_native_app_glue code isn't _that_ complex and could well be re-implemented in Rust at some point, although it's not clear how beneficial it would be. I would note that `ndk-glue` did go down the route of re-implementing the glue layer for `NativeActivity` purely in Rust but I wasn't confident about it's synchronization model is correct which imho highlights that the code should only be re-written if there are some clear technical benefits. (See here for more discussion: https://github.com/rust-windowing/winit/issues/2293)
# Synchronizing with Upstream...
Upstream distribute `android_native_app_glue.c` and `GameActivity.cpp` code as a "prefab" that is bundled as part of a `GameActivity-release.aar` archive. The idea is that it's a build system agnostic way of bundling native glue code with archives that build systems can extract the code via a command line tool, along with some metadata to describe how it should be compiled - though tbh it feels over complicated and not very practical here.
It's fairly easy to extract the C/C++ files and just integrate them in a way that suits Rust / Cargo better.
`.aar` files are simply zip archives that can be unpacked and the files under `prefab/modules/game-activity/include` can be moved to `csrc/` in this repo, which will then be built by `build.rs` via the `cc` crate.
The easiest way I found to get to the `GameActivity-release.aar` is to download the "express" agdk-libraries release from https://developer.android.com/games/agdk/download, and you should find `GameActivity-release.aar` at the top level of the archive after unpacking.
The git repo for the source code can be found here: https://android.googlesource.com/platform/frameworks/opt/gamesdk/ with the prefab code under `GameActivity/prefab-src/modules/game-activity/include` - though it may be best to synchronize with official releases.
## Minor modifications
There are a few C symbols that need to be exported from the cdylib that's built for GameActivity to load at runtime but Rust/Cargo doesn't support compiling C/C++ code in a way that can export these symbols directly and we instead have to export wrappers from Rust code.
At the bottom of GameActivity.cpp then `Java_com_google_androidgamesdk_GameActivity_loadNativeCode` should be given a `_C` suffix like `Java_com_google_androidgamesdk_GameActivity_loadNativeCode_C`
At the bottom of `android_native_app_glue.c` and `android_native_app_glue.h` `GameActivity_onCreate` should also be given a `_C` suffix like `GameActivity_onCreate_C`
Since we want to call the application's main function from Rust after initializing our own `AndroidApp` state, but we want to let applications use the same `android_main` symbol name then `android_main` should be renamed to `_rust_glue_entry` in `android_native_app_glue.h` and `android_native_app_glue.c`
One limitation discovered with the input API provided by GameActivity was that it doesn't capture keyboard scan codes which are required to properly implement a winit backend. These were the changes made to enable scan code capture:
```diff
commit 7f7df6a670d5d6dfaa315bc956210108caac57f3 (HEAD -> master)
Author: Robert Bragg <robert@sixbynine.org>
Date: Sun May 8 02:41:48 2022 +0100
GameActivity PATCH: capture KeyEvent scanCode
diff --git a/game-activity/csrc/game-activity/GameActivity.cpp b/game-activity/csrc/game-activity/GameActivity.cpp
index 2b37365..57bc4e1 100644
--- a/game-activity/csrc/game-activity/GameActivity.cpp
+++ b/game-activity/csrc/game-activity/GameActivity.cpp
@@ -1015,6 +1015,7 @@ static struct {
jmethodID getModifiers;
jmethodID getRepeatCount;
jmethodID getKeyCode;
+ jmethodID getScanCode;
} gKeyEventClassInfo;
extern "C" void GameActivityKeyEvent_fromJava(JNIEnv *env, jobject keyEvent,
@@ -1046,6 +1047,8 @@ extern "C" void GameActivityKeyEvent_fromJava(JNIEnv *env, jobject keyEvent,
env->GetMethodID(keyEventClass, "getRepeatCount", "()I");
gKeyEventClassInfo.getKeyCode =
env->GetMethodID(keyEventClass, "getKeyCode", "()I");
+ gKeyEventClassInfo.getScanCode =
+ env->GetMethodID(keyEventClass, "getScanCode", "()I");
gKeyEventClassInfoInitialized = true;
}
@@ -1070,7 +1073,9 @@ extern "C" void GameActivityKeyEvent_fromJava(JNIEnv *env, jobject keyEvent,
/*repeatCount=*/
env->CallIntMethod(keyEvent, gKeyEventClassInfo.getRepeatCount),
/*keyCode=*/
- env->CallIntMethod(keyEvent, gKeyEventClassInfo.getKeyCode)};
+ env->CallIntMethod(keyEvent, gKeyEventClassInfo.getKeyCode),
+ /*scanCode=*/
+ env->CallIntMethod(keyEvent, gKeyEventClassInfo.getScanCode)};
}
static bool onTouchEvent_native(JNIEnv *env, jobject javaGameActivity,
diff --git a/game-activity/csrc/game-activity/GameActivity.h b/game-activity/csrc/game-activity/GameActivity.h
index da102bc..7a5645c 100644
--- a/game-activity/csrc/game-activity/GameActivity.h
+++ b/game-activity/csrc/game-activity/GameActivity.h
@@ -262,6 +262,7 @@ typedef struct GameActivityKeyEvent {
int32_t modifiers;
int32_t repeatCount;
int32_t keyCode;
+ int32_t scanCode;
} GameActivityKeyEvent;
/**
```
## Generate Rust bindings
Since we know we only care about android build targets then to simplify the build we pre-generate Rust bindings for the C/C++ headers using bindgen via `generate-bindings.sh`
Install bindgen via `cargo install bindgen`
`export ANDROID_NDK_ROOT=/path/to/ndk` so that `generate-bindings.sh` can find suitable sysroot headers.
Run `./generate-bindings.sh` from the top of the repo after putting the latest prefab source/headers under `csrc/`
-23
View File
@@ -1,23 +0,0 @@
fn main() {
cc::Build::new()
.cpp(true)
.include("csrc")
.file("csrc/game-activity/GameActivity.cpp")
.extra_warnings(false)
.cpp_link_stdlib("c++_static")
.compile("libgame_activity.a");
cc::Build::new()
.cpp(true)
.include("csrc")
.file("csrc/game-text-input/gametextinput.cpp")
.cpp_link_stdlib("c++_static")
.compile("libgame_text_input.a");
cc::Build::new()
.include("csrc")
.include("csrc/game-activity/native_app_glue")
.file("csrc/game-activity/native_app_glue/android_native_app_glue.c")
.extra_warnings(false)
.cpp_link_stdlib("c++_static")
.compile("libnative_app_glue.a");
}
File diff suppressed because it is too large Load Diff
@@ -1,819 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @addtogroup GameActivity Game Activity
* The interface to use GameActivity.
* @{
*/
/**
* @file GameActivity.h
*/
#ifndef ANDROID_GAME_SDK_GAME_ACTIVITY_H
#define ANDROID_GAME_SDK_GAME_ACTIVITY_H
#include <android/asset_manager.h>
#include <android/input.h>
#include <android/native_window.h>
#include <android/rect.h>
#include <jni.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/types.h>
#include "game-text-input/gametextinput.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* {@link GameActivityCallbacks}
*/
struct GameActivityCallbacks;
/**
* This structure defines the native side of an android.app.GameActivity.
* It is created by the framework, and handed to the application's native
* code as it is being launched.
*/
typedef struct GameActivity {
/**
* Pointer to the callback function table of the native application.
* You can set the functions here to your own callbacks. The callbacks
* pointer itself here should not be changed; it is allocated and managed
* for you by the framework.
*/
struct GameActivityCallbacks* callbacks;
/**
* The global handle on the process's Java VM.
*/
JavaVM* vm;
/**
* JNI context for the main thread of the app. Note that this field
* can ONLY be used from the main thread of the process; that is, the
* thread that calls into the GameActivityCallbacks.
*/
JNIEnv* env;
/**
* The GameActivity object handle.
*/
jobject javaGameActivity;
/**
* Path to this application's internal data directory.
*/
const char* internalDataPath;
/**
* Path to this application's external (removable/mountable) data directory.
*/
const char* externalDataPath;
/**
* The platform's SDK version code.
*/
int32_t sdkVersion;
/**
* This is the native instance of the application. It is not used by
* the framework, but can be set by the application to its own instance
* state.
*/
void* instance;
/**
* Pointer to the Asset Manager instance for the application. The
* application uses this to access binary assets bundled inside its own .apk
* file.
*/
AAssetManager* assetManager;
/**
* Available starting with Honeycomb: path to the directory containing
* the application's OBB files (if any). If the app doesn't have any
* OBB files, this directory may not exist.
*/
const char* obbPath;
} GameActivity;
/**
* The maximum number of axes supported in an Android MotionEvent.
* See https://developer.android.com/ndk/reference/group/input.
*/
#define GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT 48
/**
* \brief Describe information about a pointer, found in a
* GameActivityMotionEvent.
*
* You can read values directly from this structure, or use helper functions
* (`GameActivityPointerAxes_getX`, `GameActivityPointerAxes_getY` and
* `GameActivityPointerAxes_getAxisValue`).
*
* The X axis and Y axis are enabled by default but any other axis that you want
* to read **must** be enabled first, using
* `GameActivityPointerAxes_enableAxis`.
*
* \see GameActivityMotionEvent
*/
typedef struct GameActivityPointerAxes {
int32_t id;
float axisValues[GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT];
float rawX;
float rawY;
} GameActivityPointerAxes;
typedef struct GameActivityHistoricalPointerAxes {
int64_t eventTime;
float axisValues[GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT];
} GameActivityHistoricalPointerAxes;
/** \brief Get the current X coordinate of the pointer. */
inline float GameActivityPointerAxes_getX(
const GameActivityPointerAxes* pointerInfo) {
return pointerInfo->axisValues[AMOTION_EVENT_AXIS_X];
}
/** \brief Get the current Y coordinate of the pointer. */
inline float GameActivityPointerAxes_getY(
const GameActivityPointerAxes* pointerInfo) {
return pointerInfo->axisValues[AMOTION_EVENT_AXIS_Y];
}
/**
* \brief Enable the specified axis, so that its value is reported in the
* GameActivityPointerAxes structures stored in a motion event.
*
* You must enable any axis that you want to read, apart from
* `AMOTION_EVENT_AXIS_X` and `AMOTION_EVENT_AXIS_Y` that are enabled by
* default.
*
* If the axis index is out of range, nothing is done.
*/
void GameActivityPointerAxes_enableAxis(int32_t axis);
/**
* \brief Disable the specified axis. Its value won't be reported in the
* GameActivityPointerAxes structures stored in a motion event anymore.
*
* Apart from X and Y, any axis that you want to read **must** be enabled first,
* using `GameActivityPointerAxes_enableAxis`.
*
* If the axis index is out of range, nothing is done.
*/
void GameActivityPointerAxes_disableAxis(int32_t axis);
/**
* \brief Enable the specified axis, so that its value is reported in the
* GameActivityHistoricalPointerAxes structures associated with a motion event.
*
* You must enable any axis that you want to read (no axes are enabled by
* default).
*
* If the axis index is out of range, nothing is done.
*/
void GameActivityHistoricalPointerAxes_enableAxis(int32_t axis);
/**
* \brief Disable the specified axis. Its value won't be reported in the
* GameActivityHistoricalPointerAxes structures associated with motion events
* anymore.
*
* If the axis index is out of range, nothing is done.
*/
void GameActivityHistoricalPointerAxes_disableAxis(int32_t axis);
/**
* \brief Get the value of the requested axis.
*
* Apart from X and Y, any axis that you want to read **must** be enabled first,
* using `GameActivityPointerAxes_enableAxis`.
*
* Find the valid enums for the axis (`AMOTION_EVENT_AXIS_X`,
* `AMOTION_EVENT_AXIS_Y`, `AMOTION_EVENT_AXIS_PRESSURE`...)
* in https://developer.android.com/ndk/reference/group/input.
*
* @param pointerInfo The structure containing information about the pointer,
* obtained from GameActivityMotionEvent.
* @param axis The axis to get the value from
* @return The value of the axis, or 0 if the axis is invalid or was not
* enabled.
*/
inline float GameActivityPointerAxes_getAxisValue(
GameActivityPointerAxes* pointerInfo, int32_t axis) {
if (axis < 0 || axis >= GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT) {
return 0;
}
return pointerInfo->axisValues[axis];
}
/**
* The maximum number of pointers returned inside a motion event.
*/
#if (defined GAMEACTIVITY_MAX_NUM_POINTERS_IN_MOTION_EVENT_OVERRIDE)
#define GAMEACTIVITY_MAX_NUM_POINTERS_IN_MOTION_EVENT \
GAMEACTIVITY_MAX_NUM_POINTERS_IN_MOTION_EVENT_OVERRIDE
#else
#define GAMEACTIVITY_MAX_NUM_POINTERS_IN_MOTION_EVENT 8
#endif
/**
* The maximum number of historic samples associated with a single motion event.
*/
#if (defined GAMEACTIVITY_MAX_NUM_HISTORICAL_IN_MOTION_EVENT_OVERRIDE)
#define GAMEACTIVITY_MAX_NUM_HISTORICAL_IN_MOTION_EVENT \
GAMEACTIVITY_MAX_NUM_HISTORICAL_IN_MOTION_EVENT_OVERRIDE
#else
#define GAMEACTIVITY_MAX_NUM_HISTORICAL_IN_MOTION_EVENT 8
#endif
/**
* \brief Describe a motion event that happened on the GameActivity SurfaceView.
*
* This is 1:1 mapping to the information contained in a Java `MotionEvent`
* (see https://developer.android.com/reference/android/view/MotionEvent).
*/
typedef struct GameActivityMotionEvent {
int32_t deviceId;
int32_t source;
int32_t action;
int64_t eventTime;
int64_t downTime;
int32_t flags;
int32_t metaState;
int32_t actionButton;
int32_t buttonState;
int32_t classification;
int32_t edgeFlags;
uint32_t pointerCount;
GameActivityPointerAxes
pointers[GAMEACTIVITY_MAX_NUM_POINTERS_IN_MOTION_EVENT];
float precisionX;
float precisionY;
int16_t historicalStart;
// Note the actual buffer of historical data has a length of
// pointerCount * historicalCount, since the historical axis
// data is per-pointer.
int16_t historicalCount;
} GameActivityMotionEvent;
/**
* \brief Describe a key event that happened on the GameActivity SurfaceView.
*
* This is 1:1 mapping to the information contained in a Java `KeyEvent`
* (see https://developer.android.com/reference/android/view/KeyEvent).
*/
typedef struct GameActivityKeyEvent {
int32_t deviceId;
int32_t source;
int32_t action;
int64_t eventTime;
int64_t downTime;
int32_t flags;
int32_t metaState;
int32_t modifiers;
int32_t repeatCount;
int32_t keyCode;
int32_t scanCode;
} GameActivityKeyEvent;
/**
* A function the user should call from their callback with the data, its length
* and the library- supplied context.
*/
typedef void (*SaveInstanceStateRecallback)(const char* bytes, int len,
void* context);
/**
* These are the callbacks the framework makes into a native application.
* All of these callbacks happen on the main thread of the application.
* By default, all callbacks are NULL; set to a pointer to your own function
* to have it called.
*/
typedef struct GameActivityCallbacks {
/**
* GameActivity has started. See Java documentation for Activity.onStart()
* for more information.
*/
void (*onStart)(GameActivity* activity);
/**
* GameActivity has resumed. See Java documentation for Activity.onResume()
* for more information.
*/
void (*onResume)(GameActivity* activity);
/**
* The framework is asking GameActivity to save its current instance state.
* See the Java documentation for Activity.onSaveInstanceState() for more
* information. The user should call the recallback with their data, its
* length and the provided context; they retain ownership of the data. Note
* that the saved state will be persisted, so it can not contain any active
* entities (pointers to memory, file descriptors, etc).
*/
void (*onSaveInstanceState)(GameActivity* activity,
SaveInstanceStateRecallback recallback,
void* context);
/**
* GameActivity has paused. See Java documentation for Activity.onPause()
* for more information.
*/
void (*onPause)(GameActivity* activity);
/**
* GameActivity has stopped. See Java documentation for Activity.onStop()
* for more information.
*/
void (*onStop)(GameActivity* activity);
/**
* GameActivity is being destroyed. See Java documentation for
* Activity.onDestroy() for more information.
*/
void (*onDestroy)(GameActivity* activity);
/**
* Focus has changed in this GameActivity's window. This is often used,
* for example, to pause a game when it loses input focus.
*/
void (*onWindowFocusChanged)(GameActivity* activity, bool hasFocus);
/**
* The drawing window for this native activity has been created. You
* can use the given native window object to start drawing.
*/
void (*onNativeWindowCreated)(GameActivity* activity,
ANativeWindow* window);
/**
* The drawing window for this native activity has been resized. You should
* retrieve the new size from the window and ensure that your rendering in
* it now matches.
*/
void (*onNativeWindowResized)(GameActivity* activity, ANativeWindow* window,
int32_t newWidth, int32_t newHeight);
/**
* The drawing window for this native activity needs to be redrawn. To
* avoid transient artifacts during screen changes (such resizing after
* rotation), applications should not return from this function until they
* have finished drawing their window in its current state.
*/
void (*onNativeWindowRedrawNeeded)(GameActivity* activity,
ANativeWindow* window);
/**
* The drawing window for this native activity is going to be destroyed.
* You MUST ensure that you do not touch the window object after returning
* from this function: in the common case of drawing to the window from
* another thread, that means the implementation of this callback must
* properly synchronize with the other thread to stop its drawing before
* returning from here.
*/
void (*onNativeWindowDestroyed)(GameActivity* activity,
ANativeWindow* window);
/**
* The current device AConfiguration has changed. The new configuration can
* be retrieved from assetManager.
*/
void (*onConfigurationChanged)(GameActivity* activity);
/**
* The system is running low on memory. Use this callback to release
* resources you do not need, to help the system avoid killing more
* important processes.
*/
void (*onTrimMemory)(GameActivity* activity, int level);
/**
* Callback called for every MotionEvent done on the GameActivity
* SurfaceView. Ownership of `event` is maintained by the library and it is
* only valid during the callback.
*/
bool (*onTouchEvent)(GameActivity* activity,
const GameActivityMotionEvent* event,
const GameActivityHistoricalPointerAxes* historical,
int historicalLen);
/**
* Callback called for every key down event on the GameActivity SurfaceView.
* Ownership of `event` is maintained by the library and it is only valid
* during the callback.
*/
bool (*onKeyDown)(GameActivity* activity,
const GameActivityKeyEvent* event);
/**
* Callback called for every key up event on the GameActivity SurfaceView.
* Ownership of `event` is maintained by the library and it is only valid
* during the callback.
*/
bool (*onKeyUp)(GameActivity* activity, const GameActivityKeyEvent* event);
/**
* Callback called for every soft-keyboard text input event.
* Ownership of `state` is maintained by the library and it is only valid
* during the callback.
*/
void (*onTextInputEvent)(GameActivity* activity,
const GameTextInputState* state);
/**
* Callback called when WindowInsets of the main app window have changed.
* Call GameActivity_getWindowInsets to retrieve the insets themselves.
*/
void (*onWindowInsetsChanged)(GameActivity* activity);
} GameActivityCallbacks;
/**
* \brief Convert a Java `MotionEvent` to a `GameActivityMotionEvent`.
*
* This is done automatically by the GameActivity: see `onTouchEvent` to set
* a callback to consume the received events.
* This function can be used if you re-implement events handling in your own
* activity. On return, the out_event->historicalStart will be zero, and should
* be updated to index into whatever buffer out_historical is copied.
* On return the length of out_historical is
* (out_event->pointerCount x out_event->historicalCount) and is in a
* pointer-major order (i.e. all axis for a pointer are contiguous)
* Ownership of out_event is maintained by the caller.
*/
int GameActivityMotionEvent_fromJava(JNIEnv* env, jobject motionEvent,
GameActivityMotionEvent* out_event,
GameActivityHistoricalPointerAxes *out_historical);
/**
* \brief Convert a Java `KeyEvent` to a `GameActivityKeyEvent`.
*
* This is done automatically by the GameActivity: see `onKeyUp` and `onKeyDown`
* to set a callback to consume the received events.
* This function can be used if you re-implement events handling in your own
* activity.
* Ownership of out_event is maintained by the caller.
*/
void GameActivityKeyEvent_fromJava(JNIEnv* env, jobject motionEvent,
GameActivityKeyEvent* out_event);
/**
* This is the function that must be in the native code to instantiate the
* application's native activity. It is called with the activity instance (see
* above); if the code is being instantiated from a previously saved instance,
* the savedState will be non-NULL and point to the saved data. You must make
* any copy of this data you need -- it will be released after you return from
* this function.
*/
typedef void GameActivity_createFunc(GameActivity* activity, void* savedState,
size_t savedStateSize);
/**
* The name of the function that NativeInstance looks for when launching its
* native code. This is the default function that is used, you can specify
* "android.app.func_name" string meta-data in your manifest to use a different
* function.
*/
extern GameActivity_createFunc GameActivity_onCreate;
/**
* Finish the given activity. Its finish() method will be called, causing it
* to be stopped and destroyed. Note that this method can be called from
* *any* thread; it will send a message to the main thread of the process
* where the Java finish call will take place.
*/
void GameActivity_finish(GameActivity* activity);
/**
* Flags for GameActivity_setWindowFlags,
* as per the Java API at android.view.WindowManager.LayoutParams.
*/
enum GameActivitySetWindowFlags {
/**
* As long as this window is visible to the user, allow the lock
* screen to activate while the screen is on. This can be used
* independently, or in combination with {@link
* GAMEACTIVITY_FLAG_KEEP_SCREEN_ON} and/or {@link
* GAMEACTIVITY_FLAG_SHOW_WHEN_LOCKED}
*/
GAMEACTIVITY_FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001,
/** Everything behind this window will be dimmed. */
GAMEACTIVITY_FLAG_DIM_BEHIND = 0x00000002,
/**
* Blur everything behind this window.
* @deprecated Blurring is no longer supported.
*/
GAMEACTIVITY_FLAG_BLUR_BEHIND = 0x00000004,
/**
* This window won't ever get key input focus, so the
* user can not send key or other button events to it. Those will
* instead go to whatever focusable window is behind it. This flag
* will also enable {@link GAMEACTIVITY_FLAG_NOT_TOUCH_MODAL} whether or not
* that is explicitly set.
*
* Setting this flag also implies that the window will not need to
* interact with
* a soft input method, so it will be Z-ordered and positioned
* independently of any active input method (typically this means it
* gets Z-ordered on top of the input method, so it can use the full
* screen for its content and cover the input method if needed. You
* can use {@link GAMEACTIVITY_FLAG_ALT_FOCUSABLE_IM} to modify this
* behavior.
*/
GAMEACTIVITY_FLAG_NOT_FOCUSABLE = 0x00000008,
/** This window can never receive touch events. */
GAMEACTIVITY_FLAG_NOT_TOUCHABLE = 0x00000010,
/**
* Even when this window is focusable (its
* {@link GAMEACTIVITY_FLAG_NOT_FOCUSABLE} is not set), allow any pointer
* events outside of the window to be sent to the windows behind it.
* Otherwise it will consume all pointer events itself, regardless of
* whether they are inside of the window.
*/
GAMEACTIVITY_FLAG_NOT_TOUCH_MODAL = 0x00000020,
/**
* When set, if the device is asleep when the touch
* screen is pressed, you will receive this first touch event. Usually
* the first touch event is consumed by the system since the user can
* not see what they are pressing on.
*
* @deprecated This flag has no effect.
*/
GAMEACTIVITY_FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040,
/**
* As long as this window is visible to the user, keep
* the device's screen turned on and bright.
*/
GAMEACTIVITY_FLAG_KEEP_SCREEN_ON = 0x00000080,
/**
* Place the window within the entire screen, ignoring
* decorations around the border (such as the status bar). The
* window must correctly position its contents to take the screen
* decoration into account.
*/
GAMEACTIVITY_FLAG_LAYOUT_IN_SCREEN = 0x00000100,
/** Allows the window to extend outside of the screen. */
GAMEACTIVITY_FLAG_LAYOUT_NO_LIMITS = 0x00000200,
/**
* Hide all screen decorations (such as the status
* bar) while this window is displayed. This allows the window to
* use the entire display space for itself -- the status bar will
* be hidden when an app window with this flag set is on the top
* layer. A fullscreen window will ignore a value of {@link
* GAMEACTIVITY_SOFT_INPUT_ADJUST_RESIZE}; the window will stay
* fullscreen and will not resize.
*/
GAMEACTIVITY_FLAG_FULLSCREEN = 0x00000400,
/**
* Override {@link GAMEACTIVITY_FLAG_FULLSCREEN} and force the
* screen decorations (such as the status bar) to be shown.
*/
GAMEACTIVITY_FLAG_FORCE_NOT_FULLSCREEN = 0x00000800,
/**
* Turn on dithering when compositing this window to
* the screen.
* @deprecated This flag is no longer used.
*/
GAMEACTIVITY_FLAG_DITHER = 0x00001000,
/**
* Treat the content of the window as secure, preventing
* it from appearing in screenshots or from being viewed on non-secure
* displays.
*/
GAMEACTIVITY_FLAG_SECURE = 0x00002000,
/**
* A special mode where the layout parameters are used
* to perform scaling of the surface when it is composited to the
* screen.
*/
GAMEACTIVITY_FLAG_SCALED = 0x00004000,
/**
* Intended for windows that will often be used when the user is
* holding the screen against their face, it will aggressively
* filter the event stream to prevent unintended presses in this
* situation that may not be desired for a particular window, when
* such an event stream is detected, the application will receive
* a {@link AMOTION_EVENT_ACTION_CANCEL} to indicate this so
* applications can handle this accordingly by taking no action on
* the event until the finger is released.
*/
GAMEACTIVITY_FLAG_IGNORE_CHEEK_PRESSES = 0x00008000,
/**
* A special option only for use in combination with
* {@link GAMEACTIVITY_FLAG_LAYOUT_IN_SCREEN}. When requesting layout in
* the screen your window may appear on top of or behind screen decorations
* such as the status bar. By also including this flag, the window
* manager will report the inset rectangle needed to ensure your
* content is not covered by screen decorations.
*/
GAMEACTIVITY_FLAG_LAYOUT_INSET_DECOR = 0x00010000,
/**
* Invert the state of {@link GAMEACTIVITY_FLAG_NOT_FOCUSABLE} with
* respect to how this window interacts with the current method.
* That is, if FLAG_NOT_FOCUSABLE is set and this flag is set,
* then the window will behave as if it needs to interact with the
* input method and thus be placed behind/away from it; if {@link
* GAMEACTIVITY_FLAG_NOT_FOCUSABLE} is not set and this flag is set,
* then the window will behave as if it doesn't need to interact
* with the input method and can be placed to use more space and
* cover the input method.
*/
GAMEACTIVITY_FLAG_ALT_FOCUSABLE_IM = 0x00020000,
/**
* If you have set {@link GAMEACTIVITY_FLAG_NOT_TOUCH_MODAL}, you
* can set this flag to receive a single special MotionEvent with
* the action
* {@link AMOTION_EVENT_ACTION_OUTSIDE} for
* touches that occur outside of your window. Note that you will not
* receive the full down/move/up gesture, only the location of the
* first down as an {@link AMOTION_EVENT_ACTION_OUTSIDE}.
*/
GAMEACTIVITY_FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000,
/**
* Special flag to let windows be shown when the screen
* is locked. This will let application windows take precedence over
* key guard or any other lock screens. Can be used with
* {@link GAMEACTIVITY_FLAG_KEEP_SCREEN_ON} to turn screen on and display
* windows directly before showing the key guard window. Can be used with
* {@link GAMEACTIVITY_FLAG_DISMISS_KEYGUARD} to automatically fully
* dismisss non-secure keyguards. This flag only applies to the top-most
* full-screen window.
*/
GAMEACTIVITY_FLAG_SHOW_WHEN_LOCKED = 0x00080000,
/**
* Ask that the system wallpaper be shown behind
* your window. The window surface must be translucent to be able
* to actually see the wallpaper behind it; this flag just ensures
* that the wallpaper surface will be there if this window actually
* has translucent regions.
*/
GAMEACTIVITY_FLAG_SHOW_WALLPAPER = 0x00100000,
/**
* When set as a window is being added or made
* visible, once the window has been shown then the system will
* poke the power manager's user activity (as if the user had woken
* up the device) to turn the screen on.
*/
GAMEACTIVITY_FLAG_TURN_SCREEN_ON = 0x00200000,
/**
* When set the window will cause the keyguard to
* be dismissed, only if it is not a secure lock keyguard. Because such
* a keyguard is not needed for security, it will never re-appear if
* the user navigates to another window (in contrast to
* {@link GAMEACTIVITY_FLAG_SHOW_WHEN_LOCKED}, which will only temporarily
* hide both secure and non-secure keyguards but ensure they reappear
* when the user moves to another UI that doesn't hide them).
* If the keyguard is currently active and is secure (requires an
* unlock pattern) than the user will still need to confirm it before
* seeing this window, unless {@link GAMEACTIVITY_FLAG_SHOW_WHEN_LOCKED} has
* also been set.
*/
GAMEACTIVITY_FLAG_DISMISS_KEYGUARD = 0x00400000,
};
/**
* Change the window flags of the given activity. Calls getWindow().setFlags()
* of the given activity.
* Note that some flags must be set before the window decoration is created,
* see
* https://developer.android.com/reference/android/view/Window#setFlags(int,%20int).
* Note also that this method can be called from
* *any* thread; it will send a message to the main thread of the process
* where the Java finish call will take place.
*/
void GameActivity_setWindowFlags(GameActivity* activity, uint32_t addFlags,
uint32_t removeFlags);
/**
* Flags for GameActivity_showSoftInput; see the Java InputMethodManager
* API for documentation.
*/
enum GameActivityShowSoftInputFlags {
/**
* Implicit request to show the input window, not as the result
* of a direct request by the user.
*/
GAMEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT = 0x0001,
/**
* The user has forced the input method open (such as by
* long-pressing menu) so it should not be closed until they
* explicitly do so.
*/
GAMEACTIVITY_SHOW_SOFT_INPUT_FORCED = 0x0002,
};
/**
* Show the IME while in the given activity. Calls
* InputMethodManager.showSoftInput() for the given activity. Note that this
* method can be called from *any* thread; it will send a message to the main
* thread of the process where the Java call will take place.
*/
void GameActivity_showSoftInput(GameActivity* activity, uint32_t flags);
/**
* Set the text entry state (see documentation of the GameTextInputState struct
* in the Game Text Input library reference).
*
* Ownership of the state is maintained by the caller.
*/
void GameActivity_setTextInputState(GameActivity* activity,
const GameTextInputState* state);
/**
* Get the last-received text entry state (see documentation of the
* GameTextInputState struct in the Game Text Input library reference).
*
*/
void GameActivity_getTextInputState(GameActivity* activity,
GameTextInputGetStateCallback callback,
void* context);
/**
* Get a pointer to the GameTextInput library instance.
*/
GameTextInput* GameActivity_getTextInput(const GameActivity* activity);
/**
* Flags for GameActivity_hideSoftInput; see the Java InputMethodManager
* API for documentation.
*/
enum GameActivityHideSoftInputFlags {
/**
* The soft input window should only be hidden if it was not
* explicitly shown by the user.
*/
GAMEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY = 0x0001,
/**
* The soft input window should normally be hidden, unless it was
* originally shown with {@link GAMEACTIVITY_SHOW_SOFT_INPUT_FORCED}.
*/
GAMEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS = 0x0002,
};
/**
* Hide the IME while in the given activity. Calls
* InputMethodManager.hideSoftInput() for the given activity. Note that this
* method can be called from *any* thread; it will send a message to the main
* thread of the process where the Java finish call will take place.
*/
void GameActivity_hideSoftInput(GameActivity* activity, uint32_t flags);
/**
* Get the current window insets of the particular component. See
* https://developer.android.com/reference/androidx/core/view/WindowInsetsCompat.Type
* for more details.
* You can use these insets to influence what you show on the screen.
*/
void GameActivity_getWindowInsets(GameActivity* activity,
GameCommonInsetsType type, ARect* insets);
/**
* Set options on how the IME behaves when it is requested for text input.
* See
* https://developer.android.com/reference/android/view/inputmethod/EditorInfo
* for the meaning of inputType, actionId and imeOptions.
*
* Note that this function will attach the current thread to the JVM if it is
* not already attached, so the caller must detach the thread from the JVM
* before the thread is destroyed using DetachCurrentThread.
*/
void GameActivity_setImeEditorInfo(GameActivity* activity, int inputType,
int actionId, int imeOptions);
#ifdef __cplusplus
}
#endif
/** @} */
#endif // ANDROID_GAME_SDK_GAME_ACTIVITY_H
@@ -1,606 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "android_native_app_glue.h"
#include <android/log.h>
#include <errno.h>
#include <jni.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define LOGI(...) \
((void)__android_log_print(ANDROID_LOG_INFO, "threaded_app", __VA_ARGS__))
#define LOGE(...) \
((void)__android_log_print(ANDROID_LOG_ERROR, "threaded_app", __VA_ARGS__))
#define LOGW(...) \
((void)__android_log_print(ANDROID_LOG_WARN, "threaded_app", __VA_ARGS__))
#define LOGW_ONCE(...) \
do { \
static bool alogw_once##__FILE__##__LINE__##__ = true; \
if (alogw_once##__FILE__##__LINE__##__) { \
alogw_once##__FILE__##__LINE__##__ = false; \
LOGW(__VA_ARGS__); \
} \
} while (0)
/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
#define LOGV(...) \
((void)__android_log_print(ANDROID_LOG_VERBOSE, "threaded_app", \
__VA_ARGS__))
#else
#define LOGV(...) ((void)0)
#endif
static void free_saved_state(struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
if (android_app->savedState != NULL) {
free(android_app->savedState);
android_app->savedState = NULL;
android_app->savedStateSize = 0;
}
pthread_mutex_unlock(&android_app->mutex);
}
int8_t android_app_read_cmd(struct android_app* android_app) {
int8_t cmd;
if (read(android_app->msgread, &cmd, sizeof(cmd)) != sizeof(cmd)) {
LOGE("No data on command pipe!");
return -1;
}
if (cmd == APP_CMD_SAVE_STATE) free_saved_state(android_app);
return cmd;
}
static void print_cur_config(struct android_app* android_app) {
char lang[2], country[2];
AConfiguration_getLanguage(android_app->config, lang);
AConfiguration_getCountry(android_app->config, country);
LOGV(
"Config: mcc=%d mnc=%d lang=%c%c cnt=%c%c orien=%d touch=%d dens=%d "
"keys=%d nav=%d keysHid=%d navHid=%d sdk=%d size=%d long=%d "
"modetype=%d modenight=%d",
AConfiguration_getMcc(android_app->config),
AConfiguration_getMnc(android_app->config), lang[0], lang[1],
country[0], country[1],
AConfiguration_getOrientation(android_app->config),
AConfiguration_getTouchscreen(android_app->config),
AConfiguration_getDensity(android_app->config),
AConfiguration_getKeyboard(android_app->config),
AConfiguration_getNavigation(android_app->config),
AConfiguration_getKeysHidden(android_app->config),
AConfiguration_getNavHidden(android_app->config),
AConfiguration_getSdkVersion(android_app->config),
AConfiguration_getScreenSize(android_app->config),
AConfiguration_getScreenLong(android_app->config),
AConfiguration_getUiModeType(android_app->config),
AConfiguration_getUiModeNight(android_app->config));
}
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case UNUSED_APP_CMD_INPUT_CHANGED:
LOGV("UNUSED_APP_CMD_INPUT_CHANGED");
// Do nothing. This can be used in the future to handle AInputQueue
// natively, like done in NativeActivity.
break;
case APP_CMD_INIT_WINDOW:
LOGV("APP_CMD_INIT_WINDOW");
pthread_mutex_lock(&android_app->mutex);
android_app->window = android_app->pendingWindow;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW");
pthread_cond_broadcast(&android_app->cond);
break;
case APP_CMD_RESUME:
case APP_CMD_START:
case APP_CMD_PAUSE:
case APP_CMD_STOP:
LOGV("activityState=%d", cmd);
pthread_mutex_lock(&android_app->mutex);
android_app->activityState = cmd;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_CONFIG_CHANGED:
LOGV("APP_CMD_CONFIG_CHANGED");
AConfiguration_fromAssetManager(
android_app->config, android_app->activity->assetManager);
print_cur_config(android_app);
break;
case APP_CMD_DESTROY:
LOGV("APP_CMD_DESTROY");
android_app->destroyRequested = 1;
break;
}
}
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW");
pthread_mutex_lock(&android_app->mutex);
android_app->window = NULL;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_SAVE_STATE:
LOGV("APP_CMD_SAVE_STATE");
pthread_mutex_lock(&android_app->mutex);
android_app->stateSaved = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_RESUME:
free_saved_state(android_app);
break;
}
}
void app_dummy() {}
static void android_app_destroy(struct android_app* android_app) {
LOGV("android_app_destroy!");
free_saved_state(android_app);
pthread_mutex_lock(&android_app->mutex);
AConfiguration_delete(android_app->config);
android_app->destroyed = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
// Can't touch android_app object after this.
}
static void process_cmd(struct android_app* app,
struct android_poll_source* source) {
int8_t cmd = android_app_read_cmd(app);
android_app_pre_exec_cmd(app, cmd);
if (app->onAppCmd != NULL) app->onAppCmd(app, cmd);
android_app_post_exec_cmd(app, cmd);
}
// This is run on a separate thread (i.e: not the main thread).
static void* android_app_entry(void* param) {
struct android_app* android_app = (struct android_app*)param;
LOGV("android_app_entry called");
android_app->config = AConfiguration_new();
LOGV("android_app = %p", android_app);
LOGV("config = %p", android_app->config);
LOGV("activity = %p", android_app->activity);
LOGV("assetmanager = %p", android_app->activity->assetManager);
AConfiguration_fromAssetManager(android_app->config,
android_app->activity->assetManager);
print_cur_config(android_app);
android_app->cmdPollSource.id = LOOPER_ID_MAIN;
android_app->cmdPollSource.app = android_app;
android_app->cmdPollSource.process = process_cmd;
ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN,
ALOOPER_EVENT_INPUT, NULL, &android_app->cmdPollSource);
android_app->looper = looper;
pthread_mutex_lock(&android_app->mutex);
android_app->running = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
_rust_glue_entry(android_app);
android_app_destroy(android_app);
return NULL;
}
// Codes from https://developer.android.com/reference/android/view/KeyEvent
#define KEY_EVENT_KEYCODE_VOLUME_DOWN 25
#define KEY_EVENT_KEYCODE_VOLUME_MUTE 164
#define KEY_EVENT_KEYCODE_VOLUME_UP 24
#define KEY_EVENT_KEYCODE_CAMERA 27
#define KEY_EVENT_KEYCODE_ZOOM_IN 168
#define KEY_EVENT_KEYCODE_ZOOM_OUT 169
// Double-buffer the key event filter to avoid race condition.
static bool default_key_filter(const GameActivityKeyEvent* event) {
// Ignore camera, volume, etc. buttons
return !(event->keyCode == KEY_EVENT_KEYCODE_VOLUME_DOWN ||
event->keyCode == KEY_EVENT_KEYCODE_VOLUME_MUTE ||
event->keyCode == KEY_EVENT_KEYCODE_VOLUME_UP ||
event->keyCode == KEY_EVENT_KEYCODE_CAMERA ||
event->keyCode == KEY_EVENT_KEYCODE_ZOOM_IN ||
event->keyCode == KEY_EVENT_KEYCODE_ZOOM_OUT);
}
// See
// https://developer.android.com/reference/android/view/InputDevice#SOURCE_TOUCHSCREEN
#define SOURCE_TOUCHSCREEN 0x00001002
static bool default_motion_filter(const GameActivityMotionEvent* event) {
// Ignore any non-touch events.
return event->source == SOURCE_TOUCHSCREEN;
}
// --------------------------------------------------------------------
// Native activity interaction (called from main thread)
// --------------------------------------------------------------------
static struct android_app* android_app_create(GameActivity* activity,
void* savedState,
size_t savedStateSize) {
// struct android_app* android_app = calloc(1, sizeof(struct android_app));
struct android_app* android_app =
(struct android_app*)malloc(sizeof(struct android_app));
memset(android_app, 0, sizeof(struct android_app));
android_app->activity = activity;
pthread_mutex_init(&android_app->mutex, NULL);
pthread_cond_init(&android_app->cond, NULL);
if (savedState != NULL) {
android_app->savedState = malloc(savedStateSize);
android_app->savedStateSize = savedStateSize;
memcpy(android_app->savedState, savedState, savedStateSize);
}
int msgpipe[2];
if (pipe(msgpipe)) {
LOGE("could not create pipe: %s", strerror(errno));
return NULL;
}
android_app->msgread = msgpipe[0];
android_app->msgwrite = msgpipe[1];
android_app->keyEventFilter = default_key_filter;
android_app->motionEventFilter = default_motion_filter;
LOGV("Launching android_app_entry in a thread");
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&android_app->thread, &attr, android_app_entry, android_app);
// Wait for thread to start.
pthread_mutex_lock(&android_app->mutex);
while (!android_app->running) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
return android_app;
}
static void android_app_write_cmd(struct android_app* android_app, int8_t cmd) {
if (write(android_app->msgwrite, &cmd, sizeof(cmd)) != sizeof(cmd)) {
LOGE("Failure writing android_app cmd: %s", strerror(errno));
}
}
static void android_app_set_window(struct android_app* android_app,
ANativeWindow* window) {
LOGV("android_app_set_window called");
pthread_mutex_lock(&android_app->mutex);
if (android_app->pendingWindow != NULL) {
android_app_write_cmd(android_app, APP_CMD_TERM_WINDOW);
}
android_app->pendingWindow = window;
if (window != NULL) {
android_app_write_cmd(android_app, APP_CMD_INIT_WINDOW);
}
while (android_app->window != android_app->pendingWindow) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_set_activity_state(struct android_app* android_app,
int8_t cmd) {
pthread_mutex_lock(&android_app->mutex);
android_app_write_cmd(android_app, cmd);
while (android_app->activityState != cmd) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_free(struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
android_app_write_cmd(android_app, APP_CMD_DESTROY);
while (!android_app->destroyed) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
close(android_app->msgread);
close(android_app->msgwrite);
pthread_cond_destroy(&android_app->cond);
pthread_mutex_destroy(&android_app->mutex);
free(android_app);
}
static inline struct android_app* ToApp(GameActivity* activity) {
return (struct android_app*)activity->instance;
}
static void onDestroy(GameActivity* activity) {
LOGV("Destroy: %p", activity);
android_app_free(ToApp(activity));
}
static void onStart(GameActivity* activity) {
LOGV("Start: %p", activity);
android_app_set_activity_state(ToApp(activity), APP_CMD_START);
}
static void onResume(GameActivity* activity) {
LOGV("Resume: %p", activity);
android_app_set_activity_state(ToApp(activity), APP_CMD_RESUME);
}
static void onSaveInstanceState(GameActivity* activity,
SaveInstanceStateRecallback recallback,
void* context) {
LOGV("SaveInstanceState: %p", activity);
struct android_app* android_app = ToApp(activity);
pthread_mutex_lock(&android_app->mutex);
android_app->stateSaved = 0;
android_app_write_cmd(android_app, APP_CMD_SAVE_STATE);
while (!android_app->stateSaved) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
if (android_app->savedState != NULL) {
// Tell the Java side about our state.
recallback((const char*)android_app->savedState,
android_app->savedStateSize, context);
// Now we can free it.
free(android_app->savedState);
android_app->savedState = NULL;
android_app->savedStateSize = 0;
}
pthread_mutex_unlock(&android_app->mutex);
}
static void onPause(GameActivity* activity) {
LOGV("Pause: %p", activity);
android_app_set_activity_state(ToApp(activity), APP_CMD_PAUSE);
}
static void onStop(GameActivity* activity) {
LOGV("Stop: %p", activity);
android_app_set_activity_state(ToApp(activity), APP_CMD_STOP);
}
static void onConfigurationChanged(GameActivity* activity) {
LOGV("ConfigurationChanged: %p", activity);
android_app_write_cmd(ToApp(activity), APP_CMD_CONFIG_CHANGED);
}
static void onTrimMemory(GameActivity* activity, int level) {
LOGV("TrimMemory: %p %d", activity, level);
android_app_write_cmd(ToApp(activity), APP_CMD_LOW_MEMORY);
}
static void onWindowFocusChanged(GameActivity* activity, bool focused) {
LOGV("WindowFocusChanged: %p -- %d", activity, focused);
android_app_write_cmd(ToApp(activity),
focused ? APP_CMD_GAINED_FOCUS : APP_CMD_LOST_FOCUS);
}
static void onNativeWindowCreated(GameActivity* activity,
ANativeWindow* window) {
LOGV("NativeWindowCreated: %p -- %p", activity, window);
android_app_set_window(ToApp(activity), window);
}
static void onNativeWindowDestroyed(GameActivity* activity,
ANativeWindow* window) {
LOGV("NativeWindowDestroyed: %p -- %p", activity, window);
android_app_set_window(ToApp(activity), NULL);
}
static void onNativeWindowRedrawNeeded(GameActivity* activity,
ANativeWindow* window) {
LOGV("NativeWindowRedrawNeeded: %p -- %p", activity, window);
android_app_write_cmd(ToApp(activity), APP_CMD_WINDOW_REDRAW_NEEDED);
}
static void onNativeWindowResized(GameActivity* activity, ANativeWindow* window,
int32_t width, int32_t height) {
LOGV("NativeWindowResized: %p -- %p ( %d x %d )", activity, window, width,
height);
android_app_write_cmd(ToApp(activity), APP_CMD_WINDOW_RESIZED);
}
void android_app_set_motion_event_filter(struct android_app* app,
android_motion_event_filter filter) {
pthread_mutex_lock(&app->mutex);
app->motionEventFilter = filter;
pthread_mutex_unlock(&app->mutex);
}
static bool onTouchEvent(GameActivity* activity,
const GameActivityMotionEvent* event,
const GameActivityHistoricalPointerAxes* historical,
int historicalLen) {
struct android_app* android_app = ToApp(activity);
pthread_mutex_lock(&android_app->mutex);
if (android_app->motionEventFilter != NULL &&
!android_app->motionEventFilter(event)) {
pthread_mutex_unlock(&android_app->mutex);
return false;
}
struct android_input_buffer* inputBuffer =
&android_app->inputBuffers[android_app->currentInputBuffer];
// Add to the list of active motion events
if (inputBuffer->motionEventsCount <
NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS) {
int new_ix = inputBuffer->motionEventsCount;
memcpy(&inputBuffer->motionEvents[new_ix], event,
sizeof(GameActivityMotionEvent));
++inputBuffer->motionEventsCount;
if (inputBuffer->historicalSamplesCount + historicalLen <=
NATIVE_APP_GLUE_MAX_HISTORICAL_POINTER_SAMPLES) {
int start_ix = inputBuffer->historicalSamplesCount;
memcpy(&inputBuffer->historicalAxisSamples[start_ix], historical,
sizeof(historical[0]) * historicalLen);
inputBuffer->historicalSamplesCount += event->historicalCount;
inputBuffer->motionEvents[new_ix].historicalStart = start_ix;
inputBuffer->motionEvents[new_ix].historicalCount = historicalLen;
} else {
inputBuffer->motionEvents[new_ix].historicalCount = 0;
}
} else {
LOGW_ONCE("Motion event will be dropped because the number of unconsumed motion"
" events exceeded NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS (%d). Consider setting"
" NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS_OVERRIDE to a larger value",
NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS);
}
pthread_mutex_unlock(&android_app->mutex);
return true;
}
struct android_input_buffer* android_app_swap_input_buffers(
struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
struct android_input_buffer* inputBuffer =
&android_app->inputBuffers[android_app->currentInputBuffer];
if (inputBuffer->motionEventsCount == 0 &&
inputBuffer->keyEventsCount == 0) {
inputBuffer = NULL;
} else {
android_app->currentInputBuffer =
(android_app->currentInputBuffer + 1) %
NATIVE_APP_GLUE_MAX_INPUT_BUFFERS;
}
pthread_mutex_unlock(&android_app->mutex);
return inputBuffer;
}
void android_app_clear_motion_events(struct android_input_buffer* inputBuffer) {
inputBuffer->motionEventsCount = 0;
}
void android_app_set_key_event_filter(struct android_app* app,
android_key_event_filter filter) {
pthread_mutex_lock(&app->mutex);
app->keyEventFilter = filter;
pthread_mutex_unlock(&app->mutex);
}
static bool onKey(GameActivity* activity, const GameActivityKeyEvent* event) {
struct android_app* android_app = ToApp(activity);
pthread_mutex_lock(&android_app->mutex);
if (android_app->keyEventFilter != NULL &&
!android_app->keyEventFilter(event)) {
pthread_mutex_unlock(&android_app->mutex);
return false;
}
struct android_input_buffer* inputBuffer =
&android_app->inputBuffers[android_app->currentInputBuffer];
// Add to the list of active key down events
if (inputBuffer->keyEventsCount < NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS) {
int new_ix = inputBuffer->keyEventsCount;
memcpy(&inputBuffer->keyEvents[new_ix], event,
sizeof(GameActivityKeyEvent));
++inputBuffer->keyEventsCount;
} else {
LOGW_ONCE("Key event will be dropped because the number of unconsumed key events exceeded"
" NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS (%d). Consider setting"
" NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS_OVERRIDE to a larger value",
NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS);
}
pthread_mutex_unlock(&android_app->mutex);
return true;
}
void android_app_clear_key_events(struct android_input_buffer* inputBuffer) {
inputBuffer->keyEventsCount = 0;
}
static void onTextInputEvent(GameActivity* activity,
const GameTextInputState* state) {
struct android_app* android_app = ToApp(activity);
pthread_mutex_lock(&android_app->mutex);
android_app->textInputState = 1;
pthread_mutex_unlock(&android_app->mutex);
}
static void onWindowInsetsChanged(GameActivity* activity) {
LOGV("WindowInsetsChanged: %p", activity);
android_app_write_cmd(ToApp(activity), APP_CMD_WINDOW_INSETS_CHANGED);
}
JNIEXPORT
void GameActivity_onCreate_C(GameActivity* activity, void* savedState,
size_t savedStateSize) {
LOGV("Creating: %p", activity);
activity->callbacks->onDestroy = onDestroy;
activity->callbacks->onStart = onStart;
activity->callbacks->onResume = onResume;
activity->callbacks->onSaveInstanceState = onSaveInstanceState;
activity->callbacks->onPause = onPause;
activity->callbacks->onStop = onStop;
activity->callbacks->onTouchEvent = onTouchEvent;
activity->callbacks->onKeyDown = onKey;
activity->callbacks->onKeyUp = onKey;
activity->callbacks->onTextInputEvent = onTextInputEvent;
activity->callbacks->onConfigurationChanged = onConfigurationChanged;
activity->callbacks->onTrimMemory = onTrimMemory;
activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;
activity->callbacks->onNativeWindowCreated = onNativeWindowCreated;
activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed;
activity->callbacks->onNativeWindowRedrawNeeded =
onNativeWindowRedrawNeeded;
activity->callbacks->onNativeWindowResized = onNativeWindowResized;
activity->callbacks->onWindowInsetsChanged = onWindowInsetsChanged;
LOGV("Callbacks set: %p", activity->callbacks);
activity->instance =
android_app_create(activity, savedState, savedStateSize);
}
@@ -1,517 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
/**
* @addtogroup android_native_app_glue Native App Glue library
* The glue library to interface your game loop with GameActivity.
* @{
*/
#include <android/configuration.h>
#include <android/looper.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include "game-activity/GameActivity.h"
#if (defined NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS_OVERRIDE)
#define NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS \
NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS_OVERRIDE
#else
#define NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS 16
#endif
#if (defined NATIVE_APP_GLUE_MAX_HISTORICAL_POINTER_SAMPLES_OVERRIDE)
#define NATIVE_APP_GLUE_MAX_HISTORICAL_POINTER_SAMPLES \
NATIVE_APP_GLUE_MAX_HISTORICAL_POINTER_SAMPLES_OVERRIDE
#else
#define NATIVE_APP_GLUE_MAX_HISTORICAL_POINTER_SAMPLES 64
#endif
#if (defined NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS_OVERRIDE)
#define NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS \
NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS_OVERRIDE
#else
#define NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS 4
#endif
#ifdef __cplusplus
extern "C" {
#endif
/**
* The GameActivity interface provided by <game-activity/GameActivity.h>
* is based on a set of application-provided callbacks that will be called
* by the Activity's main thread when certain events occur.
*
* This means that each one of this callbacks _should_ _not_ block, or they
* risk having the system force-close the application. This programming
* model is direct, lightweight, but constraining.
*
* The 'android_native_app_glue' static library is used to provide a different
* execution model where the application can implement its own main event
* loop in a different thread instead. Here's how it works:
*
* 1/ The application must provide a function named "android_main()" that
* will be called when the activity is created, in a new thread that is
* distinct from the activity's main thread.
*
* 2/ android_main() receives a pointer to a valid "android_app" structure
* that contains references to other important objects, e.g. the
* GameActivity obejct instance the application is running in.
*
* 3/ the "android_app" object holds an ALooper instance that already
* listens to activity lifecycle events (e.g. "pause", "resume").
* See APP_CMD_XXX declarations below.
*
* This corresponds to an ALooper identifier returned by
* ALooper_pollOnce with value LOOPER_ID_MAIN.
*
* Your application can use the same ALooper to listen to additional
* file-descriptors. They can either be callback based, or with return
* identifiers starting with LOOPER_ID_USER.
*
* 4/ Whenever you receive a LOOPER_ID_MAIN event,
* the returned data will point to an android_poll_source structure. You
* can call the process() function on it, and fill in android_app->onAppCmd
* to be called for your own processing of the event.
*
* Alternatively, you can call the low-level functions to read and process
* the data directly... look at the process_cmd() and process_input()
* implementations in the glue to see how to do this.
*
* See the sample named "native-activity" that comes with the NDK with a
* full usage example. Also look at the documentation of GameActivity.
*/
struct android_app;
/**
* Data associated with an ALooper fd that will be returned as the "outData"
* when that source has data ready.
*/
struct android_poll_source {
/**
* The identifier of this source. May be LOOPER_ID_MAIN or
* LOOPER_ID_INPUT.
*/
int32_t id;
/** The android_app this ident is associated with. */
struct android_app* app;
/**
* Function to call to perform the standard processing of data from
* this source.
*/
void (*process)(struct android_app* app,
struct android_poll_source* source);
};
struct android_input_buffer {
/**
* Pointer to a read-only array of pointers to GameActivityMotionEvent.
* Only the first motionEventsCount events are valid.
*/
GameActivityMotionEvent motionEvents[NATIVE_APP_GLUE_MAX_NUM_MOTION_EVENTS];
/**
* The number of valid motion events in `motionEvents`.
*/
uint64_t motionEventsCount;
/**
* Pointer to a read-only array of pointers to GameActivityHistoricalPointerAxes.
*
* Only the first historicalSamplesCount samples are valid.
* Refer to event->historicalStart, event->pointerCount and event->historicalCount
* to access the specific samples that relate to an event.
*
* Each slice of samples for one event has a length of
* (event->pointerCount and event->historicalCount) and is in pointer-major
* order so the historic samples for each pointer are contiguous.
* E.g. you would access historic sample index 3 for pointer 2 of an event with:
*
* historicalAxisSamples[event->historicalStart + (event->historicalCount * 2) + 3];
*/
GameActivityHistoricalPointerAxes historicalAxisSamples[NATIVE_APP_GLUE_MAX_HISTORICAL_POINTER_SAMPLES];
/**
* The number of valid historical samples in `historicalAxisSamples`.
*/
uint64_t historicalSamplesCount;
/**
* Pointer to a read-only array of pointers to GameActivityKeyEvent.
* Only the first keyEventsCount events are valid.
*/
GameActivityKeyEvent keyEvents[NATIVE_APP_GLUE_MAX_NUM_KEY_EVENTS];
/**
* The number of valid "Key" events in `keyEvents`.
*/
uint64_t keyEventsCount;
};
/**
* Function pointer declaration for the filtering of key events.
* A function with this signature should be passed to
* android_app_set_key_event_filter and return false for any events that should
* not be handled by android_native_app_glue. These events will be handled by
* the system instead.
*/
typedef bool (*android_key_event_filter)(const GameActivityKeyEvent*);
/**
* Function pointer definition for the filtering of motion events.
* A function with this signature should be passed to
* android_app_set_motion_event_filter and return false for any events that
* should not be handled by android_native_app_glue. These events will be
* handled by the system instead.
*/
typedef bool (*android_motion_event_filter)(const GameActivityMotionEvent*);
/**
* This is the interface for the standard glue code of a threaded
* application. In this model, the application's code is running
* in its own thread separate from the main thread of the process.
* It is not required that this thread be associated with the Java
* VM, although it will need to be in order to make JNI calls any
* Java objects.
*/
struct android_app {
/**
* An optional pointer to application-defined state.
*/
void* userData;
/**
* A required callback for processing main app commands (`APP_CMD_*`).
* This is called each frame if there are app commands that need processing.
*/
void (*onAppCmd)(struct android_app* app, int32_t cmd);
/** The GameActivity object instance that this app is running in. */
GameActivity* activity;
/** The current configuration the app is running in. */
AConfiguration* config;
/**
* The last activity saved state, as provided at creation time.
* It is NULL if there was no state. You can use this as you need; the
* memory will remain around until you call android_app_exec_cmd() for
* APP_CMD_RESUME, at which point it will be freed and savedState set to
* NULL. These variables should only be changed when processing a
* APP_CMD_SAVE_STATE, at which point they will be initialized to NULL and
* you can malloc your state and place the information here. In that case
* the memory will be freed for you later.
*/
void* savedState;
/**
* The size of the activity saved state. It is 0 if `savedState` is NULL.
*/
size_t savedStateSize;
/** The ALooper associated with the app's thread. */
ALooper* looper;
/** When non-NULL, this is the window surface that the app can draw in. */
ANativeWindow* window;
/**
* Current content rectangle of the window; this is the area where the
* window's content should be placed to be seen by the user.
*/
ARect contentRect;
/**
* Current state of the app's activity. May be either APP_CMD_START,
* APP_CMD_RESUME, APP_CMD_PAUSE, or APP_CMD_STOP.
*/
int activityState;
/**
* This is non-zero when the application's GameActivity is being
* destroyed and waiting for the app thread to complete.
*/
int destroyRequested;
#define NATIVE_APP_GLUE_MAX_INPUT_BUFFERS 2
/**
* This is used for buffering input from GameActivity. Once ready, the
* application thread switches the buffers and processes what was
* accumulated.
*/
struct android_input_buffer inputBuffers[NATIVE_APP_GLUE_MAX_INPUT_BUFFERS];
int currentInputBuffer;
/**
* 0 if no text input event is outstanding, 1 if it is.
* Use `GameActivity_getTextInputState` to get information
* about the text entered by the user.
*/
int textInputState;
// Below are "private" implementation of the glue code.
/** @cond INTERNAL */
pthread_mutex_t mutex;
pthread_cond_t cond;
int msgread;
int msgwrite;
pthread_t thread;
struct android_poll_source cmdPollSource;
int running;
int stateSaved;
int destroyed;
int redrawNeeded;
ANativeWindow* pendingWindow;
ARect pendingContentRect;
android_key_event_filter keyEventFilter;
android_motion_event_filter motionEventFilter;
/** @endcond */
};
/**
* Looper ID of commands coming from the app's main thread, an AInputQueue or
* user-defined sources.
*/
enum NativeAppGlueLooperId {
/**
* Looper data ID of commands coming from the app's main thread, which
* is returned as an identifier from ALooper_pollOnce(). The data for this
* identifier is a pointer to an android_poll_source structure.
* These can be retrieved and processed with android_app_read_cmd()
* and android_app_exec_cmd().
*/
LOOPER_ID_MAIN = 1,
/**
* Unused. Reserved for future use when usage of AInputQueue will be
* supported.
*/
LOOPER_ID_INPUT = 2,
/**
* Start of user-defined ALooper identifiers.
*/
LOOPER_ID_USER = 3,
};
/**
* Commands passed from the application's main Java thread to the game's thread.
*/
enum NativeAppGlueAppCmd {
/**
* Unused. Reserved for future use when usage of AInputQueue will be
* supported.
*/
UNUSED_APP_CMD_INPUT_CHANGED,
/**
* Command from main thread: a new ANativeWindow is ready for use. Upon
* receiving this command, android_app->window will contain the new window
* surface.
*/
APP_CMD_INIT_WINDOW,
/**
* Command from main thread: the existing ANativeWindow needs to be
* terminated. Upon receiving this command, android_app->window still
* contains the existing window; after calling android_app_exec_cmd
* it will be set to NULL.
*/
APP_CMD_TERM_WINDOW,
/**
* Command from main thread: the current ANativeWindow has been resized.
* Please redraw with its new size.
*/
APP_CMD_WINDOW_RESIZED,
/**
* Command from main thread: the system needs that the current ANativeWindow
* be redrawn. You should redraw the window before handing this to
* android_app_exec_cmd() in order to avoid transient drawing glitches.
*/
APP_CMD_WINDOW_REDRAW_NEEDED,
/**
* Command from main thread: the content area of the window has changed,
* such as from the soft input window being shown or hidden. You can
* find the new content rect in android_app::contentRect.
*/
APP_CMD_CONTENT_RECT_CHANGED,
/**
* Command from main thread: the app's activity window has gained
* input focus.
*/
APP_CMD_GAINED_FOCUS,
/**
* Command from main thread: the app's activity window has lost
* input focus.
*/
APP_CMD_LOST_FOCUS,
/**
* Command from main thread: the current device configuration has changed.
*/
APP_CMD_CONFIG_CHANGED,
/**
* Command from main thread: the system is running low on memory.
* Try to reduce your memory use.
*/
APP_CMD_LOW_MEMORY,
/**
* Command from main thread: the app's activity has been started.
*/
APP_CMD_START,
/**
* Command from main thread: the app's activity has been resumed.
*/
APP_CMD_RESUME,
/**
* Command from main thread: the app should generate a new saved state
* for itself, to restore from later if needed. If you have saved state,
* allocate it with malloc and place it in android_app.savedState with
* the size in android_app.savedStateSize. The will be freed for you
* later.
*/
APP_CMD_SAVE_STATE,
/**
* Command from main thread: the app's activity has been paused.
*/
APP_CMD_PAUSE,
/**
* Command from main thread: the app's activity has been stopped.
*/
APP_CMD_STOP,
/**
* Command from main thread: the app's activity is being destroyed,
* and waiting for the app thread to clean up and exit before proceeding.
*/
APP_CMD_DESTROY,
/**
* Command from main thread: the app's insets have changed.
*/
APP_CMD_WINDOW_INSETS_CHANGED,
};
/**
* Call when ALooper_pollAll() returns LOOPER_ID_MAIN, reading the next
* app command message.
*/
int8_t android_app_read_cmd(struct android_app* android_app);
/**
* Call with the command returned by android_app_read_cmd() to do the
* initial pre-processing of the given command. You can perform your own
* actions for the command after calling this function.
*/
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Call with the command returned by android_app_read_cmd() to do the
* final post-processing of the given command. You must have done your own
* actions for the command before calling this function.
*/
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Call this before processing input events to get the events buffer.
* The function returns NULL if there are no events to process.
*/
struct android_input_buffer* android_app_swap_input_buffers(
struct android_app* android_app);
/**
* Clear the array of motion events that were waiting to be handled, and release
* each of them.
*
* This method should be called after you have processed the motion events in
* your game loop. You should handle events at each iteration of your game loop.
*/
void android_app_clear_motion_events(struct android_input_buffer* inputBuffer);
/**
* Clear the array of key events that were waiting to be handled, and release
* each of them.
*
* This method should be called after you have processed the key up events in
* your game loop. You should handle events at each iteration of your game loop.
*/
void android_app_clear_key_events(struct android_input_buffer* inputBuffer);
/**
* This is a springboard into the Rust glue layer that wraps calling the
* main entry for the app itself.
*/
extern void _rust_glue_entry(struct android_app* app);
/**
* Set the filter to use when processing key events.
* Any events for which the filter returns false will be ignored by
* android_native_app_glue. If filter is set to NULL, no filtering is done.
*
* The default key filter will filter out volume and camera button presses.
*/
void android_app_set_key_event_filter(struct android_app* app,
android_key_event_filter filter);
/**
* Set the filter to use when processing touch and motion events.
* Any events for which the filter returns false will be ignored by
* android_native_app_glue. If filter is set to NULL, no filtering is done.
*
* Note that the default motion event filter will only allow touchscreen events
* through, in order to mimic NativeActivity's behaviour, so for controller
* events to be passed to the app, set the filter to NULL.
*/
void android_app_set_motion_event_filter(struct android_app* app,
android_motion_event_filter filter);
void GameActivity_onCreate_C(GameActivity* activity, void* savedState,
size_t savedStateSize);
#ifdef __cplusplus
}
#endif
/** @} */
@@ -1,41 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @defgroup game_common Game Common
* Common structures and functions used within AGDK
* @{
*/
#pragma once
/**
* The type of a component for which to retrieve insets. See
* https://developer.android.com/reference/androidx/core/view/WindowInsetsCompat.Type
*/
typedef enum GameCommonInsetsType {
GAMECOMMON_INSETS_TYPE_CAPTION_BAR = 0,
GAMECOMMON_INSETS_TYPE_DISPLAY_CUTOUT,
GAMECOMMON_INSETS_TYPE_IME,
GAMECOMMON_INSETS_TYPE_MANDATORY_SYSTEM_GESTURES,
GAMECOMMON_INSETS_TYPE_NAVIGATION_BARS,
GAMECOMMON_INSETS_TYPE_STATUS_BARS,
GAMECOMMON_INSETS_TYPE_SYSTEM_BARS,
GAMECOMMON_INSETS_TYPE_SYSTEM_GESTURES,
GAMECOMMON_INSETS_TYPE_TAPABLE_ELEMENT,
GAMECOMMON_INSETS_TYPE_WATERFALL,
GAMECOMMON_INSETS_TYPE_COUNT
} GameCommonInsetsType;
@@ -1,364 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "game-text-input/gametextinput.h"
#include <android/log.h>
#include <jni.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <memory>
#include <vector>
#define LOG_TAG "GameTextInput"
static constexpr int32_t DEFAULT_MAX_STRING_SIZE = 1 << 16;
// Cache of field ids in the Java GameTextInputState class
struct StateClassInfo {
jfieldID text;
jfieldID selectionStart;
jfieldID selectionEnd;
jfieldID composingRegionStart;
jfieldID composingRegionEnd;
};
// Main GameTextInput object.
struct GameTextInput {
public:
GameTextInput(JNIEnv *env, uint32_t max_string_size);
~GameTextInput();
void setState(const GameTextInputState &state);
const GameTextInputState &getState() const { return currentState_; }
void setInputConnection(jobject inputConnection);
void processEvent(jobject textInputEvent);
void showIme(uint32_t flags);
void hideIme(uint32_t flags);
void setEventCallback(GameTextInputEventCallback callback, void *context);
jobject stateToJava(const GameTextInputState &state) const;
void stateFromJava(jobject textInputEvent,
GameTextInputGetStateCallback callback,
void *context) const;
void setImeInsetsCallback(GameTextInputImeInsetsCallback callback,
void *context);
void processImeInsets(const ARect *insets);
const ARect &getImeInsets() const { return currentInsets_; }
private:
// Copy string and set other fields
void setStateInner(const GameTextInputState &state);
static void processCallback(void *context, const GameTextInputState *state);
JNIEnv *env_ = nullptr;
// Cached at initialization from
// com/google/androidgamesdk/gametextinput/State.
jclass stateJavaClass_ = nullptr;
// The latest text input update.
GameTextInputState currentState_ = {};
// An instance of gametextinput.InputConnection.
jclass inputConnectionClass_ = nullptr;
jobject inputConnection_ = nullptr;
jmethodID inputConnectionSetStateMethod_;
jmethodID setSoftKeyboardActiveMethod_;
void (*eventCallback_)(void *context,
const struct GameTextInputState *state) = nullptr;
void *eventCallbackContext_ = nullptr;
void (*insetsCallback_)(void *context,
const struct ARect *insets) = nullptr;
ARect currentInsets_ = {};
void *insetsCallbackContext_ = nullptr;
StateClassInfo stateClassInfo_ = {};
// Constant-sized buffer used to store state text.
std::vector<char> stateStringBuffer_;
};
std::unique_ptr<GameTextInput> s_gameTextInput;
extern "C" {
///////////////////////////////////////////////////////////
/// GameTextInputState C Functions
///////////////////////////////////////////////////////////
// Convert to a Java structure.
jobject currentState_toJava(const GameTextInput *gameTextInput,
const GameTextInputState *state) {
if (state == nullptr) return NULL;
return gameTextInput->stateToJava(*state);
}
// Convert from Java structure.
void currentState_fromJava(const GameTextInput *gameTextInput,
jobject textInputEvent,
GameTextInputGetStateCallback callback,
void *context) {
gameTextInput->stateFromJava(textInputEvent, callback, context);
}
///////////////////////////////////////////////////////////
/// GameTextInput C Functions
///////////////////////////////////////////////////////////
struct GameTextInput *GameTextInput_init(JNIEnv *env,
uint32_t max_string_size) {
if (s_gameTextInput.get() != nullptr) {
__android_log_print(ANDROID_LOG_WARN, LOG_TAG,
"Warning: called GameTextInput_init twice without "
"calling GameTextInput_destroy");
return s_gameTextInput.get();
}
// Don't use make_unique, for C++11 compatibility
s_gameTextInput =
std::unique_ptr<GameTextInput>(new GameTextInput(env, max_string_size));
return s_gameTextInput.get();
}
void GameTextInput_destroy(GameTextInput *input) {
if (input == nullptr || s_gameTextInput.get() == nullptr) return;
s_gameTextInput.reset();
}
void GameTextInput_setState(GameTextInput *input,
const GameTextInputState *state) {
if (state == nullptr) return;
input->setState(*state);
}
void GameTextInput_getState(GameTextInput *input,
GameTextInputGetStateCallback callback,
void *context) {
callback(context, &input->getState());
}
void GameTextInput_setInputConnection(GameTextInput *input,
jobject inputConnection) {
input->setInputConnection(inputConnection);
}
void GameTextInput_processEvent(GameTextInput *input, jobject textInputEvent) {
input->processEvent(textInputEvent);
}
void GameTextInput_processImeInsets(GameTextInput *input, const ARect *insets) {
input->processImeInsets(insets);
}
void GameTextInput_showIme(struct GameTextInput *input, uint32_t flags) {
input->showIme(flags);
}
void GameTextInput_hideIme(struct GameTextInput *input, uint32_t flags) {
input->hideIme(flags);
}
void GameTextInput_setEventCallback(struct GameTextInput *input,
GameTextInputEventCallback callback,
void *context) {
input->setEventCallback(callback, context);
}
void GameTextInput_setImeInsetsCallback(struct GameTextInput *input,
GameTextInputImeInsetsCallback callback,
void *context) {
input->setImeInsetsCallback(callback, context);
}
void GameTextInput_getImeInsets(const GameTextInput *input, ARect *insets) {
*insets = input->getImeInsets();
}
} // extern "C"
///////////////////////////////////////////////////////////
/// GameTextInput C++ class Implementation
///////////////////////////////////////////////////////////
GameTextInput::GameTextInput(JNIEnv *env, uint32_t max_string_size)
: env_(env),
stateStringBuffer_(max_string_size == 0 ? DEFAULT_MAX_STRING_SIZE
: max_string_size) {
stateJavaClass_ = (jclass)env_->NewGlobalRef(
env_->FindClass("com/google/androidgamesdk/gametextinput/State"));
inputConnectionClass_ = (jclass)env_->NewGlobalRef(env_->FindClass(
"com/google/androidgamesdk/gametextinput/InputConnection"));
inputConnectionSetStateMethod_ =
env_->GetMethodID(inputConnectionClass_, "setState",
"(Lcom/google/androidgamesdk/gametextinput/State;)V");
setSoftKeyboardActiveMethod_ = env_->GetMethodID(
inputConnectionClass_, "setSoftKeyboardActive", "(ZI)V");
stateClassInfo_.text =
env_->GetFieldID(stateJavaClass_, "text", "Ljava/lang/String;");
stateClassInfo_.selectionStart =
env_->GetFieldID(stateJavaClass_, "selectionStart", "I");
stateClassInfo_.selectionEnd =
env_->GetFieldID(stateJavaClass_, "selectionEnd", "I");
stateClassInfo_.composingRegionStart =
env_->GetFieldID(stateJavaClass_, "composingRegionStart", "I");
stateClassInfo_.composingRegionEnd =
env_->GetFieldID(stateJavaClass_, "composingRegionEnd", "I");
}
GameTextInput::~GameTextInput() {
if (stateJavaClass_ != NULL) {
env_->DeleteGlobalRef(stateJavaClass_);
stateJavaClass_ = NULL;
}
if (inputConnectionClass_ != NULL) {
env_->DeleteGlobalRef(inputConnectionClass_);
inputConnectionClass_ = NULL;
}
if (inputConnection_ != NULL) {
env_->DeleteGlobalRef(inputConnection_);
inputConnection_ = NULL;
}
}
void GameTextInput::setState(const GameTextInputState &state) {
if (inputConnection_ == nullptr) return;
jobject jstate = stateToJava(state);
env_->CallVoidMethod(inputConnection_, inputConnectionSetStateMethod_,
jstate);
env_->DeleteLocalRef(jstate);
setStateInner(state);
}
void GameTextInput::setStateInner(const GameTextInputState &state) {
// Check if we're setting using our own string (other parts may be
// different)
if (state.text_UTF8 == currentState_.text_UTF8) {
currentState_ = state;
return;
}
// Otherwise, copy across the string.
auto bytes_needed =
std::min(static_cast<uint32_t>(state.text_length + 1),
static_cast<uint32_t>(stateStringBuffer_.size()));
currentState_.text_UTF8 = stateStringBuffer_.data();
std::copy(state.text_UTF8, state.text_UTF8 + bytes_needed - 1,
stateStringBuffer_.data());
currentState_.text_length = state.text_length;
currentState_.selection = state.selection;
currentState_.composingRegion = state.composingRegion;
stateStringBuffer_[bytes_needed - 1] = 0;
}
void GameTextInput::setInputConnection(jobject inputConnection) {
if (inputConnection_ != NULL) {
env_->DeleteGlobalRef(inputConnection_);
}
inputConnection_ = env_->NewGlobalRef(inputConnection);
}
/*static*/ void GameTextInput::processCallback(
void *context, const GameTextInputState *state) {
auto thiz = static_cast<GameTextInput *>(context);
if (state != nullptr) thiz->setStateInner(*state);
}
void GameTextInput::processEvent(jobject textInputEvent) {
stateFromJava(textInputEvent, processCallback, this);
if (eventCallback_) {
eventCallback_(eventCallbackContext_, &currentState_);
}
}
void GameTextInput::showIme(uint32_t flags) {
if (inputConnection_ == nullptr) return;
env_->CallVoidMethod(inputConnection_, setSoftKeyboardActiveMethod_, true,
flags);
}
void GameTextInput::setEventCallback(GameTextInputEventCallback callback,
void *context) {
eventCallback_ = callback;
eventCallbackContext_ = context;
}
void GameTextInput::setImeInsetsCallback(
GameTextInputImeInsetsCallback callback, void *context) {
insetsCallback_ = callback;
insetsCallbackContext_ = context;
}
void GameTextInput::processImeInsets(const ARect *insets) {
currentInsets_ = *insets;
if (insetsCallback_) {
insetsCallback_(insetsCallbackContext_, &currentInsets_);
}
}
void GameTextInput::hideIme(uint32_t flags) {
if (inputConnection_ == nullptr) return;
env_->CallVoidMethod(inputConnection_, setSoftKeyboardActiveMethod_, false,
flags);
}
jobject GameTextInput::stateToJava(const GameTextInputState &state) const {
static jmethodID constructor = nullptr;
if (constructor == nullptr) {
constructor = env_->GetMethodID(stateJavaClass_, "<init>",
"(Ljava/lang/String;IIII)V");
if (constructor == nullptr) {
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG,
"Can't find gametextinput.State constructor");
return nullptr;
}
}
const char *text = state.text_UTF8;
if (text == nullptr) {
static char empty_string[] = "";
text = empty_string;
}
// Note that this expects 'modified' UTF-8 which is not the same as UTF-8
// https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8
jstring jtext = env_->NewStringUTF(text);
jobject jobj =
env_->NewObject(stateJavaClass_, constructor, jtext,
state.selection.start, state.selection.end,
state.composingRegion.start, state.composingRegion.end);
env_->DeleteLocalRef(jtext);
return jobj;
}
void GameTextInput::stateFromJava(jobject textInputEvent,
GameTextInputGetStateCallback callback,
void *context) const {
jstring text =
(jstring)env_->GetObjectField(textInputEvent, stateClassInfo_.text);
// Note this is 'modified' UTF-8, not true UTF-8. It has no NULLs in it,
// except at the end. It's actually not specified whether the value returned
// by GetStringUTFChars includes a null at the end, but it *seems to* on
// Android.
const char *text_chars = env_->GetStringUTFChars(text, NULL);
int text_len = env_->GetStringUTFLength(
text); // Length in bytes, *not* including the null.
int selectionStart =
env_->GetIntField(textInputEvent, stateClassInfo_.selectionStart);
int selectionEnd =
env_->GetIntField(textInputEvent, stateClassInfo_.selectionEnd);
int composingRegionStart =
env_->GetIntField(textInputEvent, stateClassInfo_.composingRegionStart);
int composingRegionEnd =
env_->GetIntField(textInputEvent, stateClassInfo_.composingRegionEnd);
GameTextInputState state{text_chars,
text_len,
{selectionStart, selectionEnd},
{composingRegionStart, composingRegionEnd}};
callback(context, &state);
env_->ReleaseStringUTFChars(text, text_chars);
env_->DeleteLocalRef(text);
}
@@ -1,290 +0,0 @@
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @defgroup game_text_input Game Text Input
* The interface to use GameTextInput.
* @{
*/
#pragma once
#include <android/rect.h>
#include <jni.h>
#include <stdint.h>
#include "gamecommon.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* This struct holds a span within a region of text from start (inclusive) to
* end (exclusive). An empty span or cursor position is specified with
* start==end. An undefined span is specified with start = end = SPAN_UNDEFINED.
*/
typedef struct GameTextInputSpan {
/** The start of the region (inclusive). */
int32_t start;
/** The end of the region (exclusive). */
int32_t end;
} GameTextInputSpan;
/**
* Values with special meaning in a GameTextInputSpan.
*/
enum GameTextInputSpanFlag { SPAN_UNDEFINED = -1 };
/**
* This struct holds the state of an editable section of text.
* The text can have a selection and a composing region defined on it.
* A composing region is used by IMEs that allow input using multiple steps to
* compose a glyph or word. Use functions GameTextInput_getState and
* GameTextInput_setState to read and modify the state that an IME is editing.
*/
typedef struct GameTextInputState {
/**
* Text owned by the state, as a modified UTF-8 string. Null-terminated.
* https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8
*/
const char *text_UTF8;
/**
* Length in bytes of text_UTF8, *not* including the null at end.
*/
int32_t text_length;
/**
* A selection defined on the text.
*/
GameTextInputSpan selection;
/**
* A composing region defined on the text.
*/
GameTextInputSpan composingRegion;
} GameTextInputState;
/**
* A callback called by GameTextInput_getState.
* @param context User-defined context.
* @param state State, owned by the library, that will be valid for the duration
* of the callback.
*/
typedef void (*GameTextInputGetStateCallback)(
void *context, const struct GameTextInputState *state);
/**
* Opaque handle to the GameTextInput API.
*/
typedef struct GameTextInput GameTextInput;
/**
* Initialize the GameTextInput library.
* If called twice without GameTextInput_destroy being called, the same pointer
* will be returned and a warning will be issued.
* @param env A JNI env valid on the calling thread.
* @param max_string_size The maximum length of a string that can be edited. If
* zero, the maximum defaults to 65536 bytes. A buffer of this size is allocated
* at initialization.
* @return A handle to the library.
*/
GameTextInput *GameTextInput_init(JNIEnv *env, uint32_t max_string_size);
/**
* When using GameTextInput, you need to create a gametextinput.InputConnection
* on the Java side and pass it using this function to the library, unless using
* GameActivity in which case this will be done for you. See the GameActivity
* source code or GameTextInput samples for examples of usage.
* @param input A valid GameTextInput library handle.
* @param inputConnection A gametextinput.InputConnection object.
*/
void GameTextInput_setInputConnection(GameTextInput *input,
jobject inputConnection);
/**
* Unless using GameActivity, it is required to call this function from your
* Java gametextinput.Listener.stateChanged method to convert eventState and
* trigger any event callbacks. When using GameActivity, this does not need to
* be called as event processing is handled by the Activity.
* @param input A valid GameTextInput library handle.
* @param eventState A Java gametextinput.State object.
*/
void GameTextInput_processEvent(GameTextInput *input, jobject eventState);
/**
* Free any resources owned by the GameTextInput library.
* Any subsequent calls to the library will fail until GameTextInput_init is
* called again.
* @param input A valid GameTextInput library handle.
*/
void GameTextInput_destroy(GameTextInput *input);
/**
* Flags to be passed to GameTextInput_showIme.
*/
enum ShowImeFlags {
SHOW_IME_UNDEFINED = 0, // Default value.
SHOW_IMPLICIT =
1, // Indicates that the user has forced the input method open so it
// should not be closed until they explicitly do so.
SHOW_FORCED = 2 // Indicates that this is an implicit request to show the
// input window, not as the result of a direct request by
// the user. The window may not be shown in this case.
};
/**
* Show the IME. Calls InputMethodManager.showSoftInput().
* @param input A valid GameTextInput library handle.
* @param flags Defined in ShowImeFlags above. For more information see:
* https://developer.android.com/reference/android/view/inputmethod/InputMethodManager
*/
void GameTextInput_showIme(GameTextInput *input, uint32_t flags);
/**
* Flags to be passed to GameTextInput_hideIme.
*/
enum HideImeFlags {
HIDE_IME_UNDEFINED = 0, // Default value.
HIDE_IMPLICIT_ONLY =
1, // Indicates that the soft input window should only be hidden if it
// was not explicitly shown by the user.
HIDE_NOT_ALWAYS =
2, // Indicates that the soft input window should normally be hidden,
// unless it was originally shown with SHOW_FORCED.
};
/**
* Show the IME. Calls InputMethodManager.hideSoftInputFromWindow().
* @param input A valid GameTextInput library handle.
* @param flags Defined in HideImeFlags above. For more information see:
* https://developer.android.com/reference/android/view/inputmethod/InputMethodManager
*/
void GameTextInput_hideIme(GameTextInput *input, uint32_t flags);
/**
* Call a callback with the current GameTextInput state, which may have been
* modified by changes in the IME and calls to GameTextInput_setState. We use a
* callback rather than returning the state in order to simplify ownership of
* text_UTF8 strings. These strings are only valid during the calling of the
* callback.
* @param input A valid GameTextInput library handle.
* @param callback A function that will be called with valid state.
* @param context Context used by the callback.
*/
void GameTextInput_getState(GameTextInput *input,
GameTextInputGetStateCallback callback,
void *context);
/**
* Set the current GameTextInput state. This state is reflected to any active
* IME.
* @param input A valid GameTextInput library handle.
* @param state The state to set. Ownership is maintained by the caller and must
* remain valid for the duration of the call.
*/
void GameTextInput_setState(GameTextInput *input,
const GameTextInputState *state);
/**
* Type of the callback needed by GameTextInput_setEventCallback that will be
* called every time the IME state changes.
* @param context User-defined context set in GameTextInput_setEventCallback.
* @param current_state Current IME state, owned by the library and valid during
* the callback.
*/
typedef void (*GameTextInputEventCallback)(
void *context, const GameTextInputState *current_state);
/**
* Optionally set a callback to be called whenever the IME state changes.
* Not necessary if you are using GameActivity, which handles these callbacks
* for you.
* @param input A valid GameTextInput library handle.
* @param callback Called by the library when the IME state changes.
* @param context Context passed as first argument to the callback.
*/
void GameTextInput_setEventCallback(GameTextInput *input,
GameTextInputEventCallback callback,
void *context);
/**
* Type of the callback needed by GameTextInput_setImeInsetsCallback that will
* be called every time the IME window insets change.
* @param context User-defined context set in
* GameTextInput_setImeWIndowInsetsCallback.
* @param current_insets Current IME insets, owned by the library and valid
* during the callback.
*/
typedef void (*GameTextInputImeInsetsCallback)(void *context,
const ARect *current_insets);
/**
* Optionally set a callback to be called whenever the IME insets change.
* Not necessary if you are using GameActivity, which handles these callbacks
* for you.
* @param input A valid GameTextInput library handle.
* @param callback Called by the library when the IME insets change.
* @param context Context passed as first argument to the callback.
*/
void GameTextInput_setImeInsetsCallback(GameTextInput *input,
GameTextInputImeInsetsCallback callback,
void *context);
/**
* Get the current window insets for the IME.
* @param input A valid GameTextInput library handle.
* @param insets Filled with the current insets by this function.
*/
void GameTextInput_getImeInsets(const GameTextInput *input, ARect *insets);
/**
* Unless using GameActivity, it is required to call this function from your
* Java gametextinput.Listener.onImeInsetsChanged method to
* trigger any event callbacks. When using GameActivity, this does not need to
* be called as insets processing is handled by the Activity.
* @param input A valid GameTextInput library handle.
* @param eventState A Java gametextinput.State object.
*/
void GameTextInput_processImeInsets(GameTextInput *input, const ARect *insets);
/**
* Convert a GameTextInputState struct to a Java gametextinput.State object.
* Don't forget to delete the returned Java local ref when you're done.
* @param input A valid GameTextInput library handle.
* @param state Input state to convert.
* @return A Java object of class gametextinput.State. The caller is required to
* delete this local reference.
*/
jobject GameTextInputState_toJava(const GameTextInput *input,
const GameTextInputState *state);
/**
* Convert from a Java gametextinput.State object into a C GameTextInputState
* struct.
* @param input A valid GameTextInput library handle.
* @param state A Java gametextinput.State object.
* @param callback A function called with the C struct, valid for the duration
* of the call.
* @param context Context passed to the callback.
*/
void GameTextInputState_fromJava(const GameTextInput *input, jobject state,
GameTextInputGetStateCallback callback,
void *context);
#ifdef __cplusplus
}
#endif
/** @} */
-176
View File
@@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-19
View File
@@ -1,19 +0,0 @@
MIT License
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.
-41
View File
@@ -1,41 +0,0 @@
#!/bin/sh
SYSROOT="${ANDROID_NDK_ROOT}"/toolchains/llvm/prebuilt/linux-x86_64/sysroot/
if ! test -d $SYSROOT; then
SYSROOT="${ANDROID_NDK_ROOT}"/toolchains/llvm/prebuilt/windows-x86_64/sysroot/
fi
while read ARCH && read TARGET ; do
# --module-raw-line 'use '
bindgen wrapper.h -o src/ffi_$ARCH.rs \
--blocklist-item 'JNI\w+' \
--blocklist-item 'C?_?JNIEnv' \
--blocklist-item '_?JavaVM' \
--blocklist-item '_?j\w+' \
--blocklist-item 'ALooper\w*' \
--blocklist-function 'ALooper\w*' \
--blocklist-item 'AAsset\w*' \
--blocklist-item 'AAssetManager\w*' \
--blocklist-function 'AAssetManager\w*' \
--blocklist-item 'ANativeWindow\w*' \
--blocklist-function 'ANativeWindow\w*' \
--blocklist-item 'AConfiguration\w*' \
--blocklist-function 'AConfiguration\w*' \
--blocklist-function 'android_main' \
--blocklist-item 'GameActivity_onCreate' \
--blocklist-function 'GameActivity_onCreate_C' \
--newtype-enum '\w+_(result|status)_t' \
-- \
-Icsrc \
--sysroot="$SYSROOT" --target=$TARGET
done << EOF
arm
arm-linux-androideabi
aarch64
aarch64-linux-android
i686
i686-linux-android
x86_64
x86_64-linux-android
EOF
-34
View File
@@ -1,34 +0,0 @@
//! The bindings are pre-generated and the right one for the platform is selected at compile time.
// Bindgen lints
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(improper_ctypes)]
#![allow(clippy::all)]
// Temporarily allow UB nullptr dereference in bindgen layout tests until fixed upstream:
// https://github.com/rust-lang/rust-bindgen/pull/2055
// https://github.com/rust-lang/rust-bindgen/pull/2064
#![allow(deref_nullptr)]
#![allow(dead_code)]
use jni_sys::*;
use ndk_sys::AAssetManager;
use ndk_sys::ANativeWindow;
use ndk_sys::{ALooper, ALooper_callbackFunc, AConfiguration};
#[cfg(all(
any(target_os = "android", feature = "test"),
any(target_arch = "arm", target_arch = "armv7")
))]
include!("ffi_arm.rs");
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "aarch64"))]
include!("ffi_aarch64.rs");
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "x86"))]
include!("ffi_i686.rs");
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "x86_64"))]
include!("ffi_x86_64.rs");
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-829
View File
@@ -1,829 +0,0 @@
use input::{Axis, InputEvent};
use jni_sys::*;
use log::{Level, error, trace};
use ndk::asset::AssetManager;
use ndk::configuration::Configuration;
use ndk::looper::{FdEvent};
use ndk::native_window::NativeWindow;
use ndk_sys::{ALooper_wake};
use ndk_sys::{ALooper, ALooper_pollAll};
use std::ffi::{CStr, CString};
use std::fs::File;
use std::hash::Hash;
use std::io::{BufRead, BufReader};
use std::marker::PhantomData;
use std::ops::Deref;
use std::os::raw;
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;
use std::{thread, ptr};
use std::os::unix::prelude::*;
use crate::input::{MotionEvent, KeyEvent};
#[cfg(not(any(target_os = "android", feature = "test")))]
compile_error!("android-ndk-sys only supports compiling for Android");
mod ffi;
pub mod input;
// Note: unlike in ndk-glue this has signed components (consistent
// with Android's ARect) which generally allows for representing
// rectangles with a negative/off-screen origin. Even though this
// is currently just used to represent the content rect (that probably
// wouldn't have any negative components) we keep the generality
// since this is a primitive type that could potentially be used
// for more things in the future.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Rect {
pub left: i32,
pub top: i32,
pub right: i32,
pub bottom: i32,
}
// XXX: NativeWindow is a ref-counted object but the NativeWindow rust API
// doesn't currently implement Clone() in terms of acquiring a reference
// and Drop() in terms of releasing a reference.
/// A reference to a `NativeWindow`, used for rendering
pub struct NativeWindowRef {
inner: NativeWindow
}
impl NativeWindowRef {
pub fn new(native_window: &NativeWindow) -> Self {
unsafe { ndk_sys::ANativeWindow_acquire(native_window.ptr().as_ptr()); }
Self { inner: native_window.clone() }
}
}
impl Drop for NativeWindowRef {
fn drop(&mut self) {
unsafe { ndk_sys::ANativeWindow_release(self.inner.ptr().as_ptr()) }
}
}
impl Deref for NativeWindowRef {
type Target = NativeWindow;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
// The only time it's safe to update the android_app->savedState pointer is
// while handling a SaveState event, so this API is only exposed for those
// events...
#[derive(Debug)]
pub struct StateSaver<'a> {
app: &'a AndroidApp,
}
impl<'a> StateSaver<'a> {
pub fn store(&self, state: &'a [u8]) {
// android_native_app_glue specifically expects savedState to have been allocated
// via libc::malloc since it will automatically handle freeing the data once it
// has been handed over to the Java Activity / main thread.
unsafe {
let app_ptr = self.app.ptr.as_ptr();
// In case the application calls store() multiple times for some reason we
// make sure to free any pre-existing state...
if (*app_ptr).savedState != ptr::null_mut() {
libc::free((*app_ptr).savedState);
(*app_ptr).savedState = ptr::null_mut();
(*app_ptr).savedStateSize = 0;
}
let buf = libc::malloc(state.len());
if buf == ptr::null_mut() {
panic!("Failed to allocate save_state buffer");
}
// Since it's a byte array there's no special alignment requirement here.
//
// Since we re-define `buf` we ensure it's not possible to access the buffer
// via its original pointer for the lifetime of the slice.
{
let buf: &mut [u8] = std::slice::from_raw_parts_mut(buf.cast(), state.len());
buf.copy_from_slice(state);
}
(*app_ptr).savedState = buf;
(*app_ptr).savedStateSize = state.len() as u64;
}
}
}
#[derive(Debug)]
pub struct StateLoader<'a> {
app: &'a AndroidApp,
}
impl<'a> StateLoader<'a> {
pub fn load(&self) -> Option<Vec<u8>> {
unsafe {
let app_ptr = self.app.ptr.as_ptr();
if (*app_ptr).savedState != ptr::null_mut() && (*app_ptr).savedStateSize > 0 {
let buf: &mut [u8] = std::slice::from_raw_parts_mut((*app_ptr).savedState.cast(), (*app_ptr).savedStateSize as usize);
let state = buf.to_vec();
Some(state)
} else {
None
}
}
}
}
// TODO: make more of these into non_exhaustive structs so it's possible to
// extend what data is passed to each event without breaking the API..
#[non_exhaustive]
#[derive(Debug)]
pub enum MainEvent<'a> {
/**
* Unused. Reserved for future use when usage of AInputQueue will be
* supported.
*/
//InputChanged,
/// Command from main thread: a new [`NativeWindow`] is ready for use. Upon
/// receiving this command, [`native_window()`] will return the new window
#[non_exhaustive]
InitWindow { },
/// Command from main thread: the existing [`NativeWindow`] needs to be
/// terminated. Upon receiving this command, [`native_window()`] still
/// returns the existing window; after returning from the [`AndroidApp::poll_events()`]
/// callback then [`native_window()`] will return `None`.
#[non_exhaustive]
TerminateWindow {},
// TODO: include the prev and new size in the event
/// Command from main thread: the current [`NativeWindow`] has been resized.
/// Please redraw with its new size.
#[non_exhaustive]
WindowResized {},
/// Command from main thread: the current [`NativeWindow`] needs to be redrawn.
/// You should redraw the window before the [`AndroidApp::poll_events()`]
/// callback returns in order to avoid transient drawing glitches.
#[non_exhaustive]
RedrawNeeded {},
/// Command from main thread: the content area of the window has changed,
/// such as from the soft input window being shown or hidden. You can
/// get the new content rect by calling [`AndroidApp::content_rect()`]
ContentRectChanged,
/// Command from main thread: the app's activity window has gained
/// input focus.
GainedFocus,
/// Command from main thread: the app's activity window has lost
/// input focus.
LostFocus,
/// Command from main thread: the current device configuration has changed.
/// You can get a copy of the latest [Configuration] by calling
/// [`AndroidApp::config()`]
ConfigChanged,
/// Command from main thread: the system is running low on memory.
/// Try to reduce your memory use.
LowMemory,
/// Command from main thread: the app's activity has been started.
Start,
/// Command from main thread: the app's activity has been resumed.
#[non_exhaustive]
Resume { loader: StateLoader<'a> },
/// Command from main thread: the app should generate a new saved state
/// for itself, to restore from later if needed. If you have saved state,
/// allocate it with malloc and place it in android_app.savedState with
/// the size in android_app.savedStateSize. The will be freed for you
/// later.
#[non_exhaustive]
SaveState { saver: StateSaver<'a> },
/// Command from main thread: the app's activity has been paused.
Pause,
/// Command from main thread: the app's activity has been stopped.
Stop,
/// Command from main thread: the app's activity is being destroyed,
/// and waiting for the app thread to clean up and exit before proceeding.
Destroy,
/// Command from main thread: the app's insets have changed.
#[non_exhaustive]
InsetsChanged {},
}
#[derive(Debug)]
#[non_exhaustive]
pub enum PollEvent<'a> {
Wake,
Timeout,
Main(MainEvent<'a>),
#[non_exhaustive]
FdEvent { ident: i32, fd: RawFd, events: FdEvent, data: *mut std::ffi::c_void },
Error
}
#[derive(Clone)]
pub struct AndroidAppWaker {
// The looper pointer is owned by the android_app and effectively
// has a 'static lifetime, and the ALooper_wake C API is thread
// safe, so this can be cloned safely and is send + sync safe
looper: NonNull<ALooper>
}
unsafe impl Send for AndroidAppWaker {}
unsafe impl Sync for AndroidAppWaker {}
impl AndroidAppWaker {
pub fn wake(&self) {
unsafe { ALooper_wake(self.looper.as_ptr()); }
}
}
#[derive(Debug, Clone)]
pub struct AndroidApp {
inner: Arc<AndroidAppInner>
}
impl PartialEq for AndroidApp {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
impl Eq for AndroidApp {}
impl Hash for AndroidApp {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.inner).hash(state);
}
}
impl Deref for AndroidApp {
type Target = Arc<AndroidAppInner>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
#[derive(Debug)]
pub struct AndroidAppInner {
ptr: NonNull<ffi::android_app>,
config: RwLock<Configuration>,
native_window: RwLock<Option<NativeWindow>>,
}
impl AndroidApp {
pub(crate) unsafe fn from_ptr(ptr: NonNull<ffi::android_app>) -> Self {
// Note: we don't use from_ptr since we don't own the android_app.config
// and need to keep in mind that the Drop handler is going to call
// AConfiguration_delete()
//
// Whenever we get a ConfigChanged notification we synchronize this
// config state with a deep copy.
let config = Configuration::clone_from_ptr(NonNull::new_unchecked((*ptr.as_ptr()).config));
Self {
inner: Arc::new(AndroidAppInner {
ptr,
config: RwLock::new(config),
native_window: Default::default(),
})
}
}
/// Queries the current [`NativeWindow`] for the application.
///
/// This will only return `Some(window)` between
/// [`AndroidAppMainEvent::InitWindow`] and [`AndroidAppMainEvent::TerminateWindow`]
/// events.
pub fn native_window<'a>(&self) -> Option<NativeWindowRef> {
let guard = self.native_window.read().unwrap();
if let Some(ref window) = *guard {
Some(NativeWindowRef::new(window))
} else {
None
}
}
/// Calls [`ALooper_pollAll`] on the looper associated with this AndroidApp as well
/// as processing any events (such as lifecycle events) via the given `callback`.
///
/// It's important to use this API for polling, and not call [`ALooper_pollAll`] directly since
/// some events require pre- and post-processing either side of the callback. For correct
/// behavior events should be handled immediately, before returning from the callback and
/// not simply queued for batch processing later. For example the existing [`NativeWindow`]
/// is accessible during a [`MainEvent::TerminateWindow`] callback and will be
/// set to `None` once the callback returns, and this is also synchronized with the Java
/// main thread. The [`MainEvent::SaveState`] event is also synchronized with the
/// Java main thread.
///
/// # Safety
/// This API must only be called from the applications main thread
pub fn poll_events<F>(&self, timeout: Option<Duration>, mut callback: F)
where F: FnMut(PollEvent)
{
trace!("poll_events");
unsafe {
let app_ptr = self.ptr;
let mut fd: i32 = 0;
let mut events: i32 = 0;
let mut source: *mut core::ffi::c_void = ptr::null_mut();
let timeout_milliseconds = if let Some(timeout) = timeout { timeout.as_millis() as i32 } else { -1 };
trace!("Calling ALooper_pollAll, timeout = {timeout_milliseconds}");
let id = ALooper_pollAll(timeout_milliseconds, &mut fd, &mut events, &mut source as *mut *mut core::ffi::c_void);
match id {
ffi::ALOOPER_POLL_WAKE => {
trace!("ALooper_pollAll returned POLL_WAKE");
callback(PollEvent::Wake);
}
ffi::ALOOPER_POLL_CALLBACK => {
// ALooper_pollAll is documented to handle all callback sources internally so it should
// never return a _CALLBACK source id...
error!("Spurious ALOOPER_POLL_CALLBACK from ALopper_pollAll() (ignored)");
}
ffi::ALOOPER_POLL_TIMEOUT => {
trace!("ALooper_pollAll returned POLL_TIMEOUT");
callback(PollEvent::Timeout);
}
ffi::ALOOPER_POLL_ERROR => {
trace!("ALooper_pollAll returned POLL_ERROR");
callback(PollEvent::Error);
// Considering that this API is quite likely to be used in `android_main`
// it's rather unergonomic to require the call to unwrap a Result for each
// call to poll_events(). Alternatively we could maybe even just panic!()
// here, while it's hard to imagine practically being able to recover
//return Err(LooperError);
}
id if id >= 0 => {
match id as u32 {
ffi::NativeAppGlueLooperId_LOOPER_ID_MAIN => {
trace!("ALooper_pollAll returned ID_MAIN");
let source: *mut ffi::android_poll_source = source.cast();
if source != ptr::null_mut() {
let cmd_i = ffi::android_app_read_cmd(app_ptr.as_ptr());
let cmd = match cmd_i as u32 {
//NativeAppGlueAppCmd_UNUSED_APP_CMD_INPUT_CHANGED => AndroidAppMainEvent::InputChanged,
ffi::NativeAppGlueAppCmd_APP_CMD_INIT_WINDOW => MainEvent::InitWindow {},
ffi::NativeAppGlueAppCmd_APP_CMD_TERM_WINDOW => MainEvent::TerminateWindow {},
ffi::NativeAppGlueAppCmd_APP_CMD_WINDOW_RESIZED => MainEvent::WindowResized {},
ffi::NativeAppGlueAppCmd_APP_CMD_WINDOW_REDRAW_NEEDED => MainEvent::RedrawNeeded {},
ffi::NativeAppGlueAppCmd_APP_CMD_CONTENT_RECT_CHANGED => MainEvent::ContentRectChanged,
ffi::NativeAppGlueAppCmd_APP_CMD_GAINED_FOCUS => MainEvent::GainedFocus,
ffi::NativeAppGlueAppCmd_APP_CMD_LOST_FOCUS => MainEvent::LostFocus,
ffi::NativeAppGlueAppCmd_APP_CMD_CONFIG_CHANGED => MainEvent::ConfigChanged,
ffi::NativeAppGlueAppCmd_APP_CMD_LOW_MEMORY => MainEvent::LowMemory,
ffi::NativeAppGlueAppCmd_APP_CMD_START => MainEvent::Start,
ffi::NativeAppGlueAppCmd_APP_CMD_RESUME => MainEvent::Resume { loader: StateLoader { app: &self } },
ffi::NativeAppGlueAppCmd_APP_CMD_SAVE_STATE => MainEvent::SaveState { saver: StateSaver { app: &self } },
ffi::NativeAppGlueAppCmd_APP_CMD_PAUSE => MainEvent::Pause,
ffi::NativeAppGlueAppCmd_APP_CMD_STOP => MainEvent::Stop,
ffi::NativeAppGlueAppCmd_APP_CMD_DESTROY => MainEvent::Destroy,
ffi::NativeAppGlueAppCmd_APP_CMD_WINDOW_INSETS_CHANGED => MainEvent::InsetsChanged {},
_ => unreachable!()
};
trace!("Read ID_MAIN command {cmd_i} = {cmd:?}");
trace!("Calling android_app_pre_exec_cmd({cmd_i})");
ffi::android_app_pre_exec_cmd(app_ptr.as_ptr(), cmd_i);
match cmd {
MainEvent::ConfigChanged => {
*self.config.write().unwrap() =
Configuration::clone_from_ptr(NonNull::new_unchecked((*app_ptr.as_ptr()).config));
}
MainEvent::InitWindow { .. } => {
let win_ptr = (*app_ptr.as_ptr()).window;
*self.native_window.write().unwrap() =
Some(NativeWindow::from_ptr(NonNull::new(win_ptr).unwrap()));
}
MainEvent::TerminateWindow { .. } => {
*self.native_window.write().unwrap() = None;
}
_ => {}
}
trace!("Invoking callback for ID_MAIN command = {:?}", cmd);
callback(PollEvent::Main(cmd));
trace!("Calling android_app_post_exec_cmd({cmd_i})");
ffi::android_app_post_exec_cmd(app_ptr.as_ptr(), cmd_i);
} else {
panic!("ALooper_pollAll returned ID_MAIN event with NULL android_poll_source!");
}
}
_ => {
let events = FdEvent::from_bits(events as u32)
.expect(&format!("Spurious ALooper_pollAll event flags {:#04x}", events as u32));
trace!("Custom ALooper event source: id = {id}, fd = {fd}, events = {events:?}, data = {source:?}");
callback(PollEvent::FdEvent{ ident: id, fd: fd as RawFd, events, data: source });
}
}
}
_ => {
error!("Spurious ALooper_pollAll return value {id} (ignored)");
}
}
}
}
/// Enables the capture of the given `axis` for pointer input events
///
/// By default only the X and Y axis are captured for pointer events and any other
/// axis must be explicitly enabled / disabled
pub fn enable_motion_axis(&self, axis: Axis) {
unsafe {
ffi::GameActivityPointerAxes_enableAxis(axis as i32)
}
}
/// Disables the capture of the given `axis` for pointer input events
///
/// By default only the X and Y axis are captured for pointer events and any other
/// axis must be explicitly enabled / disabled
pub fn disable_motion_axis(&self, axis: Axis) {
unsafe {
ffi::GameActivityPointerAxes_disableAxis(axis as i32)
}
}
/// Creates a means to wake up the main loop while it is blocked waiting for
/// events within [`poll_events()`].
///
/// Internally this uses [`ALooper_wake`] on the looper associated with this
/// [AndroidApp].
///
/// # Safety
/// This API can be used from any thread
pub fn create_waker(&self) -> AndroidAppWaker {
unsafe {
// From the application's pov we assume the app_ptr and looper pointer
// have static lifetimes and we can safely assume they are never NULL.
let app_ptr = self.ptr.as_ptr();
AndroidAppWaker { looper: NonNull::new_unchecked((*app_ptr).looper) }
}
}
/// Returns a deep copy of this application's [`Configuration`]
pub fn config(&self) -> Configuration {
self.config.read().unwrap().clone()
}
/// Queries the current content rectangle of the window; this is the area where the
/// window's content should be placed to be seen by the user.
///
/// # Safety
/// This API must only be called from the applications main thread
pub fn content_rect(&self) -> Rect {
unsafe {
let app_ptr = self.ptr.as_ptr();
Rect {
left: (*app_ptr).contentRect.left,
right: (*app_ptr).contentRect.right,
top: (*app_ptr).contentRect.top,
bottom: (*app_ptr).contentRect.bottom,
}
}
}
/// Queries the Asset Manager instance for the application.
///
/// Use this to access binary assets bundled inside your application's .apk file.
///
/// # Safety
/// This API must only be called from the applications main thread
pub fn asset_manager(&self) -> AssetManager {
unsafe {
let app_ptr = self.ptr.as_ptr();
let am_ptr = NonNull::new_unchecked((*(*app_ptr).activity).assetManager);
AssetManager::from_ptr(am_ptr)
}
}
/// Process all currently buffered input events
///
/// Internally input events are captured asynchronously (within the Java
/// main thread) and double buffered so that the application can safely read
/// and process one buffer while further input events may continue to be
/// accumulated in the other buffer. Each call to this API will trigger an
/// internal buffer swap.
///
/// Input capture is notably not currently integrated with [`poll_events()`]
/// or the internal `Looper`, which means it's expected that applications
/// explicitly check for events (e.g. as part of preparing a new frame to
/// render). I.e. this is a pull model, not a push model; input events aren't
/// immediately delivered as they arrive. One benefit of this design is that
/// detailed input events can be buffered and processed more efficiently as
/// a batch at a time that's most appropriate for your application. One
/// disadvantage though is that your application won't be woken up purely
/// due to input events and so you need some other external trigger to ensure
/// input is checked periodically. This is currently best suited to games
/// that render continuously.
///
/// To optimize the capture of pointer data then by default only the X
/// and Y pointer [Axis] are recorded. Additional axis can be enabled and
/// disabled via [`enable_motion_axis()`] and [`disable_motion_axis()`]
///
/// # Safety
/// This API must only be called from the applications main thread
pub fn input_events<'b, F>(&self, mut callback: F)
where F: FnMut(&InputEvent)
{
let buf = unsafe {
let app_ptr = self.ptr.as_ptr();
let input_buffer = ffi::android_app_swap_input_buffers(app_ptr);
if input_buffer == ptr::null_mut() {
return;
}
InputBuffer::from_ptr(NonNull::new_unchecked(input_buffer))
};
for key_event in buf.key_events_iter() {
callback(&InputEvent::KeyEvent(key_event));
}
for motion_event in buf.motion_events_iter() {
callback(&InputEvent::MotionEvent(motion_event));
}
}
/// The user-visible SDK version of the framework
///
/// Also referred to as [`Build.VERSION_CODES`](https://developer.android.com/reference/android/os/Build.VERSION_CODES)
pub fn sdk_version() -> i32 {
let mut prop = android_properties::getprop("ro.build.version.sdk");
if let Some(val) = prop.value() {
i32::from_str_radix(&val, 10).expect("Failed to parse ro.build.version.sdk property")
} else {
panic!("Couldn't read ro.build.version.sdk system property");
}
}
fn try_get_path_from_ptr(path: *const u8) -> Option<std::path::PathBuf> {
if path == ptr::null() { return None; }
let cstr = unsafe {
let cstr_slice = CStr::from_ptr(path);
cstr_slice.to_str().ok()?
};
if cstr.len() == 0 { return None; }
Some(std::path::PathBuf::from(cstr))
}
/// Path to this application's internal data directory
pub fn internal_data_path(&self) -> Option<std::path::PathBuf> {
unsafe {
let app_ptr = self.ptr.as_ptr();
Self::try_get_path_from_ptr((*(*app_ptr).activity).internalDataPath)
}
}
/// Path to this application's external data directory
pub fn external_data_path(&self) -> Option<std::path::PathBuf> {
unsafe {
let app_ptr = self.ptr.as_ptr();
Self::try_get_path_from_ptr((*(*app_ptr).activity).externalDataPath)
}
}
/// Path to the directory containing the application's OBB files (if any).
pub fn obb_path(&self) -> Option<std::path::PathBuf> {
unsafe {
let app_ptr = self.ptr.as_ptr();
Self::try_get_path_from_ptr((*(*app_ptr).activity).obbPath)
}
}
}
struct MotionEventsIterator<'a> {
pos: usize,
count: usize,
buffer: &'a InputBuffer<'a>
}
impl<'a> Iterator for MotionEventsIterator<'a> {
type Item = MotionEvent;
fn next(&mut self) -> Option<Self::Item> {
if self.pos < self.count {
unsafe {
let ga_event = (*self.buffer.ptr.as_ptr()).motionEvents[self.pos];
let event = MotionEvent::new(ga_event);
self.pos += 1;
Some(event)
}
} else {
None
}
}
}
struct KeyEventsIterator<'a> {
pos: usize,
count: usize,
buffer: &'a InputBuffer<'a>
}
impl<'a> Iterator for KeyEventsIterator<'a> {
type Item = KeyEvent;
fn next(&mut self) -> Option<Self::Item> {
if self.pos < self.count {
unsafe {
let ga_event = (*self.buffer.ptr.as_ptr()).keyEvents[self.pos];
let event = KeyEvent::new(ga_event);
self.pos += 1;
Some(event)
}
} else {
None
}
}
}
struct InputBuffer<'a> {
ptr: NonNull<ffi::android_input_buffer>,
_lifetime: PhantomData<&'a ffi::android_input_buffer>
}
impl<'a> InputBuffer<'a> {
pub(crate) fn from_ptr(ptr: NonNull<ffi::android_input_buffer>) -> InputBuffer<'a> {
Self {
ptr,
_lifetime: PhantomData::default()
}
}
// XXX: It's really not ideal here that Rust iterators can't yield values
// that borrow from the iterator, so we implicitly have to copy the
// events as we iterate...
pub fn motion_events_iter<'b>(&'b self) -> MotionEventsIterator<'b> {
unsafe {
let count = (*self.ptr.as_ptr()).motionEventsCount as usize;
MotionEventsIterator { pos: 0, count, buffer: self }
}
}
pub fn key_events_iter<'b>(&'b self) -> KeyEventsIterator<'b> {
unsafe {
let count = (*self.ptr.as_ptr()).keyEventsCount as usize;
KeyEventsIterator { pos: 0, count, buffer: self }
}
}
}
impl<'a> Drop for InputBuffer<'a> {
fn drop(&mut self) {
unsafe {
ffi::android_app_clear_motion_events(self.ptr.as_ptr());
ffi::android_app_clear_key_events(self.ptr.as_ptr());
}
}
}
// Rust doesn't give us a clean way to directly export symbols from C/C++
// so we rename the C/C++ symbols and re-export these JNI entrypoints from
// Rust...
//
// https://github.com/rust-lang/rfcs/issues/2771
extern "C" {
pub fn Java_com_google_androidgamesdk_GameActivity_loadNativeCode_C(
env: *mut JNIEnv,
javaGameActivity: jobject,
path: jstring,
funcName: jstring,
internalDataDir: jstring,
obbDir: jstring,
externalDataDir: jstring,
jAssetMgr: jobject,
savedState: jbyteArray,
) -> jlong;
pub fn GameActivity_onCreate_C(
activity: *mut ffi::GameActivity,
savedState: *mut ::std::os::raw::c_void,
savedStateSize: ffi::size_t,
);
}
#[no_mangle]
pub unsafe extern "C" fn Java_com_google_androidgamesdk_GameActivity_loadNativeCode(
env: *mut JNIEnv,
java_game_activity: jobject,
path: jstring,
func_name: jstring,
internal_data_dir: jstring,
obb_dir: jstring,
external_data_dir: jstring,
jasset_mgr: jobject,
saved_state: jbyteArray,
) -> jni_sys::jlong
{
Java_com_google_androidgamesdk_GameActivity_loadNativeCode_C(env, java_game_activity, path, func_name,
internal_data_dir, obb_dir, external_data_dir, jasset_mgr, saved_state)
}
#[no_mangle]
pub unsafe extern "C" fn GameActivity_onCreate(
activity: *mut ffi::GameActivity,
saved_state: *mut ::std::os::raw::c_void,
saved_state_size: ffi::size_t,
)
{
GameActivity_onCreate_C(activity, saved_state, saved_state_size);
}
fn android_log(level: Level, tag: &CStr, msg: &CStr) {
let prio = match level {
Level::Error => ndk_sys::android_LogPriority_ANDROID_LOG_ERROR,
Level::Warn => ndk_sys::android_LogPriority_ANDROID_LOG_WARN,
Level::Info => ndk_sys::android_LogPriority_ANDROID_LOG_INFO,
Level::Debug => ndk_sys::android_LogPriority_ANDROID_LOG_DEBUG,
Level::Trace => ndk_sys::android_LogPriority_ANDROID_LOG_VERBOSE,
};
unsafe {
ndk_sys::__android_log_write(prio as raw::c_int, tag.as_ptr(), msg.as_ptr());
}
}
extern "Rust" {
pub fn android_main(app: AndroidApp);
}
// This is a spring board between android_native_app_glue and the user's
// `app_main` function. This is run on a dedicated thread spawned
// by android_native_app_glue.
#[no_mangle]
pub unsafe extern "C" fn _rust_glue_entry(app: *mut ffi::android_app) {
// Maybe make this stdout/stderr redirection an optional / opt-in feature?...
let mut logpipe: [RawFd; 2] = Default::default();
libc::pipe(logpipe.as_mut_ptr());
libc::dup2(logpipe[1], libc::STDOUT_FILENO);
libc::dup2(logpipe[1], libc::STDERR_FILENO);
thread::spawn(move || {
let tag = CStr::from_bytes_with_nul(b"RustStdoutStderr\0").unwrap();
let file = File::from_raw_fd(logpipe[0]);
let mut reader = BufReader::new(file);
let mut buffer = String::new();
loop {
buffer.clear();
if let Ok(len) = reader.read_line(&mut buffer) {
if len == 0 {
break;
} else if let Ok(msg) = CString::new(buffer.clone()) {
android_log(Level::Info, tag, &msg);
}
}
}
});
let jvm: *mut JavaVM = (*(*app).activity).vm;
let activity: jobject = (*(*app).activity).javaGameActivity;
ndk_context::initialize_android_context(jvm.cast(), activity.cast());
let app = AndroidApp::from_ptr(NonNull::new(app).unwrap());
// Since this is a newly spawned thread then the JVM hasn't been attached
// to the thread yet. Attach before calling the applications main function
// so they can safely make JNI calls
let mut jenv_out: *mut core::ffi::c_void = std::ptr::null_mut();
if let Some(attach_current_thread) = (*(*jvm)).AttachCurrentThread {
attach_current_thread(jvm, &mut jenv_out, std::ptr::null_mut());
}
// XXX: If we were in control of the Java Activity subclass then
// we could potentially run the android_main function via a Java native method
// springboard (e.g. call an Activity subclass method that calls a jni native
// method that then just calls android_main()) that would make sure there was
// a Java frame at the base of our call stack which would then be recognised
// when calling FindClass to lookup a suitable classLoader, instead of
// defaulting to the system loader. Without this then it's difficult for native
// code to look up non-standard Java classes.
android_main(app);
// Since this is a newly spawned thread then the JVM hasn't been attached
// to the thread yet. Attach before calling the applications main function
// so they can safely make JNI calls
if let Some(detach_current_thread) = (*(*jvm)).DetachCurrentThread {
detach_current_thread(jvm);
}
ndk_context::release_android_context();
}
-3
View File
@@ -1,3 +0,0 @@
#include <game-activity/GameActivity.h>
#include <game-activity/native_app_glue/android_native_app_glue.h>
#include <game-text-input/gametextinput.h>
-10
View File
@@ -1,10 +0,0 @@
/target
Cargo.lock
# Added by cargo
#
# already existing elements were commented out
#/target
#Cargo.lock
-30
View File
@@ -1,30 +0,0 @@
[package]
name = "native-activity"
version = "0.1.0"
edition = "2021"
keywords = ["android", "ndk"]
readme = "../README.md"
license = "MIT OR Apache-2.0"
[dependencies]
log = "0.4"
jni-sys = "0.3"
ndk = { version = "0.6" }
ndk-sys = { version = "0.3" }
ndk-context = { version = "0.1" }
android-properties = "0.2"
lazy_static = "1.4.0"
num_enum = "0.5"
bitflags = "1.3"
libc = "0.2.84"
[build-dependencies]
cc = { version = "1.0", features = ["parallel"] }
[package.metadata.docs.rs]
targets = [
"aarch64-linux-android",
"armv7-linux-androideabi",
"i686-linux-android",
"x86_64-linux-android",
]
-12
View File
@@ -1,12 +0,0 @@
The third-party glue code, from the Android Game Development Kit, under the csrc/ directory
is covered by the Apache 2.0 license only:
Apache License, Version 2.0 (docs/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
All other code is dual-licensed under either
* MIT License (docs/LICENSE-MIT or http://opensource.org/licenses/MIT)
* Apache License, Version 2.0 (docs/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
at your option.
-39
View File
@@ -1,39 +0,0 @@
This crate provides a "glue" layer for building native Rust applications on Android which aims to be API compatible with the `game-activity` crate as far as possible but is based on the `NativeActivity` class instead on `GameActivity`.
The idea is to figure out if there's some minimal subset API that could potentially be factored out into a standard "glue" crate which could potentially be used by Winit. This way it might be more practical to support a wider variety of `Activity` base classes for Android applications when they don't affect how Winit works.
# Why not pure Rust?
The `android_native_app_glue` library that's provided by the NDK happens to be written in C and it has been well tested and works. Considering the somewhat fiddly thread synchronization that needs to be done for specific events like window terminations or state saves then it seems wise to re-use this logic instead of re-implementing it.
The android_native_app_glue code isn't _that_ complex and could potentially be re-implemented in Rust at some point, although it's not clear how beneficial it would be. I would note that `ndk-glue` did go down the route of re-implementing the glue layer for `NativeActivity` purely in Rust but I wasn't confident that it's synchronization model was correct. (See here for more discussion: https://github.com/rust-windowing/winit/issues/2293)
# Synchronizing with Upstream...
Upstream distribute `android_native_app_glue.c` as part of the NDK under `$ANDROID_NDK_HOME/sources/android/native_app_glue/android_native_app_glue.c`
This code is something like >10 years old and isn't expected to change.
## Minor modifications
`NativeActivity_onCreate` should be renamed to `NativeActivity_onCreate_C` because Rust/Cargo doesn't support compiling C/C++ code in a way that can export these symbols directly and we instead have to export wrappers from Rust code.
Since we want to call the application's main function from Rust after initializing our own `AndroidApp` state, but we want to let applications use the same `android_main` symbol name then `android_main` should be renamed to `_rust_glue_entry` in `android_native_app_glue.h` and `android_native_app_glue.c`
The `ID_INPUT` looper event source is disabled because we decouple polling + emitting events from input handling (I.e we expect applications to _pull_ input events when they want them instead of _push_ input events immediately). For now it's assumed that applications will explicitly check for input based as part of processing a new frame.
_(The technical difficulty with the input source is that once it triggers an event then it won't stop triggering events until all the outstanding events are read - which isn't compatible with allowing applications to explicitly check for input instead of immediately pushing input events at them (all other mainloop events will become drowned out by the input source). Unfortunately the looper API doesn't expose `epoll`'s edge triggering which would probably be ideal in this case.)_
## Generate Rust bindings
Since we know we only care about android build targets then to simplify the build we pre-generate Rust bindings for the C/C++ headers using bindgen via `generate-bindings.sh`
Install bindgen via `cargo install bindgen`
`export ANDROID_NDK_ROOT=/path/to/ndk` so that `generate-bindings.sh` can find suitable sysroot headers.
Run `./generate-bindings.sh` from the top of the repo after putting the latest prefab source/headers under `csrc/`
-8
View File
@@ -1,8 +0,0 @@
fn main() {
cc::Build::new()
.include("csrc")
.include("csrc/native-activity/native_app_glue")
.file("csrc/native-activity/native_app_glue/android_native_app_glue.c")
.compile("libnative_app_glue.a");
}
@@ -1,444 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <jni.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/resource.h>
#include "android_native_app_glue.h"
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "threaded_app", __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "threaded_app", __VA_ARGS__))
/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
# define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "threaded_app", __VA_ARGS__))
#else
# define LOGV(...) ((void)0)
#endif
static void free_saved_state(struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
if (android_app->savedState != NULL) {
free(android_app->savedState);
android_app->savedState = NULL;
android_app->savedStateSize = 0;
}
pthread_mutex_unlock(&android_app->mutex);
}
int8_t android_app_read_cmd(struct android_app* android_app) {
int8_t cmd;
if (read(android_app->msgread, &cmd, sizeof(cmd)) == sizeof(cmd)) {
switch (cmd) {
case APP_CMD_SAVE_STATE:
free_saved_state(android_app);
break;
}
return cmd;
} else {
LOGE("No data on command pipe!");
}
return -1;
}
static void print_cur_config(struct android_app* android_app) {
char lang[2], country[2];
AConfiguration_getLanguage(android_app->config, lang);
AConfiguration_getCountry(android_app->config, country);
LOGV("Config: mcc=%d mnc=%d lang=%c%c cnt=%c%c orien=%d touch=%d dens=%d "
"keys=%d nav=%d keysHid=%d navHid=%d sdk=%d size=%d long=%d "
"modetype=%d modenight=%d",
AConfiguration_getMcc(android_app->config),
AConfiguration_getMnc(android_app->config),
lang[0], lang[1], country[0], country[1],
AConfiguration_getOrientation(android_app->config),
AConfiguration_getTouchscreen(android_app->config),
AConfiguration_getDensity(android_app->config),
AConfiguration_getKeyboard(android_app->config),
AConfiguration_getNavigation(android_app->config),
AConfiguration_getKeysHidden(android_app->config),
AConfiguration_getNavHidden(android_app->config),
AConfiguration_getSdkVersion(android_app->config),
AConfiguration_getScreenSize(android_app->config),
AConfiguration_getScreenLong(android_app->config),
AConfiguration_getUiModeType(android_app->config),
AConfiguration_getUiModeNight(android_app->config));
}
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case APP_CMD_INPUT_CHANGED:
LOGV("APP_CMD_INPUT_CHANGED\n");
pthread_mutex_lock(&android_app->mutex);
if (android_app->inputQueue != NULL) {
//AInputQueue_detachLooper(android_app->inputQueue);
}
android_app->inputQueue = android_app->pendingInputQueue;
if (android_app->inputQueue != NULL) {
//LOGV("Attaching input queue to looper");
//AInputQueue_attachLooper(android_app->inputQueue,
// android_app->looper, LOOPER_ID_INPUT, NULL,
// &android_app->inputPollSource);
}
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_INIT_WINDOW:
LOGV("APP_CMD_INIT_WINDOW\n");
pthread_mutex_lock(&android_app->mutex);
android_app->window = android_app->pendingWindow;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW\n");
pthread_cond_broadcast(&android_app->cond);
break;
case APP_CMD_RESUME:
case APP_CMD_START:
case APP_CMD_PAUSE:
case APP_CMD_STOP:
LOGV("activityState=%d\n", cmd);
pthread_mutex_lock(&android_app->mutex);
android_app->activityState = cmd;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_CONFIG_CHANGED:
LOGV("APP_CMD_CONFIG_CHANGED\n");
AConfiguration_fromAssetManager(android_app->config,
android_app->activity->assetManager);
print_cur_config(android_app);
break;
case APP_CMD_DESTROY:
LOGV("APP_CMD_DESTROY\n");
android_app->destroyRequested = 1;
break;
}
}
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW\n");
pthread_mutex_lock(&android_app->mutex);
android_app->window = NULL;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_SAVE_STATE:
LOGV("APP_CMD_SAVE_STATE\n");
pthread_mutex_lock(&android_app->mutex);
android_app->stateSaved = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_RESUME:
free_saved_state(android_app);
break;
}
}
void app_dummy() {
}
static void android_app_destroy(struct android_app* android_app) {
LOGV("android_app_destroy!");
free_saved_state(android_app);
pthread_mutex_lock(&android_app->mutex);
if (android_app->inputQueue != NULL) {
AInputQueue_detachLooper(android_app->inputQueue);
}
AConfiguration_delete(android_app->config);
android_app->destroyed = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
// Can't touch android_app object after this.
}
/*
static void process_input(struct android_app* app, __attribute__((unused)) struct android_poll_source* source) {
AInputEvent* event = NULL;
while (AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
LOGV("New input event: type=%d\n", AInputEvent_getType(event));
if (AInputQueue_preDispatchEvent(app->inputQueue, event)) {
continue;
}
int32_t handled = 0;
if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event);
AInputQueue_finishEvent(app->inputQueue, event, handled);
}
}
*/
static void process_cmd(struct android_app* app, __attribute__((unused)) struct android_poll_source* source) {
int8_t cmd = android_app_read_cmd(app);
android_app_pre_exec_cmd(app, cmd);
if (app->onAppCmd != NULL) app->onAppCmd(app, cmd);
android_app_post_exec_cmd(app, cmd);
}
static void* android_app_entry(void* param) {
struct android_app* android_app = (struct android_app*)param;
android_app->config = AConfiguration_new();
AConfiguration_fromAssetManager(android_app->config, android_app->activity->assetManager);
print_cur_config(android_app);
android_app->cmdPollSource.id = LOOPER_ID_MAIN;
android_app->cmdPollSource.app = android_app;
android_app->cmdPollSource.process = process_cmd;
//android_app->inputPollSource.id = LOOPER_ID_INPUT;
//android_app->inputPollSource.app = android_app;
//android_app->inputPollSource.process = process_input;
ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, NULL,
&android_app->cmdPollSource);
android_app->looper = looper;
pthread_mutex_lock(&android_app->mutex);
android_app->running = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
_rust_glue_entry(android_app);
android_app_destroy(android_app);
return NULL;
}
// --------------------------------------------------------------------
// Native activity interaction (called from main thread)
// --------------------------------------------------------------------
static struct android_app* android_app_create(ANativeActivity* activity,
void* savedState, size_t savedStateSize) {
struct android_app* android_app = (struct android_app*)malloc(sizeof(struct android_app));
memset(android_app, 0, sizeof(struct android_app));
android_app->activity = activity;
pthread_mutex_init(&android_app->mutex, NULL);
pthread_cond_init(&android_app->cond, NULL);
if (savedState != NULL) {
android_app->savedState = malloc(savedStateSize);
android_app->savedStateSize = savedStateSize;
memcpy(android_app->savedState, savedState, savedStateSize);
}
int msgpipe[2];
if (pipe(msgpipe)) {
LOGE("could not create pipe: %s", strerror(errno));
return NULL;
}
android_app->msgread = msgpipe[0];
android_app->msgwrite = msgpipe[1];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&android_app->thread, &attr, android_app_entry, android_app);
// Wait for thread to start.
pthread_mutex_lock(&android_app->mutex);
while (!android_app->running) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
return android_app;
}
static void android_app_write_cmd(struct android_app* android_app, int8_t cmd) {
if (write(android_app->msgwrite, &cmd, sizeof(cmd)) != sizeof(cmd)) {
LOGE("Failure writing android_app cmd: %s\n", strerror(errno));
}
}
static void android_app_set_input(struct android_app* android_app, AInputQueue* inputQueue) {
pthread_mutex_lock(&android_app->mutex);
android_app->pendingInputQueue = inputQueue;
android_app_write_cmd(android_app, APP_CMD_INPUT_CHANGED);
while (android_app->inputQueue != android_app->pendingInputQueue) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_set_window(struct android_app* android_app, ANativeWindow* window) {
pthread_mutex_lock(&android_app->mutex);
if (android_app->pendingWindow != NULL) {
android_app_write_cmd(android_app, APP_CMD_TERM_WINDOW);
}
android_app->pendingWindow = window;
if (window != NULL) {
android_app_write_cmd(android_app, APP_CMD_INIT_WINDOW);
}
while (android_app->window != android_app->pendingWindow) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_set_activity_state(struct android_app* android_app, int8_t cmd) {
pthread_mutex_lock(&android_app->mutex);
android_app_write_cmd(android_app, cmd);
while (android_app->activityState != cmd) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_free(struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
android_app_write_cmd(android_app, APP_CMD_DESTROY);
while (!android_app->destroyed) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
close(android_app->msgread);
close(android_app->msgwrite);
pthread_cond_destroy(&android_app->cond);
pthread_mutex_destroy(&android_app->mutex);
free(android_app);
}
static void onDestroy(ANativeActivity* activity) {
LOGV("Destroy: %p\n", activity);
android_app_free((struct android_app*)activity->instance);
}
static void onStart(ANativeActivity* activity) {
LOGV("Start: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_START);
}
static void onResume(ANativeActivity* activity) {
LOGV("Resume: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_RESUME);
}
static void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen) {
struct android_app* android_app = (struct android_app*)activity->instance;
void* savedState = NULL;
LOGV("SaveInstanceState: %p\n", activity);
pthread_mutex_lock(&android_app->mutex);
android_app->stateSaved = 0;
android_app_write_cmd(android_app, APP_CMD_SAVE_STATE);
while (!android_app->stateSaved) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
if (android_app->savedState != NULL) {
savedState = android_app->savedState;
*outLen = android_app->savedStateSize;
android_app->savedState = NULL;
android_app->savedStateSize = 0;
}
pthread_mutex_unlock(&android_app->mutex);
return savedState;
}
static void onPause(ANativeActivity* activity) {
LOGV("Pause: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_PAUSE);
}
static void onStop(ANativeActivity* activity) {
LOGV("Stop: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_STOP);
}
static void onConfigurationChanged(ANativeActivity* activity) {
struct android_app* android_app = (struct android_app*)activity->instance;
LOGV("ConfigurationChanged: %p\n", activity);
android_app_write_cmd(android_app, APP_CMD_CONFIG_CHANGED);
}
static void onLowMemory(ANativeActivity* activity) {
struct android_app* android_app = (struct android_app*)activity->instance;
LOGV("LowMemory: %p\n", activity);
android_app_write_cmd(android_app, APP_CMD_LOW_MEMORY);
}
static void onWindowFocusChanged(ANativeActivity* activity, int focused) {
LOGV("WindowFocusChanged: %p -- %d\n", activity, focused);
android_app_write_cmd((struct android_app*)activity->instance,
focused ? APP_CMD_GAINED_FOCUS : APP_CMD_LOST_FOCUS);
}
static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) {
LOGV("NativeWindowCreated: %p -- %p\n", activity, window);
android_app_set_window((struct android_app*)activity->instance, window);
}
static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window) {
LOGV("NativeWindowDestroyed: %p -- %p\n", activity, window);
android_app_set_window((struct android_app*)activity->instance, NULL);
}
static void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue) {
LOGV("InputQueueCreated: %p -- %p\n", activity, queue);
android_app_set_input((struct android_app*)activity->instance, queue);
}
static void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue) {
LOGV("InputQueueDestroyed: %p -- %p\n", activity, queue);
android_app_set_input((struct android_app*)activity->instance, NULL);
}
JNIEXPORT
void ANativeActivity_onCreate_C(ANativeActivity* activity, void* savedState,
size_t savedStateSize) {
LOGV("Creating: %p\n", activity);
activity->callbacks->onDestroy = onDestroy;
activity->callbacks->onStart = onStart;
activity->callbacks->onResume = onResume;
activity->callbacks->onSaveInstanceState = onSaveInstanceState;
activity->callbacks->onPause = onPause;
activity->callbacks->onStop = onStop;
activity->callbacks->onConfigurationChanged = onConfigurationChanged;
activity->callbacks->onLowMemory = onLowMemory;
activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;
activity->callbacks->onNativeWindowCreated = onNativeWindowCreated;
activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed;
activity->callbacks->onInputQueueCreated = onInputQueueCreated;
activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed;
activity->instance = android_app_create(activity, savedState, savedStateSize);
}
@@ -1,354 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _ANDROID_NATIVE_APP_GLUE_H
#define _ANDROID_NATIVE_APP_GLUE_H
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <android/configuration.h>
#include <android/looper.h>
#include <android/native_activity.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* The native activity interface provided by <android/native_activity.h>
* is based on a set of application-provided callbacks that will be called
* by the Activity's main thread when certain events occur.
*
* This means that each one of this callbacks _should_ _not_ block, or they
* risk having the system force-close the application. This programming
* model is direct, lightweight, but constraining.
*
* The 'android_native_app_glue' static library is used to provide a different
* execution model where the application can implement its own main event
* loop in a different thread instead. Here's how it works:
*
* 1/ The application must provide a function named "android_main()" that
* will be called when the activity is created, in a new thread that is
* distinct from the activity's main thread.
*
* 2/ android_main() receives a pointer to a valid "android_app" structure
* that contains references to other important objects, e.g. the
* ANativeActivity obejct instance the application is running in.
*
* 3/ the "android_app" object holds an ALooper instance that already
* listens to two important things:
*
* - activity lifecycle events (e.g. "pause", "resume"). See APP_CMD_XXX
* declarations below.
*
* - input events coming from the AInputQueue attached to the activity.
*
* Each of these correspond to an ALooper identifier returned by
* ALooper_pollOnce with values of LOOPER_ID_MAIN and LOOPER_ID_INPUT,
* respectively.
*
* Your application can use the same ALooper to listen to additional
* file-descriptors. They can either be callback based, or with return
* identifiers starting with LOOPER_ID_USER.
*
* 4/ Whenever you receive a LOOPER_ID_MAIN or LOOPER_ID_INPUT event,
* the returned data will point to an android_poll_source structure. You
* can call the process() function on it, and fill in android_app->onAppCmd
* and android_app->onInputEvent to be called for your own processing
* of the event.
*
* Alternatively, you can call the low-level functions to read and process
* the data directly... look at the process_cmd() and process_input()
* implementations in the glue to see how to do this.
*
* See the sample named "native-activity" that comes with the NDK with a
* full usage example. Also look at the JavaDoc of NativeActivity.
*/
struct android_app;
/**
* Data associated with an ALooper fd that will be returned as the "outData"
* when that source has data ready.
*/
struct android_poll_source {
// The identifier of this source. May be LOOPER_ID_MAIN or
// LOOPER_ID_INPUT.
int32_t id;
// The android_app this ident is associated with.
struct android_app* app;
// Function to call to perform the standard processing of data from
// this source.
void (*process)(struct android_app* app, struct android_poll_source* source);
};
/**
* This is the interface for the standard glue code of a threaded
* application. In this model, the application's code is running
* in its own thread separate from the main thread of the process.
* It is not required that this thread be associated with the Java
* VM, although it will need to be in order to make JNI calls any
* Java objects.
*/
struct android_app {
// The application can place a pointer to its own state object
// here if it likes.
void* userData;
// Fill this in with the function to process main app commands (APP_CMD_*)
void (*onAppCmd)(struct android_app* app, int32_t cmd);
// Fill this in with the function to process input events. At this point
// the event has already been pre-dispatched, and it will be finished upon
// return. Return 1 if you have handled the event, 0 for any default
// dispatching.
int32_t (*onInputEvent)(struct android_app* app, AInputEvent* event);
// The ANativeActivity object instance that this app is running in.
ANativeActivity* activity;
// The current configuration the app is running in.
AConfiguration* config;
// This is the last instance's saved state, as provided at creation time.
// It is NULL if there was no state. You can use this as you need; the
// memory will remain around until you call android_app_exec_cmd() for
// APP_CMD_RESUME, at which point it will be freed and savedState set to NULL.
// These variables should only be changed when processing a APP_CMD_SAVE_STATE,
// at which point they will be initialized to NULL and you can malloc your
// state and place the information here. In that case the memory will be
// freed for you later.
void* savedState;
size_t savedStateSize;
// The ALooper associated with the app's thread.
ALooper* looper;
// When non-NULL, this is the input queue from which the app will
// receive user input events.
AInputQueue* inputQueue;
// When non-NULL, this is the window surface that the app can draw in.
ANativeWindow* window;
// Current content rectangle of the window; this is the area where the
// window's content should be placed to be seen by the user.
ARect contentRect;
// Current state of the app's activity. May be either APP_CMD_START,
// APP_CMD_RESUME, APP_CMD_PAUSE, or APP_CMD_STOP; see below.
int activityState;
// This is non-zero when the application's NativeActivity is being
// destroyed and waiting for the app thread to complete.
int destroyRequested;
// -------------------------------------------------
// Below are "private" implementation of the glue code.
pthread_mutex_t mutex;
pthread_cond_t cond;
int msgread;
int msgwrite;
pthread_t thread;
struct android_poll_source cmdPollSource;
struct android_poll_source inputPollSource;
int running;
int stateSaved;
int destroyed;
int redrawNeeded;
AInputQueue* pendingInputQueue;
ANativeWindow* pendingWindow;
ARect pendingContentRect;
};
enum {
/**
* Looper data ID of commands coming from the app's main thread, which
* is returned as an identifier from ALooper_pollOnce(). The data for this
* identifier is a pointer to an android_poll_source structure.
* These can be retrieved and processed with android_app_read_cmd()
* and android_app_exec_cmd().
*/
LOOPER_ID_MAIN = 1,
/**
* Looper data ID of events coming from the AInputQueue of the
* application's window, which is returned as an identifier from
* ALooper_pollOnce(). The data for this identifier is a pointer to an
* android_poll_source structure. These can be read via the inputQueue
* object of android_app.
*/
LOOPER_ID_INPUT = 2,
/**
* Start of user-defined ALooper identifiers.
*/
LOOPER_ID_USER = 3,
};
enum {
/**
* Command from main thread: the AInputQueue has changed. Upon processing
* this command, android_app->inputQueue will be updated to the new queue
* (or NULL).
*/
APP_CMD_INPUT_CHANGED,
/**
* Command from main thread: a new ANativeWindow is ready for use. Upon
* receiving this command, android_app->window will contain the new window
* surface.
*/
APP_CMD_INIT_WINDOW,
/**
* Command from main thread: the existing ANativeWindow needs to be
* terminated. Upon receiving this command, android_app->window still
* contains the existing window; after calling android_app_exec_cmd
* it will be set to NULL.
*/
APP_CMD_TERM_WINDOW,
/**
* Command from main thread: the current ANativeWindow has been resized.
* Please redraw with its new size.
*/
APP_CMD_WINDOW_RESIZED,
/**
* Command from main thread: the system needs that the current ANativeWindow
* be redrawn. You should redraw the window before handing this to
* android_app_exec_cmd() in order to avoid transient drawing glitches.
*/
APP_CMD_WINDOW_REDRAW_NEEDED,
/**
* Command from main thread: the content area of the window has changed,
* such as from the soft input window being shown or hidden. You can
* find the new content rect in android_app::contentRect.
*/
APP_CMD_CONTENT_RECT_CHANGED,
/**
* Command from main thread: the app's activity window has gained
* input focus.
*/
APP_CMD_GAINED_FOCUS,
/**
* Command from main thread: the app's activity window has lost
* input focus.
*/
APP_CMD_LOST_FOCUS,
/**
* Command from main thread: the current device configuration has changed.
*/
APP_CMD_CONFIG_CHANGED,
/**
* Command from main thread: the system is running low on memory.
* Try to reduce your memory use.
*/
APP_CMD_LOW_MEMORY,
/**
* Command from main thread: the app's activity has been started.
*/
APP_CMD_START,
/**
* Command from main thread: the app's activity has been resumed.
*/
APP_CMD_RESUME,
/**
* Command from main thread: the app should generate a new saved state
* for itself, to restore from later if needed. If you have saved state,
* allocate it with malloc and place it in android_app.savedState with
* the size in android_app.savedStateSize. The will be freed for you
* later.
*/
APP_CMD_SAVE_STATE,
/**
* Command from main thread: the app's activity has been paused.
*/
APP_CMD_PAUSE,
/**
* Command from main thread: the app's activity has been stopped.
*/
APP_CMD_STOP,
/**
* Command from main thread: the app's activity is being destroyed,
* and waiting for the app thread to clean up and exit before proceeding.
*/
APP_CMD_DESTROY,
};
/**
* Call when ALooper_pollAll() returns LOOPER_ID_MAIN, reading the next
* app command message.
*/
int8_t android_app_read_cmd(struct android_app* android_app);
/**
* Call with the command returned by android_app_read_cmd() to do the
* initial pre-processing of the given command. You can perform your own
* actions for the command after calling this function.
*/
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Call with the command returned by android_app_read_cmd() to do the
* final post-processing of the given command. You must have done your own
* actions for the command before calling this function.
*/
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Dummy function that used to be used to prevent the linker from stripping app
* glue code. No longer necessary, since __attribute__((visibility("default")))
* does this for us.
*/
__attribute__((
deprecated("Calls to app_dummy are no longer necessary. See "
"https://github.com/android-ndk/ndk/issues/381."))) void
app_dummy();
/**
* This is the function that application code must implement, representing
* the main entry to the app.
*/
extern void _rust_glue_entry(struct android_app* app);
#ifdef __cplusplus
}
#endif
#endif /* _ANDROID_NATIVE_APP_GLUE_H */
-176
View File
@@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-19
View File
@@ -1,19 +0,0 @@
MIT License
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.
-43
View File
@@ -1,43 +0,0 @@
#!/bin/sh
SYSROOT="${ANDROID_NDK_ROOT}"/toolchains/llvm/prebuilt/linux-x86_64/sysroot/
if ! test -d $SYSROOT; then
SYSROOT="${ANDROID_NDK_ROOT}"/toolchains/llvm/prebuilt/windows-x86_64/sysroot/
fi
while read ARCH && read TARGET ; do
# --module-raw-line 'use '
bindgen wrapper.h -o src/ffi_$ARCH.rs \
--blocklist-item 'JNI\w+' \
--blocklist-item 'C?_?JNIEnv' \
--blocklist-item '_?JavaVM' \
--blocklist-item '_?j\w+' \
--blocklist-item 'ALooper\w*' \
--blocklist-function 'ALooper\w*' \
--blocklist-item 'AAsset\w*' \
--blocklist-item 'AAssetManager\w*' \
--blocklist-function 'AAssetManager\w*' \
--blocklist-item 'ANativeWindow\w*' \
--blocklist-function 'ANativeWindow\w*' \
--blocklist-item 'AConfiguration\w*' \
--blocklist-function 'AConfiguration\w*' \
--blocklist-function 'android_main' \
--blocklist-item 'AInputQueue\w*' \
--blocklist-function 'AInputQueue\w*' \
--blocklist-item 'GameActivity_onCreate' \
--blocklist-function 'GameActivity_onCreate_C' \
--newtype-enum '\w+_(result|status)_t' \
-- \
-Icsrc \
--sysroot="$SYSROOT" --target=$TARGET
done << EOF
arm
arm-linux-androideabi
aarch64
aarch64-linux-android
i686
i686-linux-android
x86_64
x86_64-linux-android
EOF
-34
View File
@@ -1,34 +0,0 @@
//! The bindings are pre-generated and the right one for the platform is selected at compile time.
// Bindgen lints
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(improper_ctypes)]
#![allow(clippy::all)]
// Temporarily allow UB nullptr dereference in bindgen layout tests until fixed upstream:
// https://github.com/rust-lang/rust-bindgen/pull/2055
// https://github.com/rust-lang/rust-bindgen/pull/2064
#![allow(deref_nullptr)]
#![allow(dead_code)]
use jni_sys::*;
use ndk_sys::AAssetManager;
use ndk_sys::ANativeWindow;
use ndk_sys::{ALooper, AConfiguration, AInputQueue};
#[cfg(all(
any(target_os = "android", feature = "test"),
any(target_arch = "arm", target_arch = "armv7")
))]
include!("ffi_arm.rs");
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "aarch64"))]
include!("ffi_aarch64.rs");
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "x86"))]
include!("ffi_i686.rs");
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "x86_64"))]
include!("ffi_x86_64.rs");
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-712
View File
@@ -1,712 +0,0 @@
use log::{Level, error, info, trace};
use ndk::asset::AssetManager;
use ndk::configuration::Configuration;
use ndk::input_queue::InputQueue;
use ndk::looper::{FdEvent};
use ndk::native_window::NativeWindow;
use ndk_sys::ALooper_wake;
use ndk_sys::{ALooper, ALooper_pollAll};
use std::ffi::{CStr, CString};
use std::fs::File;
use std::hash::Hash;
use std::io::{BufRead, BufReader};
use std::ops::Deref;
use std::os::raw;
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;
use std::{thread, ptr};
use std::os::unix::prelude::*;
#[cfg(not(any(target_os = "android", feature = "test")))]
compile_error!("android-ndk-sys only supports compiling for Android");
mod ffi;
pub mod input {
pub use ndk::event::{
InputEvent, Source, MetaState,
MotionEvent, Pointer, MotionAction, Axis, ButtonState, EdgeFlags, MotionEventFlags,
KeyEvent, KeyAction, Keycode, KeyEventFlags
};
}
//pub mod input;
pub type InputEvent = ndk::event::InputEvent;
// Note: unlike in ndk-glue this has signed components (consistent
// with Android's ARect) which generally allows for representing
// rectangles with a negative/off-screen origin. Even though this
// is currently just used to represent the content rect (that probably
// wouldn't have any negative components) we keep the generality
// since this is a primitive type that could potentially be used
// for more things in the future.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Rect {
pub left: i32,
pub top: i32,
pub right: i32,
pub bottom: i32,
}
// XXX: NativeWindow is a ref-counted object but the NativeWindow rust API
// doesn't currently implement Clone() in terms of acquiring a reference
// and Drop() in terms of releasing a reference.
/// A reference to a `NativeWindow`, used for rendering
pub struct NativeWindowRef {
inner: NativeWindow
}
impl NativeWindowRef {
pub fn new(native_window: &NativeWindow) -> Self {
unsafe { ndk_sys::ANativeWindow_acquire(native_window.ptr().as_ptr()); }
Self { inner: native_window.clone() }
}
}
impl Drop for NativeWindowRef {
fn drop(&mut self) {
unsafe { ndk_sys::ANativeWindow_release(self.inner.ptr().as_ptr()) }
}
}
impl Deref for NativeWindowRef {
type Target = NativeWindow;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
// The only time it's safe to update the android_app->savedState pointer is
// while handling a SaveState event, so this API is only exposed for those
// events...
#[derive(Debug)]
pub struct StateSaver<'a> {
app: &'a AndroidApp,
}
impl<'a> StateSaver<'a> {
pub fn store(&self, state: &'a [u8]) {
// android_native_app_glue specifically expects savedState to have been allocated
// via libc::malloc since it will automatically handle freeing the data once it
// has been handed over to the Java Activity / main thread.
unsafe {
let app_ptr = self.app.ptr.as_ptr();
// In case the application calls store() multiple times for some reason we
// make sure to free any pre-existing state...
if (*app_ptr).savedState != ptr::null_mut() {
libc::free((*app_ptr).savedState);
(*app_ptr).savedState = ptr::null_mut();
(*app_ptr).savedStateSize = 0;
}
let buf = libc::malloc(state.len());
if buf == ptr::null_mut() {
panic!("Failed to allocate save_state buffer");
}
// Since it's a byte array there's no special alignment requirement here.
//
// Since we re-define `buf` we ensure it's not possible to access the buffer
// via its original pointer for the lifetime of the slice.
{
let buf: &mut [u8] = std::slice::from_raw_parts_mut(buf.cast(), state.len());
buf.copy_from_slice(state);
}
(*app_ptr).savedState = buf;
(*app_ptr).savedStateSize = state.len() as u64;
}
}
}
#[derive(Debug)]
pub struct StateLoader<'a> {
app: &'a AndroidApp,
}
impl<'a> StateLoader<'a> {
pub fn load(&self) -> Option<Vec<u8>> {
unsafe {
let app_ptr = self.app.ptr.as_ptr();
if (*app_ptr).savedState != ptr::null_mut() && (*app_ptr).savedStateSize > 0 {
let buf: &mut [u8] = std::slice::from_raw_parts_mut((*app_ptr).savedState.cast(), (*app_ptr).savedStateSize as usize);
let state = buf.to_vec();
Some(state)
} else {
None
}
}
}
}
// TODO: make more of these into non_exhaustive structs so it's possible to
// extend what data is passed to each event without breaking the API..
#[non_exhaustive]
#[derive(Debug)]
pub enum MainEvent<'a> {
// XXX: No need to expose for now, and isn't applicable with GameActivity
// Command from main thread: the input queue has changed.
// Note: since the internal `AInputQueue` is not exposed directly, applications
// won't typically need to react to this.
//InputQueueChanged,
/// Command from main thread: a new [`NativeWindow`] is ready for use. Upon
/// receiving this command, [`native_window()`] will return the new window
#[non_exhaustive]
InitWindow { },
/// Command from main thread: the existing [`NativeWindow`] needs to be
/// terminated. Upon receiving this command, [`native_window()`] still
/// returns the existing window; after returning from the [`AndroidApp::poll_events()`]
/// callback then [`native_window()`] will return `None`.
#[non_exhaustive]
TerminateWindow {},
// TODO: include the prev and new size in the event
/// Command from main thread: the current [`NativeWindow`] has been resized.
/// Please redraw with its new size.
#[non_exhaustive]
WindowResized {},
/// Command from main thread: the current [`NativeWindow`] needs to be redrawn.
/// You should redraw the window before the [`AndroidApp::poll_events()`]
/// callback returns in order to avoid transient drawing glitches.
#[non_exhaustive]
RedrawNeeded {},
/// Command from main thread: the content area of the window has changed,
/// such as from the soft input window being shown or hidden. You can
/// get the new content rect by calling [`AndroidApp::content_rect()`]
ContentRectChanged,
/// Command from main thread: the app's activity window has gained
/// input focus.
GainedFocus,
/// Command from main thread: the app's activity window has lost
/// input focus.
LostFocus,
/// Command from main thread: the current device configuration has changed.
/// You can get a copy of the latest [Configuration] by calling
/// [`AndroidApp::config()`]
ConfigChanged,
/// Command from main thread: the system is running low on memory.
/// Try to reduce your memory use.
LowMemory,
/// Command from main thread: the app's activity has been started.
Start,
/// Command from main thread: the app's activity has been resumed.
#[non_exhaustive]
Resume { loader: StateLoader<'a> },
/// Command from main thread: the app should generate a new saved state
/// for itself, to restore from later if needed. If you have saved state,
/// allocate it with malloc and place it in android_app.savedState with
/// the size in android_app.savedStateSize. The will be freed for you
/// later.
#[non_exhaustive]
SaveState { saver: StateSaver<'a> },
/// Command from main thread: the app's activity has been paused.
Pause,
/// Command from main thread: the app's activity has been stopped.
Stop,
/// Command from main thread: the app's activity is being destroyed,
/// and waiting for the app thread to clean up and exit before proceeding.
Destroy,
/// Command from main thread: the app's insets have changed.
#[non_exhaustive]
InsetsChanged {},
}
#[derive(Debug)]
#[non_exhaustive]
pub enum PollEvent<'a> {
Wake,
Timeout,
Main(MainEvent<'a>),
#[non_exhaustive]
FdEvent { ident: i32, fd: RawFd, events: FdEvent, data: *mut std::ffi::c_void },
Error
}
#[derive(Clone)]
pub struct AndroidAppWaker {
// The looper pointer is owned by the android_app and effectively
// has a 'static lifetime, and the ALooper_wake C API is thread
// safe, so this can be cloned safely and is send + sync safe
looper: NonNull<ALooper>
}
unsafe impl Send for AndroidAppWaker {}
unsafe impl Sync for AndroidAppWaker {}
impl AndroidAppWaker {
pub fn wake(&self) {
unsafe { ALooper_wake(self.looper.as_ptr()); }
}
}
#[derive(Debug, Clone)]
pub struct AndroidApp {
inner: Arc<AndroidAppInner>
}
impl PartialEq for AndroidApp {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
impl Eq for AndroidApp {}
impl Hash for AndroidApp {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.inner).hash(state);
}
}
impl Deref for AndroidApp {
type Target = Arc<AndroidAppInner>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
#[derive(Debug)]
pub struct AndroidAppInner {
ptr: NonNull<ffi::android_app>,
config: RwLock<Configuration>,
native_window: RwLock<Option<NativeWindow>>,
}
impl AndroidApp {
pub(crate) unsafe fn from_ptr(ptr: NonNull<ffi::android_app>) -> Self {
// Note: we don't use from_ptr since we don't own the android_app.config
// and need to keep in mind that the Drop handler is going to call
// AConfiguration_delete()
//
// Whenever we get a ConfigChanged notification we synchronize this
// config state with a deep copy.
let config = Configuration::clone_from_ptr(NonNull::new_unchecked((*ptr.as_ptr()).config));
Self {
inner: Arc::new(AndroidAppInner {
ptr,
config: RwLock::new(config),
native_window: Default::default()
})
}
}
pub(crate) fn native_activity(&self) -> *const ndk_sys::ANativeActivity {
unsafe {
let app_ptr = self.ptr.as_ptr();
(*app_ptr).activity.cast()
}
}
/// Queries the current [`NativeWindow`] for the application.
///
/// This will only return `Some(window)` between
/// [`AndroidAppMainEvent::InitWindow`] and [`AndroidAppMainEvent::TerminateWindow`]
/// events.
pub fn native_window<'a>(&self) -> Option<NativeWindowRef> {
let guard = self.native_window.read().unwrap();
if let Some(ref window) = *guard {
Some(NativeWindowRef::new(window))
} else {
None
}
}
/// Calls [`ALooper_pollAll`] on the looper associated with this AndroidApp as well
/// as processing any events (such as lifecycle events) via the given `callback`.
///
/// It's important to use this API for polling, and not call [`ALooper_pollAll`] directly since
/// some events require pre- and post-processing either side of the callback. For correct
/// behavior events should be handled immediately, before returning from the callback and
/// not simply queued for batch processing later. For example the existing [`NativeWindow`]
/// is accessible during a [`MainEvent::TerminateWindow`] callback and will be
/// set to `None` once the callback returns, and this is also synchronized with the Java
/// main thread. The [`MainEvent::SaveState`] event is also synchronized with the
/// Java main thread.
///
/// # Safety
/// This API must only be called from the applications main thread
pub fn poll_events<F>(&self, timeout: Option<Duration>, mut callback: F)
where F: FnMut(PollEvent)
{
trace!("poll_events");
unsafe {
let app_ptr = self.ptr;
let mut fd: i32 = 0;
let mut events: i32 = 0;
let mut source: *mut core::ffi::c_void = ptr::null_mut();
let timeout_milliseconds = if let Some(timeout) = timeout { timeout.as_millis() as i32 } else { -1 };
info!("Calling ALooper_pollAll, timeout = {timeout_milliseconds}");
let id = ALooper_pollAll(timeout_milliseconds, &mut fd, &mut events, &mut source as *mut *mut core::ffi::c_void);
info!("pollAll id = {id}");
match id {
ffi::ALOOPER_POLL_WAKE => {
trace!("ALooper_pollAll returned POLL_WAKE");
callback(PollEvent::Wake);
}
ffi::ALOOPER_POLL_CALLBACK => {
// ALooper_pollAll is documented to handle all callback sources internally so it should
// never return a _CALLBACK source id...
error!("Spurious ALOOPER_POLL_CALLBACK from ALopper_pollAll() (ignored)");
}
ffi::ALOOPER_POLL_TIMEOUT => {
trace!("ALooper_pollAll returned POLL_TIMEOUT");
callback(PollEvent::Timeout);
}
ffi::ALOOPER_POLL_ERROR => {
trace!("ALooper_pollAll returned POLL_ERROR");
callback(PollEvent::Error);
// Considering that this API is quite likely to be used in `android_main`
// it's rather unergonomic to require the call to unwrap a Result for each
// call to poll_events(). Alternatively we could maybe even just panic!()
// here, while it's hard to imagine practically being able to recover
//return Err(LooperError);
}
id if id >= 0 => {
match id as u32 {
ffi::LOOPER_ID_MAIN => {
trace!("ALooper_pollAll returned ID_MAIN");
let source: *mut ffi::android_poll_source = source.cast();
if source != ptr::null_mut() {
let cmd_i = ffi::android_app_read_cmd(app_ptr.as_ptr());
let cmd = match cmd_i as u32 {
// We don't forward info about the AInputQueue to apps since it's
// an implementation details that's also not compatible with
// GameActivity
ffi::APP_CMD_INPUT_CHANGED => None,
ffi::APP_CMD_INIT_WINDOW => Some(MainEvent::InitWindow {}),
ffi::APP_CMD_TERM_WINDOW => Some(MainEvent::TerminateWindow {}),
ffi::APP_CMD_WINDOW_RESIZED => Some(MainEvent::WindowResized {}),
ffi::APP_CMD_WINDOW_REDRAW_NEEDED => Some(MainEvent::RedrawNeeded {}),
ffi::APP_CMD_CONTENT_RECT_CHANGED => Some(MainEvent::ContentRectChanged),
ffi::APP_CMD_GAINED_FOCUS => Some(MainEvent::GainedFocus),
ffi::APP_CMD_LOST_FOCUS => Some(MainEvent::LostFocus),
ffi::APP_CMD_CONFIG_CHANGED => Some(MainEvent::ConfigChanged),
ffi::APP_CMD_LOW_MEMORY => Some(MainEvent::LowMemory),
ffi::APP_CMD_START => Some(MainEvent::Start),
ffi::APP_CMD_RESUME => Some(MainEvent::Resume { loader: StateLoader { app: &self } }),
ffi::APP_CMD_SAVE_STATE => Some(MainEvent::SaveState { saver: StateSaver { app: &self } }),
ffi::APP_CMD_PAUSE => Some(MainEvent::Pause),
ffi::APP_CMD_STOP => Some(MainEvent::Stop),
ffi::APP_CMD_DESTROY => Some(MainEvent::Destroy),
//ffi::NativeAppGlueAppCmd_APP_CMD_WINDOW_INSETS_CHANGED => MainEvent::InsetsChanged {},
_ => unreachable!()
};
trace!("Calling android_app_pre_exec_cmd({cmd_i})");
ffi::android_app_pre_exec_cmd(app_ptr.as_ptr(), cmd_i);
if let Some(cmd) = cmd {
trace!("Read ID_MAIN command {cmd_i} = {cmd:?}");
match cmd {
MainEvent::ConfigChanged => {
*self.config.write().unwrap() =
Configuration::clone_from_ptr(NonNull::new_unchecked((*app_ptr.as_ptr()).config));
}
MainEvent::InitWindow { .. } => {
let win_ptr = (*app_ptr.as_ptr()).window;
*self.native_window.write().unwrap() =
Some(NativeWindow::from_ptr(NonNull::new(win_ptr).unwrap()));
}
MainEvent::TerminateWindow { .. } => {
*self.native_window.write().unwrap() = None;
}
_ => {}
}
trace!("Invoking callback for ID_MAIN command = {:?}", cmd);
callback(PollEvent::Main(cmd));
}
trace!("Calling android_app_post_exec_cmd({cmd_i})");
ffi::android_app_post_exec_cmd(app_ptr.as_ptr(), cmd_i);
} else {
panic!("ALooper_pollAll returned ID_MAIN event with NULL android_poll_source!");
}
}
ffi::LOOPER_ID_INPUT => {
trace!("ALooper_pollAll returned ID_INPUT");
// For now we don't forward notifications of input events specifically, we just
// forward the notifications as a wake up, and assume the application main loop
// will unconditionally check events for each iteration of it's event loop
//
// (Specifically notifying when input events are received would be inconsistent
// with the current design of GameActivity input handling which we want to stay
// compatible with))
//
// XXX: Actually it was a bad idea to emit a Wake for input since applications
// are likely to _not_ consider that on its own a cause to redraw and it could
// end up spamming enough wake ups to interfere with other events that would
// trigger a redraw + input handling
//callback(PollEvent::Wake);
}
_ => {
let events = FdEvent::from_bits(events as u32)
.expect(&format!("Spurious ALooper_pollAll event flags {:#04x}", events as u32));
trace!("Custom ALooper event source: id = {id}, fd = {fd}, events = {events:?}, data = {source:?}");
callback(PollEvent::FdEvent{ ident: id, fd: fd as RawFd, events, data: source });
}
}
}
_ => {
error!("Spurious ALooper_pollAll return value {id} (ignored)");
}
}
}
}
/// Creates a means to wake up the main loop while it is blocked waiting for
/// events within [`poll_events()`].
///
/// Internally this uses [`ALooper_wake`] on the looper associated with this
/// [AndroidApp].
///
/// # Safety
/// This API can be used from any thread
pub fn create_waker(&self) -> AndroidAppWaker {
unsafe {
// From the application's pov we assume the app_ptr and looper pointer
// have static lifetimes and we can safely assume they are never NULL.
let app_ptr = self.ptr.as_ptr();
AndroidAppWaker { looper: NonNull::new_unchecked((*app_ptr).looper) }
}
}
/// Returns a deep copy of this application's [`Configuration`]
pub fn config(&self) -> Configuration {
self.config.read().unwrap().clone()
}
/// Queries the current content rectangle of the window; this is the area where the
/// window's content should be placed to be seen by the user.
///
/// # Safety
/// This API must only be called from the applications main thread
pub fn content_rect(&self) -> Rect {
unsafe {
let app_ptr = self.ptr.as_ptr();
Rect {
left: (*app_ptr).contentRect.left,
right: (*app_ptr).contentRect.right,
top: (*app_ptr).contentRect.top,
bottom: (*app_ptr).contentRect.bottom,
}
}
}
/// Queries the Asset Manager instance for the application.
///
/// Use this to access binary assets bundled inside your application's .apk file.
///
/// # Safety
/// This API must only be called from the applications main thread
pub fn asset_manager(&self) -> AssetManager {
unsafe {
let app_ptr = self.ptr.as_ptr();
let am_ptr = NonNull::new_unchecked((*(*app_ptr).activity).assetManager);
AssetManager::from_ptr(am_ptr)
}
}
pub fn input_events<'b, F>(&self, mut callback: F)
where F: FnMut(&InputEvent)
{
let queue = unsafe {
let app_ptr = self.ptr.as_ptr();
if (*app_ptr).inputQueue == ptr::null_mut() {
return;
}
let queue = NonNull::new_unchecked((*app_ptr).inputQueue);
InputQueue::from_ptr(queue)
};
info!("collect_events: START");
while let Some(event) = queue.get_event() {
info!("Got input event {event:?}");
if let Some(event) = queue.pre_dispatch(event) {
trace!("Pre dispatched input event {event:?}");
callback(&event);
// Always report events as 'handled'. This means we won't get
// so called 'fallback' events generated (such as converting trackball
// events into emulated keypad events), but we could conceivably
// implement similar emulation somewhere else in the stack if
// necessary, and this will be more consistent with the GameActivity
// input handling that doesn't do any kind of emulation.
info!("Finishing input event {event:?}");
queue.finish_event(event, true);
}
}
}
/// The user-visible SDK version of the framework
///
/// Also referred to as [`Build.VERSION_CODES`](https://developer.android.com/reference/android/os/Build.VERSION_CODES)
pub fn sdk_version() -> i32 {
let mut prop = android_properties::getprop("ro.build.version.sdk");
if let Some(val) = prop.value() {
i32::from_str_radix(&val, 10).expect("Failed to parse ro.build.version.sdk property")
} else {
panic!("Couldn't read ro.build.version.sdk system property");
}
}
fn try_get_path_from_ptr(path: *const u8) -> Option<std::path::PathBuf> {
if path == ptr::null() { return None; }
let cstr = unsafe {
let cstr_slice = CStr::from_ptr(path);
cstr_slice.to_str().ok()?
};
if cstr.len() == 0 { return None; }
Some(std::path::PathBuf::from(cstr))
}
/// Path to this application's internal data directory
pub fn internal_data_path(&self) -> Option<std::path::PathBuf> {
let na = self.native_activity();
unsafe { Self::try_get_path_from_ptr((*na).internalDataPath.cast()) }
}
/// Path to this application's external data directory
pub fn external_data_path(&self) -> Option<std::path::PathBuf> {
let na = self.native_activity();
unsafe { Self::try_get_path_from_ptr((*na).externalDataPath.cast()) }
}
/// Path to the directory containing the application's OBB files (if any).
pub fn obb_path(&self) -> Option<std::path::PathBuf> {
let na = self.native_activity();
unsafe { Self::try_get_path_from_ptr((*na).obbPath.cast()) }
}
}
// Rust doesn't give us a clean way to directly export symbols from C/C++
// so we rename the C/C++ symbols and re-export this entrypoint from
// Rust...
//
// https://github.com/rust-lang/rfcs/issues/2771
extern "C" {
pub fn ANativeActivity_onCreate_C(
activity: *mut std::os::raw::c_void,
savedState: *mut ::std::os::raw::c_void,
savedStateSize: usize,
);
}
#[no_mangle]
unsafe extern "C" fn ANativeActivity_onCreate(
activity: *mut std::os::raw::c_void,
saved_state: *mut std::os::raw::c_void,
saved_state_size: usize,
) {
ANativeActivity_onCreate_C(activity, saved_state, saved_state_size);
}
fn android_log(level: Level, tag: &CStr, msg: &CStr) {
let prio = match level {
Level::Error => ndk_sys::android_LogPriority_ANDROID_LOG_ERROR,
Level::Warn => ndk_sys::android_LogPriority_ANDROID_LOG_WARN,
Level::Info => ndk_sys::android_LogPriority_ANDROID_LOG_INFO,
Level::Debug => ndk_sys::android_LogPriority_ANDROID_LOG_DEBUG,
Level::Trace => ndk_sys::android_LogPriority_ANDROID_LOG_VERBOSE,
};
unsafe {
ndk_sys::__android_log_write(prio as raw::c_int, tag.as_ptr(), msg.as_ptr());
}
}
extern "Rust" {
pub fn android_main(app: AndroidApp);
}
// This is a spring board between android_native_app_glue and the user's
// `app_main` function. This is run on a dedicated thread spawned
// by android_native_app_glue.
#[no_mangle]
pub unsafe extern "C" fn _rust_glue_entry(app: *mut ffi::android_app) {
// Maybe make this stdout/stderr redirection an optional / opt-in feature?...
let mut logpipe: [RawFd; 2] = Default::default();
libc::pipe(logpipe.as_mut_ptr());
libc::dup2(logpipe[1], libc::STDOUT_FILENO);
libc::dup2(logpipe[1], libc::STDERR_FILENO);
thread::spawn(move || {
let tag = CStr::from_bytes_with_nul(b"RustStdoutStderr\0").unwrap();
let file = File::from_raw_fd(logpipe[0]);
let mut reader = BufReader::new(file);
let mut buffer = String::new();
loop {
buffer.clear();
if let Ok(len) = reader.read_line(&mut buffer) {
if len == 0 {
break;
} else if let Ok(msg) = CString::new(buffer.clone()) {
android_log(Level::Info, tag, &msg);
}
}
}
});
let app = AndroidApp::from_ptr(NonNull::new(app).unwrap());
let na = app.native_activity();
let jvm = (*na).vm;
let activity = (*na).clazz; // Completely bogus name; this is the _instance_ not class pointer
ndk_context::initialize_android_context(jvm.cast(), activity.cast());
// Since this is a newly spawned thread then the JVM hasn't been attached
// to the thread yet. Attach before calling the applications main function
// so they can safely make JNI calls
let mut jenv_out: *mut core::ffi::c_void = std::ptr::null_mut();
if let Some(attach_current_thread) = (*(*jvm)).AttachCurrentThread {
attach_current_thread(jvm, &mut jenv_out, std::ptr::null_mut());
}
// XXX: If we were in control of the Java Activity subclass then
// we could potentially run the android_main function via a Java native method
// springboard (e.g. call an Activity subclass method that calls a jni native
// method that then just calls android_main()) that would make sure there was
// a Java frame at the base of our call stack which would then be recognised
// when calling FindClass to lookup a suitable classLoader, instead of
// defaulting to the system loader. Without this then it's difficult for native
// code to look up non-standard Java classes.
android_main(app);
// Since this is a newly spawned thread then the JVM hasn't been attached
// to the thread yet. Attach before calling the applications main function
// so they can safely make JNI calls
if let Some(detach_current_thread) = (*(*jvm)).DetachCurrentThread {
detach_current_thread(jvm);
}
ndk_context::release_android_context();
}
-1
View File
@@ -1 +0,0 @@
#include <native-activity/native_app_glue/android_native_app_glue.h>