Skip to content

Commit 737b559

Browse files
committed
Android: rework backend to use android_activity crate
This updates the Android backend to use the android_activity crate instead of ndk-glue. This solves a few issues: 1. The backend is agnostic of the application's choice of Activity base class 2. Winit is no longer responsible for handling any Java synchronization details, since these are encapsulated by the design of android_activity 3. The backend no longer depends on global / static getters for state such as the native_window() which puts it in a better position to support running multiple activities within a single Android process. 4. Redraw requests are flagged, not queued, in a way that avoids taking priority over user events (resolves rust-windowing#2299) Addresses: PR rust-windowing#1892 Addresses: PR rust-windowing#2307 Addresses: PR rust-windowing#2343 Addresses: rust-windowing#2293 Resolves: rust-windowing#2299
1 parent 2e4338b commit 737b559

File tree

6 files changed

+702
-414
lines changed

6 files changed

+702
-414
lines changed

CHANGELOG.md

+12
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,19 @@ Please keep one empty line before and after all headers. (This is required for `
77
And please only add new entries to the top of this list, right below the `# Unreleased` header.
88

99
# Unreleased
10+
- **Breaking:** On Android, switched to using [`android-activity`](https://github.com/rib/android-activity) crate as a glue layer instead of [`ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue). See [README.md#Android](https://github.com/rust-windowing/winit#Android) for more details. ([#2444](https://github.com/rust-windowing/winit/pull/2444))
1011

12+
# 0.27.3
13+
14+
- On Windows, added `WindowExtWindows::set_undecorated_shadow` and `WindowBuilderExtWindows::with_undecorated_shadow` to draw the drop shadow behind a borderless window.
15+
- On Windows, fixed default window features (ie snap, animations, shake, etc.) when decorations are disabled.
16+
- On Windows, fixed ALT+Space shortcut to open window menu.
17+
- On Wayland, fixed `Ime::Preedit` not being sent on IME reset.
18+
- Fixed unbound version specified for `raw-window-handle` leading to compilation failures.
19+
- Empty `Ime::Preedit` event will be sent before `Ime::Commit` to help clearing preedit.
20+
- On X11, fixed IME context picking by querying for supported styles beforehand.
21+
22+
>>>>>>> 4943d368 (Android: rework backend to use android_activity crate)
1123
# 0.27.2 (2022-8-12)
1224

1325
- On macOS, fixed touch phase reporting when scrolling.

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ simple_logger = "2.1.0"
5858
[target.'cfg(target_os = "android")'.dependencies]
5959
# Coordinate the next winit release with android-ndk-rs: https://github.com/rust-windowing/winit/issues/1995
6060
ndk = "0.7.0"
61-
ndk-glue = "0.7.0"
61+
android-activity = "0.4.0-beta"
6262

6363
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
6464
objc = "0.2.7"

README.md

+56-15
Original file line numberDiff line numberDiff line change
@@ -99,36 +99,77 @@ book].
9999

100100
#### Android
101101

102-
This library makes use of the [ndk-rs](https://github.com/rust-windowing/android-ndk-rs) crates, refer to that repo for more documentation.
102+
The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/0.7.0/ndk/) crate.
103103

104-
The `ndk-glue` version needs to match the version used by `winit`. Otherwise, the application will not start correctly as `ndk-glue`'s internal `NativeActivity` static is not the same due to version mismatch.
104+
Native Android applications need some form of "glue" crate that is responsible for defining the main entry point for your Rust application as well as tracking various life-cycle events and synchronizing with the main JVM thread.
105105

106-
`winit` compatibility table with `ndk-glue`:
106+
Winit uses the [android-activity](https://github.com/rib/android-activity) as a glue crate (prior to `0.28` it used [ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue).
107107

108-
| winit | ndk-glue |
109-
| :---: | :------------------: |
110-
| 0.24 | `ndk-glue = "0.2.0"` |
111-
| 0.25 | `ndk-glue = "0.3.0"` |
112-
| 0.26 | `ndk-glue = "0.5.0"` |
113-
| 0.27 | `ndk-glue = "0.7.0"` |
108+
The version of the glue crate that your application depends on _must_ match the version that Winit depends on because the glue crate is responsible for your application's main entrypoint. If Cargo resolves multiple versions they will clash.
109+
110+
`winit` glue compatibility table:
111+
112+
| winit | ndk-glue |
113+
| :---: | :--------------------------: |
114+
| 0.28 | `android-activity = "0.3.0"` |
115+
| 0.27 | `ndk-glue = "0.7.0"` |
116+
| 0.26 | `ndk-glue = "0.5.0"` |
117+
| 0.25 | `ndk-glue = "0.3.0"` |
118+
| 0.24 | `ndk-glue = "0.2.0"` |
119+
120+
_Note: There is unfortunately no ergonomic way to configure Cargo so that it understands that the glue crate is special on Android and to give a clear error if multiple versions are resolved. With `ndk-glue` you will get a runtime failure caused by clashing, global static variables. With `android-activity` you will see a compile-time error due to missing feature flags._
114121

115122
Running on an Android device needs a dynamic system library, add this to Cargo.toml:
116123

117124
```toml
118125
[[example]]
119-
name = "request_redraw_threaded"
126+
name = "main"
120127
crate-type = ["cdylib"]
121128
```
122129

123-
And add this to the example file to add the native activity glue:
130+
All Android applications are based on an `Activity` subclass and the `android-activity` crate is designed to support different choices for this base class. You application must specify the base class it needs via a feature flag:
131+
132+
| Base Class | Feature Flag | Notes |
133+
| :--------------: | :---------------: | :-----: |
134+
| `NativeActivity` | `native-activity` | Built-in to Android - making it possible to build some tests/demos without needing to compile any JVM code. Can give a false sense of convenience because it's often not really possible to avoid needing a build system that can compile some JVM code, to at least subclass `NativeActivity` |
135+
| [`GameActivity`] | `game-activity` | Derives from [`AndroidAppCompat`] which is a defacto standard `Activity` base class that helps support a wider range of Android versions. Will offer integration with [`GameTextInput`] library for soft keyboard support. Requires a build system that can compile Java and fetch Android dependencies from a Maven repository (with [Gradle] being the defacto standard build system for Android applications) |
136+
137+
[`GameActivity`]: https://developer.android.com/games/agdk/game-activity
138+
[`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
139+
[`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity
140+
[Gradle]: https://developer.android.com/studio/build
141+
142+
For example, add this to Cargo.toml:
143+
```toml
144+
[target.'cfg(target_os = "android")'.dependencies]
145+
android_logger = "0.11.0"
146+
android-activity = { version = "0.3", features = [ "game-activity" ] }
147+
```
148+
149+
And, for example, define an entry point for your library like this:
124150
```rust
125-
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on"))]
126-
fn main() {
127-
...
151+
#[cfg(target_os = "android")]
152+
#[no_mangle]
153+
fn android_main(app: AndroidApp) {
154+
use winit::platform::android::EventLoopBuilderExtAndroid;
155+
156+
android_logger::init_once(android_logger::Config::default().with_min_level(log::Level::Trace));
157+
158+
let event_loop = EventLoopBuilder::with_user_event()
159+
.with_android_app(app)
160+
.build();
161+
_main(event_loop);
128162
}
129163
```
130164

131-
And run the application with `cargo apk run --example request_redraw_threaded`
165+
For more details, refer to these `android-activity` [example applications](https://github.com/rib/android-activity/tree/main/examples).
166+
167+
##### Converting from `ndk-glue` to `android-activity`
168+
169+
If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk` then the minimal changes would be:
170+
1. Remove `ndk-glue` from your `Cargo.toml` and add dependency on `android-activity` that specifies the `"native-activity"` feature like: `android-activity = { version = "0.3", features = [ "native-activity" ] }`
171+
2. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above).
172+
3. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
132173

133174
#### MacOS
134175

src/event_loop.rs

+10
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,18 @@ impl<T> EventLoopBuilder<T> {
9797
/// `WINIT_UNIX_BACKEND`. Legal values are `x11` and `wayland`.
9898
/// If it is not set, winit will try to connect to a Wayland connection, and if that fails,
9999
/// will fall back on X11. If this variable is set with any other value, winit will panic.
100+
/// - **Android:** Must be configured with an `AndroidApp` from `android_main()` by calling
101+
/// [`.with_android_app(app)`] before calling `.build()`.
100102
///
101103
/// [`platform`]: crate::platform
104+
#[cfg_attr(
105+
target_os = "android",
106+
doc = "[`.with_android_app(app)`]: crate::platform::android::EventLoopBuilderExtAndroid::with_android_app"
107+
)]
108+
#[cfg_attr(
109+
not(target_os = "android"),
110+
doc = "[`.with_android_app(app)`]: #only-available-on-android"
111+
)]
102112
#[inline]
103113
pub fn build(&mut self) -> EventLoop<T> {
104114
static EVENT_LOOP_CREATED: OnceCell<()> = OnceCell::new();

src/platform/android.rs

+19-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
#![cfg(any(target_os = "android"))]
22

33
use crate::{
4-
event_loop::{EventLoop, EventLoopWindowTarget},
4+
event_loop::{EventLoop, EventLoopBuilder, EventLoopWindowTarget},
55
window::{Window, WindowBuilder},
66
};
7-
use ndk::configuration::Configuration;
8-
use ndk_glue::Rect;
7+
8+
use android_activity::{AndroidApp, ConfigurationRef, Rect};
99

1010
/// Additional methods on [`EventLoop`] that are specific to Android.
1111
pub trait EventLoopExtAndroid {}
@@ -19,15 +19,15 @@ pub trait EventLoopWindowTargetExtAndroid {}
1919
pub trait WindowExtAndroid {
2020
fn content_rect(&self) -> Rect;
2121

22-
fn config(&self) -> Configuration;
22+
fn config(&self) -> ConfigurationRef;
2323
}
2424

2525
impl WindowExtAndroid for Window {
2626
fn content_rect(&self) -> Rect {
2727
self.window.content_rect()
2828
}
2929

30-
fn config(&self) -> Configuration {
30+
fn config(&self) -> ConfigurationRef {
3131
self.window.config()
3232
}
3333
}
@@ -38,3 +38,17 @@ impl<T> EventLoopWindowTargetExtAndroid for EventLoopWindowTarget<T> {}
3838
pub trait WindowBuilderExtAndroid {}
3939

4040
impl WindowBuilderExtAndroid for WindowBuilder {}
41+
42+
pub trait EventLoopBuilderExtAndroid {
43+
/// Associates the `AndroidApp` that was passed to `android_main()` with the event loop
44+
///
45+
/// This must be called on Android since the `AndroidApp` is not global state.
46+
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self;
47+
}
48+
49+
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
50+
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self {
51+
self.platform_specific.android_app = Some(app);
52+
self
53+
}
54+
}

0 commit comments

Comments
 (0)