Added README.md

This commit is contained in:
Dominic Letz 2021-08-19 17:48:06 +02:00
parent c1e8fcf915
commit 524ee3824e
45 changed files with 1430 additions and 0 deletions

17
.gitignore vendored Normal file
View file

@ -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

3
.idea/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

1
.idea/.name Normal file
View file

@ -0,0 +1 @@
TodoApp

View file

@ -0,0 +1,123 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
<codeStyleSettings language="XML">
<option name="FORCE_REARRANGE_MODE" value="1" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>
<arrangement>
<rules>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:android</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>xmlns:.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:id</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*:name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>name</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>style</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>^$</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>http://schemas.android.com/apk/res/android</XML_NAMESPACE>
</AND>
</match>
<order>ANDROID_ATTRIBUTE_ORDER</order>
</rule>
</section>
<section>
<rule>
<match>
<AND>
<NAME>.*</NAME>
<XML_ATTRIBUTE />
<XML_NAMESPACE>.*</XML_NAMESPACE>
</AND>
</match>
<order>BY_NAME</order>
</rule>
</section>
</rules>
</arrangement>
</codeStyleSettings>
<codeStyleSettings language="kotlin">
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</codeStyleSettings>
</code_scheme>
</component>

View file

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="USE_PER_PROJECT_SETTINGS" value="true" />
</state>
</component>

6
.idea/compiler.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="11" />
</component>
</project>

20
.idea/gradle.xml Normal file
View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
<option name="resolveModulePerSourceSet" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>

30
.idea/jarRepositories.xml Normal file
View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="MavenRepo" />
<option name="name" value="MavenRepo" />
<option name="url" value="https://repo.maven.apache.org/maven2/" />
</remote-repository>
<remote-repository>
<option name="id" value="BintrayJCenter" />
<option name="name" value="BintrayJCenter" />
<option name="url" value="https://jcenter.bintray.com/" />
</remote-repository>
<remote-repository>
<option name="id" value="Google" />
<option name="name" value="Google" />
<option name="url" value="https://dl.google.com/dl/android/maven2/" />
</remote-repository>
</component>
</project>

20
.idea/misc.xml Normal file
View file

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DesignSurface">
<option name="filePathToZoomLevelMap">
<map>
<entry key="app/src/main/res/drawable-v24/ic_launcher_foreground.xml" value="0.3416666666666667" />
<entry key="app/src/main/res/drawable/ic_launcher_background.xml" value="0.3416666666666667" />
<entry key="app/src/main/res/layout/activity_main.xml" value="0.1752786220871327" />
<entry key="app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml" value="0.20625" />
<entry key="app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml" value="0.20625" />
</map>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>

8
.idea/vcs.xml Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/app/elixir-app" vcs="Git" />
<mapping directory="$PROJECT_DIR$/app/elixir-app/deps/desktop" vcs="Git" />
</component>
</project>

22
LICENSE.md Normal file
View file

@ -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.

48
README.md Normal file
View file

@ -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`.

BIN
android_elixir.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

BIN
app.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

1
app/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/build

70
app/build.gradle Normal file
View file

@ -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'
}

21
app/proguard-rules.pro vendored Normal file
View file

@ -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

View file

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.elixirdesktop.example">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:usesCleartextTraffic="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Default">
<activity android:name="io.elixirdesktop.example.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -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} )

View file

@ -0,0 +1,216 @@
#include <jni.h>
#include <string>
#include <thread>
#include <unistd.h>
#include <dlfcn.h>
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 <android/log.h>
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);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

View file

@ -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")
}
}
}

View file

@ -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
}
}

View file

@ -0,0 +1,57 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<group android:scaleX="0.15452316"
android:scaleY="0.15452316"
android:translateX="26.46"
android:translateY="31.547009">
<path
android:pathData="m289.562,14.25c-5.663,0 -11.327,2.17 -15.667,6.509L145.175,149.48 86.891,91.195c-8.679,-8.679 -22.654,-8.679 -31.333,0l-39.231,39.231c-8.679,8.679 -8.679,22.653 0,31.332l73.944,73.945c0.002,0.002 0.004,0.004 0.007,0.007l37.415,37.415c8.679,8.679 22.654,8.679 31.333,0L198.257,233.894 342.645,89.508c8.679,-8.679 8.679,-22.654 0,-31.333L305.229,20.759c-4.34,-4.34 -10.003,-6.509 -15.666,-6.509z"
android:strokeLineJoin="miter"
android:strokeWidth="4.9847827"
android:strokeColor="#00000000"
android:fillType="nonZero"
android:strokeLineCap="butt">
<aapt:attr name="android:fillColor">
<gradient
android:gradientRadius="151.22067"
android:centerX="152.22423"
android:centerY="106.852066"
android:type="radial">
<item android:offset="0" android:color="#FF000000"/>
<item android:offset="1" android:color="#00000000"/>
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M125.555,264.573L14.189,153.206A22.156,22.156 90,0 1,14.189 121.873L53.42,82.642A22.156,22.156 90,0 1,84.753 82.642L196.119,194.009A22.156,22.156 0,0 1,196.119 225.342L156.888,264.573A22.156,22.156 0,0 1,125.555 264.573z"
android:strokeLineJoin="miter"
android:strokeWidth="4.9847827"
android:fillColor="#421658"
android:strokeColor="#00000000"
android:fillType="nonZero"
android:strokeLineCap="butt"/>
<path
android:pathData="M88.14,195.825L271.758,12.207A22.156,22.156 90,0 1,303.091 12.207L340.506,49.622A22.156,22.156 90,0 1,340.506 80.955L156.888,264.573A22.156,22.156 0,0 1,125.555 264.573L88.14,227.158A22.156,22.156 90,0 1,88.14 195.825z"
android:strokeLineJoin="miter"
android:strokeWidth="4.9847827"
android:strokeColor="#00000000"
android:fillType="nonZero"
android:strokeLineCap="butt">
<aapt:attr name="android:fillColor">
<gradient
android:startY="247.62767"
android:startX="105.08517"
android:endY="29.152084"
android:endX="323.56076"
android:type="linear">
<item android:offset="0" android:color="#FF61496D"/>
<item android:offset="1" android:color="#FF8B8290"/>
</gradient>
</aapt:attr>
</path>
</group>
</vector>

View file

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/splash"
android:layout_width="0dp"
android:layout_height="0dp"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher_foreground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<WebView
android:id="@+id/browser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</WebView>
</androidx.constraintlayout.widget.ConstraintLayout>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

View file

@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Default" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_200</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
</resources>

View file

@ -0,0 +1,3 @@
<resources>
<string name="app_name">TodoApp</string>
</resources>

View file

@ -0,0 +1,16 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Default" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>
<item name="colorOnPrimary">@color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/teal_200</item>
<item name="colorSecondaryVariant">@color/teal_700</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

27
build.gradle Normal file
View file

@ -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
}

19
gradle.properties Normal file
View file

@ -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

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View file

@ -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

172
gradlew vendored Executable file
View file

@ -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" "$@"

84
gradlew.bat vendored Normal file
View file

@ -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

BIN
icon.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

22
run_mix Executable file
View file

@ -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"

2
settings.gradle Normal file
View file

@ -0,0 +1,2 @@
rootProject.name = "TodoApp"
include ':app'