Repository: rust-windowing/android-rs-glue
Branch: master
Commit: 3c4c9745eafc
Files: 52
Total size: 141.7 KB
Directory structure:
gitextract_s03qm1pi/
├── .circleci/
│ └── config.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── cargo-apk/
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── native_app_glue/
│ │ ├── NOTICE
│ │ ├── android_native_app_glue.c
│ │ └── android_native_app_glue.h
│ ├── src/
│ │ ├── config.rs
│ │ ├── main.rs
│ │ └── ops/
│ │ ├── build/
│ │ │ ├── compile.rs
│ │ │ ├── targets.rs
│ │ │ ├── tempfile.rs
│ │ │ └── util.rs
│ │ ├── build.rs
│ │ ├── install.rs
│ │ ├── mod.rs
│ │ └── run.rs
│ └── tests/
│ ├── cc/
│ │ ├── Cargo.toml
│ │ ├── build.rs
│ │ ├── cc_src/
│ │ │ ├── cpptest.cpp
│ │ │ └── ctest.c
│ │ └── src/
│ │ └── main.rs
│ ├── cmake/
│ │ ├── Cargo.toml
│ │ ├── build.rs
│ │ ├── libcmaketest/
│ │ │ ├── CMakeLists.txt
│ │ │ └── cmaketest.c
│ │ └── src/
│ │ └── main.rs
│ ├── inner_attributes/
│ │ ├── Cargo.toml
│ │ └── src/
│ │ └── main.rs
│ ├── native-library/
│ │ ├── Cargo.toml
│ │ └── src/
│ │ └── main.rs
│ └── run_tests.sh
├── examples/
│ ├── advanced/
│ │ ├── Cargo.toml
│ │ ├── assets/
│ │ │ └── test_asset
│ │ └── src/
│ │ └── main.rs
│ ├── basic/
│ │ ├── Cargo.toml
│ │ └── src/
│ │ └── main.rs
│ ├── multiple_targets/
│ │ ├── Cargo.toml
│ │ ├── examples/
│ │ │ └── example1.rs
│ │ └── src/
│ │ ├── bin/
│ │ │ └── secondary-bin.rs
│ │ └── main.rs
│ ├── use_assets/
│ │ ├── Cargo.toml
│ │ ├── assets/
│ │ │ └── test_asset
│ │ └── src/
│ │ └── main.rs
│ └── use_icon/
│ ├── Cargo.toml
│ └── src/
│ └── main.rs
└── glue/
├── .gitignore
├── Cargo.toml
└── src/
└── lib.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .circleci/config.yml
================================================
version: 2
jobs:
build-and-test:
environment:
IMAGE_NAME: tomaka/cargo-apk
docker:
- image: docker:stable
steps:
- checkout
- setup_remote_docker
- run:
name: Build image
command: docker build -t $IMAGE_NAME:latest .
- run:
name: Archive image
command: docker save -o image.tar $IMAGE_NAME
- persist_to_workspace:
root: .
paths:
- ./image.tar
publish-docker-image:
environment:
IMAGE_NAME: tomaka/cargo-apk
docker:
- image: docker:stable
steps:
- attach_workspace:
at: /tmp/workspace
- setup_remote_docker
- run:
name: Load image
command: docker load -i /tmp/workspace/image.tar
- run:
name: Publish final image
command: |
echo "$DOCKERHUB_PASSWORD" | docker login -u $DOCKERHUB_LOGIN --password-stdin
docker push $IMAGE_NAME
publish-crates-io:
working_directory: ~/android-rs-glue
docker:
- image: circleci/rust:buster
steps:
- checkout
- run: cd ./cargo-apk && cargo publish --token $CRATESIO_TOKEN
- run: cd ./glue && cargo publish --token $CRATESIO_TOKEN
workflows:
version: 2
all:
jobs:
- build-and-test
- publish-docker-image:
requires:
- build-and-test
filters:
branches:
only: master
- publish-crates-io:
requires:
- build-and-test
filters:
branches:
only: master
================================================
FILE: .gitignore
================================================
target/
.idea
*.iml
CMakeFiles
================================================
FILE: Dockerfile
================================================
FROM rust:stretch
RUN apt-get update
RUN apt-get install -yq openjdk-8-jre unzip wget cmake
RUN rustup target add armv7-linux-androideabi
RUN rustup target add aarch64-linux-android
RUN rustup target add i686-linux-android
RUN rustup target add x86_64-linux-android
# Install Android SDK
ENV ANDROID_HOME /opt/android-sdk-linux
RUN mkdir ${ANDROID_HOME} && \
cd ${ANDROID_HOME} && \
wget -q https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip && \
unzip -q sdk-tools-linux-4333796.zip && \
rm sdk-tools-linux-4333796.zip && \
chown -R root:root /opt
RUN yes | ${ANDROID_HOME}/tools/bin/sdkmanager "platform-tools" | grep -v = || true
RUN yes | ${ANDROID_HOME}/tools/bin/sdkmanager "platforms;android-29" | grep -v = || true
RUN yes | ${ANDROID_HOME}/tools/bin/sdkmanager "build-tools;29.0.0" | grep -v = || true
RUN ${ANDROID_HOME}/tools/bin/sdkmanager --update | grep -v = || true
# Install Android NDK
RUN cd /usr/local && \
wget -q http://dl.google.com/android/repository/android-ndk-r20-linux-x86_64.zip && \
unzip -q android-ndk-r20-linux-x86_64.zip && \
rm android-ndk-r20-linux-x86_64.zip
ENV NDK_HOME /usr/local/android-ndk-r20
# Copy contents to container. Should only use this on a clean directory
COPY . /root/cargo-apk
# Install binary
RUN cargo install --path /root/cargo-apk/cargo-apk
# Run tests
RUN cd /root/cargo-apk/cargo-apk && ./tests/run_tests.sh
# Remove source and build files
RUN rm -rf /root/cargo-apk
# Make directory for user code
RUN mkdir /root/src
WORKDIR /root/src
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.
================================================
FILE: README.md
================================================
deprecated in favor of https://github.com/rust-windowing/android-ndk-rs which works with winit master
# Android Glue
[](https://crates.io/crates/android-glue)
[](https://crates.io/crates/cargo-apk)
[](https://circleci.com/gh/rust-windowing/android-rs-glue)
# Usage
## With Docker
The easiest way to compile for Android is to use [Docker](https://www.docker.com/) and the
[philipalldredge/cargo-apk](https://hub.docker.com/r/philipalldredge/cargo-apk/) image.
In order to build an APK, simply do this:
```
docker run --rm -v <path-to-local-directory-with-Cargo.toml>:/root/src philipalldredge/cargo-apk cargo apk build
```
For example if you're on Linux and you want to compile the project in the current working
directory.
```
docker run --rm -v "$(pwd):/root/src" -w /root/src philipalldredge/cargo-apk cargo apk build
```
Do not mount a volume on `/root` or you will erase the local installation of Cargo.
After the build is finished, you should get an Android package in `target/android-artifacts/debug/apk`.
## Manual usage
### Setting up your environment
Before you can compile for Android, you need to setup your environment. This needs to be done only once per system.
- Install [`rustup`](https://rustup.rs/).
- Run `rustup target add <target>` for all supported targets to which you want to compile. Building will attempt to build for all supported targets unless the build targets are adjusted via `Cargo.toml`.
- `rustup target add armv7-linux-androideabi`
- `rustup target add aarch64-linux-android`
- `rustup target add i686-linux-android`
- `rustup target add x86_64-linux-android`
- Install the Java JRE or JDK (on Ubuntu, `sudo apt-get install openjdk-8-jdk`).
- Download and unzip [the Android NDK](https://developer.android.com/ndk).
- Download and unzip [the Android SDK](https://developer.android.com/studio).
- Install some components in the SDK: `./android-sdk/tools/bin/sdkmanager "platform-tools" "platforms;android-29" "build-tools;29.0.0"`.
- Install `cargo-apk` with `cargo install cargo-apk`.
- Set the environment variables `NDK_HOME` to the path of the NDK and `ANDROID_HOME` to the path of the SDK.
### Compiling
In the project root for your Android crate, run `cargo apk build`. You can use the same options as
with the regular `cargo build`.
This will build an Android package in `target/android-artifacts/<debug|release>/apk`.
### Compiling Multiple Binaries
`cargo apk build` supports building multiple binaries and examples using the same arguments as `cargo build`. It will produce an APK for each binary.
Android packages for bin targets are placed in `target/android-artifacts/<debug|release>/apk`.
Android packages for example targets are placed in `target/android-artifacts/<debug|release>/apk/examples`.
### Testing on an Android emulator
Start the emulator, then run:
```sh
cargo apk run
```
This will install your application on the emulator, then run it.
If you only want to install, use `cargo apk install`.
To show log run: `cargo apk logcat | grep RustAndroidGlueStdouterr`
# Interfacing with Android
An application is not very useful if it doesn't have access to the screen, the user inputs, etc.
The `android_glue` crate provides FFI with the Android environment for things that are not in
the stdlib.
# How it works
## The build process
The build process works by:
- Using rustc to always compile your crate as a shared library by:
- Creating a custom CMake toolchain file and setting environment variables which expose the appropriate NDK provided build tools for use with the `cc` and `cmake` crates.
- Creating a temporary file in the same directory as your crate root. This temporary file serves as the crate root of the static library. It contains the contents of the original crate root along with an `android_main` implementation.
- Compiling a forked version of `android_native_app_glue`. `android_native_app_glue` is originally provided by the NDK. It provides the entrypoint used by Android's `NativeActivity` that calls `android_main`.
- Linking using the NDK provided linker.
This first step outputs a shared library, and is run once per target architecture.
The command then builds the APK using the shared libraries, generated manifest, and tools from the Android SDK. If the C++ standard library is used, it adds the appropriate shared library to the APK.
It signs the APK with the default debug keystore used by Android development tools. If the keystore doesn't exist, it creates it using the keytool from the JRE or JDK.
# Supported `[package.metadata.android]` entries
```toml
# The target Android API level.
# "android_version" is the compile SDK version. It defaults to 29.
# (target_sdk_version defaults to the value of "android_version")
# (min_sdk_version defaults to 18) It defaults to 18 because this is the minimum supported by rustc.
android_version = 29
target_sdk_version = 29
min_sdk_version = 26
# Specifies the array of targets to build for.
# Defaults to "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android".
build_targets = [ "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android", "x86_64-linux-android" ]
# The following values can be customized on a per bin/example basis. See multiple_targets example
# If a value is not specified for a secondary target, it will inherit the value defined in the `package.metadata.android`
# section unless otherwise noted.
#
# The Java package name for your application.
# Hyphens are converted to underscores.
# Defaults to rust.<target_name> for binaries.
# Defaults to rust.<package_name>.example.<target_name> for examples.
# For example: for a binary "my_app", the default package name will be "rust.my_app"
# Secondary targets will not inherit the value defined in the root android configuration.
package_name = "rust.cargo.apk.advanced"
# The user-friendly name for your app, as displayed in the applications menu.
# Defaults to the target name
# Secondary targets will not inherit the value defined in the root android configuration.
label = "My Android App"
# Internal version number used to determine whether one version is more recent than another. Must be an integer.
# Defaults to 1
# See https://developer.android.com/guide/topics/manifest/manifest-element
version_code = 2
# The version number shown to users.
# Defaults to the cargo package version number
# See https://developer.android.com/guide/topics/manifest/manifest-element
version_name = "2.0"
# Path to your application's resources folder.
# If not specified, resources will not be included in the APK
res = "path/to/res_folder"
# Virtual path your application's icon for any mipmap level.
# If not specified, an icon will not be included in the APK.
icon = "@mipmap/ic_launcher"
# Path to the folder containing your application's assets.
# If not specified, assets will not be included in the APK
assets = "path/to/assets_folder"
# If set to true, makes the app run in full-screen, by adding the following line
# as an XML attribute to the manifest's <application> tag :
# android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen
# Defaults to false.
fullscreen = false
# The maximum supported OpenGL ES version , as claimed by the manifest.
# Defaults to 2.0.
# See https://developer.android.com/guide/topics/graphics/opengl.html#manifest
opengles_version_major = 3
opengles_version_minor = 2
# Adds extra arbitrary XML attributes to the <application> tag in the manifest.
# See https://developer.android.com/guide/topics/manifest/application-element.html
[package.metadata.android.application_attributes]
"android:debuggable" = "true"
"android:hardwareAccelerated" = "true"
# Adds extra arbitrary XML attributes to the <activity> tag in the manifest.
# See https://developer.android.com/guide/topics/manifest/activity-element.html
[package.metadata.android.activity_attributes]
"android:screenOrientation" = "unspecified"
"android:uiOptions" = "none"
# Adds a uses-feature element to the manifest
# Supported keys: name, required, version
# The glEsVersion attribute is not supported using this section.
# It can be specified using the opengles_version_major and opengles_version_minor values
# See https://developer.android.com/guide/topics/manifest/uses-feature-element
[[package.metadata.android.feature]]
name = "android.hardware.camera"
[[package.metadata.android.feature]]
name = "android.hardware.vulkan.level"
version = "1"
required = false
# Adds a uses-permission element to the manifest.
# Note that android_version 23 and higher, Android requires the application to request permissions at runtime.
# There is currently no way to do this using a pure NDK based application.
# See https://developer.android.com/guide/topics/manifest/uses-permission-element
[[package.metadata.android.permission]]
name = "android.permission.WRITE_EXTERNAL_STORAGE"
max_sdk_version = 18
[[package.metadata.android.permission]]
name = "android.permission.CAMERA"
```
# Environment Variables
Cargo-apk sets environment variables which are used to expose the appropriate C and C++ build tools to build scripts. The primary intent is to support building crates which have build scripts which use the `cc` and `cmake` crates.
- CC : path to NDK provided `clang` wrapper for the appropriate target and android platform.
- CXX : path to NDK provided `clang++` wrapper for the appropriate target and android platform.
- AR : path to NDK provided `ar`
- CXXSTDLIB : `c++` to use the full featured C++ standard library provided by the NDK.
- CMAKE_TOOLCHAIN_FILE : the path to the generated CMake toolchain. This toolchain sets the ABI, overrides any target specified, and includes the toolchain provided by the NDK.
- CMAKE_GENERATOR : `Unix Makefiles` to default to `Unix Makefiles` as opposed to using the CMake default which may not be appropriate depending on platform.
- CMAKE_MAKE_PROGRAM: Path to NDK provided make.
# C++ Standard Library Compatibility Issues
When a crate links to the C++ standard library, the shared library version provided by the NDK is used. Unfortunately, dependency loading issues will cause the application to crash on older versions of android. Once `lld` linker issues are resolved on all platforms, cargo apk will be updated to link to the static C++ library. This should resolve the compatibility issues.
================================================
FILE: cargo-apk/.gitignore
================================================
/target
================================================
FILE: cargo-apk/Cargo.toml
================================================
[package]
name = "cargo-apk"
version = "0.4.3"
authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>", "Philip Alldredge <philip@philipalldredge.com>"]
license = "MIT"
description = "Cargo subcommand that allows you to build Android packages"
repository = "https://github.com/rust-windowing/android-rs-glue/tree/master/cargo-apk"
edition = "2018"
[dependencies]
cargo = "0.41.0"
clap = "2.33.0"
itertools = "0.8.2"
dirs = "2.0.2"
failure = "0.1.6"
multimap = "0.8.0"
serde = "1.0.104"
toml = "0.5.5"
[dev-dependencies]
assert_cmd = "0.12.0"
================================================
FILE: cargo-apk/native_app_glue/NOTICE
================================================
Copyright (C) 2016 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.
================================================
FILE: cargo-apk/native_app_glue/android_native_app_glue.c
================================================
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <jni.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/resource.h>
#include "android_native_app_glue.h"
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "threaded_app", __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "threaded_app", __VA_ARGS__))
/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
# define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "threaded_app", __VA_ARGS__))
#else
# define LOGV(...) ((void)0)
#endif
static void free_saved_state(struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
if (android_app->savedState != NULL) {
free(android_app->savedState);
android_app->savedState = NULL;
android_app->savedStateSize = 0;
}
pthread_mutex_unlock(&android_app->mutex);
}
int8_t android_app_read_cmd(struct android_app* android_app) {
int8_t cmd;
if (read(android_app->msgread, &cmd, sizeof(cmd)) == sizeof(cmd)) {
switch (cmd) {
case APP_CMD_SAVE_STATE:
free_saved_state(android_app);
break;
}
return cmd;
} else {
LOGE("No data on command pipe!");
}
return -1;
}
static void print_cur_config(struct android_app* android_app) {
char lang[2], country[2];
AConfiguration_getLanguage(android_app->config, lang);
AConfiguration_getCountry(android_app->config, country);
LOGV("Config: mcc=%d mnc=%d lang=%c%c cnt=%c%c orien=%d touch=%d dens=%d "
"keys=%d nav=%d keysHid=%d navHid=%d sdk=%d size=%d long=%d "
"modetype=%d modenight=%d",
AConfiguration_getMcc(android_app->config),
AConfiguration_getMnc(android_app->config),
lang[0], lang[1], country[0], country[1],
AConfiguration_getOrientation(android_app->config),
AConfiguration_getTouchscreen(android_app->config),
AConfiguration_getDensity(android_app->config),
AConfiguration_getKeyboard(android_app->config),
AConfiguration_getNavigation(android_app->config),
AConfiguration_getKeysHidden(android_app->config),
AConfiguration_getNavHidden(android_app->config),
AConfiguration_getSdkVersion(android_app->config),
AConfiguration_getScreenSize(android_app->config),
AConfiguration_getScreenLong(android_app->config),
AConfiguration_getUiModeType(android_app->config),
AConfiguration_getUiModeNight(android_app->config));
}
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case APP_CMD_INPUT_CHANGED:
LOGV("APP_CMD_INPUT_CHANGED\n");
pthread_mutex_lock(&android_app->mutex);
if (android_app->inputQueue != NULL) {
AInputQueue_detachLooper(android_app->inputQueue);
}
android_app->inputQueue = android_app->pendingInputQueue;
if (android_app->inputQueue != NULL) {
LOGV("Attaching input queue to looper");
AInputQueue_attachLooper(android_app->inputQueue,
android_app->looper, LOOPER_ID_INPUT, NULL,
&android_app->inputPollSource);
}
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_INIT_WINDOW:
LOGV("APP_CMD_INIT_WINDOW\n");
pthread_mutex_lock(&android_app->mutex);
android_app->window = android_app->pendingWindow;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW\n");
pthread_cond_broadcast(&android_app->cond);
break;
case APP_CMD_RESUME:
case APP_CMD_START:
case APP_CMD_PAUSE:
case APP_CMD_STOP:
LOGV("activityState=%d\n", cmd);
pthread_mutex_lock(&android_app->mutex);
android_app->activityState = cmd;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_CONFIG_CHANGED:
LOGV("APP_CMD_CONFIG_CHANGED\n");
AConfiguration_fromAssetManager(android_app->config,
android_app->activity->assetManager);
print_cur_config(android_app);
break;
case APP_CMD_DESTROY:
LOGV("APP_CMD_DESTROY\n");
android_app->destroyRequested = 1;
break;
}
}
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW\n");
pthread_mutex_lock(&android_app->mutex);
android_app->window = NULL;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_SAVE_STATE:
LOGV("APP_CMD_SAVE_STATE\n");
pthread_mutex_lock(&android_app->mutex);
android_app->stateSaved = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_RESUME:
free_saved_state(android_app);
break;
}
}
void app_dummy() {
}
static void android_app_destroy(struct android_app* android_app) {
LOGV("android_app_destroy!");
free_saved_state(android_app);
pthread_mutex_lock(&android_app->mutex);
if (!android_app->destroyRequested)
ANativeActivity_finish(android_app->activity);
if (android_app->inputQueue != NULL)
AInputQueue_detachLooper(android_app->inputQueue);
AConfiguration_delete(android_app->config);
android_app->destroyed = 1;
pthread_mutex_unlock(&android_app->mutex);
// Can't touch android_app object after this.
}
static void process_input(struct android_app* app, struct android_poll_source* source) {
AInputEvent* event = NULL;
while (AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
LOGV("New input event: type=%d\n", AInputEvent_getType(event));
if (AInputQueue_preDispatchEvent(app->inputQueue, event)) {
continue;
}
int32_t handled = 0;
if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event);
AInputQueue_finishEvent(app->inputQueue, event, handled);
}
}
static void process_cmd(struct android_app* app, struct android_poll_source* source) {
int8_t cmd = android_app_read_cmd(app);
android_app_pre_exec_cmd(app, cmd);
if (app->onAppCmd != NULL) app->onAppCmd(app, cmd);
android_app_post_exec_cmd(app, cmd);
}
static void* android_app_entry(void* param) {
struct android_app* android_app = (struct android_app*)param;
android_app->config = AConfiguration_new();
AConfiguration_fromAssetManager(android_app->config, android_app->activity->assetManager);
print_cur_config(android_app);
android_app->cmdPollSource.id = LOOPER_ID_MAIN;
android_app->cmdPollSource.app = android_app;
android_app->cmdPollSource.process = process_cmd;
android_app->inputPollSource.id = LOOPER_ID_INPUT;
android_app->inputPollSource.app = android_app;
android_app->inputPollSource.process = process_input;
ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, NULL,
&android_app->cmdPollSource);
android_app->looper = looper;
pthread_mutex_lock(&android_app->mutex);
android_app->running = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
ANDROID_APP = android_app;
android_main(android_app);
android_app_destroy(android_app);
LOGV("thread exiting");
return NULL;
}
static void *logging_thread(void *fd_as_ptr) {
int fd = (int) (size_t) fd_as_ptr;
LOGV("Logging thread started; fd is %d", fd);
char buffer[2048];
int cursor = 0;
while (1) {
int result = read(fd, (void *) buffer + cursor, 2047 - cursor);
if (result == 0) return NULL;
if (result < 0) {
LOGE("Logging thread: error reading from pipe: %s", strerror(errno));
return NULL;
}
int old_cursor = cursor;
cursor += result;
char *newline = (char *) memchr((void *) buffer + old_cursor, '\n', cursor);
if (newline) {
*newline = '\0';
__android_log_write(ANDROID_LOG_DEBUG, "RustStdoutStderr", buffer);
int new_start = newline + 1 - buffer;
memcpy((void *) buffer, (void *) newline + 1, cursor - new_start);
cursor -= new_start;
} else if (cursor == 2047) {
buffer[2047] = '\0';
__android_log_write(ANDROID_LOG_DEBUG, "RustStdoutStderr", buffer);
cursor = 0;
}
}
}
// --------------------------------------------------------------------
// Native activity interaction (called from main thread)
// --------------------------------------------------------------------
static struct android_app* android_app_create(ANativeActivity* activity,
void* savedState, size_t savedStateSize) {
struct android_app* android_app = (struct android_app*)malloc(sizeof(struct android_app));
memset(android_app, 0, sizeof(struct android_app));
android_app->activity = activity;
pthread_mutex_init(&android_app->mutex, NULL);
pthread_cond_init(&android_app->cond, NULL);
if (savedState != NULL) {
android_app->savedState = malloc(savedStateSize);
android_app->savedStateSize = savedStateSize;
memcpy(android_app->savedState, savedState, savedStateSize);
}
int msgpipe[2];
if (pipe(msgpipe)) {
LOGE("could not create pipe: %s", strerror(errno));
return NULL;
}
android_app->msgread = msgpipe[0];
android_app->msgwrite = msgpipe[1];
int logpipe[2];
if (pipe(logpipe)) {
LOGE("could not create pipe: %s", strerror(errno));
return NULL;
}
dup2(logpipe[1], STDOUT_FILENO);
dup2(logpipe[1], STDERR_FILENO);
pthread_t log_thread;
pthread_create(&log_thread, NULL, logging_thread, (void *) (size_t) logpipe[0]);
pthread_detach(log_thread);
pthread_create(&android_app->thread, NULL, android_app_entry, android_app);
// Wait for thread to start.
pthread_mutex_lock(&android_app->mutex);
while (!android_app->running) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
return android_app;
}
static void android_app_write_cmd(struct android_app* android_app, int8_t cmd) {
if (write(android_app->msgwrite, &cmd, sizeof(cmd)) != sizeof(cmd)) {
LOGE("Failure writing android_app cmd: %s\n", strerror(errno));
}
}
static void android_app_set_input(struct android_app* android_app, AInputQueue* inputQueue) {
pthread_mutex_lock(&android_app->mutex);
android_app->pendingInputQueue = inputQueue;
android_app_write_cmd(android_app, APP_CMD_INPUT_CHANGED);
while (android_app->inputQueue != android_app->pendingInputQueue) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_set_window(struct android_app* android_app, ANativeWindow* window) {
pthread_mutex_lock(&android_app->mutex);
if (android_app->pendingWindow != NULL) {
android_app_write_cmd(android_app, APP_CMD_TERM_WINDOW);
}
android_app->pendingWindow = window;
if (window != NULL) {
android_app_write_cmd(android_app, APP_CMD_INIT_WINDOW);
}
while (android_app->window != android_app->pendingWindow) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_set_activity_state(struct android_app* android_app, int8_t cmd) {
pthread_mutex_lock(&android_app->mutex);
android_app_write_cmd(android_app, cmd);
while (android_app->activityState != cmd) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_free(struct android_app* android_app) {
android_app_write_cmd(android_app, APP_CMD_DESTROY);
pthread_join(android_app->thread, NULL);
close(android_app->msgread);
close(android_app->msgwrite);
pthread_cond_destroy(&android_app->cond);
pthread_mutex_destroy(&android_app->mutex);
free(android_app);
exit(0);
}
static void onDestroy(ANativeActivity* activity) {
LOGV("Destroy: %p\n", activity);
android_app_free((struct android_app*)activity->instance);
}
static void onStart(ANativeActivity* activity) {
LOGV("Start: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_START);
}
static void onResume(ANativeActivity* activity) {
LOGV("Resume: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_RESUME);
}
static void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen) {
struct android_app* android_app = (struct android_app*)activity->instance;
void* savedState = NULL;
LOGV("SaveInstanceState: %p\n", activity);
pthread_mutex_lock(&android_app->mutex);
android_app->stateSaved = 0;
android_app_write_cmd(android_app, APP_CMD_SAVE_STATE);
while (!android_app->stateSaved) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
if (android_app->savedState != NULL) {
savedState = android_app->savedState;
*outLen = android_app->savedStateSize;
android_app->savedState = NULL;
android_app->savedStateSize = 0;
}
pthread_mutex_unlock(&android_app->mutex);
return savedState;
}
static void onPause(ANativeActivity* activity) {
LOGV("Pause: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_PAUSE);
}
static void onStop(ANativeActivity* activity) {
LOGV("Stop: %p\n", activity);
android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_STOP);
}
static void onConfigurationChanged(ANativeActivity* activity) {
struct android_app* android_app = (struct android_app*)activity->instance;
LOGV("ConfigurationChanged: %p\n", activity);
android_app_write_cmd(android_app, APP_CMD_CONFIG_CHANGED);
}
static void onLowMemory(ANativeActivity* activity) {
struct android_app* android_app = (struct android_app*)activity->instance;
LOGV("LowMemory: %p\n", activity);
android_app_write_cmd(android_app, APP_CMD_LOW_MEMORY);
}
static void onWindowFocusChanged(ANativeActivity* activity, int focused) {
LOGV("WindowFocusChanged: %p -- %d\n", activity, focused);
android_app_write_cmd((struct android_app*)activity->instance,
focused ? APP_CMD_GAINED_FOCUS : APP_CMD_LOST_FOCUS);
}
static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) {
LOGV("NativeWindowCreated: %p -- %p\n", activity, window);
android_app_set_window((struct android_app*)activity->instance, window);
}
static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window) {
LOGV("NativeWindowDestroyed: %p -- %p\n", activity, window);
android_app_set_window((struct android_app*)activity->instance, NULL);
}
static void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue) {
LOGV("InputQueueCreated: %p -- %p\n", activity, queue);
android_app_set_input((struct android_app*)activity->instance, queue);
}
static void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue) {
LOGV("InputQueueDestroyed: %p -- %p\n", activity, queue);
android_app_set_input((struct android_app*)activity->instance, NULL);
}
// Called by ANativeActivity_onCreate which will be exported and will call this function.
// Needed because this symbol will not be globally exported.
void native_app_glue_onCreate(ANativeActivity* activity, void* savedState,
size_t savedStateSize) {
LOGV("Creating: %p\n", activity);
activity->callbacks->onDestroy = onDestroy;
activity->callbacks->onStart = onStart;
activity->callbacks->onResume = onResume;
activity->callbacks->onSaveInstanceState = onSaveInstanceState;
activity->callbacks->onPause = onPause;
activity->callbacks->onStop = onStop;
activity->callbacks->onConfigurationChanged = onConfigurationChanged;
activity->callbacks->onLowMemory = onLowMemory;
activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;
activity->callbacks->onNativeWindowCreated = onNativeWindowCreated;
activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed;
activity->callbacks->onInputQueueCreated = onInputQueueCreated;
activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed;
activity->instance = android_app_create(activity, savedState, savedStateSize);
}
================================================
FILE: cargo-apk/native_app_glue/android_native_app_glue.h
================================================
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _ANDROID_NATIVE_APP_GLUE_H
#define _ANDROID_NATIVE_APP_GLUE_H
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <android/configuration.h>
#include <android/looper.h>
#include <android/native_activity.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* The native activity interface provided by <android/native_activity.h>
* is based on a set of application-provided callbacks that will be called
* by the Activity's main thread when certain events occur.
*
* This means that each one of this callbacks _should_ _not_ block, or they
* risk having the system force-close the application. This programming
* model is direct, lightweight, but constraining.
*
* The 'android_native_app_glue' static library is used to provide a different
* execution model where the application can implement its own main event
* loop in a different thread instead. Here's how it works:
*
* 1/ The application must provide a function named "android_main()" that
* will be called when the activity is created, in a new thread that is
* distinct from the activity's main thread.
*
* 2/ android_main() receives a pointer to a valid "android_app" structure
* that contains references to other important objects, e.g. the
* ANativeActivity obejct instance the application is running in.
*
* 3/ the "android_app" object holds an ALooper instance that already
* listens to two important things:
*
* - activity lifecycle events (e.g. "pause", "resume"). See APP_CMD_XXX
* declarations below.
*
* - input events coming from the AInputQueue attached to the activity.
*
* Each of these correspond to an ALooper identifier returned by
* ALooper_pollOnce with values of LOOPER_ID_MAIN and LOOPER_ID_INPUT,
* respectively.
*
* Your application can use the same ALooper to listen to additional
* file-descriptors. They can either be callback based, or with return
* identifiers starting with LOOPER_ID_USER.
*
* 4/ Whenever you receive a LOOPER_ID_MAIN or LOOPER_ID_INPUT event,
* the returned data will point to an android_poll_source structure. You
* can call the process() function on it, and fill in android_app->onAppCmd
* and android_app->onInputEvent to be called for your own processing
* of the event.
*
* Alternatively, you can call the low-level functions to read and process
* the data directly... look at the process_cmd() and process_input()
* implementations in the glue to see how to do this.
*
* See the sample named "native-activity" that comes with the NDK with a
* full usage example. Also look at the JavaDoc of NativeActivity.
*/
struct android_app;
/**
* Data associated with an ALooper fd that will be returned as the "outData"
* when that source has data ready.
*/
struct android_poll_source {
// The identifier of this source. May be LOOPER_ID_MAIN or
// LOOPER_ID_INPUT.
int32_t id;
// The android_app this ident is associated with.
struct android_app* app;
// Function to call to perform the standard processing of data from
// this source.
void (*process)(struct android_app* app, struct android_poll_source* source);
};
/**
* This is the interface for the standard glue code of a threaded
* application. In this model, the application's code is running
* in its own thread separate from the main thread of the process.
* It is not required that this thread be associated with the Java
* VM, although it will need to be in order to make JNI calls any
* Java objects.
*/
struct android_app {
// The application can place a pointer to its own state object
// here if it likes.
void* userData;
// Fill this in with the function to process main app commands (APP_CMD_*)
void (*onAppCmd)(struct android_app* app, int32_t cmd);
// Fill this in with the function to process input events. At this point
// the event has already been pre-dispatched, and it will be finished upon
// return. Return 1 if you have handled the event, 0 for any default
// dispatching.
int32_t (*onInputEvent)(struct android_app* app, AInputEvent* event);
// The ANativeActivity object instance that this app is running in.
ANativeActivity* activity;
// The current configuration the app is running in.
AConfiguration* config;
// This is the last instance's saved state, as provided at creation time.
// It is NULL if there was no state. You can use this as you need; the
// memory will remain around until you call android_app_exec_cmd() for
// APP_CMD_RESUME, at which point it will be freed and savedState set to NULL.
// These variables should only be changed when processing a APP_CMD_SAVE_STATE,
// at which point they will be initialized to NULL and you can malloc your
// state and place the information here. In that case the memory will be
// freed for you later.
void* savedState;
size_t savedStateSize;
// The ALooper associated with the app's thread.
ALooper* looper;
// When non-NULL, this is the input queue from which the app will
// receive user input events.
AInputQueue* inputQueue;
// When non-NULL, this is the window surface that the app can draw in.
ANativeWindow* window;
// Current content rectangle of the window; this is the area where the
// window's content should be placed to be seen by the user.
ARect contentRect;
// Current state of the app's activity. May be either APP_CMD_START,
// APP_CMD_RESUME, APP_CMD_PAUSE, or APP_CMD_STOP; see below.
int activityState;
// This is non-zero when the application's NativeActivity is being
// destroyed and waiting for the app thread to complete.
int destroyRequested;
// -------------------------------------------------
// Below are "private" implementation of the glue code.
pthread_mutex_t mutex;
pthread_cond_t cond;
int msgread;
int msgwrite;
pthread_t thread;
struct android_poll_source cmdPollSource;
struct android_poll_source inputPollSource;
int running;
int stateSaved;
int destroyed;
int redrawNeeded;
AInputQueue* pendingInputQueue;
ANativeWindow* pendingWindow;
ARect pendingContentRect;
};
enum {
/**
* Looper data ID of commands coming from the app's main thread, which
* is returned as an identifier from ALooper_pollOnce(). The data for this
* identifier is a pointer to an android_poll_source structure.
* These can be retrieved and processed with android_app_read_cmd()
* and android_app_exec_cmd().
*/
LOOPER_ID_MAIN = 1,
/**
* Looper data ID of events coming from the AInputQueue of the
* application's window, which is returned as an identifier from
* ALooper_pollOnce(). The data for this identifier is a pointer to an
* android_poll_source structure. These can be read via the inputQueue
* object of android_app.
*/
LOOPER_ID_INPUT = 2,
/**
* Start of user-defined ALooper identifiers.
*/
LOOPER_ID_USER = 3,
};
enum {
/**
* Command from main thread: the AInputQueue has changed. Upon processing
* this command, android_app->inputQueue will be updated to the new queue
* (or NULL).
*/
APP_CMD_INPUT_CHANGED,
/**
* Command from main thread: a new ANativeWindow is ready for use. Upon
* receiving this command, android_app->window will contain the new window
* surface.
*/
APP_CMD_INIT_WINDOW,
/**
* Command from main thread: the existing ANativeWindow needs to be
* terminated. Upon receiving this command, android_app->window still
* contains the existing window; after calling android_app_exec_cmd
* it will be set to NULL.
*/
APP_CMD_TERM_WINDOW,
/**
* Command from main thread: the current ANativeWindow has been resized.
* Please redraw with its new size.
*/
APP_CMD_WINDOW_RESIZED,
/**
* Command from main thread: the system needs that the current ANativeWindow
* be redrawn. You should redraw the window before handing this to
* android_app_exec_cmd() in order to avoid transient drawing glitches.
*/
APP_CMD_WINDOW_REDRAW_NEEDED,
/**
* Command from main thread: the content area of the window has changed,
* such as from the soft input window being shown or hidden. You can
* find the new content rect in android_app::contentRect.
*/
APP_CMD_CONTENT_RECT_CHANGED,
/**
* Command from main thread: the app's activity window has gained
* input focus.
*/
APP_CMD_GAINED_FOCUS,
/**
* Command from main thread: the app's activity window has lost
* input focus.
*/
APP_CMD_LOST_FOCUS,
/**
* Command from main thread: the current device configuration has changed.
*/
APP_CMD_CONFIG_CHANGED,
/**
* Command from main thread: the system is running low on memory.
* Try to reduce your memory use.
*/
APP_CMD_LOW_MEMORY,
/**
* Command from main thread: the app's activity has been started.
*/
APP_CMD_START,
/**
* Command from main thread: the app's activity has been resumed.
*/
APP_CMD_RESUME,
/**
* Command from main thread: the app should generate a new saved state
* for itself, to restore from later if needed. If you have saved state,
* allocate it with malloc and place it in android_app.savedState with
* the size in android_app.savedStateSize. The will be freed for you
* later.
*/
APP_CMD_SAVE_STATE,
/**
* Command from main thread: the app's activity has been paused.
*/
APP_CMD_PAUSE,
/**
* Command from main thread: the app's activity has been stopped.
*/
APP_CMD_STOP,
/**
* Command from main thread: the app's activity is being destroyed,
* and waiting for the app thread to clean up and exit before proceeding.
*/
APP_CMD_DESTROY,
};
/**
* Call when ALooper_pollAll() returns LOOPER_ID_MAIN, reading the next
* app command message.
*/
int8_t android_app_read_cmd(struct android_app* android_app);
/**
* Call with the command returned by android_app_read_cmd() to do the
* initial pre-processing of the given command. You can perform your own
* actions for the command after calling this function.
*/
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Call with the command returned by android_app_read_cmd() to do the
* final post-processing of the given command. You must have done your own
* actions for the command before calling this function.
*/
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Dummy function that used to be used to prevent the linker from stripping app
* glue code. No longer necessary, since __attribute__((visibility("default")))
* does this for us.
*/
__attribute__((
deprecated("Calls to app_dummy are no longer necessary. See "
"https://github.com/android-ndk/ndk/issues/381."))) void
app_dummy();
/**
* This is the function that application code must implement, representing
* the main entry to the app.
*/
extern void android_main(struct android_app* app);
struct android_app* ANDROID_APP = NULL;
#ifdef __cplusplus
}
#endif
#endif /* _ANDROID_NATIVE_APP_GLUE_H */
================================================
FILE: cargo-apk/src/config.rs
================================================
use cargo::core::{TargetKind, Workspace};
use cargo::ops;
use cargo::util::CargoResult;
use cargo::CliError;
use failure::format_err;
use itertools::Itertools;
use serde::Deserialize;
use std::collections::btree_map::BTreeMap;
use std::env;
use std::fs;
use std::fs::File;
use std::io::Read;
use std::iter::FromIterator;
use std::path::Path;
use std::path::PathBuf;
use toml;
#[derive(Clone)]
pub struct AndroidConfig {
/// Name of the cargo package
pub cargo_package_name: String,
/// Version of the cargo package
pub cargo_package_version: String,
/// Path to the manifest
pub manifest_path: PathBuf,
/// Path to the root of the Android SDK.
pub sdk_path: PathBuf,
/// Path to the root of the Android NDK.
pub ndk_path: PathBuf,
/// List of targets to build the app for. Eg. `armv7-linux-androideabi`.
pub build_targets: Vec<AndroidBuildTarget>,
/// Path to the android.jar for the selected android platform
pub android_jar_path: PathBuf,
/// Version of android:targetSdkVersion (optional). Default Value = android_version
pub target_sdk_version: u32,
/// Version of android:minSdkVersion (optional). Default Value = android_version
pub min_sdk_version: u32,
/// Version of the build tools to use
pub build_tools_version: String,
/// Should we build in release mode?
pub release: bool,
/// Target configuration settings that are associated with a specific target
default_target_config: TomlAndroidTarget,
/// Target specific configuration settings
target_configs: BTreeMap<(TargetKind, String), TomlAndroidTarget>,
}
impl AndroidConfig {
/// Builds the android target config based on the default target config and the specific target configs defined in the manifest
pub fn resolve(&self, target: (TargetKind, String)) -> CargoResult<AndroidTargetConfig> {
let primary_config = self.target_configs.get(&target);
let target_name = target.1;
let is_default_target = target_name == self.cargo_package_name;
let example = target.0 == TargetKind::ExampleBin;
Ok(AndroidTargetConfig {
package_name: primary_config
.and_then(|a| a.package_name.clone())
.or_else(|| {
if is_default_target {
self.default_target_config.package_name.clone()
} else {
None
}
})
.unwrap_or_else(|| {
if example {
format!("rust.{}.example.{}", self.cargo_package_name, target_name)
} else {
format!("rust.{}", target_name)
}
}),
package_label: primary_config
.and_then(|a| a.label.clone())
.or_else(|| {
if is_default_target {
self.default_target_config.label.clone()
} else {
None
}
})
.unwrap_or_else(|| target_name.clone()),
version_code: primary_config
.and_then(|a| a.version_code)
.or_else(|| self.default_target_config.version_code)
.unwrap_or(1),
version_name: primary_config
.and_then(|a| a.version_name.clone())
.or_else(|| self.default_target_config.version_name.clone())
.unwrap_or_else(|| self.cargo_package_version.clone()),
package_icon: primary_config
.and_then(|a| a.icon.clone())
.or_else(|| self.default_target_config.icon.clone()),
assets_path: primary_config
.and_then(|a| a.assets.as_ref())
.or_else(|| self.default_target_config.assets.as_ref())
.map(|p| self.manifest_path.parent().unwrap().join(p)),
res_path: primary_config
.and_then(|a| a.res.as_ref())
.or_else(|| self.default_target_config.res.as_ref())
.map(|p| self.manifest_path.parent().unwrap().join(p)),
fullscreen: primary_config
.and_then(|a| a.fullscreen)
.or_else(|| self.default_target_config.fullscreen)
.unwrap_or(false),
application_attributes: primary_config
.and_then(|a| a.application_attributes.clone())
.or_else(|| self.default_target_config.application_attributes.clone())
.map(build_attribute_string),
activity_attributes: primary_config
.and_then(|a| a.activity_attributes.clone())
.or_else(|| self.default_target_config.activity_attributes.clone())
.map(build_attribute_string),
opengles_version_major: primary_config
.and_then(|a| a.opengles_version_major)
.or_else(|| self.default_target_config.opengles_version_major)
.unwrap_or(2),
opengles_version_minor: primary_config
.and_then(|a| a.opengles_version_minor)
.or_else(|| self.default_target_config.opengles_version_minor)
.unwrap_or(0),
features: primary_config
.and_then(|a| a.feature.clone())
.or_else(|| self.default_target_config.feature.clone())
.unwrap_or_else(Vec::new)
.into_iter()
.map(AndroidFeature::from)
.collect(),
permissions: primary_config
.and_then(|a| a.permission.clone())
.or_else(|| self.default_target_config.permission.clone())
.unwrap_or_else(Vec::new)
.into_iter()
.map(AndroidPermission::from)
.collect(),
})
}
}
/// Build targets supported by NDK
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum AndroidBuildTarget {
#[serde(rename(deserialize = "armv7-linux-androideabi"))]
ArmV7a,
#[serde(rename(deserialize = "aarch64-linux-android"))]
Arm64V8a,
#[serde(rename(deserialize = "i686-linux-android"))]
X86,
#[serde(rename(deserialize = "x86_64-linux-android"))]
X86_64,
}
#[derive(Clone)]
pub struct AndroidFeature {
pub name: String,
pub required: bool,
pub version: Option<String>,
}
impl From<TomlFeature> for AndroidFeature {
fn from(f: TomlFeature) -> Self {
AndroidFeature {
name: f.name,
required: f.required.unwrap_or(true),
version: f.version,
}
}
}
#[derive(Clone)]
pub struct AndroidPermission {
pub name: String,
pub max_sdk_version: Option<u32>,
}
impl From<TomlPermission> for AndroidPermission {
fn from(p: TomlPermission) -> Self {
AndroidPermission {
name: p.name,
max_sdk_version: p.max_sdk_version,
}
}
}
/// Android build settings for a specific target
pub struct AndroidTargetConfig {
/// Name that the package will have on the Android machine.
/// This is the key that Android uses to identify your package, so it should be unique for
/// for each application and should contain the vendor's name.
pub package_name: String,
/// Label for the package.
pub package_label: String,
/// Internal version number for manifest.
pub version_code: i32,
/// Version number which is shown to users.
pub version_name: String,
/// Name of the launcher icon.
/// Versions of this icon with different resolutions have to reside in the res folder
pub package_icon: Option<String>,
/// If `Some`, a path that contains the list of assets to ship as part of the package.
///
/// The assets can later be loaded with the runtime library.
pub assets_path: Option<PathBuf>,
/// If `Some`, a path that contains the list of resources to ship as part of the package.
///
/// The resources can later be loaded with the runtime library.
/// This folder contains for example the launcher icon, the styles and resolution dependent images.
pub res_path: Option<PathBuf>,
/// Should this app be in fullscreen mode (hides the title bar)?
pub fullscreen: bool,
/// Appends this string to the application attributes in the AndroidManifest.xml
pub application_attributes: Option<String>,
/// Appends this string to the activity attributes in the AndroidManifest.xml
pub activity_attributes: Option<String>,
/// The OpenGL ES major version in the AndroidManifest.xml
pub opengles_version_major: u8,
/// The OpenGL ES minor version in the AndroidManifest.xml
pub opengles_version_minor: u8,
/// uses-feature in AndroidManifest.xml
pub features: Vec<AndroidFeature>,
/// uses-permission in AndroidManifest.xml
pub permissions: Vec<AndroidPermission>,
}
pub fn load(
workspace: &Workspace,
flag_package: &Option<String>,
) -> Result<AndroidConfig, CliError> {
// Find out the package requested by the user.
let package = {
let packages = Vec::from_iter(flag_package.iter().cloned());
let spec = ops::Packages::Packages(packages);
match spec {
ops::Packages::Default => unreachable!("cargo apk supports single package only"),
ops::Packages::All => unreachable!("cargo apk supports single package only"),
ops::Packages::OptOut(_) => unreachable!("cargo apk supports single package only"),
ops::Packages::Packages(xs) => match xs.len() {
0 => workspace.current()?,
1 => workspace
.members()
.find(|pkg| *pkg.name() == xs[0])
.ok_or_else(|| {
format_err!("package `{}` is not a member of the workspace", xs[0])
})?,
_ => unreachable!("cargo apk supports single package only"),
},
}
};
// Determine the name of the package and the Android-specific metadata from the Cargo.toml
let manifest_content = {
// Load Cargo.toml & parse
let content = {
let mut file = File::open(package.manifest_path()).unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
content
};
let config: TomlConfig = toml::from_str(&content).map_err(failure::Error::from)?;
config.package.metadata.and_then(|m| m.android)
};
// Determine the NDK path
let ndk_path = env::var("NDK_HOME").map_err(|_| {
format_err!(
"Please set the path to the Android NDK with the \
$NDK_HOME environment variable."
)
})?;
let sdk_path = {
let mut sdk_path = env::var("ANDROID_SDK_HOME").ok();
if sdk_path.is_none() {
sdk_path = env::var("ANDROID_HOME").ok();
}
sdk_path.ok_or_else(|| {
format_err!(
"Please set the path to the Android SDK with either the $ANDROID_SDK_HOME or \
the $ANDROID_HOME environment variable."
)
})?
};
// Find the highest build tools.
let build_tools_version = {
let dir = fs::read_dir(Path::new(&sdk_path).join("build-tools"))
.map_err(|_| format_err!("Android SDK has no build-tools directory"))?;
let mut versions = Vec::new();
for next in dir {
let next = next.unwrap();
let meta = next.metadata().unwrap();
if !meta.is_dir() {
if !meta.is_file() {
// It seems, symlink is here, so we should follow it
let meta = next.path().metadata().unwrap();
if !meta.is_dir() {
continue;
}
} else {
continue;
}
}
let file_name = next.file_name().into_string().unwrap();
if !file_name.chars().next().unwrap().is_digit(10) {
continue;
}
versions.push(file_name);
}
versions.sort_by(|a, b| b.cmp(&a));
versions
.into_iter()
.next()
.ok_or_else(|| format_err!("Unable to determine build tools version"))?
};
// Determine the Sdk versions (compile, target, min)
let android_version = manifest_content
.as_ref()
.and_then(|a| a.android_version)
.unwrap_or(29);
// Check that the tool for the android platform is installed
let android_jar_path = Path::new(&sdk_path)
.join("platforms")
.join(format!("android-{}", android_version))
.join("android.jar");
if !android_jar_path.exists() {
Err(format_err!(
"'{}' does not exist",
android_jar_path.to_string_lossy()
))?;
}
let target_sdk_version = manifest_content
.as_ref()
.and_then(|a| a.target_sdk_version)
.unwrap_or(android_version);
let min_sdk_version = manifest_content
.as_ref()
.and_then(|a| a.min_sdk_version)
.unwrap_or(18);
let default_target_config = manifest_content
.as_ref()
.map(|a| a.default_target_config.clone())
.unwrap_or_else(Default::default);
let mut target_configs = BTreeMap::new();
manifest_content
.as_ref()
.and_then(|a| a.bin.as_ref())
.unwrap_or(&Vec::new())
.iter()
.for_each(|t| {
target_configs.insert((TargetKind::Bin, t.name.clone()), t.config.clone());
});
manifest_content
.as_ref()
.and_then(|a| a.example.as_ref())
.unwrap_or(&Vec::new())
.iter()
.for_each(|t| {
target_configs.insert((TargetKind::ExampleBin, t.name.clone()), t.config.clone());
});
// For the moment some fields of the config are dummies.
Ok(AndroidConfig {
cargo_package_name: package.name().to_string(),
cargo_package_version: package.version().to_string(),
manifest_path: package.manifest_path().to_owned(),
sdk_path: Path::new(&sdk_path).to_owned(),
ndk_path: Path::new(&ndk_path).to_owned(),
android_jar_path,
target_sdk_version,
min_sdk_version,
build_tools_version,
release: false,
build_targets: manifest_content
.as_ref()
.and_then(|a| a.build_targets.clone())
.unwrap_or_else(|| {
vec![
AndroidBuildTarget::ArmV7a,
AndroidBuildTarget::Arm64V8a,
AndroidBuildTarget::X86,
]
}),
default_target_config,
target_configs,
})
}
fn build_attribute_string(input_map: BTreeMap<String, String>) -> String {
input_map
.iter()
.map(|(key, val)| format!("\n{}=\"{}\"", key, val))
.join("")
}
#[derive(Debug, Clone, Deserialize)]
struct TomlConfig {
package: TomlPackage,
}
#[derive(Debug, Clone, Deserialize)]
struct TomlPackage {
name: String,
metadata: Option<TomlMetadata>,
}
#[derive(Debug, Clone, Deserialize)]
struct TomlMetadata {
android: Option<TomlAndroid>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct TomlAndroid {
android_version: Option<u32>,
target_sdk_version: Option<u32>,
min_sdk_version: Option<u32>,
build_targets: Option<Vec<AndroidBuildTarget>>,
#[serde(flatten)]
default_target_config: TomlAndroidTarget,
bin: Option<Vec<TomlAndroidSpecificTarget>>,
example: Option<Vec<TomlAndroidSpecificTarget>>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct TomlFeature {
name: String,
required: Option<bool>,
version: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct TomlPermission {
name: String,
max_sdk_version: Option<u32>,
}
/// Configuration specific to a single cargo target
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct TomlAndroidSpecificTarget {
name: String,
#[serde(flatten)]
config: TomlAndroidTarget,
}
#[derive(Debug, Default, Clone, Deserialize)]
struct TomlAndroidTarget {
package_name: Option<String>,
label: Option<String>,
version_code: Option<i32>,
version_name: Option<String>,
icon: Option<String>,
assets: Option<String>,
res: Option<String>,
fullscreen: Option<bool>,
application_attributes: Option<BTreeMap<String, String>>,
activity_attributes: Option<BTreeMap<String, String>>,
opengles_version_major: Option<u8>,
opengles_version_minor: Option<u8>,
feature: Option<Vec<TomlFeature>>,
permission: Option<Vec<TomlPermission>>,
}
================================================
FILE: cargo-apk/src/main.rs
================================================
use cargo::core::Workspace;
use cargo::util::process_builder::process;
use cargo::util::Config as CargoConfig;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use failure::format_err;
use cargo::util::command_prelude::opt;
use cargo::util::command_prelude::AppExt;
use cargo::util::command_prelude::ArgMatchesExt;
mod config;
mod ops;
fn main() {
let mut cargo_config = CargoConfig::default().unwrap();
let args = match cli().get_matches_safe() {
Ok(args) => args,
Err(err) => cargo::exit_with_error(err.into(), &mut *cargo_config.shell()),
};
let args = match args.subcommand() {
("apk", Some(subcommand_matches)) => subcommand_matches,
_ => &args,
};
let (command, subcommand_args) = match args.subcommand() {
(command, Some(subcommand_args)) => (command, subcommand_args),
_ => {
drop(cli().print_help());
return;
}
};
let arg_target_dir = &subcommand_args.value_of_path("target-dir", &cargo_config);
cargo_config
.configure(
args.occurrences_of("verbose") as u32,
if args.is_present("quiet") {
Some(true)
} else {
None
},
&args.value_of("color").map(|s| s.to_string()),
args.is_present("frozen"),
args.is_present("locked"),
args.is_present("offline"),
arg_target_dir,
&args
.values_of_lossy("unstable-features")
.unwrap_or_default(),
)
.unwrap();
let err = match command {
"build" => execute_build(&subcommand_args, &cargo_config),
"install" => execute_install(&subcommand_args, &cargo_config),
"run" => execute_run(&subcommand_args, &cargo_config),
"logcat" => execute_logcat(&subcommand_args, &cargo_config),
_ => cargo::exit_with_error(
format_err!(
"Expected `build`, `install`, `run`, or `logcat`. Got {}",
command
)
.into(),
&mut *cargo_config.shell(),
),
};
match err {
Ok(_) => (),
Err(err) => cargo::exit_with_error(err, &mut *cargo_config.shell()),
}
}
fn cli() -> App<'static, 'static> {
App::new("cargo-apk")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::VersionlessSubcommands,
AppSettings::AllowExternalSubcommands,
])
.arg(
opt(
"verbose",
"Use verbose output (-vv very verbose/build.rs output)",
)
.short("v")
.multiple(true)
.global(true),
)
.arg(opt("quiet", "No output printed to stdout").short("q"))
.arg(
opt("color", "Coloring: auto, always, never")
.value_name("WHEN")
.global(true),
)
.arg(opt("frozen", "Require Cargo.lock and cache are up to date").global(true))
.arg(opt("locked", "Require Cargo.lock is up to date").global(true))
.arg(opt("offline", "Run without accessing the network").global(true))
.arg(
Arg::with_name("unstable-features")
.help("Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details")
.short("Z")
.value_name("FLAG")
.multiple(true)
.number_of_values(1)
.global(true),
)
.subcommands(vec![
cli_apk(),
cli_build(),
cli_install(),
cli_run(),
cli_logcat(),
])
}
fn cli_apk() -> App<'static, 'static> {
SubCommand::with_name("apk")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
])
.about("dummy subcommand to allow for calling cargo apk instead of cargo-apk")
.subcommands(vec![cli_build(), cli_install(), cli_run(), cli_logcat()])
}
fn cli_build() -> App<'static, 'static> {
SubCommand::with_name("build")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
])
.alias("b")
.about("Compile a local package and all of its dependencies")
.arg_package_spec(
"Package to build (see `cargo help pkgid`)",
"Build all packages in the workspace",
"Exclude packages from the build",
)
.arg_jobs()
.arg_targets_all(
"Build only this package's library",
"Build only the specified binary",
"Build all binaries",
"Build only the specified example",
"Build all examples",
"Build only the specified test target",
"Build all tests",
"Build only the specified bench target",
"Build all benches",
"Build all targets",
)
.arg_release("Build artifacts in release mode, with optimizations")
.arg_features()
.arg_target_triple("Build for the target triple")
.arg_target_dir()
.arg(opt("out-dir", "Copy final artifacts to this directory").value_name("PATH"))
.arg_manifest_path()
.arg_message_format()
.arg_build_plan()
.after_help(
"\
All packages in the workspace are built if the `--all` flag is supplied. The
`--all` flag is automatically assumed for a virtual manifest.
Note that `--exclude` has to be specified in conjunction with the `--all` flag.
Compilation can be configured via the use of profiles which are configured in
the manifest. The default profile for this command is `dev`, but passing
the --release flag will use the `release` profile instead.
",
)
}
fn cli_install() -> App<'static, 'static> {
SubCommand::with_name("install")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
])
.about("Install a Rust binary")
.arg(Arg::with_name("crate").empty_values(false).multiple(true))
.arg(
opt("version", "Specify a version to install from crates.io")
.alias("vers")
.value_name("VERSION"),
)
.arg(opt("git", "Git URL to install the specified crate from").value_name("URL"))
.arg(opt("branch", "Branch to use when installing from git").value_name("BRANCH"))
.arg(opt("tag", "Tag to use when installing from git").value_name("TAG"))
.arg(opt("rev", "Specific commit to use when installing from git").value_name("SHA"))
.arg(opt("path", "Filesystem path to local crate to install").value_name("PATH"))
.arg(opt(
"list",
"list all installed packages and their versions",
))
.arg_jobs()
.arg(opt("force", "Force overwriting existing crates or binaries").short("f"))
.arg_features()
.arg(opt("debug", "Build in debug mode instead of release mode"))
.arg_targets_bins_examples(
"Install only the specified binary",
"Install all binaries",
"Install only the specified example",
"Install all examples",
)
.arg_target_triple("Build for the target triple")
.arg(opt("root", "Directory to install packages into").value_name("DIR"))
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
.after_help(
"\
This command manages Cargo's local set of installed binary crates. Only packages
which have [[bin]] targets can be installed, and all binaries are installed into
the installation root's `bin` folder. The installation root is determined, in
order of precedence, by `--root`, `$CARGO_INSTALL_ROOT`, the `install.root`
configuration key, and finally the home directory (which is either
`$CARGO_HOME` if set or `$HOME/.cargo` by default).
There are multiple sources from which a crate can be installed. The default
location is crates.io but the `--git` and `--path` flags can change this source.
If the source contains more than one package (such as crates.io or a git
repository with multiple crates) the `<crate>` argument is required to indicate
which crate should be installed.
Crates from crates.io can optionally specify the version they wish to install
via the `--vers` flags, and similarly packages from git repositories can
optionally specify the branch, tag, or revision that should be installed. If a
crate has multiple binaries, the `--bin` argument can selectively install only
one of them, and if you'd rather install examples the `--example` argument can
be used as well.
By default cargo will refuse to overwrite existing binaries. The `--force` flag
enables overwriting existing binaries. Thus you can reinstall a crate with
`cargo install --force <crate>`.
Omitting the <crate> specification entirely will
install the crate in the current directory. That is, `install` is equivalent to
the more explicit `install --path .`. This behaviour is deprecated, and no
longer supported as of the Rust 2018 edition.
If the source is crates.io or `--git` then by default the crate will be built
in a temporary target directory. To avoid this, the target directory can be
specified by setting the `CARGO_TARGET_DIR` environment variable to a relative
path. In particular, this can be useful for caching build artifacts on
continuous integration systems.",
)
}
fn cli_run() -> App<'static, 'static> {
SubCommand::with_name("run")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
])
.alias("r")
.setting(AppSettings::TrailingVarArg)
.about("Run the main binary of the local package (src/main.rs)")
.arg(Arg::with_name("args").multiple(true))
.arg_targets_bin_example(
"Name of the bin target to run",
"Name of the example target to run",
)
.arg_package("Package with the target to run")
.arg_jobs()
.arg_release("Build artifacts in release mode, with optimizations")
.arg_features()
.arg_target_triple("Build for the target triple")
.arg_target_dir()
.arg_manifest_path()
.arg_message_format()
.after_help(
"\
If neither `--bin` nor `--example` are given, then if the package only has one
bin target it will be run. Otherwise `--bin` specifies the bin target to run,
and `--example` specifies the example target to run. At most one of `--bin` or
`--example` can be provided.
All the arguments following the two dashes (`--`) are passed to the binary to
run. If you're passing arguments to both Cargo and the binary, the ones after
`--` go to the binary, the ones before go to Cargo.
",
)
}
fn cli_logcat() -> App<'static, 'static> {
SubCommand::with_name("logcat")
.settings(&[
AppSettings::UnifiedHelpMessage,
AppSettings::DeriveDisplayOrder,
AppSettings::DontCollapseArgsInUsage,
])
.alias("r")
.about("Print Android log")
.arg_message_format()
}
pub fn execute_build(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult {
let root_manifest = options.root_manifest(&cargo_config)?;
let workspace = Workspace::new(&root_manifest, &cargo_config)?;
let mut android_config = config::load(
&workspace,
&options.value_of("package").map(|s| s.to_owned()),
)?;
android_config.release = options.is_present("release");
ops::build(&workspace, &android_config, &options)?;
Ok(())
}
pub fn execute_install(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult {
let root_manifest = options.root_manifest(&cargo_config)?;
let workspace = Workspace::new(&root_manifest, &cargo_config)?;
let mut android_config = config::load(
&workspace,
&options.value_of("package").map(|s| s.to_owned()),
)?;
android_config.release = !options.is_present("debug");
ops::install(&workspace, &android_config, &options)?;
Ok(())
}
pub fn execute_run(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult {
let root_manifest = options.root_manifest(&cargo_config)?;
let workspace = Workspace::new(&root_manifest, &cargo_config)?;
let mut android_config = config::load(
&workspace,
&options.value_of("package").map(|s| s.to_owned()),
)?;
android_config.release = options.is_present("release");
ops::run(&workspace, &android_config, &options)?;
Ok(())
}
pub fn execute_logcat(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult {
let root_manifest = options.root_manifest(&cargo_config)?;
let workspace = Workspace::new(&root_manifest, &cargo_config)?;
let android_config = config::load(
&workspace,
&options.value_of("package").map(|s| s.to_owned()),
)?;
drop(writeln!(
workspace.config().shell().err(),
"Starting logcat"
));
let adb = android_config.sdk_path.join("platform-tools/adb");
process(&adb).arg("logcat").exec()?;
Ok(())
}
================================================
FILE: cargo-apk/src/ops/build/compile.rs
================================================
use super::tempfile::TempFile;
use super::util;
use crate::config::AndroidBuildTarget;
use crate::config::AndroidConfig;
use cargo::core::compiler::Executor;
use cargo::core::compiler::{CompileKind, CompileMode, CompileTarget};
use cargo::core::manifest::TargetSourcePath;
use cargo::core::{PackageId, Target, TargetKind, Workspace};
use cargo::util::command_prelude::{ArgMatchesExt, ProfileChecking};
use cargo::util::{process, CargoResult, ProcessBuilder, dylib_path};
use clap::ArgMatches;
use failure::format_err;
use multimap::MultiMap;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::collections::{HashSet, HashMap};
pub struct SharedLibrary {
pub abi: AndroidBuildTarget,
pub path: PathBuf,
pub filename: String,
}
pub struct SharedLibraries {
pub shared_libraries: MultiMap<Target, SharedLibrary>,
}
/// For each build target and cargo binary or example target, produce a shared library
pub fn build_shared_libraries(
workspace: &Workspace,
config: &AndroidConfig,
options: &ArgMatches,
root_build_dir: &PathBuf,
) -> CargoResult<SharedLibraries> {
let android_native_glue_src_path = write_native_app_glue_src(&root_build_dir)?;
let shared_libraries: Arc<Mutex<MultiMap<Target, SharedLibrary>>> =
Arc::new(Mutex::new(MultiMap::new()));
for &build_target in config.build_targets.iter() {
// Directory that will contain files specific to this build target
let build_target_dir = root_build_dir.join(build_target.android_abi());
fs::create_dir_all(&build_target_dir).unwrap();
// Set environment variables needed for use with the cc crate
std::env::set_var("CC", util::find_clang(config, build_target)?);
std::env::set_var("CXX", util::find_clang_cpp(config, build_target)?);
std::env::set_var("AR", util::find_ar(config, build_target)?);
// Use libc++. It is current default C++ runtime
std::env::set_var("CXXSTDLIB", "c++");
// Generate cmake toolchain and set environment variables to allow projects which use the cmake crate to build correctly
let cmake_toolchain_path = write_cmake_toolchain(config, &build_target_dir, build_target)?;
std::env::set_var("CMAKE_TOOLCHAIN_FILE", cmake_toolchain_path);
std::env::set_var("CMAKE_GENERATOR", r#"Unix Makefiles"#);
std::env::set_var("CMAKE_MAKE_PROGRAM", util::make_path(config));
// Build android_native_glue
let android_native_glue_object = build_android_native_glue(
config,
&android_native_glue_src_path,
&build_target_dir,
build_target,
)?;
// Configure compilation options so that we will build the desired build_target
let mut opts = options.compile_options(
workspace.config(),
CompileMode::Build,
Some(&workspace),
ProfileChecking::Unchecked,
)?;
opts.build_config.requested_kind =
CompileKind::Target(CompileTarget::new(build_target.rust_triple())?);
// Create executor
let config = Arc::new(config.clone());
let executor: Arc<dyn Executor> = Arc::new(SharedLibraryExecutor {
config: Arc::clone(&config),
build_target_dir: build_target_dir.clone(),
android_native_glue_object,
build_target,
shared_libraries: shared_libraries.clone(),
});
// Compile all targets for the requested build target
cargo::ops::compile_with_exec(workspace, &opts, &executor)?;
}
// Remove the set of targets from the reference counted mutex
let mut shared_libraries = shared_libraries.lock().unwrap();
let shared_libraries = std::mem::replace(&mut *shared_libraries, MultiMap::new());
Ok(SharedLibraries { shared_libraries })
}
/// Executor which builds binary and example targets as static libraries
struct SharedLibraryExecutor {
config: Arc<AndroidConfig>,
build_target_dir: PathBuf,
android_native_glue_object: PathBuf,
build_target: AndroidBuildTarget,
// Shared libraries built by the executor are added to this multimap
shared_libraries: Arc<Mutex<MultiMap<Target, SharedLibrary>>>,
}
impl Executor for SharedLibraryExecutor {
fn exec(
&self,
cmd: ProcessBuilder,
_id: PackageId,
target: &Target,
mode: CompileMode,
on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
) -> CargoResult<()> {
if mode == CompileMode::Build
&& (target.kind() == &TargetKind::Bin || target.kind() == &TargetKind::ExampleBin)
{
let mut new_args = cmd.get_args().to_owned();
//
// Determine source path
//
let path = if let TargetSourcePath::Path(path) = target.src_path() {
path.to_owned()
} else {
// Ignore other values
return Ok(());
};
let original_src_filepath = path.canonicalize()?;
//
// Generate source file that will be built
//
// Determine the name of the temporary file
let tmp_lib_filepath = original_src_filepath.parent().unwrap().join(format!(
"__cargo_apk_{}.tmp",
original_src_filepath
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(String::new)
));
// Create the temporary file
let original_contents = fs::read_to_string(original_src_filepath).unwrap();
let tmp_file = TempFile::new(tmp_lib_filepath.clone(), |lib_src_file| {
let extra_code = r##"
mod cargo_apk_glue_code {
use std::os::raw::c_void;
// Exported function which is called be Android's NativeActivity
#[no_mangle]
pub unsafe extern "C" fn ANativeActivity_onCreate(
activity: *mut c_void,
saved_state: *mut c_void,
saved_state_size: usize,
) {
native_app_glue_onCreate(activity, saved_state, saved_state_size);
}
extern "C" {
#[allow(non_snake_case)]
fn native_app_glue_onCreate(
activity: *mut c_void,
saved_state: *mut c_void,
saved_state_size: usize,
);
}
#[no_mangle]
extern "C" fn android_main(_app: *mut c_void) {
let _ = super::main();
}
#[link(name = "android")]
#[link(name = "log")]
extern "C" {}
}"##;
writeln!( lib_src_file, "{}\n{}", original_contents, extra_code)?;
Ok(())
}).map_err(|e| format_err!(
"Unable to create temporary source file `{}`. Source directory must be writable. Cargo-apk creates temporary source files as part of the build process. {}.", tmp_lib_filepath.to_string_lossy(), e)
)?;
//
// Replace source argument
//
let filename = path.file_name().unwrap().to_owned();
let source_arg = new_args.iter_mut().find_map(|arg| {
let path_arg = Path::new(&arg);
let tmp = path_arg.file_name().unwrap();
if filename == tmp {
Some(arg)
} else {
None
}
});
if let Some(source_arg) = source_arg {
// Build a new relative path to the temporary source file and use it as the source argument
// Using an absolute path causes compatibility issues in some cases under windows
// If a UNC path is used then relative paths used in "include* macros" may not work if
// the relative path includes "/" instead of "\"
let path_arg = Path::new(&source_arg);
let mut path_arg = path_arg.to_path_buf();
path_arg.set_file_name(tmp_file.path.file_name().unwrap());
*source_arg = path_arg.into_os_string();
} else {
return Err(format_err!(
"Unable to replace source argument when building target '{}'",
target.name()
));
}
//
// Create output directory inside the build target directory
//
let build_path = self.build_target_dir.join("build");
fs::create_dir_all(&build_path).unwrap();
//
// Change crate-type from bin to cdylib
// Replace output directory with the directory we created
//
let mut iter = new_args.iter_mut().rev().peekable();
while let Some(arg) = iter.next() {
if let Some(prev_arg) = iter.peek() {
if *prev_arg == "--crate-type" && arg == "bin" {
*arg = "cdylib".into();
} else if *prev_arg == "--out-dir" {
*arg = build_path.clone().into();
}
}
}
// Helper function to build arguments composed of concatenating two strings
fn build_arg(start: &str, end: impl AsRef<OsStr>) -> OsString {
let mut new_arg = OsString::new();
new_arg.push(start);
new_arg.push(end.as_ref());
new_arg
}
// Determine paths
let tool_root = util::llvm_toolchain_root(&self.config);
let linker_path = tool_root
.join("bin")
.join(format!("{}-ld", &self.build_target.ndk_triple()));
let sysroot = tool_root.join("sysroot");
let version_independent_libraries_path = sysroot
.join("usr")
.join("lib")
.join(&self.build_target.ndk_triple());
let version_specific_libraries_path =
util::find_ndk_path(self.config.min_sdk_version, |platform| {
version_independent_libraries_path.join(platform.to_string())
})?;
let gcc_lib_path = tool_root
.join("lib/gcc")
.join(&self.build_target.ndk_triple())
.join("4.9.x");
// Add linker arguments
// Specify linker
new_args.push(build_arg("-Clinker=", linker_path));
// Set linker flavor
new_args.push("-Clinker-flavor=ld".into());
// Set system root
new_args.push(build_arg("-Clink-arg=--sysroot=", sysroot));
// Add version specific libraries directory to search path
new_args.push(build_arg("-Clink-arg=-L", &version_specific_libraries_path));
// Add version independent libraries directory to search path
new_args.push(build_arg(
"-Clink-arg=-L",
&version_independent_libraries_path,
));
// Add path to folder containing libgcc.a to search path
new_args.push(build_arg("-Clink-arg=-L", gcc_lib_path));
// Add android native glue
new_args.push(build_arg("-Clink-arg=", &self.android_native_glue_object));
// Strip symbols for release builds
if self.config.release {
new_args.push("-Clink-arg=-strip-all".into());
}
// Require position independent code
new_args.push("-Crelocation-model=pic".into());
// Create new command
let mut cmd = cmd.clone();
cmd.args_replace(&new_args);
//
// Execute the command
//
cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
.map(drop)?;
// Execute the command again with the print flag to determine the name of the produced shared library and then add it to the list of shared librares to be added to the APK
let stdout = cmd.arg("--print").arg("file-names").exec_with_output()?;
let stdout = String::from_utf8(stdout.stdout).unwrap();
let library_path = build_path.join(stdout.lines().next().unwrap());
let mut shared_libraries = self.shared_libraries.lock().unwrap();
shared_libraries.insert(
target.clone(),
SharedLibrary {
abi: self.build_target,
path: library_path.clone(),
filename: format!("lib{}.so", target.name()),
},
);
// If the target uses the C++ standard library, add the appropriate shared library
// to the list of shared libraries to be added to the APK
let readelf_path = util::find_readelf(&self.config, self.build_target)?;
// Gets libraries search paths from compiler
let mut libs_search_paths = libs_search_paths_from_args(cmd.get_args());
// Add path for searching version independent libraries like 'libc++_shared.so'
libs_search_paths.push(version_independent_libraries_path);
// Add target/ARCH/PROFILE/deps directory for searching dylib/cdylib
libs_search_paths.push(self.build_target_dir.join("deps"));
// FIXME: Add extra libraries search paths (from "LD_LIBRARY_PATH")
libs_search_paths.extend(dylib_path());
// Find android platform shared libraries
let android_dylibs = list_android_dylibs(&version_specific_libraries_path)?;
// The map of [library]: is_processed
let mut found_dylibs =
// Add android platform libraries as processed to avoid packaging it
android_dylibs.into_iter().map(|dylib| (dylib, true))
.collect::<HashMap<_, _>>();
// Extract all needed shared libraries from main
for dylib in list_needed_dylibs(&readelf_path, &library_path)? {
// Insert new libraries only
found_dylibs.entry(dylib).or_insert(false);
}
while let Some(dylib) = found_dylibs.iter()
.find(|(_, is_processed)| !*is_processed)
.map(|(dylib, _)| dylib.clone())
{
// Mark library as processed
*found_dylibs.get_mut(&dylib).unwrap() = true;
// Find library in known path
if let Some(path) = find_library_path(&libs_search_paths, &dylib) {
// Extract all needed shared libraries recursively
for dylib in list_needed_dylibs(&readelf_path, &path)? {
// Insert new libraries only
found_dylibs.entry(dylib).or_insert(false);
}
// Add found library
shared_libraries.insert(
target.clone(),
SharedLibrary {
abi: self.build_target,
path,
filename: dylib.clone(),
},
);
} else {
on_stderr_line(&format!("Warning: Shared library \"{}\" not found.", &dylib))?;
}
}
} else if mode == CompileMode::Test {
// This occurs when --all-targets is specified
eprintln!("Ignoring CompileMode::Test for target: {}", target.name());
} else if mode == CompileMode::Build {
let mut new_args = cmd.get_args().to_owned();
//
// Change crate-type from cdylib to rlib
//
let mut iter = new_args.iter_mut().rev().peekable();
while let Some(arg) = iter.next() {
if let Some(prev_arg) = iter.peek() {
if *prev_arg == "--crate-type" && arg == "cdylib" {
*arg = "rlib".into();
}
}
}
let mut cmd = cmd.clone();
cmd.args_replace(&new_args);
cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
.map(drop)?
} else {
cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false)
.map(drop)?
}
Ok(())
}
}
/// List all linked shared libraries
fn list_needed_dylibs(readelf_path: &Path, library_path: &Path) -> CargoResult<HashSet<String>> {
let readelf_output = process(readelf_path)
.arg("-d")
.arg(&library_path)
.exec_with_output()?;
use std::io::BufRead;
Ok(readelf_output.stdout.lines().filter_map(|l| {
let l = l.as_ref().unwrap();
if l.contains("(NEEDED)") {
if let Some(lib) = l.split("Shared library: [").last() {
if let Some(lib) = lib.split("]").next() {
return Some(lib.into());
}
}
}
None
}).collect())
}
/// List Android shared libraries
fn list_android_dylibs(version_specific_libraries_path: &Path) -> CargoResult<HashSet<String>> {
fs::read_dir(version_specific_libraries_path)?
.filter_map(|entry| {
entry.map(|entry| {
if entry.path().is_file() {
if let Some(file_name) = entry.file_name().to_str() {
if file_name.ends_with(".so") {
return Some(file_name.into());
}
}
}
None
}).transpose()
})
.collect::<Result<_, _>>()
.map_err(|err| err.into())
}
/// Get native library search paths from rustc args
fn libs_search_paths_from_args(args: &[std::ffi::OsString]) -> Vec<PathBuf> {
let mut is_search_path = false;
args.iter().filter_map(|arg| {
if is_search_path {
is_search_path = false;
arg.to_str().and_then(|arg| if arg.starts_with("native=") || arg.starts_with("dependency=") {
Some(arg.split("=").last().unwrap().into())
} else {
None
})
} else {
if arg == "-L" {
is_search_path = true;
}
None
}
}).collect()
}
/// Resolves native library using search paths
fn find_library_path<S: AsRef<Path>>(paths: &Vec<PathBuf>, library: S) -> Option<PathBuf> {
paths.iter().filter_map(|path| {
let lib_path = path.join(&library);
if lib_path.is_file() {
Some(lib_path)
} else {
None
}
}).nth(0)
}
/// Returns the path to the ".c" file for the android native app glue
fn write_native_app_glue_src(android_artifacts_dir: &Path) -> CargoResult<PathBuf> {
let output_dir = android_artifacts_dir.join("native_app_glue");
fs::create_dir_all(&output_dir).unwrap();
let mut h_file = File::create(output_dir.join("android_native_app_glue.h"))?;
h_file.write_all(&include_bytes!("../../../native_app_glue/android_native_app_glue.h")[..])?;
let c_path = output_dir.join("android_native_app_glue.c");
let mut c_file = File::create(&c_path)?;
c_file.write_all(&include_bytes!("../../../native_app_glue/android_native_app_glue.c")[..])?;
Ok(c_path)
}
/// Returns the path to the built object file for the android native glue
fn build_android_native_glue(
config: &AndroidConfig,
android_native_glue_src_path: &PathBuf,
build_target_dir: &PathBuf,
build_target: AndroidBuildTarget,
) -> CargoResult<PathBuf> {
let clang = util::find_clang(config, build_target)?;
let android_native_glue_build_path = build_target_dir.join("android_native_glue");
fs::create_dir_all(&android_native_glue_build_path)?;
let android_native_glue_object_path =
android_native_glue_build_path.join("android_native_glue.o");
// Will produce warnings when bulding on linux? Create constants for extensions that can be used.. Or have separate functions?
util::script_process(clang)
.arg(android_native_glue_src_path)
.arg("-c")
.arg("-o")
.arg(&android_native_glue_object_path)
.exec()?;
Ok(android_native_glue_object_path)
}
/// Write a CMake toolchain which will remove references to the rustc build target before including
/// the NDK provided toolchain. The NDK provided android toolchain will set the target appropriately
/// Returns the path to the generated toolchain file
fn write_cmake_toolchain(
config: &AndroidConfig,
build_target_dir: &PathBuf,
build_target: AndroidBuildTarget,
) -> CargoResult<PathBuf> {
let toolchain_path = build_target_dir.join("cargo-apk.toolchain.cmake");
let mut toolchain_file = File::create(&toolchain_path).unwrap();
writeln!(
toolchain_file,
r#"set(ANDROID_PLATFORM android-{min_sdk_version})
set(ANDROID_ABI {abi})
string(REPLACE "--target={build_target}" "" CMAKE_C_FLAGS "${{CMAKE_C_FLAGS}}")
string(REPLACE "--target={build_target}" "" CMAKE_CXX_FLAGS "${{CMAKE_CXX_FLAGS}}")
unset(CMAKE_C_COMPILER CACHE)
unset(CMAKE_CXX_COMPILER CACHE)
include("{ndk_path}/build/cmake/android.toolchain.cmake")"#,
min_sdk_version = config.min_sdk_version,
ndk_path = config.ndk_path.to_string_lossy().replace("\\", "/"), // Use forward slashes even on windows to avoid path escaping issues.
build_target = build_target.rust_triple(),
abi = build_target.android_abi(),
)?;
Ok(toolchain_path)
}
================================================
FILE: cargo-apk/src/ops/build/targets.rs
================================================
use crate::config::AndroidBuildTarget;
impl AndroidBuildTarget {
/// Identifier used in the NDK to refer to the ABI
pub fn android_abi(self) -> &'static str {
match self {
AndroidBuildTarget::ArmV7a => "armeabi-v7a",
AndroidBuildTarget::Arm64V8a => "arm64-v8a",
AndroidBuildTarget::X86 => "x86",
AndroidBuildTarget::X86_64 => "x86_64",
}
}
/// Returns the triple used by the rust build tools
pub fn rust_triple(self) -> &'static str {
match self {
AndroidBuildTarget::ArmV7a => "armv7-linux-androideabi",
AndroidBuildTarget::Arm64V8a => "aarch64-linux-android",
AndroidBuildTarget::X86 => "i686-linux-android",
AndroidBuildTarget::X86_64 => "x86_64-linux-android",
}
}
// Returns the triple NDK provided LLVM
pub fn ndk_llvm_triple(self) -> &'static str {
match self {
AndroidBuildTarget::ArmV7a => "armv7a-linux-androideabi",
AndroidBuildTarget::Arm64V8a => "aarch64-linux-android",
AndroidBuildTarget::X86 => "i686-linux-android",
AndroidBuildTarget::X86_64 => "x86_64-linux-android",
}
}
/// Returns the triple used by the non-LLVM parts of the NDK
pub fn ndk_triple(self) -> &'static str {
match self {
AndroidBuildTarget::ArmV7a => "arm-linux-androideabi",
AndroidBuildTarget::Arm64V8a => "aarch64-linux-android",
AndroidBuildTarget::X86 => "i686-linux-android",
AndroidBuildTarget::X86_64 => "x86_64-linux-android",
}
}
}
================================================
FILE: cargo-apk/src/ops/build/tempfile.rs
================================================
use cargo::util::CargoResult;
use std::fs::{self, File};
use std::path::PathBuf;
/// Temporary file implementation that allows creating a file with a specified path which
/// will be deleted when dropped.
pub struct TempFile {
pub path: PathBuf,
}
impl TempFile {
/// Create a new `TempFile` using the contents provided by a closure.
/// If the file already exists, it will be overwritten and then deleted when the instance
/// is dropped.
pub fn new<F>(path: PathBuf, write_contents: F) -> CargoResult<TempFile>
where
F: FnOnce(&mut File) -> CargoResult<()>,
{
let tmp_file = TempFile { path };
// Write the contents to the the temp file
let mut file = File::create(&tmp_file.path)?;
write_contents(&mut file)?;
Ok(tmp_file)
}
}
impl Drop for TempFile {
fn drop(&mut self) {
fs::remove_file(&self.path).unwrap_or_else(|e| {
eprintln!(
"Unable to remove temporary file: {}. {}",
&self.path.to_string_lossy(),
&e
);
})
}
}
================================================
FILE: cargo-apk/src/ops/build/util.rs
================================================
use crate::config::{AndroidBuildTarget, AndroidConfig};
use cargo::core::{Target, TargetKind, Workspace};
use cargo::util::{process, CargoResult, ProcessBuilder};
use failure::format_err;
use std::ffi::OsStr;
use std::path::PathBuf;
/// Returns the directory in which all cargo apk artifacts for the current
/// debug/release configuration should be produced.
pub fn get_root_build_directory(workspace: &Workspace, config: &AndroidConfig) -> PathBuf {
let android_artifacts_dir = workspace
.target_dir()
.join("android-artifacts")
.into_path_unlocked();
if config.release {
android_artifacts_dir.join("release")
} else {
android_artifacts_dir.join("debug")
}
}
/// Returns the sub directory within the root build directory for the specified target.
pub fn get_target_directory(root_build_dir: &PathBuf, target: &Target) -> CargoResult<PathBuf> {
let target_directory = match target.kind() {
TargetKind::Bin => root_build_dir.join("bin"),
TargetKind::ExampleBin => root_build_dir.join("examples"),
_ => unreachable!("Unexpected target kind"),
};
let target_directory = target_directory.join(target.name());
Ok(target_directory)
}
/// Returns path to NDK provided make
pub fn make_path(config: &AndroidConfig) -> PathBuf {
config.ndk_path.join("prebuild").join(HOST_TAG).join("make")
}
/// Returns the path to the LLVM toolchain provided by the NDK
pub fn llvm_toolchain_root(config: &AndroidConfig) -> PathBuf {
config
.ndk_path
.join("toolchains")
.join("llvm")
.join("prebuilt")
.join(HOST_TAG)
}
// Helper function for looking for a path based on the platform version
// Calls a closure for each attempt and then return the PathBuf for the first file that exists.
// Uses approach that NDK build tools use which is described at:
// https://developer.android.com/ndk/guides/application_mk
// " - The platform version matching APP_PLATFORM.
// - The next available API level below APP_PLATFORM. For example, android-19 will be used when
// APP_PLATFORM is android-20, since there were no new native APIs in android-20.
// - The minimum API level supported by the NDK."
pub fn find_ndk_path<F>(platform: u32, path_builder: F) -> CargoResult<PathBuf>
where
F: Fn(u32) -> PathBuf,
{
let mut tmp_platform = platform;
// Look for the file which matches the specified platform
// If that doesn't exist, look for a lower version
while tmp_platform > 1 {
let path = path_builder(tmp_platform);
if path.exists() {
return Ok(path);
}
tmp_platform -= 1;
}
// If that doesn't exist... Look for a higher one. This would be the minimum API level supported by the NDK
tmp_platform = platform;
while tmp_platform < 100 {
let path = path_builder(tmp_platform);
if path.exists() {
return Ok(path);
}
tmp_platform += 1;
}
Err(format_err!("Unable to find NDK file"))
}
// Returns path to clang executable/script that should be used to build the target
pub fn find_clang(
config: &AndroidConfig,
build_target: AndroidBuildTarget,
) -> CargoResult<PathBuf> {
let bin_folder = llvm_toolchain_root(config).join("bin");
find_ndk_path(config.min_sdk_version, |platform| {
bin_folder.join(format!(
"{}{}-clang{}",
build_target.ndk_llvm_triple(),
platform,
EXECUTABLE_SUFFIX_CMD
))
})
.map_err(|_| format_err!("Unable to find NDK clang"))
}
// Returns path to clang++ executable/script that should be used to build the target
pub fn find_clang_cpp(
config: &AndroidConfig,
build_target: AndroidBuildTarget,
) -> CargoResult<PathBuf> {
let bin_folder = llvm_toolchain_root(config).join("bin");
find_ndk_path(config.min_sdk_version, |platform| {
bin_folder.join(format!(
"{}{}-clang++{}",
build_target.ndk_llvm_triple(),
platform,
EXECUTABLE_SUFFIX_CMD
))
})
.map_err(|_| format_err!("Unable to find NDK clang++"))
}
// Returns path to ar.
pub fn find_ar(config: &AndroidConfig, build_target: AndroidBuildTarget) -> CargoResult<PathBuf> {
let ar_path = llvm_toolchain_root(config).join("bin").join(format!(
"{}-ar{}",
build_target.ndk_triple(),
EXECUTABLE_SUFFIX_EXE
));
if ar_path.exists() {
Ok(ar_path)
} else {
Err(format_err!(
"Unable to find ar at `{}`",
ar_path.to_string_lossy()
))
}
}
// Returns path to readelf
pub fn find_readelf(
config: &AndroidConfig,
build_target: AndroidBuildTarget,
) -> CargoResult<PathBuf> {
let readelf_path = llvm_toolchain_root(config).join("bin").join(format!(
"{}-readelf{}",
build_target.ndk_triple(),
EXECUTABLE_SUFFIX_EXE
));
if readelf_path.exists() {
Ok(readelf_path)
} else {
Err(format_err!(
"Unable to find readelf at `{}`",
readelf_path.to_string_lossy()
))
}
}
/// Returns a ProcessBuilder which runs the specified command. Uses "cmd" on windows in order to
/// allow execution of batch files.
pub fn script_process(cmd: impl AsRef<OsStr>) -> ProcessBuilder {
if cfg!(target_os = "windows") {
let mut pb = process("cmd");
pb.arg("/C").arg(cmd);
pb
} else {
process(cmd)
}
}
#[cfg(all(target_os = "windows", target_pointer_width = "64"))]
const HOST_TAG: &str = "windows-x86_64";
#[cfg(all(target_os = "windows", target_pointer_width = "32"))]
const HOST_TAG: &str = "windows";
#[cfg(target_os = "linux")]
const HOST_TAG: &str = "linux-x86_64";
#[cfg(target_os = "macos")]
const HOST_TAG: &str = "darwin-x86_64";
// These are executable suffixes used to simplify building commands.
// On non-windows platforms they are empty.
#[cfg(target_os = "windows")]
const EXECUTABLE_SUFFIX_EXE: &str = ".exe";
#[cfg(not(target_os = "windows"))]
const EXECUTABLE_SUFFIX_EXE: &str = "";
#[cfg(target_os = "windows")]
const EXECUTABLE_SUFFIX_CMD: &str = ".cmd";
#[cfg(not(target_os = "windows"))]
const EXECUTABLE_SUFFIX_CMD: &str = "";
#[cfg(target_os = "windows")]
pub const EXECUTABLE_SUFFIX_BAT: &str = ".bat";
#[cfg(not(target_os = "windows"))]
pub const EXECUTABLE_SUFFIX_BAT: &str = "";
================================================
FILE: cargo-apk/src/ops/build.rs
================================================
mod compile;
mod targets;
pub mod tempfile;
mod util;
use self::compile::SharedLibraries;
use crate::config::{AndroidConfig, AndroidTargetConfig};
use cargo::core::{Target, TargetKind, Workspace};
use cargo::util::process_builder::process;
use cargo::util::CargoResult;
use clap::ArgMatches;
use failure::format_err;
use std::collections::BTreeMap;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::{env, fs};
#[derive(Debug)]
pub struct BuildResult {
/// Mapping from target kind and target name to the built APK
pub target_to_apk_map: BTreeMap<(TargetKind, String), PathBuf>,
}
pub fn build(
workspace: &Workspace,
config: &AndroidConfig,
options: &ArgMatches,
) -> CargoResult<BuildResult> {
let root_build_dir = util::get_root_build_directory(workspace, config);
let shared_libraries =
compile::build_shared_libraries(workspace, config, options, &root_build_dir)?;
build_apks(config, &root_build_dir, shared_libraries)
}
fn build_apks(
config: &AndroidConfig,
root_build_dir: &PathBuf,
shared_libraries: SharedLibraries,
) -> CargoResult<BuildResult> {
// Create directory to hold final APKs which are signed using the debug key
let final_apk_dir = root_build_dir.join("apk");
fs::create_dir_all(&final_apk_dir)?;
// Paths of created APKs
let mut target_to_apk_map = BTreeMap::new();
// Build an APK for each cargo target
for (target, shared_libraries) in shared_libraries.shared_libraries.iter_all() {
let target_directory = util::get_target_directory(root_build_dir, target)?;
fs::create_dir_all(&target_directory)?;
// Determine Target Configuration
let target_config = config.resolve((target.kind().to_owned(), target.name().to_owned()))?;
//
// Run commands to produce APK
//
build_manifest(&target_directory, &config, &target_config, &target)?;
let build_tools_path = config
.sdk_path
.join("build-tools")
.join(&config.build_tools_version);
let aapt_path = build_tools_path.join("aapt");
let zipalign_path = build_tools_path.join("zipalign");
// Create unaligned APK which includes resources and assets
let unaligned_apk_name = format!("{}_unaligned.apk", target.name());
let unaligned_apk_path = target_directory.join(&unaligned_apk_name);
if unaligned_apk_path.exists() {
std::fs::remove_file(unaligned_apk_path)
.map_err(|e| format_err!("Unable to delete APK file. {}", e))?;
}
let mut aapt_package_cmd = process(&aapt_path);
aapt_package_cmd
.arg("package")
.arg("-F")
.arg(&unaligned_apk_name)
.arg("-M")
.arg("AndroidManifest.xml")
.arg("-I")
.arg(&config.android_jar_path);
if let Some(res_path) = target_config.res_path {
aapt_package_cmd.arg("-S").arg(res_path);
}
// Link assets
if let Some(assets_path) = &target_config.assets_path {
aapt_package_cmd.arg("-A").arg(assets_path);
}
aapt_package_cmd.cwd(&target_directory).exec()?;
// Add shared libraries to the APK
for shared_library in shared_libraries {
// Copy the shared library to the appropriate location in the target directory and with the appropriate name
// Note: that the type of slash used matters. This path is passed to aapt and the shared library
// will not load if backslashes are used.
let so_path = format!(
"lib/{}/{}",
&shared_library.abi.android_abi(),
shared_library.filename
);
let target_shared_object_path = target_directory.join(&so_path);
fs::create_dir_all(target_shared_object_path.parent().unwrap())?;
fs::copy(&shared_library.path, target_shared_object_path)?;
// Add to the APK
process(&aapt_path)
.arg("add")
.arg(&unaligned_apk_name)
.arg(so_path)
.cwd(&target_directory)
.exec()?;
}
// Determine the directory in which to place the aligned and signed APK
let target_apk_directory = match target.kind() {
TargetKind::Bin => final_apk_dir.clone(),
TargetKind::ExampleBin => final_apk_dir.join("examples"),
_ => unreachable!("Unexpected target kind"),
};
fs::create_dir_all(&target_apk_directory)?;
// Align apk
let final_apk_path = target_apk_directory.join(format!("{}.apk", target.name()));
process(&zipalign_path)
.arg("-f")
.arg("-v")
.arg("4")
.arg(&unaligned_apk_name)
.arg(&final_apk_path)
.cwd(&target_directory)
.exec()?;
// Find or generate a debug keystore for signing the APK
// We use the same debug keystore as used by the Android SDK. If it does not exist,
// then we create it using keytool which is part of the JRE/JDK
let android_directory = dirs::home_dir()
.ok_or_else(|| format_err!("Unable to determine home directory"))?
.join(".android");
fs::create_dir_all(&android_directory)?;
let keystore_path = android_directory.join("debug.keystore");
if !keystore_path.exists() {
// Generate key
let keytool_filename = if cfg!(target_os = "windows") {
"keytool.exe"
} else {
"keytool"
};
let keytool_path = find_java_executable(keytool_filename)?;
process(keytool_path)
.arg("-genkey")
.arg("-v")
.arg("-keystore")
.arg(&keystore_path)
.arg("-storepass")
.arg("android")
.arg("-alias")
.arg("androidebugkey")
.arg("-keypass")
.arg("android")
.arg("-dname")
.arg("CN=Android Debug,O=Android,C=US")
.arg("-keyalg")
.arg("RSA")
.arg("-keysize")
.arg("2048")
.arg("-validity")
.arg("10000")
.cwd(root_build_dir)
.exec()?;
}
// Sign the APK with the development certificate
util::script_process(
build_tools_path.join(format!("apksigner{}", util::EXECUTABLE_SUFFIX_BAT)),
)
.arg("sign")
.arg("--ks")
.arg(keystore_path)
.arg("--ks-pass")
.arg("pass:android")
.arg(&final_apk_path)
.cwd(&target_directory)
.exec()?;
target_to_apk_map.insert(
(target.kind().to_owned(), target.name().to_owned()),
final_apk_path,
);
}
Ok(BuildResult { target_to_apk_map })
}
/// Find an executable that is part of the Java SDK
fn find_java_executable(name: &str) -> CargoResult<PathBuf> {
// Look in PATH
env::var_os("PATH")
.and_then(|paths| {
env::split_paths(&paths)
.filter_map(|path| {
let filepath = path.join(name);
if fs::metadata(&filepath).is_ok() {
Some(filepath)
} else {
None
}
})
.next()
})
.or_else(||
// Look in JAVA_HOME
env::var_os("JAVA_HOME").and_then(|java_home| {
let filepath = PathBuf::from(java_home).join("bin").join(name);
if filepath.exists() {
Some(filepath)
} else {
None
}
}))
.ok_or_else(|| {
format_err!(
"Unable to find executable: '{}'. Configure PATH or JAVA_HOME with the path to the JRE or JDK.",
name
)
})
}
fn build_manifest(
path: &Path,
config: &AndroidConfig,
target_config: &AndroidTargetConfig,
target: &Target,
) -> CargoResult<()> {
let file = path.join("AndroidManifest.xml");
let mut file = File::create(&file)?;
// Building application attributes
let application_attrs = format!(
r#"
android:hasCode="false" android:label="{0}"{1}{2}{3}"#,
target_config.package_label,
target_config
.package_icon
.as_ref()
.map_or(String::new(), |a| format!(
r#"
android:icon="{}""#,
a
)),
if target_config.fullscreen {
r#"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen""#
} else {
""
},
target_config
.application_attributes
.as_ref()
.map_or(String::new(), |a| a.replace("\n", "\n "))
);
// Build activity attributes
let activity_attrs = format!(
r#"
android:name="android.app.NativeActivity"
android:label="{0}"
android:configChanges="orientation|keyboardHidden|screenSize" {1}"#,
target_config.package_label,
target_config
.activity_attributes
.as_ref()
.map_or(String::new(), |a| a.replace("\n", "\n "))
);
let uses_features = target_config
.features
.iter()
.map(|f| {
format!(
"\n\t<uses-feature android:name=\"{}\" android:required=\"{}\" {}/>",
f.name,
f.required,
f.version
.as_ref()
.map_or(String::new(), |v| format!(r#"android:version="{}""#, v))
)
})
.collect::<Vec<String>>()
.join(", ");
let uses_permissions = target_config
.permissions
.iter()
.map(|f| {
format!(
"\n\t<uses-permission android:name=\"{}\" {max_sdk_version}/>",
f.name,
max_sdk_version = f.max_sdk_version.map_or(String::new(), |v| format!(
r#"android:maxSdkVersion="{}""#,
v
))
)
})
.collect::<Vec<String>>()
.join(", ");
// Write final AndroidManifest
writeln!(
file,
r#"<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="{package}"
android:versionCode="{version_code}"
android:versionName="{version_name}">
<uses-sdk android:targetSdkVersion="{targetSdkVersion}" android:minSdkVersion="{minSdkVersion}" />
<uses-feature android:glEsVersion="{glEsVersion}" android:required="true"></uses-feature>{uses_features}{uses_permissions}
<application {application_attrs} >
<activity {activity_attrs} >
<meta-data android:name="android.app.lib_name" android:value="{target_name}" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>"#,
package = target_config.package_name.replace("-", "_"),
version_code = target_config.version_code,
version_name = target_config.version_name,
targetSdkVersion = config.target_sdk_version,
minSdkVersion = config.min_sdk_version,
glEsVersion = format!(
"0x{:04}{:04}",
target_config.opengles_version_major, target_config.opengles_version_minor
),
uses_features = uses_features,
uses_permissions = uses_permissions,
application_attrs = application_attrs,
activity_attrs = activity_attrs,
target_name = target.name(),
)?;
Ok(())
}
================================================
FILE: cargo-apk/src/ops/install.rs
================================================
use super::BuildResult;
use crate::config::AndroidConfig;
use crate::ops::build;
use cargo::core::Workspace;
use cargo::util::process_builder::process;
use cargo::util::CargoResult;
use clap::ArgMatches;
pub fn install(
workspace: &Workspace,
config: &AndroidConfig,
options: &ArgMatches,
) -> CargoResult<BuildResult> {
let build_result = build::build(workspace, config, options)?;
let adb = config.sdk_path.join("platform-tools/adb");
for apk_path in build_result.target_to_apk_map.values() {
drop(writeln!(
workspace.config().shell().err(),
"Installing apk '{}' to the device",
apk_path.file_name().unwrap().to_string_lossy()
));
process(&adb)
.arg("install")
.arg("-r")
.arg(apk_path)
.exec()?;
}
Ok(build_result)
}
================================================
FILE: cargo-apk/src/ops/mod.rs
================================================
mod build;
mod install;
mod run;
pub use self::build::build;
pub use self::build::BuildResult;
pub use self::install::install;
pub use self::run::run;
================================================
FILE: cargo-apk/src/ops/run.rs
================================================
use crate::config::AndroidConfig;
use crate::ops::install;
use cargo::core::{TargetKind, Workspace};
use cargo::util::process_builder::process;
use cargo::util::CargoResult;
use clap::ArgMatches;
use failure::format_err;
pub fn run(workspace: &Workspace, config: &AndroidConfig, options: &ArgMatches) -> CargoResult<()> {
let build_result = install::install(workspace, config, options)?;
// Determine the target that should be executed
let requested_target = if options.is_present("example") && options.is_present("bin") {
return Err(format_err!(
"Specifying both example and bin targets is not supported"
));
} else if let Some(bin) = options.value_of("bin") {
(TargetKind::Bin, bin.to_owned())
} else if let Some(example) = options.value_of("example") {
(TargetKind::ExampleBin, example.to_owned())
} else {
match build_result.target_to_apk_map.len() {
1 => build_result
.target_to_apk_map
.keys()
.next()
.unwrap()
.to_owned(),
0 => return Err(format_err!("No APKs to execute.")),
_ => {
return Err(format_err!(
"Multiple APKs built. Specify which APK to execute using '--bin' or '--example'."
))
}
}
};
// Determine package name
let package_name = config.resolve(requested_target)?.package_name;
//
// Start the APK using adb
//
let adb = config.sdk_path.join("platform-tools/adb");
// Found it by doing this :
// adb shell "cmd package resolve-activity --brief com.author.myproject | tail -n 1"
let activity_path = format!(
"{}/android.app.NativeActivity",
package_name.replace("-", "_"),
);
drop(writeln!(workspace.config().shell().err(), "Running apk"));
process(&adb)
.arg("shell")
.arg("am")
.arg("start")
.arg("-a")
.arg("android.intent.action.MAIN")
.arg("-n")
.arg(&activity_path)
.exec()?;
Ok(())
}
================================================
FILE: cargo-apk/tests/cc/Cargo.toml
================================================
[package]
name = "test_cc-rs"
version = "0.1.0"
authors = ["Philip Alldredge <philip@philipalldredge.com>"]
description = "Simple test to ensure cargo-apk works with crates that use cc crate to build C and C++ static libraries."
edition = "2018"
publish = false
[package.metadata.android]
build_targets = [ "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android", "x86_64-linux-android" ]
[build-dependencies]
cc = "1.0"
================================================
FILE: cargo-apk/tests/cc/build.rs
================================================
fn main() {
cc::Build::new()
.file("./cc_src/ctest.c")
.compile("ctest");
cc::Build::new()
.cpp(true)
.file("./cc_src/cpptest.cpp")
.compile("cpptest");
}
================================================
FILE: cargo-apk/tests/cc/cc_src/cpptest.cpp
================================================
#include <cstdint>
#include <iostream>
extern "C" int32_t multiply_by_four(int32_t value) {
return value * 4;
}
// Print using std::cout to verify C++ standard library is working properly.
extern "C" void print_value(int32_t value) {
std::cout << "Value printed from cout: " << value << std::endl;
}
================================================
FILE: cargo-apk/tests/cc/cc_src/ctest.c
================================================
#include <stdint.h>
int32_t add_two(int32_t value) {
return value + 2;
}
================================================
FILE: cargo-apk/tests/cc/src/main.rs
================================================
fn main() {
println!("Android cc test");
let result = unsafe {
multiply_by_four(add_two(4))
};
println!("multiply_by_four(add_two(4)): {}", result);
println!("Printing value using c++ library:");
unsafe {
print_value(result);
}
}
#[link(name = "ctest")]
extern "C" {
fn add_two(value : i32) -> i32;
}
#[link(name = "cpptest")]
extern "C" {
fn multiply_by_four(value : i32) -> i32;
fn print_value(value : i32) -> std::ffi::c_void;
}
================================================
FILE: cargo-apk/tests/cmake/Cargo.toml
================================================
[package]
name = "test_cmake-rs"
version = "0.1.0"
authors = ["Philip Alldredge <philip@philipalldredge.com>"]
description = "Simple test to ensure cargo-apk works with crates that use cmake crate"
edition = "2018"
publish = false
[package.metadata.android]
build_targets = [ "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android", "x86_64-linux-android" ]
[build-dependencies]
cmake = "0.1"
================================================
FILE: cargo-apk/tests/cmake/build.rs
================================================
use cmake::Config;
fn main() {
let dst = Config::new("libcmaketest")
.build();
println!("cargo:rustc-link-search=native={}", dst.display());
println!("cargo:rustc-link-lib=static=cmaketest");
}
================================================
FILE: cargo-apk/tests/cmake/libcmaketest/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 2.8.9)
project(cmaketest)
set(CMAKE_BUILD_TYPE Release)
ADD_LIBRARY(cmaketest STATIC cmaketest.c )
install(TARGETS cmaketest DESTINATION .)
================================================
FILE: cargo-apk/tests/cmake/libcmaketest/cmaketest.c
================================================
int multiply_by_10(int value) {
return value * 10;
}
================================================
FILE: cargo-apk/tests/cmake/src/main.rs
================================================
fn main() {
println!("Android cmake test");
let result = unsafe {
multiply_by_10(2)
};
println!("multiply_by_10(2): {}", result);
}
#[link(name = "cmaketest")]
extern "C" {
fn multiply_by_10(value : i32) -> i32;
}
================================================
FILE: cargo-apk/tests/inner_attributes/Cargo.toml
================================================
[package]
name = "test_inner_attributes"
version = "0.1.0"
authors = ["Philip Alldredge <philip@philipalldredge.com>"]
edition = "2018"
publish = false
================================================
FILE: cargo-apk/tests/inner_attributes/src/main.rs
================================================
#![cfg(target_os = "android")]
fn main() {
println!("Inner attributes test");
}
================================================
FILE: cargo-apk/tests/native-library/Cargo.toml
================================================
[package]
name = "test_native-library"
version = "0.1.0"
authors = ["Philip Alldredge <philip@philipalldredge.com>"]
edition = "2018"
publish = false
================================================
FILE: cargo-apk/tests/native-library/src/main.rs
================================================
#![cfg(target_os = "android")]
use std::ffi::c_void;
use std::ptr;
fn main() {
println!("Android native library test");
let display = unsafe { eglGetDisplay(ptr::null()) };
println!("eglGetDisplay(0) result: {:?}", display);
}
// Link to the EGL to ensure that additional libraries can be linked
#[link(name = "EGL")]
extern "C" {
fn eglGetDisplay(native_display : *const c_void) -> *mut c_void;
}
================================================
FILE: cargo-apk/tests/run_tests.sh
================================================
#!/bin/bash
set -e
fail() {
echo "$@"
exit 1
}
[[ $(basename $(pwd)) = cargo-apk ]] || fail "Must be run in cargo-apk directory"
do_test() {
do_package "tests/$1" || fail "Compiling test $1 failed"
check_symbols "tests/$1" || fail "onCreate not found in test $1"
}
do_example() {
do_package "../examples/$1" || fail "Compiling example $1 failed"
check_symbols "../examples/$1" || fail "onCreate not found in example $1"
}
do_package() {
pushd "$1" >/dev/null
cargo apk build --all-targets || return 1
cargo apk build --all-targets --release || return 1
popd >/dev/null
}
check_symbols() {
(find "$1/target/android-artifacts/release/bin" -name *.so -not -name libc++_shared.so && \
find "$1/target/android-artifacts/debug/bin" -name *.so -not -name libc++_shared.so) | \
while read f ; do
nm -Dg --defined-only "$f" | cut -f3 -d' ' | grep -qxF ANativeActivity_onCreate || return 1
done
}
do_example advanced
do_example basic
do_example multiple_targets
do_example use_assets
do_example use_icon
do_test inner_attributes
do_test native-library
do_test cc
do_test cmake
================================================
FILE: examples/advanced/Cargo.toml
================================================
[package]
name = "advanced"
version = "0.1.0"
authors = ["Philip Alldredge <philip@philipalldredge.com"]
publish = false
edition = "2018"
[package.metadata.android]
# The target Android API level.
# "android_version" is the compile SDK version. It defaults to 29.
# (target_sdk_version defaults to the value of "android_version")
# (min_sdk_version defaults to 18) It defaults to 18 because this is the minimum supported by rustc.
android_version = 29
target_sdk_version = 29
min_sdk_version = 26
# Specifies the array of targets to build for.
# Defaults to "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android".
build_targets = [ "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android", "x86_64-linux-android" ]
#
# The following value can be customized on a per bin/example basis. See multiple_targets example
# If a value is not specified for a secondary target, it will inherit the value defined in the `package.metadata.android`
# section unless otherwise noted.
#
# The Java package name for your application.
# Hyphens are converted to underscores.
package_name = "rust.cargo.apk.advanced"
# The user-friendly name for your app, as displayed in the applications menu.
label = "Advanced android-rs-glue example"
# Internal version number used to determine whether one version is more recent than another. Must be an integer.
# Defaults to 1
# See https://developer.android.com/guide/topics/manifest/manifest-element
version_code = 2
# The version number shown to users.
# Defaults to the cargo package version number
# See https://developer.android.com/guide/topics/manifest/manifest-element
version_name = "2.0"
# Path to your application's res/ folder.
res = "res"
# Virtual path your application's icon for any mipmap level.
icon = "@mipmap/ic_launcher"
# Path to the folder containing your application's assets.
assets = "assets"
# If set to true, makes the app run in full-screen, by adding the following line
# as an XML attribute to the manifest's <application> tag :
# android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen
# Defaults to false.
fullscreen = false
# The maximum supported OpenGL ES version , as claimed by the manifest. Defaults to 2.0.
# See https://developer.android.com/guide/topics/graphics/opengl.html#manifest
opengles_version_major = 3
opengles_version_minor = 2
# Adds extra arbitrary XML attributes to the <application> tag in the manifest.
# See https://developer.android.com/guide/topics/manifest/application-element.html
[package.metadata.android.application_attributes]
"android:debuggable" = "true"
"android:hardwareAccelerated" = "true"
# Adds extra arbitrary XML attributes to the <activity> tag in the manifest.
# See https://developer.android.com/guide/topics/manifest/activity-element.html
[package.metadata.android.activity_attributes]
"android:screenOrientation" = "unspecified"
"android:uiOptions" = "none"
# Adds a uses-feature element to the manifest
# Supported keys: name, required, version
# The glEsVersion attribute is not supported using this section.
# It can be specified using the opengles_version_major and opengles_version_minor values
# See https://developer.android.com/guide/topics/manifest/uses-feature-element
[[package.metadata.android.feature]]
name = "android.hardware.camera"
[[package.metadata.android.feature]]
name = "android.hardware.vulkan.level"
version = "1"
required = false
# Adds a uses-permission element to the manifest.
# Note that android_version 23 and higher, Android requires the application to request permissions at runtime.
# There is currently no way to do this using a pure NDK based application.
# See https://developer.android.com/guide/topics/manifest/uses-permission-element
[[package.metadata.android.permission]]
name = "android.permission.WRITE_EXTERNAL_STORAGE"
max_sdk_version = 18
[[package.metadata.android.permission]]
name = "android.permission.CAMERA"
================================================
FILE: examples/advanced/assets/test_asset
================================================
str1
str2
str3
================================================
FILE: examples/advanced/src/main.rs
================================================
fn main() {
println!("main() has been called from advanced example");
}
================================================
FILE: examples/basic/Cargo.toml
================================================
[package]
name = "android_glue_example"
version = "0.1.0"
authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>"]
edition = "2018"
[dependencies]
android_glue = { path = "../../glue" }
================================================
FILE: examples/basic/src/main.rs
================================================
fn main() {
println!("main() has been called");
}
================================================
FILE: examples/multiple_targets/Cargo.toml
================================================
[package]
name = "android_primary_bin"
version = "0.1.0"
authors = ["Philip Alldredge <philip@philipalldredge.com>"]
publish = false
edition = "2018"
[dependencies.android_glue]
path = "../../glue"
[package.metadata.android]
label = "Primary Binary"
[[package.metadata.android.bin]]
name = "secondary-bin"
label = "Secondary Binary"
[[package.metadata.android.example]]
name = "example1"
label = "Example 1"
================================================
FILE: examples/multiple_targets/examples/example1.rs
================================================
fn main() {
println!("main() has been called on example1");
}
================================================
FILE: examples/multiple_targets/src/bin/secondary-bin.rs
================================================
fn main() {
println!("main() has been called on the secondary binary");
}
================================================
FILE: examples/multiple_targets/src/main.rs
================================================
fn main() {
println!("main() has been called on the primary binary");
}
================================================
FILE: examples/use_assets/Cargo.toml
================================================
[package]
name = "android_glue_assets_example"
version = "0.1.0"
authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>"]
edition = "2018"
[package.metadata.android]
label = "Using assets android-rs-glue example"
assets = "assets"
[dependencies]
android-ndk = { git = "https://github.com/rust-windowing/android-ndk-rs" }
[dependencies.android_glue]
path = "../../glue"
================================================
FILE: examples/use_assets/assets/test_asset
================================================
str1
str2
str3
================================================
FILE: examples/use_assets/src/main.rs
================================================
use android_ndk::android_app::AndroidApp;
use android_ndk::asset::Asset;
use std::ffi::CString;
use std::io::{BufRead, BufReader};
fn main() {
let android_app = unsafe { AndroidApp::from_ptr(android_glue::get_android_app()) };
let f = open_asset(&android_app, "test_asset");
for line in BufReader::new(f).lines() {
println!("{:?}", line);
}
}
fn open_asset(android_app: &AndroidApp, name: &str) -> Asset {
let asset_manager = android_app.activity().asset_manager();
asset_manager
.open(&CString::new(name).unwrap())
.expect("Could not open asset")
}
================================================
FILE: examples/use_icon/Cargo.toml
================================================
[package]
name = "android_glue_icon_example"
version = "0.1.0"
authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>"]
edition = "2018"
[package.metadata.android]
label = "Using icon android-rs-glue example"
res = "res"
icon = "@mipmap/ic_launcher"
[dependencies.android_glue]
path = "../../glue"
================================================
FILE: examples/use_icon/src/main.rs
================================================
fn main() {
println!("main() has been called, did you like the icon?");
}
================================================
FILE: glue/.gitignore
================================================
/target
/Cargo.lock
================================================
FILE: glue/Cargo.toml
================================================
[package]
name = "android_glue"
version = "0.2.3"
authors = ["Pierre Krieger <pierre.krieger1708@gmail.com>"]
license = "MIT"
description = "Glue for building Android NDK apps with cargo-apk"
repository = "https://github.com/rust-windowing/android-rs-glue"
edition = "2018"
[dependencies]
android-ndk-sys = { git = "https://github.com/rust-windowing/android-ndk-rs" }
================================================
FILE: glue/src/lib.rs
================================================
//! Glue for working with cargo-apk
//!
//! Previously, this library provided an abstraction over the event loop. However, this has been
//! removed in favor of giving users more flexibility. Use android-ndk or Winit for a higher-level
//! abstraction.
use android_ndk_sys::native_app_glue::android_app;
use std::ptr::NonNull;
extern "C" {
static ANDROID_APP: *mut android_app;
}
/// Get the `struct android_app` instance from the `android_native_app_glue` code.
pub fn get_android_app() -> NonNull<android_app> {
NonNull::new(unsafe { ANDROID_APP }).unwrap()
}
gitextract_s03qm1pi/
├── .circleci/
│ └── config.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── cargo-apk/
│ ├── .gitignore
│ ├── Cargo.toml
│ ├── native_app_glue/
│ │ ├── NOTICE
│ │ ├── android_native_app_glue.c
│ │ └── android_native_app_glue.h
│ ├── src/
│ │ ├── config.rs
│ │ ├── main.rs
│ │ └── ops/
│ │ ├── build/
│ │ │ ├── compile.rs
│ │ │ ├── targets.rs
│ │ │ ├── tempfile.rs
│ │ │ └── util.rs
│ │ ├── build.rs
│ │ ├── install.rs
│ │ ├── mod.rs
│ │ └── run.rs
│ └── tests/
│ ├── cc/
│ │ ├── Cargo.toml
│ │ ├── build.rs
│ │ ├── cc_src/
│ │ │ ├── cpptest.cpp
│ │ │ └── ctest.c
│ │ └── src/
│ │ └── main.rs
│ ├── cmake/
│ │ ├── Cargo.toml
│ │ ├── build.rs
│ │ ├── libcmaketest/
│ │ │ ├── CMakeLists.txt
│ │ │ └── cmaketest.c
│ │ └── src/
│ │ └── main.rs
│ ├── inner_attributes/
│ │ ├── Cargo.toml
│ │ └── src/
│ │ └── main.rs
│ ├── native-library/
│ │ ├── Cargo.toml
│ │ └── src/
│ │ └── main.rs
│ └── run_tests.sh
├── examples/
│ ├── advanced/
│ │ ├── Cargo.toml
│ │ ├── assets/
│ │ │ └── test_asset
│ │ └── src/
│ │ └── main.rs
│ ├── basic/
│ │ ├── Cargo.toml
│ │ └── src/
│ │ └── main.rs
│ ├── multiple_targets/
│ │ ├── Cargo.toml
│ │ ├── examples/
│ │ │ └── example1.rs
│ │ └── src/
│ │ ├── bin/
│ │ │ └── secondary-bin.rs
│ │ └── main.rs
│ ├── use_assets/
│ │ ├── Cargo.toml
│ │ ├── assets/
│ │ │ └── test_asset
│ │ └── src/
│ │ └── main.rs
│ └── use_icon/
│ ├── Cargo.toml
│ └── src/
│ └── main.rs
└── glue/
├── .gitignore
├── Cargo.toml
└── src/
└── lib.rs
SYMBOL INDEX (143 symbols across 28 files)
FILE: cargo-apk/native_app_glue/android_native_app_glue.c
function free_saved_state (line 39) | static void free_saved_state(struct android_app* android_app) {
function android_app_read_cmd (line 49) | int8_t android_app_read_cmd(struct android_app* android_app) {
function print_cur_config (line 64) | static void print_cur_config(struct android_app* android_app) {
function android_app_pre_exec_cmd (line 89) | void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cm...
function android_app_post_exec_cmd (line 146) | void android_app_post_exec_cmd(struct android_app* android_app, int8_t c...
function app_dummy (line 170) | void app_dummy() {
function android_app_destroy (line 174) | static void android_app_destroy(struct android_app* android_app) {
function process_input (line 188) | static void process_input(struct android_app* app, struct android_poll_s...
function process_cmd (line 201) | static void process_cmd(struct android_app* app, struct android_poll_sou...
type android_app (line 209) | struct android_app
type android_app (line 209) | struct android_app
type android_app (line 276) | struct android_app
type android_app (line 278) | struct android_app
type android_app (line 278) | struct android_app
type android_app (line 278) | struct android_app
type android_app (line 279) | struct android_app
function android_app_write_cmd (line 323) | static void android_app_write_cmd(struct android_app* android_app, int8_...
function android_app_set_input (line 329) | static void android_app_set_input(struct android_app* android_app, AInpu...
function android_app_set_window (line 339) | static void android_app_set_window(struct android_app* android_app, ANat...
function android_app_set_activity_state (line 354) | static void android_app_set_activity_state(struct android_app* android_a...
function android_app_free (line 363) | static void android_app_free(struct android_app* android_app) {
function onDestroy (line 376) | static void onDestroy(ANativeActivity* activity) {
function onStart (line 381) | static void onStart(ANativeActivity* activity) {
function onResume (line 386) | static void onResume(ANativeActivity* activity) {
type android_app (line 392) | struct android_app
type android_app (line 392) | struct android_app
function onPause (line 415) | static void onPause(ANativeActivity* activity) {
function onStop (line 420) | static void onStop(ANativeActivity* activity) {
function onConfigurationChanged (line 425) | static void onConfigurationChanged(ANativeActivity* activity) {
function onLowMemory (line 431) | static void onLowMemory(ANativeActivity* activity) {
function onWindowFocusChanged (line 437) | static void onWindowFocusChanged(ANativeActivity* activity, int focused) {
function onNativeWindowCreated (line 443) | static void onNativeWindowCreated(ANativeActivity* activity, ANativeWind...
function onNativeWindowDestroyed (line 448) | static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWi...
function onInputQueueCreated (line 453) | static void onInputQueueCreated(ANativeActivity* activity, AInputQueue* ...
function onInputQueueDestroyed (line 458) | static void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue...
function native_app_glue_onCreate (line 465) | void native_app_glue_onCreate(ANativeActivity* activity, void* savedState,
FILE: cargo-apk/native_app_glue/android_native_app_glue.h
type android_app (line 84) | struct android_app
type android_poll_source (line 90) | struct android_poll_source {
type android_app (line 111) | struct android_app {
type android_app (line 318) | struct android_app
type android_app (line 325) | struct android_app
type android_app (line 332) | struct android_app
type android_app (line 348) | struct android_app
type android_app (line 350) | struct android_app
FILE: cargo-apk/src/config.rs
type AndroidConfig (line 19) | pub struct AndroidConfig {
method resolve (line 59) | pub fn resolve(&self, target: (TargetKind, String)) -> CargoResult<And...
type AndroidBuildTarget (line 151) | pub enum AndroidBuildTarget {
type AndroidFeature (line 163) | pub struct AndroidFeature {
method from (line 170) | fn from(f: TomlFeature) -> Self {
type AndroidPermission (line 180) | pub struct AndroidPermission {
method from (line 186) | fn from(p: TomlPermission) -> Self {
type AndroidTargetConfig (line 195) | pub struct AndroidTargetConfig {
function load (line 247) | pub fn load(
function build_attribute_string (line 424) | fn build_attribute_string(input_map: BTreeMap<String, String>) -> String {
type TomlConfig (line 432) | struct TomlConfig {
type TomlPackage (line 437) | struct TomlPackage {
type TomlMetadata (line 443) | struct TomlMetadata {
type TomlAndroid (line 449) | struct TomlAndroid {
type TomlFeature (line 464) | struct TomlFeature {
type TomlPermission (line 472) | struct TomlPermission {
type TomlAndroidSpecificTarget (line 480) | struct TomlAndroidSpecificTarget {
type TomlAndroidTarget (line 488) | struct TomlAndroidTarget {
FILE: cargo-apk/src/main.rs
function main (line 14) | fn main() {
function cli (line 77) | fn cli() -> App<'static, 'static> {
function cli_apk (line 121) | fn cli_apk() -> App<'static, 'static> {
function cli_build (line 132) | fn cli_build() -> App<'static, 'static> {
function cli_install (line 180) | fn cli_install() -> App<'static, 'static> {
function cli_run (line 255) | fn cli_run() -> App<'static, 'static> {
function cli_logcat (line 292) | fn cli_logcat() -> App<'static, 'static> {
function execute_build (line 304) | pub fn execute_build(options: &ArgMatches, cargo_config: &CargoConfig) -...
function execute_install (line 319) | pub fn execute_install(options: &ArgMatches, cargo_config: &CargoConfig)...
function execute_run (line 334) | pub fn execute_run(options: &ArgMatches, cargo_config: &CargoConfig) -> ...
function execute_logcat (line 349) | pub fn execute_logcat(options: &ArgMatches, cargo_config: &CargoConfig) ...
FILE: cargo-apk/src/ops/build.rs
type BuildResult (line 21) | pub struct BuildResult {
function build (line 26) | pub fn build(
function build_apks (line 37) | fn build_apks(
function find_java_executable (line 204) | fn find_java_executable(name: &str) -> CargoResult<PathBuf> {
function build_manifest (line 237) | fn build_manifest(
FILE: cargo-apk/src/ops/build/compile.rs
type SharedLibrary (line 23) | pub struct SharedLibrary {
type SharedLibraries (line 29) | pub struct SharedLibraries {
function build_shared_libraries (line 34) | pub fn build_shared_libraries(
type SharedLibraryExecutor (line 103) | struct SharedLibraryExecutor {
method exec (line 114) | fn exec(
function list_needed_dylibs (line 422) | fn list_needed_dylibs(readelf_path: &Path, library_path: &Path) -> Cargo...
function list_android_dylibs (line 442) | fn list_android_dylibs(version_specific_libraries_path: &Path) -> CargoR...
function libs_search_paths_from_args (line 461) | fn libs_search_paths_from_args(args: &[std::ffi::OsString]) -> Vec<PathB...
function find_library_path (line 481) | fn find_library_path<S: AsRef<Path>>(paths: &Vec<PathBuf>, library: S) -...
function write_native_app_glue_src (line 493) | fn write_native_app_glue_src(android_artifacts_dir: &Path) -> CargoResul...
function build_android_native_glue (line 508) | fn build_android_native_glue(
function write_cmake_toolchain (line 535) | fn write_cmake_toolchain(
FILE: cargo-apk/src/ops/build/targets.rs
method android_abi (line 5) | pub fn android_abi(self) -> &'static str {
method rust_triple (line 15) | pub fn rust_triple(self) -> &'static str {
method ndk_llvm_triple (line 25) | pub fn ndk_llvm_triple(self) -> &'static str {
method ndk_triple (line 35) | pub fn ndk_triple(self) -> &'static str {
FILE: cargo-apk/src/ops/build/tempfile.rs
type TempFile (line 7) | pub struct TempFile {
method new (line 15) | pub fn new<F>(path: PathBuf, write_contents: F) -> CargoResult<TempFile>
method drop (line 30) | fn drop(&mut self) {
FILE: cargo-apk/src/ops/build/util.rs
function get_root_build_directory (line 10) | pub fn get_root_build_directory(workspace: &Workspace, config: &AndroidC...
function get_target_directory (line 24) | pub fn get_target_directory(root_build_dir: &PathBuf, target: &Target) -...
function make_path (line 36) | pub fn make_path(config: &AndroidConfig) -> PathBuf {
function llvm_toolchain_root (line 41) | pub fn llvm_toolchain_root(config: &AndroidConfig) -> PathBuf {
function find_ndk_path (line 58) | pub fn find_ndk_path<F>(platform: u32, path_builder: F) -> CargoResult<P...
function find_clang (line 90) | pub fn find_clang(
function find_clang_cpp (line 107) | pub fn find_clang_cpp(
function find_ar (line 124) | pub fn find_ar(config: &AndroidConfig, build_target: AndroidBuildTarget)...
function find_readelf (line 141) | pub fn find_readelf(
function script_process (line 162) | pub fn script_process(cmd: impl AsRef<OsStr>) -> ProcessBuilder {
constant HOST_TAG (line 173) | const HOST_TAG: &str = "windows-x86_64";
constant HOST_TAG (line 176) | const HOST_TAG: &str = "windows";
constant HOST_TAG (line 179) | const HOST_TAG: &str = "linux-x86_64";
constant HOST_TAG (line 182) | const HOST_TAG: &str = "darwin-x86_64";
constant EXECUTABLE_SUFFIX_EXE (line 188) | const EXECUTABLE_SUFFIX_EXE: &str = ".exe";
constant EXECUTABLE_SUFFIX_EXE (line 191) | const EXECUTABLE_SUFFIX_EXE: &str = "";
constant EXECUTABLE_SUFFIX_CMD (line 194) | const EXECUTABLE_SUFFIX_CMD: &str = ".cmd";
constant EXECUTABLE_SUFFIX_CMD (line 197) | const EXECUTABLE_SUFFIX_CMD: &str = "";
constant EXECUTABLE_SUFFIX_BAT (line 200) | pub const EXECUTABLE_SUFFIX_BAT: &str = ".bat";
constant EXECUTABLE_SUFFIX_BAT (line 203) | pub const EXECUTABLE_SUFFIX_BAT: &str = "";
FILE: cargo-apk/src/ops/install.rs
function install (line 9) | pub fn install(
FILE: cargo-apk/src/ops/run.rs
function run (line 9) | pub fn run(workspace: &Workspace, config: &AndroidConfig, options: &ArgM...
FILE: cargo-apk/tests/cc/build.rs
function main (line 1) | fn main() {
FILE: cargo-apk/tests/cc/cc_src/cpptest.cpp
function multiply_by_four (line 4) | int32_t multiply_by_four(int32_t value) {
function print_value (line 9) | void print_value(int32_t value) {
FILE: cargo-apk/tests/cc/cc_src/ctest.c
function add_two (line 3) | int32_t add_two(int32_t value) {
FILE: cargo-apk/tests/cc/src/main.rs
function main (line 1) | fn main() {
function add_two (line 17) | fn add_two(value : i32) -> i32;
function multiply_by_four (line 22) | fn multiply_by_four(value : i32) -> i32;
function print_value (line 23) | fn print_value(value : i32) -> std::ffi::c_void;
FILE: cargo-apk/tests/cmake/build.rs
function main (line 3) | fn main() {
FILE: cargo-apk/tests/cmake/libcmaketest/cmaketest.c
function multiply_by_10 (line 1) | int multiply_by_10(int value) {
FILE: cargo-apk/tests/cmake/src/main.rs
function main (line 1) | fn main() {
function multiply_by_10 (line 13) | fn multiply_by_10(value : i32) -> i32;
FILE: cargo-apk/tests/inner_attributes/src/main.rs
function main (line 3) | fn main() {
FILE: cargo-apk/tests/native-library/src/main.rs
function main (line 5) | fn main() {
function eglGetDisplay (line 14) | fn eglGetDisplay(native_display : *const c_void) -> *mut c_void;
FILE: examples/advanced/src/main.rs
function main (line 1) | fn main() {
FILE: examples/basic/src/main.rs
function main (line 1) | fn main() {
FILE: examples/multiple_targets/examples/example1.rs
function main (line 1) | fn main() {
FILE: examples/multiple_targets/src/bin/secondary-bin.rs
function main (line 1) | fn main() {
FILE: examples/multiple_targets/src/main.rs
function main (line 1) | fn main() {
FILE: examples/use_assets/src/main.rs
function main (line 6) | fn main() {
function open_asset (line 15) | fn open_asset(android_app: &AndroidApp, name: &str) -> Asset {
FILE: examples/use_icon/src/main.rs
function main (line 1) | fn main() {
FILE: glue/src/lib.rs
function get_android_app (line 15) | pub fn get_android_app() -> NonNull<android_app> {
Condensed preview — 52 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (154K chars).
[
{
"path": ".circleci/config.yml",
"chars": 1616,
"preview": "version: 2\njobs:\n build-and-test:\n environment:\n IMAGE_NAME: tomaka/cargo-apk\n docker:\n - image: docker"
},
{
"path": ".gitignore",
"chars": 31,
"preview": "target/\n.idea\n*.iml\nCMakeFiles\n"
},
{
"path": "Dockerfile",
"chars": 1555,
"preview": "FROM rust:stretch\n\nRUN apt-get update\nRUN apt-get install -yq openjdk-8-jre unzip wget cmake\n\nRUN rustup target add armv"
},
{
"path": "LICENSE",
"chars": 11324,
"preview": "Apache License\n Version 2.0, January 2004\n http://www.apache.org/licens"
},
{
"path": "README.md",
"chars": 10624,
"preview": "deprecated in favor of https://github.com/rust-windowing/android-ndk-rs which works with winit master\n\n# Android Glue\n\n["
},
{
"path": "cargo-apk/.gitignore",
"chars": 8,
"preview": "/target\n"
},
{
"path": "cargo-apk/Cargo.toml",
"chars": 547,
"preview": "[package]\nname = \"cargo-apk\"\nversion = \"0.4.3\"\nauthors = [\"Pierre Krieger <pierre.krieger1708@gmail.com>\", \"Philip Alldr"
},
{
"path": "cargo-apk/native_app_glue/NOTICE",
"chars": 577,
"preview": "Copyright (C) 2016 The Android Open Source Project\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou "
},
{
"path": "cargo-apk/native_app_glue/android_native_app_glue.c",
"chars": 18108,
"preview": "/*\n * Copyright (C) 2010 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"Lice"
},
{
"path": "cargo-apk/native_app_glue/android_native_app_glue.h",
"chars": 12059,
"preview": "/*\n * Copyright (C) 2010 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"Lice"
},
{
"path": "cargo-apk/src/config.rs",
"chars": 16979,
"preview": "use cargo::core::{TargetKind, Workspace};\nuse cargo::ops;\nuse cargo::util::CargoResult;\nuse cargo::CliError;\nuse failure"
},
{
"path": "cargo-apk/src/main.rs",
"chars": 13543,
"preview": "use cargo::core::Workspace;\nuse cargo::util::process_builder::process;\nuse cargo::util::Config as CargoConfig;\nuse clap:"
},
{
"path": "cargo-apk/src/ops/build/compile.rs",
"chars": 21818,
"preview": "use super::tempfile::TempFile;\nuse super::util;\nuse crate::config::AndroidBuildTarget;\nuse crate::config::AndroidConfig;"
},
{
"path": "cargo-apk/src/ops/build/targets.rs",
"chars": 1636,
"preview": "use crate::config::AndroidBuildTarget;\n\nimpl AndroidBuildTarget {\n /// Identifier used in the NDK to refer to the ABI"
},
{
"path": "cargo-apk/src/ops/build/tempfile.rs",
"chars": 1103,
"preview": "use cargo::util::CargoResult;\nuse std::fs::{self, File};\nuse std::path::PathBuf;\n\n/// Temporary file implementation that"
},
{
"path": "cargo-apk/src/ops/build/util.rs",
"chars": 6424,
"preview": "use crate::config::{AndroidBuildTarget, AndroidConfig};\nuse cargo::core::{Target, TargetKind, Workspace};\nuse cargo::uti"
},
{
"path": "cargo-apk/src/ops/build.rs",
"chars": 12209,
"preview": "mod compile;\nmod targets;\npub mod tempfile;\nmod util;\n\nuse self::compile::SharedLibraries;\nuse crate::config::{AndroidCo"
},
{
"path": "cargo-apk/src/ops/install.rs",
"chars": 865,
"preview": "use super::BuildResult;\nuse crate::config::AndroidConfig;\nuse crate::ops::build;\nuse cargo::core::Workspace;\nuse cargo::"
},
{
"path": "cargo-apk/src/ops/mod.rs",
"chars": 152,
"preview": "mod build;\nmod install;\nmod run;\n\npub use self::build::build;\npub use self::build::BuildResult;\npub use self::install::i"
},
{
"path": "cargo-apk/src/ops/run.rs",
"chars": 2115,
"preview": "use crate::config::AndroidConfig;\nuse crate::ops::install;\nuse cargo::core::{TargetKind, Workspace};\nuse cargo::util::pr"
},
{
"path": "cargo-apk/tests/cc/Cargo.toml",
"chars": 440,
"preview": "[package]\nname = \"test_cc-rs\"\nversion = \"0.1.0\"\nauthors = [\"Philip Alldredge <philip@philipalldredge.com>\"]\ndescription "
},
{
"path": "cargo-apk/tests/cc/build.rs",
"chars": 204,
"preview": "fn main() {\n cc::Build::new()\n .file(\"./cc_src/ctest.c\")\n .compile(\"ctest\");\n\n cc::Build::new()\n "
},
{
"path": "cargo-apk/tests/cc/cc_src/cpptest.cpp",
"chars": 309,
"preview": "#include <cstdint>\n#include <iostream>\n\nextern \"C\" int32_t multiply_by_four(int32_t value) {\n return value * 4;\n}\n\n//"
},
{
"path": "cargo-apk/tests/cc/cc_src/ctest.c",
"chars": 77,
"preview": "#include <stdint.h>\n\nint32_t add_two(int32_t value) {\n return value + 2;\n}"
},
{
"path": "cargo-apk/tests/cc/src/main.rs",
"chars": 493,
"preview": "fn main() {\n println!(\"Android cc test\");\n let result = unsafe {\n multiply_by_four(add_two(4))\n };\n\n "
},
{
"path": "cargo-apk/tests/cmake/Cargo.toml",
"chars": 412,
"preview": "[package]\nname = \"test_cmake-rs\"\nversion = \"0.1.0\"\nauthors = [\"Philip Alldredge <philip@philipalldredge.com>\"]\ndescripti"
},
{
"path": "cargo-apk/tests/cmake/build.rs",
"chars": 215,
"preview": "use cmake::Config;\n\nfn main() {\n let dst = Config::new(\"libcmaketest\")\n .build();\n println!(\"cargo:rustc-li"
},
{
"path": "cargo-apk/tests/cmake/libcmaketest/CMakeLists.txt",
"chars": 172,
"preview": "cmake_minimum_required(VERSION 2.8.9)\nproject(cmaketest)\n\nset(CMAKE_BUILD_TYPE Release)\nADD_LIBRARY(cmaketest STATIC cma"
},
{
"path": "cargo-apk/tests/cmake/libcmaketest/cmaketest.c",
"chars": 56,
"preview": "int multiply_by_10(int value) {\n return value * 10;\n}"
},
{
"path": "cargo-apk/tests/cmake/src/main.rs",
"chars": 246,
"preview": "fn main() {\n println!(\"Android cmake test\");\n let result = unsafe {\n multiply_by_10(2)\n };\n\n println!"
},
{
"path": "cargo-apk/tests/inner_attributes/Cargo.toml",
"chars": 154,
"preview": "[package]\nname = \"test_inner_attributes\"\nversion = \"0.1.0\"\nauthors = [\"Philip Alldredge <philip@philipalldredge.com>\"]\ne"
},
{
"path": "cargo-apk/tests/inner_attributes/src/main.rs",
"chars": 86,
"preview": "#![cfg(target_os = \"android\")]\n\nfn main() {\n println!(\"Inner attributes test\");\n}\n\n"
},
{
"path": "cargo-apk/tests/native-library/Cargo.toml",
"chars": 150,
"preview": "[package]\nname = \"test_native-library\"\nversion = \"0.1.0\"\nauthors = [\"Philip Alldredge <philip@philipalldredge.com>\"]\nedi"
},
{
"path": "cargo-apk/tests/native-library/src/main.rs",
"chars": 415,
"preview": "#![cfg(target_os = \"android\")]\nuse std::ffi::c_void;\nuse std::ptr;\n\nfn main() {\n println!(\"Android native library tes"
},
{
"path": "cargo-apk/tests/run_tests.sh",
"chars": 1152,
"preview": "#!/bin/bash\n\nset -e\n\nfail() {\n echo \"$@\"\n exit 1\n}\n\n[[ $(basename $(pwd)) = cargo-apk ]] || fail \"Must be run in c"
},
{
"path": "examples/advanced/Cargo.toml",
"chars": 3938,
"preview": "[package]\nname = \"advanced\"\nversion = \"0.1.0\"\nauthors = [\"Philip Alldredge <philip@philipalldredge.com\"]\npublish = false"
},
{
"path": "examples/advanced/assets/test_asset",
"chars": 15,
"preview": "str1\nstr2\nstr3\n"
},
{
"path": "examples/advanced/src/main.rs",
"chars": 76,
"preview": "fn main() {\n println!(\"main() has been called from advanced example\");\n}\n"
},
{
"path": "examples/basic/Cargo.toml",
"chars": 190,
"preview": "[package]\nname = \"android_glue_example\"\nversion = \"0.1.0\"\nauthors = [\"Pierre Krieger <pierre.krieger1708@gmail.com>\"]\ned"
},
{
"path": "examples/basic/src/main.rs",
"chars": 54,
"preview": "fn main() {\n println!(\"main() has been called\");\n}\n"
},
{
"path": "examples/multiple_targets/Cargo.toml",
"chars": 412,
"preview": "[package]\nname = \"android_primary_bin\"\nversion = \"0.1.0\"\nauthors = [\"Philip Alldredge <philip@philipalldredge.com>\"]\npub"
},
{
"path": "examples/multiple_targets/examples/example1.rs",
"chars": 66,
"preview": "fn main() {\n println!(\"main() has been called on example1\");\n}\n"
},
{
"path": "examples/multiple_targets/src/bin/secondary-bin.rs",
"chars": 78,
"preview": "fn main() {\n println!(\"main() has been called on the secondary binary\");\n}\n"
},
{
"path": "examples/multiple_targets/src/main.rs",
"chars": 76,
"preview": "fn main() {\n println!(\"main() has been called on the primary binary\");\n}\n"
},
{
"path": "examples/use_assets/Cargo.toml",
"chars": 375,
"preview": "[package]\nname = \"android_glue_assets_example\"\nversion = \"0.1.0\"\nauthors = [\"Pierre Krieger <pierre.krieger1708@gmail.co"
},
{
"path": "examples/use_assets/assets/test_asset",
"chars": 15,
"preview": "str1\nstr2\nstr3\n"
},
{
"path": "examples/use_assets/src/main.rs",
"chars": 601,
"preview": "use android_ndk::android_app::AndroidApp;\nuse android_ndk::asset::Asset;\nuse std::ffi::CString;\nuse std::io::{BufRead, B"
},
{
"path": "examples/use_icon/Cargo.toml",
"chars": 302,
"preview": "[package]\nname = \"android_glue_icon_example\"\nversion = \"0.1.0\"\nauthors = [\"Pierre Krieger <pierre.krieger1708@gmail.com>"
},
{
"path": "examples/use_icon/src/main.rs",
"chars": 78,
"preview": "fn main() {\n println!(\"main() has been called, did you like the icon?\");\n}\n"
},
{
"path": "glue/.gitignore",
"chars": 20,
"preview": "/target\n/Cargo.lock\n"
},
{
"path": "glue/Cargo.toml",
"chars": 369,
"preview": "[package]\nname = \"android_glue\"\nversion = \"0.2.3\"\nauthors = [\"Pierre Krieger <pierre.krieger1708@gmail.com>\"]\nlicense = "
},
{
"path": "glue/src/lib.rs",
"chars": 575,
"preview": "//! Glue for working with cargo-apk\n//!\n//! Previously, this library provided an abstraction over the event loop. Howev"
}
]
About this extraction
This page contains the full source code of the rust-windowing/android-rs-glue GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 52 files (141.7 KB), approximately 34.6k tokens, and a symbol index with 143 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.