mirror of
https://github.com/rust-mobile/android-activity.git
synced 2026-07-05 14:27:27 +00:00
Compare commits
128 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 946dcdc919 | |||
| c18a4dd135 | |||
| 4827e0b17b | |||
| a8637e3f25 | |||
| aaf0e8b30a | |||
| 46d2fa87c3 | |||
| 249e7d1834 | |||
| e686e80112 | |||
| b9e883866e | |||
| 9e8c85c647 | |||
| a97cf1ceae | |||
| 1652ebb229 | |||
| b943f58863 | |||
| 019ad634a2 | |||
| 87cda3c560 | |||
| bde1cb3436 | |||
| 69f3642499 | |||
| c0f3fa6754 | |||
| 42af0cccfa | |||
| 5d7616e30e | |||
| 3755ed7e7a | |||
| 5367c865e3 | |||
| eacddd744a | |||
| 36832feacf | |||
| 88714f0b6a | |||
| 85eb7274f4 | |||
| 49f2b86424 | |||
| 976e9d06af | |||
| ac2e17e977 | |||
| db3ea3386f | |||
| 51d05d48c8 | |||
| fe171bc532 | |||
| 0d299300f4 | |||
| 0a87a84c57 | |||
| 7bd3ba6dde | |||
| 6a0197c28f | |||
| e5b8242ff2 | |||
| c9faa9c44e | |||
| 4b9b8d754b | |||
| 526d39c1f3 | |||
| 4ffa3ac2e1 | |||
| 967882f3d9 | |||
| 35e080baf0 | |||
| 5cb67a2b89 | |||
| 672360c5e6 | |||
| 9fce890219 | |||
| 2deec162b5 | |||
| eeeb80209f | |||
| 6c3583dc24 | |||
| bfd8bfd04c | |||
| af341897a2 | |||
| a84722ff23 | |||
| d9af67008a | |||
| c2f467c174 | |||
| e14d2c1deb | |||
| 100d5bc1d4 | |||
| 98aef99419 | |||
| a7114c807f | |||
| a7dc90d9bb | |||
| 6af4d61227 | |||
| 6e036c99e4 | |||
| 2a917ca5c4 | |||
| add58dbb2e | |||
| d16cb79350 | |||
| b590ec5484 | |||
| 74d9669854 | |||
| a92237fab4 | |||
| 969ba5adf9 | |||
| ce4413b2c6 | |||
| a291e378ee | |||
| 2ecaab9f15 | |||
| 3d5e479a4e | |||
| 219a14bda1 | |||
| 733fabffd3 | |||
| f2132c4dab | |||
| 9930b9bf90 | |||
| 0eefd623ed | |||
| 83cdb56e24 | |||
| 942053d88e | |||
| 865cc6a780 | |||
| 4f6d7d68de | |||
| 7ea440d6c1 | |||
| 75e9e8672d | |||
| 47a073f702 | |||
| 499d09595b | |||
| 23a8570d48 | |||
| c9f57a734f | |||
| e91176cb08 | |||
| 2a61f84c70 | |||
| 2654c9659b | |||
| 35fe600235 | |||
| 242285b205 | |||
| 379f064170 | |||
| e2f69421a0 | |||
| 1b3334178b | |||
| 535994f4a2 | |||
| 6b3307410e | |||
| b4cf0eeabf | |||
| af331e3bff | |||
| 6f72dde55d | |||
| d0f10a0dd9 | |||
| 3464ba20bc | |||
| 1abb02c820 | |||
| c0a9e20c5a | |||
| 66cfc68dac | |||
| ed2dc53ee4 | |||
| 74f510a99a | |||
| 741e633ea8 | |||
| 41f30c39ad | |||
| 96497f9da9 | |||
| c22a5453df | |||
| 9bb5f9c9cf | |||
| a604c0aa9f | |||
| b09526a4a9 | |||
| cc3983ca21 | |||
| 2a2f27637f | |||
| d2d18154d9 | |||
| 3e3fb84c03 | |||
| 202ab4c1e9 | |||
| d6345abb2a | |||
| c471fdf903 | |||
| 1a8a92b3fb | |||
| bb97af154f | |||
| 8a21219695 | |||
| c10a2fb67a | |||
| ab2606a73d | |||
| a84a7b54cd | |||
| a9e91f4308 |
+34
-28
@@ -2,7 +2,7 @@ name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: '*'
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
@@ -12,18 +12,32 @@ env:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# See top README for MSRV policy
|
||||
rust_version: [1.64.0, stable]
|
||||
rust-version: [1.85.0, stable]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: hecrj/setup-rust-action@v1
|
||||
# Downgrade all dependencies to their minimum version, both to ensure our
|
||||
# minimum version bounds are correct and buildable, as well as to satisfy
|
||||
# our MSRV check when arbitrary dependencies bump their MSRV beyond our
|
||||
# MSRV in a patch-release.
|
||||
# This implies that downstream consumers can only rely on our MSRV when
|
||||
# downgrading various (transitive) dependencies.
|
||||
- uses: hecrj/setup-rust-action@v2
|
||||
with:
|
||||
rust-version: ${{ matrix.rust_version }}
|
||||
rust-version: nightly
|
||||
if: ${{ matrix.rust-version != 'stable' }}
|
||||
- name: Downgrade dependencies
|
||||
run: cargo +nightly generate-lockfile -Zminimal-versions
|
||||
if: ${{ matrix.rust-version != 'stable' }}
|
||||
|
||||
- uses: hecrj/setup-rust-action@v2
|
||||
with:
|
||||
rust-version: ${{ matrix.rust-version }}
|
||||
|
||||
- name: Install Rust targets
|
||||
run: >
|
||||
@@ -34,18 +48,7 @@ jobs:
|
||||
i686-linux-android
|
||||
|
||||
- name: Install cargo-ndk
|
||||
# We're currently sticking with cargo-ndk 2, until we bump our
|
||||
# MSRV to 1.68+
|
||||
run: cargo install cargo-ndk --version "^2"
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: '17'
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: android-actions/setup-android@v2
|
||||
run: cargo +stable install cargo-ndk
|
||||
|
||||
- name: Build game-activity
|
||||
working-directory: android-activity
|
||||
@@ -68,7 +71,7 @@ jobs:
|
||||
build --features native-activity
|
||||
|
||||
- name: Build agdk-mainloop example
|
||||
if: matrix.rust_version == 'stable'
|
||||
if: matrix.rust-version == 'stable'
|
||||
working-directory: examples/agdk-mainloop
|
||||
run: >
|
||||
cargo ndk
|
||||
@@ -79,7 +82,7 @@ jobs:
|
||||
-o app/src/main/jniLibs/ -- build
|
||||
|
||||
- name: Build na-mainloop example
|
||||
if: matrix.rust_version == 'stable'
|
||||
if: matrix.rust-version == 'stable'
|
||||
working-directory: examples/na-mainloop
|
||||
run: >
|
||||
cargo ndk
|
||||
@@ -93,17 +96,20 @@ jobs:
|
||||
run: >
|
||||
cargo ndk -t arm64-v8a doc --no-deps
|
||||
|
||||
- name: Build doctests
|
||||
# All doctests are set to no_run, because they require running in the
|
||||
# context of an Android app.
|
||||
# Only run on stable because cross-compiling doctests is only supported
|
||||
# since Rust 1.89.
|
||||
if: ${{ matrix.rust-version == 'stable' }}
|
||||
run: |
|
||||
cargo test --doc -F native-activity --target aarch64-linux-android
|
||||
cargo ndk -t arm64-v8a -- test --doc -F game-activity
|
||||
|
||||
format:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
override: true
|
||||
components: rustfmt
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Format
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
+2
-1
@@ -1 +1,2 @@
|
||||
target
|
||||
/target
|
||||
/Cargo.lock
|
||||
|
||||
+6
-6
@@ -1,8 +1,8 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"android-activity"
|
||||
]
|
||||
resolver = "2"
|
||||
members = ["android-activity"]
|
||||
|
||||
exclude = [
|
||||
"examples",
|
||||
]
|
||||
exclude = ["examples"]
|
||||
|
||||
[patch.crates-io]
|
||||
jni = { git = "https://github.com/jni-rs/jni-rs.git", branch = "release-0.22" }
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
[](https://github.com/rust-mobile/android-activity/actions/workflows/ci.yml)
|
||||
[](https://crates.io/crates/android-activity)
|
||||
[](https://docs.rs/android-activity)
|
||||
[](https://blog.rust-lang.org/2022/09/22/Rust-1.64.0.html)
|
||||
[](https://blog.rust-lang.org/2023/03/09/Rust-1.68.0.html)
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -36,8 +36,8 @@ Cargo.toml
|
||||
```toml
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
android_logger = "0.11"
|
||||
android-activity = { version = "0.4", features = [ "native-activity" ] }
|
||||
android_logger = "0.13"
|
||||
android-activity = { version = "0.5", features = [ "native-activity" ] }
|
||||
|
||||
[lib]
|
||||
crate_type = ["cdylib"]
|
||||
@@ -126,8 +126,8 @@ Middleware libraries can instead look at using the [ndk-context](https://crates.
|
||||
The steps to switch a simple standalone application over from `ndk-glue` to `android-activity` (still based on `NativeActivity`) should be:
|
||||
|
||||
1. Remove `ndk-glue` from your Cargo.toml
|
||||
2. Add a dependency on `android-activity`, like `android-activity = { version="0.4", features = [ "native-activity" ] }`
|
||||
3. Optionally add a dependency on `android_logger = "0.11.0"`
|
||||
2. Add a dependency on `android-activity`, like `android-activity = { version="0.5", features = [ "native-activity" ] }`
|
||||
3. Optionally add a dependency on `android_logger = "0.13.0"`
|
||||
4. Update the `main` entry point to look like this:
|
||||
|
||||
```rust
|
||||
@@ -157,8 +157,8 @@ Prior to working on android-activity, the existing glue crates available for bui
|
||||
## MSRV
|
||||
|
||||
We aim to (at least) support stable releases of Rust from the last three months. Rust has a 6 week release cycle which means we will support the last three stable releases.
|
||||
For example, when Rust 1.69 is released we would limit our `rust_version` to 1.67.
|
||||
For example, when Rust 1.69 is released we would limit our `rust-version` to 1.67.
|
||||
|
||||
We will only bump the `rust_version` at the point where we either depend on a new features or a dependency has increased its MSRV, and we won't be greedy. In other words we will only set the MSRV to the lowest version that's _needed_.
|
||||
We will only bump the `rust-version` at the point where we either depend on a new features or a dependency has increased its MSRV, and we won't be greedy. In other words we will only set the MSRV to the lowest version that's _needed_.
|
||||
|
||||
MSRV updates are not considered to be inherently semver breaking (unless a new feature is exposed in the public API) and so a `rust_version` change may happen in patch releases.
|
||||
MSRV updates are not considered to be inherently semver breaking (unless a new feature is exposed in the public API) and so a `rust-version` change may happen in patch releases.
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
|
||||
|
||||
# Added by cargo
|
||||
#
|
||||
# already existing elements were commented out
|
||||
|
||||
#/target
|
||||
#Cargo.lock
|
||||
@@ -1,41 +1,215 @@
|
||||
<!-- markdownlint-disable MD022 MD024 MD032 MD033 -->
|
||||
|
||||
# Changelog
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
## [0.4.2] - 2022-02-16
|
||||
- The `ndk` and `ndk-sys` crates are now re-exported under `android_activity::ndk` and `android_activity::ndk_sys` ([#194](https://github.com/rust-mobile/android-activity/pull/194))
|
||||
- input: TextInputAction enum representing action button types on soft keyboards.
|
||||
- input: InputEvent::TextAction event for handling action button presses from soft keyboards.
|
||||
|
||||
### Changed
|
||||
|
||||
- rust-version bumped to 1.85.0 ([#193](https://github.com/rust-mobile/android-activity/pull/193), TODO: link)
|
||||
- GameActivity updated to 4.0.0 (requires the corresponding 4.0.0 `.aar` release from Google) ([#191](https://github.com/rust-mobile/android-activity/pull/191))
|
||||
|
||||
## [0.6.0] - 2024-04-26
|
||||
|
||||
### Changed
|
||||
- rust-version bumped to 1.69.0 ([#156](https://github.com/rust-mobile/android-activity/pull/156))
|
||||
- Upgrade to `ndk-sys 0.6.0` and `ndk 0.9.0` ([#155](https://github.com/rust-mobile/android-activity/pull/155))
|
||||
|
||||
### Fixed
|
||||
- Check for null `saved_state_in` pointer from `NativeActivity`
|
||||
|
||||
## [0.5.2] - 2024-01-30
|
||||
|
||||
### Fixed
|
||||
- NativeActivity: OR with `EVENT_ACTION_MASK` when extracting action from `MotionEvent` - fixing multi-touch input ([#146](https://github.com/rust-mobile/android-activity/issues/146), [#147](https://github.com/rust-mobile/android-activity/pull/147))
|
||||
|
||||
## [0.5.1] - 2023-12-20
|
||||
|
||||
### Changed
|
||||
- Avoids depending on default features for `ndk` crate to avoid pulling in any `raw-window-handle` dependencies ([#142](https://github.com/rust-mobile/android-activity/pull/142))
|
||||
|
||||
**Note:** Technically, this could be observed as a breaking change in case you
|
||||
were depending on the `rwh_06` feature that was enabled by default in the
|
||||
`ndk` crate. This could be observed via the `NativeWindow` type (exposed via
|
||||
`AndroidApp::native_window()`) no longer implementing `rwh_06::HasWindowHandle`.
|
||||
|
||||
In the unlikely case that you were depending on the `ndk`'s `rwh_06` API
|
||||
being enabled by default via `android-activity`'s `ndk` dependency, your crate
|
||||
should explicitly enable the `rwh_06` feature for the `ndk` crate.
|
||||
|
||||
As far as could be seen though, it's not expected that anything was
|
||||
depending on this (e.g. anything based on Winit enables the `ndk` feature
|
||||
based on an equivalent `winit` feature).
|
||||
|
||||
The benefit of the change is that it can help avoid a redundant
|
||||
`raw-window-handle 0.6` dependency in projects that still need to use older
|
||||
(non-default) `raw-window-handle` versions. (Though note that this may be
|
||||
awkward to achieve in practice since other crates that depend on the `ndk`
|
||||
are still likely to use default features and also pull in
|
||||
`raw-window-handles 0.6`)
|
||||
|
||||
- The IO thread now gets named `stdio-to-logcat` and main thread is named `android_main` ([#145](https://github.com/rust-mobile/android-activity/pull/145))
|
||||
- Improved IO error handling in `stdio-to-logcat` IO loop. ([#133](https://github.com/rust-mobile/android-activity/pull/133))
|
||||
|
||||
## [0.5.0] - 2023-10-16
|
||||
### Added
|
||||
- Added `MotionEvent::action_button()` exposing the button associated with button press/release actions ([#138](https://github.com/rust-mobile/android-activity/pull/138))
|
||||
|
||||
### Changed
|
||||
- rust-version bumped to 0.68 ([#123](https://github.com/rust-mobile/android-activity/pull/123))
|
||||
- *Breaking*: updates to `ndk 0.8` and `ndk-sys 0.5` ([#128](https://github.com/rust-mobile/android-activity/pull/128))
|
||||
- The `Pointer` and `PointerIter` types from the `ndk` crate are no longer directly exposed in the public API ([#122](https://github.com/rust-mobile/android-activity/pull/122))
|
||||
- All input API enums based on Android SDK enums have been made runtime extensible via hidden `__Unknown(u32)` variants ([#131](https://github.com/rust-mobile/android-activity/pull/131))
|
||||
|
||||
## [0.5.0-beta.1] - 2023-08-15
|
||||
### Changed
|
||||
- Pulled in `ndk-sys 0.5.0-beta.0` and `ndk 0.8.0-beta.0` ([#113](https://github.com/rust-mobile/android-activity/pull/113))
|
||||
|
||||
## [0.5.0-beta.0] - 2023-08-15
|
||||
|
||||
### Added
|
||||
- Added `KeyEvent::meta_state()` for being able to query the state of meta keys, needed for character mapping ([#102](https://github.com/rust-mobile/android-activity/pull/102))
|
||||
- Added `KeyCharacterMap` JNI bindings to the corresponding Android SDK API ([#102](https://github.com/rust-mobile/android-activity/pull/102))
|
||||
- Added `AndroidApp::device_key_character_map()` for being able to get a `KeyCharacterMap` for a given `device_id` for unicode character mapping ([#102](https://github.com/rust-mobile/android-activity/pull/102))
|
||||
|
||||
<details>
|
||||
<summary>Click here for an example of how to handle unicode character mapping:</summary>
|
||||
|
||||
```rust
|
||||
let mut combining_accent = None;
|
||||
// Snip
|
||||
|
||||
|
||||
let combined_key_char = if let Ok(map) = app.device_key_character_map(device_id) {
|
||||
match map.get(key_event.key_code(), key_event.meta_state()) {
|
||||
Ok(KeyMapChar::Unicode(unicode)) => {
|
||||
let combined_unicode = if let Some(accent) = combining_accent {
|
||||
match map.get_dead_char(accent, unicode) {
|
||||
Ok(Some(key)) => {
|
||||
info!("KeyEvent: Combined '{unicode}' with accent '{accent}' to give '{key}'");
|
||||
Some(key)
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(err) => {
|
||||
log::error!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("KeyEvent: Pressed '{unicode}'");
|
||||
Some(unicode)
|
||||
};
|
||||
combining_accent = None;
|
||||
combined_unicode.map(|unicode| KeyMapChar::Unicode(unicode))
|
||||
}
|
||||
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||
info!("KeyEvent: Pressed 'dead key' combining accent '{accent}'");
|
||||
combining_accent = Some(accent);
|
||||
Some(KeyMapChar::CombiningAccent(accent))
|
||||
}
|
||||
Ok(KeyMapChar::None) => {
|
||||
info!("KeyEvent: Pressed non-unicode key");
|
||||
combining_accent = None;
|
||||
None
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("KeyEvent: Failed to get key map character: {err:?}");
|
||||
combining_accent = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
```
|
||||
|
||||
</details>
|
||||
- Added `TextEvent` Input Method event for supporting text editing via virtual keyboards ([#24](https://github.com/rust-mobile/android-activity/pull/24))
|
||||
|
||||
### Changed
|
||||
- GameActivity updated to 2.0.2 (requires the corresponding 2.0.2 `.aar` release from Google) ([#88](https://github.com/rust-mobile/android-activity/pull/88))
|
||||
- `AndroidApp::input_events()` is replaced by `AndroidApp::input_events_iter()` ([#102](https://github.com/rust-mobile/android-activity/pull/102))
|
||||
|
||||
<details>
|
||||
<summary>Click here for an example of how to use `input_events_iter()`:</summary>
|
||||
|
||||
```rust
|
||||
match app.input_events_iter() {
|
||||
Ok(mut iter) => {
|
||||
loop {
|
||||
let read_input = iter.next(|event| {
|
||||
let handled = match event {
|
||||
InputEvent::KeyEvent(key_event) => {
|
||||
// Snip
|
||||
}
|
||||
InputEvent::MotionEvent(motion_event) => {
|
||||
// Snip
|
||||
}
|
||||
event => {
|
||||
// Snip
|
||||
}
|
||||
};
|
||||
|
||||
handled
|
||||
});
|
||||
|
||||
if !read_input {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Failed to get input events iterator: {err:?}");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## [0.4.3] - 2023-07-30
|
||||
### Fixed
|
||||
- Fixed a deadlock in the `native-activity` backend while waiting for the native thread after getting an `onDestroy` callback from Java ([#94](https://github.com/rust-mobile/android-activity/pull/94))
|
||||
- Fixed numerous deadlocks in the `game-activity` backend with how it would wait for the native thread in various Java callbacks, after the app has returned from `android_main` ([#98](https://github.com/rust-mobile/android-activity/pull/98))
|
||||
|
||||
## [0.4.2] - 2023-06-17
|
||||
### Changed
|
||||
- The `Activity.finish()` method is now called when `android_main` returns so the `Activity` will be destroyed ([#67](https://github.com/rust-mobile/android-activity/issues/67))
|
||||
- The `native-activity` backend now propagates `NativeWindow` redraw/resize and `ContentRectChanged` callbacks to main loop ([#70](https://github.com/rust-mobile/android-activity/pull/70))
|
||||
- The `game-activity` implementation of `pointer_index()` was fixed to not always return `0` ([#80](https://github.com/rust-mobile/android-activity/pull/84))
|
||||
- Added `panic` guards around application's `android_main()` and native code that could potentially unwind across a Java FFI boundary ([#68](https://github.com/rust-mobile/android-activity/pull/68))
|
||||
|
||||
## [0.4.1] - 2022-02-16
|
||||
## [0.4.1] - 2023-02-16
|
||||
### Added
|
||||
- Added `AndroidApp::vm_as_ptr()` to expose JNI `JavaVM` pointer ([#60](https://github.com/rust-mobile/android-activity/issues/60))
|
||||
- Added `AndroidApp::activity_as_ptr()` to expose Android `Activity` JNI reference as pointer ([#60](https://github.com/rust-mobile/android-activity/issues/60))
|
||||
### Changed
|
||||
- Removed some overly-verbose logging in the `native-activity` backend ([#49](https://github.com/rust-mobile/android-activity/pull/49))
|
||||
### Removed
|
||||
- Most of the examples were moved to https://github.com/rust-mobile/rust-android-examples ([#50](https://github.com/rust-mobile/android-activity/pull/50))
|
||||
- Most of the examples were moved to <https://github.com/rust-mobile/rust-android-examples> ([#50](https://github.com/rust-mobile/android-activity/pull/50))
|
||||
|
||||
## [0.4] - 2022-11-10
|
||||
## [0.4.0] - 2022-11-10
|
||||
### Changed
|
||||
- *Breaking*: `input_events` callback now return whether an event was handled or not to allow for fallback handling ([#31](https://github.com/rust-mobile/android-activity/issues/31))
|
||||
- The native-activity backend is now implemented in Rust only, without building on `android_native_app_glue.c` ([#35](https://github.com/rust-mobile/android-activity/pull/35))
|
||||
### Added
|
||||
- Added `Pointer::tool_type()` API to `GameActivity` backend for compatibility with `ndk` events API ([#38](https://github.com/rust-mobile/android-activity/pull/38))
|
||||
|
||||
## [0.3] - 2022-09-15
|
||||
## [0.3.0] - 2022-09-15
|
||||
### Added
|
||||
- `show/hide_sot_input` API for being able to show/hide a soft keyboard (other IME still pending)
|
||||
- `set_window_flags()` API for setting WindowManager params
|
||||
### Changed
|
||||
- *Breaking*: Created extensible, `#[non_exhaustive]` `InputEvent` wrapper enum instead of exposing `ndk` type directly
|
||||
|
||||
## [0.2] - 2022-08-25
|
||||
## [0.2.0] - 2022-08-25
|
||||
### Added
|
||||
- Emit an `InputAvailable` event for new input with `NativeActivity` and `GameActivity`
|
||||
enabling gui apps that don't render continuously
|
||||
@@ -52,6 +226,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
### Changed
|
||||
- Documentation fixes
|
||||
|
||||
## [0.1] - 2022-07-04
|
||||
## [0.1.0] - 2022-07-04
|
||||
### Added
|
||||
- Initial release
|
||||
- Initial release
|
||||
|
||||
[unreleased]: https://github.com/rust-mobile/android-activity/compare/v0.6.0...HEAD
|
||||
[0.6.0]: https://github.com/rust-mobile/android-activity/compare/v0.5.2...v0.6.0
|
||||
[0.5.2]: https://github.com/rust-mobile/android-activity/compare/v0.5.1...v0.5.2
|
||||
[0.5.1]: https://github.com/rust-mobile/android-activity/compare/v0.5.0...v0.5.1
|
||||
[0.5.0]: https://github.com/rust-mobile/android-activity/compare/v0.4.3...v0.5.0
|
||||
[0.4.3]: https://github.com/rust-mobile/android-activity/compare/v0.4.2...v0.4.3
|
||||
[0.4.2]: https://github.com/rust-mobile/android-activity/compare/v0.4.1...v0.4.2
|
||||
[0.4.1]: https://github.com/rust-mobile/android-activity/compare/v0.4.0...v0.4.1
|
||||
[0.4.0]: https://github.com/rust-mobile/android-activity/compare/v0.3.0...v0.4.0
|
||||
[0.3.0]: https://github.com/rust-mobile/android-activity/compare/v0.2.0...v0.3.0
|
||||
[0.2.0]: https://github.com/rust-mobile/android-activity/compare/v0.1.1...v0.2.0
|
||||
[0.1.1]: https://github.com/rust-mobile/android-activity/compare/v0.1.0...v0.1.1
|
||||
[0.1.0]: https://github.com/rust-mobile/android-activity/releases/tag/v0.1.0
|
||||
|
||||
+21
-10
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "android-activity"
|
||||
version = "0.4.2"
|
||||
version = "0.6.0"
|
||||
edition = "2021"
|
||||
keywords = ["android", "ndk"]
|
||||
readme = "../README.md"
|
||||
@@ -9,7 +9,14 @@ repository = "https://github.com/rust-mobile/android-activity"
|
||||
documentation = "https://docs.rs/android-activity"
|
||||
description = "Glue for building Rust applications on Android with NativeActivity or GameActivity"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.64"
|
||||
include = [
|
||||
"/build.rs",
|
||||
"/android-games-sdk",
|
||||
"/LICENSE*",
|
||||
"/src",
|
||||
]
|
||||
|
||||
rust-version = "1.85.0"
|
||||
|
||||
[features]
|
||||
# Note: we don't enable any backend by default since features
|
||||
@@ -21,20 +28,24 @@ rust-version = "1.64"
|
||||
default = []
|
||||
game-activity = []
|
||||
native-activity = []
|
||||
api-level-30 = ["ndk/api-level-30"]
|
||||
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
jni-sys = "0.3"
|
||||
ndk = "0.7"
|
||||
ndk-sys = "0.4"
|
||||
ndk-context = "0.1"
|
||||
cesu8 = "1"
|
||||
jni = "0.22"
|
||||
jni-sys = "0.4.1"
|
||||
ndk-sys = "0.6.0"
|
||||
ndk = { version = "0.9.0", default-features = false }
|
||||
ndk-context = "0.1.1"
|
||||
android-properties = "0.2"
|
||||
num_enum = "0.6"
|
||||
bitflags = "1.3"
|
||||
libc = "0.2"
|
||||
num_enum = "0.7"
|
||||
bitflags = "2.0"
|
||||
libc = "0.2.139"
|
||||
thiserror = "1"
|
||||
|
||||
[build-dependencies]
|
||||
cc = { version = "1.0", features = ["parallel"] }
|
||||
cc = { version = "1.0.42", features = ["parallel"] }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = [
|
||||
|
||||
@@ -1,12 +1,24 @@
|
||||
The third-party glue code, under the native-activity-csrc/ and game-activity-csrc/ directories
|
||||
is covered by the Apache 2.0 license only:
|
||||
# License
|
||||
|
||||
Apache License, Version 2.0 (docs/LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
|
||||
## GameActivity
|
||||
|
||||
The third-party glue code, under the game-activity-csrc/ directory is covered by
|
||||
the Apache 2.0 license only:
|
||||
|
||||
Apache License, Version 2.0 (LICENSE-APACHE or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
|
||||
## SDK Documentation
|
||||
|
||||
Documentation for APIs that are direct bindings of Android platform APIs are covered
|
||||
by the Apache 2.0 license only:
|
||||
|
||||
Apache License, Version 2.0 (LICENSE-APACHE or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
|
||||
## android-activity
|
||||
|
||||
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)
|
||||
- MIT License (LICENSE-MIT or <http://opensource.org/licenses/MIT>)
|
||||
- Apache License, Version 2.0 (LICENSE-APACHE or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
|
||||
at your option.
|
||||
at your option.
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# android-games-sdk
|
||||
|
||||
This is an imported copy of the native "prefab" source for `GameActivity` and
|
||||
`GameTextInput`, from our fork of Google's
|
||||
[android-games-sdk](https://github.com/rust-mobile/android-games-sdk).
|
||||
|
||||
We use an external fork to track our integration patches on top of the Android
|
||||
Game Development Kit (AGDK) in a way that it is easier to update to new upstream
|
||||
versions. It also makes it easier to try and upstream changes when we fix bugs.
|
||||
|
||||
## Updating to new agdk version checklist
|
||||
|
||||
This is a basic checklist for things that need to be done when updating to a new
|
||||
agdk version:
|
||||
|
||||
- [ ] Create a new integration branch based on our last integrated branch and
|
||||
rebase that on the latest *release* branch from Google:
|
||||
|
||||
```bash
|
||||
git clone git@github.com:rust-mobile/android-games-sdk.git
|
||||
cd android-games-sdk
|
||||
git remote add google https://android.googlesource.com/platform/frameworks/opt/gamesdk
|
||||
git fetch google
|
||||
git checkout -b android-activity-5.0.0 origin/android-activity-4.0.0
|
||||
git rebase --onto google/android-games-sdk-game-activity-release <base>
|
||||
# (where <base> is the upstream commit ID below our stack of integration patches)
|
||||
```
|
||||
|
||||
- [ ] Set the `ANDROID_GAMES_SDK` environment variable so you can build
|
||||
android-activity against your external games-sdk branch while updating.
|
||||
- [ ] Re-generate the `GameActivity` FFI bindings with `./generate-bindings.sh`
|
||||
(this can be done with `ANDROID_GAMES_SDK` set in your environment and also
|
||||
repeated after importing)
|
||||
- [ ] Update [build.rs](../build.rs) with any new includes and src files
|
||||
- [ ] Update the `src/game-activity` backend as needed
|
||||
- [ ] Push a new `android-games-sdk` branch like `android-activity-5.0.0` that
|
||||
can be referenced when importing a copy into `android-activity`
|
||||
- [ ] Review and run `./import-games-sdk.sh` when ready to copy external AGDK
|
||||
code into this repo
|
||||
- [ ] Clearly reference the branch name and commit hash from the
|
||||
`android-games-sdk` repo in the `android-activity` commit that imports new
|
||||
games-sdk source.
|
||||
- [ ] Update CHANGELOG.md as required
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../../../../include/common/
|
||||
+711
@@ -0,0 +1,711 @@
|
||||
/*
|
||||
* 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 <common/gamesdk_common.h>
|
||||
#include <game-activity/GameActivityEvents.h>
|
||||
#include <game-text-input/gametextinput.h>
|
||||
#include <jni.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define GAMEACTIVITY_MAJOR_VERSION 4
|
||||
#define GAMEACTIVITY_MINOR_VERSION 0
|
||||
#define GAMEACTIVITY_BUGFIX_VERSION 0
|
||||
#define GAMEACTIVITY_PACKED_VERSION \
|
||||
ANDROID_GAMESDK_PACKED_VERSION(GAMEACTIVITY_MAJOR_VERSION, \
|
||||
GAMEACTIVITY_MINOR_VERSION, \
|
||||
GAMEACTIVITY_BUGFIX_VERSION)
|
||||
|
||||
/**
|
||||
* The type of a component for which to retrieve insets. See
|
||||
* https://developer.android.com/reference/androidx/core/view/WindowInsetsCompat.Type
|
||||
*/
|
||||
typedef enum GameCommonInsetsType : uint8_t {
|
||||
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;
|
||||
|
||||
/**
|
||||
* {@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;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* Callback called when the rectangle in the window where the content
|
||||
* should be placed has changed.
|
||||
*/
|
||||
void (*onContentRectChanged)(GameActivity* activity, const ARect* rect);
|
||||
|
||||
/**
|
||||
* Callback called when the software keyboard is shown or hidden.
|
||||
*/
|
||||
void (*onSoftwareKeyboardVisibilityChanged)(GameActivity* activity,
|
||||
bool visible);
|
||||
|
||||
/**
|
||||
* Callback called when the software keyboard is shown or hidden.
|
||||
*/
|
||||
bool (*onEditorAction)(GameActivity* activity, int action);
|
||||
} GameActivityCallbacks;
|
||||
|
||||
/**
|
||||
* 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_C;
|
||||
|
||||
/**
|
||||
* 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 : uint32_t {
|
||||
/**
|
||||
* 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 : uint8_t {
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* Restarts the input method. Calls InputMethodManager.restartInput().
|
||||
* 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_restartInput(GameActivity* activity);
|
||||
|
||||
/**
|
||||
* 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 : uint16_t {
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* Tells whether the software keyboard is visible or not.
|
||||
*/
|
||||
bool GameActivity_isSoftwareKeyboardVisible(GameActivity* activity);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* <b>Note:</b> currently only TYPE_NULL AND TYPE_CLASS_NUMBER are supported.
|
||||
*/
|
||||
void GameActivity_setImeEditorInfo(GameActivity* activity,
|
||||
enum GameTextInputType inputType,
|
||||
enum GameTextInputActionType actionId,
|
||||
enum GameTextInputImeOptions imeOptions);
|
||||
|
||||
/**
|
||||
* These are getters for Configuration class members. They may be called from
|
||||
* any thread.
|
||||
*/
|
||||
int GameActivity_getOrientation(GameActivity* activity);
|
||||
int GameActivity_getColorMode(GameActivity* activity);
|
||||
int GameActivity_getDensityDpi(GameActivity* activity);
|
||||
float GameActivity_getFontScale(GameActivity* activity);
|
||||
int GameActivity_getFontWeightAdjustment(GameActivity* activity);
|
||||
int GameActivity_getHardKeyboardHidden(GameActivity* activity);
|
||||
int GameActivity_getKeyboard(GameActivity* activity);
|
||||
int GameActivity_getKeyboardHidden(GameActivity* activity);
|
||||
int GameActivity_getLocalesCount(GameActivity* activity);
|
||||
int GameActivity_getMcc(GameActivity* activity);
|
||||
int GameActivity_getMnc(GameActivity* activity);
|
||||
int GameActivity_getNavigation(GameActivity* activity);
|
||||
int GameActivity_getNavigationHidden(GameActivity* activity);
|
||||
int GameActivity_getOrientation(GameActivity* activity);
|
||||
int GameActivity_getScreenHeightDp(GameActivity* activity);
|
||||
int GameActivity_getScreenLayout(GameActivity* activity);
|
||||
int GameActivity_getScreenWidthDp(GameActivity* activity);
|
||||
int GameActivity_getSmallestScreenWidthDp(GameActivity* activity);
|
||||
int GameActivity_getTouchscreen(GameActivity* activity);
|
||||
int GameActivity_getUIMode(GameActivity* activity);
|
||||
|
||||
/**
|
||||
* The functions below return Java locale information.
|
||||
*
|
||||
* In simple cases there will be just one locale, but it's possible tha
|
||||
* there are more than one locale objects. Users are encouraged to write code
|
||||
* that handles all locales and not just the first one.
|
||||
*
|
||||
* The functions in the block below return string values in the provided buffer.
|
||||
* Return value is zero if there were no errors, otherwise it's non-zero.
|
||||
* If the return value is zero, `dst` will contain a null-terminated string:
|
||||
* strlen(dst) <= dst_size - 1.
|
||||
* If the return value is non-zero, the content of dst is undefined.
|
||||
*
|
||||
* Parameters:
|
||||
*
|
||||
* dst, dst_size: define a receiver buffer. Locale string can be something
|
||||
* short like "EN/EN", but it may be longer. You should be safe with a buffer
|
||||
* size of 256 bytes.
|
||||
*
|
||||
* If the buffer is too small, ENOBUFS is returned. Try allocating a larger
|
||||
* buffer in this case.
|
||||
*
|
||||
* localeIdx must be between 0 and the value of GameActivity_getLocalesCount().
|
||||
* If localeIdx is out of range, EINVAL is returned.
|
||||
*
|
||||
* Refer to Java documentation of locales for more information.
|
||||
*/
|
||||
int GameActivity_getLocaleLanguage(char* dst, size_t dst_size,
|
||||
GameActivity* activity, size_t localeIdx);
|
||||
int GameActivity_getLocaleScript(char* dst, size_t dst_size,
|
||||
GameActivity* activity, size_t localeIdx);
|
||||
int GameActivity_getLocaleCountry(char* dst, size_t dst_size,
|
||||
GameActivity* activity, size_t localeIdx);
|
||||
int GameActivity_getLocaleVariant(char* dst, size_t dst_size,
|
||||
GameActivity* activity, size_t localeIdx);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif // ANDROID_GAME_SDK_GAME_ACTIVITY_H
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
/*
|
||||
* Copyright (C) 2022 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 Events
|
||||
* The interface to use Game Activity Events.
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file GameActivityEvents.h
|
||||
*/
|
||||
#ifndef ANDROID_GAME_SDK_GAME_ACTIVITY_EVENTS_H
|
||||
#define ANDROID_GAME_SDK_GAME_ACTIVITY_EVENTS_H
|
||||
|
||||
#include <android/input.h>
|
||||
#include <jni.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* 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;
|
||||
int32_t toolType;
|
||||
float axisValues[GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT];
|
||||
float rawX;
|
||||
float rawY;
|
||||
} GameActivityPointerAxes;
|
||||
|
||||
/** \brief Get the toolType of the pointer. */
|
||||
inline int32_t GameActivityPointerAxes_getToolType(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return pointerInfo->toolType;
|
||||
}
|
||||
|
||||
/** \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 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.
|
||||
*/
|
||||
float GameActivityPointerAxes_getAxisValue(
|
||||
const GameActivityPointerAxes* pointerInfo, int32_t axis);
|
||||
|
||||
inline float GameActivityPointerAxes_getPressure(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return GameActivityPointerAxes_getAxisValue(pointerInfo,
|
||||
AMOTION_EVENT_AXIS_PRESSURE);
|
||||
}
|
||||
|
||||
inline float GameActivityPointerAxes_getSize(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return GameActivityPointerAxes_getAxisValue(pointerInfo,
|
||||
AMOTION_EVENT_AXIS_SIZE);
|
||||
}
|
||||
|
||||
inline float GameActivityPointerAxes_getTouchMajor(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return GameActivityPointerAxes_getAxisValue(pointerInfo,
|
||||
AMOTION_EVENT_AXIS_TOUCH_MAJOR);
|
||||
}
|
||||
|
||||
inline float GameActivityPointerAxes_getTouchMinor(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return GameActivityPointerAxes_getAxisValue(pointerInfo,
|
||||
AMOTION_EVENT_AXIS_TOUCH_MINOR);
|
||||
}
|
||||
|
||||
inline float GameActivityPointerAxes_getToolMajor(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return GameActivityPointerAxes_getAxisValue(pointerInfo,
|
||||
AMOTION_EVENT_AXIS_TOOL_MAJOR);
|
||||
}
|
||||
|
||||
inline float GameActivityPointerAxes_getToolMinor(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return GameActivityPointerAxes_getAxisValue(pointerInfo,
|
||||
AMOTION_EVENT_AXIS_TOOL_MINOR);
|
||||
}
|
||||
|
||||
inline float GameActivityPointerAxes_getOrientation(
|
||||
const GameActivityPointerAxes* pointerInfo) {
|
||||
return GameActivityPointerAxes_getAxisValue(pointerInfo,
|
||||
AMOTION_EVENT_AXIS_ORIENTATION);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
/**
|
||||
* \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];
|
||||
|
||||
int historySize;
|
||||
int64_t* historicalEventTimesMillis;
|
||||
int64_t* historicalEventTimesNanos;
|
||||
float* historicalAxisValues;
|
||||
|
||||
float precisionX;
|
||||
float precisionY;
|
||||
} GameActivityMotionEvent;
|
||||
|
||||
float GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
const GameActivityMotionEvent* event, int axis, int pointerIndex,
|
||||
int historyPos);
|
||||
|
||||
inline int GameActivityMotionEvent_getHistorySize(
|
||||
const GameActivityMotionEvent* event) {
|
||||
return event->historySize;
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalX(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_X, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalY(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_Y, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalPressure(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_PRESSURE, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalSize(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_SIZE, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalTouchMajor(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalTouchMinor(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalToolMajor(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalToolMinor(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
inline float GameActivityMotionEvent_getHistoricalOrientation(
|
||||
const GameActivityMotionEvent* event, int pointerIndex, int historyPos) {
|
||||
return GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
event, AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex, historyPos);
|
||||
}
|
||||
|
||||
/** \brief Handle the freeing of the GameActivityMotionEvent struct. */
|
||||
void GameActivityMotionEvent_destroy(GameActivityMotionEvent* c_event);
|
||||
|
||||
/**
|
||||
* \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).
|
||||
* The only exception is the event times, which are reported as
|
||||
* nanoseconds in this struct.
|
||||
*/
|
||||
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;
|
||||
// int32_t unicodeChar;
|
||||
} GameActivityKeyEvent;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif // ANDROID_GAME_SDK_GAME_ACTIVITY_EVENTS_H
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
* Copyright (C) 2022 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_GAME_SDK_GAME_ACTIVITY_LOG_H_
|
||||
#define ANDROID_GAME_SDK_GAME_ACTIVITY_LOG_H_
|
||||
|
||||
#define LOG_TAG "GameActivity"
|
||||
#include <android/log.h>
|
||||
|
||||
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__);
|
||||
#define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__);
|
||||
#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__);
|
||||
#ifdef NDEBUG
|
||||
#define ALOGV(...)
|
||||
#else
|
||||
#define ALOGV(...) \
|
||||
__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__);
|
||||
#endif
|
||||
|
||||
/* Returns 2nd arg. Used to substitute default value if caller's vararg list
|
||||
* is empty.
|
||||
*/
|
||||
#define __android_second(first, second, ...) second
|
||||
|
||||
/* If passed multiple args, returns ',' followed by all but 1st arg, otherwise
|
||||
* returns nothing.
|
||||
*/
|
||||
#define __android_rest(first, ...) , ##__VA_ARGS__
|
||||
|
||||
#define android_printAssert(cond, tag, fmt...) \
|
||||
__android_log_assert(cond, tag, \
|
||||
__android_second(0, ##fmt, NULL) __android_rest(fmt))
|
||||
|
||||
#define CONDITION(cond) (__builtin_expect((cond) != 0, 0))
|
||||
|
||||
#ifndef LOG_ALWAYS_FATAL_IF
|
||||
#define LOG_ALWAYS_FATAL_IF(cond, ...) \
|
||||
((CONDITION(cond)) \
|
||||
? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
|
||||
: (void)0)
|
||||
#endif
|
||||
|
||||
#ifndef LOG_ALWAYS_FATAL
|
||||
#define LOG_ALWAYS_FATAL(...) \
|
||||
(((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Simplified macro to send a warning system log message using current LOG_TAG.
|
||||
*/
|
||||
#ifndef SLOGW
|
||||
#define SLOGW(...) \
|
||||
((void)__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
|
||||
#endif
|
||||
|
||||
#ifndef SLOGW_IF
|
||||
#define SLOGW_IF(cond, ...) \
|
||||
((__predict_false(cond)) \
|
||||
? ((void)__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) \
|
||||
: (void)0)
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Versions of LOG_ALWAYS_FATAL_IF and LOG_ALWAYS_FATAL that
|
||||
* are stripped out of release builds.
|
||||
*/
|
||||
#if LOG_NDEBUG
|
||||
|
||||
#ifndef LOG_FATAL_IF
|
||||
#define LOG_FATAL_IF(cond, ...) ((void)0)
|
||||
#endif
|
||||
#ifndef LOG_FATAL
|
||||
#define LOG_FATAL(...) ((void)0)
|
||||
#endif
|
||||
|
||||
#else
|
||||
|
||||
#ifndef LOG_FATAL_IF
|
||||
#define LOG_FATAL_IF(cond, ...) LOG_ALWAYS_FATAL_IF(cond, ##__VA_ARGS__)
|
||||
#endif
|
||||
#ifndef LOG_FATAL
|
||||
#define LOG_FATAL(...) LOG_ALWAYS_FATAL(__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Assertion that generates a log message when the assertion fails.
|
||||
* Stripped out of release builds. Uses the current LOG_TAG.
|
||||
*/
|
||||
#ifndef ALOG_ASSERT
|
||||
#define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ##__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
#define LOG_TRACE(...)
|
||||
|
||||
#endif // ANDROID_GAME_SDK_GAME_ACTIVITY_LOG_H_
|
||||
+561
@@ -0,0 +1,561 @@
|
||||
/*
|
||||
* 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 <stdint.h>
|
||||
|
||||
#include "game-activity/GameActivity.h"
|
||||
|
||||
#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 GameActivityMotionEvent.
|
||||
* Only the first motionEventsCount events are valid.
|
||||
*/
|
||||
GameActivityMotionEvent* motionEvents;
|
||||
|
||||
/**
|
||||
* The number of valid motion events in `motionEvents`.
|
||||
*/
|
||||
uint64_t motionEventsCount;
|
||||
|
||||
/**
|
||||
* The size of the `motionEvents` buffer.
|
||||
*/
|
||||
uint64_t motionEventsBufferSize;
|
||||
|
||||
/**
|
||||
* Pointer to a read-only array of GameActivityKeyEvent.
|
||||
* Only the first keyEventsCount events are valid.
|
||||
*/
|
||||
GameActivityKeyEvent* keyEvents;
|
||||
|
||||
/**
|
||||
* The number of valid "Key" events in `keyEvents`.
|
||||
*/
|
||||
uint64_t keyEventsCount;
|
||||
|
||||
/**
|
||||
* The size of the `keyEvents` buffer.
|
||||
*/
|
||||
uint64_t keyEventsBufferSize;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* Whether the software keyboard is visible or not.
|
||||
*/
|
||||
bool softwareKeyboardVisible;
|
||||
|
||||
/**
|
||||
* Last editor action. Valid within APP_CMD_SOFTWARE_KB_VIS_CHANGED handler.
|
||||
*
|
||||
* Note: the upstream comment above isn't accurate.
|
||||
* - `APP_CMD_SOFTWARE_KB_VIS_CHANGED` is associated with `softwareKeyboardVisible`
|
||||
* changes, not `editorAction`.
|
||||
* - `APP_CMD_EDITOR_ACTION` is associated with this state but unlike for
|
||||
* `window` state there's no synchonization that blocks the Java main
|
||||
* thread, so we can't say that this is only valid within the `APP_CMD_` handler.
|
||||
*/
|
||||
int editorAction;
|
||||
/**
|
||||
* true when editorAction has been set
|
||||
*/
|
||||
bool pendingEditorAction;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
// When new input is received we set both of these flags and use the looper to
|
||||
// wake up the application mainloop.
|
||||
//
|
||||
// To avoid spamming the mainloop with wake ups from lots of input though we
|
||||
// don't sent a wake up if the inputSwapPending flag is already set. (i.e.
|
||||
// we already expect input to be processed in a finite amount of time due to
|
||||
// our previous wake up)
|
||||
//
|
||||
// When a wake up is received then we will check this flag (clearing it
|
||||
// at the same time). If it was set then an InputAvailable event is sent to
|
||||
// the application - which should lead to all input being processed within
|
||||
// a finite amount of time.
|
||||
//
|
||||
// The next time android_app_swap_input_buffers is called, both flags will be
|
||||
// cleared.
|
||||
//
|
||||
// NB: both of these should only be read with the app mutex held
|
||||
bool inputAvailableWakeUp;
|
||||
bool inputSwapPending;
|
||||
|
||||
/** @endcond */
|
||||
};
|
||||
|
||||
/**
|
||||
* Looper ID of commands coming from the app's main thread, an AInputQueue or
|
||||
* user-defined sources.
|
||||
*/
|
||||
enum NativeAppGlueLooperId : int8_t {
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* Values from 0 to 127 are reserved for this library; values from -128 to -1
|
||||
* can be used for custom user's events.
|
||||
*/
|
||||
enum NativeAppGlueAppCmd : int8_t {
|
||||
/**
|
||||
* 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 software keyboard was shown or hidden.
|
||||
*/
|
||||
APP_CMD_SOFTWARE_KB_VIS_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,
|
||||
|
||||
/**
|
||||
* Command from main thread: an editor action has been triggered.
|
||||
*/
|
||||
//APP_CMD_EDITOR_ACTION,
|
||||
|
||||
/**
|
||||
* Command from main thread: a keyboard event has been received.
|
||||
*/
|
||||
//APP_CMD_KEY_EVENT,
|
||||
|
||||
/**
|
||||
* Command from main thread: a touch event has been received.
|
||||
*/
|
||||
//APP_CMD_TOUCH_EVENT,
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
/**
|
||||
* You can send your custom events using the function below.
|
||||
*
|
||||
* Make sure your custom codes do not overlap with this library's ones.
|
||||
*
|
||||
* Values from 0 to 127 are reserved for this library; values from -128 to -1
|
||||
* can be used for custom user's events.
|
||||
*/
|
||||
void android_app_write_cmd(struct android_app* android_app, int8_t cmd);
|
||||
|
||||
/**
|
||||
* Determines if a looper wake up was due to new input becoming available
|
||||
*/
|
||||
bool android_app_input_available_wake_up(struct android_app* app);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../../../../game-text-input/prefab-src/modules/game-text-input/include/game-text-input/gametextinput.h
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"export_libraries": [],
|
||||
"library_name": null,
|
||||
"android": {
|
||||
"export_libraries": ["-landroid", "-llog"],
|
||||
"library_name": null
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../../../../src/common/system_utils.cpp
|
||||
+1399
File diff suppressed because it is too large
Load Diff
+335
@@ -0,0 +1,335 @@
|
||||
/*
|
||||
* Copyright (C) 2022 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-activity/GameActivityEvents.h>
|
||||
#include <game-activity/GameActivityLog.h>
|
||||
#include <sys/system_properties.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "GameActivityEvents_internal.h"
|
||||
#include "system_utils.h"
|
||||
|
||||
static bool enabledAxes[GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT] = {
|
||||
/* AMOTION_EVENT_AXIS_X */ true,
|
||||
/* AMOTION_EVENT_AXIS_Y */ true,
|
||||
// Disable all other axes by default (they can be enabled using
|
||||
// `GameActivityPointerAxes_enableAxis`).
|
||||
false};
|
||||
|
||||
extern "C" void GameActivityPointerAxes_enableAxis(int32_t axis) {
|
||||
if (axis < 0 || axis >= GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT) {
|
||||
return;
|
||||
}
|
||||
|
||||
enabledAxes[axis] = true;
|
||||
}
|
||||
|
||||
float GameActivityPointerAxes_getAxisValue(
|
||||
const GameActivityPointerAxes *pointerInfo, int32_t axis) {
|
||||
if (axis < 0 || axis >= GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!enabledAxes[axis]) {
|
||||
ALOGW("Axis %d must be enabled before it can be accessed.", axis);
|
||||
return 0;
|
||||
}
|
||||
|
||||
return pointerInfo->axisValues[axis];
|
||||
}
|
||||
|
||||
extern "C" void GameActivityPointerAxes_disableAxis(int32_t axis) {
|
||||
if (axis < 0 || axis >= GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT) {
|
||||
return;
|
||||
}
|
||||
|
||||
enabledAxes[axis] = false;
|
||||
}
|
||||
|
||||
float GameActivityMotionEvent_getHistoricalAxisValue(
|
||||
const GameActivityMotionEvent *event, int axis, int pointerIndex,
|
||||
int historyPos) {
|
||||
if (axis < 0 || axis >= GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT) {
|
||||
ALOGE("Invalid axis %d", axis);
|
||||
return -1;
|
||||
}
|
||||
if (pointerIndex < 0 || pointerIndex >= event->pointerCount) {
|
||||
ALOGE("Invalid pointer index %d", pointerIndex);
|
||||
return -1;
|
||||
}
|
||||
if (historyPos < 0 || historyPos >= event->historySize) {
|
||||
ALOGE("Invalid history index %d", historyPos);
|
||||
return -1;
|
||||
}
|
||||
if (!enabledAxes[axis]) {
|
||||
ALOGW("Axis %d must be enabled before it can be accessed.", axis);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int pointerOffset = pointerIndex * GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT;
|
||||
int historyValuesOffset =
|
||||
historyPos * event->pointerCount * GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT;
|
||||
return event
|
||||
->historicalAxisValues[historyValuesOffset + pointerOffset + axis];
|
||||
}
|
||||
|
||||
static struct {
|
||||
jmethodID getDeviceId;
|
||||
jmethodID getSource;
|
||||
jmethodID getAction;
|
||||
|
||||
jmethodID getEventTime;
|
||||
jmethodID getDownTime;
|
||||
|
||||
jmethodID getFlags;
|
||||
jmethodID getMetaState;
|
||||
|
||||
jmethodID getActionButton;
|
||||
jmethodID getButtonState;
|
||||
jmethodID getClassification;
|
||||
jmethodID getEdgeFlags;
|
||||
|
||||
jmethodID getHistorySize;
|
||||
jmethodID getHistoricalEventTime;
|
||||
|
||||
jmethodID getPointerCount;
|
||||
jmethodID getPointerId;
|
||||
|
||||
jmethodID getToolType;
|
||||
|
||||
jmethodID getRawX;
|
||||
jmethodID getRawY;
|
||||
jmethodID getXPrecision;
|
||||
jmethodID getYPrecision;
|
||||
jmethodID getAxisValue;
|
||||
|
||||
jmethodID getHistoricalAxisValue;
|
||||
} gMotionEventClassInfo;
|
||||
|
||||
extern "C" void GameActivityMotionEvent_destroy(
|
||||
GameActivityMotionEvent *c_event) {
|
||||
delete c_event->historicalAxisValues;
|
||||
delete c_event->historicalEventTimesMillis;
|
||||
delete c_event->historicalEventTimesNanos;
|
||||
}
|
||||
|
||||
static void initMotionEvents(JNIEnv *env) {
|
||||
int sdkVersion = gamesdk::GetSystemPropAsInt("ro.build.version.sdk");
|
||||
gMotionEventClassInfo = {0};
|
||||
jclass motionEventClass = env->FindClass("android/view/MotionEvent");
|
||||
gMotionEventClassInfo.getDeviceId =
|
||||
env->GetMethodID(motionEventClass, "getDeviceId", "()I");
|
||||
gMotionEventClassInfo.getSource =
|
||||
env->GetMethodID(motionEventClass, "getSource", "()I");
|
||||
gMotionEventClassInfo.getAction =
|
||||
env->GetMethodID(motionEventClass, "getAction", "()I");
|
||||
gMotionEventClassInfo.getEventTime =
|
||||
env->GetMethodID(motionEventClass, "getEventTime", "()J");
|
||||
gMotionEventClassInfo.getDownTime =
|
||||
env->GetMethodID(motionEventClass, "getDownTime", "()J");
|
||||
gMotionEventClassInfo.getFlags =
|
||||
env->GetMethodID(motionEventClass, "getFlags", "()I");
|
||||
gMotionEventClassInfo.getMetaState =
|
||||
env->GetMethodID(motionEventClass, "getMetaState", "()I");
|
||||
if (sdkVersion >= 23) {
|
||||
gMotionEventClassInfo.getActionButton =
|
||||
env->GetMethodID(motionEventClass, "getActionButton", "()I");
|
||||
}
|
||||
if (sdkVersion >= 14) {
|
||||
gMotionEventClassInfo.getButtonState =
|
||||
env->GetMethodID(motionEventClass, "getButtonState", "()I");
|
||||
}
|
||||
if (sdkVersion >= 29) {
|
||||
gMotionEventClassInfo.getClassification =
|
||||
env->GetMethodID(motionEventClass, "getClassification", "()I");
|
||||
}
|
||||
gMotionEventClassInfo.getEdgeFlags =
|
||||
env->GetMethodID(motionEventClass, "getEdgeFlags", "()I");
|
||||
|
||||
gMotionEventClassInfo.getHistorySize =
|
||||
env->GetMethodID(motionEventClass, "getHistorySize", "()I");
|
||||
gMotionEventClassInfo.getHistoricalEventTime =
|
||||
env->GetMethodID(motionEventClass, "getHistoricalEventTime", "(I)J");
|
||||
|
||||
gMotionEventClassInfo.getPointerCount =
|
||||
env->GetMethodID(motionEventClass, "getPointerCount", "()I");
|
||||
gMotionEventClassInfo.getPointerId =
|
||||
env->GetMethodID(motionEventClass, "getPointerId", "(I)I");
|
||||
gMotionEventClassInfo.getToolType =
|
||||
env->GetMethodID(motionEventClass, "getToolType", "(I)I");
|
||||
if (sdkVersion >= 29) {
|
||||
gMotionEventClassInfo.getRawX =
|
||||
env->GetMethodID(motionEventClass, "getRawX", "(I)F");
|
||||
gMotionEventClassInfo.getRawY =
|
||||
env->GetMethodID(motionEventClass, "getRawY", "(I)F");
|
||||
}
|
||||
gMotionEventClassInfo.getXPrecision =
|
||||
env->GetMethodID(motionEventClass, "getXPrecision", "()F");
|
||||
gMotionEventClassInfo.getYPrecision =
|
||||
env->GetMethodID(motionEventClass, "getYPrecision", "()F");
|
||||
gMotionEventClassInfo.getAxisValue =
|
||||
env->GetMethodID(motionEventClass, "getAxisValue", "(II)F");
|
||||
|
||||
gMotionEventClassInfo.getHistoricalAxisValue =
|
||||
env->GetMethodID(motionEventClass, "getHistoricalAxisValue", "(III)F");
|
||||
}
|
||||
|
||||
extern "C" void GameActivityMotionEvent_fromJava(
|
||||
JNIEnv *env, jobject motionEvent, GameActivityMotionEvent *out_event,
|
||||
int pointerCount, int historySize) {
|
||||
pointerCount =
|
||||
std::min(pointerCount, GAMEACTIVITY_MAX_NUM_POINTERS_IN_MOTION_EVENT);
|
||||
out_event->pointerCount = pointerCount;
|
||||
for (int i = 0; i < pointerCount; ++i) {
|
||||
out_event->pointers[i] = {
|
||||
/*id=*/env->CallIntMethod(motionEvent,
|
||||
gMotionEventClassInfo.getPointerId, i),
|
||||
/*toolType=*/
|
||||
env->CallIntMethod(motionEvent, gMotionEventClassInfo.getToolType, i),
|
||||
/*axisValues=*/{0},
|
||||
/*rawX=*/gMotionEventClassInfo.getRawX
|
||||
? env->CallFloatMethod(motionEvent, gMotionEventClassInfo.getRawX,
|
||||
i)
|
||||
: 0,
|
||||
/*rawY=*/gMotionEventClassInfo.getRawY
|
||||
? env->CallFloatMethod(motionEvent, gMotionEventClassInfo.getRawY,
|
||||
i)
|
||||
: 0,
|
||||
};
|
||||
|
||||
for (int axisIndex = 0; axisIndex < GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT;
|
||||
++axisIndex) {
|
||||
if (enabledAxes[axisIndex]) {
|
||||
out_event->pointers[i].axisValues[axisIndex] = env->CallFloatMethod(
|
||||
motionEvent, gMotionEventClassInfo.getAxisValue, axisIndex, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out_event->historySize = historySize;
|
||||
out_event->historicalAxisValues =
|
||||
new float[historySize * pointerCount *
|
||||
GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT];
|
||||
out_event->historicalEventTimesMillis = new int64_t[historySize];
|
||||
out_event->historicalEventTimesNanos = new int64_t[historySize];
|
||||
|
||||
for (int historyIndex = 0; historyIndex < historySize; historyIndex++) {
|
||||
out_event->historicalEventTimesMillis[historyIndex] = env->CallLongMethod(
|
||||
motionEvent, gMotionEventClassInfo.getHistoricalEventTime,
|
||||
historyIndex);
|
||||
out_event->historicalEventTimesNanos[historyIndex] =
|
||||
out_event->historicalEventTimesMillis[historyIndex] * 1000000;
|
||||
for (int i = 0; i < pointerCount; ++i) {
|
||||
int pointerOffset = i * GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT;
|
||||
int historyAxisOffset =
|
||||
historyIndex * pointerCount * GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT;
|
||||
float *axisValues =
|
||||
&out_event->historicalAxisValues[historyAxisOffset + pointerOffset];
|
||||
for (int axisIndex = 0; axisIndex < GAME_ACTIVITY_POINTER_INFO_AXIS_COUNT;
|
||||
++axisIndex) {
|
||||
if (enabledAxes[axisIndex]) {
|
||||
axisValues[axisIndex] = env->CallFloatMethod(
|
||||
motionEvent, gMotionEventClassInfo.getHistoricalAxisValue,
|
||||
axisIndex, i, historyIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static struct {
|
||||
jmethodID getDeviceId;
|
||||
jmethodID getSource;
|
||||
jmethodID getAction;
|
||||
|
||||
jmethodID getEventTime;
|
||||
jmethodID getDownTime;
|
||||
|
||||
jmethodID getFlags;
|
||||
jmethodID getMetaState;
|
||||
|
||||
jmethodID getModifiers;
|
||||
jmethodID getRepeatCount;
|
||||
jmethodID getKeyCode;
|
||||
jmethodID getScanCode;
|
||||
// jmethodID getUnicodeChar;
|
||||
} gKeyEventClassInfo;
|
||||
|
||||
static void initKeyEvents(JNIEnv *env) {
|
||||
int sdkVersion = gamesdk::GetSystemPropAsInt("ro.build.version.sdk");
|
||||
gKeyEventClassInfo = {0};
|
||||
jclass keyEventClass = env->FindClass("android/view/KeyEvent");
|
||||
gKeyEventClassInfo.getDeviceId =
|
||||
env->GetMethodID(keyEventClass, "getDeviceId", "()I");
|
||||
gKeyEventClassInfo.getSource =
|
||||
env->GetMethodID(keyEventClass, "getSource", "()I");
|
||||
gKeyEventClassInfo.getAction =
|
||||
env->GetMethodID(keyEventClass, "getAction", "()I");
|
||||
gKeyEventClassInfo.getEventTime =
|
||||
env->GetMethodID(keyEventClass, "getEventTime", "()J");
|
||||
gKeyEventClassInfo.getDownTime =
|
||||
env->GetMethodID(keyEventClass, "getDownTime", "()J");
|
||||
gKeyEventClassInfo.getFlags =
|
||||
env->GetMethodID(keyEventClass, "getFlags", "()I");
|
||||
gKeyEventClassInfo.getMetaState =
|
||||
env->GetMethodID(keyEventClass, "getMetaState", "()I");
|
||||
if (sdkVersion >= 13) {
|
||||
gKeyEventClassInfo.getModifiers =
|
||||
env->GetMethodID(keyEventClass, "getModifiers", "()I");
|
||||
}
|
||||
gKeyEventClassInfo.getRepeatCount =
|
||||
env->GetMethodID(keyEventClass, "getRepeatCount", "()I");
|
||||
gKeyEventClassInfo.getKeyCode =
|
||||
env->GetMethodID(keyEventClass, "getKeyCode", "()I");
|
||||
gKeyEventClassInfo.getScanCode =
|
||||
env->GetMethodID(keyEventClass, "getScanCode", "()I");
|
||||
//gKeyEventClassInfo.getUnicodeChar =
|
||||
//env->GetMethodID(keyEventClass, "getUnicodeChar", "()I");
|
||||
}
|
||||
|
||||
extern "C" void GameActivityKeyEvent_fromJava(JNIEnv *env, jobject keyEvent,
|
||||
GameActivityKeyEvent *out_event) {
|
||||
*out_event = {
|
||||
/*deviceId=*/env->CallIntMethod(keyEvent, gKeyEventClassInfo.getDeviceId),
|
||||
/*source=*/env->CallIntMethod(keyEvent, gKeyEventClassInfo.getSource),
|
||||
/*action=*/env->CallIntMethod(keyEvent, gKeyEventClassInfo.getAction),
|
||||
// TODO: introduce a millisecondsToNanoseconds helper:
|
||||
/*eventTime=*/
|
||||
env->CallLongMethod(keyEvent, gKeyEventClassInfo.getEventTime) * 1000000,
|
||||
/*downTime=*/
|
||||
env->CallLongMethod(keyEvent, gKeyEventClassInfo.getDownTime) * 1000000,
|
||||
/*flags=*/env->CallIntMethod(keyEvent, gKeyEventClassInfo.getFlags),
|
||||
/*metaState=*/
|
||||
env->CallIntMethod(keyEvent, gKeyEventClassInfo.getMetaState),
|
||||
/*modifiers=*/gKeyEventClassInfo.getModifiers
|
||||
? env->CallIntMethod(keyEvent, gKeyEventClassInfo.getModifiers)
|
||||
: 0,
|
||||
/*repeatCount=*/
|
||||
env->CallIntMethod(keyEvent, gKeyEventClassInfo.getRepeatCount),
|
||||
/*keyCode=*/
|
||||
env->CallIntMethod(keyEvent, gKeyEventClassInfo.getKeyCode),
|
||||
/*scanCode=*/
|
||||
env->CallIntMethod(keyEvent, gKeyEventClassInfo.getScanCode)
|
||||
/*unicodeChar=*/
|
||||
// env->CallIntMethod(keyEvent, gKeyEventClassInfo.getUnicodeChar)
|
||||
};
|
||||
}
|
||||
|
||||
extern "C" void GameActivityEventsInit(JNIEnv *env) {
|
||||
initMotionEvents(env);
|
||||
initKeyEvents(env);
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright (C) 2022 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 Events Internal
|
||||
* These functions are internal details of Game Activity Events.
|
||||
* Please do not rely on anything in this file as this can be changed
|
||||
* without notice.
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @file GameActivityEvents_internal.h
|
||||
*/
|
||||
#ifndef ANDROID_GAME_SDK_GAME_ACTIVITY_EVENTS_INTERNAL_H
|
||||
#define ANDROID_GAME_SDK_GAME_ACTIVITY_EVENTS_INTERNAL_H
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/** \brief Performs necessary initialization steps for GameActivityEvents.
|
||||
*
|
||||
* User must call this function before calling any other functions of this unit.
|
||||
* If you use GameActivity it will call this function for you.
|
||||
*/
|
||||
void GameActivityEventsInit(JNIEnv* env);
|
||||
|
||||
/**
|
||||
* \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.
|
||||
* Ownership of out_event is maintained by the caller.
|
||||
* Note that we pass as much information from Java Activity as possible
|
||||
* to avoid extra JNI calls.
|
||||
*/
|
||||
void GameActivityMotionEvent_fromJava(JNIEnv* env, jobject motionEvent,
|
||||
GameActivityMotionEvent* out_event,
|
||||
int pointerCount, int historySize);
|
||||
|
||||
/**
|
||||
* \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);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif // ANDROID_GAME_SDK_GAME_ACTIVITY_EVENTS_INTERNAL_H
|
||||
+777
@@ -0,0 +1,777 @@
|
||||
/*
|
||||
* 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-activity/native_app_glue/android_native_app_glue.h"
|
||||
|
||||
#include <android/log.h>
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <jni.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define NATIVE_APP_GLUE_MOTION_EVENTS_DEFAULT_BUF_SIZE 16
|
||||
#define NATIVE_APP_GLUE_KEY_EVENTS_DEFAULT_BUF_SIZE 4
|
||||
|
||||
#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;
|
||||
int input_buf_idx = 0;
|
||||
|
||||
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);
|
||||
|
||||
/* initialize event buffers */
|
||||
for (input_buf_idx = 0; input_buf_idx < NATIVE_APP_GLUE_MAX_INPUT_BUFFERS;
|
||||
input_buf_idx++) {
|
||||
struct android_input_buffer* buf =
|
||||
&android_app->inputBuffers[input_buf_idx];
|
||||
|
||||
buf->motionEventsBufferSize =
|
||||
NATIVE_APP_GLUE_MOTION_EVENTS_DEFAULT_BUF_SIZE;
|
||||
buf->motionEvents = (GameActivityMotionEvent*)malloc(
|
||||
sizeof(GameActivityMotionEvent) * buf->motionEventsBufferSize);
|
||||
|
||||
buf->keyEventsBufferSize = NATIVE_APP_GLUE_KEY_EVENTS_DEFAULT_BUF_SIZE;
|
||||
buf->keyEvents = (GameActivityKeyEvent*)malloc(
|
||||
sizeof(GameActivityKeyEvent) * buf->keyEventsBufferSize);
|
||||
}
|
||||
|
||||
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) != 0;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------
|
||||
// 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;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
// NB: we have to consider that the native thread could have already
|
||||
// (gracefully) exit (setting android_app->destroyed) and so we need
|
||||
// to be careful to avoid a deadlock waiting for a thread that's
|
||||
// already exit.
|
||||
if (android_app->destroyed) {
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
return;
|
||||
}
|
||||
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);
|
||||
|
||||
// NB: we have to consider that the native thread could have already
|
||||
// (gracefully) exit (setting android_app->destroyed) and so we need
|
||||
// to be careful to avoid a deadlock waiting for a thread that's
|
||||
// already exit.
|
||||
if (!android_app->destroyed) {
|
||||
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) {
|
||||
int input_buf_idx = 0;
|
||||
|
||||
pthread_mutex_lock(&android_app->mutex);
|
||||
|
||||
// It's possible that onDestroy is called after we have already 'destroyed'
|
||||
// the app (via `android_app_destroy` due to `android_main` returning.
|
||||
//
|
||||
// In this case `->destroyed` will already be set (so we won't deadlock in
|
||||
// the loop below) but we still need to close the messaging fds and finish
|
||||
// freeing the android_app
|
||||
|
||||
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);
|
||||
|
||||
for (input_buf_idx = 0; input_buf_idx < NATIVE_APP_GLUE_MAX_INPUT_BUFFERS;
|
||||
input_buf_idx++) {
|
||||
struct android_input_buffer* buf =
|
||||
&android_app->inputBuffers[input_buf_idx];
|
||||
|
||||
android_app_clear_motion_events(buf);
|
||||
free(buf->motionEvents);
|
||||
free(buf->keyEvents);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
// NB: we have to consider that the native thread could have already
|
||||
// (gracefully) exit (setting android_app->destroyed) and so we need
|
||||
// to be careful to avoid a deadlock waiting for a thread that's
|
||||
// already exit.
|
||||
if (android_app->destroyed) {
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
bool android_app_input_available_wake_up(struct android_app* app) {
|
||||
pthread_mutex_lock(&app->mutex);
|
||||
bool available = app->inputAvailableWakeUp;
|
||||
app->inputAvailableWakeUp = false;
|
||||
pthread_mutex_unlock(&app->mutex);
|
||||
return available;
|
||||
}
|
||||
|
||||
// NB: should be called with the android_app->mutex held already
|
||||
static void notifyInput(struct android_app* android_app) {
|
||||
// Don't spam the mainloop with wake ups if we've already sent one
|
||||
if (android_app->inputSwapPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (android_app->looper != NULL) {
|
||||
// for the app thread to know why it received the wake() up
|
||||
android_app->inputAvailableWakeUp = true;
|
||||
android_app->inputSwapPending = true;
|
||||
ALooper_wake(android_app->looper);
|
||||
}
|
||||
}
|
||||
|
||||
static bool onTouchEvent(GameActivity* activity,
|
||||
const GameActivityMotionEvent* event) {
|
||||
struct android_app* android_app = ToApp(activity);
|
||||
pthread_mutex_lock(&android_app->mutex);
|
||||
|
||||
// NB: we have to consider that the native thread could have already
|
||||
// (gracefully) exit (setting android_app->destroyed) and so we need
|
||||
// to be careful to avoid a deadlock waiting for a thread that's
|
||||
// already exit.
|
||||
if (android_app->destroyed) {
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
return false;
|
||||
}
|
||||
|
||||
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 >= inputBuffer->motionEventsBufferSize) {
|
||||
inputBuffer->motionEventsBufferSize *= 2;
|
||||
inputBuffer->motionEvents = (GameActivityMotionEvent*)realloc(
|
||||
inputBuffer->motionEvents,
|
||||
sizeof(GameActivityMotionEvent) * inputBuffer->motionEventsBufferSize);
|
||||
|
||||
if (inputBuffer->motionEvents == NULL) {
|
||||
LOGE("onTouchEvent: out of memory");
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
int new_ix = inputBuffer->motionEventsCount;
|
||||
memcpy(&inputBuffer->motionEvents[new_ix], event,
|
||||
sizeof(GameActivityMotionEvent));
|
||||
++inputBuffer->motionEventsCount;
|
||||
notifyInput(android_app);
|
||||
|
||||
//android_app_write_cmd(android_app, APP_CMD_TOUCH_EVENT);
|
||||
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;
|
||||
}
|
||||
|
||||
android_app->inputSwapPending = false;
|
||||
android_app->inputAvailableWakeUp = false;
|
||||
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
|
||||
return inputBuffer;
|
||||
}
|
||||
|
||||
void android_app_clear_motion_events(struct android_input_buffer* inputBuffer) {
|
||||
// We do not need to lock here if the inputBuffer has already been swapped
|
||||
// as is handled by the game loop thread
|
||||
while (inputBuffer->motionEventsCount > 0) {
|
||||
GameActivityMotionEvent_destroy(
|
||||
&inputBuffer->motionEvents[inputBuffer->motionEventsCount - 1]);
|
||||
|
||||
inputBuffer->motionEventsCount--;
|
||||
}
|
||||
assert(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);
|
||||
|
||||
// NB: we have to consider that the native thread could have already
|
||||
// (gracefully) exit (setting android_app->destroyed) and so we need
|
||||
// to be careful to avoid a deadlock waiting for a thread that's
|
||||
// already exit.
|
||||
if (android_app->destroyed) {
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
return false;
|
||||
}
|
||||
|
||||
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 >= inputBuffer->keyEventsBufferSize) {
|
||||
inputBuffer->keyEventsBufferSize = inputBuffer->keyEventsBufferSize * 2;
|
||||
inputBuffer->keyEvents = (GameActivityKeyEvent*)realloc(
|
||||
inputBuffer->keyEvents,
|
||||
sizeof(GameActivityKeyEvent) * inputBuffer->keyEventsBufferSize);
|
||||
|
||||
if (inputBuffer->keyEvents == NULL) {
|
||||
LOGE("onKey: out of memory");
|
||||
abort();
|
||||
}
|
||||
}
|
||||
|
||||
int new_ix = inputBuffer->keyEventsCount;
|
||||
memcpy(&inputBuffer->keyEvents[new_ix], event, sizeof(GameActivityKeyEvent));
|
||||
++inputBuffer->keyEventsCount;
|
||||
notifyInput(android_app);
|
||||
|
||||
//android_app_write_cmd(android_app, APP_CMD_KEY_EVENT);
|
||||
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);
|
||||
if (!android_app->destroyed) {
|
||||
android_app->textInputState = 1;
|
||||
notifyInput(android_app);
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
static void onContentRectChanged(GameActivity* activity, const ARect* rect) {
|
||||
LOGV("ContentRectChanged: %p -- (%d %d) (%d %d)", activity, rect->left,
|
||||
rect->top, rect->right, rect->bottom);
|
||||
|
||||
struct android_app* android_app = ToApp(activity);
|
||||
|
||||
pthread_mutex_lock(&android_app->mutex);
|
||||
android_app->contentRect = *rect;
|
||||
|
||||
android_app_write_cmd(android_app, APP_CMD_CONTENT_RECT_CHANGED);
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
}
|
||||
|
||||
static void onSoftwareKeyboardVisibilityChanged(GameActivity* activity,
|
||||
bool visible) {
|
||||
LOGV("SoftwareKeyboardVisibilityChanged: %p -- %d", activity, (int)visible);
|
||||
|
||||
struct android_app* android_app = ToApp(activity);
|
||||
|
||||
pthread_mutex_lock(&android_app->mutex);
|
||||
android_app->softwareKeyboardVisible = visible;
|
||||
|
||||
android_app_write_cmd(android_app, APP_CMD_SOFTWARE_KB_VIS_CHANGED);
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
}
|
||||
|
||||
static bool onEditorAction(GameActivity* activity, int action) {
|
||||
LOGV("EditorAction: %p -- %d", activity, action);
|
||||
|
||||
struct android_app* android_app = ToApp(activity);
|
||||
|
||||
pthread_mutex_lock(&android_app->mutex);
|
||||
|
||||
// XXX: this is a racy design that could lose InputConnection actions if the
|
||||
// application doesn't manage to look at app->editorAction before another
|
||||
// action is delivered.
|
||||
if (android_app->pendingEditorAction) {
|
||||
LOGW("Dropping editor action %d because previous action %d not yet "
|
||||
"handled",
|
||||
action, android_app->editorAction);
|
||||
}
|
||||
android_app->editorAction = action;
|
||||
android_app->pendingEditorAction = true;
|
||||
notifyInput(android_app);
|
||||
// TODO: buffer IME text events and editor actions like other input events
|
||||
|
||||
//android_app_write_cmd(android_app, APP_CMD_EDITOR_ACTION);
|
||||
pthread_mutex_unlock(&android_app->mutex);
|
||||
return true;
|
||||
}
|
||||
|
||||
// XXX: This symbol is renamed with a _C suffix and then re-exported from
|
||||
// Rust because Rust/Cargo don't give us a way to directly export symbols
|
||||
// from C/C++ code: https://github.com/rust-lang/rfcs/issues/2771
|
||||
//
|
||||
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;
|
||||
activity->callbacks->onContentRectChanged = onContentRectChanged;
|
||||
activity->callbacks->onSoftwareKeyboardVisibilityChanged =
|
||||
onSoftwareKeyboardVisibilityChanged;
|
||||
activity->callbacks->onEditorAction = onEditorAction;
|
||||
LOGV("Callbacks set: %p", activity->callbacks);
|
||||
|
||||
activity->instance = android_app_create(activity, savedState, savedStateSize);
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../../../../game-text-input/prefab-src/modules/game-text-input/src/game-text-input/gametextinput.cpp
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../../../../game-text-input/prefab-src/modules/game-text-input/include/game-text-input/gametextinput.h
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "game-activity",
|
||||
"schema_version": 1,
|
||||
"dependencies": [],
|
||||
"version": "0.0.1",
|
||||
"cpp_files": [
|
||||
"src/common/system_utils.cpp",
|
||||
"src/game-activity/GameActivity.cpp",
|
||||
"src/game-activity/native_app_glue/android_native_app_glue.c",
|
||||
"src/game-activity/GameActivityEvents.cpp",
|
||||
"src/game-text-input/gametextinput.cpp"
|
||||
]
|
||||
}
|
||||
android-activity/android-games-sdk/game-text-input/prefab-src/modules/game-text-input/include/common
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../../../../include/common/
|
||||
+929
@@ -0,0 +1,929 @@
|
||||
/*
|
||||
* 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 "common/gamesdk_common.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define GAMETEXTINPUT_MAJOR_VERSION 4
|
||||
#define GAMETEXTINPUT_MINOR_VERSION 0
|
||||
#define GAMETEXTINPUT_BUGFIX_VERSION 0
|
||||
#define GAMETEXTINPUT_PACKED_VERSION \
|
||||
ANDROID_GAMESDK_PACKED_VERSION(GAMETEXTINPUT_MAJOR_VERSION, \
|
||||
GAMETEXTINPUT_MINOR_VERSION, \
|
||||
GAMETEXTINPUT_BUGFIX_VERSION)
|
||||
|
||||
/**
|
||||
* 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 : int32_t { 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 : uint32_t {
|
||||
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 : uint32_t {
|
||||
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.
|
||||
};
|
||||
|
||||
/**
|
||||
* Hide 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);
|
||||
|
||||
/**
|
||||
* Restarts the input method. Calls InputMethodManager.restartInput().
|
||||
* @param input A valid GameTextInput library handle.
|
||||
*/
|
||||
void GameTextInput_restartInput(GameTextInput *input);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* <b>This function is deprecated. Don't perform any complex processing inside
|
||||
* the callback other than copying the state variable. Using any synchronization
|
||||
* primitives inside this callback may cause a deadlock.</b>
|
||||
*/
|
||||
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);
|
||||
|
||||
/**
|
||||
* Definitions for inputType argument of GameActivity_setImeEditorInfo()
|
||||
*
|
||||
* <pre>
|
||||
* |-------|-------|-------|-------|
|
||||
* 1111 TYPE_MASK_CLASS
|
||||
* 11111111 TYPE_MASK_VARIATION
|
||||
* 111111111111 TYPE_MASK_FLAGS
|
||||
* |-------|-------|-------|-------|
|
||||
* TYPE_NULL
|
||||
* |-------|-------|-------|-------|
|
||||
* 1 TYPE_CLASS_TEXT
|
||||
* 1 TYPE_TEXT_VARIATION_URI
|
||||
* 1 TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|
||||
* 11 TYPE_TEXT_VARIATION_EMAIL_SUBJECT
|
||||
* 1 TYPE_TEXT_VARIATION_SHORT_MESSAGE
|
||||
* 1 1 TYPE_TEXT_VARIATION_LONG_MESSAGE
|
||||
* 11 TYPE_TEXT_VARIATION_PERSON_NAME
|
||||
* 111 TYPE_TEXT_VARIATION_POSTAL_ADDRESS
|
||||
* 1 TYPE_TEXT_VARIATION_PASSWORD
|
||||
* 1 1 TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
|
||||
* 1 1 TYPE_TEXT_VARIATION_WEB_EDIT_TEXT
|
||||
* 1 11 TYPE_TEXT_VARIATION_FILTER
|
||||
* 11 TYPE_TEXT_VARIATION_PHONETIC
|
||||
* 11 1 TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS
|
||||
* 111 TYPE_TEXT_VARIATION_WEB_PASSWORD
|
||||
* 1 TYPE_TEXT_FLAG_CAP_CHARACTERS
|
||||
* 1 TYPE_TEXT_FLAG_CAP_WORDS
|
||||
* 1 TYPE_TEXT_FLAG_CAP_SENTENCES
|
||||
* 1 TYPE_TEXT_FLAG_AUTO_CORRECT
|
||||
* 1 TYPE_TEXT_FLAG_AUTO_COMPLETE
|
||||
* 1 TYPE_TEXT_FLAG_MULTI_LINE
|
||||
* 1 TYPE_TEXT_FLAG_IME_MULTI_LINE
|
||||
* 1 TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
* 1 TYPE_TEXT_FLAG_ENABLE_TEXT_CONVERSION_SUGGESTIONS
|
||||
* |-------|-------|-------|-------|
|
||||
* 1 TYPE_CLASS_NUMBER
|
||||
* 1 TYPE_NUMBER_VARIATION_PASSWORD
|
||||
* 1 TYPE_NUMBER_FLAG_SIGNED
|
||||
* 1 TYPE_NUMBER_FLAG_DECIMAL
|
||||
* |-------|-------|-------|-------|
|
||||
* 11 TYPE_CLASS_PHONE
|
||||
* |-------|-------|-------|-------|
|
||||
* 1 TYPE_CLASS_DATETIME
|
||||
* 1 TYPE_DATETIME_VARIATION_DATE
|
||||
* 1 TYPE_DATETIME_VARIATION_TIME
|
||||
* |-------|-------|-------|-------|</pre>
|
||||
*/
|
||||
|
||||
enum GameTextInputType : uint32_t {
|
||||
/**
|
||||
* Mask of bits that determine the overall class
|
||||
* of text being given. Currently supported classes are:
|
||||
* {@link #TYPE_CLASS_TEXT}, {@link #TYPE_CLASS_NUMBER},
|
||||
* {@link #TYPE_CLASS_PHONE}, {@link #TYPE_CLASS_DATETIME}.
|
||||
* <p>IME authors: If the class is not one you
|
||||
* understand, assume {@link #TYPE_CLASS_TEXT} with NO variation
|
||||
* or flags.<p>
|
||||
*/
|
||||
TYPE_MASK_CLASS = 0x0000000f,
|
||||
|
||||
/**
|
||||
* Mask of bits that determine the variation of
|
||||
* the base content class.
|
||||
*/
|
||||
TYPE_MASK_VARIATION = 0x00000ff0,
|
||||
|
||||
/**
|
||||
* Mask of bits that provide addition bit flags
|
||||
* of options.
|
||||
*/
|
||||
TYPE_MASK_FLAGS = 0x00fff000,
|
||||
|
||||
/**
|
||||
* Special content type for when no explicit type has been specified.
|
||||
* This should be interpreted to mean that the target input connection
|
||||
* is not rich, it can not process and show things like candidate text nor
|
||||
* retrieve the current text, so the input method will need to run in a
|
||||
* limited "generate key events" mode, if it supports it. Note that some
|
||||
* input methods may not support it, for example a voice-based input
|
||||
* method will likely not be able to generate key events even if this
|
||||
* flag is set.
|
||||
*/
|
||||
TYPE_NULL = 0x00000000,
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Class for normal text. This class supports the following flags (only
|
||||
* one of which should be set):
|
||||
* {@link #TYPE_TEXT_FLAG_CAP_CHARACTERS},
|
||||
* {@link #TYPE_TEXT_FLAG_CAP_WORDS}, and.
|
||||
* {@link #TYPE_TEXT_FLAG_CAP_SENTENCES}. It also supports the
|
||||
* following variations:
|
||||
* {@link #TYPE_TEXT_VARIATION_NORMAL}, and
|
||||
* {@link #TYPE_TEXT_VARIATION_URI}. If you do not recognize the
|
||||
* variation, normal should be assumed.
|
||||
*/
|
||||
TYPE_CLASS_TEXT = 0x00000001,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: capitalize all characters. Overrides
|
||||
* {@link #TYPE_TEXT_FLAG_CAP_WORDS} and
|
||||
* {@link #TYPE_TEXT_FLAG_CAP_SENTENCES}. This value is explicitly defined
|
||||
* to be the same as {@link TextUtils#CAP_MODE_CHARACTERS}. Of course,
|
||||
* this only affects languages where there are upper-case and lower-case
|
||||
* letters.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_CAP_CHARACTERS = 0x00001000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: capitalize the first character of
|
||||
* every word. Overrides {@link #TYPE_TEXT_FLAG_CAP_SENTENCES}. This
|
||||
* value is explicitly defined
|
||||
* to be the same as {@link TextUtils#CAP_MODE_WORDS}. Of course,
|
||||
* this only affects languages where there are upper-case and lower-case
|
||||
* letters.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_CAP_WORDS = 0x00002000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: capitalize the first character of
|
||||
* each sentence. This value is explicitly defined
|
||||
* to be the same as {@link TextUtils#CAP_MODE_SENTENCES}. For example
|
||||
* in English it means to capitalize after a period and a space (note that
|
||||
* other languages may have different characters for period, or not use
|
||||
* spaces, or use different grammatical rules). Of course, this only affects
|
||||
* languages where there are upper-case and lower-case letters.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_CAP_SENTENCES = 0x00004000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: the user is entering free-form
|
||||
* text that should have auto-correction applied to it. Without this flag,
|
||||
* the IME will not try to correct typos. You should always set this flag
|
||||
* unless you really expect users to type non-words in this field, for
|
||||
* example to choose a name for a character in a game.
|
||||
* Contrast this with {@link #TYPE_TEXT_FLAG_AUTO_COMPLETE} and
|
||||
* {@link #TYPE_TEXT_FLAG_NO_SUGGESTIONS}:
|
||||
* {@code TYPE_TEXT_FLAG_AUTO_CORRECT} means that the IME will try to
|
||||
* auto-correct typos as the user is typing, but does not define whether
|
||||
* the IME offers an interface to show suggestions.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_AUTO_CORRECT = 0x00008000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: the text editor (which means
|
||||
* the application) is performing auto-completion of the text being entered
|
||||
* based on its own semantics, which it will present to the user as they type.
|
||||
* This generally means that the input method should not be showing
|
||||
* candidates itself, but can expect the editor to supply its own
|
||||
* completions/candidates from
|
||||
* {@link android.view.inputmethod.InputMethodSession#displayCompletions
|
||||
* InputMethodSession.displayCompletions()} as a result of the editor calling
|
||||
* {@link android.view.inputmethod.InputMethodManager#displayCompletions
|
||||
* InputMethodManager.displayCompletions()}.
|
||||
* Note the contrast with {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} and
|
||||
* {@link #TYPE_TEXT_FLAG_NO_SUGGESTIONS}:
|
||||
* {@code TYPE_TEXT_FLAG_AUTO_COMPLETE} means the editor should show an
|
||||
* interface for displaying suggestions, but instead of supplying its own
|
||||
* it will rely on the Editor to pass completions/corrections.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_AUTO_COMPLETE = 0x00010000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: multiple lines of text can be
|
||||
* entered into the field. If this flag is not set, the text field
|
||||
* will be constrained to a single line. The IME may also choose not to
|
||||
* display an enter key when this flag is not set, as there should be no
|
||||
* need to create new lines.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_MULTI_LINE = 0x00020000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: the regular text view associated
|
||||
* with this should not be multi-line, but when a fullscreen input method
|
||||
* is providing text it should use multiple lines if it can.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_IME_MULTI_LINE = 0x00040000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: the input method does not need to
|
||||
* display any dictionary-based candidates. This is useful for text views that
|
||||
* do not contain words from the language and do not benefit from any
|
||||
* dictionary-based completions or corrections. It overrides the
|
||||
* {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} value when set.
|
||||
* Please avoid using this unless you are certain this is what you want.
|
||||
* Many input methods need suggestions to work well, for example the ones
|
||||
* based on gesture typing. Consider clearing
|
||||
* {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} instead if you just do not
|
||||
* want the IME to correct typos.
|
||||
* Note the contrast with {@link #TYPE_TEXT_FLAG_AUTO_CORRECT} and
|
||||
* {@link #TYPE_TEXT_FLAG_AUTO_COMPLETE}:
|
||||
* {@code TYPE_TEXT_FLAG_NO_SUGGESTIONS} means the IME does not need to
|
||||
* show an interface to display suggestions. Most IMEs will also take this to
|
||||
* mean they do not need to try to auto-correct what the user is typing.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_NO_SUGGESTIONS = 0x00080000,
|
||||
|
||||
/**
|
||||
* Flag for {@link #TYPE_CLASS_TEXT}: Let the IME know the text conversion
|
||||
* suggestions are required by the application. Text conversion suggestion is
|
||||
* for the transliteration languages which has pronunciation characters and
|
||||
* target characters. When the user is typing the pronunciation charactes, the
|
||||
* IME could provide the possible target characters to the user. When this
|
||||
* flag is set, the IME should insert the text conversion suggestions through
|
||||
* {@link Builder#setTextConversionSuggestions(List)} and
|
||||
* the {@link TextAttribute} with initialized with the text conversion
|
||||
* suggestions is provided by the IME to the application. To receive the
|
||||
* additional information, the application needs to implement {@link
|
||||
* InputConnection#setComposingText(CharSequence, int, TextAttribute)},
|
||||
* {@link InputConnection#setComposingRegion(int, int, TextAttribute)}, and
|
||||
* {@link InputConnection#commitText(CharSequence, int, TextAttribute)}.
|
||||
*/
|
||||
TYPE_TEXT_FLAG_ENABLE_TEXT_CONVERSION_SUGGESTIONS = 0x00100000,
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Default variation of {@link #TYPE_CLASS_TEXT}: plain old normal text.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_NORMAL = 0x00000000,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering a URI.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_URI = 0x00000010,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering an e-mail address.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_EMAIL_ADDRESS = 0x00000020,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering the subject line of
|
||||
* an e-mail.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_EMAIL_SUBJECT = 0x00000030,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering a short, possibly informal
|
||||
* message such as an instant message or a text message.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_SHORT_MESSAGE = 0x00000040,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering the content of a long,
|
||||
* possibly formal message such as the body of an e-mail.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_LONG_MESSAGE = 0x00000050,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering the name of a person.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_PERSON_NAME = 0x00000060,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering a postal mailing address.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_POSTAL_ADDRESS = 0x00000070,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering a password.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_PASSWORD = 0x00000080,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering a password, which should
|
||||
* be visible to the user.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_VISIBLE_PASSWORD = 0x00000090,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering text inside of a web form.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_WEB_EDIT_TEXT = 0x000000a0,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering text to filter contents
|
||||
* of a list etc.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_FILTER = 0x000000b0,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering text for phonetic
|
||||
* pronunciation, such as a phonetic name field in contacts. This is mostly
|
||||
* useful for languages where one spelling may have several phonetic
|
||||
* readings, like Japanese.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_PHONETIC = 0x000000c0,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering e-mail address inside
|
||||
* of a web form. This was added in
|
||||
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An IME must target
|
||||
* this API version or later to see this input type; if it doesn't, a request
|
||||
* for this type will be seen as {@link #TYPE_TEXT_VARIATION_EMAIL_ADDRESS}
|
||||
* when passed through {@link
|
||||
* android.view.inputmethod.EditorInfo#makeCompatible(int)
|
||||
* EditorInfo.makeCompatible(int)}.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS = 0x000000d0,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_TEXT}: entering password inside
|
||||
* of a web form. This was added in
|
||||
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An IME must target
|
||||
* this API version or later to see this input type; if it doesn't, a request
|
||||
* for this type will be seen as {@link #TYPE_TEXT_VARIATION_PASSWORD}
|
||||
* when passed through {@link
|
||||
* android.view.inputmethod.EditorInfo#makeCompatible(int)
|
||||
* EditorInfo.makeCompatible(int)}.
|
||||
*/
|
||||
TYPE_TEXT_VARIATION_WEB_PASSWORD = 0x000000e0,
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Class for numeric text. This class supports the following flags:
|
||||
* {@link #TYPE_NUMBER_FLAG_SIGNED} and
|
||||
* {@link #TYPE_NUMBER_FLAG_DECIMAL}. It also supports the following
|
||||
* variations: {@link #TYPE_NUMBER_VARIATION_NORMAL} and
|
||||
* {@link #TYPE_NUMBER_VARIATION_PASSWORD}.
|
||||
* <p>IME authors: If you do not recognize
|
||||
* the variation, normal should be assumed.</p>
|
||||
*/
|
||||
TYPE_CLASS_NUMBER = 0x00000002,
|
||||
|
||||
/**
|
||||
* Flag of {@link #TYPE_CLASS_NUMBER}: the number is signed, allowing
|
||||
* a positive or negative sign at the start.
|
||||
*/
|
||||
TYPE_NUMBER_FLAG_SIGNED = 0x00001000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #TYPE_CLASS_NUMBER}: the number is decimal, allowing
|
||||
* a decimal point to provide fractional values.
|
||||
*/
|
||||
TYPE_NUMBER_FLAG_DECIMAL = 0x00002000,
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Default variation of {@link #TYPE_CLASS_NUMBER}: plain normal
|
||||
* numeric text. This was added in
|
||||
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An IME must target
|
||||
* this API version or later to see this input type; if it doesn't, a request
|
||||
* for this type will be dropped when passed through
|
||||
* {@link android.view.inputmethod.EditorInfo#makeCompatible(int)
|
||||
* EditorInfo.makeCompatible(int)}.
|
||||
*/
|
||||
TYPE_NUMBER_VARIATION_NORMAL = 0x00000000,
|
||||
|
||||
/**
|
||||
* Variation of {@link #TYPE_CLASS_NUMBER}: entering a numeric password.
|
||||
* This was added in {@link android.os.Build.VERSION_CODES#HONEYCOMB}. An
|
||||
* IME must target this API version or later to see this input type; if it
|
||||
* doesn't, a request for this type will be dropped when passed
|
||||
* through {@link android.view.inputmethod.EditorInfo#makeCompatible(int)
|
||||
* EditorInfo.makeCompatible(int)}.
|
||||
*/
|
||||
TYPE_NUMBER_VARIATION_PASSWORD = 0x00000010,
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
/**
|
||||
* Class for a phone number. This class currently supports no variations
|
||||
* or flags.
|
||||
*/
|
||||
TYPE_CLASS_PHONE = 0x00000003,
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Class for dates and times. It supports the
|
||||
* following variations:
|
||||
* {@link #TYPE_DATETIME_VARIATION_NORMAL}
|
||||
* {@link #TYPE_DATETIME_VARIATION_DATE}, and
|
||||
* {@link #TYPE_DATETIME_VARIATION_TIME}.
|
||||
*/
|
||||
TYPE_CLASS_DATETIME = 0x00000004,
|
||||
|
||||
/**
|
||||
* Default variation of {@link #TYPE_CLASS_DATETIME}: allows entering
|
||||
* both a date and time.
|
||||
*/
|
||||
TYPE_DATETIME_VARIATION_NORMAL = 0x00000000,
|
||||
|
||||
/**
|
||||
* Default variation of {@link #TYPE_CLASS_DATETIME}: allows entering
|
||||
* only a date.
|
||||
*/
|
||||
TYPE_DATETIME_VARIATION_DATE = 0x00000010,
|
||||
|
||||
/**
|
||||
* Default variation of {@link #TYPE_CLASS_DATETIME}: allows entering
|
||||
* only a time.
|
||||
*/
|
||||
TYPE_DATETIME_VARIATION_TIME = 0x00000020,
|
||||
};
|
||||
|
||||
/**
|
||||
* actionId and imeOptions argument of GameActivity_setImeEditorInfo().
|
||||
*
|
||||
* <pre>
|
||||
* |-------|-------|-------|-------|
|
||||
* 1111 IME_MASK_ACTION
|
||||
* |-------|-------|-------|-------|
|
||||
* IME_ACTION_UNSPECIFIED
|
||||
* 1 IME_ACTION_NONE
|
||||
* 1 IME_ACTION_GO
|
||||
* 11 IME_ACTION_SEARCH
|
||||
* 1 IME_ACTION_SEND
|
||||
* 1 1 IME_ACTION_NEXT
|
||||
* 11 IME_ACTION_DONE
|
||||
* 111 IME_ACTION_PREVIOUS
|
||||
* 1 IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||
* 1 IME_FLAG_NO_FULLSCREEN
|
||||
* 1 IME_FLAG_NAVIGATE_PREVIOUS
|
||||
* 1 IME_FLAG_NAVIGATE_NEXT
|
||||
* 1 IME_FLAG_NO_EXTRACT_UI
|
||||
* 1 IME_FLAG_NO_ACCESSORY_ACTION
|
||||
* 1 IME_FLAG_NO_ENTER_ACTION
|
||||
* 1 IME_FLAG_FORCE_ASCII
|
||||
* |-------|-------|-------|-------|</pre>
|
||||
*/
|
||||
|
||||
enum GameTextInputActionType : uint32_t {
|
||||
/**
|
||||
* Set of bits in {@link #imeOptions} that provide alternative actions
|
||||
* associated with the "enter" key. This both helps the IME provide
|
||||
* better feedback about what the enter key will do, and also allows it
|
||||
* to provide alternative mechanisms for providing that command.
|
||||
*/
|
||||
IME_MASK_ACTION = 0x000000ff,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: no specific action has been
|
||||
* associated with this editor, let the editor come up with its own if
|
||||
* it can.
|
||||
*/
|
||||
IME_ACTION_UNSPECIFIED = 0x00000000,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: there is no available action.
|
||||
*/
|
||||
IME_ACTION_NONE = 0x00000001,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: the action key performs a "go"
|
||||
* operation to take the user to the target of the text they typed.
|
||||
* Typically used, for example, when entering a URL.
|
||||
*/
|
||||
IME_ACTION_GO = 0x00000002,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: the action key performs a "search"
|
||||
* operation, taking the user to the results of searching for the text
|
||||
* they have typed (in whatever context is appropriate).
|
||||
*/
|
||||
IME_ACTION_SEARCH = 0x00000003,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: the action key performs a "send"
|
||||
* operation, delivering the text to its target. This is typically used
|
||||
* when composing a message in IM or SMS where sending is immediate.
|
||||
*/
|
||||
IME_ACTION_SEND = 0x00000004,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: the action key performs a "next"
|
||||
* operation, taking the user to the next field that will accept text.
|
||||
*/
|
||||
IME_ACTION_NEXT = 0x00000005,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: the action key performs a "done"
|
||||
* operation, typically meaning there is nothing more to input and the
|
||||
* IME will be closed.
|
||||
*/
|
||||
IME_ACTION_DONE = 0x00000006,
|
||||
|
||||
/**
|
||||
* Bits of {@link #IME_MASK_ACTION}: like {@link #IME_ACTION_NEXT}, but
|
||||
* for moving to the previous field. This will normally not be used to
|
||||
* specify an action (since it precludes {@link #IME_ACTION_NEXT}), but
|
||||
* can be returned to the app if it sets {@link #IME_FLAG_NAVIGATE_PREVIOUS}.
|
||||
*/
|
||||
IME_ACTION_PREVIOUS = 0x00000007,
|
||||
};
|
||||
|
||||
enum GameTextInputImeOptions : uint32_t {
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: used to request that the IME should not update
|
||||
* any personalized data such as typing history and personalized language
|
||||
* model based on what the user typed on this text editing object. Typical
|
||||
* use cases are: <ul> <li>When the application is in a special mode, where
|
||||
* user's activities are expected to be not recorded in the application's
|
||||
* history. Some web browsers and chat applications may have this kind of
|
||||
* modes.</li> <li>When storing typing history does not make much sense.
|
||||
* Specifying this flag in typing games may help to avoid typing history from
|
||||
* being filled up with words that the user is less likely to type in their
|
||||
* daily life. Another example is that when the application already knows
|
||||
* that the expected input is not a valid word (e.g. a promotion code that is
|
||||
* not a valid word in any natural language).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Applications need to be aware that the flag is not a guarantee, and some
|
||||
* IMEs may not respect it.</p>
|
||||
*/
|
||||
IME_FLAG_NO_PERSONALIZED_LEARNING = 0x1000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: used to request that the IME never go
|
||||
* into fullscreen mode.
|
||||
* By default, IMEs may go into full screen mode when they think
|
||||
* it's appropriate, for example on small screens in landscape
|
||||
* orientation where displaying a software keyboard may occlude
|
||||
* such a large portion of the screen that the remaining part is
|
||||
* too small to meaningfully display the application UI.
|
||||
* If this flag is set, compliant IMEs will never go into full screen mode,
|
||||
* and always leave some space to display the application UI.
|
||||
* Applications need to be aware that the flag is not a guarantee, and
|
||||
* some IMEs may ignore it.
|
||||
*/
|
||||
IME_FLAG_NO_FULLSCREEN = 0x2000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: like {@link #IME_FLAG_NAVIGATE_NEXT}, but
|
||||
* specifies there is something interesting that a backward navigation
|
||||
* can focus on. If the user selects the IME's facility to backward
|
||||
* navigate, this will show up in the application as an {@link
|
||||
* #IME_ACTION_PREVIOUS} at {@link InputConnection#performEditorAction(int)
|
||||
* InputConnection.performEditorAction(int)}.
|
||||
*/
|
||||
IME_FLAG_NAVIGATE_PREVIOUS = 0x4000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: used to specify that there is something
|
||||
* interesting that a forward navigation can focus on. This is like using
|
||||
* {@link #IME_ACTION_NEXT}, except allows the IME to be multiline (with
|
||||
* an enter key) as well as provide forward navigation. Note that some
|
||||
* IMEs may not be able to do this, especially when running on a small
|
||||
* screen where there is little space. In that case it does not need to
|
||||
* present a UI for this option. Like {@link #IME_ACTION_NEXT}, if the
|
||||
* user selects the IME's facility to forward navigate, this will show up
|
||||
* in the application at {@link InputConnection#performEditorAction(int)
|
||||
* InputConnection.performEditorAction(int)}.
|
||||
*/
|
||||
IME_FLAG_NAVIGATE_NEXT = 0x8000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: used to specify that the IME does not need
|
||||
* to show its extracted text UI. For input methods that may be fullscreen,
|
||||
* often when in landscape mode, this allows them to be smaller and let part
|
||||
* of the application be shown behind, through transparent UI parts in the
|
||||
* fullscreen IME. The part of the UI visible to the user may not be
|
||||
* responsive to touch because the IME will receive touch events, which may
|
||||
* confuse the user; use {@link #IME_FLAG_NO_FULLSCREEN} instead for a better
|
||||
* experience. Using this flag is discouraged and it may become deprecated in
|
||||
* the future. Its meaning is unclear in some situations and it may not work
|
||||
* appropriately on older versions of the platform.
|
||||
*/
|
||||
IME_FLAG_NO_EXTRACT_UI = 0x10000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: used in conjunction with one of the actions
|
||||
* masked by {@link #IME_MASK_ACTION}, this indicates that the action
|
||||
* should not be available as an accessory button on the right of the
|
||||
* extracted text when the input method is full-screen. Note that by setting
|
||||
* this flag, there can be cases where the action is simply never available to
|
||||
* the user. Setting this generally means that you think that in fullscreen
|
||||
* mode, where there is little space to show the text, it's not worth taking
|
||||
* some screen real estate to display the action and it should be used instead
|
||||
* to show more text.
|
||||
*/
|
||||
IME_FLAG_NO_ACCESSORY_ACTION = 0x20000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: used in conjunction with one of the actions
|
||||
* masked by {@link #IME_MASK_ACTION}. If this flag is not set, IMEs will
|
||||
* normally replace the "enter" key with the action supplied. This flag
|
||||
* indicates that the action should not be available in-line as a replacement
|
||||
* for the "enter" key. Typically this is because the action has such a
|
||||
* significant impact or is not recoverable enough that accidentally hitting
|
||||
* it should be avoided, such as sending a message. Note that
|
||||
* {@link android.widget.TextView} will automatically set this flag for you
|
||||
* on multi-line text views.
|
||||
*/
|
||||
IME_FLAG_NO_ENTER_ACTION = 0x40000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #imeOptions}: used to request an IME that is capable of
|
||||
* inputting ASCII characters. The intention of this flag is to ensure that
|
||||
* the user can type Roman alphabet characters in a {@link
|
||||
* android.widget.TextView}. It is typically used for an account ID or
|
||||
* password input. A lot of the time, IMEs are already able to input ASCII
|
||||
* even without being told so (such IMEs already respect this flag in a
|
||||
* sense), but there are cases when this is not the default. For instance,
|
||||
* users of languages using a different script like Arabic, Greek, Hebrew or
|
||||
* Russian typically have a keyboard that can't input ASCII characters by
|
||||
* default. Applications need to be aware that the flag is not a guarantee,
|
||||
* and some IMEs may not respect it. However, it is strongly recommended for
|
||||
* IME authors to respect this flag especially when their IME could end up
|
||||
* with a state where only languages using non-ASCII are enabled.
|
||||
*/
|
||||
IME_FLAG_FORCE_ASCII = 0x80000000,
|
||||
|
||||
/**
|
||||
* Flag of {@link #internalImeOptions}: flag is set when app window containing
|
||||
* this
|
||||
* {@link EditorInfo} is using {@link Configuration#ORIENTATION_PORTRAIT}
|
||||
* mode.
|
||||
* @hide
|
||||
*/
|
||||
IME_INTERNAL_FLAG_APP_WINDOW_PORTRAIT = 0x00000001,
|
||||
|
||||
/**
|
||||
* Generic unspecified type for {@link #imeOptions}.
|
||||
*/
|
||||
IME_NULL = 0x00000000,
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"export_libraries": [],
|
||||
"library_name": null,
|
||||
"android": {
|
||||
"export_libraries": null,
|
||||
"library_name": null
|
||||
}
|
||||
}
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
/*
|
||||
* 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 <mutex>
|
||||
#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);
|
||||
GameTextInputState getState() const {
|
||||
std::lock_guard<std::mutex> lock(currentStateMutex_);
|
||||
return currentState_;
|
||||
}
|
||||
void setInputConnection(jobject inputConnection);
|
||||
void processEvent(jobject textInputEvent);
|
||||
void showIme(uint32_t flags);
|
||||
void hideIme(uint32_t flags);
|
||||
void restartInput();
|
||||
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_ = {};
|
||||
// A mutex to protect currentState_.
|
||||
mutable std::mutex currentStateMutex_;
|
||||
// An instance of gametextinput.InputConnection.
|
||||
jclass inputConnectionClass_ = nullptr;
|
||||
jobject inputConnection_ = nullptr;
|
||||
jmethodID inputConnectionSetStateMethod_;
|
||||
jmethodID setSoftKeyboardActiveMethod_;
|
||||
jmethodID restartInputMethod_;
|
||||
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) {
|
||||
GameTextInputState state = input->getState();
|
||||
callback(context, &state);
|
||||
}
|
||||
|
||||
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_restartInput(struct GameTextInput *input) {
|
||||
input->restartInput();
|
||||
}
|
||||
|
||||
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");
|
||||
restartInputMethod_ =
|
||||
env_->GetMethodID(inputConnectionClass_, "restartInput", "()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) {
|
||||
std::lock_guard<std::mutex> lock(currentStateMutex_);
|
||||
|
||||
// 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_) {
|
||||
std::lock_guard<std::mutex> lock(currentStateMutex_);
|
||||
eventCallback_(eventCallbackContext_, ¤tState_);
|
||||
}
|
||||
}
|
||||
|
||||
void GameTextInput::showIme(uint32_t flags) {
|
||||
if (inputConnection_ == nullptr) return;
|
||||
env_->CallVoidMethod(inputConnection_, setSoftKeyboardActiveMethod_, true,
|
||||
static_cast<jint>(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_, ¤tInsets_);
|
||||
}
|
||||
}
|
||||
|
||||
void GameTextInput::hideIme(uint32_t flags) {
|
||||
if (inputConnection_ == nullptr) return;
|
||||
env_->CallVoidMethod(inputConnection_, setSoftKeyboardActiveMethod_, false,
|
||||
static_cast<jint>(flags));
|
||||
}
|
||||
|
||||
void GameTextInput::restartInput() {
|
||||
if (inputConnection_ == nullptr) return;
|
||||
env_->CallVoidMethod(inputConnection_, restartInputMethod_);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "game-text-input",
|
||||
"schema_version": 1,
|
||||
"dependencies": [],
|
||||
"version": "0.0.1",
|
||||
"cpp_files": [
|
||||
"src/game-text-input/gametextinput.cpp"
|
||||
]
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#!/bin/bash
|
||||
set -xe
|
||||
|
||||
# Copies the native, prefab-src for GameActivity + GameTextInput from the
|
||||
# upstream, android-games-sdk, including our android-activity integration
|
||||
# changes.
|
||||
#
|
||||
# This code is maintained out-of-tree, based on a fork of Google's AGDK repo, so
|
||||
# it's more practical to try and upstream changes we make, or to rebase on new
|
||||
# versions.
|
||||
|
||||
if [ $# -ne 1 ]; then
|
||||
echo "Usage: $0 <android-games-sdk dir>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SOURCE_DIR="$1"
|
||||
TOP_DIR=$(git rev-parse --show-toplevel)
|
||||
DEST_DIR="$TOP_DIR/android-activity/android-games-sdk"
|
||||
|
||||
if [ ! -d "$SOURCE_DIR" ]; then
|
||||
echo "Error: Source directory '$SOURCE_DIR' does not exist."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -d "$DEST_DIR" ]; then
|
||||
echo "Error: expected find destination directory $DEST_DIR"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
rm -fr "$DEST_DIR/game-activity"
|
||||
rm -fr "$DEST_DIR/game-text-input"
|
||||
rm -fr "$DEST_DIR/src/common"
|
||||
rm -fr "$DEST_DIR/include/common"
|
||||
|
||||
mkdir -p "$DEST_DIR/game-activity"
|
||||
mkdir -p "$DEST_DIR/game-text-input"
|
||||
mkdir -p "$DEST_DIR/include/common"
|
||||
mkdir -p "$DEST_DIR/src/common"
|
||||
|
||||
cp -av "$SOURCE_DIR/game-activity/prefab-src" "$DEST_DIR/game-activity"
|
||||
cp -av "$SOURCE_DIR/game-text-input/prefab-src" "$DEST_DIR/game-text-input"
|
||||
cp -av "$SOURCE_DIR/include/common/gamesdk_common.h" "$DEST_DIR/include/common"
|
||||
cp -av "$SOURCE_DIR/src/common/system_utils.h" "$DEST_DIR/src/common"
|
||||
cp -av "$SOURCE_DIR/src/common/system_utils.cpp" "$DEST_DIR/src/common"
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright 2020 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This is the main interface to the Android Performance Tuner library, also
|
||||
* known as Tuning Fork.
|
||||
*
|
||||
* It is part of the Android Games SDK and produces best results when integrated
|
||||
* with the Swappy Frame Pacing Library.
|
||||
*
|
||||
* See the documentation at
|
||||
* https://developer.android.com/games/sdk/performance-tuner/custom-engine for
|
||||
* more information on using this library in a native Android game.
|
||||
*
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// There are separate versions for each GameSDK component that use this format:
|
||||
#define ANDROID_GAMESDK_PACKED_VERSION(MAJOR, MINOR, BUGFIX) \
|
||||
((MAJOR << 16) | (MINOR << 8) | (BUGFIX))
|
||||
// Accessors
|
||||
#define ANDROID_GAMESDK_MAJOR_VERSION(PACKED) ((PACKED) >> 16)
|
||||
#define ANDROID_GAMESDK_MINOR_VERSION(PACKED) (((PACKED) >> 8) & 0xff)
|
||||
#define ANDROID_GAMESDK_BUGFIX_VERSION(PACKED) ((PACKED) & 0xff)
|
||||
|
||||
#define AGDK_STRINGIFY(NUMBER) #NUMBER
|
||||
#define AGDK_STRING_VERSION(MAJOR, MINOR, BUGFIX) \
|
||||
AGDK_STRINGIFY(MAJOR) "." AGDK_STRINGIFY(MINOR) "." AGDK_STRINGIFY(BUGFIX)
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* Copyright 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 "system_utils.h"
|
||||
|
||||
#include <android/api-level.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/system_properties.h>
|
||||
|
||||
namespace gamesdk {
|
||||
|
||||
#if __ANDROID_API__ >= 26
|
||||
std::string getSystemPropViaCallback(const char* key,
|
||||
const char* default_value = "") {
|
||||
const prop_info* prop = __system_property_find(key);
|
||||
if (prop == nullptr) {
|
||||
return default_value;
|
||||
}
|
||||
std::string return_value;
|
||||
auto thunk = [](void* cookie, const char* /*name*/, const char* value,
|
||||
uint32_t /*serial*/) {
|
||||
if (value != nullptr) {
|
||||
std::string* r = static_cast<std::string*>(cookie);
|
||||
*r = value;
|
||||
}
|
||||
};
|
||||
__system_property_read_callback(prop, thunk, &return_value);
|
||||
return return_value;
|
||||
}
|
||||
#else
|
||||
std::string getSystemPropViaGet(const char* key,
|
||||
const char* default_value = "") {
|
||||
char buffer[PROP_VALUE_MAX + 1] = ""; // +1 for terminator
|
||||
int bufferLen = __system_property_get(key, buffer);
|
||||
if (bufferLen > 0)
|
||||
return buffer;
|
||||
else
|
||||
return "";
|
||||
}
|
||||
#endif
|
||||
|
||||
std::string GetSystemProp(const char* key, const char* default_value) {
|
||||
#if __ANDROID_API__ >= 26
|
||||
return getSystemPropViaCallback(key, default_value);
|
||||
#else
|
||||
return getSystemPropViaGet(key, default_value);
|
||||
#endif
|
||||
}
|
||||
|
||||
int GetSystemPropAsInt(const char* key, int default_value) {
|
||||
std::string prop = GetSystemProp(key);
|
||||
return prop == "" ? default_value : strtoll(prop.c_str(), nullptr, 10);
|
||||
}
|
||||
|
||||
bool GetSystemPropAsBool(const char* key, bool default_value) {
|
||||
return GetSystemPropAsInt(key, default_value) != 0;
|
||||
}
|
||||
|
||||
} // namespace gamesdk
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 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
|
||||
|
||||
#include "string"
|
||||
|
||||
namespace gamesdk {
|
||||
|
||||
// Get the value of the given system property
|
||||
std::string GetSystemProp(const char* key, const char* default_value = "");
|
||||
|
||||
// Get the value of the given system property as an integer
|
||||
int GetSystemPropAsInt(const char* key, int default_value = 0);
|
||||
|
||||
// Get the value of the given system property as a bool
|
||||
bool GetSystemPropAsBool(const char* key, bool default_value = false);
|
||||
|
||||
} // namespace gamesdk
|
||||
+90
-11
@@ -1,23 +1,87 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
fn build_glue_for_game_activity() {
|
||||
let android_games_sdk =
|
||||
std::env::var("ANDROID_GAMES_SDK").unwrap_or_else(|_err| "android-games-sdk".to_string());
|
||||
|
||||
let activity_path = |src_inc, name| {
|
||||
format!("{android_games_sdk}/game-activity/prefab-src/modules/game-activity/{src_inc}/game-activity/{name}")
|
||||
};
|
||||
let textinput_path = |src_inc, name| {
|
||||
format!("{android_games_sdk}/game-text-input/prefab-src/modules/game-text-input/{src_inc}/game-text-input/{name}")
|
||||
};
|
||||
|
||||
for f in ["GameActivity.cpp", "GameActivityEvents.cpp"] {
|
||||
println!("cargo:rerun-if-changed={}", activity_path("src", f));
|
||||
}
|
||||
|
||||
for f in [
|
||||
"GameActivity.h",
|
||||
"GameActivityEvents.h",
|
||||
"GameActivityLog.h",
|
||||
"GameActivityEvents_internal.h",
|
||||
] {
|
||||
println!("cargo:rerun-if-changed={}", activity_path("include", f));
|
||||
}
|
||||
|
||||
cc::Build::new()
|
||||
.cpp(true)
|
||||
.include("game-activity-csrc")
|
||||
.file("game-activity-csrc/game-activity/GameActivity.cpp")
|
||||
.include("android-games-sdk/src/common")
|
||||
.file("android-games-sdk/src/common/system_utils.cpp")
|
||||
.extra_warnings(false)
|
||||
.cpp_link_stdlib("c++_static")
|
||||
.compile("libgame_common.a");
|
||||
|
||||
println!("cargo:rerun-if-changed=android-games-sdk/src/common/system_utils.cpp");
|
||||
println!("cargo:rerun-if-changed=android-games-sdk/src/common/system_utils.h");
|
||||
|
||||
cc::Build::new()
|
||||
.cpp(true)
|
||||
.include("android-games-sdk/src/common")
|
||||
.include("android-games-sdk/include")
|
||||
.include("android-games-sdk/game-activity/prefab-src/modules/game-activity/include")
|
||||
.include("android-games-sdk/game-text-input/prefab-src/modules/game-text-input/include")
|
||||
.file(activity_path("src", "GameActivity.cpp"))
|
||||
.file(activity_path("src", "GameActivityEvents.cpp"))
|
||||
.extra_warnings(false)
|
||||
.cpp_link_stdlib("c++_static")
|
||||
.compile("libgame_activity.a");
|
||||
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
textinput_path("include", "gametextinput.h")
|
||||
);
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
textinput_path("src", "gametextinput.cpp")
|
||||
);
|
||||
|
||||
cc::Build::new()
|
||||
.cpp(true)
|
||||
.include("game-activity-csrc")
|
||||
.file("game-activity-csrc/game-text-input/gametextinput.cpp")
|
||||
.include("android-games-sdk/src/common")
|
||||
.include("android-games-sdk/include")
|
||||
.include("android-games-sdk/game-text-input/prefab-src/modules/game-text-input/include")
|
||||
.file(textinput_path("src", "gametextinput.cpp"))
|
||||
.cpp_link_stdlib("c++_static")
|
||||
.compile("libgame_text_input.a");
|
||||
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
activity_path("src", "native_app_glue/android_native_app_glue.c")
|
||||
);
|
||||
println!(
|
||||
"cargo:rerun-if-changed={}",
|
||||
activity_path("include", "native_app_glue/android_native_app_glue.h")
|
||||
);
|
||||
|
||||
cc::Build::new()
|
||||
.include("game-activity-csrc")
|
||||
.include("game-activity-csrc/game-activity/native_app_glue")
|
||||
.file("game-activity-csrc/game-activity/native_app_glue/android_native_app_glue.c")
|
||||
.include("android-games-sdk/src/common")
|
||||
.include("android-games-sdk/include")
|
||||
.include("android-games-sdk/game-activity/prefab-src/modules/game-activity/include")
|
||||
.include("android-games-sdk/game-text-input/prefab-src/modules/game-text-input/include")
|
||||
.include(activity_path("include", ""))
|
||||
.file(activity_path(
|
||||
"src",
|
||||
"native_app_glue/android_native_app_glue.c",
|
||||
))
|
||||
.extra_warnings(false)
|
||||
.cpp_link_stdlib("c++_static")
|
||||
.compile("libnative_app_glue.a");
|
||||
@@ -28,6 +92,21 @@ fn build_glue_for_game_activity() {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
#[cfg(feature = "game-activity")]
|
||||
build_glue_for_game_activity();
|
||||
// Enable Cargo's change-detection to avoid re-running build script if
|
||||
// irrelvant parts changed. Using build.rs here is just a dummy used to
|
||||
// disable the default "rerun on every change" behaviour Cargo has.
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
|
||||
if cfg!(feature = "game-activity") {
|
||||
build_glue_for_game_activity();
|
||||
}
|
||||
|
||||
// Whether this is used directly in or as a dependency on docs.rs.
|
||||
//
|
||||
// `cfg(docsrs)` cannot be used, since it's only set for the crate being
|
||||
// built, and not for any dependent crates.
|
||||
println!("cargo:rustc-check-cfg=cfg(used_on_docsrs)");
|
||||
if std::env::var("DOCS_RS").is_ok() {
|
||||
println!("cargo:rustc-cfg=used_on_docsrs");
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,820 +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;
|
||||
int32_t toolType;
|
||||
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
|
||||
-639
@@ -1,639 +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);
|
||||
}
|
||||
|
||||
bool android_app_input_available_wake_up(struct android_app* app) {
|
||||
pthread_mutex_lock(&app->mutex);
|
||||
// TODO: use atomic ops for this
|
||||
bool available = app->inputAvailableWakeUp;
|
||||
app->inputAvailableWakeUp = false;
|
||||
pthread_mutex_unlock(&app->mutex);
|
||||
return available;
|
||||
}
|
||||
|
||||
// NB: should be called with the android_app->mutex held already
|
||||
static void notifyInput(struct android_app* android_app) {
|
||||
// Don't spam the mainloop with wake ups if we've already sent one
|
||||
if (android_app->inputSwapPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (android_app->looper != NULL) {
|
||||
LOGV("Input Notify: %p", android_app);
|
||||
// for the app thread to know why it received the wake() up
|
||||
android_app->inputAvailableWakeUp = true;
|
||||
android_app->inputSwapPending = true;
|
||||
ALooper_wake(android_app->looper);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
notifyInput(android_app);
|
||||
} 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;
|
||||
}
|
||||
|
||||
android_app->inputSwapPending = false;
|
||||
android_app->inputAvailableWakeUp = false;
|
||||
|
||||
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;
|
||||
|
||||
notifyInput(android_app);
|
||||
} 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);
|
||||
}
|
||||
-541
@@ -1,541 +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;
|
||||
|
||||
// When new input is received we set both of these flags and use the looper to
|
||||
// wake up the application mainloop.
|
||||
//
|
||||
// To avoid spamming the mainloop with wake ups from lots of input though we
|
||||
// don't sent a wake up if the inputSwapPending flag is already set. (i.e.
|
||||
// we already expect input to be processed in a finite amount of time due to
|
||||
// our previous wake up)
|
||||
//
|
||||
// When a wake up is received then we will check this flag (clearing it
|
||||
// at the same time). If it was set then an InputAvailable event is sent to
|
||||
// the application - which should lead to all input being processed within
|
||||
// a finite amount of time.
|
||||
//
|
||||
// The next time android_app_swap_input_buffers is called, both flags will be
|
||||
// cleared.
|
||||
//
|
||||
// NB: both of these should only be read with the app mutex held
|
||||
bool inputAvailableWakeUp;
|
||||
bool inputSwapPending;
|
||||
|
||||
/** @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);
|
||||
|
||||
/**
|
||||
* Determines if a looper wake up was due to new input becoming available
|
||||
*/
|
||||
bool android_app_input_available_wake_up(struct android_app* app);
|
||||
|
||||
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_, ¤tState_);
|
||||
}
|
||||
}
|
||||
|
||||
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_, ¤tInsets_);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
/** @} */
|
||||
Regular → Executable
+7
-1
@@ -1,5 +1,8 @@
|
||||
#!/bin/sh
|
||||
|
||||
# First install bindgen-cli via `cargo install bindgen-cli`
|
||||
|
||||
SDK_DIR="${ANDROID_GAMES_SDK:-android-games-sdk}"
|
||||
if test -z "${ANDROID_NDK_ROOT}"; then
|
||||
export ANDROID_NDK_ROOT=${ANDROID_NDK_HOME}
|
||||
fi
|
||||
@@ -12,6 +15,7 @@ while read ARCH && read TARGET ; do
|
||||
|
||||
# --module-raw-line 'use '
|
||||
bindgen game-activity-ffi.h -o src/game_activity/ffi_$ARCH.rs \
|
||||
--rust-target '1.85.0' \
|
||||
--blocklist-item 'JNI\w+' \
|
||||
--blocklist-item 'C?_?JNIEnv' \
|
||||
--blocklist-item '_?JavaVM' \
|
||||
@@ -34,7 +38,9 @@ while read ARCH && read TARGET ; do
|
||||
--blocklist-function 'GameActivity_onCreate_C' \
|
||||
--newtype-enum '\w+_(result|status)_t' \
|
||||
-- \
|
||||
-Igame-activity-csrc \
|
||||
"-I$SDK_DIR/game-activity/prefab-src/modules/game-activity/include" \
|
||||
"-I$SDK_DIR/game-text-input/prefab-src/modules/game-text-input/include" \
|
||||
"-I$SDK_DIR/include" \
|
||||
--sysroot="$SYSROOT" --target=$TARGET
|
||||
|
||||
done << EOF
|
||||
|
||||
@@ -6,13 +6,14 @@ use ndk::configuration::{
|
||||
ScreenSize, Touchscreen, UiModeNight, UiModeType,
|
||||
};
|
||||
|
||||
/// A (cheaply clonable) reference to this application's [`ndk::configuration::Configuration`]
|
||||
/// A runtime-replacable reference to [`ndk::configuration::Configuration`].
|
||||
///
|
||||
/// This provides a thread-safe way to access the latest configuration state for
|
||||
/// an application without deeply copying the large [`ndk::configuration::Configuration`] struct.
|
||||
/// # Warning
|
||||
///
|
||||
/// If the application is notified of configuration changes then those changes
|
||||
/// will become visible via pre-existing configuration references.
|
||||
/// The value held by this reference **will change** with every [`super::MainEvent::ConfigChanged`]
|
||||
/// event that is raised. You should **not** [`Clone`] this type to compare it against a
|
||||
/// "new" [`super::AndroidApp::config()`] when that event is raised, since both point to the same
|
||||
/// internal [`ndk::configuration::Configuration`] and will be identical.
|
||||
#[derive(Clone)]
|
||||
pub struct ConfigurationRef {
|
||||
config: Arc<RwLock<Configuration>>,
|
||||
@@ -28,8 +29,6 @@ impl PartialEq for ConfigurationRef {
|
||||
}
|
||||
}
|
||||
impl Eq for ConfigurationRef {}
|
||||
unsafe impl Send for ConfigurationRef {}
|
||||
unsafe impl Sync for ConfigurationRef {}
|
||||
|
||||
impl fmt::Debug for ConfigurationRef {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum AppError {
|
||||
#[error("Operation only supported from the android_main() thread: {0}")]
|
||||
NonMainThread(String),
|
||||
|
||||
#[error("Java VM or JNI error, including Java exceptions")]
|
||||
JavaError(String),
|
||||
|
||||
#[error("Input unavailable")]
|
||||
InputUnavailable,
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, AppError>;
|
||||
|
||||
// XXX: we don't want to expose jni-rs in the public API
|
||||
// so we have an internal error type that we can generally
|
||||
// use in the backends and then we can strip the error
|
||||
// in the frontend of the API.
|
||||
//
|
||||
// This way we avoid exposing a public trait implementation for
|
||||
// `From<jni::errors::Error>`
|
||||
#[derive(Error, Debug)]
|
||||
pub(crate) enum InternalAppError {
|
||||
#[error("A JNI error")]
|
||||
JniError(jni::errors::JniError),
|
||||
#[error("A Java Exception was thrown via a JNI method call")]
|
||||
JniException(String),
|
||||
// For internal errors that don't lead to a Java exception but are
|
||||
// still JNI related.
|
||||
#[error("A bad argument was passed to a JNI method: {0}")]
|
||||
JniBadArgument(String),
|
||||
#[error("A Java VM error")]
|
||||
JvmError(jni::errors::Error),
|
||||
#[error("Input unavailable")]
|
||||
InputUnavailable,
|
||||
}
|
||||
|
||||
pub(crate) type InternalResult<T> = std::result::Result<T, InternalAppError>;
|
||||
|
||||
impl From<jni::errors::Error> for InternalAppError {
|
||||
fn from(value: jni::errors::Error) -> Self {
|
||||
InternalAppError::JvmError(value)
|
||||
}
|
||||
}
|
||||
impl From<jni::errors::JniError> for InternalAppError {
|
||||
fn from(value: jni::errors::JniError) -> Self {
|
||||
InternalAppError::JniError(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InternalAppError> for AppError {
|
||||
fn from(value: InternalAppError) -> Self {
|
||||
match value {
|
||||
InternalAppError::JniError(err) => AppError::JavaError(err.to_string()),
|
||||
InternalAppError::JniException(msg) => AppError::JavaError(msg),
|
||||
InternalAppError::JniBadArgument(msg) => AppError::JavaError(msg),
|
||||
InternalAppError::JvmError(err) => AppError::JavaError(err.to_string()),
|
||||
InternalAppError::InputUnavailable => AppError::InputUnavailable,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,21 +12,18 @@
|
||||
#![allow(deref_nullptr)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
use jni_sys::*;
|
||||
use libc::{pthread_cond_t, pthread_mutex_t, pthread_t, size_t};
|
||||
use jni::sys::*;
|
||||
use libc::{pthread_cond_t, pthread_mutex_t, pthread_t};
|
||||
use ndk_sys::{AAssetManager, AConfiguration, ALooper, ALooper_callbackFunc, ANativeWindow, ARect};
|
||||
|
||||
#[cfg(all(
|
||||
any(target_os = "android", feature = "test"),
|
||||
any(target_arch = "arm", target_arch = "armv7")
|
||||
))]
|
||||
#[cfg(all(any(target_os = "android"), target_arch = "arm"))]
|
||||
include!("ffi_arm.rs");
|
||||
|
||||
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "aarch64"))]
|
||||
#[cfg(all(any(target_os = "android"), target_arch = "aarch64"))]
|
||||
include!("ffi_aarch64.rs");
|
||||
|
||||
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "x86"))]
|
||||
#[cfg(all(any(target_os = "android"), target_arch = "x86"))]
|
||||
include!("ffi_i686.rs");
|
||||
|
||||
#[cfg(all(any(target_os = "android", feature = "test"), target_arch = "x86_64"))]
|
||||
#[cfg(all(any(target_os = "android"), 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
@@ -1,21 +1,19 @@
|
||||
#![cfg(feature = "game-activity")]
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
use std::os::unix::prelude::*;
|
||||
use std::panic::catch_unwind;
|
||||
use std::ptr;
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::sync::Weak;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::Duration;
|
||||
use std::{ptr, thread};
|
||||
|
||||
use jni::objects::JObject;
|
||||
use jni::refs::Global;
|
||||
use libc::c_void;
|
||||
use log::{error, trace, Level};
|
||||
use log::{error, trace};
|
||||
|
||||
use jni_sys::*;
|
||||
use jni::sys::*;
|
||||
|
||||
use ndk_sys::ALooper_wake;
|
||||
use ndk_sys::{ALooper, ALooper_pollAll};
|
||||
@@ -24,15 +22,21 @@ use ndk::asset::AssetManager;
|
||||
use ndk::configuration::Configuration;
|
||||
use ndk::native_window::NativeWindow;
|
||||
|
||||
use crate::util::{abort_on_panic, android_log, log_panic};
|
||||
use crate::error::InternalResult;
|
||||
use crate::input::{device_key_character_map, Axis, KeyCharacterMap, TextInputAction};
|
||||
use crate::util::{
|
||||
abort_on_panic, forward_stdio_to_logcat, init_android_main_thread, log_panic,
|
||||
try_get_path_from_ptr,
|
||||
};
|
||||
use crate::{
|
||||
util, AndroidApp, ConfigurationRef, InputStatus, MainEvent, PollEvent, Rect, WindowManagerFlags,
|
||||
AndroidApp, ConfigurationRef, InputStatus, MainEvent, PollEvent, Rect, WindowManagerFlags,
|
||||
};
|
||||
|
||||
mod ffi;
|
||||
|
||||
pub mod input;
|
||||
use input::{Axis, InputEvent, KeyEvent, MotionEvent};
|
||||
use crate::input::{TextInputState, TextSpan};
|
||||
use input::{InputEvent, KeyEvent, MotionEvent};
|
||||
|
||||
// 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
|
||||
@@ -82,14 +86,14 @@ impl<'a> StateSaver<'a> {
|
||||
pub struct StateLoader<'a> {
|
||||
app: &'a AndroidAppInner,
|
||||
}
|
||||
impl<'a> StateLoader<'a> {
|
||||
impl StateLoader<'_> {
|
||||
pub fn load(&self) -> Option<Vec<u8>> {
|
||||
unsafe {
|
||||
let app_ptr = self.app.native_app.as_ptr();
|
||||
if !(*app_ptr).savedState.is_null() && (*app_ptr).savedStateSize > 0 {
|
||||
let buf: &mut [u8] = std::slice::from_raw_parts_mut(
|
||||
(*app_ptr).savedState.cast(),
|
||||
(*app_ptr).savedStateSize as usize,
|
||||
(*app_ptr).savedStateSize,
|
||||
);
|
||||
let state = buf.to_vec();
|
||||
Some(state)
|
||||
@@ -119,23 +123,35 @@ impl AndroidAppWaker {
|
||||
}
|
||||
|
||||
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()
|
||||
let config = Configuration::clone_from_ptr(NonNull::new_unchecked((*ptr.as_ptr()).config));
|
||||
pub(crate) unsafe fn from_ptr(ptr: NonNull<ffi::android_app>, jvm: jni::JavaVM) -> Self {
|
||||
// We attach to the thread before creating the AndroidApp
|
||||
jvm.with_local_frame(10, |env| -> jni::errors::Result<_> {
|
||||
if let Err(err) = crate::input::jni_init(env) {
|
||||
panic!("Failed to init JNI bindings: {err:?}");
|
||||
};
|
||||
|
||||
Self {
|
||||
inner: Arc::new(RwLock::new(AndroidAppInner {
|
||||
native_app: NativeAppGlue { ptr },
|
||||
config: ConfigurationRef::new(config),
|
||||
native_window: Default::default(),
|
||||
})),
|
||||
}
|
||||
// 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()
|
||||
let config =
|
||||
Configuration::clone_from_ptr(NonNull::new_unchecked((*ptr.as_ptr()).config));
|
||||
|
||||
Ok(Self {
|
||||
inner: Arc::new(RwLock::new(AndroidAppInner {
|
||||
jvm: jvm.clone(),
|
||||
native_app: NativeAppGlue { ptr },
|
||||
config: ConfigurationRef::new(config),
|
||||
native_window: Default::default(),
|
||||
key_maps: Mutex::new(HashMap::new()),
|
||||
input_receiver: Mutex::new(None),
|
||||
})),
|
||||
})
|
||||
})
|
||||
.expect("Failed to create AndroidApp instance")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, Clone)]
|
||||
struct NativeAppGlue {
|
||||
ptr: NonNull<ffi::android_app>,
|
||||
}
|
||||
@@ -149,11 +165,126 @@ impl Deref for NativeAppGlue {
|
||||
unsafe impl Send for NativeAppGlue {}
|
||||
unsafe impl Sync for NativeAppGlue {}
|
||||
|
||||
impl NativeAppGlue {
|
||||
// TODO: move into a trait
|
||||
pub fn text_input_state(&self) -> TextInputState {
|
||||
unsafe {
|
||||
let activity = (*self.as_ptr()).activity;
|
||||
let mut out_state = TextInputState {
|
||||
text: String::new(),
|
||||
selection: TextSpan { start: 0, end: 0 },
|
||||
compose_region: None,
|
||||
};
|
||||
let out_ptr = &mut out_state as *mut TextInputState;
|
||||
|
||||
// NEON WARNING:
|
||||
//
|
||||
// It's not clearly documented but the GameActivity API over the
|
||||
// GameTextInput library directly exposes _modified_ UTF8 text
|
||||
// from Java so we need to be careful to convert text to and
|
||||
// from UTF8
|
||||
//
|
||||
// GameTextInput also uses a pre-allocated, fixed-sized buffer for
|
||||
// the current text state and has shared `currentState_` that
|
||||
// appears to have no lock to guard access from multiple threads.
|
||||
//
|
||||
// There's also no locking at the GameActivity level, so I'm fairly
|
||||
// certain that `GameActivity_getTextInputState` isn't thread
|
||||
// safe: https://issuetracker.google.com/issues/294112477
|
||||
//
|
||||
// Overall this is all quite gnarly - and probably a good reminder
|
||||
// of why we want to use Rust instead of C/C++.
|
||||
ffi::GameActivity_getTextInputState(
|
||||
activity,
|
||||
Some(AndroidAppInner::map_input_state_to_text_event_callback),
|
||||
out_ptr.cast(),
|
||||
);
|
||||
|
||||
out_state
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_text_input_state(&self) -> TextInputState {
|
||||
unsafe {
|
||||
let app_ptr = self.as_ptr();
|
||||
(*app_ptr).textInputState = 0;
|
||||
}
|
||||
self.text_input_state()
|
||||
}
|
||||
|
||||
// TODO: move into a trait
|
||||
pub fn set_text_input_state(&self, state: TextInputState) {
|
||||
unsafe {
|
||||
let activity = (*self.as_ptr()).activity;
|
||||
let modified_utf8 = cesu8::to_java_cesu8(&state.text);
|
||||
let text_length = modified_utf8.len() as i32;
|
||||
let modified_utf8_bytes = modified_utf8.as_ptr();
|
||||
let ffi_state = ffi::GameTextInputState {
|
||||
text_UTF8: modified_utf8_bytes.cast(), // NB: may be signed or unsigned depending on target
|
||||
text_length,
|
||||
selection: ffi::GameTextInputSpan {
|
||||
start: state.selection.start as i32,
|
||||
end: state.selection.end as i32,
|
||||
},
|
||||
composingRegion: match state.compose_region {
|
||||
Some(span) => {
|
||||
// The GameText subclass of InputConnection only has a special case for removing the
|
||||
// compose region if `start == -1` but the docs for `setComposingRegion` imply that
|
||||
// the region should effectively be removed if any empty region is given (unlike for the
|
||||
// selection region, it's not meaningful to maintain an empty compose region)
|
||||
//
|
||||
// We aim for more consistent behaviour by normalizing any empty region into `(-1, -1)`
|
||||
// to remove the compose region.
|
||||
//
|
||||
// NB `setComposingRegion` itself is documented to clamp start/end to the text bounds
|
||||
// so apart from this special-case handling in GameText's implementation of
|
||||
// `setComposingRegion` then there's nothing special about `(-1, -1)` - it's just an empty
|
||||
// region that should get clamped to `(0, 0)` and then get removed.
|
||||
if span.start == span.end {
|
||||
ffi::GameTextInputSpan { start: -1, end: -1 }
|
||||
} else {
|
||||
ffi::GameTextInputSpan {
|
||||
start: span.start as i32,
|
||||
end: span.end as i32,
|
||||
}
|
||||
}
|
||||
}
|
||||
None => ffi::GameTextInputSpan { start: -1, end: -1 },
|
||||
},
|
||||
};
|
||||
ffi::GameActivity_setTextInputState(activity, &ffi_state as *const _);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_pending_editor_action(&self) -> Option<i32> {
|
||||
unsafe {
|
||||
let app_ptr = self.as_ptr();
|
||||
if (*app_ptr).pendingEditorAction {
|
||||
(*app_ptr).pendingEditorAction = false;
|
||||
Some((*app_ptr).editorAction)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AndroidAppInner {
|
||||
pub(crate) jvm: jni::JavaVM,
|
||||
native_app: NativeAppGlue,
|
||||
config: ConfigurationRef,
|
||||
native_window: RwLock<Option<NativeWindow>>,
|
||||
|
||||
/// A table of `KeyCharacterMap`s per `InputDevice` ID
|
||||
/// these are used to be able to map key presses to unicode
|
||||
/// characters
|
||||
key_maps: Mutex<HashMap<i32, KeyCharacterMap>>,
|
||||
|
||||
/// While an app is reading input events it holds an
|
||||
/// InputReceiver reference which we track to ensure
|
||||
/// we don't hand out more than one receiver at a time
|
||||
input_receiver: Mutex<Option<Weak<InputReceiver>>>,
|
||||
}
|
||||
|
||||
impl AndroidAppInner {
|
||||
@@ -179,6 +310,11 @@ impl AndroidAppInner {
|
||||
|
||||
unsafe {
|
||||
let native_app = &self.native_app;
|
||||
assert_eq!(
|
||||
ndk_sys::ALooper_forThread(),
|
||||
(*native_app.as_ptr()).looper,
|
||||
"Application tried to poll events from non-main thread"
|
||||
);
|
||||
|
||||
let mut fd: i32 = 0;
|
||||
let mut events: i32 = 0;
|
||||
@@ -222,56 +358,71 @@ impl AndroidAppInner {
|
||||
panic!("ALooper_pollAll returned POLL_ERROR");
|
||||
}
|
||||
id if id >= 0 => {
|
||||
match id as u32 {
|
||||
match id as ffi::NativeAppGlueLooperId {
|
||||
ffi::NativeAppGlueLooperId_LOOPER_ID_MAIN => {
|
||||
trace!("ALooper_pollAll returned ID_MAIN");
|
||||
let source: *mut ffi::android_poll_source = source.cast();
|
||||
if !source.is_null() {
|
||||
let cmd_i = ffi::android_app_read_cmd(native_app.as_ptr());
|
||||
|
||||
let cmd = match cmd_i as u32 {
|
||||
let cmd = match cmd_i as ffi::NativeAppGlueAppCmd {
|
||||
//NativeAppGlueAppCmd_UNUSED_APP_CMD_INPUT_CHANGED => AndroidAppMainEvent::InputChanged,
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_INIT_WINDOW => {
|
||||
MainEvent::InitWindow {}
|
||||
Some(MainEvent::InitWindow {})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_TERM_WINDOW => {
|
||||
MainEvent::TerminateWindow {}
|
||||
Some(MainEvent::TerminateWindow {})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_WINDOW_RESIZED => {
|
||||
MainEvent::WindowResized {}
|
||||
Some(MainEvent::WindowResized {})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_WINDOW_REDRAW_NEEDED => {
|
||||
MainEvent::RedrawNeeded {}
|
||||
Some(MainEvent::RedrawNeeded {})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_CONTENT_RECT_CHANGED => {
|
||||
MainEvent::ContentRectChanged {}
|
||||
Some(MainEvent::ContentRectChanged {})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_GAINED_FOCUS => {
|
||||
MainEvent::GainedFocus
|
||||
Some(MainEvent::GainedFocus)
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_LOST_FOCUS => {
|
||||
MainEvent::LostFocus
|
||||
Some(MainEvent::LostFocus)
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_CONFIG_CHANGED => {
|
||||
MainEvent::ConfigChanged {}
|
||||
Some(MainEvent::ConfigChanged {})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_LOW_MEMORY => {
|
||||
MainEvent::LowMemory
|
||||
Some(MainEvent::LowMemory)
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_START => {
|
||||
Some(MainEvent::Start)
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_RESUME => {
|
||||
Some(MainEvent::Resume {
|
||||
loader: StateLoader { app: self },
|
||||
})
|
||||
}
|
||||
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 {
|
||||
Some(MainEvent::SaveState {
|
||||
saver: StateSaver { app: self },
|
||||
}
|
||||
})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_PAUSE => {
|
||||
Some(MainEvent::Pause)
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_STOP => Some(MainEvent::Stop),
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_DESTROY => {
|
||||
Some(MainEvent::Destroy)
|
||||
}
|
||||
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 {}
|
||||
Some(MainEvent::InsetsChanged {})
|
||||
}
|
||||
ffi::NativeAppGlueAppCmd_APP_CMD_SOFTWARE_KB_VIS_CHANGED => {
|
||||
// NOOP: we ignore these events because they are driven by a
|
||||
// potentially-unreliable heuristic (based on watching for
|
||||
// inset changes) and we don't currently have a public event
|
||||
// for exposing this state.
|
||||
None
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
@@ -280,30 +431,35 @@ impl AndroidAppInner {
|
||||
|
||||
trace!("Calling android_app_pre_exec_cmd({cmd_i})");
|
||||
ffi::android_app_pre_exec_cmd(native_app.as_ptr(), cmd_i);
|
||||
match cmd {
|
||||
MainEvent::ConfigChanged { .. } => {
|
||||
self.config.replace(Configuration::clone_from_ptr(
|
||||
NonNull::new_unchecked((*native_app.as_ptr()).config),
|
||||
));
|
||||
}
|
||||
MainEvent::InitWindow { .. } => {
|
||||
let win_ptr = (*native_app.as_ptr()).window;
|
||||
// It's important that we use ::clone_from_ptr() here
|
||||
// because NativeWindow has a Drop implementation that
|
||||
// will unconditionally _release() the native window
|
||||
*self.native_window.write().unwrap() =
|
||||
Some(NativeWindow::clone_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));
|
||||
if let Some(cmd) = cmd {
|
||||
match cmd {
|
||||
MainEvent::ConfigChanged { .. } => {
|
||||
self.config.replace(Configuration::clone_from_ptr(
|
||||
NonNull::new_unchecked(
|
||||
(*native_app.as_ptr()).config,
|
||||
),
|
||||
));
|
||||
}
|
||||
MainEvent::InitWindow { .. } => {
|
||||
let win_ptr = (*native_app.as_ptr()).window;
|
||||
// It's important that we use ::clone_from_ptr() here
|
||||
// because NativeWindow has a Drop implementation that
|
||||
// will unconditionally _release() the native window
|
||||
*self.native_window.write().unwrap() =
|
||||
Some(NativeWindow::clone_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(native_app.as_ptr(), cmd_i);
|
||||
@@ -360,11 +516,76 @@ impl AndroidAppInner {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C" fn map_input_state_to_text_event_callback(
|
||||
context: *mut c_void,
|
||||
state: *const ffi::GameTextInputState,
|
||||
) {
|
||||
// Java uses a modified UTF-8 format, which is a modified cesu8 format
|
||||
let out_ptr: *mut TextInputState = context.cast();
|
||||
let text_modified_utf8: *const u8 = (*state).text_UTF8.cast();
|
||||
let text_modified_utf8 =
|
||||
std::slice::from_raw_parts(text_modified_utf8, (*state).text_length as usize);
|
||||
match cesu8::from_java_cesu8(text_modified_utf8) {
|
||||
Ok(str) => {
|
||||
let len = str.len();
|
||||
(*out_ptr).text = String::from(str);
|
||||
|
||||
let selection_start = (*state).selection.start.clamp(0, len as i32 + 1);
|
||||
let selection_end = (*state).selection.end.clamp(0, len as i32 + 1);
|
||||
(*out_ptr).selection = TextSpan {
|
||||
start: selection_start as usize,
|
||||
end: selection_end as usize,
|
||||
};
|
||||
if (*state).composingRegion.start < 0 || (*state).composingRegion.end < 0 {
|
||||
(*out_ptr).compose_region = None;
|
||||
} else {
|
||||
(*out_ptr).compose_region = Some(TextSpan {
|
||||
start: (*state).composingRegion.start as usize,
|
||||
end: (*state).composingRegion.end as usize,
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Invalid UTF8 text in TextEvent: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move into a trait
|
||||
pub fn text_input_state(&self) -> TextInputState {
|
||||
self.native_app.text_input_state()
|
||||
}
|
||||
|
||||
// TODO: move into a trait
|
||||
pub fn set_text_input_state(&self, state: TextInputState) {
|
||||
self.native_app.set_text_input_state(state);
|
||||
}
|
||||
|
||||
pub(crate) fn device_key_character_map(
|
||||
&self,
|
||||
device_id: i32,
|
||||
) -> InternalResult<KeyCharacterMap> {
|
||||
let mut guard = self.key_maps.lock().unwrap();
|
||||
|
||||
let key_map = match guard.entry(device_id) {
|
||||
std::collections::hash_map::Entry::Occupied(occupied) => occupied.get().clone(),
|
||||
std::collections::hash_map::Entry::Vacant(vacant) => {
|
||||
let character_map = device_key_character_map(self.jvm.clone(), device_id)?;
|
||||
vacant.insert(character_map.clone());
|
||||
character_map
|
||||
}
|
||||
};
|
||||
|
||||
Ok(key_map)
|
||||
}
|
||||
|
||||
pub fn enable_motion_axis(&mut self, axis: Axis) {
|
||||
let axis: u32 = axis.into();
|
||||
unsafe { ffi::GameActivityPointerAxes_enableAxis(axis as i32) }
|
||||
}
|
||||
|
||||
pub fn disable_motion_axis(&mut self, axis: Axis) {
|
||||
let axis: u32 = axis.into();
|
||||
unsafe { ffi::GameActivityPointerAxes_disableAxis(axis as i32) }
|
||||
}
|
||||
|
||||
@@ -403,71 +624,75 @@ impl AndroidAppInner {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn input_events<F>(&self, mut callback: F)
|
||||
where
|
||||
F: FnMut(&InputEvent) -> InputStatus,
|
||||
{
|
||||
let buf = unsafe {
|
||||
let app_ptr = self.native_app.as_ptr();
|
||||
let input_buffer = ffi::android_app_swap_input_buffers(app_ptr);
|
||||
if input_buffer.is_null() {
|
||||
return;
|
||||
}
|
||||
InputBuffer::from_ptr(NonNull::new_unchecked(input_buffer))
|
||||
};
|
||||
pub(crate) fn input_events_receiver(&self) -> InternalResult<Arc<InputReceiver>> {
|
||||
let mut guard = self.input_receiver.lock().unwrap();
|
||||
|
||||
let mut keys_iter = KeyEventsLendingIterator::new(&buf);
|
||||
while let Some(key_event) = keys_iter.next() {
|
||||
callback(&InputEvent::KeyEvent(key_event));
|
||||
}
|
||||
let mut motion_iter = MotionEventsLendingIterator::new(&buf);
|
||||
while let Some(motion_event) = motion_iter.next() {
|
||||
callback(&InputEvent::MotionEvent(motion_event));
|
||||
// Make sure we don't hand out more than one receiver at a time because
|
||||
// turning the receiver into an iterator will perform a swap_buffers
|
||||
// for the buffered input events which shouldn't happen while we're in
|
||||
// the middle of iterating events
|
||||
if let Some(receiver) = &*guard {
|
||||
if receiver.strong_count() > 0 {
|
||||
return Err(crate::error::InternalAppError::InputUnavailable);
|
||||
}
|
||||
}
|
||||
*guard = None;
|
||||
|
||||
let receiver = Arc::new(InputReceiver {
|
||||
native_app: self.native_app.clone(),
|
||||
});
|
||||
|
||||
*guard = Some(Arc::downgrade(&receiver));
|
||||
Ok(receiver)
|
||||
}
|
||||
|
||||
pub fn internal_data_path(&self) -> Option<std::path::PathBuf> {
|
||||
unsafe {
|
||||
let app_ptr = self.native_app.as_ptr();
|
||||
util::try_get_path_from_ptr((*(*app_ptr).activity).internalDataPath)
|
||||
try_get_path_from_ptr((*(*app_ptr).activity).internalDataPath)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn external_data_path(&self) -> Option<std::path::PathBuf> {
|
||||
unsafe {
|
||||
let app_ptr = self.native_app.as_ptr();
|
||||
util::try_get_path_from_ptr((*(*app_ptr).activity).externalDataPath)
|
||||
try_get_path_from_ptr((*(*app_ptr).activity).externalDataPath)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn obb_path(&self) -> Option<std::path::PathBuf> {
|
||||
unsafe {
|
||||
let app_ptr = self.native_app.as_ptr();
|
||||
util::try_get_path_from_ptr((*(*app_ptr).activity).obbPath)
|
||||
try_get_path_from_ptr((*(*app_ptr).activity).obbPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MotionEventsLendingIterator<'a> {
|
||||
struct MotionEventsLendingIterator {
|
||||
pos: usize,
|
||||
count: usize,
|
||||
buffer: &'a InputBuffer<'a>,
|
||||
}
|
||||
|
||||
// A kind of lending iterator but since our MSRV is 1.60 we can't handle this
|
||||
// via a generic trait. The iteration of motion events is entirely private
|
||||
// though so this is ok for now.
|
||||
impl<'a> MotionEventsLendingIterator<'a> {
|
||||
fn new(buffer: &'a InputBuffer<'a>) -> Self {
|
||||
impl MotionEventsLendingIterator {
|
||||
fn new(buffer: &InputBuffer) -> Self {
|
||||
Self {
|
||||
pos: 0,
|
||||
count: buffer.motion_events_count(),
|
||||
buffer,
|
||||
}
|
||||
}
|
||||
fn next(&mut self) -> Option<MotionEvent<'a>> {
|
||||
fn next<'buf>(&mut self, buffer: &'buf InputBuffer) -> Option<MotionEvent<'buf>> {
|
||||
if self.pos < self.count {
|
||||
let ga_event = unsafe { &(*self.buffer.ptr.as_ptr()).motionEvents[self.pos] };
|
||||
// Safety:
|
||||
// - This iterator currently has exclusive access to the front buffer of events
|
||||
// - We know the buffer is non-null
|
||||
// - `pos` is less than the number of events stored in the buffer
|
||||
let ga_event = unsafe {
|
||||
(*buffer.ptr.as_ptr())
|
||||
.motionEvents
|
||||
.add(self.pos)
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
};
|
||||
let event = MotionEvent::new(ga_event);
|
||||
self.pos += 1;
|
||||
Some(event)
|
||||
@@ -477,26 +702,31 @@ impl<'a> MotionEventsLendingIterator<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
struct KeyEventsLendingIterator<'a> {
|
||||
struct KeyEventsLendingIterator {
|
||||
pos: usize,
|
||||
count: usize,
|
||||
buffer: &'a InputBuffer<'a>,
|
||||
}
|
||||
|
||||
// A kind of lending iterator but since our MSRV is 1.60 we can't handle this
|
||||
// via a generic trait. The iteration of key events is entirely private
|
||||
// though so this is ok for now.
|
||||
impl<'a> KeyEventsLendingIterator<'a> {
|
||||
fn new(buffer: &'a InputBuffer<'a>) -> Self {
|
||||
impl KeyEventsLendingIterator {
|
||||
fn new(buffer: &InputBuffer) -> Self {
|
||||
Self {
|
||||
pos: 0,
|
||||
count: buffer.key_events_count(),
|
||||
buffer,
|
||||
}
|
||||
}
|
||||
fn next(&mut self) -> Option<KeyEvent<'a>> {
|
||||
fn next<'buf>(&mut self, buffer: &'buf InputBuffer) -> Option<KeyEvent<'buf>> {
|
||||
if self.pos < self.count {
|
||||
let ga_event = unsafe { &(*self.buffer.ptr.as_ptr()).keyEvents[self.pos] };
|
||||
// Safety:
|
||||
// - This iterator currently has exclusive access to the front buffer of events
|
||||
// - We know the buffer is non-null
|
||||
// - `pos` is less than the number of events stored in the buffer
|
||||
let ga_event = unsafe {
|
||||
(*buffer.ptr.as_ptr())
|
||||
.keyEvents
|
||||
.add(self.pos)
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
};
|
||||
let event = KeyEvent::new(ga_event);
|
||||
self.pos += 1;
|
||||
Some(event)
|
||||
@@ -515,7 +745,7 @@ impl<'a> InputBuffer<'a> {
|
||||
pub(crate) fn from_ptr(ptr: NonNull<ffi::android_input_buffer>) -> InputBuffer<'a> {
|
||||
Self {
|
||||
ptr,
|
||||
_lifetime: PhantomData::default(),
|
||||
_lifetime: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -528,7 +758,7 @@ impl<'a> InputBuffer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for InputBuffer<'a> {
|
||||
impl Drop for InputBuffer<'_> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::android_app_clear_motion_events(self.ptr.as_ptr());
|
||||
@@ -537,22 +767,144 @@ impl<'a> Drop for InputBuffer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Conceptually we can think of this like the receiver end of an
|
||||
/// input events channel.
|
||||
///
|
||||
/// After being passed back to AndroidApp it gets turned into a
|
||||
/// lending iterator for pending input events.
|
||||
///
|
||||
/// It serves two purposes:
|
||||
/// 1. It represents an exclusive access to input events (the application
|
||||
/// can only have one receiver at a time) and it's intended to support
|
||||
/// the double-buffering design for input events in GameActivity where
|
||||
/// we issue a swap_buffers before iterating events and wouldn't want
|
||||
/// another swap to be possible before finishing - especially since
|
||||
/// we want to borrow directly from the buffer while dispatching.
|
||||
/// 2. It doesn't borrow from AndroidAppInner so we can pass it back to
|
||||
/// AndroidApp which can drop its lock around AndroidAppInner and
|
||||
/// it can then be turned into a lending iterator. (We wouldn't
|
||||
/// be able to pass the iterator back to the application if it
|
||||
/// borrowed from within the lock and we need to drop the lock
|
||||
/// because otherwise the app wouldn't be able to access the AndroidApp
|
||||
/// API in any way while iterating events)
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct InputReceiver {
|
||||
// Safety: the native_app effectively has a static lifetime and it
|
||||
// has its own internal locking when calling
|
||||
// `android_app_swap_input_buffers`
|
||||
native_app: NativeAppGlue,
|
||||
}
|
||||
|
||||
impl<'a> From<Arc<InputReceiver>> for InputIteratorInner<'a> {
|
||||
fn from(receiver: Arc<InputReceiver>) -> Self {
|
||||
let buffered = unsafe {
|
||||
let app_ptr = receiver.native_app.as_ptr();
|
||||
let input_buffer = ffi::android_app_swap_input_buffers(app_ptr);
|
||||
NonNull::new(input_buffer).map(|input_buffer| {
|
||||
let buffer = InputBuffer::from_ptr(input_buffer);
|
||||
let keys_iter = KeyEventsLendingIterator::new(&buffer);
|
||||
let motion_iter = MotionEventsLendingIterator::new(&buffer);
|
||||
BufferedEvents::<'a> {
|
||||
buffer,
|
||||
keys_iter,
|
||||
motion_iter,
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
let native_app = receiver.native_app.clone();
|
||||
Self {
|
||||
_receiver: receiver,
|
||||
buffered,
|
||||
native_app,
|
||||
ime_text_input_state_checked: false,
|
||||
ime_editor_action_checked: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BufferedEvents<'a> {
|
||||
buffer: InputBuffer<'a>,
|
||||
keys_iter: KeyEventsLendingIterator,
|
||||
motion_iter: MotionEventsLendingIterator,
|
||||
}
|
||||
|
||||
pub(crate) struct InputIteratorInner<'a> {
|
||||
// Held to maintain exclusive access to buffered input events
|
||||
_receiver: Arc<InputReceiver>,
|
||||
|
||||
buffered: Option<BufferedEvents<'a>>,
|
||||
native_app: NativeAppGlue,
|
||||
ime_text_input_state_checked: bool,
|
||||
ime_editor_action_checked: bool,
|
||||
}
|
||||
|
||||
impl InputIteratorInner<'_> {
|
||||
pub(crate) fn next<F>(&mut self, callback: F) -> bool
|
||||
where
|
||||
F: FnOnce(&input::InputEvent) -> InputStatus,
|
||||
{
|
||||
if let Some(buffered) = &mut self.buffered {
|
||||
if let Some(key_event) = buffered.keys_iter.next(&buffered.buffer) {
|
||||
let _ = callback(&InputEvent::KeyEvent(key_event));
|
||||
return true;
|
||||
}
|
||||
if let Some(motion_event) = buffered.motion_iter.next(&buffered.buffer) {
|
||||
let _ = callback(&InputEvent::MotionEvent(motion_event));
|
||||
return true;
|
||||
}
|
||||
self.buffered = None;
|
||||
}
|
||||
|
||||
// We make sure any input state changes are sent before we check
|
||||
// for editor actions, so actions will apply to the latest state.
|
||||
if !self.ime_text_input_state_checked {
|
||||
self.ime_text_input_state_checked = true;
|
||||
unsafe {
|
||||
let app_ptr = self.native_app.as_ptr();
|
||||
|
||||
// XXX: It looks like the GameActivity implementation should
|
||||
// be using atomic ops to set this flag, and require us to
|
||||
// use atomics to check and clear it too.
|
||||
//
|
||||
// We currently just hope that with the lack of atomic ops that
|
||||
// the compiler isn't reordering code so this gets flagged
|
||||
// before the java main thread really updates the state.
|
||||
if (*app_ptr).textInputState != 0 {
|
||||
let state = self.native_app.take_text_input_state(); // Will clear .textInputState
|
||||
let _ = callback(&InputEvent::TextEvent(state));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !self.ime_editor_action_checked {
|
||||
self.ime_editor_action_checked = true;
|
||||
if let Some(action) = self.native_app.take_pending_editor_action() {
|
||||
let _ = callback(&InputEvent::TextAction(TextInputAction::from(action)));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// 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(
|
||||
pub fn Java_com_google_androidgamesdk_GameActivity_initializeNativeCode_C(
|
||||
env: *mut JNIEnv,
|
||||
javaGameActivity: jobject,
|
||||
path: jstring,
|
||||
funcName: jstring,
|
||||
internalDataDir: jstring,
|
||||
obbDir: jstring,
|
||||
externalDataDir: jstring,
|
||||
jAssetMgr: jobject,
|
||||
savedState: jbyteArray,
|
||||
javaConfig: jobject,
|
||||
) -> jlong;
|
||||
|
||||
pub fn GameActivity_onCreate_C(
|
||||
@@ -563,27 +915,25 @@ extern "C" {
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn Java_com_google_androidgamesdk_GameActivity_loadNativeCode(
|
||||
pub unsafe extern "C" fn Java_com_google_androidgamesdk_GameActivity_initializeNativeCode(
|
||||
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(
|
||||
java_config: jobject,
|
||||
) -> jlong {
|
||||
Java_com_google_androidgamesdk_GameActivity_initializeNativeCode_C(
|
||||
env,
|
||||
java_game_activity,
|
||||
path,
|
||||
func_name,
|
||||
internal_data_dir,
|
||||
obb_dir,
|
||||
external_data_dir,
|
||||
jasset_mgr,
|
||||
saved_state,
|
||||
java_config,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -604,76 +954,60 @@ extern "Rust" {
|
||||
// `app_main` function. This is run on a dedicated thread spawned
|
||||
// by android_native_app_glue.
|
||||
#[no_mangle]
|
||||
#[allow(unused_unsafe)] // Otherwise rust 1.64 moans about using unsafe{} in unsafe functions
|
||||
pub unsafe extern "C" fn _rust_glue_entry(native_app: *mut ffi::android_app) {
|
||||
abort_on_panic(|| {
|
||||
// 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 _join_log_forwarder = forward_stdio_to_logcat();
|
||||
|
||||
let jvm = unsafe {
|
||||
let (jvm, jni_activity) = unsafe {
|
||||
let jvm = (*(*native_app).activity).vm;
|
||||
let activity: jobject = (*(*native_app).activity).javaGameActivity;
|
||||
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());
|
||||
}
|
||||
|
||||
jvm
|
||||
(jni::JavaVM::from_raw(jvm), activity)
|
||||
};
|
||||
// Note: At this point we can assume jni::JavaVM::singleton is initialized
|
||||
|
||||
unsafe {
|
||||
let app = AndroidApp::from_ptr(NonNull::new(native_app).unwrap());
|
||||
// Note: the GameActivity implementation will have already attached the main thread to the
|
||||
// JVM before calling _rust_glue_entry so we don't to set the thread name via
|
||||
// attach_current_thread_with_config since that won't actually create a new attachment.
|
||||
//
|
||||
// Calling .attach_current_thread will ensure that the `jni` crate knows about the
|
||||
// attachment, as a convenience.
|
||||
jvm.attach_current_thread(|env| -> jni::errors::Result<()> {
|
||||
// SAFETY: We know jni_activity is a valid JNI global ref to an Activity instance
|
||||
let jni_activity = unsafe { env.as_cast_raw::<Global<JObject>>(&jni_activity)? };
|
||||
|
||||
// We want to specifically catch any panic from the application's android_main
|
||||
// so we can finish + destroy the Activity gracefully via the JVM
|
||||
catch_unwind(|| {
|
||||
// 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);
|
||||
})
|
||||
.unwrap_or_else(|panic| log_panic(panic));
|
||||
|
||||
// Let JVM know that our Activity can be destroyed before detaching from the JVM
|
||||
//
|
||||
// "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"
|
||||
ffi::GameActivity_finish((*native_app).activity);
|
||||
|
||||
if let Some(detach_current_thread) = (*(*jvm)).DetachCurrentThread {
|
||||
detach_current_thread(jvm);
|
||||
if let Err(err) = init_android_main_thread(&jvm, &jni_activity) {
|
||||
eprintln!("Failed to name Java thread and set thread context class loader: {err}");
|
||||
}
|
||||
|
||||
ndk_context::release_android_context();
|
||||
}
|
||||
unsafe {
|
||||
let app = AndroidApp::from_ptr(NonNull::new(native_app).unwrap(), jvm.clone());
|
||||
// We want to specifically catch any panic from the application's android_main
|
||||
// so we can finish + destroy the Activity gracefully via the JVM
|
||||
catch_unwind(|| {
|
||||
// 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);
|
||||
})
|
||||
.unwrap_or_else(log_panic);
|
||||
|
||||
// Let JVM know that our Activity can be destroyed before detaching from the JVM
|
||||
//
|
||||
// "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"
|
||||
ffi::GameActivity_finish((*native_app).activity);
|
||||
|
||||
ndk_context::release_android_context();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.expect("Failed to attach thread to JVM");
|
||||
})
|
||||
}
|
||||
|
||||
+1006
-29
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,288 @@
|
||||
use jni::sys::jint;
|
||||
use jni::{objects::Global, JavaVM};
|
||||
|
||||
use crate::error::{AppError, InternalAppError, InternalResult};
|
||||
use crate::input::{Keycode, MetaState};
|
||||
use crate::jni_utils;
|
||||
|
||||
/// An enum representing the types of keyboards that may generate key events
|
||||
///
|
||||
/// See [getKeyboardType() docs](https://developer.android.com/reference/android/view/KeyCharacterMap#getKeyboardType())
|
||||
///
|
||||
/// # Android Extensible Enum
|
||||
///
|
||||
/// This is a runtime [extensible enum](`crate#android-extensible-enums`) and
|
||||
/// should be handled similar to a `#[non_exhaustive]` enum to maintain
|
||||
/// forwards compatibility.
|
||||
///
|
||||
/// This implements `Into<u32>` and `From<u32>` for converting to/from Android
|
||||
/// SDK integer values.
|
||||
#[derive(
|
||||
Debug, Clone, Copy, PartialEq, Eq, Hash, num_enum::FromPrimitive, num_enum::IntoPrimitive,
|
||||
)]
|
||||
#[non_exhaustive]
|
||||
#[repr(u32)]
|
||||
pub enum KeyboardType {
|
||||
/// A numeric (12-key) keyboard.
|
||||
///
|
||||
/// A numeric keyboard supports text entry using a multi-tap approach. It may be necessary to tap a key multiple times to generate the desired letter or symbol.
|
||||
///
|
||||
/// This type of keyboard is generally designed for thumb typing.
|
||||
Numeric,
|
||||
|
||||
/// A keyboard with all the letters, but with more than one letter per key.
|
||||
///
|
||||
/// This type of keyboard is generally designed for thumb typing.
|
||||
Predictive,
|
||||
|
||||
/// A keyboard with all the letters, and maybe some numbers.
|
||||
///
|
||||
/// An alphabetic keyboard supports text entry directly but may have a condensed layout with a small form factor. In contrast to a full keyboard, some symbols may only be accessible using special on-screen character pickers. In addition, to improve typing speed and accuracy, the framework provides special affordances for alphabetic keyboards such as auto-capitalization and toggled / locked shift and alt keys.
|
||||
///
|
||||
/// This type of keyboard is generally designed for thumb typing.
|
||||
Alpha,
|
||||
|
||||
/// A full PC-style keyboard.
|
||||
///
|
||||
/// A full keyboard behaves like a PC keyboard. All symbols are accessed directly by pressing keys on the keyboard without on-screen support or affordances such as auto-capitalization.
|
||||
///
|
||||
/// This type of keyboard is generally designed for full two hand typing.
|
||||
Full,
|
||||
|
||||
/// A keyboard that is only used to control special functions rather than for typing.
|
||||
///
|
||||
/// A special function keyboard consists only of non-printing keys such as HOME and POWER that are not actually used for typing.
|
||||
SpecialFunction,
|
||||
|
||||
#[doc(hidden)]
|
||||
#[num_enum(catch_all)]
|
||||
__Unknown(u32),
|
||||
}
|
||||
|
||||
/// Either represents, a unicode character or combining accent from a
|
||||
/// [`KeyCharacterMap`], or `None` for non-printable keys.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum KeyMapChar {
|
||||
None,
|
||||
Unicode(char),
|
||||
CombiningAccent(char),
|
||||
}
|
||||
|
||||
jni::bind_java_type! {
|
||||
pub(crate) AKeyCharacterMap => "android.view.KeyCharacterMap",
|
||||
methods {
|
||||
priv fn _get(key_code: jint, meta_state: jint) -> jint,
|
||||
priv static fn _get_dead_char(accent_char: jint, base_char: jint) -> jint,
|
||||
priv fn _get_keyboard_type() -> jint,
|
||||
}
|
||||
}
|
||||
|
||||
impl AKeyCharacterMap<'_> {
|
||||
pub(crate) fn get<'local>(
|
||||
&self,
|
||||
env: &'local mut jni::Env,
|
||||
key_code: jint,
|
||||
meta_state: jint,
|
||||
) -> Result<jint, InternalAppError> {
|
||||
self._get(env, key_code, meta_state)
|
||||
.map_err(|err| jni_utils::clear_and_map_exception_to_err(env, err))
|
||||
}
|
||||
|
||||
pub(crate) fn get_dead_char(
|
||||
env: &mut jni::Env,
|
||||
accent_char: jint,
|
||||
base_char: jint,
|
||||
) -> Result<jint, InternalAppError> {
|
||||
Self::_get_dead_char(env, accent_char, base_char)
|
||||
.map_err(|err| jni_utils::clear_and_map_exception_to_err(env, err))
|
||||
}
|
||||
|
||||
pub(crate) fn get_keyboard_type<'local>(
|
||||
&self,
|
||||
env: &'local mut jni::Env,
|
||||
) -> Result<jint, InternalAppError> {
|
||||
self._get_keyboard_type(env)
|
||||
.map_err(|err| jni_utils::clear_and_map_exception_to_err(env, err))
|
||||
}
|
||||
}
|
||||
|
||||
jni::bind_java_type! {
|
||||
rust_type = AInputDevice,
|
||||
java_type = "android.view.InputDevice",
|
||||
type_map {
|
||||
AKeyCharacterMap => "android.view.KeyCharacterMap",
|
||||
},
|
||||
methods {
|
||||
static fn get_device(id: jint) -> AInputDevice,
|
||||
fn get_key_character_map() -> AKeyCharacterMap,
|
||||
}
|
||||
}
|
||||
|
||||
// Explicitly initialize the JNI bindings so we can get and early, upfront,
|
||||
// error if something is wrong.
|
||||
pub fn jni_init(env: &jni::Env) -> jni::errors::Result<()> {
|
||||
let _ = AKeyCharacterMapAPI::get(env, &Default::default())?;
|
||||
let _ = AInputDeviceAPI::get(env, &Default::default())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Describes the keys provided by a keyboard device and their associated labels.
|
||||
#[derive(Debug)]
|
||||
pub struct KeyCharacterMap {
|
||||
jvm: JavaVM,
|
||||
key_map: Global<AKeyCharacterMap<'static>>,
|
||||
}
|
||||
impl Clone for KeyCharacterMap {
|
||||
fn clone(&self) -> Self {
|
||||
let jvm = self.jvm.clone();
|
||||
jvm.attach_current_thread(|env| -> jni::errors::Result<_> {
|
||||
Ok(Self {
|
||||
jvm: jvm.clone(),
|
||||
key_map: env.new_global_ref(&self.key_map)?,
|
||||
})
|
||||
})
|
||||
.expect("Failed to attach thread to JVM and clone key map")
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyCharacterMap {
|
||||
pub(crate) fn new(jvm: JavaVM, key_map: Global<AKeyCharacterMap<'static>>) -> Self {
|
||||
Self { jvm, key_map }
|
||||
}
|
||||
|
||||
/// Gets the Unicode character generated by the specified [`Keycode`] and [`MetaState`] combination.
|
||||
///
|
||||
/// Returns [`KeyMapChar::None`] if the key is not one that is used to type Unicode characters.
|
||||
///
|
||||
/// Returns [`KeyMapChar::CombiningAccent`] if the key is a "dead key" that should be combined with
|
||||
/// another to actually produce a character -- see [`KeyCharacterMap::get_dead_char`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Since this API needs to use JNI internally to call into the Android JVM it may return
|
||||
/// a [`AppError::JavaError`] in case there is a spurious JNI error or an exception
|
||||
/// is caught.
|
||||
pub fn get(&self, key_code: Keycode, meta_state: MetaState) -> Result<KeyMapChar, AppError> {
|
||||
let key_code: u32 = key_code.into();
|
||||
let key_code = key_code as i32;
|
||||
let meta_state = meta_state.0 as i32;
|
||||
|
||||
let vm = self.jvm.clone();
|
||||
vm.attach_current_thread(|env| -> InternalResult<_> {
|
||||
let unicode = self.key_map.get(env, key_code, meta_state)?;
|
||||
let unicode = unicode as u32;
|
||||
|
||||
const COMBINING_ACCENT: u32 = 0x80000000;
|
||||
const COMBINING_ACCENT_MASK: u32 = !COMBINING_ACCENT;
|
||||
|
||||
if unicode == 0 {
|
||||
Ok(KeyMapChar::None)
|
||||
} else if unicode & COMBINING_ACCENT == COMBINING_ACCENT {
|
||||
let accent = unicode & COMBINING_ACCENT_MASK;
|
||||
// Safety: assumes Android key maps don't contain invalid unicode characters
|
||||
Ok(KeyMapChar::CombiningAccent(unsafe {
|
||||
char::from_u32_unchecked(accent)
|
||||
}))
|
||||
} else {
|
||||
// Safety: assumes Android key maps don't contain invalid unicode characters
|
||||
Ok(KeyMapChar::Unicode(unsafe {
|
||||
char::from_u32_unchecked(unicode)
|
||||
}))
|
||||
}
|
||||
})
|
||||
.map_err(|err| {
|
||||
let err: InternalAppError = err.into();
|
||||
err.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the character that is produced by combining the dead key producing accent with the key producing character c.
|
||||
///
|
||||
/// For example, ``get_dead_char('`', 'e')`` returns `'è'`. `get_dead_char('^', ' ')` returns `'^'` and `get_dead_char('^', '^')` returns `'^'`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Since this API needs to use JNI internally to call into the Android JVM it may return a
|
||||
/// [`AppError::JavaError`] in case there is a spurious JNI error or an exception is caught.
|
||||
pub fn get_dead_char(
|
||||
&self,
|
||||
accent_char: char,
|
||||
base_char: char,
|
||||
) -> Result<Option<char>, AppError> {
|
||||
let accent_char = accent_char as jni::sys::jint;
|
||||
let base_char = base_char as jni::sys::jint;
|
||||
|
||||
let vm = self.jvm.clone();
|
||||
vm.attach_current_thread(|env| -> InternalResult<_> {
|
||||
let unicode = AKeyCharacterMap::get_dead_char(env, accent_char, base_char)?;
|
||||
let unicode = unicode as u32;
|
||||
|
||||
// Safety: assumes Android key maps don't contain invalid unicode characters
|
||||
Ok(if unicode == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(unsafe { char::from_u32_unchecked(unicode) })
|
||||
})
|
||||
})
|
||||
.map_err(|err| {
|
||||
let err: InternalAppError = err.into();
|
||||
err.into()
|
||||
})
|
||||
}
|
||||
|
||||
/// Gets the keyboard type.
|
||||
///
|
||||
/// Different keyboard types have different semantics. See [`KeyboardType`] for details.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Since this API needs to use JNI internally to call into the Android JVM it may return
|
||||
/// a [`AppError::JavaError`] in case there is a spurious JNI error or an exception
|
||||
/// is caught.
|
||||
pub fn get_keyboard_type(&self) -> Result<KeyboardType, AppError> {
|
||||
let vm = self.jvm.clone();
|
||||
vm.attach_current_thread(|env| -> InternalResult<_> {
|
||||
let keyboard_type = self.key_map.get_keyboard_type(env)?;
|
||||
let keyboard_type = keyboard_type as u32;
|
||||
Ok(keyboard_type.into())
|
||||
})
|
||||
.map_err(|err| {
|
||||
let err: InternalAppError = err.into();
|
||||
err.into()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn device_key_character_map_with_env(
|
||||
env: &mut jni::Env<'_>,
|
||||
device_id: i32,
|
||||
) -> jni::errors::Result<KeyCharacterMap> {
|
||||
let device = AInputDevice::get_device(env, device_id)?;
|
||||
if device.is_null() {
|
||||
// This isn't really an error from a JNI perspective but we would only expect
|
||||
// this to return null for a device ID of zero or an invalid device ID.
|
||||
log::error!("No input device with id {}", device_id);
|
||||
return Err(jni::errors::Error::WrongObjectType);
|
||||
}
|
||||
let character_map = device.get_key_character_map(env)?;
|
||||
let character_map = env.new_global_ref(character_map)?;
|
||||
Ok(KeyCharacterMap::new(
|
||||
env.get_java_vm().clone(),
|
||||
character_map,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn device_key_character_map(
|
||||
jvm: JavaVM,
|
||||
device_id: i32,
|
||||
) -> InternalResult<KeyCharacterMap> {
|
||||
jvm.attach_current_thread(|env| {
|
||||
if device_id == 0 {
|
||||
return Err(InternalAppError::JniBadArgument(
|
||||
"Can't get key character map for non-physical device_id 0".into(),
|
||||
));
|
||||
}
|
||||
device_key_character_map_with_env(env, device_id)
|
||||
.map_err(|err| jni_utils::clear_and_map_exception_to_err(env, err))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! The JNI calls we make in this crate are often not part of a Java native
|
||||
//! method implementation and so we can't assume we have a JNI local frame that
|
||||
//! is going to unwind and free local references, and we also can't just leave
|
||||
//! exceptions to get thrown when returning to Java.
|
||||
//!
|
||||
//! These utilities help us check + clear exceptions and map them into Rust Errors.
|
||||
|
||||
use crate::error::InternalAppError;
|
||||
|
||||
fn try_get_stack_trace(
|
||||
env: &mut jni::Env<'_>,
|
||||
throwable: &jni::objects::JThrowable,
|
||||
) -> jni::errors::Result<String> {
|
||||
let stack_trace = throwable.get_stack_trace(env)?;
|
||||
let len = stack_trace.len(env)?;
|
||||
let mut trace = String::new();
|
||||
for i in 0..len {
|
||||
let element = stack_trace.get_element(env, i)?;
|
||||
let element_jstr = element.try_to_string(env)?;
|
||||
trace.push_str(&format!("{i}: {element_jstr}\n"));
|
||||
}
|
||||
Ok(trace)
|
||||
}
|
||||
|
||||
/// Use with `.map_err()` to map `jni::errors::Error::JavaException` into a
|
||||
/// richer error based on the actual contents of the `JThrowable`
|
||||
///
|
||||
/// (The `jni` crate doesn't do that automatically since it's more
|
||||
/// common to let the exception get thrown when returning to Java)
|
||||
///
|
||||
/// This will also clear the exception
|
||||
pub(crate) fn clear_and_map_exception_to_err(
|
||||
env: &mut jni::Env<'_>,
|
||||
err: jni::errors::Error,
|
||||
) -> InternalAppError {
|
||||
if matches!(err, jni::errors::Error::JavaException) {
|
||||
let result = env.with_local_frame::<_, _, InternalAppError>(5, |env| {
|
||||
let Some(e) = env.exception_occurred() else {
|
||||
// should only be called after receiving a JavaException Result
|
||||
unreachable!("JNI Error was JavaException but no exception was set");
|
||||
};
|
||||
env.exception_clear();
|
||||
|
||||
let msg = e.get_message(env)?;
|
||||
let mut msg: String = msg.to_string();
|
||||
match try_get_stack_trace(env, &e) {
|
||||
Ok(stack_trace) => {
|
||||
msg.push_str("stack trace:\n");
|
||||
msg.push_str(&stack_trace);
|
||||
}
|
||||
Err(err) => {
|
||||
msg.push_str(&format!("\nfailed to get stack trace: {err:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(msg)
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(msg) => InternalAppError::JniException(msg),
|
||||
Err(err) => InternalAppError::JniException(format!(
|
||||
"UNKNOWN (Failed to query JThrowable: {err:?})"
|
||||
)),
|
||||
}
|
||||
} else {
|
||||
err.into()
|
||||
}
|
||||
}
|
||||
+280
-48
@@ -13,15 +13,15 @@
|
||||
//! a wider range of devices.
|
||||
//!
|
||||
//! Standalone applications based on this crate need to be built as `cdylib` libraries, like:
|
||||
//! ```
|
||||
//! ```toml
|
||||
//! [lib]
|
||||
//! crate_type=["cdylib"]
|
||||
//! ```
|
||||
//!
|
||||
//! and implement a `#[no_mangle]` `android_main` entry point like this:
|
||||
//! ```rust
|
||||
//! ```no_run
|
||||
//! #[no_mangle]
|
||||
//! fn android_main(app: AndroidApp) {
|
||||
//! fn android_main(app: android_activity::AndroidApp) {
|
||||
//!
|
||||
//! }
|
||||
//! ```
|
||||
@@ -35,6 +35,18 @@
|
||||
//! marshalled between the Java thread that owns the `Activity` and the native
|
||||
//! thread that runs the `android_main()` code.
|
||||
//!
|
||||
//! # Cheaply Clonable [`AndroidApp`]
|
||||
//!
|
||||
//! [`AndroidApp`] is intended to be something that can be cheaply passed around
|
||||
//! by referenced within an application. It is reference counted and can be
|
||||
//! cheaply cloned.
|
||||
//!
|
||||
//! # `Send` and `Sync` [`AndroidApp`]
|
||||
//!
|
||||
//! Although an [`AndroidApp`] implements `Send` and `Sync` you do need to take
|
||||
//! into consideration that some APIs, such as [`AndroidApp::poll_events()`] are
|
||||
//! explicitly documented to only be usable from your `android_main()` thread.
|
||||
//!
|
||||
//! # Main Thread Initialization
|
||||
//!
|
||||
//! Before `android_main()` is called, the following application state
|
||||
@@ -51,22 +63,74 @@
|
||||
//!
|
||||
//! These are undone after `android_main()` returns
|
||||
//!
|
||||
//! # Android Extensible Enums
|
||||
// TODO: Move this to the NDK crate, which now implements this for most of the code?
|
||||
//!
|
||||
//! There are numerous enums in the `android-activity` API which are effectively
|
||||
//! bindings to enums declared in the Android SDK which need to be considered
|
||||
//! _runtime_ extensible.
|
||||
//!
|
||||
//! Any enum variants that come from the Android SDK may be extended in future
|
||||
//! versions of Android and your code could be exposed to new variants if you
|
||||
//! build an application that might be installed on new versions of Android.
|
||||
//!
|
||||
//! This crate follows a convention of adding a hidden `__Unknown(u32)` variant
|
||||
//! to these enum to ensure we can always do lossless conversions between the
|
||||
//! integers from the SDK and our corresponding Rust enums. This can be
|
||||
//! important in case you need to pass certain variants back to the SDK
|
||||
//! regardless of whether you knew about that variants specific semantics at
|
||||
//! compile time.
|
||||
//!
|
||||
//! You should never include this `__Unknown(u32)` variant within any exhaustive
|
||||
//! pattern match and should instead treat the enums like `#[non_exhaustive]`
|
||||
//! enums that require you to add a catch-all for any `unknown => {}` values.
|
||||
//!
|
||||
//! Any code that would exhaustively include the `__Unknown(u32)` variant when
|
||||
//! pattern matching can not be guaranteed to be forwards compatible with new
|
||||
//! releases of `android-activity` which may add new Rust variants to these
|
||||
//! enums without requiring a breaking semver bump.
|
||||
//!
|
||||
//! You can (infallibly) convert these enums to and from primitive `u32` values
|
||||
//! using `.into()`:
|
||||
//!
|
||||
//! For example, here is how you could ensure forwards compatibility with both
|
||||
//! compile-time and runtime extensions of a `SomeEnum` enum:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! match some_enum {
|
||||
//! SomeEnum::Foo => {},
|
||||
//! SomeEnum::Bar => {},
|
||||
//! unhandled => {
|
||||
//! let sdk_val: u32 = unhandled.into();
|
||||
//! println!("Unhandled enum variant {some_enum:?} has SDK value: {sdk_val}");
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! [`Activity`]: https://developer.android.com/reference/android/app/Activity
|
||||
//! [`NativeActivity`]: https://developer.android.com/reference/android/app/NativeActivity
|
||||
//! [ndk_concepts]: https://developer.android.com/ndk/guides/concepts#naa
|
||||
//! [`GameActivity`]: https://developer.android.com/games/agdk/integrate-game-activity
|
||||
//! [Looper]: https://developer.android.com/reference/android/os/Looper
|
||||
|
||||
#![deny(clippy::manual_let_else)]
|
||||
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use bitflags::bitflags;
|
||||
use libc::c_void;
|
||||
|
||||
use ndk::asset::AssetManager;
|
||||
use ndk::native_window::NativeWindow;
|
||||
|
||||
use bitflags::bitflags;
|
||||
// Since we expose `ndk` types in our public API it's convenient if crates can
|
||||
// defer to these re-exported APIs and avoid having to bump explicit
|
||||
// dependencies when they pull in new releases of android-activity.
|
||||
pub use ndk;
|
||||
pub use ndk_sys;
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
compile_error!("android-activity only supports compiling for Android");
|
||||
@@ -77,7 +141,7 @@ compile_error!(
|
||||
);
|
||||
#[cfg(all(
|
||||
not(any(feature = "game-activity", feature = "native-activity")),
|
||||
not(doc)
|
||||
not(any(doc, used_on_docsrs)),
|
||||
))]
|
||||
compile_error!(
|
||||
r#"Either "game-activity" or "native-activity" must be enabled as features
|
||||
@@ -96,23 +160,33 @@ You may need to add a `[patch]` into your Cargo.toml to ensure a specific versio
|
||||
android-activity is used across all of your application's crates."#
|
||||
);
|
||||
|
||||
#[cfg(any(feature = "native-activity", doc))]
|
||||
mod native_activity;
|
||||
#[cfg(any(feature = "native-activity", doc))]
|
||||
use native_activity as activity_impl;
|
||||
#[cfg_attr(feature = "native-activity", path = "native_activity/mod.rs")]
|
||||
#[cfg_attr(feature = "game-activity", path = "game_activity/mod.rs")]
|
||||
#[cfg_attr(
|
||||
all(
|
||||
// No activities enabled.
|
||||
not(any(feature = "native-activity", feature = "game-activity")),
|
||||
// And building docs.
|
||||
any(doc, used_on_docsrs),
|
||||
),
|
||||
// Fall back to documenting native activity.
|
||||
path = "native_activity/mod.rs"
|
||||
)]
|
||||
pub(crate) mod activity_impl;
|
||||
|
||||
#[cfg(feature = "game-activity")]
|
||||
mod game_activity;
|
||||
#[cfg(feature = "game-activity")]
|
||||
use game_activity as activity_impl;
|
||||
pub mod error;
|
||||
use error::Result;
|
||||
|
||||
pub mod input;
|
||||
use input::KeyCharacterMap;
|
||||
|
||||
mod config;
|
||||
pub use config::ConfigurationRef;
|
||||
|
||||
mod util;
|
||||
|
||||
mod jni_utils;
|
||||
|
||||
/// A rectangle with integer edge coordinates. Used to represent window insets, for example.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Rect {
|
||||
@@ -163,14 +237,14 @@ pub use activity_impl::StateSaver;
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug)]
|
||||
pub enum MainEvent<'a> {
|
||||
/// New input events are available via [`AndroidApp::input_events()`]
|
||||
/// New input events are available via [`AndroidApp::input_events_iter()`]
|
||||
///
|
||||
/// _Note: Even if more input is received this event will not be resent
|
||||
/// until [`AndroidApp::input_events()`] has been called, which enables
|
||||
/// until [`AndroidApp::input_events_iter()`] has been called, which enables
|
||||
/// applications to batch up input processing without there being lots of
|
||||
/// redundant event loop wake ups._
|
||||
///
|
||||
/// [`AndroidApp::input_events()`]: AndroidApp::input_events
|
||||
/// [`AndroidApp::input_events_iter()`]: AndroidApp::input_events_iter
|
||||
InputAvailable,
|
||||
|
||||
/// Command from main thread: a new [`NativeWindow`] is ready for use. Upon
|
||||
@@ -211,9 +285,9 @@ pub enum MainEvent<'a> {
|
||||
/// input focus.
|
||||
LostFocus,
|
||||
|
||||
/// Command from main thread: the current device configuration has changed.
|
||||
/// You can get a copy of the latest [`ndk::configuration::Configuration`] by calling
|
||||
/// [`AndroidApp::config()`]
|
||||
/// Command from main thread: the current device configuration has changed. Any
|
||||
/// reference gotten via [`AndroidApp::config()`] will automatically contain the latest
|
||||
/// [`ndk::configuration::Configuration`].
|
||||
#[non_exhaustive]
|
||||
ConfigChanged {},
|
||||
|
||||
@@ -275,6 +349,7 @@ pub use activity_impl::AndroidAppWaker;
|
||||
bitflags! {
|
||||
/// Flags for [`AndroidApp::set_window_flags`]
|
||||
/// as per the [android.view.WindowManager.LayoutParams Java API](https://developer.android.com/reference/android/view/WindowManager.LayoutParams)
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct WindowManagerFlags: u32 {
|
||||
/// 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
|
||||
@@ -445,6 +520,18 @@ bitflags! {
|
||||
/// marshalled between the Java thread that owns the `Activity` and the native
|
||||
/// thread that runs the `android_main()` code.
|
||||
///
|
||||
/// # Cheaply Clonable [`AndroidApp`]
|
||||
///
|
||||
/// [`AndroidApp`] is intended to be something that can be cheaply passed around
|
||||
/// by referenced within an application. It is reference counted and can be
|
||||
/// cheaply cloned.
|
||||
///
|
||||
/// # `Send` and `Sync` [`AndroidApp`]
|
||||
///
|
||||
/// Although an [`AndroidApp`] implements `Send` and `Sync` you do need to take
|
||||
/// into consideration that some APIs, such as [`AndroidApp::poll_events()`] are
|
||||
/// explicitly documented to only be usable from your `android_main()` thread.
|
||||
///
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AndroidApp {
|
||||
pub(crate) inner: Arc<RwLock<AndroidAppInner>>,
|
||||
@@ -479,11 +566,11 @@ impl AndroidApp {
|
||||
/// with the [`jni`] crate (or similar crates) to make JNI calls that bridge
|
||||
/// between native Rust code and Java/Kotlin code running within the JVM.
|
||||
///
|
||||
/// If you use the [`jni`] crate you can wrap this as a [`JavaVM`] via:
|
||||
/// ```ignore
|
||||
/// If you use the [`jni`] crate you can could this as a [`JavaVM`] via:
|
||||
/// ```no_run
|
||||
/// # use jni::JavaVM;
|
||||
/// # let app: AndroidApp = todo!();
|
||||
/// let vm = unsafe { JavaVM::from_raw(app.vm_as_ptr()) };
|
||||
/// # let app: android_activity::AndroidApp = todo!();
|
||||
/// let vm = unsafe { JavaVM::from_raw(app.vm_as_ptr().cast()) };
|
||||
/// ```
|
||||
///
|
||||
/// [`jni`]: https://crates.io/crates/jni
|
||||
@@ -494,24 +581,28 @@ impl AndroidApp {
|
||||
|
||||
/// Returns a JNI object reference for this application's JVM `Activity` as a pointer
|
||||
///
|
||||
/// If you use the [`jni`] crate you can wrap this as an object reference via:
|
||||
/// ```ignore
|
||||
/// If you use the [`jni`] crate you can cast this as a `JObject` reference via:
|
||||
/// ```no_run
|
||||
/// # use jni::objects::JObject;
|
||||
/// # let app: AndroidApp = todo!();
|
||||
/// let activity = unsafe { JObject::from_raw(app.activity_as_ptr()) };
|
||||
/// # use jni::refs::Global;
|
||||
/// # fn use_jni(env: &jni::Env, app: &android_activity::AndroidApp) -> jni::errors::Result<()> {
|
||||
/// let raw_activity_global = app.activity_as_ptr() as jni::sys::jobject;
|
||||
/// // SAFETY: The pointer is valid as long as `app` is valid.
|
||||
/// let activity = unsafe { env.as_cast_raw::<Global<JObject>>(&raw_activity_global)? };
|
||||
/// # Ok(()) }
|
||||
/// ```
|
||||
///
|
||||
/// # JNI Safety
|
||||
///
|
||||
/// Note that the object reference will be a JNI global reference, not a
|
||||
/// local reference and it should not be deleted. Don't wrap the reference
|
||||
/// in an [`AutoLocal`] which would try to explicitly delete the reference
|
||||
/// when dropped. Similarly, don't wrap the reference as a [`GlobalRef`]
|
||||
/// in an [`Auto`] which would try to explicitly delete the reference
|
||||
/// when dropped. Similarly, don't wrap the reference as a [`Global`]
|
||||
/// which would also try to explicitly delete the reference when dropped.
|
||||
///
|
||||
/// [`jni`]: https://crates.io/crates/jni
|
||||
/// [`AutoLocal`]: https://docs.rs/jni/latest/jni/objects/struct.AutoLocal.html
|
||||
/// [`GlobalRef`]: https://docs.rs/jni/latest/jni/objects/struct.GlobalRef.html
|
||||
/// [`Auto`]: https://docs.rs/jni/latest/jni/refs/struct.Auto.html
|
||||
/// [`Global`]: https://docs.rs/jni/latest/jni/refs/struct.Global.html
|
||||
pub fn activity_as_ptr(&self) -> *mut c_void {
|
||||
self.inner.read().unwrap().activity_as_ptr()
|
||||
}
|
||||
@@ -536,18 +627,25 @@ impl AndroidApp {
|
||||
/// [`ALooper_pollAll`]: ndk::looper::ThreadLooper::poll_all
|
||||
pub fn poll_events<F>(&self, timeout: Option<Duration>, callback: F)
|
||||
where
|
||||
F: FnMut(PollEvent),
|
||||
F: FnMut(PollEvent<'_>),
|
||||
{
|
||||
self.inner.read().unwrap().poll_events(timeout, callback);
|
||||
}
|
||||
|
||||
/// Creates a means to wake up the main loop while it is blocked waiting for
|
||||
/// events within [`AndroidApp::poll_events()`].
|
||||
pub fn create_waker(&self) -> activity_impl::AndroidAppWaker {
|
||||
pub fn create_waker(&self) -> AndroidAppWaker {
|
||||
self.inner.read().unwrap().create_waker()
|
||||
}
|
||||
|
||||
/// Returns a (cheaply clonable) reference to this application's [`ndk::configuration::Configuration`]
|
||||
/// Returns a **reference** to this application's [`ndk::configuration::Configuration`].
|
||||
///
|
||||
/// # Warning
|
||||
///
|
||||
/// The value held by this reference **will change** with every [`MainEvent::ConfigChanged`]
|
||||
/// event that is raised. You should **not** [`Clone`] this type to compare it against a
|
||||
/// "new" [`AndroidApp::config()`] when that event is raised, since both point to the same
|
||||
/// internal [`ndk::configuration::Configuration`] and will be identical.
|
||||
pub fn config(&self) -> ConfigurationRef {
|
||||
self.inner.read().unwrap().config()
|
||||
}
|
||||
@@ -618,24 +716,158 @@ impl AndroidApp {
|
||||
.hide_soft_input(hide_implicit_only);
|
||||
}
|
||||
|
||||
/// Query and process all out-standing input event
|
||||
/// Fetch the current input text state, as updated by any active IME.
|
||||
pub fn text_input_state(&self) -> input::TextInputState {
|
||||
self.inner.read().unwrap().text_input_state()
|
||||
}
|
||||
|
||||
/// Forward the given input text `state` to any active IME.
|
||||
pub fn set_text_input_state(&self, state: input::TextInputState) {
|
||||
self.inner.read().unwrap().set_text_input_state(state);
|
||||
}
|
||||
|
||||
/// Get an exclusive, lending iterator over buffered input events
|
||||
///
|
||||
/// `callback` should return [`InputStatus::Unhandled`] for any input events that aren't directly
|
||||
/// handled by the application, or else [`InputStatus::Handled`]. Unhandled events may lead to a
|
||||
/// fallback interpretation of the event.
|
||||
/// Applications are expected to call this in-sync with their rendering or
|
||||
/// in response to a [`MainEvent::InputAvailable`] event being delivered.
|
||||
///
|
||||
/// Applications are generally either expected to call this in-sync with their rendering or
|
||||
/// in response to a [`MainEvent::InputAvailable`] event being delivered. _Note though that your
|
||||
/// application is will only be delivered a single [`MainEvent::InputAvailable`] event between calls
|
||||
/// to this API._
|
||||
/// _**Note:** your application is will only be delivered a single
|
||||
/// [`MainEvent::InputAvailable`] event between calls to this API._
|
||||
///
|
||||
/// To reduce overhead, by default only [`input::Axis::X`] and [`input::Axis::Y`] are enabled
|
||||
/// To reduce overhead, by default, only [`input::Axis::X`] and [`input::Axis::Y`] are enabled
|
||||
/// and other axis should be enabled explicitly via [`Self::enable_motion_axis`].
|
||||
pub fn input_events<F>(&self, callback: F)
|
||||
where
|
||||
F: FnMut(&input::InputEvent) -> InputStatus,
|
||||
{
|
||||
self.inner.read().unwrap().input_events(callback)
|
||||
///
|
||||
/// This isn't the most ergonomic iteration API since we can't return a standard `Iterator`:
|
||||
/// - This API returns a lending iterator may borrow from the internal buffer
|
||||
/// of pending events without copying them.
|
||||
/// - For each event we want to ensure the application reports whether the
|
||||
/// event was handled.
|
||||
///
|
||||
/// # Example
|
||||
/// Code to iterate all pending input events would look something like this:
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use android_activity::{AndroidApp, InputStatus, input::InputEvent};
|
||||
/// # let app: AndroidApp = todo!();
|
||||
/// match app.input_events_iter() {
|
||||
/// Ok(mut iter) => {
|
||||
/// loop {
|
||||
/// let read_input = iter.next(|event| {
|
||||
/// let handled = match event {
|
||||
/// InputEvent::KeyEvent(key_event) => {
|
||||
/// // Snip
|
||||
/// InputStatus::Handled
|
||||
/// }
|
||||
/// InputEvent::MotionEvent(motion_event) => {
|
||||
/// InputStatus::Unhandled
|
||||
/// }
|
||||
/// event => {
|
||||
/// InputStatus::Unhandled
|
||||
/// }
|
||||
/// };
|
||||
///
|
||||
/// handled
|
||||
/// });
|
||||
///
|
||||
/// if !read_input {
|
||||
/// break;
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// Err(err) => {
|
||||
/// log::error!("Failed to get input events iterator: {err:?}");
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This must only be called from your `android_main()` thread and it may panic if called
|
||||
/// from another thread.
|
||||
pub fn input_events_iter(&self) -> Result<input::InputIterator<'_>> {
|
||||
let receiver = {
|
||||
let guard = self.inner.read().unwrap();
|
||||
guard.input_events_receiver()?
|
||||
};
|
||||
|
||||
Ok(input::InputIterator {
|
||||
inner: receiver.into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Lookup the [`KeyCharacterMap`] for the given input `device_id`
|
||||
///
|
||||
/// Use [`KeyCharacterMap::get`] to map key codes + meta state into unicode characters
|
||||
/// or dead keys that compose with the next key.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// Code to handle unicode character mapping as well as combining dead keys could look some thing like:
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use android_activity::{AndroidApp, input::{InputEvent, KeyEvent, KeyMapChar}};
|
||||
/// # let app: AndroidApp = todo!();
|
||||
/// # let key_event: KeyEvent = todo!();
|
||||
/// let mut combining_accent = None;
|
||||
/// // Snip
|
||||
///
|
||||
/// let combined_key_char = if let Ok(map) = app.device_key_character_map(key_event.device_id()) {
|
||||
/// match map.get(key_event.key_code(), key_event.meta_state()) {
|
||||
/// Ok(KeyMapChar::Unicode(unicode)) => {
|
||||
/// let combined_unicode = if let Some(accent) = combining_accent {
|
||||
/// match map.get_dead_char(accent, unicode) {
|
||||
/// Ok(Some(key)) => {
|
||||
/// println!("KeyEvent: Combined '{unicode}' with accent '{accent}' to give '{key}'");
|
||||
/// Some(key)
|
||||
/// }
|
||||
/// Ok(None) => None,
|
||||
/// Err(err) => {
|
||||
/// eprintln!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||
/// None
|
||||
/// }
|
||||
/// }
|
||||
/// } else {
|
||||
/// println!("KeyEvent: Pressed '{unicode}'");
|
||||
/// Some(unicode)
|
||||
/// };
|
||||
/// combining_accent = None;
|
||||
/// combined_unicode.map(|unicode| KeyMapChar::Unicode(unicode))
|
||||
/// }
|
||||
/// Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||
/// println!("KeyEvent: Pressed 'dead key' combining accent '{accent}'");
|
||||
/// combining_accent = Some(accent);
|
||||
/// Some(KeyMapChar::CombiningAccent(accent))
|
||||
/// }
|
||||
/// Ok(KeyMapChar::None) => {
|
||||
/// println!("KeyEvent: Pressed non-unicode key");
|
||||
/// combining_accent = None;
|
||||
/// None
|
||||
/// }
|
||||
/// Err(err) => {
|
||||
/// eprintln!("KeyEvent: Failed to get key map character: {err:?}");
|
||||
/// combining_accent = None;
|
||||
/// None
|
||||
/// }
|
||||
/// }
|
||||
/// } else {
|
||||
/// None
|
||||
/// };
|
||||
/// ```
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Since this API needs to use JNI internally to call into the Android JVM it may return
|
||||
/// a [`error::AppError::JavaError`] in case there is a spurious JNI error or an exception
|
||||
/// is caught.
|
||||
///
|
||||
/// This API should not be called with a `device_id` of `0`, since that indicates a non-physical
|
||||
/// device and will result in a [`error::AppError::JavaError`].
|
||||
pub fn device_key_character_map(&self, device_id: i32) -> Result<KeyCharacterMap> {
|
||||
Ok(self
|
||||
.inner
|
||||
.read()
|
||||
.unwrap()
|
||||
.device_key_character_map(device_id)?)
|
||||
}
|
||||
|
||||
/// The user-visible SDK version of the framework
|
||||
|
||||
@@ -3,22 +3,17 @@
|
||||
//! synchronization between the two threads.
|
||||
|
||||
use std::{
|
||||
ffi::{CStr, CString},
|
||||
fs::File,
|
||||
io::{BufRead, BufReader},
|
||||
ops::Deref,
|
||||
os::unix::prelude::{FromRawFd, RawFd},
|
||||
panic::catch_unwind,
|
||||
ptr::{self, NonNull},
|
||||
sync::{Arc, Condvar, Mutex, Weak},
|
||||
};
|
||||
|
||||
use log::Level;
|
||||
use jni::{objects::JObject, refs::Global, vm::AttachConfig};
|
||||
use ndk::{configuration::Configuration, input_queue::InputQueue, native_window::NativeWindow};
|
||||
|
||||
use crate::{
|
||||
util::android_log,
|
||||
util::{abort_on_panic, log_panic},
|
||||
util::{abort_on_panic, forward_stdio_to_logcat, init_android_main_thread, log_panic},
|
||||
ConfigurationRef,
|
||||
};
|
||||
|
||||
@@ -86,12 +81,14 @@ pub struct WaitableNativeActivityState {
|
||||
pub cond: Condvar,
|
||||
}
|
||||
|
||||
// SAFETY: ndk::NativeActivity is also SendSync.
|
||||
unsafe impl Send for WaitableNativeActivityState {}
|
||||
unsafe impl Sync for WaitableNativeActivityState {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NativeActivityGlue {
|
||||
pub inner: Arc<WaitableNativeActivityState>,
|
||||
}
|
||||
unsafe impl Send for NativeActivityGlue {}
|
||||
unsafe impl Sync for NativeActivityGlue {}
|
||||
|
||||
impl Deref for NativeActivityGlue {
|
||||
type Target = WaitableNativeActivityState;
|
||||
@@ -199,21 +196,35 @@ impl NativeActivityGlue {
|
||||
}
|
||||
}
|
||||
|
||||
/// The status of the native thread that's created to run
|
||||
/// `android_main`
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum NativeThreadState {
|
||||
/// The `android_main` thread hasn't been created yet
|
||||
Init,
|
||||
/// The `android_main` thread has been spawned and started running
|
||||
Running,
|
||||
/// The `android_main` thread has finished
|
||||
Stopped,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NativeActivityState {
|
||||
pub msg_read: libc::c_int,
|
||||
pub msg_write: libc::c_int,
|
||||
pub config: super::ConfigurationRef,
|
||||
pub config: ConfigurationRef,
|
||||
pub saved_state: Vec<u8>,
|
||||
pub input_queue: *mut ndk_sys::AInputQueue,
|
||||
pub window: Option<NativeWindow>,
|
||||
pub content_rect: ndk_sys::ARect,
|
||||
pub activity_state: State,
|
||||
pub destroy_requested: bool,
|
||||
pub running: bool,
|
||||
pub thread_state: NativeThreadState,
|
||||
pub app_has_saved_state: bool,
|
||||
|
||||
/// Set as soon as the Java main thread notifies us of an
|
||||
/// `onDestroyed` callback.
|
||||
pub destroyed: bool,
|
||||
pub redraw_needed: bool,
|
||||
pub pending_input_queue: *mut ndk_sys::AInputQueue,
|
||||
pub pending_window: Option<NativeWindow>,
|
||||
}
|
||||
@@ -303,8 +314,6 @@ impl Drop for WaitableNativeActivityState {
|
||||
unsafe {
|
||||
let mut guard = self.mutex.lock().unwrap();
|
||||
guard.detach_input_queue_from_looper();
|
||||
guard.destroyed = true;
|
||||
self.cond.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -329,8 +338,11 @@ impl WaitableNativeActivityState {
|
||||
}
|
||||
}
|
||||
|
||||
let saved_state = unsafe {
|
||||
std::slice::from_raw_parts(saved_state_in as *const u8, saved_state_size as _)
|
||||
let saved_state = if saved_state_in.is_null() {
|
||||
Vec::new()
|
||||
} else {
|
||||
unsafe { std::slice::from_raw_parts(saved_state_in as *const u8, saved_state_size) }
|
||||
.to_vec()
|
||||
};
|
||||
|
||||
let config = unsafe {
|
||||
@@ -350,16 +362,15 @@ impl WaitableNativeActivityState {
|
||||
msg_read: msgpipe[0],
|
||||
msg_write: msgpipe[1],
|
||||
config,
|
||||
saved_state: saved_state.into(),
|
||||
saved_state,
|
||||
input_queue: ptr::null_mut(),
|
||||
window: None,
|
||||
content_rect: Rect::empty().into(),
|
||||
activity_state: State::Init,
|
||||
destroy_requested: false,
|
||||
running: false,
|
||||
thread_state: NativeThreadState::Init,
|
||||
app_has_saved_state: false,
|
||||
destroyed: false,
|
||||
redraw_needed: false,
|
||||
pending_input_queue: ptr::null_mut(),
|
||||
pending_window: None,
|
||||
}),
|
||||
@@ -369,10 +380,11 @@ impl WaitableNativeActivityState {
|
||||
|
||||
pub fn notify_destroyed(&self) {
|
||||
let mut guard = self.mutex.lock().unwrap();
|
||||
guard.destroyed = true;
|
||||
|
||||
unsafe {
|
||||
guard.write_cmd(AppCmd::Destroy);
|
||||
while !guard.destroyed {
|
||||
while guard.thread_state != NativeThreadState::Stopped {
|
||||
guard = self.cond.wait(guard).unwrap();
|
||||
}
|
||||
|
||||
@@ -435,7 +447,9 @@ impl WaitableNativeActivityState {
|
||||
|
||||
guard.pending_input_queue = input_queue;
|
||||
guard.write_cmd(AppCmd::InputQueueChanged);
|
||||
while guard.input_queue != guard.pending_input_queue {
|
||||
while guard.thread_state == NativeThreadState::Running
|
||||
&& guard.input_queue != guard.pending_input_queue
|
||||
{
|
||||
guard = self.cond.wait(guard).unwrap();
|
||||
}
|
||||
guard.pending_input_queue = ptr::null_mut();
|
||||
@@ -456,7 +470,9 @@ impl WaitableNativeActivityState {
|
||||
if guard.pending_window.is_some() {
|
||||
guard.write_cmd(AppCmd::InitWindow);
|
||||
}
|
||||
while guard.window != guard.pending_window {
|
||||
while guard.thread_state == NativeThreadState::Running
|
||||
&& guard.window != guard.pending_window
|
||||
{
|
||||
guard = self.cond.wait(guard).unwrap();
|
||||
}
|
||||
guard.pending_window = None;
|
||||
@@ -480,7 +496,7 @@ impl WaitableNativeActivityState {
|
||||
};
|
||||
guard.write_cmd(cmd);
|
||||
|
||||
while guard.activity_state != state {
|
||||
while guard.thread_state == NativeThreadState::Running && guard.activity_state != state {
|
||||
guard = self.cond.wait(guard).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -493,7 +509,7 @@ impl WaitableNativeActivityState {
|
||||
// this to be None
|
||||
debug_assert!(!guard.app_has_saved_state, "SaveState request clash");
|
||||
guard.write_cmd(AppCmd::SaveState);
|
||||
while !guard.app_has_saved_state {
|
||||
while guard.thread_state == NativeThreadState::Running && !guard.app_has_saved_state {
|
||||
guard = self.cond.wait(guard).unwrap();
|
||||
}
|
||||
guard.app_has_saved_state = false;
|
||||
@@ -502,7 +518,7 @@ impl WaitableNativeActivityState {
|
||||
// given via a `malloc()` allocated pointer since it will automatically
|
||||
// `free()` the state after it has been converted to a buffer for the JVM.
|
||||
if !guard.saved_state.is_empty() {
|
||||
let saved_state_size = guard.saved_state.len() as _;
|
||||
let saved_state_size = guard.saved_state.len();
|
||||
let saved_state_src_ptr = guard.saved_state.as_ptr();
|
||||
unsafe {
|
||||
let saved_state = libc::malloc(saved_state_size);
|
||||
@@ -541,10 +557,18 @@ impl WaitableNativeActivityState {
|
||||
|
||||
pub fn notify_main_thread_running(&self) {
|
||||
let mut guard = self.mutex.lock().unwrap();
|
||||
guard.running = true;
|
||||
guard.thread_state = NativeThreadState::Running;
|
||||
self.cond.notify_one();
|
||||
}
|
||||
|
||||
pub fn notify_main_thread_stopped_running(&self) {
|
||||
let mut guard = self.mutex.lock().unwrap();
|
||||
guard.thread_state = NativeThreadState::Stopped;
|
||||
// Notify all waiters to unblock any Android callbacks that would otherwise be waiting
|
||||
// indefinitely for the now-stopped (!) main thread.
|
||||
self.cond.notify_all();
|
||||
}
|
||||
|
||||
pub unsafe fn pre_exec_cmd(
|
||||
&self,
|
||||
cmd: AppCmd,
|
||||
@@ -660,7 +684,7 @@ unsafe extern "C" fn on_resume(activity: *mut ndk_sys::ANativeActivity) {
|
||||
|
||||
unsafe extern "C" fn on_save_instance_state(
|
||||
activity: *mut ndk_sys::ANativeActivity,
|
||||
out_len: *mut ndk_sys::size_t,
|
||||
out_len: *mut usize,
|
||||
) -> *mut libc::c_void {
|
||||
abort_on_panic(|| {
|
||||
log::debug!("SaveInstanceState: {:p}\n", activity);
|
||||
@@ -668,7 +692,7 @@ unsafe extern "C" fn on_save_instance_state(
|
||||
let mut ret = ptr::null_mut();
|
||||
try_with_waitable_activity_ref(activity, |waitable_activity| {
|
||||
let (state, len) = waitable_activity.request_save_state();
|
||||
*out_len = len as ndk_sys::size_t;
|
||||
*out_len = len;
|
||||
ret = state
|
||||
});
|
||||
|
||||
@@ -808,42 +832,17 @@ unsafe extern "C" fn on_content_rect_changed(
|
||||
|
||||
/// This is the native entrypoint for our cdylib library that `ANativeActivity` will look for via `dlsym`
|
||||
#[no_mangle]
|
||||
#[allow(unused_unsafe)] // Otherwise rust 1.64 moans about using unsafe{} in unsafe functions
|
||||
extern "C" fn ANativeActivity_onCreate(
|
||||
activity: *mut ndk_sys::ANativeActivity,
|
||||
saved_state: *const libc::c_void,
|
||||
saved_state_size: libc::size_t,
|
||||
) {
|
||||
abort_on_panic(|| {
|
||||
// Maybe make this stdout/stderr redirection an optional / opt-in feature?...
|
||||
unsafe {
|
||||
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);
|
||||
std::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 _join_log_forwarder = forward_stdio_to_logcat();
|
||||
|
||||
log::trace!(
|
||||
eprintln!(
|
||||
"Creating: {:p}, saved_state = {:p}, save_state_size = {}",
|
||||
activity,
|
||||
saved_state,
|
||||
saved_state_size
|
||||
activity, saved_state, saved_state_size
|
||||
);
|
||||
|
||||
// Conceptually we associate a glue reference with the JVM main thread, and another
|
||||
@@ -857,62 +856,82 @@ extern "C" fn ANativeActivity_onCreate(
|
||||
// Note: we drop the thread handle which will detach the thread
|
||||
std::thread::spawn(move || {
|
||||
let activity: *mut ndk_sys::ANativeActivity = activity_ptr as *mut _;
|
||||
|
||||
let jvm = unsafe {
|
||||
let na = 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());
|
||||
}
|
||||
|
||||
jvm
|
||||
};
|
||||
|
||||
let app = AndroidApp::new(rust_glue.clone());
|
||||
|
||||
rust_glue.notify_main_thread_running();
|
||||
|
||||
unsafe {
|
||||
// We want to specifically catch any panic from the application's android_main
|
||||
// so we can finish + destroy the Activity gracefully via the JVM
|
||||
catch_unwind(|| {
|
||||
// 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);
|
||||
})
|
||||
.unwrap_or_else(|panic| log_panic(panic));
|
||||
|
||||
// Let JVM know that our Activity can be destroyed before detaching from the JVM
|
||||
//
|
||||
// "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"
|
||||
ndk_sys::ANativeActivity_finish(activity);
|
||||
|
||||
if let Some(detach_current_thread) = (*(*jvm)).DetachCurrentThread {
|
||||
detach_current_thread(jvm);
|
||||
}
|
||||
|
||||
ndk_context::release_android_context();
|
||||
}
|
||||
rust_glue_entry(rust_glue, activity);
|
||||
});
|
||||
|
||||
// Wait for thread to start.
|
||||
let mut guard = jvm_glue.mutex.lock().unwrap();
|
||||
while !guard.running {
|
||||
|
||||
// Don't specifically wait for `Running` just in case `android_main` returns
|
||||
// immediately and the state is set to `Stopped`
|
||||
while guard.thread_state == NativeThreadState::Init {
|
||||
guard = jvm_glue.cond.wait(guard).unwrap();
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn rust_glue_entry(rust_glue: NativeActivityGlue, activity: *mut ndk_sys::ANativeActivity) {
|
||||
abort_on_panic(|| {
|
||||
let (jvm, jni_activity) = unsafe {
|
||||
let jvm: *mut jni::sys::JavaVM = (*activity).vm.cast();
|
||||
let jni_activity: jni::sys::jobject = (*activity).clazz as _; // Completely bogus name; this is the _instance_ not class pointer
|
||||
ndk_context::initialize_android_context(jvm.cast(), jni_activity.cast());
|
||||
(jni::JavaVM::from_raw(jvm), jni_activity)
|
||||
};
|
||||
// Note: At this point we can assume jni::JavaVM::singleton is initialized
|
||||
|
||||
// Since this is a newly spawned thread then the JVM hasn't been attached to the
|
||||
// thread yet.
|
||||
//
|
||||
// For compatibility we attach before calling the applications main function to
|
||||
// allow it to assume the thread is attached before making JNI calls.
|
||||
jvm.attach_current_thread_with_config(
|
||||
|| AttachConfig::new().name("android_main"),
|
||||
Some(16),
|
||||
|env| -> jni::errors::Result<()> {
|
||||
// SAFETY: We know jni_activity is a valid JNI global ref to an Activity instance
|
||||
let jni_activity = unsafe { env.as_cast_raw::<Global<JObject>>(&jni_activity)? };
|
||||
|
||||
if let Err(err) = init_android_main_thread(&jvm, &jni_activity) {
|
||||
eprintln!(
|
||||
"Failed to name Java thread and set thread context class loader: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
let app = AndroidApp::new(rust_glue.clone(), jvm.clone());
|
||||
|
||||
rust_glue.notify_main_thread_running();
|
||||
|
||||
unsafe {
|
||||
// We want to specifically catch any panic from the application's android_main
|
||||
// so we can finish + destroy the Activity gracefully via the JVM
|
||||
catch_unwind(|| {
|
||||
// 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);
|
||||
})
|
||||
.unwrap_or_else(log_panic);
|
||||
|
||||
// Let JVM know that our Activity can be destroyed before detaching from the JVM
|
||||
//
|
||||
// "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"
|
||||
ndk_sys::ANativeActivity_finish(activity);
|
||||
|
||||
ndk_context::release_android_context();
|
||||
}
|
||||
|
||||
rust_glue.notify_main_thread_stopped_running();
|
||||
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.expect("Failed to attach thread to JVM");
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
pub use ndk::event::{
|
||||
Axis, ButtonState, EdgeFlags, KeyAction, KeyEventFlags, Keycode, MetaState, MotionAction,
|
||||
MotionEventFlags, Pointer, PointersIter,
|
||||
use crate::input::{
|
||||
Axis, Button, ButtonState, EdgeFlags, KeyAction, Keycode, MetaState, MotionAction,
|
||||
MotionEventFlags, Pointer, PointersIter, Source, ToolType,
|
||||
};
|
||||
|
||||
use crate::input::{Class, Source};
|
||||
|
||||
/// A motion event
|
||||
///
|
||||
/// For general discussion of motion events in Android, see [the relevant
|
||||
@@ -17,7 +15,7 @@ pub struct MotionEvent<'a> {
|
||||
ndk_event: ndk::event::MotionEvent,
|
||||
_lifetime: PhantomData<&'a ndk::event::MotionEvent>,
|
||||
}
|
||||
impl<'a> MotionEvent<'a> {
|
||||
impl MotionEvent<'_> {
|
||||
pub(crate) fn new(ndk_event: ndk::event::MotionEvent) -> Self {
|
||||
Self {
|
||||
ndk_event,
|
||||
@@ -34,18 +32,11 @@ impl<'a> MotionEvent<'a> {
|
||||
pub fn source(&self) -> Source {
|
||||
// XXX: we use `AInputEvent_getSource` directly (instead of calling
|
||||
// ndk_event.source()) since we have our own `Source` enum that we
|
||||
// share between backends, which may not exactly match the ndk crate's
|
||||
// `Source` enum.
|
||||
// share between backends, which may also capture unknown variants
|
||||
// added in new versions of Android.
|
||||
let source =
|
||||
unsafe { ndk_sys::AInputEvent_getSource(self.ndk_event.ptr().as_ptr()) as u32 };
|
||||
source.try_into().unwrap_or(Source::Unknown)
|
||||
}
|
||||
|
||||
/// Get the class of the event source.
|
||||
///
|
||||
#[inline]
|
||||
pub fn class(&self) -> Class {
|
||||
Class::from(self.source())
|
||||
source.into()
|
||||
}
|
||||
|
||||
/// Get the device id associated with the event.
|
||||
@@ -60,7 +51,26 @@ impl<'a> MotionEvent<'a> {
|
||||
/// See [the MotionEvent docs](https://developer.android.com/reference/android/view/MotionEvent#getActionMasked())
|
||||
#[inline]
|
||||
pub fn action(&self) -> MotionAction {
|
||||
self.ndk_event.action()
|
||||
// XXX: we use `AMotionEvent_getAction` directly since we have our own
|
||||
// `MotionAction` enum that we share between backends, which may also
|
||||
// capture unknown variants added in new versions of Android.
|
||||
let action =
|
||||
unsafe { ndk_sys::AMotionEvent_getAction(self.ndk_event.ptr().as_ptr()) as u32 }
|
||||
& ndk_sys::AMOTION_EVENT_ACTION_MASK;
|
||||
action.into()
|
||||
}
|
||||
|
||||
/// Returns which button has been modified during a press or release action.
|
||||
///
|
||||
/// For actions other than [`MotionAction::ButtonPress`] and
|
||||
/// [`MotionAction::ButtonRelease`] the returned value is undefined.
|
||||
///
|
||||
/// See [the MotionEvent docs](https://developer.android.com/reference/android/view/MotionEvent#getActionButton())
|
||||
#[inline]
|
||||
pub fn action_button(&self) -> Button {
|
||||
let action_button =
|
||||
unsafe { ndk_sys::AMotionEvent_getActionButton(self.ndk_event.ptr().as_ptr()) as u32 };
|
||||
action_button.into()
|
||||
}
|
||||
|
||||
/// Returns the pointer index of an `Up` or `Down` event.
|
||||
@@ -99,7 +109,11 @@ impl<'a> MotionEvent<'a> {
|
||||
/// An iterator over the pointers in this motion event
|
||||
#[inline]
|
||||
pub fn pointers(&self) -> PointersIter<'_> {
|
||||
self.ndk_event.pointers()
|
||||
PointersIter {
|
||||
inner: PointersIterImpl {
|
||||
ndk_pointers_iter: self.ndk_event.pointers(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The pointer at a given pointer index. Panics if the pointer index is out of bounds.
|
||||
@@ -107,7 +121,11 @@ impl<'a> MotionEvent<'a> {
|
||||
/// If you need to loop over all the pointers, prefer the [`pointers()`](Self::pointers) method.
|
||||
#[inline]
|
||||
pub fn pointer_at_index(&self, index: usize) -> Pointer<'_> {
|
||||
self.ndk_event.pointer_at_index(index)
|
||||
Pointer {
|
||||
inner: PointerImpl {
|
||||
ndk_pointer: self.ndk_event.pointer_at_index(index),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -136,7 +154,7 @@ impl<'a> MotionEvent<'a> {
|
||||
/// docs](https://developer.android.com/ndk/reference/group/input#amotionevent_getmetastate)
|
||||
#[inline]
|
||||
pub fn meta_state(&self) -> MetaState {
|
||||
self.ndk_event.meta_state()
|
||||
self.ndk_event.meta_state().into()
|
||||
}
|
||||
|
||||
/// Returns the button state during this event, as a bitfield.
|
||||
@@ -145,7 +163,7 @@ impl<'a> MotionEvent<'a> {
|
||||
/// docs](https://developer.android.com/ndk/reference/group/input#amotionevent_getbuttonstate)
|
||||
#[inline]
|
||||
pub fn button_state(&self) -> ButtonState {
|
||||
self.ndk_event.button_state()
|
||||
self.ndk_event.button_state().into()
|
||||
}
|
||||
|
||||
/// Returns the time of the start of this gesture, in the `java.lang.System.nanoTime()` time
|
||||
@@ -164,7 +182,7 @@ impl<'a> MotionEvent<'a> {
|
||||
/// docs](https://developer.android.com/ndk/reference/group/input#amotionevent_getedgeflags)
|
||||
#[inline]
|
||||
pub fn edge_flags(&self) -> EdgeFlags {
|
||||
self.ndk_event.edge_flags()
|
||||
self.ndk_event.edge_flags().into()
|
||||
}
|
||||
|
||||
/// Returns the time of this event, in the `java.lang.System.nanoTime()` time base
|
||||
@@ -182,7 +200,7 @@ impl<'a> MotionEvent<'a> {
|
||||
/// docs](https://developer.android.com/ndk/reference/group/input#amotionevent_getflags)
|
||||
#[inline]
|
||||
pub fn flags(&self) -> MotionEventFlags {
|
||||
self.ndk_event.flags()
|
||||
self.ndk_event.flags().into()
|
||||
}
|
||||
|
||||
/* Missing from GameActivity currently...
|
||||
@@ -224,6 +242,73 @@ impl<'a> MotionEvent<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A view into the data of a specific pointer in a motion event.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PointerImpl<'a> {
|
||||
ndk_pointer: ndk::event::Pointer<'a>,
|
||||
}
|
||||
|
||||
impl PointerImpl<'_> {
|
||||
#[inline]
|
||||
pub fn pointer_index(&self) -> usize {
|
||||
self.ndk_pointer.pointer_index()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn pointer_id(&self) -> i32 {
|
||||
self.ndk_pointer.pointer_id()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn axis_value(&self, axis: Axis) -> f32 {
|
||||
let value: u32 = axis.into();
|
||||
let value = value as i32;
|
||||
self.ndk_pointer.axis_value(value.into())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn raw_x(&self) -> f32 {
|
||||
self.ndk_pointer.raw_x()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn raw_y(&self) -> f32 {
|
||||
self.ndk_pointer.raw_y()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn tool_type(&self) -> ToolType {
|
||||
let value: i32 = self.ndk_pointer.tool_type().into();
|
||||
let value = value as u32;
|
||||
value.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator over the pointers in a [`MotionEvent`].
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PointersIterImpl<'a> {
|
||||
ndk_pointers_iter: ndk::event::PointersIter<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Iterator for PointersIterImpl<'a> {
|
||||
type Item = Pointer<'a>;
|
||||
fn next(&mut self) -> Option<Pointer<'a>> {
|
||||
self.ndk_pointers_iter.next().map(|ndk_pointer| Pointer {
|
||||
inner: PointerImpl { ndk_pointer },
|
||||
})
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.ndk_pointers_iter.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for PointersIterImpl<'_> {
|
||||
fn len(&self) -> usize {
|
||||
self.ndk_pointers_iter.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// A key event
|
||||
///
|
||||
/// For general discussion of key events in Android, see [the relevant
|
||||
@@ -234,7 +319,7 @@ pub struct KeyEvent<'a> {
|
||||
ndk_event: ndk::event::KeyEvent,
|
||||
_lifetime: PhantomData<&'a ndk::event::KeyEvent>,
|
||||
}
|
||||
impl<'a> KeyEvent<'a> {
|
||||
impl KeyEvent<'_> {
|
||||
pub(crate) fn new(ndk_event: ndk::event::KeyEvent) -> Self {
|
||||
Self {
|
||||
ndk_event,
|
||||
@@ -251,18 +336,11 @@ impl<'a> KeyEvent<'a> {
|
||||
pub fn source(&self) -> Source {
|
||||
// XXX: we use `AInputEvent_getSource` directly (instead of calling
|
||||
// ndk_event.source()) since we have our own `Source` enum that we
|
||||
// share between backends, which may not exactly match the ndk crate's
|
||||
// `Source` enum.
|
||||
// share between backends, which may also capture unknown variants
|
||||
// added in new versions of Android.
|
||||
let source =
|
||||
unsafe { ndk_sys::AInputEvent_getSource(self.ndk_event.ptr().as_ptr()) as u32 };
|
||||
source.try_into().unwrap_or(Source::Unknown)
|
||||
}
|
||||
|
||||
/// Get the class of the event source.
|
||||
///
|
||||
#[inline]
|
||||
pub fn class(&self) -> Class {
|
||||
Class::from(self.source())
|
||||
source.into()
|
||||
}
|
||||
|
||||
/// Get the device id associated with the event.
|
||||
@@ -277,7 +355,11 @@ impl<'a> KeyEvent<'a> {
|
||||
/// See [the KeyEvent docs](https://developer.android.com/reference/android/view/KeyEvent#getAction())
|
||||
#[inline]
|
||||
pub fn action(&self) -> KeyAction {
|
||||
self.ndk_event.action()
|
||||
// XXX: we use `AInputEvent_getAction` directly since we have our own
|
||||
// `KeyAction` enum that we share between backends, which may also
|
||||
// capture unknown variants added in new versions of Android.
|
||||
let action = unsafe { ndk_sys::AKeyEvent_getAction(self.ndk_event.ptr().as_ptr()) as u32 };
|
||||
action.into()
|
||||
}
|
||||
|
||||
/// Returns the last time the key was pressed. This is on the scale of
|
||||
@@ -306,7 +388,12 @@ impl<'a> KeyEvent<'a> {
|
||||
/// docs](https://developer.android.com/ndk/reference/group/input#akeyevent_getkeycode)
|
||||
#[inline]
|
||||
pub fn key_code(&self) -> Keycode {
|
||||
self.ndk_event.key_code()
|
||||
// XXX: we use `AInputEvent_getKeyCode` directly since we have our own
|
||||
// `Keycode` enum that we share between backends, which may also
|
||||
// capture unknown variants added in new versions of Android.
|
||||
let keycode =
|
||||
unsafe { ndk_sys::AKeyEvent_getKeyCode(self.ndk_event.ptr().as_ptr()) as u32 };
|
||||
keycode.into()
|
||||
}
|
||||
|
||||
/// Returns the number of repeats of a key.
|
||||
@@ -326,6 +413,15 @@ impl<'a> KeyEvent<'a> {
|
||||
pub fn scan_code(&self) -> i32 {
|
||||
self.ndk_event.scan_code()
|
||||
}
|
||||
|
||||
/// Returns the state of the modifiers during this key event, represented by a bitmask.
|
||||
///
|
||||
/// See [the NDK
|
||||
/// docs](https://developer.android.com/ndk/reference/group/input#akeyevent_getmetastate)
|
||||
#[inline]
|
||||
pub fn meta_state(&self) -> MetaState {
|
||||
self.ndk_event.meta_state().into()
|
||||
}
|
||||
}
|
||||
|
||||
// We use our own wrapper type for input events to have better consistency
|
||||
@@ -337,4 +433,6 @@ impl<'a> KeyEvent<'a> {
|
||||
pub enum InputEvent<'a> {
|
||||
MotionEvent(self::MotionEvent<'a>),
|
||||
KeyEvent(self::KeyEvent<'a>),
|
||||
TextEvent(crate::input::TextInputState),
|
||||
TextAction(crate::input::TextInputAction),
|
||||
}
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
#![cfg(any(feature = "native-activity", doc))]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::ptr;
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::sync::{Arc, Mutex, RwLock, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use jni::JavaVM;
|
||||
use libc::c_void;
|
||||
use log::{error, trace};
|
||||
use ndk::input_queue::InputQueue;
|
||||
use ndk::{asset::AssetManager, native_window::NativeWindow};
|
||||
|
||||
use crate::error::InternalResult;
|
||||
use crate::input::{device_key_character_map, Axis, KeyCharacterMap};
|
||||
use crate::input::{TextInputState, TextSpan};
|
||||
use crate::{
|
||||
util, AndroidApp, ConfigurationRef, InputStatus, MainEvent, PollEvent, Rect, WindowManagerFlags,
|
||||
};
|
||||
@@ -45,7 +51,7 @@ impl<'a> StateSaver<'a> {
|
||||
pub struct StateLoader<'a> {
|
||||
app: &'a AndroidAppInner,
|
||||
}
|
||||
impl<'a> StateLoader<'a> {
|
||||
impl StateLoader<'_> {
|
||||
/// Returns whatever state was saved during the last [MainEvent::SaveState] event or `None`
|
||||
pub fn load(&self) -> Option<Vec<u8>> {
|
||||
self.app.native_activity.saved_state()
|
||||
@@ -78,37 +84,47 @@ impl AndroidAppWaker {
|
||||
}
|
||||
|
||||
impl AndroidApp {
|
||||
pub(crate) fn new(native_activity: NativeActivityGlue) -> Self {
|
||||
let app = Self {
|
||||
inner: Arc::new(RwLock::new(AndroidAppInner {
|
||||
native_activity,
|
||||
looper: Looper {
|
||||
ptr: ptr::null_mut(),
|
||||
},
|
||||
})),
|
||||
};
|
||||
pub(crate) fn new(native_activity: NativeActivityGlue, jvm: JavaVM) -> Self {
|
||||
jvm.with_local_frame(10, |env| -> jni::errors::Result<_> {
|
||||
if let Err(err) = crate::input::jni_init(env) {
|
||||
panic!("Failed to init JNI bindings: {err:?}");
|
||||
};
|
||||
|
||||
{
|
||||
let mut guard = app.inner.write().unwrap();
|
||||
let app = Self {
|
||||
inner: Arc::new(RwLock::new(AndroidAppInner {
|
||||
jvm: jvm.clone(),
|
||||
native_activity,
|
||||
looper: Looper {
|
||||
ptr: ptr::null_mut(),
|
||||
},
|
||||
key_maps: Mutex::new(HashMap::new()),
|
||||
input_receiver: Mutex::new(None),
|
||||
})),
|
||||
};
|
||||
|
||||
let main_fd = guard.native_activity.cmd_read_fd();
|
||||
unsafe {
|
||||
guard.looper.ptr = ndk_sys::ALooper_prepare(
|
||||
ndk_sys::ALOOPER_PREPARE_ALLOW_NON_CALLBACKS as libc::c_int,
|
||||
);
|
||||
ndk_sys::ALooper_addFd(
|
||||
guard.looper.ptr,
|
||||
main_fd,
|
||||
LOOPER_ID_MAIN,
|
||||
ndk_sys::ALOOPER_EVENT_INPUT as libc::c_int,
|
||||
None,
|
||||
//&mut guard.cmd_poll_source as *mut _ as *mut _);
|
||||
ptr::null_mut(),
|
||||
);
|
||||
{
|
||||
let mut guard = app.inner.write().unwrap();
|
||||
|
||||
let main_fd = guard.native_activity.cmd_read_fd();
|
||||
unsafe {
|
||||
guard.looper.ptr = ndk_sys::ALooper_prepare(
|
||||
ndk_sys::ALOOPER_PREPARE_ALLOW_NON_CALLBACKS as libc::c_int,
|
||||
);
|
||||
ndk_sys::ALooper_addFd(
|
||||
guard.looper.ptr,
|
||||
main_fd,
|
||||
LOOPER_ID_MAIN,
|
||||
ndk_sys::ALOOPER_EVENT_INPUT as libc::c_int,
|
||||
None,
|
||||
//&mut guard.cmd_poll_source as *mut _ as *mut _);
|
||||
ptr::null_mut(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app
|
||||
Ok(app)
|
||||
})
|
||||
.expect("Failed to create AndroidApp instance")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,8 +137,20 @@ unsafe impl Sync for Looper {}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AndroidAppInner {
|
||||
pub(crate) jvm: JavaVM,
|
||||
|
||||
pub(crate) native_activity: NativeActivityGlue,
|
||||
looper: Looper,
|
||||
|
||||
/// A table of `KeyCharacterMap`s per `InputDevice` ID
|
||||
/// these are used to be able to map key presses to unicode
|
||||
/// characters
|
||||
key_maps: Mutex<HashMap<i32, KeyCharacterMap>>,
|
||||
|
||||
/// While an app is reading input events it holds an
|
||||
/// InputReceiver reference which we track to ensure
|
||||
/// we don't hand out more than one receiver at a time
|
||||
input_receiver: Mutex<Option<Weak<InputReceiver>>>,
|
||||
}
|
||||
|
||||
impl AndroidAppInner {
|
||||
@@ -149,14 +177,14 @@ impl AndroidAppInner {
|
||||
|
||||
pub fn poll_events<F>(&self, timeout: Option<Duration>, mut callback: F)
|
||||
where
|
||||
F: FnMut(PollEvent),
|
||||
F: FnMut(PollEvent<'_>),
|
||||
{
|
||||
trace!("poll_events");
|
||||
|
||||
unsafe {
|
||||
let mut fd: i32 = 0;
|
||||
let mut events: i32 = 0;
|
||||
let mut source: *mut core::ffi::c_void = ptr::null_mut();
|
||||
let mut source: *mut c_void = ptr::null_mut();
|
||||
|
||||
let timeout_milliseconds = if let Some(timeout) = timeout {
|
||||
timeout.as_millis() as i32
|
||||
@@ -165,15 +193,16 @@ impl AndroidAppInner {
|
||||
};
|
||||
|
||||
trace!("Calling ALooper_pollAll, timeout = {timeout_milliseconds}");
|
||||
assert!(
|
||||
!ndk_sys::ALooper_forThread().is_null(),
|
||||
assert_eq!(
|
||||
ndk_sys::ALooper_forThread(),
|
||||
self.looper.ptr,
|
||||
"Application tried to poll events from non-main thread"
|
||||
);
|
||||
let id = ndk_sys::ALooper_pollAll(
|
||||
timeout_milliseconds,
|
||||
&mut fd,
|
||||
&mut events,
|
||||
&mut source as *mut *mut core::ffi::c_void,
|
||||
&mut source as *mut *mut c_void,
|
||||
);
|
||||
trace!("pollAll id = {id}");
|
||||
match id {
|
||||
@@ -341,59 +370,67 @@ impl AndroidAppInner {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enable_motion_axis(&self, _axis: input::Axis) {
|
||||
// TODO: move into a trait
|
||||
pub fn text_input_state(&self) -> TextInputState {
|
||||
TextInputState {
|
||||
text: String::new(),
|
||||
selection: TextSpan { start: 0, end: 0 },
|
||||
compose_region: None,
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move into a trait
|
||||
pub fn set_text_input_state(&self, _state: TextInputState) {
|
||||
// NOP: Unsupported
|
||||
}
|
||||
|
||||
pub fn device_key_character_map(&self, device_id: i32) -> InternalResult<KeyCharacterMap> {
|
||||
let mut guard = self.key_maps.lock().unwrap();
|
||||
|
||||
let key_map = match guard.entry(device_id) {
|
||||
std::collections::hash_map::Entry::Occupied(occupied) => occupied.get().clone(),
|
||||
std::collections::hash_map::Entry::Vacant(vacant) => {
|
||||
let character_map = device_key_character_map(self.jvm.clone(), device_id)?;
|
||||
vacant.insert(character_map.clone());
|
||||
character_map
|
||||
}
|
||||
};
|
||||
|
||||
Ok(key_map)
|
||||
}
|
||||
|
||||
pub fn enable_motion_axis(&self, _axis: Axis) {
|
||||
// NOP - The InputQueue API doesn't let us optimize which axis values are read
|
||||
}
|
||||
|
||||
pub fn disable_motion_axis(&self, _axis: input::Axis) {
|
||||
pub fn disable_motion_axis(&self, _axis: Axis) {
|
||||
// NOP - The InputQueue API doesn't let us optimize which axis values are read
|
||||
}
|
||||
|
||||
pub fn input_events<F>(&self, mut callback: F)
|
||||
where
|
||||
F: FnMut(&input::InputEvent) -> InputStatus,
|
||||
{
|
||||
pub fn input_events_receiver(&self) -> InternalResult<Arc<InputReceiver>> {
|
||||
let mut guard = self.input_receiver.lock().unwrap();
|
||||
|
||||
if let Some(receiver) = &*guard {
|
||||
if receiver.strong_count() > 0 {
|
||||
return Err(crate::error::InternalAppError::InputUnavailable);
|
||||
}
|
||||
}
|
||||
*guard = None;
|
||||
|
||||
// Get the InputQueue for the NativeActivity (if there is one) and also ensure
|
||||
// the queue is re-attached to our event Looper (so new input events will again
|
||||
// trigger a wake up)
|
||||
let queue = self
|
||||
.native_activity
|
||||
.looper_attached_input_queue(self.looper(), LOOPER_ID_INPUT);
|
||||
let queue = match queue {
|
||||
Some(queue) => queue,
|
||||
None => return,
|
||||
};
|
||||
|
||||
// Note: we basically ignore errors from get_event() currently. Looking
|
||||
// at the source code for Android's InputQueue, the only error that
|
||||
// can be returned here is 'WOULD_BLOCK', which we want to just treat as
|
||||
// meaning the queue is empty.
|
||||
//
|
||||
// ref: https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/jni/android_view_InputQueue.cpp
|
||||
//
|
||||
while let Ok(Some(event)) = queue.get_event() {
|
||||
if let Some(ndk_event) = queue.pre_dispatch(event) {
|
||||
let event = match ndk_event {
|
||||
ndk::event::InputEvent::MotionEvent(e) => {
|
||||
input::InputEvent::MotionEvent(input::MotionEvent::new(e))
|
||||
}
|
||||
ndk::event::InputEvent::KeyEvent(e) => {
|
||||
input::InputEvent::KeyEvent(input::KeyEvent::new(e))
|
||||
}
|
||||
};
|
||||
let handled = callback(&event);
|
||||
// Note: we don't treat it as an error if there is no queue, so if applications
|
||||
// iterate input before a queue has been created (e.g. before onStart) then
|
||||
// it will simply behave like there are no events available currently.
|
||||
let receiver = Arc::new(InputReceiver { queue });
|
||||
|
||||
let ndk_event = match event {
|
||||
input::InputEvent::MotionEvent(e) => {
|
||||
ndk::event::InputEvent::MotionEvent(e.into_ndk_event())
|
||||
}
|
||||
input::InputEvent::KeyEvent(e) => {
|
||||
ndk::event::InputEvent::KeyEvent(e.into_ndk_event())
|
||||
}
|
||||
};
|
||||
queue.finish_event(ndk_event, matches!(handled, InputStatus::Handled));
|
||||
}
|
||||
}
|
||||
*guard = Some(Arc::downgrade(&receiver));
|
||||
Ok(receiver)
|
||||
}
|
||||
|
||||
pub fn internal_data_path(&self) -> Option<std::path::PathBuf> {
|
||||
@@ -411,3 +448,88 @@ impl AndroidAppInner {
|
||||
unsafe { util::try_get_path_from_ptr((*na).obbPath) }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct InputReceiver {
|
||||
queue: Option<InputQueue>,
|
||||
}
|
||||
|
||||
impl From<Arc<InputReceiver>> for InputIteratorInner<'_> {
|
||||
fn from(receiver: Arc<InputReceiver>) -> Self {
|
||||
Self {
|
||||
receiver,
|
||||
_lifetime: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct InputIteratorInner<'a> {
|
||||
// Held to maintain exclusive access to buffered input events
|
||||
receiver: Arc<InputReceiver>,
|
||||
_lifetime: PhantomData<&'a ()>,
|
||||
}
|
||||
|
||||
impl InputIteratorInner<'_> {
|
||||
pub(crate) fn next<F>(&self, callback: F) -> bool
|
||||
where
|
||||
F: FnOnce(&input::InputEvent) -> InputStatus,
|
||||
{
|
||||
let Some(queue) = &self.receiver.queue else {
|
||||
log::trace!("no queue available for events");
|
||||
return false;
|
||||
};
|
||||
|
||||
// Note: we basically ignore errors from event() currently. Looking at the source code for
|
||||
// Android's InputQueue, the only error that can be returned here is 'WOULD_BLOCK', which we
|
||||
// want to just treat as meaning the queue is empty.
|
||||
//
|
||||
// ref: https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/jni/android_view_InputQueue.cpp
|
||||
//
|
||||
if let Ok(Some(ndk_event)) = queue.event() {
|
||||
log::trace!("queue: got event: {ndk_event:?}");
|
||||
|
||||
if let Some(ndk_event) = queue.pre_dispatch(ndk_event) {
|
||||
let event = match ndk_event {
|
||||
ndk::event::InputEvent::MotionEvent(e) => {
|
||||
input::InputEvent::MotionEvent(input::MotionEvent::new(e))
|
||||
}
|
||||
ndk::event::InputEvent::KeyEvent(e) => {
|
||||
input::InputEvent::KeyEvent(input::KeyEvent::new(e))
|
||||
}
|
||||
_ => todo!("NDK added a new type"),
|
||||
};
|
||||
|
||||
// `finish_event` needs to be called for each event otherwise
|
||||
// the app would likely get an ANR
|
||||
let result = std::panic::catch_unwind(AssertUnwindSafe(|| callback(&event)));
|
||||
|
||||
let ndk_event = match event {
|
||||
input::InputEvent::MotionEvent(e) => {
|
||||
ndk::event::InputEvent::MotionEvent(e.into_ndk_event())
|
||||
}
|
||||
input::InputEvent::KeyEvent(e) => {
|
||||
ndk::event::InputEvent::KeyEvent(e.into_ndk_event())
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let handled = match result {
|
||||
Ok(handled) => handled,
|
||||
Err(payload) => {
|
||||
log::error!("Calling `finish_event` after panic in input event handler, to try and avoid being killed via an ANR");
|
||||
queue.finish_event(ndk_event, false);
|
||||
std::panic::resume_unwind(payload);
|
||||
}
|
||||
};
|
||||
|
||||
log::trace!("queue: finishing event");
|
||||
queue.finish_event(ndk_event, handled == InputStatus::Handled);
|
||||
}
|
||||
|
||||
true
|
||||
} else {
|
||||
log::trace!("queue: no more events");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
use log::Level;
|
||||
use jni::{
|
||||
jni_str,
|
||||
objects::{JObject, JString, JThread},
|
||||
vm::JavaVM,
|
||||
};
|
||||
use log::{error, Level};
|
||||
use std::{
|
||||
ffi::{CStr, CString},
|
||||
os::raw::c_char,
|
||||
fs::File,
|
||||
io::{BufRead as _, BufReader, Result},
|
||||
os::{
|
||||
fd::{FromRawFd as _, RawFd},
|
||||
raw::c_char,
|
||||
},
|
||||
};
|
||||
|
||||
pub fn try_get_path_from_ptr(path: *const c_char) -> Option<std::path::PathBuf> {
|
||||
@@ -31,6 +41,44 @@ pub(crate) fn android_log(level: Level, tag: &CStr, msg: &CStr) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn forward_stdio_to_logcat() -> std::thread::JoinHandle<Result<()>> {
|
||||
// XXX: make this stdout/stderr redirection an optional / opt-in feature?...
|
||||
|
||||
let file = unsafe {
|
||||
let mut logpipe: [RawFd; 2] = Default::default();
|
||||
libc::pipe2(logpipe.as_mut_ptr(), libc::O_CLOEXEC);
|
||||
libc::dup2(logpipe[1], libc::STDOUT_FILENO);
|
||||
libc::dup2(logpipe[1], libc::STDERR_FILENO);
|
||||
libc::close(logpipe[1]);
|
||||
|
||||
File::from_raw_fd(logpipe[0])
|
||||
};
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("stdio-to-logcat".to_string())
|
||||
.spawn(move || -> Result<()> {
|
||||
let tag = CStr::from_bytes_with_nul(b"RustStdoutStderr\0").unwrap();
|
||||
let mut reader = BufReader::new(file);
|
||||
let mut buffer = String::new();
|
||||
loop {
|
||||
buffer.clear();
|
||||
let len = match reader.read_line(&mut buffer) {
|
||||
Ok(len) => len,
|
||||
Err(e) => {
|
||||
error!("Logcat forwarder failed to read stdin/stderr: {e:?}");
|
||||
break Err(e);
|
||||
}
|
||||
};
|
||||
if len == 0 {
|
||||
break Ok(());
|
||||
} else if let Ok(msg) = CString::new(buffer.clone()) {
|
||||
android_log(Level::Info, tag, &msg);
|
||||
}
|
||||
}
|
||||
})
|
||||
.expect("Failed to start stdout/stderr to logcat forwarder thread")
|
||||
}
|
||||
|
||||
pub(crate) fn log_panic(panic: Box<dyn std::any::Any + Send>) {
|
||||
let rust_panic = unsafe { CStr::from_bytes_with_nul_unchecked(b"RustPanic\0") };
|
||||
|
||||
@@ -68,3 +116,29 @@ pub(crate) fn abort_on_panic<R>(f: impl FnOnce() -> R) -> R {
|
||||
std::process::abort();
|
||||
})
|
||||
}
|
||||
|
||||
/// Name the Java Thread + native thread "android_main" and set the Java Thread context class loader
|
||||
/// so that jni code can more-easily find non-system Java classes.
|
||||
pub(crate) fn init_android_main_thread(
|
||||
vm: &JavaVM,
|
||||
jni_activity: &JObject,
|
||||
) -> jni::errors::Result<()> {
|
||||
vm.with_local_frame(10, |env| -> jni::errors::Result<()> {
|
||||
let activity_class = env.get_object_class(jni_activity)?;
|
||||
let class_loader = activity_class.get_class_loader(env)?;
|
||||
|
||||
let thread = JThread::current_thread(env)?;
|
||||
thread.set_context_class_loader(env, &class_loader)?;
|
||||
let thread_name = JString::from_jni_str(env, jni_str!("android_main"))?;
|
||||
thread.set_name(env, &thread_name)?;
|
||||
|
||||
// Also name native thread - this needs to happen here after attaching to a JVM thread,
|
||||
// since that changes the thread name to something like "Thread-2".
|
||||
unsafe {
|
||||
let thread_name = std::ffi::CStr::from_bytes_with_nul(b"android_main\0").unwrap();
|
||||
let _ = libc::pthread_setname_np(libc::pthread_self(), thread_name.as_ptr());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
*.iml
|
||||
.idea
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/caches
|
||||
/.idea/libraries
|
||||
/.idea/modules.xml
|
||||
/.idea/workspace.xml
|
||||
/.idea/navEditor.xml
|
||||
/.idea/assetWizardSettings.xml
|
||||
/.idea
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
|
||||
Generated
-3
@@ -1,3 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="11" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-19
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="testRunner" value="GRADLE" />
|
||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/app" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-9
@@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="Android Studio default JDK" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
<component name="ProjectType">
|
||||
<option name="id" value="Android" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-7
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -9,9 +9,12 @@ edition = "2021"
|
||||
log = "0.4"
|
||||
android_logger = "0.11.0"
|
||||
android-activity = { path="../../android-activity", features = ["game-activity"] }
|
||||
ndk-sys = "0.4"
|
||||
ndk = "0.7"
|
||||
ndk-sys = "0.6.0"
|
||||
ndk = "0.9.0"
|
||||
|
||||
[lib]
|
||||
name="main"
|
||||
crate_type=["cdylib"]
|
||||
crate_type=["cdylib"]
|
||||
|
||||
[patch.crates-io]
|
||||
jni = { git = "https://github.com/jni-rs/jni-rs.git", branch = "release-0.22" }
|
||||
@@ -12,8 +12,6 @@ android {
|
||||
targetSdk 31
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
@@ -38,12 +36,10 @@ android {
|
||||
|
||||
dependencies {
|
||||
|
||||
implementation 'androidx.appcompat:appcompat:1.4.1'
|
||||
implementation 'com.google.android.material:material:1.5.0'
|
||||
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
|
||||
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
|
||||
implementation "androidx.core:core:1.5.0"
|
||||
implementation "androidx.constraintlayout:constraintlayout:2.0.4"
|
||||
implementation 'androidx.fragment:fragment:1.2.5'
|
||||
implementation 'com.google.oboe:oboe:1.5.0'
|
||||
|
||||
// To use the Android Frame Pacing library
|
||||
//implementation "androidx.games:games-frame-pacing:1.9.1"
|
||||
@@ -52,12 +48,12 @@ dependencies {
|
||||
//implementation "androidx.games:games-performance-tuner:1.5.0"
|
||||
|
||||
// To use the Games Activity library
|
||||
implementation "androidx.games:games-activity:1.1.0"
|
||||
implementation "androidx.games:games-activity:4.0.0"
|
||||
|
||||
// To use the Games Controller Library
|
||||
//implementation "androidx.games:games-controller:1.1.0"
|
||||
//implementation "androidx.games:games-controller:2.0.2"
|
||||
|
||||
// To use the Games Text Input Library
|
||||
//implementation "androidx.games:games-text-input:1.1.0"
|
||||
//implementation "androidx.games:games-text-input:2.0.2"
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,11 @@ public class MainActivity extends GameActivity {
|
||||
super.onCreate(savedInstanceState);
|
||||
}
|
||||
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
hideSystemUI();
|
||||
}
|
||||
|
||||
public boolean isGooglePlayGames() {
|
||||
PackageManager pm = getPackageManager();
|
||||
return pm.hasSystemFeature("com.google.android.play.feature.HPE_EXPERIENCE");
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Hello World!"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintLeft_toLeftOf="parent"
|
||||
app:layout_constraintRight_toRightOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
@@ -1,16 +0,0 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.RustTemplate" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
||||
<!-- Primary brand color. -->
|
||||
<item name="colorPrimary">@color/purple_200</item>
|
||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
||||
<item name="colorOnPrimary">@color/black</item>
|
||||
<!-- Secondary brand color. -->
|
||||
<item name="colorSecondary">@color/teal_200</item>
|
||||
<item name="colorSecondaryVariant">@color/teal_200</item>
|
||||
<item name="colorOnSecondary">@color/black</item>
|
||||
<!-- Status bar color. -->
|
||||
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,16 +1,3 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.RustTemplate" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
|
||||
<!-- Primary brand color. -->
|
||||
<item name="colorPrimary">@color/purple_500</item>
|
||||
<item name="colorPrimaryVariant">@color/purple_700</item>
|
||||
<item name="colorOnPrimary">@color/white</item>
|
||||
<!-- Secondary brand color. -->
|
||||
<item name="colorSecondary">@color/teal_200</item>
|
||||
<item name="colorSecondaryVariant">@color/teal_700</item>
|
||||
<item name="colorOnSecondary">@color/black</item>
|
||||
<!-- Status bar color. -->
|
||||
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
<resources xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<style name="Theme.RustTemplate" parent="Theme.AppCompat.Light.NoActionBar" />
|
||||
</resources>
|
||||
@@ -1,6 +1,6 @@
|
||||
#Mon May 02 15:39:12 BST 2022
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
|
||||
distributionPath=wrapper/dists
|
||||
zipStorePath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use android_activity::{AndroidApp, InputStatus, MainEvent, PollEvent};
|
||||
use android_activity::{
|
||||
input::{InputEvent, KeyAction, KeyEvent, KeyMapChar, MotionAction},
|
||||
AndroidApp, InputStatus, MainEvent, PollEvent,
|
||||
};
|
||||
use log::info;
|
||||
|
||||
#[no_mangle]
|
||||
@@ -9,6 +12,8 @@ fn android_main(app: AndroidApp) {
|
||||
let mut redraw_pending = true;
|
||||
let mut native_window: Option<ndk::native_window::NativeWindow> = None;
|
||||
|
||||
let mut combining_accent = None;
|
||||
|
||||
while !quit {
|
||||
app.poll_events(
|
||||
Some(std::time::Duration::from_secs(1)), /* timeout */
|
||||
@@ -68,11 +73,56 @@ fn android_main(app: AndroidApp) {
|
||||
if let Some(native_window) = &native_window {
|
||||
redraw_pending = false;
|
||||
|
||||
// Handle input
|
||||
app.input_events(|event| {
|
||||
info!("Input Event: {event:?}");
|
||||
InputStatus::Unhandled
|
||||
});
|
||||
// Handle input, via a lending iterator
|
||||
match app.input_events_iter() {
|
||||
Ok(mut iter) => loop {
|
||||
info!("Checking for next input event...");
|
||||
if !iter.next(|event| {
|
||||
match event {
|
||||
InputEvent::KeyEvent(key_event) => {
|
||||
let combined_key_char = character_map_and_combine_key(
|
||||
&app,
|
||||
key_event,
|
||||
&mut combining_accent,
|
||||
);
|
||||
info!("KeyEvent: combined key: {combined_key_char:?}")
|
||||
}
|
||||
InputEvent::MotionEvent(motion_event) => {
|
||||
println!("action = {:?}", motion_event.action());
|
||||
match motion_event.action() {
|
||||
MotionAction::Up => {
|
||||
let pointer = motion_event.pointer_index();
|
||||
let pointer =
|
||||
motion_event.pointer_at_index(pointer);
|
||||
let x = pointer.x();
|
||||
let y = pointer.y();
|
||||
|
||||
println!("POINTER UP {x}, {y}");
|
||||
if x < 200.0 && y < 200.0 {
|
||||
println!("Requesting to show keyboard");
|
||||
app.show_soft_input(true);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
InputEvent::TextEvent(state) => {
|
||||
info!("Input Method State: {state:?}");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
info!("Input Event: {event:?}");
|
||||
InputStatus::Unhandled
|
||||
}) {
|
||||
info!("No more input available");
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
log::error!("Failed to get input events iterator: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
info!("Render...");
|
||||
dummy_render(native_window);
|
||||
@@ -83,6 +133,73 @@ fn android_main(app: AndroidApp) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to map the `key_event` to a `KeyMapChar` containing a unicode character or dead key accent
|
||||
///
|
||||
/// This shows how to take a `KeyEvent` and look up its corresponding `KeyCharacterMap` and
|
||||
/// use that to try and map the `key_code` + `meta_state` to a unicode character or a
|
||||
/// dead key that be combined with the next key press.
|
||||
fn character_map_and_combine_key(
|
||||
app: &AndroidApp,
|
||||
key_event: &KeyEvent,
|
||||
combining_accent: &mut Option<char>,
|
||||
) -> Option<KeyMapChar> {
|
||||
let device_id = key_event.device_id();
|
||||
|
||||
let key_map = match app.device_key_character_map(device_id) {
|
||||
Ok(key_map) => key_map,
|
||||
Err(err) => {
|
||||
log::error!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
||||
Ok(KeyMapChar::Unicode(unicode)) => {
|
||||
// Only do dead key combining on key down
|
||||
if key_event.action() == KeyAction::Down {
|
||||
let combined_unicode = if let Some(accent) = combining_accent {
|
||||
match key_map.get_dead_char(*accent, unicode) {
|
||||
Ok(Some(key)) => {
|
||||
info!("KeyEvent: Combined '{unicode}' with accent '{accent}' to give '{key}'");
|
||||
Some(key)
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(err) => {
|
||||
log::error!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("KeyEvent: Pressed '{unicode}'");
|
||||
Some(unicode)
|
||||
};
|
||||
*combining_accent = None;
|
||||
combined_unicode.map(|unicode| KeyMapChar::Unicode(unicode))
|
||||
} else {
|
||||
Some(KeyMapChar::Unicode(unicode))
|
||||
}
|
||||
}
|
||||
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||
if key_event.action() == KeyAction::Down {
|
||||
info!("KeyEvent: Pressed 'dead key' combining accent '{accent}'");
|
||||
*combining_accent = Some(accent);
|
||||
}
|
||||
Some(KeyMapChar::CombiningAccent(accent))
|
||||
}
|
||||
Ok(KeyMapChar::None) => {
|
||||
// Leave any combining_accent state in tact (seems to match how other
|
||||
// Android apps work)
|
||||
info!("KeyEvent: Pressed non-unicode key");
|
||||
None
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("KeyEvent: Failed to get key map character: {err:?}");
|
||||
*combining_accent = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Post a NOP frame to the window
|
||||
///
|
||||
/// Since this is a bare minimum test app we don't depend
|
||||
|
||||
Generated
-3
@@ -1,3 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
Generated
-6
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="11" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-19
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="testRunner" value="GRADLE" />
|
||||
<option name="distributionType" value="DEFAULT_WRAPPED" />
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$" />
|
||||
<option value="$PROJECT_DIR$/app" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
Generated
-18
@@ -1,18 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DesignSurface">
|
||||
<option name="filePathToZoomLevelMap">
|
||||
<map>
|
||||
<entry key="..\:/Users/Robert/src/agdk-rust/examples/na-mainloop/app/src/main/res/drawable-v24/ic_launcher_foreground.xml" value="0.2595" />
|
||||
<entry key="..\:/Users/Robert/src/agdk-rust/examples/na-mainloop/app/src/main/res/drawable/ic_launcher_background.xml" value="0.2595" />
|
||||
<entry key="..\:/Users/Robert/src/agdk-rust/examples/na-mainloop/app/src/main/res/layout/activity_main.xml" value="0.25416666666666665" />
|
||||
</map>
|
||||
</option>
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="Android Studio default JDK" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||
</component>
|
||||
<component name="ProjectType">
|
||||
<option name="id" value="Android" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
-7
@@ -1,7 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -9,8 +9,8 @@ edition = "2021"
|
||||
log = "0.4"
|
||||
android_logger = "0.11.0"
|
||||
android-activity = { path="../../android-activity", features = [ "native-activity" ] }
|
||||
ndk-sys = "0.4"
|
||||
ndk = "0.7"
|
||||
ndk-sys = "0.6.0"
|
||||
ndk = "0.9.0"
|
||||
|
||||
[lib]
|
||||
#name="na_mainloop"
|
||||
@@ -181,4 +181,7 @@ label = "Application Name"
|
||||
#port = "8080"
|
||||
#path = "/rust-windowing/android-ndk-rs/tree/master/cargo-apk"
|
||||
#path_prefix = "/rust-windowing/"
|
||||
#mime_type = "image/jpeg"
|
||||
#mime_type = "image/jpeg"
|
||||
|
||||
[patch.crates-io]
|
||||
jni = { git = "https://github.com/jni-rs/jni-rs.git", branch = "release-0.22" }
|
||||
@@ -1,4 +1,7 @@
|
||||
use android_activity::{AndroidApp, InputStatus, MainEvent, PollEvent};
|
||||
use android_activity::{
|
||||
input::{InputEvent, KeyAction, KeyEvent, KeyMapChar, MotionAction},
|
||||
AndroidApp, InputStatus, MainEvent, PollEvent,
|
||||
};
|
||||
use log::info;
|
||||
|
||||
#[no_mangle]
|
||||
@@ -9,6 +12,8 @@ fn android_main(app: AndroidApp) {
|
||||
let mut redraw_pending = true;
|
||||
let mut native_window: Option<ndk::native_window::NativeWindow> = None;
|
||||
|
||||
let mut combining_accent = None;
|
||||
|
||||
while !quit {
|
||||
app.poll_events(
|
||||
Some(std::time::Duration::from_secs(1)), /* timeout */
|
||||
@@ -68,11 +73,56 @@ fn android_main(app: AndroidApp) {
|
||||
if let Some(native_window) = &native_window {
|
||||
redraw_pending = false;
|
||||
|
||||
// Handle input
|
||||
app.input_events(|event| {
|
||||
info!("Input Event: {event:?}");
|
||||
InputStatus::Unhandled
|
||||
});
|
||||
// Handle input, via a lending iterator
|
||||
match app.input_events_iter() {
|
||||
Ok(mut iter) => loop {
|
||||
info!("Checking for next input event...");
|
||||
if !iter.next(|event| {
|
||||
match event {
|
||||
InputEvent::KeyEvent(key_event) => {
|
||||
let combined_key_char = character_map_and_combine_key(
|
||||
&app,
|
||||
key_event,
|
||||
&mut combining_accent,
|
||||
);
|
||||
info!("KeyEvent: combined key: {combined_key_char:?}")
|
||||
}
|
||||
InputEvent::MotionEvent(motion_event) => {
|
||||
println!("action = {:?}", motion_event.action());
|
||||
match motion_event.action() {
|
||||
MotionAction::Up => {
|
||||
let pointer = motion_event.pointer_index();
|
||||
let pointer =
|
||||
motion_event.pointer_at_index(pointer);
|
||||
let x = pointer.x();
|
||||
let y = pointer.y();
|
||||
|
||||
println!("POINTER UP {x}, {y}");
|
||||
if x < 200.0 && y < 200.0 {
|
||||
println!("Requesting to show keyboard");
|
||||
app.show_soft_input(true);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
InputEvent::TextEvent(state) => {
|
||||
info!("Input Method State: {state:?}");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
info!("Input Event: {event:?}");
|
||||
InputStatus::Unhandled
|
||||
}) {
|
||||
info!("No more input available");
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(err) => {
|
||||
log::error!("Failed to get input events iterator: {err:?}");
|
||||
}
|
||||
}
|
||||
|
||||
info!("Render...");
|
||||
dummy_render(native_window);
|
||||
@@ -83,6 +133,73 @@ fn android_main(app: AndroidApp) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to map the `key_event` to a `KeyMapChar` containing a unicode character or dead key accent
|
||||
///
|
||||
/// This shows how to take a `KeyEvent` and look up its corresponding `KeyCharacterMap` and
|
||||
/// use that to try and map the `key_code` + `meta_state` to a unicode character or a
|
||||
/// dead key that be combined with the next key press.
|
||||
fn character_map_and_combine_key(
|
||||
app: &AndroidApp,
|
||||
key_event: &KeyEvent,
|
||||
combining_accent: &mut Option<char>,
|
||||
) -> Option<KeyMapChar> {
|
||||
let device_id = key_event.device_id();
|
||||
|
||||
let key_map = match app.device_key_character_map(device_id) {
|
||||
Ok(key_map) => key_map,
|
||||
Err(err) => {
|
||||
log::error!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
||||
Ok(KeyMapChar::Unicode(unicode)) => {
|
||||
// Only do dead key combining on key down
|
||||
if key_event.action() == KeyAction::Down {
|
||||
let combined_unicode = if let Some(accent) = combining_accent {
|
||||
match key_map.get_dead_char(*accent, unicode) {
|
||||
Ok(Some(key)) => {
|
||||
info!("KeyEvent: Combined '{unicode}' with accent '{accent}' to give '{key}'");
|
||||
Some(key)
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(err) => {
|
||||
log::error!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("KeyEvent: Pressed '{unicode}'");
|
||||
Some(unicode)
|
||||
};
|
||||
*combining_accent = None;
|
||||
combined_unicode.map(|unicode| KeyMapChar::Unicode(unicode))
|
||||
} else {
|
||||
Some(KeyMapChar::Unicode(unicode))
|
||||
}
|
||||
}
|
||||
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||
if key_event.action() == KeyAction::Down {
|
||||
info!("KeyEvent: Pressed 'dead key' combining accent '{accent}'");
|
||||
*combining_accent = Some(accent);
|
||||
}
|
||||
Some(KeyMapChar::CombiningAccent(accent))
|
||||
}
|
||||
Ok(KeyMapChar::None) => {
|
||||
// Leave any combining_accent state in tact (seems to match how other
|
||||
// Android apps work)
|
||||
info!("KeyEvent: Pressed non-unicode key");
|
||||
None
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("KeyEvent: Failed to get key map character: {err:?}");
|
||||
*combining_accent = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Post a NOP frame to the window
|
||||
///
|
||||
/// Since this is a bare minimum test app we don't depend
|
||||
|
||||
Reference in New Issue
Block a user