Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Android (Kotlin) app template #1867

Merged
merged 17 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/cli/src/__tests__/e2e/p1/create.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Commands:
wasm [options] <language> <name> Create a Polywrap wasm wrapper. langs:
assemblyscript, rust, golang, interface
app [options] <language> <name> Create a Polywrap application. langs:
typescript
typescript, android
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can there be vanilla kotlin or something? Just wondering since the template here is android specific

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could create another template that is not Android, sure. We have always treated Kotlin as a means of targeting android users, so I think having an Android template makes more sense.

plugin [options] <language> <name> Create a Polywrap plugin. langs:
typescript, rust, python
template [options] <url> <name> Download template from a URL. formats:
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const urlStr = intlMsg.commands_create_options_t_url();

export const supportedLangs = {
wasm: ["assemblyscript", "rust", "golang", "interface"] as const,
app: ["typescript"] as const,
app: ["typescript", "android"] as const,
plugin: ["typescript", "rust", "python"] as const,
};

Expand Down
15 changes: 15 additions & 0 deletions packages/templates/app/android/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
*.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
1 change: 1 addition & 0 deletions packages/templates/app/android/app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
107 changes: 107 additions & 0 deletions packages/templates/app/android/app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.serialization")
id("com.github.node-gradle.node")
}

android {
namespace = "io.template.polywrap"
compileSdk = 33

defaultConfig {
applicationId = "io.template.polywrap"
minSdk = 24
targetSdk = 33
versionCode = 1
versionName = "1.0"

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary = true
}
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.4.8"
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}

dependencies {
// polywrap client
implementation("io.polywrap:polywrap-client:0.11.0-SNAPSHOT")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.5.1")
// polywrap logger plugin
implementation("io.polywrap.plugins:logger:0.10.2")
implementation("com.github.tony19:logback-android:3.0.0")

// ui
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1")

// defaults
implementation("androidx.core:core-ktx:1.10.1")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1")
implementation("androidx.activity:activity-compose:1.7.2")
implementation(platform("androidx.compose:compose-bom:2023.03.00"))
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-graphics")
implementation("androidx.compose.ui:ui-tooling-preview")
implementation("androidx.compose.material3:material3")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00"))
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
debugImplementation("androidx.compose.ui:ui-tooling")
debugImplementation("androidx.compose.ui:ui-test-manifest")
}

// set up NodeJS to run the Polywrap CLI
// NodeJS installation will be stored in gradle cache
node {
val nullString: String? = null
distBaseUrl.set(nullString)
// Whether to download and install a specific Node.js version or not
// If false, it will use the globally installed Node.js
// If true, it will download node using above parameters
// Note that npm is bundled with Node.js
download.set(true)
}

tasks.register<com.github.gradle.node.npm.task.NpxTask>("codegen") {
group = "polywrap"
dependsOn(tasks.npmInstall)
command.set("polywrap")
args.set(listOf("codegen",
"-m", "$rootDir/polywrap.yaml",
"-g", "$projectDir/src/main/java/wrap"
))
}

tasks.withType<KotlinCompile> { dependsOn("codegen") }
21 changes: 21 additions & 0 deletions packages/templates/app/android/app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.template.polywrap

import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4

import org.junit.Test
import org.junit.runner.RunWith

import org.junit.Assert.*

/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("io.template.polywrap", appContext.packageName)
}
}
28 changes: 28 additions & 0 deletions packages/templates/app/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Template"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Template">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
18 changes: 18 additions & 0 deletions packages/templates/app/android/app/src/main/assets/logback.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<configuration
xmlns="https://tony19.github.io/logback-android/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://tony19.github.io/logback-android/xml https://cdn.jsdelivr.net/gh/tony19/logback-android/logback.xsd"
>
<appender name="logcat" class="ch.qos.logback.classic.android.LogcatAppender">
<tagEncoder>
<pattern>%logger{12}</pattern>
</tagEncoder>
<encoder>
<pattern>[%-20thread] %msg</pattern>
</encoder>
</appender>

<root level="DEBUG">
<appender-ref ref="logcat" />
</root>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package io.template.polywrap

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.viewmodel.compose.viewModel
import io.template.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
PolywrapDemo()
}
}
}
}
}

@Composable
fun PolywrapDemo(demoViewModel: PolywrapDemoViewModel = viewModel()) {
Button(onClick = { demoViewModel.polywrapDemo() }) {
Text(text = "Hello Polywrap!")
}
}

@Preview(showBackground = true)
@Composable
fun PolywrapDemoPreview() {
MyApplicationTheme {
PolywrapDemo()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package io.template.polywrap

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import io.polywrap.client.PolywrapClient
import io.polywrap.configBuilder.polywrapClient
import io.polywrap.plugins.logger.loggerPlugin
import kotlinx.coroutines.launch
import wrap.Ethereum
import wrap.EthereumArgsEncodeParams
import wrap.Logging
import wrap.LoggingArgsLog
import wrap.LoggingLogLevel

class PolywrapDemoViewModel: ViewModel() {

// we can create a custom client
val loggerInterfaceUri = "wrapscan.io/polywrap/logger@1.0"
private val client = polywrapClient {
addDefaults()
setPackage("plugin/logger" to loggerPlugin(null))
addInterfaceImplementation(loggerInterfaceUri, "plugin/logger")
setRedirect(loggerInterfaceUri to "plugin/logger")
}

// and use the custom client to create an SDK class instance
private val logger = Logging(client)
// the client can be shared across SDK instances
private val ethereum = Ethereum(client)

// Because their lifetimes are tied to the client, SDK instances work well as extension properties
val PolywrapClient.eth
get() = ethereum

// or we can create an SDK class instance with a new client using default configuration
private val defaultEth = Ethereum()

fun polywrapDemo() = viewModelScope.launch {
Log.i("polywrapDemo","Invoking: Logging.info(...)")

logger.log(LoggingArgsLog(LoggingLogLevel.INFO, "Hello there")).getOrThrow()
logger.log(LoggingArgsLog(LoggingLogLevel.INFO, "Hello again")).getOrThrow()
logger.log(LoggingArgsLog(LoggingLogLevel.INFO, "One last time...")).getOrThrow()

Log.i("polywrapDemo","Invoking: Ethereum.encodeParams(...)")

val encodeArgs = EthereumArgsEncodeParams(
types = listOf("address", "uint256"),
values = listOf("0xB1B7586656116D546033e3bAFF69BFcD6592225E", "500")
)
val result = client.eth.encodeParams(encodeArgs)

if (result.isSuccess) {
println("Ethereum.encodeParams:\n${result.getOrThrow()}")
} else {
println("Error - Ethereum.encodeParams:\n${result.exceptionOrNull()}")
}
}

override fun onCleared() {
super.onCleared()
// remember to close clients to prevent memory leaks when you're done using them
client.close()
defaultEth.client.close()
}
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package io.template.myapplication.ui.theme

import androidx.compose.ui.graphics.Color

val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)

val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
Loading
Loading