diff --git a/Cargo.toml b/Cargo.toml index f1ec87f..16cfdc2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,13 +41,4 @@ wasm-bindgen = "0.2" web-sys = { version = "0.3", features = ["EventTarget", "SpeechSynthesis", "SpeechSynthesisErrorCode", "SpeechSynthesisErrorEvent", "SpeechSynthesisEvent", "SpeechSynthesisUtterance", "Window", ] } [target.'cfg(target_os="android")'.dependencies] -jni = "0.18" -ndk-glue = "0.2" - -[package.metadata.android] -target_sdk_version = 29 -min_sdk_version = 21 - -[[example]] -name = "hello_world_android" -crate-type = ["cdylib"] +jni = "0.18" \ No newline at end of file diff --git a/examples/android/.gitignore b/examples/android/.gitignore new file mode 100644 index 0000000..26fa1c5 --- /dev/null +++ b/examples/android/.gitignore @@ -0,0 +1,16 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties +Cargo.lock diff --git a/examples/android/.idea/.gitignore b/examples/android/.idea/.gitignore new file mode 100644 index 0000000..eaf91e2 --- /dev/null +++ b/examples/android/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/examples/android/.idea/compiler.xml b/examples/android/.idea/compiler.xml new file mode 100644 index 0000000..851fce6 --- /dev/null +++ b/examples/android/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/examples/android/.idea/gradle.xml b/examples/android/.idea/gradle.xml new file mode 100644 index 0000000..c272f95 --- /dev/null +++ b/examples/android/.idea/gradle.xml @@ -0,0 +1,21 @@ + + + + + + + \ No newline at end of file diff --git a/examples/android/.idea/jarRepositories.xml b/examples/android/.idea/jarRepositories.xml new file mode 100644 index 0000000..17c8136 --- /dev/null +++ b/examples/android/.idea/jarRepositories.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/android/.idea/misc.xml b/examples/android/.idea/misc.xml new file mode 100644 index 0000000..673075e --- /dev/null +++ b/examples/android/.idea/misc.xml @@ -0,0 +1,9 @@ + + + + + + + + \ No newline at end of file diff --git a/examples/android/.idea/vcs.xml b/examples/android/.idea/vcs.xml new file mode 100644 index 0000000..c8ade07 --- /dev/null +++ b/examples/android/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/examples/android/app/.gitignore b/examples/android/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/examples/android/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/examples/android/app/build.gradle b/examples/android/app/build.gradle new file mode 100644 index 0000000..8cefd06 --- /dev/null +++ b/examples/android/app/build.gradle @@ -0,0 +1,55 @@ +plugins { + id "com.android.application" + id "kotlin-android" +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + defaultConfig { + applicationId "rs.tts" + minSdkVersion 21 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation "androidx.core:core-ktx:1.2.0" + implementation "com.google.android.material:material:1.1.0" + implementation "androidx.constraintlayout:constraintlayout:1.1.3" +} + +apply plugin: "com.github.willir.rust.cargo-ndk-android" + +cargoNdk { + module = "." +} + +project.afterEvaluate { + android.applicationVariants.all { variant -> + task "run${variant.name.capitalize()}"(type: Exec, dependsOn: "install${variant.name.capitalize()}", group: "run") { + commandLine = ["adb", "shell", "monkey", "-p", variant.applicationId + " 1"] + doLast { + println "Launching ${variant.applicationId}" + } + } + } +} diff --git a/examples/android/app/proguard-rules.pro b/examples/android/app/proguard-rules.pro new file mode 100644 index 0000000..64b4a05 --- /dev/null +++ b/examples/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/examples/android/app/src/main/.gitignore b/examples/android/app/src/main/.gitignore new file mode 100644 index 0000000..e1230da --- /dev/null +++ b/examples/android/app/src/main/.gitignore @@ -0,0 +1 @@ +jniLibs diff --git a/examples/android/app/src/main/AndroidManifest.xml b/examples/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..86dda62 --- /dev/null +++ b/examples/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/android/app/src/main/java/rs/tts/MainActivity.kt b/examples/android/app/src/main/java/rs/tts/MainActivity.kt new file mode 100644 index 0000000..2b58854 --- /dev/null +++ b/examples/android/app/src/main/java/rs/tts/MainActivity.kt @@ -0,0 +1,8 @@ +package rs.tts + +import android.app.NativeActivity +import android.speech.tts.TextToSpeech.OnInitListener + +class MainActivity : NativeActivity(), OnInitListener { + override fun onInit(status:Int) {} +} \ No newline at end of file diff --git a/examples/android/app/src/main/res/values/strings.xml b/examples/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..524d08f --- /dev/null +++ b/examples/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + TTS-RS + \ No newline at end of file diff --git a/examples/android/build.gradle b/examples/android/build.gradle new file mode 100644 index 0000000..dd9a15c --- /dev/null +++ b/examples/android/build.gradle @@ -0,0 +1,29 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + ext.kotlin_version = "1.3.72" + repositories { + google() + jcenter() + maven { + url "https://plugins.gradle.org/m2/" + } + } + dependencies { + classpath "com.android.tools.build:gradle:4.1.1" + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "gradle.plugin.com.github.willir.rust:plugin:0.3.3" + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} \ No newline at end of file diff --git a/examples/android/cargo.toml b/examples/android/cargo.toml new file mode 100644 index 0000000..a7ff289 --- /dev/null +++ b/examples/android/cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "hello_world" +version = "0.1.0" +authors = ["Nolan Darilek "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["dylib"] + +[dependencies] +ndk-glue = "0.2" +tts = { path = "../.." } \ No newline at end of file diff --git a/examples/android/gradle.properties b/examples/android/gradle.properties new file mode 100644 index 0000000..a38cbbb --- /dev/null +++ b/examples/android/gradle.properties @@ -0,0 +1,21 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Automatically convert third-party libraries to use AndroidX +android.enableJetifier=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official \ No newline at end of file diff --git a/examples/android/gradle/wrapper/gradle-wrapper.jar b/examples/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f Binary files /dev/null and b/examples/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/android/gradle/wrapper/gradle-wrapper.properties b/examples/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7b15717 --- /dev/null +++ b/examples/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Dec 28 17:32:22 CST 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip diff --git a/examples/android/gradlew b/examples/android/gradlew new file mode 100644 index 0000000..cccdd3d --- /dev/null +++ b/examples/android/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/examples/android/gradlew.bat b/examples/android/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/examples/android/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/examples/android/settings.gradle b/examples/android/settings.gradle new file mode 100644 index 0000000..1fb859b --- /dev/null +++ b/examples/android/settings.gradle @@ -0,0 +1 @@ +include ":app" \ No newline at end of file diff --git a/examples/hello_world_android.rs b/examples/android/src/lib.rs similarity index 74% rename from examples/hello_world_android.rs rename to examples/android/src/lib.rs index 8243936..8a256d6 100644 --- a/examples/hello_world_android.rs +++ b/examples/android/src/lib.rs @@ -1,17 +1,6 @@ -use std::io; - -#[cfg(target_os = "macos")] -use cocoa_foundation::base::id; -#[cfg(target_os = "macos")] -use cocoa_foundation::foundation::NSRunLoop; -#[cfg(target_os = "macos")] -use objc::{msg_send, sel, sel_impl}; - use tts::*; -// Use a separate function so the same examples run everywhere. fn run() -> Result<(), Error> { - env_logger::init(); let mut tts = TTS::default()?; let Features { utterance_callbacks, @@ -68,22 +57,10 @@ fn run() -> Result<(), Error> { tts.set_volume(original_volume)?; } tts.speak("Goodbye.", false)?; - let mut _input = String::new(); - // The below is only needed to make the example run on MacOS because there is no NSRunLoop in this context. - // It shouldn't be needed in an app or game that almost certainly has one already. - #[cfg(target_os = "macos")] - { - let run_loop: id = unsafe { NSRunLoop::currentRunLoop() }; - unsafe { - let _: () = msg_send![run_loop, run]; - } - } - io::stdin().read_line(&mut _input)?; Ok(()) } -#[cfg(target_os = "android")] #[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on"))] -fn main() { +pub fn main() { run().expect("Failed to run"); } diff --git a/src/backends/android.rs b/src/backends/android.rs index a2d1fc4..9e3f842 100644 --- a/src/backends/android.rs +++ b/src/backends/android.rs @@ -14,12 +14,16 @@ lazy_static! { pub(crate) struct Android(BackendId); impl Android { - pub(crate) fn new() -> Self { + pub(crate) fn new() -> Result { info!("Initializing Android backend"); let mut backend_id = NEXT_BACKEND_ID.lock().unwrap(); let bid = BackendId::Android(*backend_id); *backend_id += 1; - Self(bid) + let native_activity = ndk_glue::native_activity(); + let vm_ptr = native_activity.vm(); + let vm = unsafe { jni::JavaVM::from_raw(vm_ptr) }?; + let env = vm.attach_current_thread()?; + Ok(Self(bid)) } } diff --git a/src/lib.rs b/src/lib.rs index 7bebbeb..ed32cf9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -115,6 +115,9 @@ pub enum Error { UnsupportedFeature, #[error("Out of range")] OutOfRange, + #[cfg(target_os = "android")] + #[error("JNI error: [0])]")] + JNI(#[from] jni::errors::Error), } #[clonable] @@ -198,7 +201,10 @@ impl TTS { #[cfg(any(target_os = "macos", target_os = "ios"))] Backends::AvFoundation => Ok(TTS(Box::new(backends::AvFoundation::new()))), #[cfg(target_os = "android")] - Backends::Android => Ok(TTS(Box::new(backends::Android::new()))), + Backends::Android => { + let tts = backends::Android::new()?; + Ok(TTS(Box::new(tts))) + } }; if let Ok(backend) = backend { if let Some(id) = backend.0.id() {