diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a13cac --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +*.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 +/app/elixir-app +/app/src/main/assets/app.zip \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..7237946 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +TodoApp \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..7643783 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,123 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..fb7f4a8 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..526b4c2 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,20 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..0380d8d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..b9bf2cd --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..7f3227a --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..625ab71 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,22 @@ +# MIT License + +Copyright (c) 2021 Dominic Letz + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..324c670 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +# TodoApp Android: An Android Sample App + +This Android Studio project wraps the [Desktop Sample App](https://github.com/elixir-desktop/desktop-example-app) to run on an Android phone. + +## How to build & run + +1. Install [Android Studio](https://developer.android.com/studio) + NDK. + +2. Go to "Files -> New -> Project from Version Control -> GitHub" + +3. [Connect your Phone](https://developer.android.com/studio/run/device) to Android Studio + +4. Start the App + +## Known todos + +### The x86_64 emulator does not work + +So you've got to run on your phone or you the slow ARM emulator. If you have an idea how to fix the issue. Please send a pull request to the runtime project. + +### Initial Startup time is slow + +Running the app for the first time it will extract the full Elixir & App runtime at start. On my Phone this takes anywhere from 10-20 seconds. After that the startup is releatively quick. + +### Menus and other integration not yet available + +This sample only launch the elixir app and shows it in an Android WebView. There is no integration yet with the Android Clipboard, sharing or other OS capabilities. They can though easily be added to the `Bridge.kt` file when needed. + +## Other notes + +- The current sample is using __Android API 23__ and above + +- The Erlang runtime is for ease of use embedded in this example git repository. The native runtimes for Android ARM, ARM64 and X86_64 and the exqlite nif are are generated using the [Desktop Runtime](https://github.com/elixir-desktop/runtime) repository. + +- Android specific settings, icons and metadata are all contained in this Android Studio wrapper project. + +- `Bridge.kt` and the native library are doing most of the wrapping of the Elixir runtime. + +## Screenshots + +![Icons](/icon.jpg?raw=true "App in Icon View") +![App](/app.jpg?raw=true "Running App") + +## Architecture + +![App](/android_elixir.png?raw=true "Architecture") + +The Android App is initializing the Erlang VM and starting it up with a new environment variable `BRIDGE_PORT`. This environment variable is used by the `Bridge` project to connect to a local TCP server _inside the android app_. Through this new TCP communication channel all calls that usually would go to `wxWidgets` are now redirected. The Android side of things implements handling in `Bridge.kt`. \ No newline at end of file diff --git a/android_elixir.png b/android_elixir.png new file mode 100644 index 0000000..080c40f Binary files /dev/null and b/android_elixir.png differ diff --git a/app.jpg b/app.jpg new file mode 100644 index 0000000..dc915ad Binary files /dev/null and b/app.jpg differ diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle new file mode 100644 index 0000000..6896f96 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,70 @@ +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +android { + compileSdkVersion 30 + buildToolsVersion "30.0.3" + + task buildNum(type: Exec, description: 'Update Elixir App') { + commandLine '../run_mix', 'package.mobile' + } + + tasks.withType(JavaCompile) { + compileTask -> compileTask.dependsOn buildNum + } + + defaultConfig { + applicationId 'io.elixirdesktop.example' + minSdkVersion 23 + targetSdkVersion 30 + versionCode 1 + versionName "1.0" + + ndk { + abiFilters "armeabi-v7a", "arm64-v8a" // , "x86_64" -- currently not working + } + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + externalNativeBuild { + cmake { + cppFlags '' + } + } + } + + 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' + } + externalNativeBuild { + cmake { + path file('src/main/cpp/CMakeLists.txt') + version '3.10.2' + } + } + buildFeatures { + viewBinding true + } +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation 'androidx.core:core-ktx:1.5.0' + implementation 'androidx.appcompat:appcompat:1.3.0' + implementation 'com.google.android.material:material:1.3.0' + implementation 'androidx.constraintlayout:constraintlayout:2.0.4' + testImplementation 'junit:junit:4.+' + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/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/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..a030db0 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/assets/arm64-v8a-nif-exqlite.zip b/app/src/main/assets/arm64-v8a-nif-exqlite.zip new file mode 100644 index 0000000..cd81f84 Binary files /dev/null and b/app/src/main/assets/arm64-v8a-nif-exqlite.zip differ diff --git a/app/src/main/assets/arm64-v8a-runtime.zip b/app/src/main/assets/arm64-v8a-runtime.zip new file mode 100644 index 0000000..0125d63 Binary files /dev/null and b/app/src/main/assets/arm64-v8a-runtime.zip differ diff --git a/app/src/main/assets/armeabi-v7a-nif-exqlite.zip b/app/src/main/assets/armeabi-v7a-nif-exqlite.zip new file mode 100644 index 0000000..9bdaea6 Binary files /dev/null and b/app/src/main/assets/armeabi-v7a-nif-exqlite.zip differ diff --git a/app/src/main/assets/armeabi-v7a-runtime.zip b/app/src/main/assets/armeabi-v7a-runtime.zip new file mode 100644 index 0000000..5115dd4 Binary files /dev/null and b/app/src/main/assets/armeabi-v7a-runtime.zip differ diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000..22c3131 --- /dev/null +++ b/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,48 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html + +# Sets the minimum version of CMake required to build the native library. + +cmake_minimum_required(VERSION 3.10.2) + +# Declares and names the project. + +project("example") + +# Creates and names a library, sets it as either STATIC +# or SHARED, and provides the relative paths to its source code. +# You can define multiple libraries, and CMake builds them for you. +# Gradle automatically packages shared libraries with your APK. + +add_library( # Sets the name of the library. + native-lib + + # Sets the library as a shared library. + SHARED + + # Provides a relative path to your source file(s). + native-lib.cpp ) + +# Searches for a specified prebuilt library and stores the path as a +# variable. Because CMake includes system libraries in the search path by +# default, you only need to specify the name of the public NDK library +# you want to add. CMake verifies that the library exists before +# completing its build. + +find_library( # Sets the name of the path variable. + log-lib + + # Specifies the name of the NDK library that + # you want CMake to locate. + log ) + +# Specifies libraries CMake should link to your target library. You +# can link multiple libraries, such as libraries you define in this +# build script, prebuilt third-party libraries, or system libraries. + +target_link_libraries( # Specifies the target library. + native-lib + + # Links the target library to the log library + # included in the NDK. + ${log-lib} ) \ No newline at end of file diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp new file mode 100644 index 0000000..9ec739e --- /dev/null +++ b/app/src/main/cpp/native-lib.cpp @@ -0,0 +1,216 @@ +#include +#include +#include +#include +#include + +std::string jstring2string(JNIEnv *env, jstring jStr); +int start_logger(); +static void logger_func(); +static std::string log_file; +void (*startfun)(int argc, char **argv); + +void ensure_slash(std::string& str) +{ + if (!str.empty() && str[str.size()-1] != '/') { + str.append("/"); + } +} + +void test_nif(std::string nif) +{ + void* lib = dlopen(nif.c_str(), RTLD_NOW); + if (!lib) { + printf("Failed opening %s: %s\n", nif.c_str(), dlerror()); + return; + } + + void* sym = dlsym(lib, "nif_init"); + printf("%s: nif_init() => %lx\n", nif.c_str(), sym); + + // dlclose(lib); +} + +#define ERROR(x) { printf(x); return x; } + +const char* startErlang(std::string root_dir, std::string log_dir) +{ + ensure_slash(root_dir); + ensure_slash(log_dir); + log_file = log_dir + "elixir.log"; + + std::string boot_file = root_dir + "releases/start_erl.data"; + FILE *fp = fopen(boot_file.c_str(), "rb"); + if (!fp) ERROR("Could not locate start_erl.data"); + + char line_buffer[128]; + size_t read = fread(line_buffer, 1, sizeof(line_buffer) - 1, fp); + fclose(fp); + line_buffer[read] = 0; + + char* erts_version = strtok(line_buffer, " "); + if (!erts_version) ERROR("Could not identify erts version in start_erl.data file"); + + char* app_version = strtok(0, " "); + if (!app_version) ERROR("Could not idenfity app version in start_erl.data file"); + + + std::string bin_dir = root_dir + "erts-" + erts_version + "/bin/"; + // keeping it static to keep the environment variable alive + static std::string env_bin_dir = std::string("BINDIR=").append(bin_dir); + char *path = getenv("PATH"); + // keeping it static to keep the environment variable alive + static std::string env_path = std::string("PATH=").append(path).append(":").append(bin_dir); + + chdir(root_dir.c_str()); + putenv((char *)env_bin_dir.c_str()); + putenv((char *)env_path.c_str()); + + start_logger(); + + // does not work on android + // https://android-ndk.narkive.com/iNWj05IV/weak-symbol-linking-when-loading-dynamic-libraries + // https://android.googlesource.com/platform/bionic/+/30b17e32f0b403a97cef7c4d1fcab471fa316340/linker/linker_namespaces.cpp#100 + std::string liberlang = bin_dir + "liberlang.so"; + void* lib = dlopen(liberlang.c_str(), RTLD_NOW | RTLD_GLOBAL); + if (!lib) ERROR("Failed opening liberlang.so\n") + + std::string nif = root_dir + "lib/exqlite-0.5.1/priv/sqlite3_nif.so"; + test_nif(nif); + + startfun = (void (*)(int, char**)) dlsym(lib, "erl_start"); + if (!startfun) ERROR("Failed loading erlang startfun\n") + + std::string config_path = root_dir + "releases/" + app_version + "/sys"; + std::string boot_path = root_dir + "releases/" + app_version + "/start"; + std::string lib_path = root_dir + "lib"; + std::string home_dir; + std::string update_dir = root_dir + "update"; + if (const char* h = getenv("HOME")) { + home_dir = h; + } else { + home_dir = root_dir + "home"; + } + + const char *args[] = { + "test_main", + "-sbwt", + "none", + "--", + "-init_debug", + "-root", + root_dir.c_str(), + "-progname", + "erl", + "--", + "-home", + home_dir.c_str(), // Was without slash / at the end + "--", + "-kernel", + "shell_history", + "enabled", + "--", + // "-heart", + "-pa", + update_dir.c_str(), + "-start_epmd", + "false", + //"-kernel", + //"inet_dist_use_interface", + //"{127,0,0,1}", + "-elixir", + "ansi_enabled", + "true", + "-noshell", + "-s", + "elixir", + "start_cli", + "-mode", + "embedded", + "-config", + config_path.c_str(), + "-boot", + boot_path.c_str(), + "-boot_var", + "RELEASE_LIB", + lib_path.c_str(), + "--", + "--", + "-extra", + "--no-halt", + }; + + // std::thread erlang(run_erlang); + // erlang.detach(); + startfun(sizeof(args) / sizeof(args[0]), (char **)args); + return "ok"; +} + +extern "C" JNIEXPORT jstring JNICALL +Java_io_elixirdesktop_example_Bridge_startErlang( + JNIEnv* env, + jobject /* this */, jstring release_dir, jstring log_dir) { + + std::string home = jstring2string(env, release_dir); + std::string logs = jstring2string(env, log_dir); + return env->NewStringUTF(startErlang(home, logs)); +} + +std::string jstring2string(JNIEnv *env, jstring jStr) { + if (!jStr) + return ""; + + const jclass stringClass = env->GetObjectClass(jStr); + const jmethodID getBytes = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B"); + const jbyteArray stringJbytes = (jbyteArray) env->CallObjectMethod(jStr, getBytes, env->NewStringUTF("UTF-8")); + + size_t length = (size_t) env->GetArrayLength(stringJbytes); + jbyte* pBytes = env->GetByteArrayElements(stringJbytes, NULL); + + std::string ret = std::string((char *)pBytes, length); + env->ReleaseByteArrayElements(stringJbytes, pBytes, JNI_ABORT); + + env->DeleteLocalRef(stringJbytes); + env->DeleteLocalRef(stringClass); + return ret; +} + + +#include + +static int pfd[2]; +static const char *tag = "BEAM"; + +int start_logger() +{ + /* make stdout line-buffered and stderr unbuffered */ + setvbuf(stdout, 0, _IOLBF, 0); + setvbuf(stderr, 0, _IONBF, 0); + + /* create the pipe and redirect stdout and stderr */ + pipe(pfd); + dup2(pfd[1], 1); + dup2(pfd[1], 2); + + std::thread logger(logger_func); + logger.detach(); + return 0; +} + +static void logger_func() +{ + static FILE* fp = 0; + //if (!fp) fp = fopen("erlang.log", "wb"); + if (!fp) fp = fopen(log_file.c_str(), "wb"); + ssize_t rdsz; + char buf[128]; + while((rdsz = read(pfd[0], buf, sizeof buf - 1)) > 0) { + if (fp) { + fwrite(buf, rdsz, 1, fp); + fflush(fp); + } + if(buf[rdsz - 1] == '\n') --rdsz; + buf[rdsz] = 0; /* add null-terminator */ + __android_log_write(ANDROID_LOG_DEBUG, tag, buf); + } +} diff --git a/app/src/main/ic_launcher-playstore.png b/app/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000..18a1e07 Binary files /dev/null and b/app/src/main/ic_launcher-playstore.png differ diff --git a/app/src/main/java/io/elixirdesktop/example/Bridge.kt b/app/src/main/java/io/elixirdesktop/example/Bridge.kt new file mode 100644 index 0000000..f1c0652 --- /dev/null +++ b/app/src/main/java/io/elixirdesktop/example/Bridge.kt @@ -0,0 +1,223 @@ +package io.elixirdesktop.example + +import android.content.Context +import android.os.Build +import android.system.Os +import android.util.Log +import android.webkit.WebSettings +import android.webkit.WebView +import android.webkit.WebViewClient +import org.json.JSONArray +import java.net.ServerSocket +import java.net.Socket +import kotlin.concurrent.thread +import java.io.* +import java.util.zip.ZipInputStream + + +class Bridge(private val applicationContext : Context, private var webview : WebView) { + private val server = ServerSocket(0) + private var lastURL = String() + + init { + Os.setenv("BRIDGE_PORT", server.localPort.toString(), false); + // not really the home directory, but persistent between app upgrades + Os.setenv("HOME", applicationContext.filesDir.absolutePath, false); + + setWebView(webview) + + thread(start = true) { + while (true) { + val socket = server.accept() + println("Client connected: ${socket.inetAddress.hostAddress}") + thread { handle(socket) } + } + } + + + // The possible values are armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips, mips64. + var prefix = "" + for (abi in Build.SUPPORTED_ABIS) { + when (abi) { + "arm64-v8a", "armeabi-v7a" -> { //, "x86_64" -> { + prefix = abi + break + } + "armeabi" -> { + prefix = "armeabi-v7a" + break + } + else -> continue + } + } + + if (prefix == "") { + throw Exception("Could not find any supported ABI") + } + + val runtime = "$prefix-runtime.zip" + Log.d("RUNTIME", runtime) + val lastUpdateTime: Long = applicationContext.packageManager + .getPackageInfo(applicationContext.packageName, 0).lastUpdateTime / 1000 + + thread(start = true) { + val assets = applicationContext.assets.list("") + val releasedir = applicationContext.filesDir.absolutePath + "/build-${lastUpdateTime}" + val donefile = File("$releasedir/done") + if (!donefile.exists()) { + if (unpackZip(releasedir, applicationContext.assets.open("app.zip")) && + unpackZip(releasedir, applicationContext.assets.open(runtime))) { + for (lib in File("$releasedir/lib").list()) { + val parts = lib.split("-") + val name = parts[0] + + val nif = "$prefix-nif-$name.zip" + if (assets!!.contains(nif)) { + unpackZip("$releasedir/lib/$lib/priv", applicationContext.assets.open(nif)) + } + } + + donefile.writeText("$lastUpdateTime") + } + } + + if (!donefile.exists()) { + Log.e("ERROR", "Failed to extract runtime") + throw Exception("Failed to extract runtime") + } else { + var logdir = applicationContext.getExternalFilesDir("")?.path + if (logdir == null) { + logdir = applicationContext.filesDir.absolutePath; + } + Log.d("ERLANG", "Starting beam...") + val ret = startErlang(releasedir, logdir!!) + Log.d("ERLANG", ret) + if (ret != "ok") { + throw Exception(ret) + } + } + } + } + + + private fun unpackZip(releasedir: String, inputStream: InputStream): Boolean + { + Log.d("RELEASEDIR", releasedir) + File(releasedir).mkdirs() + try + { + val zis = ZipInputStream(BufferedInputStream(inputStream)) + val buffer = ByteArray(1024) + + var ze = zis.nextEntry + while (ze != null) + { + val filename = ze.name + + // Need to create directories if not exists, or + // it will generate an Exception... + var fullpath = "$releasedir/$filename" + if (ze.isDirectory) { + Log.d("DIR", fullpath) + File(fullpath).mkdirs() + zis.closeEntry() + ze = zis.nextEntry + continue + } + + Log.d("FILE", fullpath) + + var isBinary = filename.contains("/bin/") || filename.endsWith(".so") + val fout = FileOutputStream(fullpath) + + var count = zis.read(buffer) + while (count != -1) { + fout.write(buffer, 0, count) + count = zis.read(buffer) + } + + fout.close() + + + if (isBinary) { + File(fullpath).setExecutable(true) + } + + zis.closeEntry() + ze = zis.nextEntry + } + + zis.close() + } + catch(e: IOException) + { + e.printStackTrace() + return false + } + + return true + } + + fun setWebView(_webview: WebView) { + webview = _webview + val settings = webview.settings + settings.javaScriptEnabled = true + settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL + settings.useWideViewPort = true + // enable Web Storage: localStorage, sessionStorage + settings.domStorageEnabled = true + // webview.webViewClient = WebViewClient() + if (lastURL.isNotBlank()) { + webview.post { webview.loadUrl(lastURL) } + } + } + + + fun getLocalPort(): Int { + return server.localPort; + } + + private fun handle(socket: Socket) { + val reader = DataInputStream(BufferedInputStream((socket.getInputStream()))) + val writer = DataOutputStream(socket.getOutputStream()) + val ref = ByteArray(8); + + while (true) { + val length = reader.readInt(); + reader.readFully(ref); + var data = ByteArray(length - ref.size); + reader.readFully(data) + + println("Parsing:: ${String(data)}") + + val json = JSONArray(String(data)) + + //val module = json.getString(0); + val method = json.getString(1); + val args = json.getJSONArray(2); + + if (method == ":loadURL") { + lastURL = args.getString(1) + webview.post { webview.loadUrl(lastURL) } + } + + val response = ref + "use_mock".toByteArray() + writer.writeInt(response.size) + writer.write(response) + } + } + + + /** + * A native method that is implemented by the 'native-lib' native library, + * which is packaged with this application. + */ + external fun startErlang(releaseDir: String, logdir: String): String + + companion object { + // Used to load the 'native-lib' library on application startup. + init { + System.loadLibrary("native-lib") + } + } +} \ No newline at end of file diff --git a/app/src/main/java/io/elixirdesktop/example/MainActivity.kt b/app/src/main/java/io/elixirdesktop/example/MainActivity.kt new file mode 100644 index 0000000..f18c3ca --- /dev/null +++ b/app/src/main/java/io/elixirdesktop/example/MainActivity.kt @@ -0,0 +1,46 @@ +package io.elixirdesktop.example + +import android.app.Activity +import android.os.Bundle +import android.util.Base64 +import android.view.View +import io.elixirdesktop.example.databinding.ActivityMainBinding +import java.io.* +import java.util.* +import android.webkit.WebView + +import android.webkit.WebViewClient + + + + +class MainActivity : Activity() { + private lateinit var binding: ActivityMainBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + binding.browser.webViewClient = object : WebViewClient() { + override fun onPageFinished(view: WebView, url: String) { + if (binding.browser.visibility != View.VISIBLE) { + binding.browser.visibility = View.VISIBLE + binding.splash.visibility = View.GONE + } + } + } + + if (bridge != null) { + // This happens on re-creation of the activity e.g. after rotating the screen + bridge!!.setWebView(binding.browser) + } else { + // This happens only on the first time when starting the app + bridge = Bridge(applicationContext, binding.browser) + } + } + + companion object { + var bridge: Bridge? = null + } +} \ No newline at end of file diff --git a/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..e7139f2 --- /dev/null +++ b/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..1031e64 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,31 @@ + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..7353dbd --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..7353dbd --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/values-night/themes.xml b/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..5547b15 --- /dev/null +++ b/app/src/main/res/values-night/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/ic_launcher_background.xml b/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..5286f8c --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + TodoApp + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..3bf0770 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,16 @@ + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..e9a48fc --- /dev/null +++ b/build.gradle @@ -0,0 +1,27 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + ext.kotlin_version = "1.5.0" + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:7.0.2' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.30" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + mavenCentral() + jcenter() // Warning: this repository is going to shut down soon + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..2521752 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,19 @@ +# 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 +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bcef597 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Jun 22 14:56:47 CEST 2021 +distributionBase=GRADLE_USER_HOME +distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip +distributionPath=wrapper/dists +zipStorePath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..cccdd3d --- /dev/null +++ b/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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/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/icon.jpg b/icon.jpg new file mode 100644 index 0000000..bca4adf Binary files /dev/null and b/icon.jpg differ diff --git a/run_mix b/run_mix new file mode 100755 index 0000000..65d8ab6 --- /dev/null +++ b/run_mix @@ -0,0 +1,22 @@ +#!/bin/bash + +BASE=`pwd` +export MIX_ENV=prod +export MIX_TARGET=android + +if [ ! -d "elixir-app" ]; then + git clone https://github.com/elixir-desktop/desktop-example-app.git elixir-app + cd elixir-app + mix deps.get +else + cd elixir-app +fi + +if [ ! -d "assets/node_modules" ]; then + cd assets && npm i && npm run deploy && cd .. && mix phx.digest +fi + +mix release --overwrite && \ + cd _build/prod/rel/todo_app && \ + zip -r $BASE/src/main/assets/app.zip lib/ releases/ --exclude "*.so" + diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..11a6f8b --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = "TodoApp" +include ':app'