Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
41 changes: 40 additions & 1 deletion Demo/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ let package = Package(
dependencies: [
.package(
path: "../"
),
.package(
url: "https://github.com/swiftlang/swift-java.git",
branch: "main"
),
.package(
url: "https://github.com/swift-android-sdk/swift-android-native.git",
from: "2.1.0"
)
],
targets: [
Expand All @@ -25,12 +33,43 @@ let package = Package(
.product(
name: "AndroidKit",
package: "Android"
)
),
"CatalogBridge"
],
path: "./app/src/main/swift",
swiftSettings: [
.swiftLanguageMode(.v5)
]
),
.target(
name: "CatalogBridge",
dependencies: [
.product(
name: "SwiftJava",
package: "swift-java"
),
.product(
name: "AndroidKit",
package: "Android"
),
.product(
name: "AndroidContext",
package: "swift-android-native"
)
],
path: "./app/src/main/swift-bridge/CatalogBridge",
exclude: [
"swift-java.config"
],
swiftSettings: [
.swiftLanguageMode(.v5)
],
plugins: [
.plugin(
name: "JExtractSwiftPlugin",
package: "swift-java"
)
]
)
]
)
117 changes: 108 additions & 9 deletions Demo/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,93 @@ plugins {
alias(libs.plugins.kotlin.compose)
}

// ---------------------------------------------------------------------------
// swift-java (jextract, JNI mode) integration
//
// The Swift package (SwiftAndroidApp + CatalogBridge) is cross-compiled to
// native `.so`s with the official Swift Android SDK; the `JExtractSwiftPlugin`
// emits the Java JNI bindings as a side effect of `swift build`. Gradle then
// adds the generated Java + SwiftKitCore runtime sources to the source set and
// stages every required `.so` into `jniLibs`.
// ---------------------------------------------------------------------------

val swiftPackageRoot: File = rootProject.projectDir
val androidTriple = "aarch64-unknown-linux-android28"
val swiftAbi = "arm64-v8a"
val userHome: String = System.getProperty("user.home")

// Configuration the Swift package is cross-compiled with, independent of the
// Android build type. Override with `-PswiftBuildConfig=release`.
val swiftBuildConfig: String = (findProperty("swiftBuildConfig") as String?) ?: "debug"

// Locates both the toolchain and the matching Android SDK artifactbundle.
val swiftToolchainVersion: String = (findProperty("swiftToolchainVersion") as String?) ?: "6.3.3"

// The Android SDK's prebuilt Swift modules require the matching swift.org
// toolchain. Override with `-PswiftBin=/path/to/swift` if installed elsewhere.
val swiftBin: String = (findProperty("swiftBin") as String?)
?: "$userHome/Library/Developer/Toolchains/swift-$swiftToolchainVersion-RELEASE.xctoolchain/usr/bin/swift"

// swift-java's `enableJavaCallbacks` feature runs its own internal Gradle
// sub-build to compile the generated Java callback interfaces, requiring a
// modern JDK — independent of whatever JDK runs *this* Gradle build.
// Override with `-PcallbacksJdkHome=/path/to/jdk`.
val callbacksJdkHome: String = (findProperty("callbacksJdkHome") as String?)
?: "/opt/homebrew/opt/openjdk@25"

// SwiftPM plugin output convention: `outputs/<package-dir-lowercased>/<TargetName>/...`.
val generatedJavaDir = File(swiftPackageRoot, ".build/plugins/outputs/demo/CatalogBridge/destination/JExtractSwiftPlugin/src/generated/java")
val swiftKitCoreDir = File(swiftPackageRoot, ".build/checkouts/swift-java/SwiftKitCore/src/main/java")
val swiftBuildDir = File(swiftPackageRoot, ".build/$androidTriple/$swiftBuildConfig")
val swiftAndroidRuntimeDir = File(
(findProperty("swiftAndroidRuntimeDir") as String?)
?: "$userHome/Library/org.swift.swiftpm/swift-sdks/swift-${swiftToolchainVersion}-RELEASE_android.artifactbundle/swift-android/swift-resources/usr/lib/swift-aarch64/android"
)

// Supplies libc++_shared.so, which every Swift Android binary links against.
val ndkRoot = File(
(findProperty("ndkRoot") as String?)
?: System.getenv("ANDROID_NDK_HOME")
?: System.getenv("ANDROID_NDK_ROOT")
?: "$userHome/Library/Android/sdk/ndk/27.2.12479018"
)

// Cross-compile the Swift package + generate the JNI Java bindings.
val jextract = tasks.register<Exec>("jextract") {
workingDir = swiftPackageRoot
environment("JAVA_HOME", callbacksJdkHome)
commandLine(
swiftBin, "build",
"--swift-sdk", androidTriple,
"-c", swiftBuildConfig,
"--disable-sandbox"
)
outputs.dir(generatedJavaDir)
outputs.file(File(swiftBuildDir, "libSwiftAndroidApp.so"))
// `swift build` is incremental itself; let it decide what is stale.
outputs.upToDateWhen { false }
}

// Stage the cross-compiled libraries, the swift-java runtime, the Swift
// Android runtime and libc++_shared into jniLibs so they end up in the APK.
val stageJniLibs = tasks.register<Copy>("stageJniLibs") {
dependsOn(jextract)
into(layout.projectDirectory.dir("src/main/jniLibs/$swiftAbi"))
from(swiftBuildDir) {
// Every dynamic library product built by the package graph — anything
// less leaves a dangling `dlopen` at runtime.
include("*.so")
}
from(swiftAndroidRuntimeDir) {
include("*.so")
// Test-only runtime libraries are not needed by the app.
exclude("*Testing*", "libXCTest.so")
}
from(File(ndkRoot, "toolchains/llvm/prebuilt/darwin-x86_64/sysroot/usr/lib/aarch64-linux-android")) {
include("libc++_shared.so")
}
}

android {
namespace = "com.pureswift.swiftandroid"
compileSdk = 35
Expand All @@ -16,7 +103,7 @@ android {
versionName = "1.0"
ndk {
//noinspection ChromeOsAbiSupport
abiFilters += listOf("arm64-v8a")
abiFilters += listOf(swiftAbi)
}
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
Expand All @@ -40,6 +127,18 @@ android {
buildFeatures {
compose = true
}

// Generated JNI bindings + the SwiftKitCore Java runtime (consumed as
// source, since swift-java is not published to Maven).
sourceSets["main"].java.srcDir(generatedJavaDir)
sourceSets["main"].java.srcDir(swiftKitCoreDir)
// These two annotations pull in `jdk.jfr` (Java Flight Recorder), which is
// unavailable on Android; the JNI bindings don't reference them.
sourceSets["main"].java.filter.exclude(
"org/swift/swiftkit/core/annotations/ThreadSafe.java",
"org/swift/swiftkit/core/annotations/Unsigned.java"
)

packaging {
resources {
excludes += listOf("/META-INF/{AL2.0,LGPL2.1}")
Expand All @@ -54,16 +153,16 @@ android {
}
}

// Compile native Swift code for the demo app with `skip android build`.
val buildSwift by tasks.registering(Exec::class) {
group = "build"
description = "Build native Swift sources for Android"
workingDir(rootProject.projectDir)
commandLine("bash", "build-swift.sh")
// Ensure Swift is built + bindings generated + libs staged before Java or
// Kotlin compiles (Kotlin also consumes the generated Java bindings).
tasks.withType<JavaCompile>().configureEach {
dependsOn(jextract)
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
dependsOn(jextract)
}

tasks.named("preBuild") {
dependsOn(buildSwift)
dependsOn(stageJniLibs)
}

dependencies {
Expand Down
3 changes: 3 additions & 0 deletions Demo/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.NFC" />

<application
android:name=".Application"
Expand Down
13 changes: 13 additions & 0 deletions Demo/app/src/main/java/com/pureswift/swiftandroid/Application.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.pureswift.swiftandroid

import android.util.Log
import com.example.swift.HelloSubclass
import com.pureswift.swiftandroid.bridge.CatalogBridge

class Application: android.app.Application() {

Expand All @@ -11,6 +13,17 @@ class Application: android.app.Application() {
override fun onCreate() {
super.onCreate()
onCreateSwift()
testCatalogBridge()
}

/// Smoke test for the jextract JNI bridge: a Java->Swift downcall and a
/// Swift->Java callback (closure/Runnable block).
private fun testCatalogBridge() {
val count = CatalogBridge.catalogEntryCount()
Log.d("CatalogBridge", "catalogEntryCount() = $count")
CatalogBridge.runBlock {
Log.d("CatalogBridge", "runBlock callback invoked from Swift")
}
}

private external fun onCreateSwift()
Expand Down
24 changes: 0 additions & 24 deletions Demo/app/src/main/java/com/pureswift/swiftandroid/Fragment.kt

This file was deleted.

This file was deleted.

Loading
Loading