├── .circleci └── config.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── cargo-apk ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── native_app_glue │ ├── NOTICE │ ├── android_native_app_glue.c │ └── android_native_app_glue.h ├── src │ ├── config.rs │ ├── main.rs │ └── ops │ │ ├── build.rs │ │ ├── build │ │ ├── compile.rs │ │ ├── targets.rs │ │ ├── tempfile.rs │ │ └── util.rs │ │ ├── install.rs │ │ ├── mod.rs │ │ └── run.rs └── tests │ ├── cc │ ├── Cargo.lock │ ├── Cargo.toml │ ├── build.rs │ ├── cc_src │ │ ├── cpptest.cpp │ │ └── ctest.c │ └── src │ │ └── main.rs │ ├── cmake │ ├── Cargo.lock │ ├── Cargo.toml │ ├── build.rs │ ├── libcmaketest │ │ ├── CMakeLists.txt │ │ └── cmaketest.c │ └── src │ │ └── main.rs │ ├── inner_attributes │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── main.rs │ ├── native-library │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── main.rs │ └── run_tests.sh ├── examples ├── advanced │ ├── Cargo.lock │ ├── Cargo.toml │ ├── assets │ │ └── test_asset │ ├── res │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ └── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ └── src │ │ └── main.rs ├── basic │ ├── Cargo.lock │ ├── Cargo.toml │ └── src │ │ └── main.rs ├── multiple_targets │ ├── Cargo.lock │ ├── Cargo.toml │ ├── examples │ │ └── example1.rs │ └── src │ │ ├── bin │ │ └── secondary-bin.rs │ │ └── main.rs ├── use_assets │ ├── Cargo.lock │ ├── Cargo.toml │ ├── assets │ │ └── test_asset │ └── src │ │ └── main.rs └── use_icon │ ├── Cargo.lock │ ├── Cargo.toml │ ├── res │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ └── mipmap-xxxhdpi │ │ └── ic_launcher.png │ └── src │ └── main.rs └── glue ├── .gitignore ├── Cargo.toml └── src └── lib.rs /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build-and-test: 4 | environment: 5 | IMAGE_NAME: tomaka/cargo-apk 6 | docker: 7 | - image: docker:stable 8 | steps: 9 | - checkout 10 | - setup_remote_docker 11 | - run: 12 | name: Build image 13 | command: docker build -t $IMAGE_NAME:latest . 14 | - run: 15 | name: Archive image 16 | command: docker save -o image.tar $IMAGE_NAME 17 | - persist_to_workspace: 18 | root: . 19 | paths: 20 | - ./image.tar 21 | publish-docker-image: 22 | environment: 23 | IMAGE_NAME: tomaka/cargo-apk 24 | docker: 25 | - image: docker:stable 26 | steps: 27 | - attach_workspace: 28 | at: /tmp/workspace 29 | - setup_remote_docker 30 | - run: 31 | name: Load image 32 | command: docker load -i /tmp/workspace/image.tar 33 | - run: 34 | name: Publish final image 35 | command: | 36 | echo "$DOCKERHUB_PASSWORD" | docker login -u $DOCKERHUB_LOGIN --password-stdin 37 | docker push $IMAGE_NAME 38 | publish-crates-io: 39 | working_directory: ~/android-rs-glue 40 | docker: 41 | - image: circleci/rust:buster 42 | steps: 43 | - checkout 44 | - run: cd ./cargo-apk && cargo publish --token $CRATESIO_TOKEN 45 | - run: cd ./glue && cargo publish --token $CRATESIO_TOKEN 46 | workflows: 47 | version: 2 48 | all: 49 | jobs: 50 | - build-and-test 51 | - publish-docker-image: 52 | requires: 53 | - build-and-test 54 | filters: 55 | branches: 56 | only: master 57 | - publish-crates-io: 58 | requires: 59 | - build-and-test 60 | filters: 61 | branches: 62 | only: master 63 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | .idea 3 | *.iml 4 | CMakeFiles 5 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rust:stretch 2 | 3 | RUN apt-get update 4 | RUN apt-get install -yq openjdk-8-jre unzip wget cmake 5 | 6 | RUN rustup target add armv7-linux-androideabi 7 | RUN rustup target add aarch64-linux-android 8 | RUN rustup target add i686-linux-android 9 | RUN rustup target add x86_64-linux-android 10 | 11 | # Install Android SDK 12 | ENV ANDROID_HOME /opt/android-sdk-linux 13 | RUN mkdir ${ANDROID_HOME} && \ 14 | cd ${ANDROID_HOME} && \ 15 | wget -q https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip && \ 16 | unzip -q sdk-tools-linux-4333796.zip && \ 17 | rm sdk-tools-linux-4333796.zip && \ 18 | chown -R root:root /opt 19 | RUN yes | ${ANDROID_HOME}/tools/bin/sdkmanager "platform-tools" | grep -v = || true 20 | RUN yes | ${ANDROID_HOME}/tools/bin/sdkmanager "platforms;android-29" | grep -v = || true 21 | RUN yes | ${ANDROID_HOME}/tools/bin/sdkmanager "build-tools;29.0.0" | grep -v = || true 22 | RUN ${ANDROID_HOME}/tools/bin/sdkmanager --update | grep -v = || true 23 | 24 | # Install Android NDK 25 | RUN cd /usr/local && \ 26 | wget -q http://dl.google.com/android/repository/android-ndk-r20-linux-x86_64.zip && \ 27 | unzip -q android-ndk-r20-linux-x86_64.zip && \ 28 | rm android-ndk-r20-linux-x86_64.zip 29 | ENV NDK_HOME /usr/local/android-ndk-r20 30 | 31 | # Copy contents to container. Should only use this on a clean directory 32 | COPY . /root/cargo-apk 33 | 34 | # Install binary 35 | RUN cargo install --path /root/cargo-apk/cargo-apk 36 | 37 | # Run tests 38 | RUN cd /root/cargo-apk/cargo-apk && ./tests/run_tests.sh 39 | 40 | # Remove source and build files 41 | RUN rm -rf /root/cargo-apk 42 | 43 | # Make directory for user code 44 | RUN mkdir /root/src 45 | WORKDIR /root/src 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | deprecated in favor of https://github.com/rust-windowing/android-ndk-rs which works with winit master 2 | 3 | # Android Glue 4 | 5 | [![Crates.io](https://img.shields.io/crates/v/android-glue.svg?label=android-glue)](https://crates.io/crates/android-glue) 6 | [![Crates.io](https://img.shields.io/crates/v/cargo-apk?label=cargo-apk)](https://crates.io/crates/cargo-apk) 7 | [![CircleCI](https://circleci.com/gh/rust-windowing/android-rs-glue.svg?style=svg)](https://circleci.com/gh/rust-windowing/android-rs-glue) 8 | 9 | # Usage 10 | 11 | ## With Docker 12 | 13 | The easiest way to compile for Android is to use [Docker](https://www.docker.com/) and the 14 | [philipalldredge/cargo-apk](https://hub.docker.com/r/philipalldredge/cargo-apk/) image. 15 | 16 | In order to build an APK, simply do this: 17 | 18 | ``` 19 | docker run --rm -v :/root/src philipalldredge/cargo-apk cargo apk build 20 | ``` 21 | 22 | For example if you're on Linux and you want to compile the project in the current working 23 | directory. 24 | 25 | ``` 26 | docker run --rm -v "$(pwd):/root/src" -w /root/src philipalldredge/cargo-apk cargo apk build 27 | ``` 28 | 29 | Do not mount a volume on `/root` or you will erase the local installation of Cargo. 30 | 31 | After the build is finished, you should get an Android package in `target/android-artifacts/debug/apk`. 32 | 33 | ## Manual usage 34 | 35 | ### Setting up your environment 36 | 37 | Before you can compile for Android, you need to setup your environment. This needs to be done only once per system. 38 | 39 | - Install [`rustup`](https://rustup.rs/). 40 | - Run `rustup target add ` 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`. 41 | - `rustup target add armv7-linux-androideabi` 42 | - `rustup target add aarch64-linux-android` 43 | - `rustup target add i686-linux-android` 44 | - `rustup target add x86_64-linux-android` 45 | - Install the Java JRE or JDK (on Ubuntu, `sudo apt-get install openjdk-8-jdk`). 46 | - Download and unzip [the Android NDK](https://developer.android.com/ndk). 47 | - Download and unzip [the Android SDK](https://developer.android.com/studio). 48 | - Install some components in the SDK: `./android-sdk/tools/bin/sdkmanager "platform-tools" "platforms;android-29" "build-tools;29.0.0"`. 49 | - Install `cargo-apk` with `cargo install cargo-apk`. 50 | - Set the environment variables `NDK_HOME` to the path of the NDK and `ANDROID_HOME` to the path of the SDK. 51 | 52 | ### Compiling 53 | 54 | In the project root for your Android crate, run `cargo apk build`. You can use the same options as 55 | with the regular `cargo build`. 56 | 57 | This will build an Android package in `target/android-artifacts//apk`. 58 | 59 | ### Compiling Multiple Binaries 60 | 61 | `cargo apk build` supports building multiple binaries and examples using the same arguments as `cargo build`. It will produce an APK for each binary. 62 | 63 | Android packages for bin targets are placed in `target/android-artifacts//apk`. 64 | 65 | Android packages for example targets are placed in `target/android-artifacts//apk/examples`. 66 | 67 | ### Testing on an Android emulator 68 | 69 | Start the emulator, then run: 70 | 71 | ```sh 72 | cargo apk run 73 | ``` 74 | 75 | This will install your application on the emulator, then run it. 76 | If you only want to install, use `cargo apk install`. 77 | 78 | To show log run: `cargo apk logcat | grep RustAndroidGlueStdouterr` 79 | 80 | # Interfacing with Android 81 | 82 | An application is not very useful if it doesn't have access to the screen, the user inputs, etc. 83 | 84 | The `android_glue` crate provides FFI with the Android environment for things that are not in 85 | the stdlib. 86 | 87 | # How it works 88 | 89 | ## The build process 90 | 91 | The build process works by: 92 | 93 | - Using rustc to always compile your crate as a shared library by: 94 | - 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. 95 | - 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. 96 | - 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`. 97 | - Linking using the NDK provided linker. 98 | 99 | This first step outputs a shared library, and is run once per target architecture. 100 | 101 | 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. 102 | 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. 103 | 104 | # Supported `[package.metadata.android]` entries 105 | 106 | ```toml 107 | # The target Android API level. 108 | # "android_version" is the compile SDK version. It defaults to 29. 109 | # (target_sdk_version defaults to the value of "android_version") 110 | # (min_sdk_version defaults to 18) It defaults to 18 because this is the minimum supported by rustc. 111 | android_version = 29 112 | target_sdk_version = 29 113 | min_sdk_version = 26 114 | 115 | # Specifies the array of targets to build for. 116 | # Defaults to "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android". 117 | build_targets = [ "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android", "x86_64-linux-android" ] 118 | 119 | # The following values can be customized on a per bin/example basis. See multiple_targets example 120 | # If a value is not specified for a secondary target, it will inherit the value defined in the `package.metadata.android` 121 | # section unless otherwise noted. 122 | # 123 | 124 | # The Java package name for your application. 125 | # Hyphens are converted to underscores. 126 | # Defaults to rust. for binaries. 127 | # Defaults to rust..example. for examples. 128 | # For example: for a binary "my_app", the default package name will be "rust.my_app" 129 | # Secondary targets will not inherit the value defined in the root android configuration. 130 | package_name = "rust.cargo.apk.advanced" 131 | 132 | # The user-friendly name for your app, as displayed in the applications menu. 133 | # Defaults to the target name 134 | # Secondary targets will not inherit the value defined in the root android configuration. 135 | label = "My Android App" 136 | 137 | # Internal version number used to determine whether one version is more recent than another. Must be an integer. 138 | # Defaults to 1 139 | # See https://developer.android.com/guide/topics/manifest/manifest-element 140 | version_code = 2 141 | 142 | # The version number shown to users. 143 | # Defaults to the cargo package version number 144 | # See https://developer.android.com/guide/topics/manifest/manifest-element 145 | version_name = "2.0" 146 | 147 | # Path to your application's resources folder. 148 | # If not specified, resources will not be included in the APK 149 | res = "path/to/res_folder" 150 | 151 | # Virtual path your application's icon for any mipmap level. 152 | # If not specified, an icon will not be included in the APK. 153 | icon = "@mipmap/ic_launcher" 154 | 155 | # Path to the folder containing your application's assets. 156 | # If not specified, assets will not be included in the APK 157 | assets = "path/to/assets_folder" 158 | 159 | # If set to true, makes the app run in full-screen, by adding the following line 160 | # as an XML attribute to the manifest's tag : 161 | # android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen 162 | # Defaults to false. 163 | fullscreen = false 164 | 165 | # The maximum supported OpenGL ES version , as claimed by the manifest. 166 | # Defaults to 2.0. 167 | # See https://developer.android.com/guide/topics/graphics/opengl.html#manifest 168 | opengles_version_major = 3 169 | opengles_version_minor = 2 170 | 171 | # Adds extra arbitrary XML attributes to the tag in the manifest. 172 | # See https://developer.android.com/guide/topics/manifest/application-element.html 173 | [package.metadata.android.application_attributes] 174 | "android:debuggable" = "true" 175 | "android:hardwareAccelerated" = "true" 176 | 177 | # Adds extra arbitrary XML attributes to the tag in the manifest. 178 | # See https://developer.android.com/guide/topics/manifest/activity-element.html 179 | [package.metadata.android.activity_attributes] 180 | "android:screenOrientation" = "unspecified" 181 | "android:uiOptions" = "none" 182 | 183 | # Adds a uses-feature element to the manifest 184 | # Supported keys: name, required, version 185 | # The glEsVersion attribute is not supported using this section. 186 | # It can be specified using the opengles_version_major and opengles_version_minor values 187 | # See https://developer.android.com/guide/topics/manifest/uses-feature-element 188 | [[package.metadata.android.feature]] 189 | name = "android.hardware.camera" 190 | 191 | [[package.metadata.android.feature]] 192 | name = "android.hardware.vulkan.level" 193 | version = "1" 194 | required = false 195 | 196 | # Adds a uses-permission element to the manifest. 197 | # Note that android_version 23 and higher, Android requires the application to request permissions at runtime. 198 | # There is currently no way to do this using a pure NDK based application. 199 | # See https://developer.android.com/guide/topics/manifest/uses-permission-element 200 | [[package.metadata.android.permission]] 201 | name = "android.permission.WRITE_EXTERNAL_STORAGE" 202 | max_sdk_version = 18 203 | 204 | [[package.metadata.android.permission]] 205 | name = "android.permission.CAMERA" 206 | ``` 207 | 208 | # Environment Variables 209 | 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. 210 | 211 | - CC : path to NDK provided `clang` wrapper for the appropriate target and android platform. 212 | - CXX : path to NDK provided `clang++` wrapper for the appropriate target and android platform. 213 | - AR : path to NDK provided `ar` 214 | - CXXSTDLIB : `c++` to use the full featured C++ standard library provided by the NDK. 215 | - 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. 216 | - CMAKE_GENERATOR : `Unix Makefiles` to default to `Unix Makefiles` as opposed to using the CMake default which may not be appropriate depending on platform. 217 | - CMAKE_MAKE_PROGRAM: Path to NDK provided make. 218 | 219 | # C++ Standard Library Compatibility Issues 220 | 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. 221 | -------------------------------------------------------------------------------- /cargo-apk/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /cargo-apk/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cargo-apk" 3 | version = "0.4.3" 4 | authors = ["Pierre Krieger ", "Philip Alldredge "] 5 | license = "MIT" 6 | description = "Cargo subcommand that allows you to build Android packages" 7 | repository = "https://github.com/rust-windowing/android-rs-glue/tree/master/cargo-apk" 8 | edition = "2018" 9 | 10 | [dependencies] 11 | cargo = "0.41.0" 12 | clap = "2.33.0" 13 | itertools = "0.8.2" 14 | dirs = "2.0.2" 15 | failure = "0.1.6" 16 | multimap = "0.8.0" 17 | serde = "1.0.104" 18 | toml = "0.5.5" 19 | 20 | [dev-dependencies] 21 | assert_cmd = "0.12.0" 22 | -------------------------------------------------------------------------------- /cargo-apk/native_app_glue/NOTICE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2016 The Android Open Source Project 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /cargo-apk/native_app_glue/android_native_app_glue.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | #include 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include "android_native_app_glue.h" 27 | #include 28 | 29 | #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "threaded_app", __VA_ARGS__)) 30 | #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "threaded_app", __VA_ARGS__)) 31 | 32 | /* For debug builds, always enable the debug traces in this library */ 33 | #ifndef NDEBUG 34 | # define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "threaded_app", __VA_ARGS__)) 35 | #else 36 | # define LOGV(...) ((void)0) 37 | #endif 38 | 39 | static void free_saved_state(struct android_app* android_app) { 40 | pthread_mutex_lock(&android_app->mutex); 41 | if (android_app->savedState != NULL) { 42 | free(android_app->savedState); 43 | android_app->savedState = NULL; 44 | android_app->savedStateSize = 0; 45 | } 46 | pthread_mutex_unlock(&android_app->mutex); 47 | } 48 | 49 | int8_t android_app_read_cmd(struct android_app* android_app) { 50 | int8_t cmd; 51 | if (read(android_app->msgread, &cmd, sizeof(cmd)) == sizeof(cmd)) { 52 | switch (cmd) { 53 | case APP_CMD_SAVE_STATE: 54 | free_saved_state(android_app); 55 | break; 56 | } 57 | return cmd; 58 | } else { 59 | LOGE("No data on command pipe!"); 60 | } 61 | return -1; 62 | } 63 | 64 | static void print_cur_config(struct android_app* android_app) { 65 | char lang[2], country[2]; 66 | AConfiguration_getLanguage(android_app->config, lang); 67 | AConfiguration_getCountry(android_app->config, country); 68 | 69 | LOGV("Config: mcc=%d mnc=%d lang=%c%c cnt=%c%c orien=%d touch=%d dens=%d " 70 | "keys=%d nav=%d keysHid=%d navHid=%d sdk=%d size=%d long=%d " 71 | "modetype=%d modenight=%d", 72 | AConfiguration_getMcc(android_app->config), 73 | AConfiguration_getMnc(android_app->config), 74 | lang[0], lang[1], country[0], country[1], 75 | AConfiguration_getOrientation(android_app->config), 76 | AConfiguration_getTouchscreen(android_app->config), 77 | AConfiguration_getDensity(android_app->config), 78 | AConfiguration_getKeyboard(android_app->config), 79 | AConfiguration_getNavigation(android_app->config), 80 | AConfiguration_getKeysHidden(android_app->config), 81 | AConfiguration_getNavHidden(android_app->config), 82 | AConfiguration_getSdkVersion(android_app->config), 83 | AConfiguration_getScreenSize(android_app->config), 84 | AConfiguration_getScreenLong(android_app->config), 85 | AConfiguration_getUiModeType(android_app->config), 86 | AConfiguration_getUiModeNight(android_app->config)); 87 | } 88 | 89 | void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd) { 90 | switch (cmd) { 91 | case APP_CMD_INPUT_CHANGED: 92 | LOGV("APP_CMD_INPUT_CHANGED\n"); 93 | pthread_mutex_lock(&android_app->mutex); 94 | if (android_app->inputQueue != NULL) { 95 | AInputQueue_detachLooper(android_app->inputQueue); 96 | } 97 | android_app->inputQueue = android_app->pendingInputQueue; 98 | if (android_app->inputQueue != NULL) { 99 | LOGV("Attaching input queue to looper"); 100 | AInputQueue_attachLooper(android_app->inputQueue, 101 | android_app->looper, LOOPER_ID_INPUT, NULL, 102 | &android_app->inputPollSource); 103 | } 104 | pthread_cond_broadcast(&android_app->cond); 105 | pthread_mutex_unlock(&android_app->mutex); 106 | break; 107 | 108 | case APP_CMD_INIT_WINDOW: 109 | LOGV("APP_CMD_INIT_WINDOW\n"); 110 | pthread_mutex_lock(&android_app->mutex); 111 | android_app->window = android_app->pendingWindow; 112 | pthread_cond_broadcast(&android_app->cond); 113 | pthread_mutex_unlock(&android_app->mutex); 114 | break; 115 | 116 | case APP_CMD_TERM_WINDOW: 117 | LOGV("APP_CMD_TERM_WINDOW\n"); 118 | pthread_cond_broadcast(&android_app->cond); 119 | break; 120 | 121 | case APP_CMD_RESUME: 122 | case APP_CMD_START: 123 | case APP_CMD_PAUSE: 124 | case APP_CMD_STOP: 125 | LOGV("activityState=%d\n", cmd); 126 | pthread_mutex_lock(&android_app->mutex); 127 | android_app->activityState = cmd; 128 | pthread_cond_broadcast(&android_app->cond); 129 | pthread_mutex_unlock(&android_app->mutex); 130 | break; 131 | 132 | case APP_CMD_CONFIG_CHANGED: 133 | LOGV("APP_CMD_CONFIG_CHANGED\n"); 134 | AConfiguration_fromAssetManager(android_app->config, 135 | android_app->activity->assetManager); 136 | print_cur_config(android_app); 137 | break; 138 | 139 | case APP_CMD_DESTROY: 140 | LOGV("APP_CMD_DESTROY\n"); 141 | android_app->destroyRequested = 1; 142 | break; 143 | } 144 | } 145 | 146 | void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd) { 147 | switch (cmd) { 148 | case APP_CMD_TERM_WINDOW: 149 | LOGV("APP_CMD_TERM_WINDOW\n"); 150 | pthread_mutex_lock(&android_app->mutex); 151 | android_app->window = NULL; 152 | pthread_cond_broadcast(&android_app->cond); 153 | pthread_mutex_unlock(&android_app->mutex); 154 | break; 155 | 156 | case APP_CMD_SAVE_STATE: 157 | LOGV("APP_CMD_SAVE_STATE\n"); 158 | pthread_mutex_lock(&android_app->mutex); 159 | android_app->stateSaved = 1; 160 | pthread_cond_broadcast(&android_app->cond); 161 | pthread_mutex_unlock(&android_app->mutex); 162 | break; 163 | 164 | case APP_CMD_RESUME: 165 | free_saved_state(android_app); 166 | break; 167 | } 168 | } 169 | 170 | void app_dummy() { 171 | 172 | } 173 | 174 | static void android_app_destroy(struct android_app* android_app) { 175 | LOGV("android_app_destroy!"); 176 | free_saved_state(android_app); 177 | pthread_mutex_lock(&android_app->mutex); 178 | if (!android_app->destroyRequested) 179 | ANativeActivity_finish(android_app->activity); 180 | if (android_app->inputQueue != NULL) 181 | AInputQueue_detachLooper(android_app->inputQueue); 182 | AConfiguration_delete(android_app->config); 183 | android_app->destroyed = 1; 184 | pthread_mutex_unlock(&android_app->mutex); 185 | // Can't touch android_app object after this. 186 | } 187 | 188 | static void process_input(struct android_app* app, struct android_poll_source* source) { 189 | AInputEvent* event = NULL; 190 | while (AInputQueue_getEvent(app->inputQueue, &event) >= 0) { 191 | LOGV("New input event: type=%d\n", AInputEvent_getType(event)); 192 | if (AInputQueue_preDispatchEvent(app->inputQueue, event)) { 193 | continue; 194 | } 195 | int32_t handled = 0; 196 | if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event); 197 | AInputQueue_finishEvent(app->inputQueue, event, handled); 198 | } 199 | } 200 | 201 | static void process_cmd(struct android_app* app, struct android_poll_source* source) { 202 | int8_t cmd = android_app_read_cmd(app); 203 | android_app_pre_exec_cmd(app, cmd); 204 | if (app->onAppCmd != NULL) app->onAppCmd(app, cmd); 205 | android_app_post_exec_cmd(app, cmd); 206 | } 207 | 208 | static void* android_app_entry(void* param) { 209 | struct android_app* android_app = (struct android_app*)param; 210 | 211 | android_app->config = AConfiguration_new(); 212 | AConfiguration_fromAssetManager(android_app->config, android_app->activity->assetManager); 213 | 214 | print_cur_config(android_app); 215 | 216 | android_app->cmdPollSource.id = LOOPER_ID_MAIN; 217 | android_app->cmdPollSource.app = android_app; 218 | android_app->cmdPollSource.process = process_cmd; 219 | android_app->inputPollSource.id = LOOPER_ID_INPUT; 220 | android_app->inputPollSource.app = android_app; 221 | android_app->inputPollSource.process = process_input; 222 | 223 | ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); 224 | ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, NULL, 225 | &android_app->cmdPollSource); 226 | android_app->looper = looper; 227 | 228 | pthread_mutex_lock(&android_app->mutex); 229 | android_app->running = 1; 230 | pthread_cond_broadcast(&android_app->cond); 231 | pthread_mutex_unlock(&android_app->mutex); 232 | 233 | ANDROID_APP = android_app; 234 | 235 | android_main(android_app); 236 | 237 | android_app_destroy(android_app); 238 | 239 | LOGV("thread exiting"); 240 | return NULL; 241 | } 242 | 243 | static void *logging_thread(void *fd_as_ptr) { 244 | int fd = (int) (size_t) fd_as_ptr; 245 | LOGV("Logging thread started; fd is %d", fd); 246 | char buffer[2048]; 247 | int cursor = 0; 248 | while (1) { 249 | int result = read(fd, (void *) buffer + cursor, 2047 - cursor); 250 | if (result == 0) return NULL; 251 | if (result < 0) { 252 | LOGE("Logging thread: error reading from pipe: %s", strerror(errno)); 253 | return NULL; 254 | } 255 | int old_cursor = cursor; 256 | cursor += result; 257 | char *newline = (char *) memchr((void *) buffer + old_cursor, '\n', cursor); 258 | if (newline) { 259 | *newline = '\0'; 260 | __android_log_write(ANDROID_LOG_DEBUG, "RustStdoutStderr", buffer); 261 | int new_start = newline + 1 - buffer; 262 | memcpy((void *) buffer, (void *) newline + 1, cursor - new_start); 263 | cursor -= new_start; 264 | } else if (cursor == 2047) { 265 | buffer[2047] = '\0'; 266 | __android_log_write(ANDROID_LOG_DEBUG, "RustStdoutStderr", buffer); 267 | cursor = 0; 268 | } 269 | } 270 | } 271 | 272 | // -------------------------------------------------------------------- 273 | // Native activity interaction (called from main thread) 274 | // -------------------------------------------------------------------- 275 | 276 | static struct android_app* android_app_create(ANativeActivity* activity, 277 | void* savedState, size_t savedStateSize) { 278 | struct android_app* android_app = (struct android_app*)malloc(sizeof(struct android_app)); 279 | memset(android_app, 0, sizeof(struct android_app)); 280 | android_app->activity = activity; 281 | 282 | pthread_mutex_init(&android_app->mutex, NULL); 283 | pthread_cond_init(&android_app->cond, NULL); 284 | 285 | if (savedState != NULL) { 286 | android_app->savedState = malloc(savedStateSize); 287 | android_app->savedStateSize = savedStateSize; 288 | memcpy(android_app->savedState, savedState, savedStateSize); 289 | } 290 | 291 | int msgpipe[2]; 292 | if (pipe(msgpipe)) { 293 | LOGE("could not create pipe: %s", strerror(errno)); 294 | return NULL; 295 | } 296 | android_app->msgread = msgpipe[0]; 297 | android_app->msgwrite = msgpipe[1]; 298 | 299 | int logpipe[2]; 300 | if (pipe(logpipe)) { 301 | LOGE("could not create pipe: %s", strerror(errno)); 302 | return NULL; 303 | } 304 | dup2(logpipe[1], STDOUT_FILENO); 305 | dup2(logpipe[1], STDERR_FILENO); 306 | 307 | pthread_t log_thread; 308 | pthread_create(&log_thread, NULL, logging_thread, (void *) (size_t) logpipe[0]); 309 | pthread_detach(log_thread); 310 | 311 | pthread_create(&android_app->thread, NULL, android_app_entry, android_app); 312 | 313 | // Wait for thread to start. 314 | pthread_mutex_lock(&android_app->mutex); 315 | while (!android_app->running) { 316 | pthread_cond_wait(&android_app->cond, &android_app->mutex); 317 | } 318 | pthread_mutex_unlock(&android_app->mutex); 319 | 320 | return android_app; 321 | } 322 | 323 | static void android_app_write_cmd(struct android_app* android_app, int8_t cmd) { 324 | if (write(android_app->msgwrite, &cmd, sizeof(cmd)) != sizeof(cmd)) { 325 | LOGE("Failure writing android_app cmd: %s\n", strerror(errno)); 326 | } 327 | } 328 | 329 | static void android_app_set_input(struct android_app* android_app, AInputQueue* inputQueue) { 330 | pthread_mutex_lock(&android_app->mutex); 331 | android_app->pendingInputQueue = inputQueue; 332 | android_app_write_cmd(android_app, APP_CMD_INPUT_CHANGED); 333 | while (android_app->inputQueue != android_app->pendingInputQueue) { 334 | pthread_cond_wait(&android_app->cond, &android_app->mutex); 335 | } 336 | pthread_mutex_unlock(&android_app->mutex); 337 | } 338 | 339 | static void android_app_set_window(struct android_app* android_app, ANativeWindow* window) { 340 | pthread_mutex_lock(&android_app->mutex); 341 | if (android_app->pendingWindow != NULL) { 342 | android_app_write_cmd(android_app, APP_CMD_TERM_WINDOW); 343 | } 344 | android_app->pendingWindow = window; 345 | if (window != NULL) { 346 | android_app_write_cmd(android_app, APP_CMD_INIT_WINDOW); 347 | } 348 | while (android_app->window != android_app->pendingWindow) { 349 | pthread_cond_wait(&android_app->cond, &android_app->mutex); 350 | } 351 | pthread_mutex_unlock(&android_app->mutex); 352 | } 353 | 354 | static void android_app_set_activity_state(struct android_app* android_app, int8_t cmd) { 355 | pthread_mutex_lock(&android_app->mutex); 356 | android_app_write_cmd(android_app, cmd); 357 | while (android_app->activityState != cmd) { 358 | pthread_cond_wait(&android_app->cond, &android_app->mutex); 359 | } 360 | pthread_mutex_unlock(&android_app->mutex); 361 | } 362 | 363 | static void android_app_free(struct android_app* android_app) { 364 | android_app_write_cmd(android_app, APP_CMD_DESTROY); 365 | pthread_join(android_app->thread, NULL); 366 | 367 | close(android_app->msgread); 368 | close(android_app->msgwrite); 369 | pthread_cond_destroy(&android_app->cond); 370 | pthread_mutex_destroy(&android_app->mutex); 371 | free(android_app); 372 | 373 | exit(0); 374 | } 375 | 376 | static void onDestroy(ANativeActivity* activity) { 377 | LOGV("Destroy: %p\n", activity); 378 | android_app_free((struct android_app*)activity->instance); 379 | } 380 | 381 | static void onStart(ANativeActivity* activity) { 382 | LOGV("Start: %p\n", activity); 383 | android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_START); 384 | } 385 | 386 | static void onResume(ANativeActivity* activity) { 387 | LOGV("Resume: %p\n", activity); 388 | android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_RESUME); 389 | } 390 | 391 | static void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen) { 392 | struct android_app* android_app = (struct android_app*)activity->instance; 393 | void* savedState = NULL; 394 | 395 | LOGV("SaveInstanceState: %p\n", activity); 396 | pthread_mutex_lock(&android_app->mutex); 397 | android_app->stateSaved = 0; 398 | android_app_write_cmd(android_app, APP_CMD_SAVE_STATE); 399 | while (!android_app->stateSaved) { 400 | pthread_cond_wait(&android_app->cond, &android_app->mutex); 401 | } 402 | 403 | if (android_app->savedState != NULL) { 404 | savedState = android_app->savedState; 405 | *outLen = android_app->savedStateSize; 406 | android_app->savedState = NULL; 407 | android_app->savedStateSize = 0; 408 | } 409 | 410 | pthread_mutex_unlock(&android_app->mutex); 411 | 412 | return savedState; 413 | } 414 | 415 | static void onPause(ANativeActivity* activity) { 416 | LOGV("Pause: %p\n", activity); 417 | android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_PAUSE); 418 | } 419 | 420 | static void onStop(ANativeActivity* activity) { 421 | LOGV("Stop: %p\n", activity); 422 | android_app_set_activity_state((struct android_app*)activity->instance, APP_CMD_STOP); 423 | } 424 | 425 | static void onConfigurationChanged(ANativeActivity* activity) { 426 | struct android_app* android_app = (struct android_app*)activity->instance; 427 | LOGV("ConfigurationChanged: %p\n", activity); 428 | android_app_write_cmd(android_app, APP_CMD_CONFIG_CHANGED); 429 | } 430 | 431 | static void onLowMemory(ANativeActivity* activity) { 432 | struct android_app* android_app = (struct android_app*)activity->instance; 433 | LOGV("LowMemory: %p\n", activity); 434 | android_app_write_cmd(android_app, APP_CMD_LOW_MEMORY); 435 | } 436 | 437 | static void onWindowFocusChanged(ANativeActivity* activity, int focused) { 438 | LOGV("WindowFocusChanged: %p -- %d\n", activity, focused); 439 | android_app_write_cmd((struct android_app*)activity->instance, 440 | focused ? APP_CMD_GAINED_FOCUS : APP_CMD_LOST_FOCUS); 441 | } 442 | 443 | static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) { 444 | LOGV("NativeWindowCreated: %p -- %p\n", activity, window); 445 | android_app_set_window((struct android_app*)activity->instance, window); 446 | } 447 | 448 | static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window) { 449 | LOGV("NativeWindowDestroyed: %p -- %p\n", activity, window); 450 | android_app_set_window((struct android_app*)activity->instance, NULL); 451 | } 452 | 453 | static void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue) { 454 | LOGV("InputQueueCreated: %p -- %p\n", activity, queue); 455 | android_app_set_input((struct android_app*)activity->instance, queue); 456 | } 457 | 458 | static void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue) { 459 | LOGV("InputQueueDestroyed: %p -- %p\n", activity, queue); 460 | android_app_set_input((struct android_app*)activity->instance, NULL); 461 | } 462 | 463 | // Called by ANativeActivity_onCreate which will be exported and will call this function. 464 | // Needed because this symbol will not be globally exported. 465 | void native_app_glue_onCreate(ANativeActivity* activity, void* savedState, 466 | size_t savedStateSize) { 467 | LOGV("Creating: %p\n", activity); 468 | activity->callbacks->onDestroy = onDestroy; 469 | activity->callbacks->onStart = onStart; 470 | activity->callbacks->onResume = onResume; 471 | activity->callbacks->onSaveInstanceState = onSaveInstanceState; 472 | activity->callbacks->onPause = onPause; 473 | activity->callbacks->onStop = onStop; 474 | activity->callbacks->onConfigurationChanged = onConfigurationChanged; 475 | activity->callbacks->onLowMemory = onLowMemory; 476 | activity->callbacks->onWindowFocusChanged = onWindowFocusChanged; 477 | activity->callbacks->onNativeWindowCreated = onNativeWindowCreated; 478 | activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed; 479 | activity->callbacks->onInputQueueCreated = onInputQueueCreated; 480 | activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed; 481 | 482 | activity->instance = android_app_create(activity, savedState, savedStateSize); 483 | } 484 | -------------------------------------------------------------------------------- /cargo-apk/native_app_glue/android_native_app_glue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | * 16 | */ 17 | 18 | #ifndef _ANDROID_NATIVE_APP_GLUE_H 19 | #define _ANDROID_NATIVE_APP_GLUE_H 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | #include 26 | #include 27 | #include 28 | 29 | #ifdef __cplusplus 30 | extern "C" { 31 | #endif 32 | 33 | /** 34 | * The native activity interface provided by 35 | * is based on a set of application-provided callbacks that will be called 36 | * by the Activity's main thread when certain events occur. 37 | * 38 | * This means that each one of this callbacks _should_ _not_ block, or they 39 | * risk having the system force-close the application. This programming 40 | * model is direct, lightweight, but constraining. 41 | * 42 | * The 'android_native_app_glue' static library is used to provide a different 43 | * execution model where the application can implement its own main event 44 | * loop in a different thread instead. Here's how it works: 45 | * 46 | * 1/ The application must provide a function named "android_main()" that 47 | * will be called when the activity is created, in a new thread that is 48 | * distinct from the activity's main thread. 49 | * 50 | * 2/ android_main() receives a pointer to a valid "android_app" structure 51 | * that contains references to other important objects, e.g. the 52 | * ANativeActivity obejct instance the application is running in. 53 | * 54 | * 3/ the "android_app" object holds an ALooper instance that already 55 | * listens to two important things: 56 | * 57 | * - activity lifecycle events (e.g. "pause", "resume"). See APP_CMD_XXX 58 | * declarations below. 59 | * 60 | * - input events coming from the AInputQueue attached to the activity. 61 | * 62 | * Each of these correspond to an ALooper identifier returned by 63 | * ALooper_pollOnce with values of LOOPER_ID_MAIN and LOOPER_ID_INPUT, 64 | * respectively. 65 | * 66 | * Your application can use the same ALooper to listen to additional 67 | * file-descriptors. They can either be callback based, or with return 68 | * identifiers starting with LOOPER_ID_USER. 69 | * 70 | * 4/ Whenever you receive a LOOPER_ID_MAIN or LOOPER_ID_INPUT event, 71 | * the returned data will point to an android_poll_source structure. You 72 | * can call the process() function on it, and fill in android_app->onAppCmd 73 | * and android_app->onInputEvent to be called for your own processing 74 | * of the event. 75 | * 76 | * Alternatively, you can call the low-level functions to read and process 77 | * the data directly... look at the process_cmd() and process_input() 78 | * implementations in the glue to see how to do this. 79 | * 80 | * See the sample named "native-activity" that comes with the NDK with a 81 | * full usage example. Also look at the JavaDoc of NativeActivity. 82 | */ 83 | 84 | struct android_app; 85 | 86 | /** 87 | * Data associated with an ALooper fd that will be returned as the "outData" 88 | * when that source has data ready. 89 | */ 90 | struct android_poll_source { 91 | // The identifier of this source. May be LOOPER_ID_MAIN or 92 | // LOOPER_ID_INPUT. 93 | int32_t id; 94 | 95 | // The android_app this ident is associated with. 96 | struct android_app* app; 97 | 98 | // Function to call to perform the standard processing of data from 99 | // this source. 100 | void (*process)(struct android_app* app, struct android_poll_source* source); 101 | }; 102 | 103 | /** 104 | * This is the interface for the standard glue code of a threaded 105 | * application. In this model, the application's code is running 106 | * in its own thread separate from the main thread of the process. 107 | * It is not required that this thread be associated with the Java 108 | * VM, although it will need to be in order to make JNI calls any 109 | * Java objects. 110 | */ 111 | struct android_app { 112 | // The application can place a pointer to its own state object 113 | // here if it likes. 114 | void* userData; 115 | 116 | // Fill this in with the function to process main app commands (APP_CMD_*) 117 | void (*onAppCmd)(struct android_app* app, int32_t cmd); 118 | 119 | // Fill this in with the function to process input events. At this point 120 | // the event has already been pre-dispatched, and it will be finished upon 121 | // return. Return 1 if you have handled the event, 0 for any default 122 | // dispatching. 123 | int32_t (*onInputEvent)(struct android_app* app, AInputEvent* event); 124 | 125 | // The ANativeActivity object instance that this app is running in. 126 | ANativeActivity* activity; 127 | 128 | // The current configuration the app is running in. 129 | AConfiguration* config; 130 | 131 | // This is the last instance's saved state, as provided at creation time. 132 | // It is NULL if there was no state. You can use this as you need; the 133 | // memory will remain around until you call android_app_exec_cmd() for 134 | // APP_CMD_RESUME, at which point it will be freed and savedState set to NULL. 135 | // These variables should only be changed when processing a APP_CMD_SAVE_STATE, 136 | // at which point they will be initialized to NULL and you can malloc your 137 | // state and place the information here. In that case the memory will be 138 | // freed for you later. 139 | void* savedState; 140 | size_t savedStateSize; 141 | 142 | // The ALooper associated with the app's thread. 143 | ALooper* looper; 144 | 145 | // When non-NULL, this is the input queue from which the app will 146 | // receive user input events. 147 | AInputQueue* inputQueue; 148 | 149 | // When non-NULL, this is the window surface that the app can draw in. 150 | ANativeWindow* window; 151 | 152 | // Current content rectangle of the window; this is the area where the 153 | // window's content should be placed to be seen by the user. 154 | ARect contentRect; 155 | 156 | // Current state of the app's activity. May be either APP_CMD_START, 157 | // APP_CMD_RESUME, APP_CMD_PAUSE, or APP_CMD_STOP; see below. 158 | int activityState; 159 | 160 | // This is non-zero when the application's NativeActivity is being 161 | // destroyed and waiting for the app thread to complete. 162 | int destroyRequested; 163 | 164 | // ------------------------------------------------- 165 | // Below are "private" implementation of the glue code. 166 | 167 | pthread_mutex_t mutex; 168 | pthread_cond_t cond; 169 | 170 | int msgread; 171 | int msgwrite; 172 | 173 | pthread_t thread; 174 | 175 | struct android_poll_source cmdPollSource; 176 | struct android_poll_source inputPollSource; 177 | 178 | int running; 179 | int stateSaved; 180 | int destroyed; 181 | int redrawNeeded; 182 | AInputQueue* pendingInputQueue; 183 | ANativeWindow* pendingWindow; 184 | ARect pendingContentRect; 185 | }; 186 | 187 | enum { 188 | /** 189 | * Looper data ID of commands coming from the app's main thread, which 190 | * is returned as an identifier from ALooper_pollOnce(). The data for this 191 | * identifier is a pointer to an android_poll_source structure. 192 | * These can be retrieved and processed with android_app_read_cmd() 193 | * and android_app_exec_cmd(). 194 | */ 195 | LOOPER_ID_MAIN = 1, 196 | 197 | /** 198 | * Looper data ID of events coming from the AInputQueue of the 199 | * application's window, which is returned as an identifier from 200 | * ALooper_pollOnce(). The data for this identifier is a pointer to an 201 | * android_poll_source structure. These can be read via the inputQueue 202 | * object of android_app. 203 | */ 204 | LOOPER_ID_INPUT = 2, 205 | 206 | /** 207 | * Start of user-defined ALooper identifiers. 208 | */ 209 | LOOPER_ID_USER = 3, 210 | }; 211 | 212 | enum { 213 | /** 214 | * Command from main thread: the AInputQueue has changed. Upon processing 215 | * this command, android_app->inputQueue will be updated to the new queue 216 | * (or NULL). 217 | */ 218 | APP_CMD_INPUT_CHANGED, 219 | 220 | /** 221 | * Command from main thread: a new ANativeWindow is ready for use. Upon 222 | * receiving this command, android_app->window will contain the new window 223 | * surface. 224 | */ 225 | APP_CMD_INIT_WINDOW, 226 | 227 | /** 228 | * Command from main thread: the existing ANativeWindow needs to be 229 | * terminated. Upon receiving this command, android_app->window still 230 | * contains the existing window; after calling android_app_exec_cmd 231 | * it will be set to NULL. 232 | */ 233 | APP_CMD_TERM_WINDOW, 234 | 235 | /** 236 | * Command from main thread: the current ANativeWindow has been resized. 237 | * Please redraw with its new size. 238 | */ 239 | APP_CMD_WINDOW_RESIZED, 240 | 241 | /** 242 | * Command from main thread: the system needs that the current ANativeWindow 243 | * be redrawn. You should redraw the window before handing this to 244 | * android_app_exec_cmd() in order to avoid transient drawing glitches. 245 | */ 246 | APP_CMD_WINDOW_REDRAW_NEEDED, 247 | 248 | /** 249 | * Command from main thread: the content area of the window has changed, 250 | * such as from the soft input window being shown or hidden. You can 251 | * find the new content rect in android_app::contentRect. 252 | */ 253 | APP_CMD_CONTENT_RECT_CHANGED, 254 | 255 | /** 256 | * Command from main thread: the app's activity window has gained 257 | * input focus. 258 | */ 259 | APP_CMD_GAINED_FOCUS, 260 | 261 | /** 262 | * Command from main thread: the app's activity window has lost 263 | * input focus. 264 | */ 265 | APP_CMD_LOST_FOCUS, 266 | 267 | /** 268 | * Command from main thread: the current device configuration has changed. 269 | */ 270 | APP_CMD_CONFIG_CHANGED, 271 | 272 | /** 273 | * Command from main thread: the system is running low on memory. 274 | * Try to reduce your memory use. 275 | */ 276 | APP_CMD_LOW_MEMORY, 277 | 278 | /** 279 | * Command from main thread: the app's activity has been started. 280 | */ 281 | APP_CMD_START, 282 | 283 | /** 284 | * Command from main thread: the app's activity has been resumed. 285 | */ 286 | APP_CMD_RESUME, 287 | 288 | /** 289 | * Command from main thread: the app should generate a new saved state 290 | * for itself, to restore from later if needed. If you have saved state, 291 | * allocate it with malloc and place it in android_app.savedState with 292 | * the size in android_app.savedStateSize. The will be freed for you 293 | * later. 294 | */ 295 | APP_CMD_SAVE_STATE, 296 | 297 | /** 298 | * Command from main thread: the app's activity has been paused. 299 | */ 300 | APP_CMD_PAUSE, 301 | 302 | /** 303 | * Command from main thread: the app's activity has been stopped. 304 | */ 305 | APP_CMD_STOP, 306 | 307 | /** 308 | * Command from main thread: the app's activity is being destroyed, 309 | * and waiting for the app thread to clean up and exit before proceeding. 310 | */ 311 | APP_CMD_DESTROY, 312 | }; 313 | 314 | /** 315 | * Call when ALooper_pollAll() returns LOOPER_ID_MAIN, reading the next 316 | * app command message. 317 | */ 318 | int8_t android_app_read_cmd(struct android_app* android_app); 319 | 320 | /** 321 | * Call with the command returned by android_app_read_cmd() to do the 322 | * initial pre-processing of the given command. You can perform your own 323 | * actions for the command after calling this function. 324 | */ 325 | void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd); 326 | 327 | /** 328 | * Call with the command returned by android_app_read_cmd() to do the 329 | * final post-processing of the given command. You must have done your own 330 | * actions for the command before calling this function. 331 | */ 332 | void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd); 333 | 334 | /** 335 | * Dummy function that used to be used to prevent the linker from stripping app 336 | * glue code. No longer necessary, since __attribute__((visibility("default"))) 337 | * does this for us. 338 | */ 339 | __attribute__(( 340 | deprecated("Calls to app_dummy are no longer necessary. See " 341 | "https://github.com/android-ndk/ndk/issues/381."))) void 342 | app_dummy(); 343 | 344 | /** 345 | * This is the function that application code must implement, representing 346 | * the main entry to the app. 347 | */ 348 | extern void android_main(struct android_app* app); 349 | 350 | struct android_app* ANDROID_APP = NULL; 351 | 352 | #ifdef __cplusplus 353 | } 354 | #endif 355 | 356 | #endif /* _ANDROID_NATIVE_APP_GLUE_H */ 357 | -------------------------------------------------------------------------------- /cargo-apk/src/config.rs: -------------------------------------------------------------------------------- 1 | use cargo::core::{TargetKind, Workspace}; 2 | use cargo::ops; 3 | use cargo::util::CargoResult; 4 | use cargo::CliError; 5 | use failure::format_err; 6 | use itertools::Itertools; 7 | use serde::Deserialize; 8 | use std::collections::btree_map::BTreeMap; 9 | use std::env; 10 | use std::fs; 11 | use std::fs::File; 12 | use std::io::Read; 13 | use std::iter::FromIterator; 14 | use std::path::Path; 15 | use std::path::PathBuf; 16 | use toml; 17 | 18 | #[derive(Clone)] 19 | pub struct AndroidConfig { 20 | /// Name of the cargo package 21 | pub cargo_package_name: String, 22 | 23 | /// Version of the cargo package 24 | pub cargo_package_version: String, 25 | 26 | /// Path to the manifest 27 | pub manifest_path: PathBuf, 28 | /// Path to the root of the Android SDK. 29 | pub sdk_path: PathBuf, 30 | /// Path to the root of the Android NDK. 31 | pub ndk_path: PathBuf, 32 | 33 | /// List of targets to build the app for. Eg. `armv7-linux-androideabi`. 34 | pub build_targets: Vec, 35 | 36 | /// Path to the android.jar for the selected android platform 37 | pub android_jar_path: PathBuf, 38 | 39 | /// Version of android:targetSdkVersion (optional). Default Value = android_version 40 | pub target_sdk_version: u32, 41 | /// Version of android:minSdkVersion (optional). Default Value = android_version 42 | pub min_sdk_version: u32, 43 | 44 | /// Version of the build tools to use 45 | pub build_tools_version: String, 46 | 47 | /// Should we build in release mode? 48 | pub release: bool, 49 | 50 | /// Target configuration settings that are associated with a specific target 51 | default_target_config: TomlAndroidTarget, 52 | 53 | /// Target specific configuration settings 54 | target_configs: BTreeMap<(TargetKind, String), TomlAndroidTarget>, 55 | } 56 | 57 | impl AndroidConfig { 58 | /// Builds the android target config based on the default target config and the specific target configs defined in the manifest 59 | pub fn resolve(&self, target: (TargetKind, String)) -> CargoResult { 60 | let primary_config = self.target_configs.get(&target); 61 | let target_name = target.1; 62 | let is_default_target = target_name == self.cargo_package_name; 63 | let example = target.0 == TargetKind::ExampleBin; 64 | 65 | Ok(AndroidTargetConfig { 66 | package_name: primary_config 67 | .and_then(|a| a.package_name.clone()) 68 | .or_else(|| { 69 | if is_default_target { 70 | self.default_target_config.package_name.clone() 71 | } else { 72 | None 73 | } 74 | }) 75 | .unwrap_or_else(|| { 76 | if example { 77 | format!("rust.{}.example.{}", self.cargo_package_name, target_name) 78 | } else { 79 | format!("rust.{}", target_name) 80 | } 81 | }), 82 | package_label: primary_config 83 | .and_then(|a| a.label.clone()) 84 | .or_else(|| { 85 | if is_default_target { 86 | self.default_target_config.label.clone() 87 | } else { 88 | None 89 | } 90 | }) 91 | .unwrap_or_else(|| target_name.clone()), 92 | version_code: primary_config 93 | .and_then(|a| a.version_code) 94 | .or_else(|| self.default_target_config.version_code) 95 | .unwrap_or(1), 96 | version_name: primary_config 97 | .and_then(|a| a.version_name.clone()) 98 | .or_else(|| self.default_target_config.version_name.clone()) 99 | .unwrap_or_else(|| self.cargo_package_version.clone()), 100 | package_icon: primary_config 101 | .and_then(|a| a.icon.clone()) 102 | .or_else(|| self.default_target_config.icon.clone()), 103 | assets_path: primary_config 104 | .and_then(|a| a.assets.as_ref()) 105 | .or_else(|| self.default_target_config.assets.as_ref()) 106 | .map(|p| self.manifest_path.parent().unwrap().join(p)), 107 | res_path: primary_config 108 | .and_then(|a| a.res.as_ref()) 109 | .or_else(|| self.default_target_config.res.as_ref()) 110 | .map(|p| self.manifest_path.parent().unwrap().join(p)), 111 | fullscreen: primary_config 112 | .and_then(|a| a.fullscreen) 113 | .or_else(|| self.default_target_config.fullscreen) 114 | .unwrap_or(false), 115 | application_attributes: primary_config 116 | .and_then(|a| a.application_attributes.clone()) 117 | .or_else(|| self.default_target_config.application_attributes.clone()) 118 | .map(build_attribute_string), 119 | activity_attributes: primary_config 120 | .and_then(|a| a.activity_attributes.clone()) 121 | .or_else(|| self.default_target_config.activity_attributes.clone()) 122 | .map(build_attribute_string), 123 | opengles_version_major: primary_config 124 | .and_then(|a| a.opengles_version_major) 125 | .or_else(|| self.default_target_config.opengles_version_major) 126 | .unwrap_or(2), 127 | opengles_version_minor: primary_config 128 | .and_then(|a| a.opengles_version_minor) 129 | .or_else(|| self.default_target_config.opengles_version_minor) 130 | .unwrap_or(0), 131 | features: primary_config 132 | .and_then(|a| a.feature.clone()) 133 | .or_else(|| self.default_target_config.feature.clone()) 134 | .unwrap_or_else(Vec::new) 135 | .into_iter() 136 | .map(AndroidFeature::from) 137 | .collect(), 138 | permissions: primary_config 139 | .and_then(|a| a.permission.clone()) 140 | .or_else(|| self.default_target_config.permission.clone()) 141 | .unwrap_or_else(Vec::new) 142 | .into_iter() 143 | .map(AndroidPermission::from) 144 | .collect(), 145 | }) 146 | } 147 | } 148 | 149 | /// Build targets supported by NDK 150 | #[derive(Debug, Copy, Clone, Deserialize)] 151 | pub enum AndroidBuildTarget { 152 | #[serde(rename(deserialize = "armv7-linux-androideabi"))] 153 | ArmV7a, 154 | #[serde(rename(deserialize = "aarch64-linux-android"))] 155 | Arm64V8a, 156 | #[serde(rename(deserialize = "i686-linux-android"))] 157 | X86, 158 | #[serde(rename(deserialize = "x86_64-linux-android"))] 159 | X86_64, 160 | } 161 | 162 | #[derive(Clone)] 163 | pub struct AndroidFeature { 164 | pub name: String, 165 | pub required: bool, 166 | pub version: Option, 167 | } 168 | 169 | impl From for AndroidFeature { 170 | fn from(f: TomlFeature) -> Self { 171 | AndroidFeature { 172 | name: f.name, 173 | required: f.required.unwrap_or(true), 174 | version: f.version, 175 | } 176 | } 177 | } 178 | 179 | #[derive(Clone)] 180 | pub struct AndroidPermission { 181 | pub name: String, 182 | pub max_sdk_version: Option, 183 | } 184 | 185 | impl From for AndroidPermission { 186 | fn from(p: TomlPermission) -> Self { 187 | AndroidPermission { 188 | name: p.name, 189 | max_sdk_version: p.max_sdk_version, 190 | } 191 | } 192 | } 193 | 194 | /// Android build settings for a specific target 195 | pub struct AndroidTargetConfig { 196 | /// Name that the package will have on the Android machine. 197 | /// This is the key that Android uses to identify your package, so it should be unique for 198 | /// for each application and should contain the vendor's name. 199 | pub package_name: String, 200 | 201 | /// Label for the package. 202 | pub package_label: String, 203 | 204 | /// Internal version number for manifest. 205 | pub version_code: i32, 206 | 207 | /// Version number which is shown to users. 208 | pub version_name: String, 209 | 210 | /// Name of the launcher icon. 211 | /// Versions of this icon with different resolutions have to reside in the res folder 212 | pub package_icon: Option, 213 | 214 | /// If `Some`, a path that contains the list of assets to ship as part of the package. 215 | /// 216 | /// The assets can later be loaded with the runtime library. 217 | pub assets_path: Option, 218 | 219 | /// If `Some`, a path that contains the list of resources to ship as part of the package. 220 | /// 221 | /// The resources can later be loaded with the runtime library. 222 | /// This folder contains for example the launcher icon, the styles and resolution dependent images. 223 | pub res_path: Option, 224 | 225 | /// Should this app be in fullscreen mode (hides the title bar)? 226 | pub fullscreen: bool, 227 | 228 | /// Appends this string to the application attributes in the AndroidManifest.xml 229 | pub application_attributes: Option, 230 | 231 | /// Appends this string to the activity attributes in the AndroidManifest.xml 232 | pub activity_attributes: Option, 233 | 234 | /// The OpenGL ES major version in the AndroidManifest.xml 235 | pub opengles_version_major: u8, 236 | 237 | /// The OpenGL ES minor version in the AndroidManifest.xml 238 | pub opengles_version_minor: u8, 239 | 240 | /// uses-feature in AndroidManifest.xml 241 | pub features: Vec, 242 | 243 | /// uses-permission in AndroidManifest.xml 244 | pub permissions: Vec, 245 | } 246 | 247 | pub fn load( 248 | workspace: &Workspace, 249 | flag_package: &Option, 250 | ) -> Result { 251 | // Find out the package requested by the user. 252 | let package = { 253 | let packages = Vec::from_iter(flag_package.iter().cloned()); 254 | let spec = ops::Packages::Packages(packages); 255 | 256 | match spec { 257 | ops::Packages::Default => unreachable!("cargo apk supports single package only"), 258 | ops::Packages::All => unreachable!("cargo apk supports single package only"), 259 | ops::Packages::OptOut(_) => unreachable!("cargo apk supports single package only"), 260 | ops::Packages::Packages(xs) => match xs.len() { 261 | 0 => workspace.current()?, 262 | 1 => workspace 263 | .members() 264 | .find(|pkg| *pkg.name() == xs[0]) 265 | .ok_or_else(|| { 266 | format_err!("package `{}` is not a member of the workspace", xs[0]) 267 | })?, 268 | _ => unreachable!("cargo apk supports single package only"), 269 | }, 270 | } 271 | }; 272 | 273 | // Determine the name of the package and the Android-specific metadata from the Cargo.toml 274 | let manifest_content = { 275 | // Load Cargo.toml & parse 276 | let content = { 277 | let mut file = File::open(package.manifest_path()).unwrap(); 278 | let mut content = String::new(); 279 | file.read_to_string(&mut content).unwrap(); 280 | content 281 | }; 282 | let config: TomlConfig = toml::from_str(&content).map_err(failure::Error::from)?; 283 | config.package.metadata.and_then(|m| m.android) 284 | }; 285 | 286 | // Determine the NDK path 287 | let ndk_path = env::var("NDK_HOME").map_err(|_| { 288 | format_err!( 289 | "Please set the path to the Android NDK with the \ 290 | $NDK_HOME environment variable." 291 | ) 292 | })?; 293 | 294 | let sdk_path = { 295 | let mut sdk_path = env::var("ANDROID_SDK_HOME").ok(); 296 | 297 | if sdk_path.is_none() { 298 | sdk_path = env::var("ANDROID_HOME").ok(); 299 | } 300 | 301 | sdk_path.ok_or_else(|| { 302 | format_err!( 303 | "Please set the path to the Android SDK with either the $ANDROID_SDK_HOME or \ 304 | the $ANDROID_HOME environment variable." 305 | ) 306 | })? 307 | }; 308 | 309 | // Find the highest build tools. 310 | let build_tools_version = { 311 | let dir = fs::read_dir(Path::new(&sdk_path).join("build-tools")) 312 | .map_err(|_| format_err!("Android SDK has no build-tools directory"))?; 313 | 314 | let mut versions = Vec::new(); 315 | for next in dir { 316 | let next = next.unwrap(); 317 | 318 | let meta = next.metadata().unwrap(); 319 | if !meta.is_dir() { 320 | if !meta.is_file() { 321 | // It seems, symlink is here, so we should follow it 322 | let meta = next.path().metadata().unwrap(); 323 | 324 | if !meta.is_dir() { 325 | continue; 326 | } 327 | } else { 328 | continue; 329 | } 330 | } 331 | 332 | let file_name = next.file_name().into_string().unwrap(); 333 | if !file_name.chars().next().unwrap().is_digit(10) { 334 | continue; 335 | } 336 | 337 | versions.push(file_name); 338 | } 339 | 340 | versions.sort_by(|a, b| b.cmp(&a)); 341 | versions 342 | .into_iter() 343 | .next() 344 | .ok_or_else(|| format_err!("Unable to determine build tools version"))? 345 | }; 346 | 347 | // Determine the Sdk versions (compile, target, min) 348 | let android_version = manifest_content 349 | .as_ref() 350 | .and_then(|a| a.android_version) 351 | .unwrap_or(29); 352 | 353 | // Check that the tool for the android platform is installed 354 | let android_jar_path = Path::new(&sdk_path) 355 | .join("platforms") 356 | .join(format!("android-{}", android_version)) 357 | .join("android.jar"); 358 | if !android_jar_path.exists() { 359 | Err(format_err!( 360 | "'{}' does not exist", 361 | android_jar_path.to_string_lossy() 362 | ))?; 363 | } 364 | 365 | let target_sdk_version = manifest_content 366 | .as_ref() 367 | .and_then(|a| a.target_sdk_version) 368 | .unwrap_or(android_version); 369 | let min_sdk_version = manifest_content 370 | .as_ref() 371 | .and_then(|a| a.min_sdk_version) 372 | .unwrap_or(18); 373 | 374 | let default_target_config = manifest_content 375 | .as_ref() 376 | .map(|a| a.default_target_config.clone()) 377 | .unwrap_or_else(Default::default); 378 | 379 | let mut target_configs = BTreeMap::new(); 380 | manifest_content 381 | .as_ref() 382 | .and_then(|a| a.bin.as_ref()) 383 | .unwrap_or(&Vec::new()) 384 | .iter() 385 | .for_each(|t| { 386 | target_configs.insert((TargetKind::Bin, t.name.clone()), t.config.clone()); 387 | }); 388 | manifest_content 389 | .as_ref() 390 | .and_then(|a| a.example.as_ref()) 391 | .unwrap_or(&Vec::new()) 392 | .iter() 393 | .for_each(|t| { 394 | target_configs.insert((TargetKind::ExampleBin, t.name.clone()), t.config.clone()); 395 | }); 396 | 397 | // For the moment some fields of the config are dummies. 398 | Ok(AndroidConfig { 399 | cargo_package_name: package.name().to_string(), 400 | cargo_package_version: package.version().to_string(), 401 | manifest_path: package.manifest_path().to_owned(), 402 | sdk_path: Path::new(&sdk_path).to_owned(), 403 | ndk_path: Path::new(&ndk_path).to_owned(), 404 | android_jar_path, 405 | target_sdk_version, 406 | min_sdk_version, 407 | build_tools_version, 408 | release: false, 409 | build_targets: manifest_content 410 | .as_ref() 411 | .and_then(|a| a.build_targets.clone()) 412 | .unwrap_or_else(|| { 413 | vec![ 414 | AndroidBuildTarget::ArmV7a, 415 | AndroidBuildTarget::Arm64V8a, 416 | AndroidBuildTarget::X86, 417 | ] 418 | }), 419 | default_target_config, 420 | target_configs, 421 | }) 422 | } 423 | 424 | fn build_attribute_string(input_map: BTreeMap) -> String { 425 | input_map 426 | .iter() 427 | .map(|(key, val)| format!("\n{}=\"{}\"", key, val)) 428 | .join("") 429 | } 430 | 431 | #[derive(Debug, Clone, Deserialize)] 432 | struct TomlConfig { 433 | package: TomlPackage, 434 | } 435 | 436 | #[derive(Debug, Clone, Deserialize)] 437 | struct TomlPackage { 438 | name: String, 439 | metadata: Option, 440 | } 441 | 442 | #[derive(Debug, Clone, Deserialize)] 443 | struct TomlMetadata { 444 | android: Option, 445 | } 446 | 447 | #[derive(Debug, Clone, Deserialize)] 448 | #[serde(deny_unknown_fields)] 449 | struct TomlAndroid { 450 | android_version: Option, 451 | target_sdk_version: Option, 452 | min_sdk_version: Option, 453 | build_targets: Option>, 454 | 455 | #[serde(flatten)] 456 | default_target_config: TomlAndroidTarget, 457 | 458 | bin: Option>, 459 | example: Option>, 460 | } 461 | 462 | #[derive(Debug, Clone, Deserialize)] 463 | #[serde(deny_unknown_fields)] 464 | struct TomlFeature { 465 | name: String, 466 | required: Option, 467 | version: Option, 468 | } 469 | 470 | #[derive(Debug, Clone, Deserialize)] 471 | #[serde(deny_unknown_fields)] 472 | struct TomlPermission { 473 | name: String, 474 | max_sdk_version: Option, 475 | } 476 | 477 | /// Configuration specific to a single cargo target 478 | #[derive(Debug, Clone, Deserialize)] 479 | #[serde(deny_unknown_fields)] 480 | struct TomlAndroidSpecificTarget { 481 | name: String, 482 | 483 | #[serde(flatten)] 484 | config: TomlAndroidTarget, 485 | } 486 | 487 | #[derive(Debug, Default, Clone, Deserialize)] 488 | struct TomlAndroidTarget { 489 | package_name: Option, 490 | label: Option, 491 | version_code: Option, 492 | version_name: Option, 493 | icon: Option, 494 | assets: Option, 495 | res: Option, 496 | fullscreen: Option, 497 | application_attributes: Option>, 498 | activity_attributes: Option>, 499 | opengles_version_major: Option, 500 | opengles_version_minor: Option, 501 | feature: Option>, 502 | permission: Option>, 503 | } 504 | -------------------------------------------------------------------------------- /cargo-apk/src/main.rs: -------------------------------------------------------------------------------- 1 | use cargo::core::Workspace; 2 | use cargo::util::process_builder::process; 3 | use cargo::util::Config as CargoConfig; 4 | use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; 5 | use failure::format_err; 6 | 7 | use cargo::util::command_prelude::opt; 8 | use cargo::util::command_prelude::AppExt; 9 | use cargo::util::command_prelude::ArgMatchesExt; 10 | 11 | mod config; 12 | mod ops; 13 | 14 | fn main() { 15 | let mut cargo_config = CargoConfig::default().unwrap(); 16 | 17 | let args = match cli().get_matches_safe() { 18 | Ok(args) => args, 19 | Err(err) => cargo::exit_with_error(err.into(), &mut *cargo_config.shell()), 20 | }; 21 | 22 | let args = match args.subcommand() { 23 | ("apk", Some(subcommand_matches)) => subcommand_matches, 24 | _ => &args, 25 | }; 26 | 27 | let (command, subcommand_args) = match args.subcommand() { 28 | (command, Some(subcommand_args)) => (command, subcommand_args), 29 | _ => { 30 | drop(cli().print_help()); 31 | return; 32 | } 33 | }; 34 | 35 | let arg_target_dir = &subcommand_args.value_of_path("target-dir", &cargo_config); 36 | 37 | cargo_config 38 | .configure( 39 | args.occurrences_of("verbose") as u32, 40 | if args.is_present("quiet") { 41 | Some(true) 42 | } else { 43 | None 44 | }, 45 | &args.value_of("color").map(|s| s.to_string()), 46 | args.is_present("frozen"), 47 | args.is_present("locked"), 48 | args.is_present("offline"), 49 | arg_target_dir, 50 | &args 51 | .values_of_lossy("unstable-features") 52 | .unwrap_or_default(), 53 | ) 54 | .unwrap(); 55 | 56 | let err = match command { 57 | "build" => execute_build(&subcommand_args, &cargo_config), 58 | "install" => execute_install(&subcommand_args, &cargo_config), 59 | "run" => execute_run(&subcommand_args, &cargo_config), 60 | "logcat" => execute_logcat(&subcommand_args, &cargo_config), 61 | _ => cargo::exit_with_error( 62 | format_err!( 63 | "Expected `build`, `install`, `run`, or `logcat`. Got {}", 64 | command 65 | ) 66 | .into(), 67 | &mut *cargo_config.shell(), 68 | ), 69 | }; 70 | 71 | match err { 72 | Ok(_) => (), 73 | Err(err) => cargo::exit_with_error(err, &mut *cargo_config.shell()), 74 | } 75 | } 76 | 77 | fn cli() -> App<'static, 'static> { 78 | App::new("cargo-apk") 79 | .settings(&[ 80 | AppSettings::UnifiedHelpMessage, 81 | AppSettings::DeriveDisplayOrder, 82 | AppSettings::VersionlessSubcommands, 83 | AppSettings::AllowExternalSubcommands, 84 | ]) 85 | .arg( 86 | opt( 87 | "verbose", 88 | "Use verbose output (-vv very verbose/build.rs output)", 89 | ) 90 | .short("v") 91 | .multiple(true) 92 | .global(true), 93 | ) 94 | .arg(opt("quiet", "No output printed to stdout").short("q")) 95 | .arg( 96 | opt("color", "Coloring: auto, always, never") 97 | .value_name("WHEN") 98 | .global(true), 99 | ) 100 | .arg(opt("frozen", "Require Cargo.lock and cache are up to date").global(true)) 101 | .arg(opt("locked", "Require Cargo.lock is up to date").global(true)) 102 | .arg(opt("offline", "Run without accessing the network").global(true)) 103 | .arg( 104 | Arg::with_name("unstable-features") 105 | .help("Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details") 106 | .short("Z") 107 | .value_name("FLAG") 108 | .multiple(true) 109 | .number_of_values(1) 110 | .global(true), 111 | ) 112 | .subcommands(vec![ 113 | cli_apk(), 114 | cli_build(), 115 | cli_install(), 116 | cli_run(), 117 | cli_logcat(), 118 | ]) 119 | } 120 | 121 | fn cli_apk() -> App<'static, 'static> { 122 | SubCommand::with_name("apk") 123 | .settings(&[ 124 | AppSettings::UnifiedHelpMessage, 125 | AppSettings::DeriveDisplayOrder, 126 | AppSettings::DontCollapseArgsInUsage, 127 | ]) 128 | .about("dummy subcommand to allow for calling cargo apk instead of cargo-apk") 129 | .subcommands(vec![cli_build(), cli_install(), cli_run(), cli_logcat()]) 130 | } 131 | 132 | fn cli_build() -> App<'static, 'static> { 133 | SubCommand::with_name("build") 134 | .settings(&[ 135 | AppSettings::UnifiedHelpMessage, 136 | AppSettings::DeriveDisplayOrder, 137 | AppSettings::DontCollapseArgsInUsage, 138 | ]) 139 | .alias("b") 140 | .about("Compile a local package and all of its dependencies") 141 | .arg_package_spec( 142 | "Package to build (see `cargo help pkgid`)", 143 | "Build all packages in the workspace", 144 | "Exclude packages from the build", 145 | ) 146 | .arg_jobs() 147 | .arg_targets_all( 148 | "Build only this package's library", 149 | "Build only the specified binary", 150 | "Build all binaries", 151 | "Build only the specified example", 152 | "Build all examples", 153 | "Build only the specified test target", 154 | "Build all tests", 155 | "Build only the specified bench target", 156 | "Build all benches", 157 | "Build all targets", 158 | ) 159 | .arg_release("Build artifacts in release mode, with optimizations") 160 | .arg_features() 161 | .arg_target_triple("Build for the target triple") 162 | .arg_target_dir() 163 | .arg(opt("out-dir", "Copy final artifacts to this directory").value_name("PATH")) 164 | .arg_manifest_path() 165 | .arg_message_format() 166 | .arg_build_plan() 167 | .after_help( 168 | "\ 169 | All packages in the workspace are built if the `--all` flag is supplied. The 170 | `--all` flag is automatically assumed for a virtual manifest. 171 | Note that `--exclude` has to be specified in conjunction with the `--all` flag. 172 | 173 | Compilation can be configured via the use of profiles which are configured in 174 | the manifest. The default profile for this command is `dev`, but passing 175 | the --release flag will use the `release` profile instead. 176 | ", 177 | ) 178 | } 179 | 180 | fn cli_install() -> App<'static, 'static> { 181 | SubCommand::with_name("install") 182 | .settings(&[ 183 | AppSettings::UnifiedHelpMessage, 184 | AppSettings::DeriveDisplayOrder, 185 | AppSettings::DontCollapseArgsInUsage, 186 | ]) 187 | .about("Install a Rust binary") 188 | .arg(Arg::with_name("crate").empty_values(false).multiple(true)) 189 | .arg( 190 | opt("version", "Specify a version to install from crates.io") 191 | .alias("vers") 192 | .value_name("VERSION"), 193 | ) 194 | .arg(opt("git", "Git URL to install the specified crate from").value_name("URL")) 195 | .arg(opt("branch", "Branch to use when installing from git").value_name("BRANCH")) 196 | .arg(opt("tag", "Tag to use when installing from git").value_name("TAG")) 197 | .arg(opt("rev", "Specific commit to use when installing from git").value_name("SHA")) 198 | .arg(opt("path", "Filesystem path to local crate to install").value_name("PATH")) 199 | .arg(opt( 200 | "list", 201 | "list all installed packages and their versions", 202 | )) 203 | .arg_jobs() 204 | .arg(opt("force", "Force overwriting existing crates or binaries").short("f")) 205 | .arg_features() 206 | .arg(opt("debug", "Build in debug mode instead of release mode")) 207 | .arg_targets_bins_examples( 208 | "Install only the specified binary", 209 | "Install all binaries", 210 | "Install only the specified example", 211 | "Install all examples", 212 | ) 213 | .arg_target_triple("Build for the target triple") 214 | .arg(opt("root", "Directory to install packages into").value_name("DIR")) 215 | .arg(opt("registry", "Registry to use").value_name("REGISTRY")) 216 | .after_help( 217 | "\ 218 | This command manages Cargo's local set of installed binary crates. Only packages 219 | which have [[bin]] targets can be installed, and all binaries are installed into 220 | the installation root's `bin` folder. The installation root is determined, in 221 | order of precedence, by `--root`, `$CARGO_INSTALL_ROOT`, the `install.root` 222 | configuration key, and finally the home directory (which is either 223 | `$CARGO_HOME` if set or `$HOME/.cargo` by default). 224 | 225 | There are multiple sources from which a crate can be installed. The default 226 | location is crates.io but the `--git` and `--path` flags can change this source. 227 | If the source contains more than one package (such as crates.io or a git 228 | repository with multiple crates) the `` argument is required to indicate 229 | which crate should be installed. 230 | 231 | Crates from crates.io can optionally specify the version they wish to install 232 | via the `--vers` flags, and similarly packages from git repositories can 233 | optionally specify the branch, tag, or revision that should be installed. If a 234 | crate has multiple binaries, the `--bin` argument can selectively install only 235 | one of them, and if you'd rather install examples the `--example` argument can 236 | be used as well. 237 | 238 | By default cargo will refuse to overwrite existing binaries. The `--force` flag 239 | enables overwriting existing binaries. Thus you can reinstall a crate with 240 | `cargo install --force `. 241 | 242 | Omitting the specification entirely will 243 | install the crate in the current directory. That is, `install` is equivalent to 244 | the more explicit `install --path .`. This behaviour is deprecated, and no 245 | longer supported as of the Rust 2018 edition. 246 | 247 | If the source is crates.io or `--git` then by default the crate will be built 248 | in a temporary target directory. To avoid this, the target directory can be 249 | specified by setting the `CARGO_TARGET_DIR` environment variable to a relative 250 | path. In particular, this can be useful for caching build artifacts on 251 | continuous integration systems.", 252 | ) 253 | } 254 | 255 | fn cli_run() -> App<'static, 'static> { 256 | SubCommand::with_name("run") 257 | .settings(&[ 258 | AppSettings::UnifiedHelpMessage, 259 | AppSettings::DeriveDisplayOrder, 260 | AppSettings::DontCollapseArgsInUsage, 261 | ]) 262 | .alias("r") 263 | .setting(AppSettings::TrailingVarArg) 264 | .about("Run the main binary of the local package (src/main.rs)") 265 | .arg(Arg::with_name("args").multiple(true)) 266 | .arg_targets_bin_example( 267 | "Name of the bin target to run", 268 | "Name of the example target to run", 269 | ) 270 | .arg_package("Package with the target to run") 271 | .arg_jobs() 272 | .arg_release("Build artifacts in release mode, with optimizations") 273 | .arg_features() 274 | .arg_target_triple("Build for the target triple") 275 | .arg_target_dir() 276 | .arg_manifest_path() 277 | .arg_message_format() 278 | .after_help( 279 | "\ 280 | If neither `--bin` nor `--example` are given, then if the package only has one 281 | bin target it will be run. Otherwise `--bin` specifies the bin target to run, 282 | and `--example` specifies the example target to run. At most one of `--bin` or 283 | `--example` can be provided. 284 | 285 | All the arguments following the two dashes (`--`) are passed to the binary to 286 | run. If you're passing arguments to both Cargo and the binary, the ones after 287 | `--` go to the binary, the ones before go to Cargo. 288 | ", 289 | ) 290 | } 291 | 292 | fn cli_logcat() -> App<'static, 'static> { 293 | SubCommand::with_name("logcat") 294 | .settings(&[ 295 | AppSettings::UnifiedHelpMessage, 296 | AppSettings::DeriveDisplayOrder, 297 | AppSettings::DontCollapseArgsInUsage, 298 | ]) 299 | .alias("r") 300 | .about("Print Android log") 301 | .arg_message_format() 302 | } 303 | 304 | pub fn execute_build(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult { 305 | let root_manifest = options.root_manifest(&cargo_config)?; 306 | 307 | let workspace = Workspace::new(&root_manifest, &cargo_config)?; 308 | 309 | let mut android_config = config::load( 310 | &workspace, 311 | &options.value_of("package").map(|s| s.to_owned()), 312 | )?; 313 | android_config.release = options.is_present("release"); 314 | 315 | ops::build(&workspace, &android_config, &options)?; 316 | Ok(()) 317 | } 318 | 319 | pub fn execute_install(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult { 320 | let root_manifest = options.root_manifest(&cargo_config)?; 321 | 322 | let workspace = Workspace::new(&root_manifest, &cargo_config)?; 323 | 324 | let mut android_config = config::load( 325 | &workspace, 326 | &options.value_of("package").map(|s| s.to_owned()), 327 | )?; 328 | android_config.release = !options.is_present("debug"); 329 | 330 | ops::install(&workspace, &android_config, &options)?; 331 | Ok(()) 332 | } 333 | 334 | pub fn execute_run(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult { 335 | let root_manifest = options.root_manifest(&cargo_config)?; 336 | 337 | let workspace = Workspace::new(&root_manifest, &cargo_config)?; 338 | 339 | let mut android_config = config::load( 340 | &workspace, 341 | &options.value_of("package").map(|s| s.to_owned()), 342 | )?; 343 | android_config.release = options.is_present("release"); 344 | 345 | ops::run(&workspace, &android_config, &options)?; 346 | Ok(()) 347 | } 348 | 349 | pub fn execute_logcat(options: &ArgMatches, cargo_config: &CargoConfig) -> cargo::CliResult { 350 | let root_manifest = options.root_manifest(&cargo_config)?; 351 | 352 | let workspace = Workspace::new(&root_manifest, &cargo_config)?; 353 | 354 | let android_config = config::load( 355 | &workspace, 356 | &options.value_of("package").map(|s| s.to_owned()), 357 | )?; 358 | 359 | drop(writeln!( 360 | workspace.config().shell().err(), 361 | "Starting logcat" 362 | )); 363 | let adb = android_config.sdk_path.join("platform-tools/adb"); 364 | process(&adb).arg("logcat").exec()?; 365 | 366 | Ok(()) 367 | } 368 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/build.rs: -------------------------------------------------------------------------------- 1 | mod compile; 2 | mod targets; 3 | pub mod tempfile; 4 | mod util; 5 | 6 | use self::compile::SharedLibraries; 7 | use crate::config::{AndroidConfig, AndroidTargetConfig}; 8 | use cargo::core::{Target, TargetKind, Workspace}; 9 | use cargo::util::process_builder::process; 10 | use cargo::util::CargoResult; 11 | use clap::ArgMatches; 12 | use failure::format_err; 13 | use std::collections::BTreeMap; 14 | use std::fs::File; 15 | use std::io::Write; 16 | use std::path::Path; 17 | use std::path::PathBuf; 18 | use std::{env, fs}; 19 | 20 | #[derive(Debug)] 21 | pub struct BuildResult { 22 | /// Mapping from target kind and target name to the built APK 23 | pub target_to_apk_map: BTreeMap<(TargetKind, String), PathBuf>, 24 | } 25 | 26 | pub fn build( 27 | workspace: &Workspace, 28 | config: &AndroidConfig, 29 | options: &ArgMatches, 30 | ) -> CargoResult { 31 | let root_build_dir = util::get_root_build_directory(workspace, config); 32 | let shared_libraries = 33 | compile::build_shared_libraries(workspace, config, options, &root_build_dir)?; 34 | build_apks(config, &root_build_dir, shared_libraries) 35 | } 36 | 37 | fn build_apks( 38 | config: &AndroidConfig, 39 | root_build_dir: &PathBuf, 40 | shared_libraries: SharedLibraries, 41 | ) -> CargoResult { 42 | // Create directory to hold final APKs which are signed using the debug key 43 | let final_apk_dir = root_build_dir.join("apk"); 44 | fs::create_dir_all(&final_apk_dir)?; 45 | 46 | // Paths of created APKs 47 | let mut target_to_apk_map = BTreeMap::new(); 48 | 49 | // Build an APK for each cargo target 50 | for (target, shared_libraries) in shared_libraries.shared_libraries.iter_all() { 51 | let target_directory = util::get_target_directory(root_build_dir, target)?; 52 | fs::create_dir_all(&target_directory)?; 53 | 54 | // Determine Target Configuration 55 | let target_config = config.resolve((target.kind().to_owned(), target.name().to_owned()))?; 56 | 57 | // 58 | // Run commands to produce APK 59 | // 60 | build_manifest(&target_directory, &config, &target_config, &target)?; 61 | 62 | let build_tools_path = config 63 | .sdk_path 64 | .join("build-tools") 65 | .join(&config.build_tools_version); 66 | let aapt_path = build_tools_path.join("aapt"); 67 | let zipalign_path = build_tools_path.join("zipalign"); 68 | 69 | // Create unaligned APK which includes resources and assets 70 | let unaligned_apk_name = format!("{}_unaligned.apk", target.name()); 71 | let unaligned_apk_path = target_directory.join(&unaligned_apk_name); 72 | if unaligned_apk_path.exists() { 73 | std::fs::remove_file(unaligned_apk_path) 74 | .map_err(|e| format_err!("Unable to delete APK file. {}", e))?; 75 | } 76 | 77 | let mut aapt_package_cmd = process(&aapt_path); 78 | aapt_package_cmd 79 | .arg("package") 80 | .arg("-F") 81 | .arg(&unaligned_apk_name) 82 | .arg("-M") 83 | .arg("AndroidManifest.xml") 84 | .arg("-I") 85 | .arg(&config.android_jar_path); 86 | 87 | if let Some(res_path) = target_config.res_path { 88 | aapt_package_cmd.arg("-S").arg(res_path); 89 | } 90 | 91 | // Link assets 92 | if let Some(assets_path) = &target_config.assets_path { 93 | aapt_package_cmd.arg("-A").arg(assets_path); 94 | } 95 | 96 | aapt_package_cmd.cwd(&target_directory).exec()?; 97 | 98 | // Add shared libraries to the APK 99 | for shared_library in shared_libraries { 100 | // Copy the shared library to the appropriate location in the target directory and with the appropriate name 101 | // Note: that the type of slash used matters. This path is passed to aapt and the shared library 102 | // will not load if backslashes are used. 103 | let so_path = format!( 104 | "lib/{}/{}", 105 | &shared_library.abi.android_abi(), 106 | shared_library.filename 107 | ); 108 | 109 | let target_shared_object_path = target_directory.join(&so_path); 110 | fs::create_dir_all(target_shared_object_path.parent().unwrap())?; 111 | fs::copy(&shared_library.path, target_shared_object_path)?; 112 | 113 | // Add to the APK 114 | process(&aapt_path) 115 | .arg("add") 116 | .arg(&unaligned_apk_name) 117 | .arg(so_path) 118 | .cwd(&target_directory) 119 | .exec()?; 120 | } 121 | 122 | // Determine the directory in which to place the aligned and signed APK 123 | let target_apk_directory = match target.kind() { 124 | TargetKind::Bin => final_apk_dir.clone(), 125 | TargetKind::ExampleBin => final_apk_dir.join("examples"), 126 | _ => unreachable!("Unexpected target kind"), 127 | }; 128 | fs::create_dir_all(&target_apk_directory)?; 129 | 130 | // Align apk 131 | let final_apk_path = target_apk_directory.join(format!("{}.apk", target.name())); 132 | process(&zipalign_path) 133 | .arg("-f") 134 | .arg("-v") 135 | .arg("4") 136 | .arg(&unaligned_apk_name) 137 | .arg(&final_apk_path) 138 | .cwd(&target_directory) 139 | .exec()?; 140 | 141 | // Find or generate a debug keystore for signing the APK 142 | // We use the same debug keystore as used by the Android SDK. If it does not exist, 143 | // then we create it using keytool which is part of the JRE/JDK 144 | let android_directory = dirs::home_dir() 145 | .ok_or_else(|| format_err!("Unable to determine home directory"))? 146 | .join(".android"); 147 | fs::create_dir_all(&android_directory)?; 148 | let keystore_path = android_directory.join("debug.keystore"); 149 | if !keystore_path.exists() { 150 | // Generate key 151 | let keytool_filename = if cfg!(target_os = "windows") { 152 | "keytool.exe" 153 | } else { 154 | "keytool" 155 | }; 156 | 157 | let keytool_path = find_java_executable(keytool_filename)?; 158 | process(keytool_path) 159 | .arg("-genkey") 160 | .arg("-v") 161 | .arg("-keystore") 162 | .arg(&keystore_path) 163 | .arg("-storepass") 164 | .arg("android") 165 | .arg("-alias") 166 | .arg("androidebugkey") 167 | .arg("-keypass") 168 | .arg("android") 169 | .arg("-dname") 170 | .arg("CN=Android Debug,O=Android,C=US") 171 | .arg("-keyalg") 172 | .arg("RSA") 173 | .arg("-keysize") 174 | .arg("2048") 175 | .arg("-validity") 176 | .arg("10000") 177 | .cwd(root_build_dir) 178 | .exec()?; 179 | } 180 | 181 | // Sign the APK with the development certificate 182 | util::script_process( 183 | build_tools_path.join(format!("apksigner{}", util::EXECUTABLE_SUFFIX_BAT)), 184 | ) 185 | .arg("sign") 186 | .arg("--ks") 187 | .arg(keystore_path) 188 | .arg("--ks-pass") 189 | .arg("pass:android") 190 | .arg(&final_apk_path) 191 | .cwd(&target_directory) 192 | .exec()?; 193 | 194 | target_to_apk_map.insert( 195 | (target.kind().to_owned(), target.name().to_owned()), 196 | final_apk_path, 197 | ); 198 | } 199 | 200 | Ok(BuildResult { target_to_apk_map }) 201 | } 202 | 203 | /// Find an executable that is part of the Java SDK 204 | fn find_java_executable(name: &str) -> CargoResult { 205 | // Look in PATH 206 | env::var_os("PATH") 207 | .and_then(|paths| { 208 | env::split_paths(&paths) 209 | .filter_map(|path| { 210 | let filepath = path.join(name); 211 | if fs::metadata(&filepath).is_ok() { 212 | Some(filepath) 213 | } else { 214 | None 215 | } 216 | }) 217 | .next() 218 | }) 219 | .or_else(|| 220 | // Look in JAVA_HOME 221 | env::var_os("JAVA_HOME").and_then(|java_home| { 222 | let filepath = PathBuf::from(java_home).join("bin").join(name); 223 | if filepath.exists() { 224 | Some(filepath) 225 | } else { 226 | None 227 | } 228 | })) 229 | .ok_or_else(|| { 230 | format_err!( 231 | "Unable to find executable: '{}'. Configure PATH or JAVA_HOME with the path to the JRE or JDK.", 232 | name 233 | ) 234 | }) 235 | } 236 | 237 | fn build_manifest( 238 | path: &Path, 239 | config: &AndroidConfig, 240 | target_config: &AndroidTargetConfig, 241 | target: &Target, 242 | ) -> CargoResult<()> { 243 | let file = path.join("AndroidManifest.xml"); 244 | let mut file = File::create(&file)?; 245 | 246 | // Building application attributes 247 | let application_attrs = format!( 248 | r#" 249 | android:hasCode="false" android:label="{0}"{1}{2}{3}"#, 250 | target_config.package_label, 251 | target_config 252 | .package_icon 253 | .as_ref() 254 | .map_or(String::new(), |a| format!( 255 | r#" 256 | android:icon="{}""#, 257 | a 258 | )), 259 | if target_config.fullscreen { 260 | r#" 261 | android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen""# 262 | } else { 263 | "" 264 | }, 265 | target_config 266 | .application_attributes 267 | .as_ref() 268 | .map_or(String::new(), |a| a.replace("\n", "\n ")) 269 | ); 270 | 271 | // Build activity attributes 272 | let activity_attrs = format!( 273 | r#" 274 | android:name="android.app.NativeActivity" 275 | android:label="{0}" 276 | android:configChanges="orientation|keyboardHidden|screenSize" {1}"#, 277 | target_config.package_label, 278 | target_config 279 | .activity_attributes 280 | .as_ref() 281 | .map_or(String::new(), |a| a.replace("\n", "\n ")) 282 | ); 283 | 284 | let uses_features = target_config 285 | .features 286 | .iter() 287 | .map(|f| { 288 | format!( 289 | "\n\t", 290 | f.name, 291 | f.required, 292 | f.version 293 | .as_ref() 294 | .map_or(String::new(), |v| format!(r#"android:version="{}""#, v)) 295 | ) 296 | }) 297 | .collect::>() 298 | .join(", "); 299 | 300 | let uses_permissions = target_config 301 | .permissions 302 | .iter() 303 | .map(|f| { 304 | format!( 305 | "\n\t", 306 | f.name, 307 | max_sdk_version = f.max_sdk_version.map_or(String::new(), |v| format!( 308 | r#"android:maxSdkVersion="{}""#, 309 | v 310 | )) 311 | ) 312 | }) 313 | .collect::>() 314 | .join(", "); 315 | 316 | // Write final AndroidManifest 317 | writeln!( 318 | file, 319 | r#" 320 | 324 | 325 | {uses_features}{uses_permissions} 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | "#, 336 | package = target_config.package_name.replace("-", "_"), 337 | version_code = target_config.version_code, 338 | version_name = target_config.version_name, 339 | targetSdkVersion = config.target_sdk_version, 340 | minSdkVersion = config.min_sdk_version, 341 | glEsVersion = format!( 342 | "0x{:04}{:04}", 343 | target_config.opengles_version_major, target_config.opengles_version_minor 344 | ), 345 | uses_features = uses_features, 346 | uses_permissions = uses_permissions, 347 | application_attrs = application_attrs, 348 | activity_attrs = activity_attrs, 349 | target_name = target.name(), 350 | )?; 351 | 352 | Ok(()) 353 | } 354 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/build/compile.rs: -------------------------------------------------------------------------------- 1 | use super::tempfile::TempFile; 2 | use super::util; 3 | use crate::config::AndroidBuildTarget; 4 | use crate::config::AndroidConfig; 5 | use cargo::core::compiler::Executor; 6 | use cargo::core::compiler::{CompileKind, CompileMode, CompileTarget}; 7 | use cargo::core::manifest::TargetSourcePath; 8 | use cargo::core::{PackageId, Target, TargetKind, Workspace}; 9 | use cargo::util::command_prelude::{ArgMatchesExt, ProfileChecking}; 10 | use cargo::util::{process, CargoResult, ProcessBuilder, dylib_path}; 11 | use clap::ArgMatches; 12 | use failure::format_err; 13 | use multimap::MultiMap; 14 | use std::ffi::{OsStr, OsString}; 15 | use std::fs; 16 | use std::fs::File; 17 | use std::io::Write; 18 | use std::path::Path; 19 | use std::path::PathBuf; 20 | use std::sync::{Arc, Mutex}; 21 | use std::collections::{HashSet, HashMap}; 22 | 23 | pub struct SharedLibrary { 24 | pub abi: AndroidBuildTarget, 25 | pub path: PathBuf, 26 | pub filename: String, 27 | } 28 | 29 | pub struct SharedLibraries { 30 | pub shared_libraries: MultiMap, 31 | } 32 | 33 | /// For each build target and cargo binary or example target, produce a shared library 34 | pub fn build_shared_libraries( 35 | workspace: &Workspace, 36 | config: &AndroidConfig, 37 | options: &ArgMatches, 38 | root_build_dir: &PathBuf, 39 | ) -> CargoResult { 40 | let android_native_glue_src_path = write_native_app_glue_src(&root_build_dir)?; 41 | 42 | let shared_libraries: Arc>> = 43 | Arc::new(Mutex::new(MultiMap::new())); 44 | for &build_target in config.build_targets.iter() { 45 | // Directory that will contain files specific to this build target 46 | let build_target_dir = root_build_dir.join(build_target.android_abi()); 47 | fs::create_dir_all(&build_target_dir).unwrap(); 48 | 49 | // Set environment variables needed for use with the cc crate 50 | std::env::set_var("CC", util::find_clang(config, build_target)?); 51 | std::env::set_var("CXX", util::find_clang_cpp(config, build_target)?); 52 | std::env::set_var("AR", util::find_ar(config, build_target)?); 53 | 54 | // Use libc++. It is current default C++ runtime 55 | std::env::set_var("CXXSTDLIB", "c++"); 56 | 57 | // Generate cmake toolchain and set environment variables to allow projects which use the cmake crate to build correctly 58 | let cmake_toolchain_path = write_cmake_toolchain(config, &build_target_dir, build_target)?; 59 | std::env::set_var("CMAKE_TOOLCHAIN_FILE", cmake_toolchain_path); 60 | std::env::set_var("CMAKE_GENERATOR", r#"Unix Makefiles"#); 61 | std::env::set_var("CMAKE_MAKE_PROGRAM", util::make_path(config)); 62 | 63 | // Build android_native_glue 64 | let android_native_glue_object = build_android_native_glue( 65 | config, 66 | &android_native_glue_src_path, 67 | &build_target_dir, 68 | build_target, 69 | )?; 70 | 71 | // Configure compilation options so that we will build the desired build_target 72 | let mut opts = options.compile_options( 73 | workspace.config(), 74 | CompileMode::Build, 75 | Some(&workspace), 76 | ProfileChecking::Unchecked, 77 | )?; 78 | opts.build_config.requested_kind = 79 | CompileKind::Target(CompileTarget::new(build_target.rust_triple())?); 80 | 81 | // Create executor 82 | let config = Arc::new(config.clone()); 83 | let executor: Arc = Arc::new(SharedLibraryExecutor { 84 | config: Arc::clone(&config), 85 | build_target_dir: build_target_dir.clone(), 86 | android_native_glue_object, 87 | build_target, 88 | shared_libraries: shared_libraries.clone(), 89 | }); 90 | 91 | // Compile all targets for the requested build target 92 | cargo::ops::compile_with_exec(workspace, &opts, &executor)?; 93 | } 94 | 95 | // Remove the set of targets from the reference counted mutex 96 | let mut shared_libraries = shared_libraries.lock().unwrap(); 97 | let shared_libraries = std::mem::replace(&mut *shared_libraries, MultiMap::new()); 98 | 99 | Ok(SharedLibraries { shared_libraries }) 100 | } 101 | 102 | /// Executor which builds binary and example targets as static libraries 103 | struct SharedLibraryExecutor { 104 | config: Arc, 105 | build_target_dir: PathBuf, 106 | android_native_glue_object: PathBuf, 107 | build_target: AndroidBuildTarget, 108 | 109 | // Shared libraries built by the executor are added to this multimap 110 | shared_libraries: Arc>>, 111 | } 112 | 113 | impl Executor for SharedLibraryExecutor { 114 | fn exec( 115 | &self, 116 | cmd: ProcessBuilder, 117 | _id: PackageId, 118 | target: &Target, 119 | mode: CompileMode, 120 | on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>, 121 | on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>, 122 | ) -> CargoResult<()> { 123 | if mode == CompileMode::Build 124 | && (target.kind() == &TargetKind::Bin || target.kind() == &TargetKind::ExampleBin) 125 | { 126 | let mut new_args = cmd.get_args().to_owned(); 127 | 128 | // 129 | // Determine source path 130 | // 131 | let path = if let TargetSourcePath::Path(path) = target.src_path() { 132 | path.to_owned() 133 | } else { 134 | // Ignore other values 135 | return Ok(()); 136 | }; 137 | 138 | let original_src_filepath = path.canonicalize()?; 139 | 140 | // 141 | // Generate source file that will be built 142 | // 143 | // Determine the name of the temporary file 144 | let tmp_lib_filepath = original_src_filepath.parent().unwrap().join(format!( 145 | "__cargo_apk_{}.tmp", 146 | original_src_filepath 147 | .file_stem() 148 | .map(|s| s.to_string_lossy().into_owned()) 149 | .unwrap_or_else(String::new) 150 | )); 151 | 152 | // Create the temporary file 153 | let original_contents = fs::read_to_string(original_src_filepath).unwrap(); 154 | let tmp_file = TempFile::new(tmp_lib_filepath.clone(), |lib_src_file| { 155 | let extra_code = r##" 156 | mod cargo_apk_glue_code { 157 | use std::os::raw::c_void; 158 | 159 | // Exported function which is called be Android's NativeActivity 160 | #[no_mangle] 161 | pub unsafe extern "C" fn ANativeActivity_onCreate( 162 | activity: *mut c_void, 163 | saved_state: *mut c_void, 164 | saved_state_size: usize, 165 | ) { 166 | native_app_glue_onCreate(activity, saved_state, saved_state_size); 167 | } 168 | 169 | extern "C" { 170 | #[allow(non_snake_case)] 171 | fn native_app_glue_onCreate( 172 | activity: *mut c_void, 173 | saved_state: *mut c_void, 174 | saved_state_size: usize, 175 | ); 176 | } 177 | 178 | #[no_mangle] 179 | extern "C" fn android_main(_app: *mut c_void) { 180 | let _ = super::main(); 181 | } 182 | 183 | #[link(name = "android")] 184 | #[link(name = "log")] 185 | extern "C" {} 186 | }"##; 187 | writeln!( lib_src_file, "{}\n{}", original_contents, extra_code)?; 188 | 189 | Ok(()) 190 | }).map_err(|e| format_err!( 191 | "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) 192 | )?; 193 | 194 | // 195 | // Replace source argument 196 | // 197 | let filename = path.file_name().unwrap().to_owned(); 198 | let source_arg = new_args.iter_mut().find_map(|arg| { 199 | let path_arg = Path::new(&arg); 200 | let tmp = path_arg.file_name().unwrap(); 201 | 202 | if filename == tmp { 203 | Some(arg) 204 | } else { 205 | None 206 | } 207 | }); 208 | 209 | if let Some(source_arg) = source_arg { 210 | // Build a new relative path to the temporary source file and use it as the source argument 211 | // Using an absolute path causes compatibility issues in some cases under windows 212 | // If a UNC path is used then relative paths used in "include* macros" may not work if 213 | // the relative path includes "/" instead of "\" 214 | let path_arg = Path::new(&source_arg); 215 | let mut path_arg = path_arg.to_path_buf(); 216 | path_arg.set_file_name(tmp_file.path.file_name().unwrap()); 217 | *source_arg = path_arg.into_os_string(); 218 | } else { 219 | return Err(format_err!( 220 | "Unable to replace source argument when building target '{}'", 221 | target.name() 222 | )); 223 | } 224 | 225 | // 226 | // Create output directory inside the build target directory 227 | // 228 | let build_path = self.build_target_dir.join("build"); 229 | fs::create_dir_all(&build_path).unwrap(); 230 | 231 | // 232 | // Change crate-type from bin to cdylib 233 | // Replace output directory with the directory we created 234 | // 235 | let mut iter = new_args.iter_mut().rev().peekable(); 236 | while let Some(arg) = iter.next() { 237 | if let Some(prev_arg) = iter.peek() { 238 | if *prev_arg == "--crate-type" && arg == "bin" { 239 | *arg = "cdylib".into(); 240 | } else if *prev_arg == "--out-dir" { 241 | *arg = build_path.clone().into(); 242 | } 243 | } 244 | } 245 | 246 | // Helper function to build arguments composed of concatenating two strings 247 | fn build_arg(start: &str, end: impl AsRef) -> OsString { 248 | let mut new_arg = OsString::new(); 249 | new_arg.push(start); 250 | new_arg.push(end.as_ref()); 251 | new_arg 252 | } 253 | 254 | // Determine paths 255 | let tool_root = util::llvm_toolchain_root(&self.config); 256 | let linker_path = tool_root 257 | .join("bin") 258 | .join(format!("{}-ld", &self.build_target.ndk_triple())); 259 | let sysroot = tool_root.join("sysroot"); 260 | let version_independent_libraries_path = sysroot 261 | .join("usr") 262 | .join("lib") 263 | .join(&self.build_target.ndk_triple()); 264 | let version_specific_libraries_path = 265 | util::find_ndk_path(self.config.min_sdk_version, |platform| { 266 | version_independent_libraries_path.join(platform.to_string()) 267 | })?; 268 | let gcc_lib_path = tool_root 269 | .join("lib/gcc") 270 | .join(&self.build_target.ndk_triple()) 271 | .join("4.9.x"); 272 | 273 | // Add linker arguments 274 | // Specify linker 275 | new_args.push(build_arg("-Clinker=", linker_path)); 276 | 277 | // Set linker flavor 278 | new_args.push("-Clinker-flavor=ld".into()); 279 | 280 | // Set system root 281 | new_args.push(build_arg("-Clink-arg=--sysroot=", sysroot)); 282 | 283 | // Add version specific libraries directory to search path 284 | new_args.push(build_arg("-Clink-arg=-L", &version_specific_libraries_path)); 285 | 286 | // Add version independent libraries directory to search path 287 | new_args.push(build_arg( 288 | "-Clink-arg=-L", 289 | &version_independent_libraries_path, 290 | )); 291 | 292 | // Add path to folder containing libgcc.a to search path 293 | new_args.push(build_arg("-Clink-arg=-L", gcc_lib_path)); 294 | 295 | // Add android native glue 296 | new_args.push(build_arg("-Clink-arg=", &self.android_native_glue_object)); 297 | 298 | // Strip symbols for release builds 299 | if self.config.release { 300 | new_args.push("-Clink-arg=-strip-all".into()); 301 | } 302 | 303 | // Require position independent code 304 | new_args.push("-Crelocation-model=pic".into()); 305 | 306 | // Create new command 307 | let mut cmd = cmd.clone(); 308 | cmd.args_replace(&new_args); 309 | 310 | // 311 | // Execute the command 312 | // 313 | cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false) 314 | .map(drop)?; 315 | 316 | // 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 317 | let stdout = cmd.arg("--print").arg("file-names").exec_with_output()?; 318 | let stdout = String::from_utf8(stdout.stdout).unwrap(); 319 | let library_path = build_path.join(stdout.lines().next().unwrap()); 320 | 321 | let mut shared_libraries = self.shared_libraries.lock().unwrap(); 322 | shared_libraries.insert( 323 | target.clone(), 324 | SharedLibrary { 325 | abi: self.build_target, 326 | path: library_path.clone(), 327 | filename: format!("lib{}.so", target.name()), 328 | }, 329 | ); 330 | 331 | // If the target uses the C++ standard library, add the appropriate shared library 332 | // to the list of shared libraries to be added to the APK 333 | let readelf_path = util::find_readelf(&self.config, self.build_target)?; 334 | 335 | // Gets libraries search paths from compiler 336 | let mut libs_search_paths = libs_search_paths_from_args(cmd.get_args()); 337 | 338 | // Add path for searching version independent libraries like 'libc++_shared.so' 339 | libs_search_paths.push(version_independent_libraries_path); 340 | 341 | // Add target/ARCH/PROFILE/deps directory for searching dylib/cdylib 342 | libs_search_paths.push(self.build_target_dir.join("deps")); 343 | 344 | // FIXME: Add extra libraries search paths (from "LD_LIBRARY_PATH") 345 | libs_search_paths.extend(dylib_path()); 346 | 347 | // Find android platform shared libraries 348 | let android_dylibs = list_android_dylibs(&version_specific_libraries_path)?; 349 | 350 | // The map of [library]: is_processed 351 | let mut found_dylibs = 352 | // Add android platform libraries as processed to avoid packaging it 353 | android_dylibs.into_iter().map(|dylib| (dylib, true)) 354 | .collect::>(); 355 | 356 | // Extract all needed shared libraries from main 357 | for dylib in list_needed_dylibs(&readelf_path, &library_path)? { 358 | // Insert new libraries only 359 | found_dylibs.entry(dylib).or_insert(false); 360 | } 361 | 362 | while let Some(dylib) = found_dylibs.iter() 363 | .find(|(_, is_processed)| !*is_processed) 364 | .map(|(dylib, _)| dylib.clone()) 365 | { 366 | // Mark library as processed 367 | *found_dylibs.get_mut(&dylib).unwrap() = true; 368 | 369 | // Find library in known path 370 | if let Some(path) = find_library_path(&libs_search_paths, &dylib) { 371 | // Extract all needed shared libraries recursively 372 | for dylib in list_needed_dylibs(&readelf_path, &path)? { 373 | // Insert new libraries only 374 | found_dylibs.entry(dylib).or_insert(false); 375 | } 376 | 377 | // Add found library 378 | shared_libraries.insert( 379 | target.clone(), 380 | SharedLibrary { 381 | abi: self.build_target, 382 | path, 383 | filename: dylib.clone(), 384 | }, 385 | ); 386 | } else { 387 | on_stderr_line(&format!("Warning: Shared library \"{}\" not found.", &dylib))?; 388 | } 389 | } 390 | } else if mode == CompileMode::Test { 391 | // This occurs when --all-targets is specified 392 | eprintln!("Ignoring CompileMode::Test for target: {}", target.name()); 393 | } else if mode == CompileMode::Build { 394 | let mut new_args = cmd.get_args().to_owned(); 395 | 396 | // 397 | // Change crate-type from cdylib to rlib 398 | // 399 | let mut iter = new_args.iter_mut().rev().peekable(); 400 | while let Some(arg) = iter.next() { 401 | if let Some(prev_arg) = iter.peek() { 402 | if *prev_arg == "--crate-type" && arg == "cdylib" { 403 | *arg = "rlib".into(); 404 | } 405 | } 406 | } 407 | 408 | let mut cmd = cmd.clone(); 409 | cmd.args_replace(&new_args); 410 | cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false) 411 | .map(drop)? 412 | } else { 413 | cmd.exec_with_streaming(on_stdout_line, on_stderr_line, false) 414 | .map(drop)? 415 | } 416 | 417 | Ok(()) 418 | } 419 | } 420 | 421 | /// List all linked shared libraries 422 | fn list_needed_dylibs(readelf_path: &Path, library_path: &Path) -> CargoResult> { 423 | let readelf_output = process(readelf_path) 424 | .arg("-d") 425 | .arg(&library_path) 426 | .exec_with_output()?; 427 | use std::io::BufRead; 428 | Ok(readelf_output.stdout.lines().filter_map(|l| { 429 | let l = l.as_ref().unwrap(); 430 | if l.contains("(NEEDED)") { 431 | if let Some(lib) = l.split("Shared library: [").last() { 432 | if let Some(lib) = lib.split("]").next() { 433 | return Some(lib.into()); 434 | } 435 | } 436 | } 437 | None 438 | }).collect()) 439 | } 440 | 441 | /// List Android shared libraries 442 | fn list_android_dylibs(version_specific_libraries_path: &Path) -> CargoResult> { 443 | fs::read_dir(version_specific_libraries_path)? 444 | .filter_map(|entry| { 445 | entry.map(|entry| { 446 | if entry.path().is_file() { 447 | if let Some(file_name) = entry.file_name().to_str() { 448 | if file_name.ends_with(".so") { 449 | return Some(file_name.into()); 450 | } 451 | } 452 | } 453 | None 454 | }).transpose() 455 | }) 456 | .collect::>() 457 | .map_err(|err| err.into()) 458 | } 459 | 460 | /// Get native library search paths from rustc args 461 | fn libs_search_paths_from_args(args: &[std::ffi::OsString]) -> Vec { 462 | let mut is_search_path = false; 463 | args.iter().filter_map(|arg| { 464 | if is_search_path { 465 | is_search_path = false; 466 | arg.to_str().and_then(|arg| if arg.starts_with("native=") || arg.starts_with("dependency=") { 467 | Some(arg.split("=").last().unwrap().into()) 468 | } else { 469 | None 470 | }) 471 | } else { 472 | if arg == "-L" { 473 | is_search_path = true; 474 | } 475 | None 476 | } 477 | }).collect() 478 | } 479 | 480 | /// Resolves native library using search paths 481 | fn find_library_path>(paths: &Vec, library: S) -> Option { 482 | paths.iter().filter_map(|path| { 483 | let lib_path = path.join(&library); 484 | if lib_path.is_file() { 485 | Some(lib_path) 486 | } else { 487 | None 488 | } 489 | }).nth(0) 490 | } 491 | 492 | /// Returns the path to the ".c" file for the android native app glue 493 | fn write_native_app_glue_src(android_artifacts_dir: &Path) -> CargoResult { 494 | let output_dir = android_artifacts_dir.join("native_app_glue"); 495 | fs::create_dir_all(&output_dir).unwrap(); 496 | 497 | let mut h_file = File::create(output_dir.join("android_native_app_glue.h"))?; 498 | h_file.write_all(&include_bytes!("../../../native_app_glue/android_native_app_glue.h")[..])?; 499 | 500 | let c_path = output_dir.join("android_native_app_glue.c"); 501 | let mut c_file = File::create(&c_path)?; 502 | c_file.write_all(&include_bytes!("../../../native_app_glue/android_native_app_glue.c")[..])?; 503 | 504 | Ok(c_path) 505 | } 506 | 507 | /// Returns the path to the built object file for the android native glue 508 | fn build_android_native_glue( 509 | config: &AndroidConfig, 510 | android_native_glue_src_path: &PathBuf, 511 | build_target_dir: &PathBuf, 512 | build_target: AndroidBuildTarget, 513 | ) -> CargoResult { 514 | let clang = util::find_clang(config, build_target)?; 515 | 516 | let android_native_glue_build_path = build_target_dir.join("android_native_glue"); 517 | fs::create_dir_all(&android_native_glue_build_path)?; 518 | let android_native_glue_object_path = 519 | android_native_glue_build_path.join("android_native_glue.o"); 520 | 521 | // Will produce warnings when bulding on linux? Create constants for extensions that can be used.. Or have separate functions? 522 | util::script_process(clang) 523 | .arg(android_native_glue_src_path) 524 | .arg("-c") 525 | .arg("-o") 526 | .arg(&android_native_glue_object_path) 527 | .exec()?; 528 | 529 | Ok(android_native_glue_object_path) 530 | } 531 | 532 | /// Write a CMake toolchain which will remove references to the rustc build target before including 533 | /// the NDK provided toolchain. The NDK provided android toolchain will set the target appropriately 534 | /// Returns the path to the generated toolchain file 535 | fn write_cmake_toolchain( 536 | config: &AndroidConfig, 537 | build_target_dir: &PathBuf, 538 | build_target: AndroidBuildTarget, 539 | ) -> CargoResult { 540 | let toolchain_path = build_target_dir.join("cargo-apk.toolchain.cmake"); 541 | let mut toolchain_file = File::create(&toolchain_path).unwrap(); 542 | writeln!( 543 | toolchain_file, 544 | r#"set(ANDROID_PLATFORM android-{min_sdk_version}) 545 | set(ANDROID_ABI {abi}) 546 | string(REPLACE "--target={build_target}" "" CMAKE_C_FLAGS "${{CMAKE_C_FLAGS}}") 547 | string(REPLACE "--target={build_target}" "" CMAKE_CXX_FLAGS "${{CMAKE_CXX_FLAGS}}") 548 | unset(CMAKE_C_COMPILER CACHE) 549 | unset(CMAKE_CXX_COMPILER CACHE) 550 | include("{ndk_path}/build/cmake/android.toolchain.cmake")"#, 551 | min_sdk_version = config.min_sdk_version, 552 | ndk_path = config.ndk_path.to_string_lossy().replace("\\", "/"), // Use forward slashes even on windows to avoid path escaping issues. 553 | build_target = build_target.rust_triple(), 554 | abi = build_target.android_abi(), 555 | )?; 556 | 557 | Ok(toolchain_path) 558 | } 559 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/build/targets.rs: -------------------------------------------------------------------------------- 1 | use crate::config::AndroidBuildTarget; 2 | 3 | impl AndroidBuildTarget { 4 | /// Identifier used in the NDK to refer to the ABI 5 | pub fn android_abi(self) -> &'static str { 6 | match self { 7 | AndroidBuildTarget::ArmV7a => "armeabi-v7a", 8 | AndroidBuildTarget::Arm64V8a => "arm64-v8a", 9 | AndroidBuildTarget::X86 => "x86", 10 | AndroidBuildTarget::X86_64 => "x86_64", 11 | } 12 | } 13 | 14 | /// Returns the triple used by the rust build tools 15 | pub fn rust_triple(self) -> &'static str { 16 | match self { 17 | AndroidBuildTarget::ArmV7a => "armv7-linux-androideabi", 18 | AndroidBuildTarget::Arm64V8a => "aarch64-linux-android", 19 | AndroidBuildTarget::X86 => "i686-linux-android", 20 | AndroidBuildTarget::X86_64 => "x86_64-linux-android", 21 | } 22 | } 23 | 24 | // Returns the triple NDK provided LLVM 25 | pub fn ndk_llvm_triple(self) -> &'static str { 26 | match self { 27 | AndroidBuildTarget::ArmV7a => "armv7a-linux-androideabi", 28 | AndroidBuildTarget::Arm64V8a => "aarch64-linux-android", 29 | AndroidBuildTarget::X86 => "i686-linux-android", 30 | AndroidBuildTarget::X86_64 => "x86_64-linux-android", 31 | } 32 | } 33 | 34 | /// Returns the triple used by the non-LLVM parts of the NDK 35 | pub fn ndk_triple(self) -> &'static str { 36 | match self { 37 | AndroidBuildTarget::ArmV7a => "arm-linux-androideabi", 38 | AndroidBuildTarget::Arm64V8a => "aarch64-linux-android", 39 | AndroidBuildTarget::X86 => "i686-linux-android", 40 | AndroidBuildTarget::X86_64 => "x86_64-linux-android", 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/build/tempfile.rs: -------------------------------------------------------------------------------- 1 | use cargo::util::CargoResult; 2 | use std::fs::{self, File}; 3 | use std::path::PathBuf; 4 | 5 | /// Temporary file implementation that allows creating a file with a specified path which 6 | /// will be deleted when dropped. 7 | pub struct TempFile { 8 | pub path: PathBuf, 9 | } 10 | 11 | impl TempFile { 12 | /// Create a new `TempFile` using the contents provided by a closure. 13 | /// If the file already exists, it will be overwritten and then deleted when the instance 14 | /// is dropped. 15 | pub fn new(path: PathBuf, write_contents: F) -> CargoResult 16 | where 17 | F: FnOnce(&mut File) -> CargoResult<()>, 18 | { 19 | let tmp_file = TempFile { path }; 20 | 21 | // Write the contents to the the temp file 22 | let mut file = File::create(&tmp_file.path)?; 23 | write_contents(&mut file)?; 24 | 25 | Ok(tmp_file) 26 | } 27 | } 28 | 29 | impl Drop for TempFile { 30 | fn drop(&mut self) { 31 | fs::remove_file(&self.path).unwrap_or_else(|e| { 32 | eprintln!( 33 | "Unable to remove temporary file: {}. {}", 34 | &self.path.to_string_lossy(), 35 | &e 36 | ); 37 | }) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/build/util.rs: -------------------------------------------------------------------------------- 1 | use crate::config::{AndroidBuildTarget, AndroidConfig}; 2 | use cargo::core::{Target, TargetKind, Workspace}; 3 | use cargo::util::{process, CargoResult, ProcessBuilder}; 4 | use failure::format_err; 5 | use std::ffi::OsStr; 6 | use std::path::PathBuf; 7 | 8 | /// Returns the directory in which all cargo apk artifacts for the current 9 | /// debug/release configuration should be produced. 10 | pub fn get_root_build_directory(workspace: &Workspace, config: &AndroidConfig) -> PathBuf { 11 | let android_artifacts_dir = workspace 12 | .target_dir() 13 | .join("android-artifacts") 14 | .into_path_unlocked(); 15 | 16 | if config.release { 17 | android_artifacts_dir.join("release") 18 | } else { 19 | android_artifacts_dir.join("debug") 20 | } 21 | } 22 | 23 | /// Returns the sub directory within the root build directory for the specified target. 24 | pub fn get_target_directory(root_build_dir: &PathBuf, target: &Target) -> CargoResult { 25 | let target_directory = match target.kind() { 26 | TargetKind::Bin => root_build_dir.join("bin"), 27 | TargetKind::ExampleBin => root_build_dir.join("examples"), 28 | _ => unreachable!("Unexpected target kind"), 29 | }; 30 | 31 | let target_directory = target_directory.join(target.name()); 32 | Ok(target_directory) 33 | } 34 | 35 | /// Returns path to NDK provided make 36 | pub fn make_path(config: &AndroidConfig) -> PathBuf { 37 | config.ndk_path.join("prebuild").join(HOST_TAG).join("make") 38 | } 39 | 40 | /// Returns the path to the LLVM toolchain provided by the NDK 41 | pub fn llvm_toolchain_root(config: &AndroidConfig) -> PathBuf { 42 | config 43 | .ndk_path 44 | .join("toolchains") 45 | .join("llvm") 46 | .join("prebuilt") 47 | .join(HOST_TAG) 48 | } 49 | 50 | // Helper function for looking for a path based on the platform version 51 | // Calls a closure for each attempt and then return the PathBuf for the first file that exists. 52 | // Uses approach that NDK build tools use which is described at: 53 | // https://developer.android.com/ndk/guides/application_mk 54 | // " - The platform version matching APP_PLATFORM. 55 | // - The next available API level below APP_PLATFORM. For example, android-19 will be used when 56 | // APP_PLATFORM is android-20, since there were no new native APIs in android-20. 57 | // - The minimum API level supported by the NDK." 58 | pub fn find_ndk_path(platform: u32, path_builder: F) -> CargoResult 59 | where 60 | F: Fn(u32) -> PathBuf, 61 | { 62 | let mut tmp_platform = platform; 63 | 64 | // Look for the file which matches the specified platform 65 | // If that doesn't exist, look for a lower version 66 | while tmp_platform > 1 { 67 | let path = path_builder(tmp_platform); 68 | if path.exists() { 69 | return Ok(path); 70 | } 71 | 72 | tmp_platform -= 1; 73 | } 74 | 75 | // If that doesn't exist... Look for a higher one. This would be the minimum API level supported by the NDK 76 | tmp_platform = platform; 77 | while tmp_platform < 100 { 78 | let path = path_builder(tmp_platform); 79 | if path.exists() { 80 | return Ok(path); 81 | } 82 | 83 | tmp_platform += 1; 84 | } 85 | 86 | Err(format_err!("Unable to find NDK file")) 87 | } 88 | 89 | // Returns path to clang executable/script that should be used to build the target 90 | pub fn find_clang( 91 | config: &AndroidConfig, 92 | build_target: AndroidBuildTarget, 93 | ) -> CargoResult { 94 | let bin_folder = llvm_toolchain_root(config).join("bin"); 95 | find_ndk_path(config.min_sdk_version, |platform| { 96 | bin_folder.join(format!( 97 | "{}{}-clang{}", 98 | build_target.ndk_llvm_triple(), 99 | platform, 100 | EXECUTABLE_SUFFIX_CMD 101 | )) 102 | }) 103 | .map_err(|_| format_err!("Unable to find NDK clang")) 104 | } 105 | 106 | // Returns path to clang++ executable/script that should be used to build the target 107 | pub fn find_clang_cpp( 108 | config: &AndroidConfig, 109 | build_target: AndroidBuildTarget, 110 | ) -> CargoResult { 111 | let bin_folder = llvm_toolchain_root(config).join("bin"); 112 | find_ndk_path(config.min_sdk_version, |platform| { 113 | bin_folder.join(format!( 114 | "{}{}-clang++{}", 115 | build_target.ndk_llvm_triple(), 116 | platform, 117 | EXECUTABLE_SUFFIX_CMD 118 | )) 119 | }) 120 | .map_err(|_| format_err!("Unable to find NDK clang++")) 121 | } 122 | 123 | // Returns path to ar. 124 | pub fn find_ar(config: &AndroidConfig, build_target: AndroidBuildTarget) -> CargoResult { 125 | let ar_path = llvm_toolchain_root(config).join("bin").join(format!( 126 | "{}-ar{}", 127 | build_target.ndk_triple(), 128 | EXECUTABLE_SUFFIX_EXE 129 | )); 130 | if ar_path.exists() { 131 | Ok(ar_path) 132 | } else { 133 | Err(format_err!( 134 | "Unable to find ar at `{}`", 135 | ar_path.to_string_lossy() 136 | )) 137 | } 138 | } 139 | 140 | // Returns path to readelf 141 | pub fn find_readelf( 142 | config: &AndroidConfig, 143 | build_target: AndroidBuildTarget, 144 | ) -> CargoResult { 145 | let readelf_path = llvm_toolchain_root(config).join("bin").join(format!( 146 | "{}-readelf{}", 147 | build_target.ndk_triple(), 148 | EXECUTABLE_SUFFIX_EXE 149 | )); 150 | if readelf_path.exists() { 151 | Ok(readelf_path) 152 | } else { 153 | Err(format_err!( 154 | "Unable to find readelf at `{}`", 155 | readelf_path.to_string_lossy() 156 | )) 157 | } 158 | } 159 | 160 | /// Returns a ProcessBuilder which runs the specified command. Uses "cmd" on windows in order to 161 | /// allow execution of batch files. 162 | pub fn script_process(cmd: impl AsRef) -> ProcessBuilder { 163 | if cfg!(target_os = "windows") { 164 | let mut pb = process("cmd"); 165 | pb.arg("/C").arg(cmd); 166 | pb 167 | } else { 168 | process(cmd) 169 | } 170 | } 171 | 172 | #[cfg(all(target_os = "windows", target_pointer_width = "64"))] 173 | const HOST_TAG: &str = "windows-x86_64"; 174 | 175 | #[cfg(all(target_os = "windows", target_pointer_width = "32"))] 176 | const HOST_TAG: &str = "windows"; 177 | 178 | #[cfg(target_os = "linux")] 179 | const HOST_TAG: &str = "linux-x86_64"; 180 | 181 | #[cfg(target_os = "macos")] 182 | const HOST_TAG: &str = "darwin-x86_64"; 183 | 184 | // These are executable suffixes used to simplify building commands. 185 | // On non-windows platforms they are empty. 186 | 187 | #[cfg(target_os = "windows")] 188 | const EXECUTABLE_SUFFIX_EXE: &str = ".exe"; 189 | 190 | #[cfg(not(target_os = "windows"))] 191 | const EXECUTABLE_SUFFIX_EXE: &str = ""; 192 | 193 | #[cfg(target_os = "windows")] 194 | const EXECUTABLE_SUFFIX_CMD: &str = ".cmd"; 195 | 196 | #[cfg(not(target_os = "windows"))] 197 | const EXECUTABLE_SUFFIX_CMD: &str = ""; 198 | 199 | #[cfg(target_os = "windows")] 200 | pub const EXECUTABLE_SUFFIX_BAT: &str = ".bat"; 201 | 202 | #[cfg(not(target_os = "windows"))] 203 | pub const EXECUTABLE_SUFFIX_BAT: &str = ""; 204 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/install.rs: -------------------------------------------------------------------------------- 1 | use super::BuildResult; 2 | use crate::config::AndroidConfig; 3 | use crate::ops::build; 4 | use cargo::core::Workspace; 5 | use cargo::util::process_builder::process; 6 | use cargo::util::CargoResult; 7 | use clap::ArgMatches; 8 | 9 | pub fn install( 10 | workspace: &Workspace, 11 | config: &AndroidConfig, 12 | options: &ArgMatches, 13 | ) -> CargoResult { 14 | let build_result = build::build(workspace, config, options)?; 15 | 16 | let adb = config.sdk_path.join("platform-tools/adb"); 17 | 18 | for apk_path in build_result.target_to_apk_map.values() { 19 | drop(writeln!( 20 | workspace.config().shell().err(), 21 | "Installing apk '{}' to the device", 22 | apk_path.file_name().unwrap().to_string_lossy() 23 | )); 24 | 25 | process(&adb) 26 | .arg("install") 27 | .arg("-r") 28 | .arg(apk_path) 29 | .exec()?; 30 | } 31 | 32 | Ok(build_result) 33 | } 34 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/mod.rs: -------------------------------------------------------------------------------- 1 | mod build; 2 | mod install; 3 | mod run; 4 | 5 | pub use self::build::build; 6 | pub use self::build::BuildResult; 7 | pub use self::install::install; 8 | pub use self::run::run; 9 | -------------------------------------------------------------------------------- /cargo-apk/src/ops/run.rs: -------------------------------------------------------------------------------- 1 | use crate::config::AndroidConfig; 2 | use crate::ops::install; 3 | use cargo::core::{TargetKind, Workspace}; 4 | use cargo::util::process_builder::process; 5 | use cargo::util::CargoResult; 6 | use clap::ArgMatches; 7 | use failure::format_err; 8 | 9 | pub fn run(workspace: &Workspace, config: &AndroidConfig, options: &ArgMatches) -> CargoResult<()> { 10 | let build_result = install::install(workspace, config, options)?; 11 | 12 | // Determine the target that should be executed 13 | let requested_target = if options.is_present("example") && options.is_present("bin") { 14 | return Err(format_err!( 15 | "Specifying both example and bin targets is not supported" 16 | )); 17 | } else if let Some(bin) = options.value_of("bin") { 18 | (TargetKind::Bin, bin.to_owned()) 19 | } else if let Some(example) = options.value_of("example") { 20 | (TargetKind::ExampleBin, example.to_owned()) 21 | } else { 22 | match build_result.target_to_apk_map.len() { 23 | 1 => build_result 24 | .target_to_apk_map 25 | .keys() 26 | .next() 27 | .unwrap() 28 | .to_owned(), 29 | 0 => return Err(format_err!("No APKs to execute.")), 30 | _ => { 31 | return Err(format_err!( 32 | "Multiple APKs built. Specify which APK to execute using '--bin' or '--example'." 33 | )) 34 | } 35 | } 36 | }; 37 | 38 | // Determine package name 39 | let package_name = config.resolve(requested_target)?.package_name; 40 | 41 | // 42 | // Start the APK using adb 43 | // 44 | let adb = config.sdk_path.join("platform-tools/adb"); 45 | 46 | // Found it by doing this : 47 | // adb shell "cmd package resolve-activity --brief com.author.myproject | tail -n 1" 48 | let activity_path = format!( 49 | "{}/android.app.NativeActivity", 50 | package_name.replace("-", "_"), 51 | ); 52 | 53 | drop(writeln!(workspace.config().shell().err(), "Running apk")); 54 | process(&adb) 55 | .arg("shell") 56 | .arg("am") 57 | .arg("start") 58 | .arg("-a") 59 | .arg("android.intent.action.MAIN") 60 | .arg("-n") 61 | .arg(&activity_path) 62 | .exec()?; 63 | 64 | Ok(()) 65 | } 66 | -------------------------------------------------------------------------------- /cargo-apk/tests/cc/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "cc" 5 | version = "1.0.38" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | 8 | [[package]] 9 | name = "test_cc-rs" 10 | version = "0.1.0" 11 | dependencies = [ 12 | "cc 1.0.38 (registry+https://github.com/rust-lang/crates.io-index)", 13 | ] 14 | 15 | [metadata] 16 | "checksum cc 1.0.38 (registry+https://github.com/rust-lang/crates.io-index)" = "ce400c638d48ee0e9ab75aef7997609ec57367ccfe1463f21bf53c3eca67bf46" 17 | -------------------------------------------------------------------------------- /cargo-apk/tests/cc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test_cc-rs" 3 | version = "0.1.0" 4 | authors = ["Philip Alldredge "] 5 | description = "Simple test to ensure cargo-apk works with crates that use cc crate to build C and C++ static libraries." 6 | edition = "2018" 7 | publish = false 8 | 9 | [package.metadata.android] 10 | build_targets = [ "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android", "x86_64-linux-android" ] 11 | 12 | [build-dependencies] 13 | cc = "1.0" 14 | -------------------------------------------------------------------------------- /cargo-apk/tests/cc/build.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | cc::Build::new() 3 | .file("./cc_src/ctest.c") 4 | .compile("ctest"); 5 | 6 | cc::Build::new() 7 | .cpp(true) 8 | .file("./cc_src/cpptest.cpp") 9 | .compile("cpptest"); 10 | } 11 | -------------------------------------------------------------------------------- /cargo-apk/tests/cc/cc_src/cpptest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | extern "C" int32_t multiply_by_four(int32_t value) { 5 | return value * 4; 6 | } 7 | 8 | // Print using std::cout to verify C++ standard library is working properly. 9 | extern "C" void print_value(int32_t value) { 10 | std::cout << "Value printed from cout: " << value << std::endl; 11 | } -------------------------------------------------------------------------------- /cargo-apk/tests/cc/cc_src/ctest.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int32_t add_two(int32_t value) { 4 | return value + 2; 5 | } -------------------------------------------------------------------------------- /cargo-apk/tests/cc/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Android cc test"); 3 | let result = unsafe { 4 | multiply_by_four(add_two(4)) 5 | }; 6 | 7 | println!("multiply_by_four(add_two(4)): {}", result); 8 | 9 | println!("Printing value using c++ library:"); 10 | unsafe { 11 | print_value(result); 12 | } 13 | } 14 | 15 | #[link(name = "ctest")] 16 | extern "C" { 17 | fn add_two(value : i32) -> i32; 18 | } 19 | 20 | #[link(name = "cpptest")] 21 | extern "C" { 22 | fn multiply_by_four(value : i32) -> i32; 23 | fn print_value(value : i32) -> std::ffi::c_void; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /cargo-apk/tests/cmake/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "cc" 5 | version = "1.0.38" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | 8 | [[package]] 9 | name = "cmake" 10 | version = "0.1.40" 11 | source = "registry+https://github.com/rust-lang/crates.io-index" 12 | dependencies = [ 13 | "cc 1.0.38 (registry+https://github.com/rust-lang/crates.io-index)", 14 | ] 15 | 16 | [[package]] 17 | name = "test_cmake-rs" 18 | version = "0.1.0" 19 | dependencies = [ 20 | "cmake 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", 21 | ] 22 | 23 | [metadata] 24 | "checksum cc 1.0.38 (registry+https://github.com/rust-lang/crates.io-index)" = "ce400c638d48ee0e9ab75aef7997609ec57367ccfe1463f21bf53c3eca67bf46" 25 | "checksum cmake 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "2ca4386c8954b76a8415b63959337d940d724b336cabd3afe189c2b51a7e1ff0" 26 | -------------------------------------------------------------------------------- /cargo-apk/tests/cmake/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test_cmake-rs" 3 | version = "0.1.0" 4 | authors = ["Philip Alldredge "] 5 | description = "Simple test to ensure cargo-apk works with crates that use cmake crate" 6 | edition = "2018" 7 | publish = false 8 | 9 | [package.metadata.android] 10 | build_targets = [ "armv7-linux-androideabi", "aarch64-linux-android", "i686-linux-android", "x86_64-linux-android" ] 11 | 12 | [build-dependencies] 13 | cmake = "0.1" 14 | -------------------------------------------------------------------------------- /cargo-apk/tests/cmake/build.rs: -------------------------------------------------------------------------------- 1 | use cmake::Config; 2 | 3 | fn main() { 4 | let dst = Config::new("libcmaketest") 5 | .build(); 6 | println!("cargo:rustc-link-search=native={}", dst.display()); 7 | println!("cargo:rustc-link-lib=static=cmaketest"); 8 | } 9 | -------------------------------------------------------------------------------- /cargo-apk/tests/cmake/libcmaketest/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.9) 2 | project(cmaketest) 3 | 4 | set(CMAKE_BUILD_TYPE Release) 5 | ADD_LIBRARY(cmaketest STATIC cmaketest.c ) 6 | 7 | install(TARGETS cmaketest DESTINATION .) -------------------------------------------------------------------------------- /cargo-apk/tests/cmake/libcmaketest/cmaketest.c: -------------------------------------------------------------------------------- 1 | int multiply_by_10(int value) { 2 | return value * 10; 3 | } -------------------------------------------------------------------------------- /cargo-apk/tests/cmake/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Android cmake test"); 3 | let result = unsafe { 4 | multiply_by_10(2) 5 | }; 6 | 7 | println!("multiply_by_10(2): {}", result); 8 | } 9 | 10 | 11 | #[link(name = "cmaketest")] 12 | extern "C" { 13 | fn multiply_by_10(value : i32) -> i32; 14 | } 15 | -------------------------------------------------------------------------------- /cargo-apk/tests/inner_attributes/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "test_inner_attributes" 5 | version = "0.1.0" 6 | 7 | -------------------------------------------------------------------------------- /cargo-apk/tests/inner_attributes/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test_inner_attributes" 3 | version = "0.1.0" 4 | authors = ["Philip Alldredge "] 5 | edition = "2018" 6 | publish = false 7 | 8 | 9 | -------------------------------------------------------------------------------- /cargo-apk/tests/inner_attributes/src/main.rs: -------------------------------------------------------------------------------- 1 | #![cfg(target_os = "android")] 2 | 3 | fn main() { 4 | println!("Inner attributes test"); 5 | } 6 | 7 | -------------------------------------------------------------------------------- /cargo-apk/tests/native-library/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "test_native-library" 5 | version = "0.1.0" 6 | 7 | -------------------------------------------------------------------------------- /cargo-apk/tests/native-library/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test_native-library" 3 | version = "0.1.0" 4 | authors = ["Philip Alldredge "] 5 | edition = "2018" 6 | publish = false 7 | -------------------------------------------------------------------------------- /cargo-apk/tests/native-library/src/main.rs: -------------------------------------------------------------------------------- 1 | #![cfg(target_os = "android")] 2 | use std::ffi::c_void; 3 | use std::ptr; 4 | 5 | fn main() { 6 | println!("Android native library test"); 7 | let display = unsafe { eglGetDisplay(ptr::null()) }; 8 | println!("eglGetDisplay(0) result: {:?}", display); 9 | } 10 | 11 | // Link to the EGL to ensure that additional libraries can be linked 12 | #[link(name = "EGL")] 13 | extern "C" { 14 | fn eglGetDisplay(native_display : *const c_void) -> *mut c_void; 15 | } -------------------------------------------------------------------------------- /cargo-apk/tests/run_tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | fail() { 6 | echo "$@" 7 | exit 1 8 | } 9 | 10 | [[ $(basename $(pwd)) = cargo-apk ]] || fail "Must be run in cargo-apk directory" 11 | 12 | do_test() { 13 | do_package "tests/$1" || fail "Compiling test $1 failed" 14 | check_symbols "tests/$1" || fail "onCreate not found in test $1" 15 | } 16 | 17 | do_example() { 18 | do_package "../examples/$1" || fail "Compiling example $1 failed" 19 | check_symbols "../examples/$1" || fail "onCreate not found in example $1" 20 | } 21 | 22 | do_package() { 23 | pushd "$1" >/dev/null 24 | cargo apk build --all-targets || return 1 25 | cargo apk build --all-targets --release || return 1 26 | popd >/dev/null 27 | } 28 | 29 | check_symbols() { 30 | (find "$1/target/android-artifacts/release/bin" -name *.so -not -name libc++_shared.so && \ 31 | find "$1/target/android-artifacts/debug/bin" -name *.so -not -name libc++_shared.so) | \ 32 | while read f ; do 33 | nm -Dg --defined-only "$f" | cut -f3 -d' ' | grep -qxF ANativeActivity_onCreate || return 1 34 | done 35 | } 36 | 37 | do_example advanced 38 | do_example basic 39 | do_example multiple_targets 40 | do_example use_assets 41 | do_example use_icon 42 | do_test inner_attributes 43 | do_test native-library 44 | do_test cc 45 | do_test cmake 46 | -------------------------------------------------------------------------------- /examples/advanced/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "advanced" 5 | version = "0.1.0" 6 | 7 | -------------------------------------------------------------------------------- /examples/advanced/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "advanced" 3 | version = "0.1.0" 4 | authors = ["Philip Alldredge tag : 55 | # android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen 56 | # Defaults to false. 57 | fullscreen = false 58 | 59 | # The maximum supported OpenGL ES version , as claimed by the manifest. Defaults to 2.0. 60 | # See https://developer.android.com/guide/topics/graphics/opengl.html#manifest 61 | opengles_version_major = 3 62 | opengles_version_minor = 2 63 | 64 | # Adds extra arbitrary XML attributes to the tag in the manifest. 65 | # See https://developer.android.com/guide/topics/manifest/application-element.html 66 | [package.metadata.android.application_attributes] 67 | "android:debuggable" = "true" 68 | "android:hardwareAccelerated" = "true" 69 | 70 | # Adds extra arbitrary XML attributes to the tag in the manifest. 71 | # See https://developer.android.com/guide/topics/manifest/activity-element.html 72 | [package.metadata.android.activity_attributes] 73 | "android:screenOrientation" = "unspecified" 74 | "android:uiOptions" = "none" 75 | 76 | # Adds a uses-feature element to the manifest 77 | # Supported keys: name, required, version 78 | # The glEsVersion attribute is not supported using this section. 79 | # It can be specified using the opengles_version_major and opengles_version_minor values 80 | # See https://developer.android.com/guide/topics/manifest/uses-feature-element 81 | [[package.metadata.android.feature]] 82 | name = "android.hardware.camera" 83 | 84 | [[package.metadata.android.feature]] 85 | name = "android.hardware.vulkan.level" 86 | version = "1" 87 | required = false 88 | 89 | # Adds a uses-permission element to the manifest. 90 | # Note that android_version 23 and higher, Android requires the application to request permissions at runtime. 91 | # There is currently no way to do this using a pure NDK based application. 92 | # See https://developer.android.com/guide/topics/manifest/uses-permission-element 93 | [[package.metadata.android.permission]] 94 | name = "android.permission.WRITE_EXTERNAL_STORAGE" 95 | max_sdk_version = 18 96 | 97 | [[package.metadata.android.permission]] 98 | name = "android.permission.CAMERA" 99 | -------------------------------------------------------------------------------- /examples/advanced/assets/test_asset: -------------------------------------------------------------------------------- 1 | str1 2 | str2 3 | str3 4 | -------------------------------------------------------------------------------- /examples/advanced/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/advanced/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/advanced/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/advanced/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/advanced/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/advanced/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/advanced/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/advanced/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/advanced/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/advanced/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/advanced/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("main() has been called from advanced example"); 3 | } 4 | -------------------------------------------------------------------------------- /examples/basic/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "android-ndk-sys" 5 | version = "0.2.0" 6 | 7 | [[package]] 8 | name = "android_glue" 9 | version = "0.2.3" 10 | dependencies = [ 11 | "android-ndk-sys 0.2.0", 12 | ] 13 | 14 | [[package]] 15 | name = "android_glue_example" 16 | version = "0.1.0" 17 | dependencies = [ 18 | "android_glue 0.2.3", 19 | ] 20 | 21 | -------------------------------------------------------------------------------- /examples/basic/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "android_glue_example" 3 | version = "0.1.0" 4 | authors = ["Pierre Krieger "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | android_glue = { path = "../../glue" } 9 | -------------------------------------------------------------------------------- /examples/basic/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("main() has been called"); 3 | } 4 | -------------------------------------------------------------------------------- /examples/multiple_targets/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "android-ndk-sys" 5 | version = "0.2.0" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | 8 | [[package]] 9 | name = "android_glue" 10 | version = "0.2.3" 11 | dependencies = [ 12 | "android-ndk-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", 13 | ] 14 | 15 | [[package]] 16 | name = "android_primary_bin" 17 | version = "0.1.0" 18 | dependencies = [ 19 | "android_glue 0.2.3", 20 | ] 21 | 22 | [metadata] 23 | "checksum android-ndk-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3ec6ef28479835db378e2202b3911608e2269405e924fabb02ac3c8fb50284fe" 24 | -------------------------------------------------------------------------------- /examples/multiple_targets/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "android_primary_bin" 3 | version = "0.1.0" 4 | authors = ["Philip Alldredge "] 5 | publish = false 6 | edition = "2018" 7 | 8 | [dependencies.android_glue] 9 | path = "../../glue" 10 | 11 | [package.metadata.android] 12 | label = "Primary Binary" 13 | 14 | [[package.metadata.android.bin]] 15 | name = "secondary-bin" 16 | label = "Secondary Binary" 17 | 18 | [[package.metadata.android.example]] 19 | name = "example1" 20 | label = "Example 1" 21 | -------------------------------------------------------------------------------- /examples/multiple_targets/examples/example1.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("main() has been called on example1"); 3 | } 4 | -------------------------------------------------------------------------------- /examples/multiple_targets/src/bin/secondary-bin.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("main() has been called on the secondary binary"); 3 | } 4 | -------------------------------------------------------------------------------- /examples/multiple_targets/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("main() has been called on the primary binary"); 3 | } 4 | -------------------------------------------------------------------------------- /examples/use_assets/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "android-ndk" 5 | version = "0.0.6" 6 | source = "git+https://github.com/rust-windowing/android-ndk-rs#ac2157b6449b50eee6fe8a08acb05003633879a3" 7 | dependencies = [ 8 | "android-ndk-sys 0.2.0 (git+https://github.com/rust-windowing/android-ndk-rs)", 9 | "jni 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)", 10 | "num_enum 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", 11 | ] 12 | 13 | [[package]] 14 | name = "android-ndk-sys" 15 | version = "0.2.0" 16 | source = "git+https://github.com/rust-windowing/android-ndk-rs#ac2157b6449b50eee6fe8a08acb05003633879a3" 17 | 18 | [[package]] 19 | name = "android_glue" 20 | version = "0.2.3" 21 | dependencies = [ 22 | "android-ndk-sys 0.2.0 (git+https://github.com/rust-windowing/android-ndk-rs)", 23 | ] 24 | 25 | [[package]] 26 | name = "android_glue_assets_example" 27 | version = "0.1.0" 28 | dependencies = [ 29 | "android-ndk 0.0.6 (git+https://github.com/rust-windowing/android-ndk-rs)", 30 | "android_glue 0.2.3", 31 | ] 32 | 33 | [[package]] 34 | name = "ascii" 35 | version = "0.9.3" 36 | source = "registry+https://github.com/rust-lang/crates.io-index" 37 | 38 | [[package]] 39 | name = "backtrace" 40 | version = "0.3.38" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | dependencies = [ 43 | "backtrace-sys 0.1.31 (registry+https://github.com/rust-lang/crates.io-index)", 44 | "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", 45 | "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", 46 | "rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", 47 | ] 48 | 49 | [[package]] 50 | name = "backtrace-sys" 51 | version = "0.1.31" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | dependencies = [ 54 | "cc 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)", 55 | "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", 56 | ] 57 | 58 | [[package]] 59 | name = "byteorder" 60 | version = "1.3.2" 61 | source = "registry+https://github.com/rust-lang/crates.io-index" 62 | 63 | [[package]] 64 | name = "cc" 65 | version = "1.0.45" 66 | source = "registry+https://github.com/rust-lang/crates.io-index" 67 | 68 | [[package]] 69 | name = "cesu8" 70 | version = "1.1.0" 71 | source = "registry+https://github.com/rust-lang/crates.io-index" 72 | 73 | [[package]] 74 | name = "cfg-if" 75 | version = "0.1.10" 76 | source = "registry+https://github.com/rust-lang/crates.io-index" 77 | 78 | [[package]] 79 | name = "combine" 80 | version = "3.8.1" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | dependencies = [ 83 | "ascii 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", 84 | "byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", 85 | "either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)", 86 | "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 87 | "unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", 88 | ] 89 | 90 | [[package]] 91 | name = "either" 92 | version = "1.5.3" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | 95 | [[package]] 96 | name = "error-chain" 97 | version = "0.12.1" 98 | source = "registry+https://github.com/rust-lang/crates.io-index" 99 | dependencies = [ 100 | "backtrace 0.3.38 (registry+https://github.com/rust-lang/crates.io-index)", 101 | "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", 102 | ] 103 | 104 | [[package]] 105 | name = "jni" 106 | version = "0.13.1" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | dependencies = [ 109 | "cesu8 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 110 | "combine 3.8.1 (registry+https://github.com/rust-lang/crates.io-index)", 111 | "error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", 112 | "jni-sys 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", 113 | "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", 114 | "walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)", 115 | ] 116 | 117 | [[package]] 118 | name = "jni-sys" 119 | version = "0.3.0" 120 | source = "registry+https://github.com/rust-lang/crates.io-index" 121 | 122 | [[package]] 123 | name = "libc" 124 | version = "0.2.62" 125 | source = "registry+https://github.com/rust-lang/crates.io-index" 126 | 127 | [[package]] 128 | name = "log" 129 | version = "0.4.8" 130 | source = "registry+https://github.com/rust-lang/crates.io-index" 131 | dependencies = [ 132 | "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", 133 | ] 134 | 135 | [[package]] 136 | name = "memchr" 137 | version = "2.2.1" 138 | source = "registry+https://github.com/rust-lang/crates.io-index" 139 | 140 | [[package]] 141 | name = "num_enum" 142 | version = "0.2.3" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | dependencies = [ 145 | "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", 146 | "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", 147 | "syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)", 148 | ] 149 | 150 | [[package]] 151 | name = "proc-macro2" 152 | version = "0.4.30" 153 | source = "registry+https://github.com/rust-lang/crates.io-index" 154 | dependencies = [ 155 | "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 156 | ] 157 | 158 | [[package]] 159 | name = "quote" 160 | version = "0.6.13" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | dependencies = [ 163 | "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", 164 | ] 165 | 166 | [[package]] 167 | name = "rustc-demangle" 168 | version = "0.1.16" 169 | source = "registry+https://github.com/rust-lang/crates.io-index" 170 | 171 | [[package]] 172 | name = "same-file" 173 | version = "1.0.5" 174 | source = "registry+https://github.com/rust-lang/crates.io-index" 175 | dependencies = [ 176 | "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 177 | ] 178 | 179 | [[package]] 180 | name = "syn" 181 | version = "0.15.44" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | dependencies = [ 184 | "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)", 185 | "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)", 186 | "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 187 | ] 188 | 189 | [[package]] 190 | name = "unicode-xid" 191 | version = "0.1.0" 192 | source = "registry+https://github.com/rust-lang/crates.io-index" 193 | 194 | [[package]] 195 | name = "unreachable" 196 | version = "1.0.0" 197 | source = "registry+https://github.com/rust-lang/crates.io-index" 198 | dependencies = [ 199 | "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", 200 | ] 201 | 202 | [[package]] 203 | name = "version_check" 204 | version = "0.1.5" 205 | source = "registry+https://github.com/rust-lang/crates.io-index" 206 | 207 | [[package]] 208 | name = "void" 209 | version = "1.0.2" 210 | source = "registry+https://github.com/rust-lang/crates.io-index" 211 | 212 | [[package]] 213 | name = "walkdir" 214 | version = "2.2.9" 215 | source = "registry+https://github.com/rust-lang/crates.io-index" 216 | dependencies = [ 217 | "same-file 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", 218 | "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 219 | "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", 220 | ] 221 | 222 | [[package]] 223 | name = "winapi" 224 | version = "0.3.8" 225 | source = "registry+https://github.com/rust-lang/crates.io-index" 226 | dependencies = [ 227 | "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 228 | "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 229 | ] 230 | 231 | [[package]] 232 | name = "winapi-i686-pc-windows-gnu" 233 | version = "0.4.0" 234 | source = "registry+https://github.com/rust-lang/crates.io-index" 235 | 236 | [[package]] 237 | name = "winapi-util" 238 | version = "0.1.2" 239 | source = "registry+https://github.com/rust-lang/crates.io-index" 240 | dependencies = [ 241 | "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 242 | ] 243 | 244 | [[package]] 245 | name = "winapi-x86_64-pc-windows-gnu" 246 | version = "0.4.0" 247 | source = "registry+https://github.com/rust-lang/crates.io-index" 248 | 249 | [metadata] 250 | "checksum android-ndk 0.0.6 (git+https://github.com/rust-windowing/android-ndk-rs)" = "" 251 | "checksum android-ndk-sys 0.2.0 (git+https://github.com/rust-windowing/android-ndk-rs)" = "" 252 | "checksum ascii 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "eab1c04a571841102f5345a8fc0f6bb3d31c315dec879b5c6e42e40ce7ffa34e" 253 | "checksum backtrace 0.3.38 (registry+https://github.com/rust-lang/crates.io-index)" = "690a62be8920ccf773ee00ef0968649b0e724cda8bd5b12286302b4ae955fdf5" 254 | "checksum backtrace-sys 0.1.31 (registry+https://github.com/rust-lang/crates.io-index)" = "82a830b4ef2d1124a711c71d263c5abdc710ef8e907bd508c88be475cebc422b" 255 | "checksum byteorder 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a7c3dd8985a7111efc5c80b44e23ecdd8c007de8ade3b96595387e812b957cf5" 256 | "checksum cc 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)" = "4fc9a35e1f4290eb9e5fc54ba6cf40671ed2a2514c3eeb2b2a908dda2ea5a1be" 257 | "checksum cesu8 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" 258 | "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 259 | "checksum combine 3.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "da3da6baa321ec19e1cc41d31bf599f00c783d0517095cdaf0332e3fe8d20680" 260 | "checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" 261 | "checksum error-chain 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3ab49e9dcb602294bc42f9a7dfc9bc6e936fca4418ea300dbfb84fe16de0b7d9" 262 | "checksum jni 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e00f1fd30a82a801f8bf38bcb0895088a0013cde111acb713c0824edc372aa4" 263 | "checksum jni-sys 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" 264 | "checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba" 265 | "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" 266 | "checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e" 267 | "checksum num_enum 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "fae2a63210048cf77ceb6031b3f87ac69e4a68cfaacb17a0261e141c4bc8467b" 268 | "checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" 269 | "checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" 270 | "checksum rustc-demangle 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "4c691c0e608126e00913e33f0ccf3727d5fc84573623b8d65b2df340b5201783" 271 | "checksum same-file 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "585e8ddcedc187886a30fa705c47985c3fa88d06624095856b36ca0b82ff4421" 272 | "checksum syn 0.15.44 (registry+https://github.com/rust-lang/crates.io-index)" = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" 273 | "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" 274 | "checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" 275 | "checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" 276 | "checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" 277 | "checksum walkdir 2.2.9 (registry+https://github.com/rust-lang/crates.io-index)" = "9658c94fa8b940eab2250bd5a457f9c48b748420d71293b165c8cdbe2f55f71e" 278 | "checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" 279 | "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 280 | "checksum winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7168bab6e1daee33b4557efd0e95d5ca70a03706d39fa5f3fe7a236f584b03c9" 281 | "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 282 | -------------------------------------------------------------------------------- /examples/use_assets/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "android_glue_assets_example" 3 | version = "0.1.0" 4 | authors = ["Pierre Krieger "] 5 | edition = "2018" 6 | 7 | [package.metadata.android] 8 | label = "Using assets android-rs-glue example" 9 | assets = "assets" 10 | 11 | [dependencies] 12 | android-ndk = { git = "https://github.com/rust-windowing/android-ndk-rs" } 13 | 14 | [dependencies.android_glue] 15 | path = "../../glue" 16 | -------------------------------------------------------------------------------- /examples/use_assets/assets/test_asset: -------------------------------------------------------------------------------- 1 | str1 2 | str2 3 | str3 4 | -------------------------------------------------------------------------------- /examples/use_assets/src/main.rs: -------------------------------------------------------------------------------- 1 | use android_ndk::android_app::AndroidApp; 2 | use android_ndk::asset::Asset; 3 | use std::ffi::CString; 4 | use std::io::{BufRead, BufReader}; 5 | 6 | fn main() { 7 | let android_app = unsafe { AndroidApp::from_ptr(android_glue::get_android_app()) }; 8 | 9 | let f = open_asset(&android_app, "test_asset"); 10 | for line in BufReader::new(f).lines() { 11 | println!("{:?}", line); 12 | } 13 | } 14 | 15 | fn open_asset(android_app: &AndroidApp, name: &str) -> Asset { 16 | let asset_manager = android_app.activity().asset_manager(); 17 | asset_manager 18 | .open(&CString::new(name).unwrap()) 19 | .expect("Could not open asset") 20 | } 21 | -------------------------------------------------------------------------------- /examples/use_icon/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "android-ndk-sys" 5 | version = "0.2.0" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | 8 | [[package]] 9 | name = "android_glue" 10 | version = "0.2.3" 11 | dependencies = [ 12 | "android-ndk-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", 13 | ] 14 | 15 | [[package]] 16 | name = "android_glue_icon_example" 17 | version = "0.1.0" 18 | dependencies = [ 19 | "android_glue 0.2.3", 20 | ] 21 | 22 | [metadata] 23 | "checksum android-ndk-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3ec6ef28479835db378e2202b3911608e2269405e924fabb02ac3c8fb50284fe" 24 | -------------------------------------------------------------------------------- /examples/use_icon/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "android_glue_icon_example" 3 | version = "0.1.0" 4 | authors = ["Pierre Krieger "] 5 | edition = "2018" 6 | 7 | [package.metadata.android] 8 | label = "Using icon android-rs-glue example" 9 | res = "res" 10 | icon = "@mipmap/ic_launcher" 11 | 12 | [dependencies.android_glue] 13 | path = "../../glue" -------------------------------------------------------------------------------- /examples/use_icon/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/use_icon/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/use_icon/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/use_icon/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/use_icon/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/use_icon/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/use_icon/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/use_icon/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/use_icon/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rust-mobile/android-rs-glue/3c4c9745eafcfc369514bd687f20b29228077d46/examples/use_icon/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /examples/use_icon/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("main() has been called, did you like the icon?"); 3 | } 4 | -------------------------------------------------------------------------------- /glue/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /glue/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "android_glue" 3 | version = "0.2.3" 4 | authors = ["Pierre Krieger "] 5 | license = "MIT" 6 | description = "Glue for building Android NDK apps with cargo-apk" 7 | repository = "https://github.com/rust-windowing/android-rs-glue" 8 | edition = "2018" 9 | 10 | [dependencies] 11 | android-ndk-sys = { git = "https://github.com/rust-windowing/android-ndk-rs" } 12 | -------------------------------------------------------------------------------- /glue/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Glue for working with cargo-apk 2 | //! 3 | //! Previously, this library provided an abstraction over the event loop. However, this has been 4 | //! removed in favor of giving users more flexibility. Use android-ndk or Winit for a higher-level 5 | //! abstraction. 6 | 7 | use android_ndk_sys::native_app_glue::android_app; 8 | use std::ptr::NonNull; 9 | 10 | extern "C" { 11 | static ANDROID_APP: *mut android_app; 12 | } 13 | 14 | /// Get the `struct android_app` instance from the `android_native_app_glue` code. 15 | pub fn get_android_app() -> NonNull { 16 | NonNull::new(unsafe { ANDROID_APP }).unwrap() 17 | } 18 | --------------------------------------------------------------------------------