Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Add the Android app: pairing, home, settings and background connection
Bee02d0cf49b945
diff --git a/Cargo.toml b/Cargo.tomlindex 7a4bf3d..f8d90ee 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -63,3 +63,9 @@ all = { level = "warn", priority = -1 }lto = "thin"codegen-units = 1strip = "symbols"++# Android: release optimizations, but symbols are kept so UniFFI can read its+# metadata from the library; the Android build strips them when packaging.+[profile.android]+inherits = "release"+strip = "debuginfo"diff --git a/android/README.md b/android/README.mdnew file mode 100644index 0000000..4931863--- /dev/null+++ b/android/README.md@@ -0,0 +1,46 @@+# Nectarlink for Android++Kotlin + Jetpack Compose (Material 3) on top of the shared Rust core,+called through UniFFI (`core/nectarlink-ffi`).++## Build++Needs the Android SDK (platform 37, NDK 30.0.16248370), Rust with the+Android targets, and `cargo-ndk`:++```+rustup target add aarch64-linux-android x86_64-linux-android+cargo install cargo-ndk+```++Then, from `android/`:++```+./gradlew assembleDebug # phones + x86_64 emulator+./gradlew assembleDebug -Pnectarlink.abis=x86_64 # emulator only (faster)+./gradlew testDebugUnitTest+```++Gradle builds the core with cargo-ndk (cargo profile `android`: release+optimizations, symbols kept for UniFFI and stripped when packaging) and+generates the Kotlin bindings from the built library. Both are generated+sources; nothing generated is checked in except the theme tokens+(`ui/theme/Tokens.kt`, from `cargo xtask tokens`).++## Layout++- `core/`: the bridge to the Rust core. `Core` owns the node and folds its+ events into `CoreState` (a pure reducer, unit-tested); `KeystoreKeyProtector`+ encrypts the identity key with a non-exportable Android Keystore key;+ `Ringer` rings on the alarm stream; battery and network monitors feed the+ core (Android doesn't let native code watch the network).+- `service/ConnectionService`: a "connected device" foreground service that+ keeps the phone reachable and holds the Wi-Fi multicast lock local+ discovery needs.+- `ui/`: pairing (QR scanner with CameraX + ZXing, no Google Play services;+ nearby pairing with a 6-digit code), home and settings. Bloom uses+ Material You colors from the wallpaper on Android 12+.++The identity lives in `noBackupFilesDir`, so it's never restored onto+another phone. `nectarlink://pair?...` links (a PC's QR code scanned with any+camera app) open the app and pair.diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.ktsnew file mode 100644index 0000000..d076164--- /dev/null+++ b/android/app/build.gradle.kts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: GPL-3.0-or-later+import javax.inject.Inject++plugins {+ alias(libs.plugins.android.application)+ alias(libs.plugins.kotlin.compose)+}++android {+ namespace = "app.nectarlink.android"+ compileSdk = 37+ ndkVersion = "30.0.16248370"++ defaultConfig {+ applicationId = "app.nectarlink"+ minSdk = 26+ targetSdk = 37+ versionCode = 1+ versionName = "0.0.1"+ }++ buildTypes {+ release {+ isMinifyEnabled = true+ isShrinkResources = true+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")+ }+ }++ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }++ buildFeatures {+ compose = true+ buildConfig = true+ }++}++// ---- The Rust core (nectarlink-ffi) ----+//+// Built with cargo-ndk for the ABIs in `nectarlink.abis` (default: devices+// and the x86_64 emulator), then UniFFI generates the Kotlin bindings from+// the built library. Both are registered as generated sources, so AGP runs+// them when needed. Rust is always built in release: debug builds of the+// core are large and slow.++/** Builds the Rust core into `<outputDir>/<abi>/libnectarlink_ffi.so`. */+abstract class CargoNdkBuild : DefaultTask() {+ @get:Inject abstract val exec: ExecOperations+ @get:Input abstract val abis: ListProperty<String>+ @get:InputDirectory @get:PathSensitive(PathSensitivity.RELATIVE) abstract val crates: DirectoryProperty+ @get:InputFile @get:PathSensitive(PathSensitivity.NONE) abstract val lockFile: RegularFileProperty+ @get:Internal abstract val workspace: DirectoryProperty+ @get:Internal abstract val ndk: DirectoryProperty+ @get:OutputDirectory abstract val outputDir: DirectoryProperty++ @TaskAction+ fun build() {+ exec.exec {+ workingDir = workspace.get().asFile+ environment("ANDROID_NDK_HOME", ndk.get().asFile.absolutePath)+ commandLine(+ buildList {+ addAll(listOf("cargo", "ndk", "--platform", "26", "-o", outputDir.get().asFile.path))+ abis.get().forEach { addAll(listOf("-t", it)) }+ addAll(listOf("build", "--profile", "android", "--locked", "-p", "nectarlink-ffi"))+ },+ )+ }+ }+}++/** Generates the Kotlin bindings from a built core library. */+abstract class UniffiBindgen : DefaultTask() {+ @get:Inject abstract val exec: ExecOperations+ @get:InputFile @get:PathSensitive(PathSensitivity.NONE) abstract val library: RegularFileProperty+ @get:Internal abstract val workspace: DirectoryProperty+ @get:OutputDirectory abstract val outputDir: DirectoryProperty++ @TaskAction+ fun generate() {+ exec.exec {+ workingDir = workspace.get().asFile+ commandLine(+ "cargo", "run", "--quiet", "--locked", "-p", "nectarlink-ffi", "--features", "bindgen",+ "--bin", "uniffi-bindgen", "--", "generate", "--library", library.get().asFile.path,+ "--language", "kotlin", "--no-format", "--out-dir", outputDir.get().asFile.path,+ )+ }+ }+}++val workspaceDir: Directory = rootProject.layout.projectDirectory.dir("..")+val rustAbis: List<String> =+ (findProperty("nectarlink.abis") as String?)?.split(",")?.map(String::trim) ?: listOf("arm64-v8a", "x86_64")++androidComponents {+ onVariants { variant ->+ val suffix = variant.name.replaceFirstChar(Char::uppercase)+ val cargo = tasks.register<CargoNdkBuild>("cargoNdkBuild$suffix") {+ description = "Builds the Rust core for Android."+ abis.set(rustAbis)+ crates.set(workspaceDir.dir("core"))+ lockFile.set(workspaceDir.file("Cargo.lock"))+ workspace.set(workspaceDir)+ ndk.set(androidComponents.sdkComponents.ndkDirectory)+ }+ val bindgen = tasks.register<UniffiBindgen>("uniffiBindgen$suffix") {+ description = "Generates the Kotlin bindings for the Rust core."+ library.set(cargo.flatMap { it.outputDir.file("${rustAbis.first()}/libnectarlink_ffi.so") })+ workspace.set(workspaceDir)+ }+ variant.sources.jniLibs?.addGeneratedSourceDirectory(cargo, CargoNdkBuild::outputDir)+ variant.sources.java?.addGeneratedSourceDirectory(bindgen, UniffiBindgen::outputDir)+ }+}++dependencies {+ implementation(platform(libs.compose.bom))+ implementation(libs.compose.ui)+ implementation(libs.compose.material3)+ implementation(libs.compose.ui.tooling.preview)+ debugImplementation(libs.compose.ui.tooling)+ implementation(libs.androidx.core.ktx)+ implementation(libs.androidx.activity.compose)+ implementation(libs.androidx.lifecycle.runtime.compose)+ implementation(libs.androidx.lifecycle.viewmodel.compose)+ implementation(libs.androidx.lifecycle.service)+ implementation(libs.kotlinx.coroutines.android)+ implementation(libs.camerax.camera2)+ implementation(libs.camerax.lifecycle)+ implementation(libs.camerax.view)+ implementation(libs.zxing.core)+ // UniFFI's Kotlin bindings call the core through JNA.+ implementation(libs.jna) { artifact { type = "aar" } }+ testImplementation(libs.junit)+}diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pronew file mode 100644index 0000000..ff7078e--- /dev/null+++ b/android/app/proguard-rules.pro@@ -0,0 +1,6 @@+# SPDX-License-Identifier: GPL-3.0-or-later+# JNA and the UniFFI bindings are reached through reflection and native code.+-keep class com.sun.jna.** { *; }+-keep class * implements com.sun.jna.** { *; }+-dontwarn java.awt.**+-keep class app.nectarlink.core.** { *; }diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..83b9372--- /dev/null+++ b/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,55 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <!-- Talking to paired PCs on the local network. -->+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+ <!-- Local discovery (mDNS) needs multicast on Wi-Fi. -->+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />+ <!-- Staying reachable in the background. -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <!-- Scanning the pairing QR code. -->+ <uses-permission android:name="android.permission.CAMERA" />+ <!-- Find my phone. -->+ <uses-permission android:name="android.permission.VIBRATE" />++ <uses-feature android:name="android.hardware.camera.any" android:required="false" />++ <application+ android:name=".NectarlinkApplication"+ 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:supportsRtl="true"+ android:theme="@style/Theme.Nectarlink">++ <activity+ android:name=".ui.MainActivity"+ android:exported="true"+ android:launchMode="singleTask"+ android:windowSoftInputMode="adjustResize">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ <!-- Pairing links: a PC's QR code scanned with any camera app. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="nectarlink" android:host="pair" />+ </intent-filter>+ </activity>++ <service+ android:name=".service.ConnectionService"+ android:exported="false"+ android:foregroundServiceType="connectedDevice" />+ </application>+</manifest>diff --git a/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt b/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.ktnew file mode 100644index 0000000..45a3896--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/NectarlinkApplication.kt@@ -0,0 +1,20 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android++import android.app.Application+import app.nectarlink.android.core.Core+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob++/** Starts the core with the process and keeps it for the app's lifetime. */+class NectarlinkApplication : Application() {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)++ val core: Core by lazy { Core(this, scope) }++ override fun onCreate() {+ super.onCreate()+ core.start()+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktnew file mode 100644index 0000000..1146348--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt@@ -0,0 +1,196 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.core++import android.content.Context+import android.net.wifi.WifiManager+import android.util.Log+import app.nectarlink.android.BuildConfig+import app.nectarlink.core.Event+import app.nectarlink.core.EventListener+import app.nectarlink.core.NectarlinkException+import app.nectarlink.core.NectarlinkNode+import app.nectarlink.core.NodeOptions+import app.nectarlink.core.PairingFailure+import app.nectarlink.core.PowerLevel+import app.nectarlink.core.initLogging+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asSharedFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch++/**+ * The app's single connection to `nectarlink-core`. Owns the node, folds+ * its events into [state], feeds it the phone's battery and network+ * changes, and runs commands for the UI.+ */+class Core(context: Context, private val scope: CoroutineScope) : EventListener {+ private val context = context.applicationContext+ private val ringer = Ringer(this.context)+ private val _state = MutableStateFlow(CoreState())+ private val _messages = MutableSharedFlow<String>(extraBufferCapacity = 8)+ private var node: NectarlinkNode? = null+ private var startJob: Job? = null+ private var networkChange: Job? = null++ private val battery = BatteryMonitor(this.context) { battery ->+ node?.let { scope.launch { it.updateBattery(battery) } }+ }+ private val network = NetworkMonitor(this.context) {+ // Network callbacks come in bursts; tell the core once they settle.+ networkChange?.cancel()+ networkChange = scope.launch {+ delay(1_000)+ node?.networkChanged()+ }+ }++ // Android drops multicast (local discovery) unless a lock is held. The+ // connection service holds one while paired; this one covers pairing.+ private val pairingMulticast: WifiManager.MulticastLock? =+ this.context.getSystemService(WifiManager::class.java)+ ?.createMulticastLock("nectarlink-pairing")+ ?.apply { setReferenceCounted(false) }++ val state: StateFlow<CoreState> = _state.asStateFlow()++ /** Short messages for the user (a command failed). */+ val messages: SharedFlow<String> = _messages.asSharedFlow()++ /** Starts the node (once). Safe to call repeatedly. */+ fun start() {+ if (startJob != null) return+ startJob = scope.launch(Dispatchers.IO) {+ initLogging(if (BuildConfig.DEBUG) "debug,iroh=info,swarm_discovery=error" else "info,iroh=warn,swarm_discovery=error")+ val options = NodeOptions(+ dataDir = context.noBackupFilesDir.resolve("core").absolutePath,+ device = deviceInfo(context),+ appVersion = BuildConfig.VERSION_NAME,+ power = PowerLevel.BASIC,+ awayMode = false,+ )+ val started = try {+ NectarlinkNode.start(options, ringer, KeystoreKeyProtector(), this@Core)+ } catch (e: NectarlinkException) {+ Log.e(TAG, "core failed to start", e)+ _state.update { it.copy(status = CoreStatus.Failed(e.message ?: e.javaClass.simpleName)) }+ return@launch+ }+ node = started+ val devices = runCatching { started.pairedDevices() }.getOrDefault(emptyList())+ _state.update { it.withDevices(devices).copy(status = CoreStatus.Ready(started.deviceId())) }+ scope.launch(Dispatchers.Main) {+ battery.start()+ network.start()+ }+ }+ }++ override fun onEvent(event: Event) {+ _state.update { it.reduce(event) }+ }++ // ---- Pairing ----++ /**+ * Pairs with a link that arrived before the core finished starting (the+ * app was launched by opening the link).+ */+ fun joinWhenReady(link: String) {+ scope.launch {+ startJob?.join()+ joinWithLink(link)+ }+ }++ /** Pairs with the PC whose QR code was scanned. */+ fun joinWithLink(link: String) = command {+ _state.update { it.copy(pairing = PairingState.Joining) }+ try {+ it.pairingJoin(link)+ } catch (e: NectarlinkException) {+ val failure = when (e) {+ is NectarlinkException.InvalidPairingLink -> PairingFailure.Other("not a Nectarlink code")+ is NectarlinkException.Denied -> PairingFailure.Rejected+ else -> PairingFailure.Unreachable+ }+ _state.update { s -> s.copy(pairing = PairingState.Failed(failure)) }+ }+ }++ /** Pairs with a nearby PC that shows its pairing screen. */+ fun pairNearby(peer: String) = command {+ _state.update { it.copy(pairing = PairingState.Connecting(peer)) }+ try {+ it.pairingStartNearby(peer)+ } catch (e: NectarlinkException) {+ _state.update { s ->+ if (s.pairing is PairingState.Connecting) s.copy(pairing = PairingState.Failed(PairingFailure.Unreachable)) else s+ }+ }+ }++ fun confirmCode(matches: Boolean) {+ val comparing = _state.value.pairing as? PairingState.Comparing ?: return+ runCatching { node?.pairingConfirm(matches) }+ _state.update {+ it.copy(+ pairing = if (matches) PairingState.Confirmed(comparing.peer, comparing.code)+ else PairingState.Failed(PairingFailure.Declined),+ )+ }+ }++ /** Keeps local discovery working while the pairing screen is open. */+ fun setPairingScreenOpen(open: Boolean) {+ pairingMulticast?.runCatching { if (open) acquire() else release() }+ }++ fun resetPairing() {+ node?.pairingCancel()+ _state.update { it.copy(pairing = PairingState.Idle) }+ }++ // ---- Devices ----++ fun ring(id: String, on: Boolean) = command { it.ring(id, on) }++ fun unpair(id: String) = command { it.unpair(id) }++ /** Stops this phone ringing. */+ fun stopRinging() {+ ringer.stopRinging()+ _state.update { it.copy(ringingFrom = null) }+ }++ /** Runs a command on the node, turning errors into a message. */+ private fun command(block: suspend (NectarlinkNode) -> Unit) {+ val node = node ?: return+ scope.launch {+ try {+ block(node)+ } catch (e: NectarlinkException) {+ _messages.tryEmit(describe(e))+ }+ }+ }++ private fun describe(e: NectarlinkException): String = when (e) {+ is NectarlinkException.Offline -> "The PC isn't connected right now."+ is NectarlinkException.NotPaired -> "That PC isn't paired anymore."+ is NectarlinkException.Timeout -> "The PC didn't answer in time."+ is NectarlinkException.Unsupported -> "The PC's app doesn't support that yet."+ else -> "Something went wrong."+ }++ private companion object {+ const val TAG = "Nectarlink"+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktnew file mode 100644index 0000000..f88d964--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -0,0 +1,106 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.core++import app.nectarlink.core.DiscoveredDevice+import app.nectarlink.core.Event+import app.nectarlink.core.Feature+import app.nectarlink.core.Link+import app.nectarlink.core.PairedDevice+import app.nectarlink.core.PairingFailure+import app.nectarlink.core.PowerLevel++/** Whether the core is running. */+sealed interface CoreStatus {+ data object Starting : CoreStatus+ data class Ready(val deviceId: String) : CoreStatus+ data class Failed(val message: String) : CoreStatus+}++/** The pairing screen's state. */+sealed interface PairingState {+ data object Idle : PairingState+ /** Joining a PC from a scanned QR code. */+ data object Joining : PairingState+ /** Dialing a nearby PC that is in pairing mode. */+ data class Connecting(val peer: String) : PairingState+ /** Both screens show this code; the user confirms it matches. */+ data class Comparing(val peer: String, val code: String) : PairingState+ /** This user confirmed; waiting for the other device. */+ data class Confirmed(val peer: String, val code: String) : PairingState+ data class Paired(val name: String) : PairingState+ data class Failed(val failure: PairingFailure) : PairingState+}++/** A paired device as the UI shows it. */+data class Device(+ val id: String,+ val name: String,+ val kind: app.nectarlink.core.DeviceKind,+ val model: String?,+ val pairedAt: Long,+ val link: Link,+ val battery: app.nectarlink.core.Battery? = null,+ val power: PowerLevel = PowerLevel.NOT_APPLICABLE,+ val features: List<Feature> = emptyList(),+) {+ val online: Boolean get() = link is Link.Online+}++/** Everything the UI renders, folded from core events. */+data class CoreState(+ val status: CoreStatus = CoreStatus.Starting,+ /** Paired devices, in pairing order. */+ val devices: List<Device> = emptyList(),+ val discovered: List<DiscoveredDevice> = emptyList(),+ val pairing: PairingState = PairingState.Idle,+ /** Name of the device making this phone ring, or null. */+ val ringingFrom: String? = null,+) {+ fun device(id: String): Device? = devices.firstOrNull { it.id == id }++ fun nameOf(id: String): String? =+ device(id)?.name ?: discovered.firstOrNull { it.id == id }?.name++ fun withDevices(paired: List<PairedDevice>): CoreState =+ copy(devices = paired.map { it.toDevice() }.sortedBy { it.pairedAt })++ /** Folds one core event into the state. */+ fun reduce(event: Event): CoreState = when (event) {+ is Event.DeviceAdded -> {+ val device = event.device.toDevice()+ copy(devices = (devices.filterNot { it.id == device.id } + device).sortedBy { it.pairedAt })+ }+ is Event.DeviceRemoved -> copy(+ devices = devices.filterNot { it.id == event.id },+ ringingFrom = if (ringingFrom == nameOf(event.id)) null else ringingFrom,+ )+ is Event.LinkChanged -> update(event.id) { it.copy(link = event.link) }+ is Event.PeerInfoChanged -> update(event.id) {+ it.copy(name = event.info.name, kind = event.info.kind, model = event.info.model)+ }+ is Event.PeerPowerChanged -> update(event.id) { it.copy(power = event.power) }+ is Event.Battery -> update(event.id) { it.copy(battery = event.battery) }+ is Event.Capabilities -> update(event.id) { it.copy(features = event.features) }+ is Event.Ring -> copy(ringingFrom = if (event.on) nameOf(event.id) ?: "" else null)+ is Event.Discovered -> copy(discovered = discovered.filterNot { it.id == event.device.id } + event.device)+ is Event.DiscoveryExpired -> copy(discovered = discovered.filterNot { it.id == event.id })+ is Event.PairingCode -> copy(pairing = PairingState.Comparing(event.peer, event.code))+ is Event.Paired -> copy(pairing = PairingState.Paired(event.device.info.name))+ // Failures of attempts the UI isn't showing (a stranger's wrong code)+ // don't open the pairing screen.+ is Event.PairingFailed ->+ if (pairing == PairingState.Idle) this else copy(pairing = PairingState.Failed(event.failure))+ }++ private fun update(id: String, change: (Device) -> Device): CoreState =+ copy(devices = devices.map { if (it.id == id) change(it) else it })+}++internal fun PairedDevice.toDevice() = Device(+ id = id,+ name = info.name,+ kind = info.kind,+ model = info.model,+ pairedAt = pairedAt,+ link = link,+)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/KeystoreKeyProtector.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/KeystoreKeyProtector.ktnew file mode 100644index 0000000..beecb00--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/KeystoreKeyProtector.kt@@ -0,0 +1,62 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.core++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import app.nectarlink.core.KeyProtector+import app.nectarlink.core.NectarlinkException+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec++/**+ * Encrypts the device's identity key with an AES-GCM key that lives in the+ * Android Keystore and can't be exported. Format: 12-byte IV, then the+ * ciphertext with its tag.+ */+class KeystoreKeyProtector : KeyProtector {++ override fun protect(plaintext: ByteArray): ByteArray = guard {+ val cipher = Cipher.getInstance(TRANSFORMATION)+ cipher.init(Cipher.ENCRYPT_MODE, key())+ cipher.iv + cipher.doFinal(plaintext)+ }++ override fun unprotect(ciphertext: ByteArray): ByteArray = guard {+ require(ciphertext.size > IV_LENGTH) { "protected key is too short" }+ val cipher = Cipher.getInstance(TRANSFORMATION)+ cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(TAG_BITS, ciphertext, 0, IV_LENGTH))+ cipher.doFinal(ciphertext, IV_LENGTH, ciphertext.size - IV_LENGTH)+ }++ private fun key(): SecretKey {+ val store = KeyStore.getInstance(KEYSTORE).apply { load(null) }+ (store.getKey(ALIAS, null) as? SecretKey)?.let { return it }+ val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)+ generator.init(+ KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+ .setKeySize(256)+ .build(),+ )+ return generator.generateKey()+ }++ /** Reports Keystore failures to the core as errors instead of crashing. */+ private inline fun guard(block: () -> ByteArray): ByteArray = try {+ block()+ } catch (e: Exception) {+ throw NectarlinkException.Internal("keystore: ${e.javaClass.simpleName}: ${e.message}")+ }++ private companion object {+ const val KEYSTORE = "AndroidKeyStore"+ const val ALIAS = "nectarlink.identity.v1"+ const val TRANSFORMATION = "AES/GCM/NoPadding"+ const val IV_LENGTH = 12+ const val TAG_BITS = 128+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Ringer.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Ringer.ktnew file mode 100644index 0000000..bebe320--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Ringer.kt@@ -0,0 +1,74 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.core++import android.content.Context+import android.media.AudioAttributes+import android.media.MediaPlayer+import android.media.RingtoneManager+import android.os.Handler+import android.os.Looper+import android.os.VibrationEffect+import android.os.Vibrator+import android.os.VibratorManager+import android.os.Build+import app.nectarlink.core.Platform++/**+ * "Find my phone": plays the alarm sound on the alarm stream (audible even+ * when the ringer is silent) and vibrates, until stopped or for a minute.+ */+class Ringer(context: Context) : Platform {+ private val context = context.applicationContext+ private val main = Handler(Looper.getMainLooper())+ private var player: MediaPlayer? = null+ private val timeout = Runnable { stopRingingNow() }++ override fun startRinging() {+ main.post { startRingingNow() }+ }++ override fun stopRinging() {+ main.post { stopRingingNow() }+ }++ private fun startRingingNow() {+ stopRingingNow()+ val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)+ ?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)+ player = runCatching {+ MediaPlayer().apply {+ setAudioAttributes(+ AudioAttributes.Builder()+ .setUsage(AudioAttributes.USAGE_ALARM)+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)+ .build(),+ )+ setDataSource(context, uri)+ isLooping = true+ prepare()+ start()+ }+ }.getOrNull()+ vibrator()?.vibrate(VibrationEffect.createWaveform(longArrayOf(0, 600, 400), 0))+ main.postDelayed(timeout, MAX_RING_MS)+ }++ private fun stopRingingNow() {+ main.removeCallbacks(timeout)+ player?.runCatching { stop(); release() }+ player = null+ vibrator()?.cancel()+ }++ private fun vibrator(): Vibrator? =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ context.getSystemService(VibratorManager::class.java)?.defaultVibrator+ } else {+ @Suppress("DEPRECATION")+ context.getSystemService(Vibrator::class.java)+ }++ private companion object {+ const val MAX_RING_MS = 60_000L+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.ktnew file mode 100644index 0000000..44e940c--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/SystemMonitors.kt@@ -0,0 +1,91 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.core++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.net.ConnectivityManager+import android.net.Network+import android.net.NetworkCapabilities+import android.os.BatteryManager+import android.os.Build+import android.provider.Settings+import androidx.core.content.ContextCompat+import app.nectarlink.core.Battery+import app.nectarlink.core.DeviceInfo+import app.nectarlink.core.DeviceKind++/** How this phone presents itself to PCs. */+fun deviceInfo(context: Context): DeviceInfo {+ val name = Settings.Global.getString(context.contentResolver, Settings.Global.DEVICE_NAME)+ ?.takeIf { it.isNotBlank() } ?: Build.MODEL+ val tablet = context.resources.configuration.smallestScreenWidthDp >= 600+ return DeviceInfo(+ name = name,+ kind = if (tablet) DeviceKind.TABLET else DeviceKind.PHONE,+ os = "android",+ osVersion = Build.VERSION.RELEASE,+ model = "${Build.MANUFACTURER.replaceFirstChar(Char::uppercase)} ${Build.MODEL}",+ accent = null,+ )+}++/** Reports the battery whenever it changes meaningfully. */+class BatteryMonitor(private val context: Context, private val onChange: (Battery) -> Unit) {+ private var last: Battery? = null++ private val receiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)+ val scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100)+ if (level < 0 || scale <= 0) return+ val plugged = when (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0)) {+ BatteryManager.BATTERY_PLUGGED_AC -> "ac"+ BatteryManager.BATTERY_PLUGGED_USB -> "usb"+ BatteryManager.BATTERY_PLUGGED_WIRELESS -> "wireless"+ else -> null+ }+ val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)+ val charging = status == BatteryManager.BATTERY_STATUS_CHARGING ||+ status == BatteryManager.BATTERY_STATUS_FULL+ val battery = Battery((level * 100 / scale).coerceIn(0, 100).toUByte(), charging, plugged)+ if (battery != last) {+ last = battery+ onChange(battery)+ }+ }+ }++ fun start() {+ // ACTION_BATTERY_CHANGED is sticky: the current state arrives at once.+ ContextCompat.registerReceiver(+ context, receiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED), ContextCompat.RECEIVER_NOT_EXPORTED,+ )+ }++ fun stop() {+ runCatching { context.unregisterReceiver(receiver) }+ }+}++/**+ * Tells the core when connectivity changes. Android doesn't let native code+ * watch the network, so iroh needs this to re-check paths quickly.+ */+class NetworkMonitor(context: Context, private val onChange: () -> Unit) {+ private val connectivity = context.getSystemService(ConnectivityManager::class.java)+ private val callback = object : ConnectivityManager.NetworkCallback() {+ override fun onAvailable(network: Network) = onChange()+ override fun onLost(network: Network) = onChange()+ override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) = Unit+ }++ fun start() {+ connectivity?.registerDefaultNetworkCallback(callback)+ }++ fun stop() {+ runCatching { connectivity?.unregisterNetworkCallback(callback) }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.ktnew file mode 100644index 0000000..af6b4c6--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt@@ -0,0 +1,153 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.service++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.net.wifi.WifiManager+import android.os.Build+import androidx.core.app.NotificationCompat+import androidx.core.app.ServiceCompat+import androidx.core.content.ContextCompat+import androidx.lifecycle.LifecycleService+import androidx.lifecycle.lifecycleScope+import app.nectarlink.android.NectarlinkApplication+import app.nectarlink.android.R+import app.nectarlink.android.core.CoreState+import app.nectarlink.android.ui.MainActivity+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.launch++/**+ * Keeps this phone reachable by its paired PCs while the app is in the+ * background: a foreground service (type "connected device") with an+ * ongoing notification, plus the Wi-Fi multicast lock that local discovery+ * needs on Android.+ */+class ConnectionService : LifecycleService() {+ private var multicastLock: WifiManager.MulticastLock? = null++ override fun onCreate() {+ super.onCreate()+ createChannels(this)+ val core = (application as NectarlinkApplication).core+ startInForeground(core.state.value)+ multicastLock = getSystemService(WifiManager::class.java)+ ?.createMulticastLock("nectarlink-discovery")+ ?.apply { setReferenceCounted(false); acquire() }++ lifecycleScope.launch {+ core.state.map { Status.of(it) }.distinctUntilChanged().collect { status ->+ getSystemService(NotificationManager::class.java)+ .notify(ONGOING_ID, ongoingNotification(status))+ }+ }+ lifecycleScope.launch {+ core.state.map { it.ringingFrom }.distinctUntilChanged().collect { from ->+ val manager = getSystemService(NotificationManager::class.java)+ if (from != null) manager.notify(RINGING_ID, ringingNotification(from)) else manager.cancel(RINGING_ID)+ }+ }+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ super.onStartCommand(intent, flags, startId)+ if (intent?.action == ACTION_STOP_RINGING) {+ (application as NectarlinkApplication).core.stopRinging()+ }+ return START_STICKY+ }++ override fun onDestroy() {+ multicastLock?.runCatching { release() }+ super.onDestroy()+ }++ private fun startInForeground(state: CoreState) {+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE+ } else {+ 0+ }+ ServiceCompat.startForeground(this, ONGOING_ID, ongoingNotification(Status.of(state)), type)+ }++ /** What the ongoing notification says. */+ private data class Status(val connected: List<String>, val paired: Int) {+ companion object {+ fun of(state: CoreState) = Status(state.devices.filter { it.online }.map { it.name }, state.devices.size)+ }+ }++ private fun ongoingNotification(status: Status): Notification {+ val text = when {+ status.connected.size == 1 -> getString(R.string.notification_connected_to, status.connected[0])+ status.connected.size > 1 -> getString(R.string.notification_connected_many, status.connected.size)+ status.paired == 0 -> getString(R.string.notification_not_paired)+ else -> getString(R.string.notification_waiting)+ }+ return NotificationCompat.Builder(this, CHANNEL_CONNECTION)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(text)+ .setContentIntent(openApp())+ .setOngoing(true)+ .setSilent(true)+ .setCategory(NotificationCompat.CATEGORY_SERVICE)+ .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)+ .build()+ }++ private fun ringingNotification(from: String): Notification {+ val stop = PendingIntent.getService(+ this, 1, Intent(this, ConnectionService::class.java).setAction(ACTION_STOP_RINGING),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ val title = if (from.isEmpty()) getString(R.string.ringing_title_unknown) else getString(R.string.ringing_title, from)+ return NotificationCompat.Builder(this, CHANNEL_RINGING)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(title)+ .setContentIntent(openApp())+ .setPriority(NotificationCompat.PRIORITY_HIGH)+ .setCategory(NotificationCompat.CATEGORY_ALARM)+ .setOngoing(true)+ .addAction(0, getString(R.string.action_stop_ringing), stop)+ .setDeleteIntent(stop)+ .build()+ }++ private fun openApp(): PendingIntent = PendingIntent.getActivity(+ this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE,+ )++ companion object {+ private const val ONGOING_ID = 1+ private const val RINGING_ID = 2+ private const val CHANNEL_CONNECTION = "connection"+ private const val CHANNEL_RINGING = "ringing"+ private const val ACTION_STOP_RINGING = "app.nectarlink.action.STOP_RINGING"++ /** Starts the service (from the foreground: Android forbids it otherwise). */+ fun start(context: Context) {+ ContextCompat.startForegroundService(context, Intent(context, ConnectionService::class.java))+ }++ private fun createChannels(context: Context) {+ val manager = context.getSystemService(NotificationManager::class.java)+ manager.createNotificationChannel(+ NotificationChannel(+ CHANNEL_CONNECTION, context.getString(R.string.channel_connection), NotificationManager.IMPORTANCE_LOW,+ ).apply { setShowBadge(false) },+ )+ manager.createNotificationChannel(+ NotificationChannel(+ CHANNEL_RINGING, context.getString(R.string.channel_ringing), NotificationManager.IMPORTANCE_HIGH,+ ).apply { setSound(null, null) },+ )+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.ktnew file mode 100644index 0000000..7d97c4b--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt@@ -0,0 +1,154 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.ui++import android.Manifest+import android.content.Intent+import android.os.Build+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.BackHandler+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.NavigationBar+import androidx.compose.material3.NavigationBarItem+import androidx.compose.material3.Scaffold+import androidx.compose.material3.SnackbarHost+import androidx.compose.material3.SnackbarHostState+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import app.nectarlink.android.NectarlinkApplication+import app.nectarlink.android.R+import app.nectarlink.android.core.Core+import app.nectarlink.android.core.CoreState+import app.nectarlink.android.core.CoreStatus+import app.nectarlink.android.core.PairingState+import app.nectarlink.android.service.ConnectionService+import app.nectarlink.android.ui.home.HomeScreen+import app.nectarlink.android.ui.pairing.PairingActions+import app.nectarlink.android.ui.pairing.PairingScreen+import app.nectarlink.android.ui.settings.SettingsScreen+import app.nectarlink.android.ui.theme.NectarlinkTheme++class MainActivity : ComponentActivity() {+ private val notificationPermission =+ registerForActivityResult(ActivityResultContracts.RequestPermission()) { }++ override fun onCreate(savedInstanceState: Bundle?) {+ enableEdgeToEdge()+ super.onCreate(savedInstanceState)+ val core = (application as NectarlinkApplication).core+ val preferences = Preferences(this)++ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)+ }+ if (savedInstanceState == null) handlePairingLink(intent)++ setContent {+ val appearance by preferences.appearance.collectAsStateWithLifecycle()+ val state by core.state.collectAsStateWithLifecycle()+ // Stay reachable in the background once a PC is paired.+ LaunchedEffect(state.devices.isNotEmpty()) {+ if (state.devices.isNotEmpty()) ConnectionService.start(this@MainActivity)+ }+ NectarlinkTheme(appearance) {+ App(core, state, preferences)+ }+ }+ }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ handlePairingLink(intent)+ }++ /** A PC's pairing QR code opened from another app (e.g. the camera). */+ private fun handlePairingLink(intent: Intent?) {+ val link = intent?.takeIf { it.action == Intent.ACTION_VIEW }?.dataString ?: return+ if (link.startsWith("nectarlink://pair?")) {+ (application as NectarlinkApplication).core.joinWhenReady(link)+ }+ }+}++private enum class Tab { Home, Settings }++@Composable+private fun App(core: Core, state: CoreState, preferences: Preferences) {+ var tab by rememberSaveable { mutableStateOf(Tab.Home) }+ var pairing by rememberSaveable { mutableStateOf(false) }+ val snackbar = remember { SnackbarHostState() }+ LaunchedEffect(Unit) { core.messages.collect { snackbar.showSnackbar(it) } }++ val actions = remember(core) {+ object : PairingActions {+ override fun visible(open: Boolean) = core.setPairingScreenOpen(open)+ override fun join(link: String) = core.joinWithLink(link)+ override fun pairNearby(id: String) = core.pairNearby(id)+ override fun confirm(matches: Boolean) = core.confirmCode(matches)+ override fun reset() = core.resetPairing()+ }+ }++ when {+ state.status is CoreStatus.Starting -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ CircularProgressIndicator()+ }+ state.status is CoreStatus.Failed -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Text(stringResource(R.string.core_failed, state.status.message))+ }+ state.devices.isEmpty() || pairing || state.pairing != PairingState.Idle -> {+ BackHandler(enabled = pairing && state.devices.isNotEmpty()) { core.resetPairing(); pairing = false }+ PairingScreen(state, actions, cancellable = state.devices.isNotEmpty()) { pairing = false }+ }+ else -> Scaffold(+ snackbarHost = { SnackbarHost(snackbar) },+ bottomBar = {+ NavigationBar {+ NavigationBarItem(+ selected = tab == Tab.Home,+ onClick = { tab = Tab.Home },+ icon = { Icon(painterResource(R.drawable.ic_home), contentDescription = null) },+ label = { Text(stringResource(R.string.home_title)) },+ )+ NavigationBarItem(+ selected = tab == Tab.Settings,+ onClick = { tab = Tab.Settings },+ icon = { Icon(painterResource(R.drawable.ic_settings), contentDescription = null) },+ label = { Text(stringResource(R.string.settings_title)) },+ )+ }+ },+ ) { padding ->+ val modifier = Modifier.fillMaxSize().padding(padding)+ when (tab) {+ Tab.Home -> HomeScreen(state, core::ring, core::stopRinging, modifier)+ Tab.Settings -> SettingsScreen(+ state = state,+ appearance = preferences.appearance.collectAsStateWithLifecycle().value,+ onAppearance = preferences::update,+ onUnpair = core::unpair,+ onPairNew = { pairing = true },+ modifier = modifier,+ )+ }+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.ktnew file mode 100644index 0000000..4fc3b2a--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/Preferences.kt@@ -0,0 +1,43 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.ui++import android.content.Context+import app.nectarlink.android.ui.theme.Appearance+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow++/** The app's look, saved in shared preferences and observable. */+class Preferences(context: Context) {+ private val prefs = context.applicationContext.getSharedPreferences("appearance", Context.MODE_PRIVATE)+ private val _appearance = MutableStateFlow(load())+ val appearance: StateFlow<Appearance> = _appearance.asStateFlow()++ private fun load(): Appearance {+ val defaults = Appearance()+ return Appearance(+ theme = prefs.getString(THEME, defaults.theme) ?: defaults.theme,+ mode = prefs.getString(MODE, defaults.mode) ?: defaults.mode,+ seed = prefs.getString(SEED, defaults.seed) ?: defaults.seed,+ dynamicColor = prefs.getBoolean(DYNAMIC, defaults.dynamicColor),+ )+ }++ fun update(change: (Appearance) -> Appearance) {+ val next = change(_appearance.value)+ prefs.edit()+ .putString(THEME, next.theme)+ .putString(MODE, next.mode)+ .putString(SEED, next.seed)+ .putBoolean(DYNAMIC, next.dynamicColor)+ .apply()+ _appearance.value = next+ }++ private companion object {+ const val THEME = "theme"+ const val MODE = "mode"+ const val SEED = "seed"+ const val DYNAMIC = "dynamic_color"+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.ktnew file mode 100644index 0000000..b22fba2--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt@@ -0,0 +1,152 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.ui.home++import android.text.format.DateUtils+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.AssistChip+import androidx.compose.material3.Button+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import app.nectarlink.android.R+import app.nectarlink.android.core.CoreState+import app.nectarlink.android.core.Device+import app.nectarlink.core.Link++/**+ * Home: each paired PC with its connection and quick actions. When a PC+ * makes this phone ring, a banner to stop it comes first.+ */+@Composable+fun HomeScreen(+ state: CoreState,+ onRing: (id: String, on: Boolean) -> Unit,+ onStopRinging: () -> Unit,+ modifier: Modifier = Modifier,+) {+ LazyColumn(+ modifier = modifier,+ contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ item {+ Text(+ stringResource(R.string.home_title),+ style = MaterialTheme.typography.headlineMedium,+ fontWeight = FontWeight.SemiBold,+ modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),+ )+ }+ state.ringingFrom?.let { from ->+ item { RingingBanner(from, onStopRinging) }+ }+ items(state.devices, key = { it.id }) { device -> PcCard(device, onRing) }+ }+}++@Composable+private fun RingingBanner(from: String, onStop: () -> Unit) {+ Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.primary) {+ Row(Modifier.fillMaxWidth().padding(20.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(+ if (from.isEmpty()) stringResource(R.string.ringing_title_unknown) else stringResource(R.string.ringing_title, from),+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.onPrimary,+ modifier = Modifier.weight(1f),+ )+ FilledTonalButton(onClick = onStop) { Text(stringResource(R.string.action_stop_ringing)) }+ }+ }+}++@Composable+private fun PcCard(device: Device, onRing: (String, Boolean) -> Unit) {+ var ringing by remember(device.id) { mutableStateOf(false) }+ Surface(+ shape = MaterialTheme.shapes.extraLarge,+ color = MaterialTheme.colorScheme.primaryContainer,+ contentColor = MaterialTheme.colorScheme.onPrimaryContainer,+ ) {+ Column(Modifier.fillMaxWidth().padding(24.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Box(+ Modifier.size(10.dp).padding(1.dp),+ ) {+ Surface(+ shape = CircleShape,+ color = if (device.online) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,+ modifier = Modifier.size(8.dp),+ ) {}+ }+ Spacer(Modifier.width(8.dp))+ Text(linkText(device.link), style = MaterialTheme.typography.labelLarge)+ }+ Spacer(Modifier.height(12.dp))+ Text(device.name, style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.SemiBold)+ device.model?.let {+ Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 2.dp))+ }+ device.battery?.let { battery ->+ Spacer(Modifier.height(12.dp))+ AssistChip(+ onClick = {},+ label = {+ Text(+ if (battery.charging) stringResource(R.string.battery_charging, battery.level.toInt())+ else stringResource(R.string.battery_level, battery.level.toInt()),+ )+ },+ )+ }+ Spacer(Modifier.height(20.dp))+ Button(+ enabled = device.online,+ onClick = {+ ringing = !ringing+ onRing(device.id, ringing)+ },+ ) {+ Text(stringResource(if (ringing) R.string.action_stop_ringing else R.string.action_ring_pc))+ }+ }+ }+}++@Composable+private fun linkText(link: Link): String = when (link) {+ is Link.Online -> when {+ link.relayed -> stringResource(R.string.link_away)+ link.rttMs >= 1u -> stringResource(R.string.link_online_rtt, link.rttMs.toInt())+ else -> stringResource(R.string.link_online)+ }+ Link.Connecting -> stringResource(R.string.link_connecting)+ is Link.Offline -> link.lastSeen?.let {+ stringResource(+ R.string.link_offline_seen,+ DateUtils.getRelativeTimeSpanString(it * 1000, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS),+ )+ } ?: stringResource(R.string.link_never)+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.ktnew file mode 100644index 0000000..761f6eb--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/PairingScreen.kt@@ -0,0 +1,291 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.ui.pairing++import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.togetherWith+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.safeDrawingPadding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.Button+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import app.nectarlink.android.R+import app.nectarlink.android.core.CoreState+import app.nectarlink.android.core.PairingState+import app.nectarlink.core.DiscoveredDevice+import app.nectarlink.core.PairingFailure+import kotlinx.coroutines.delay++/** What the user does on the pairing screen. */+interface PairingActions {+ /** The screen is shown or hidden (discovery needs a multicast lock). */+ fun visible(open: Boolean)+ fun join(link: String)+ fun pairNearby(id: String)+ fun confirm(matches: Boolean)+ fun reset()+}++/**+ * Pairing with a PC: scan the QR code it shows, or pick it from the PCs+ * nearby and compare a 6-digit code. `onDone` runs after success (or when+ * the user backs out, if `cancellable`).+ */+@Composable+fun PairingScreen(+ state: CoreState,+ actions: PairingActions,+ cancellable: Boolean,+ onDone: () -> Unit,+) {+ var nearby by rememberSaveable { mutableStateOf(false) }+ val pairing = state.pairing+ DisposableEffect(Unit) {+ actions.visible(true)+ onDispose { actions.visible(false) }+ }++ LaunchedEffect(pairing) {+ if (pairing is PairingState.Paired) {+ delay(1_400)+ actions.reset()+ onDone()+ }+ }++ Column(+ Modifier.fillMaxSize().safeDrawingPadding().padding(horizontal = 24.dp, vertical = 16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ Spacer(Modifier.height(24.dp))+ Text(+ text = when (pairing) {+ is PairingState.Comparing, is PairingState.Confirmed -> stringResource(R.string.pair_check_code)+ is PairingState.Paired -> stringResource(R.string.pair_done_title)+ is PairingState.Failed -> stringResource(R.string.pair_failed_title)+ else -> if (nearby) stringResource(R.string.pair_nearby_title) else stringResource(R.string.pair_title)+ },+ style = MaterialTheme.typography.headlineMedium,+ fontWeight = FontWeight.SemiBold,+ textAlign = TextAlign.Center,+ )+ Spacer(Modifier.height(20.dp))++ AnimatedContent(+ targetState = pairing to nearby,+ transitionSpec = { fadeIn() togetherWith fadeOut() },+ modifier = Modifier.weight(1f),+ label = "pairing",+ ) { (current, showNearby) ->+ when (current) {+ PairingState.Idle -> if (showNearby) {+ NearbyList(state.discovered, actions::pairNearby)+ } else {+ Scan(actions::join)+ }+ PairingState.Joining -> Working(stringResource(R.string.pair_joining))+ is PairingState.Connecting ->+ Working(stringResource(R.string.pair_connecting, state.nameOf(current.peer) ?: ""))+ is PairingState.Comparing -> Compare(state.nameOf(current.peer), current.code, actions::confirm)+ is PairingState.Confirmed -> Column(horizontalAlignment = Alignment.CenterHorizontally) {+ CodeDigits(current.code)+ Spacer(Modifier.height(24.dp))+ Working(stringResource(R.string.pair_waiting, state.nameOf(current.peer) ?: ""))+ }+ is PairingState.Paired -> Outcome(true, stringResource(R.string.pair_done, current.name))+ is PairingState.Failed -> Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Outcome(false, failureText(current.failure))+ Spacer(Modifier.height(16.dp))+ Button(onClick = actions::reset) { Text(stringResource(R.string.action_try_again)) }+ }+ }+ }++ if (pairing == PairingState.Idle) {+ FilledTonalButton(onClick = { nearby = !nearby }) {+ Text(stringResource(if (nearby) R.string.action_scan_instead else R.string.action_pair_nearby))+ }+ }+ if (cancellable && pairing !is PairingState.Paired) {+ TextButton(onClick = { actions.reset(); onDone() }) { Text(stringResource(R.string.action_cancel)) }+ }+ }+}++@Composable+private fun Scan(onLink: (String) -> Unit) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(+ stringResource(R.string.pair_scan_hint),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ )+ Spacer(Modifier.height(20.dp))+ QrScanner(+ onLink = onLink,+ modifier = Modifier+ .fillMaxWidth()+ .aspectRatio(1f)+ .clip(MaterialTheme.shapes.extraLarge)+ .background(MaterialTheme.colorScheme.surfaceContainerHigh),+ )+ }+}++@Composable+private fun NearbyList(devices: List<DiscoveredDevice>, onPair: (String) -> Unit) {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Text(+ stringResource(R.string.pair_nearby_hint),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth(),+ )+ Spacer(Modifier.height(6.dp))+ if (devices.isEmpty()) {+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {+ CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)+ Spacer(Modifier.width(10.dp))+ Text(stringResource(R.string.pair_looking), style = MaterialTheme.typography.bodySmall)+ }+ }+ devices.forEach { device ->+ Surface(+ shape = MaterialTheme.shapes.large,+ color = MaterialTheme.colorScheme.surfaceContainerHigh,+ modifier = Modifier.fillMaxWidth().clickable { onPair(device.id) },+ ) {+ Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(+ device.name ?: device.id.take(8),+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.weight(1f),+ )+ Button(onClick = { onPair(device.id) }) { Text(stringResource(R.string.action_pair)) }+ }+ }+ }+ }+}++@Composable+private fun Compare(peerName: String?, code: String, onConfirm: (Boolean) -> Unit) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(+ stringResource(R.string.pair_compare_hint, peerName ?: stringResource(R.string.your_pc)),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ textAlign = TextAlign.Center,+ )+ Spacer(Modifier.height(24.dp))+ CodeDigits(code)+ Spacer(Modifier.height(32.dp))+ Button(onClick = { onConfirm(true) }, modifier = Modifier.fillMaxWidth().height(52.dp)) {+ Text(stringResource(R.string.action_codes_match))+ }+ Spacer(Modifier.height(8.dp))+ OutlinedButton(onClick = { onConfirm(false) }, modifier = Modifier.fillMaxWidth().height(52.dp)) {+ Text(stringResource(R.string.action_codes_differ))+ }+ }+}++@Composable+private fun CodeDigits(code: String) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.semantics { contentDescription = code.toList().joinToString(" ") },+ ) {+ code.forEach { digit ->+ Surface(+ shape = MaterialTheme.shapes.medium,+ color = MaterialTheme.colorScheme.surfaceContainerHigh,+ modifier = Modifier.size(width = 44.dp, height = 56.dp),+ ) {+ Box(contentAlignment = Alignment.Center) {+ Text(digit.toString(), fontFamily = FontFamily.Monospace, fontSize = 26.sp, fontWeight = FontWeight.Bold)+ }+ }+ }+ }+}++@Composable+private fun Working(text: String) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)+ Spacer(Modifier.width(12.dp))+ Text(text, style = MaterialTheme.typography.bodyLarge)+ }+}++@Composable+private fun Outcome(success: Boolean, text: String) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Surface(+ shape = CircleShape,+ color = if (success) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh,+ modifier = Modifier.size(64.dp),+ ) {+ Box(contentAlignment = Alignment.Center) {+ Text(+ if (success) "✓" else "!",+ fontSize = 28.sp,+ fontWeight = FontWeight.Bold,+ color = if (success) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface,+ )+ }+ }+ Spacer(Modifier.height(16.dp))+ Text(text, style = MaterialTheme.typography.bodyLarge, textAlign = TextAlign.Center)+ }+}++@Composable+private fun failureText(failure: PairingFailure): String = when (failure) {+ PairingFailure.Rejected -> stringResource(R.string.pair_failed_rejected)+ PairingFailure.Declined -> stringResource(R.string.pair_failed_declined)+ PairingFailure.Expired -> stringResource(R.string.pair_failed_expired)+ PairingFailure.Unreachable -> stringResource(R.string.pair_failed_unreachable)+ is PairingFailure.Other -> stringResource(R.string.pair_failed_other)+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/QrScanner.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/QrScanner.ktnew file mode 100644index 0000000..dfbfb73--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/pairing/QrScanner.kt@@ -0,0 +1,141 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.ui.pairing++import android.Manifest+import android.content.pm.PackageManager+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.camera.core.CameraSelector+import androidx.camera.core.ImageAnalysis+import androidx.camera.core.ImageProxy+import androidx.camera.core.Preview+import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.camera.view.PreviewView+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Button+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.viewinterop.AndroidView+import androidx.core.content.ContextCompat+import androidx.lifecycle.compose.LocalLifecycleOwner+import app.nectarlink.android.R+import com.google.zxing.BarcodeFormat+import com.google.zxing.BinaryBitmap+import com.google.zxing.DecodeHintType+import com.google.zxing.MultiFormatReader+import com.google.zxing.NotFoundException+import com.google.zxing.PlanarYUVLuminanceSource+import com.google.zxing.common.HybridBinarizer+import java.util.concurrent.Executors+import java.util.concurrent.atomic.AtomicBoolean++/** Pairing links start with this; anything else is ignored while scanning. */+private const val LINK_PREFIX = "nectarlink://pair?"++/**+ * A camera preview that reports the first Nectarlink pairing link it sees.+ * Asks for the camera permission if needed.+ */+@Composable+fun QrScanner(onLink: (String) -> Unit, modifier: Modifier = Modifier) {+ val context = LocalContext.current+ var granted by remember {+ mutableStateOf(+ ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED,+ )+ }+ val request = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted = it }+ LaunchedEffect(Unit) { if (!granted) request.launch(Manifest.permission.CAMERA) }++ if (granted) {+ CameraPreview(onLink, modifier)+ } else {+ Column(modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) {+ Text(+ stringResource(R.string.camera_permission_needed),+ style = MaterialTheme.typography.bodyMedium,+ textAlign = TextAlign.Center,+ )+ Button(onClick = { request.launch(Manifest.permission.CAMERA) }, modifier = Modifier.padding(top = 12.dp)) {+ Text(stringResource(R.string.action_allow_camera))+ }+ }+ }+}++@Composable+private fun CameraPreview(onLink: (String) -> Unit, modifier: Modifier) {+ val context = LocalContext.current+ val lifecycleOwner = LocalLifecycleOwner.current+ val currentOnLink by rememberUpdatedState(onLink)+ val previewView = remember { PreviewView(context).apply { scaleType = PreviewView.ScaleType.FILL_CENTER } }+ val analyzerExecutor = remember { Executors.newSingleThreadExecutor() }++ DisposableEffect(lifecycleOwner) {+ val found = AtomicBoolean(false)+ val providerFuture = ProcessCameraProvider.getInstance(context)+ providerFuture.addListener({+ val provider = providerFuture.get()+ val preview = Preview.Builder().build().also { it.surfaceProvider = previewView.surfaceProvider }+ val analysis = ImageAnalysis.Builder()+ .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+ .build()+ val reader = MultiFormatReader().apply {+ setHints(mapOf(DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE)))+ }+ analysis.setAnalyzer(analyzerExecutor) { image ->+ image.use {+ val text = decode(reader, it)+ if (text != null && text.startsWith(LINK_PREFIX) && found.compareAndSet(false, true)) {+ ContextCompat.getMainExecutor(context).execute { currentOnLink(text) }+ }+ }+ }+ provider.unbindAll()+ provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis)+ }, ContextCompat.getMainExecutor(context))++ onDispose {+ if (providerFuture.isDone) providerFuture.get().unbindAll()+ analyzerExecutor.shutdown()+ }+ }++ Box(modifier) {+ AndroidView(factory = { previewView }, modifier = Modifier.fillMaxSize())+ }+}++/** Decodes a QR code from the frame's luminance (Y) plane, or null. */+private fun decode(reader: MultiFormatReader, image: ImageProxy): String? {+ val plane = image.planes[0]+ val buffer = plane.buffer+ val data = ByteArray(buffer.remaining()).also { buffer.get(it) }+ val source = PlanarYUVLuminanceSource(+ data, plane.rowStride, image.height, 0, 0, image.width, image.height, false,+ )+ return try {+ reader.decodeWithState(BinaryBitmap(HybridBinarizer(source))).text+ } catch (_: NotFoundException) {+ null+ } finally {+ reader.reset()+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktnew file mode 100644index 0000000..ec16360--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt@@ -0,0 +1,197 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.ui.settings++import android.os.Build+import androidx.compose.foundation.border+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.SegmentedButton+import androidx.compose.material3.SegmentedButtonDefaults+import androidx.compose.material3.SingleChoiceSegmentedButtonRow+import androidx.compose.material3.Surface+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import app.nectarlink.android.BuildConfig+import app.nectarlink.android.R+import app.nectarlink.android.core.CoreState+import app.nectarlink.android.core.CoreStatus+import app.nectarlink.android.core.Device+import app.nectarlink.android.ui.theme.Appearance+import app.nectarlink.android.ui.theme.Tokens++@Composable+fun SettingsScreen(+ state: CoreState,+ appearance: Appearance,+ onAppearance: ((Appearance) -> Appearance) -> Unit,+ onUnpair: (String) -> Unit,+ onPairNew: () -> Unit,+ modifier: Modifier = Modifier,+) {+ var confirmUnpair by remember { mutableStateOf<Device?>(null) }++ Column(+ modifier.verticalScroll(rememberScrollState()).padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Text(+ stringResource(R.string.settings_title),+ style = MaterialTheme.typography.headlineMedium,+ fontWeight = FontWeight.SemiBold,+ modifier = Modifier.padding(top = 8.dp, bottom = 4.dp),+ )++ Section(stringResource(R.string.settings_appearance)) {+ Label(stringResource(R.string.settings_theme))+ Choice(+ listOf("bloom" to stringResource(R.string.theme_bloom), "graphite" to stringResource(R.string.theme_graphite)),+ appearance.theme,+ ) { value -> onAppearance { it.copy(theme = value) } }+ Label(stringResource(R.string.settings_mode))+ Choice(+ listOf(+ "system" to stringResource(R.string.mode_system),+ "light" to stringResource(R.string.mode_light),+ "dark" to stringResource(R.string.mode_dark),+ ),+ appearance.mode,+ ) { value -> onAppearance { it.copy(mode = value) } }+ if (appearance.theme == "bloom") {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f)) {+ Text(stringResource(R.string.settings_dynamic_color), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(R.string.settings_dynamic_color_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ Switch(+ checked = appearance.dynamicColor,+ onCheckedChange = { on -> onAppearance { it.copy(dynamicColor = on) } },+ )+ }+ }+ if (!appearance.dynamicColor || Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Tokens.bloomSeeds.forEach { (name, seed) ->+ val selected = appearance.seed == name+ Surface(+ shape = CircleShape,+ color = seed.color,+ modifier = Modifier+ .size(32.dp)+ .then(if (selected) Modifier.border(2.dp, MaterialTheme.colorScheme.onSurface, CircleShape) else Modifier)+ .clickable { onAppearance { it.copy(seed = name) } }+ .semantics { contentDescription = name },+ ) {}+ }+ }+ }+ }+ }++ Section(stringResource(R.string.settings_devices)) {+ state.devices.forEach { device ->+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f)) {+ Text(device.name, style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(if (device.online) R.string.connected else R.string.not_connected),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ OutlinedButton(onClick = { confirmUnpair = device }) { Text(stringResource(R.string.action_unpair)) }+ }+ }+ FilledTonalButton(onClick = onPairNew) { Text(stringResource(R.string.action_pair_new)) }+ }++ Section(stringResource(R.string.settings_about)) {+ Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME), style = MaterialTheme.typography.bodyMedium)+ (state.status as? CoreStatus.Ready)?.let {+ Text(+ it.deviceId,+ style = MaterialTheme.typography.bodySmall,+ fontFamily = FontFamily.Monospace,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }++ confirmUnpair?.let { device ->+ AlertDialog(+ onDismissRequest = { confirmUnpair = null },+ title = { Text(stringResource(R.string.unpair_title, device.name)) },+ text = { Text(stringResource(R.string.unpair_text)) },+ confirmButton = {+ TextButton(onClick = { onUnpair(device.id); confirmUnpair = null }) {+ Text(stringResource(R.string.action_unpair))+ }+ },+ dismissButton = {+ TextButton(onClick = { confirmUnpair = null }) { Text(stringResource(R.string.action_cancel)) }+ },+ )+ }+}++@Composable+private fun Section(title: String, content: @Composable () -> Unit) {+ Text(+ title,+ style = MaterialTheme.typography.labelLarge,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(top = 8.dp),+ )+ Surface(shape = MaterialTheme.shapes.large, color = MaterialTheme.colorScheme.surfaceContainer) {+ Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { content() }+ }+}++@Composable+private fun Label(text: String) {+ Text(text, style = MaterialTheme.typography.titleSmall)+}++@Composable+private fun Choice(options: List<Pair<String, String>>, selected: String, onSelect: (String) -> Unit) {+ SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) {+ options.forEachIndexed { index, (value, label) ->+ SegmentedButton(+ selected = value == selected,+ onClick = { onSelect(value) },+ shape = SegmentedButtonDefaults.itemShape(index, options.size),+ ) { Text(label) }+ }+ }+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.ktnew file mode 100644index 0000000..77d9ab8--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Theme.kt@@ -0,0 +1,112 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.ui.theme++import android.app.Activity+import android.os.Build+import androidx.compose.foundation.isSystemInDarkTheme+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.ColorScheme+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Shapes+import androidx.compose.material3.darkColorScheme+import androidx.compose.material3.dynamicDarkColorScheme+import androidx.compose.material3.dynamicLightColorScheme+import androidx.compose.material3.lightColorScheme+import androidx.compose.runtime.Composable+import androidx.compose.runtime.SideEffect+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalView+import androidx.compose.ui.unit.dp+import androidx.core.view.WindowCompat++/** The user's look choices (see Preferences). */+data class Appearance(+ val theme: String = "bloom",+ val mode: String = "system",+ val seed: String = Tokens.DEFAULT_SEED,+ /** Bloom takes its colors from the wallpaper (Android 12+). */+ val dynamicColor: Boolean = true,+)++private fun Palette.toScheme(dark: Boolean, error: androidx.compose.ui.graphics.Color): ColorScheme {+ val base = if (dark) darkColorScheme() else lightColorScheme()+ return base.copy(+ primary = primary,+ onPrimary = onPrimary,+ primaryContainer = primaryContainer,+ onPrimaryContainer = onPrimaryContainer,+ secondary = primary,+ onSecondary = onPrimary,+ secondaryContainer = secondaryContainer,+ onSecondaryContainer = onSecondaryContainer,+ tertiary = primary,+ onTertiary = onPrimary,+ background = surface,+ onBackground = onSurface,+ surface = surface,+ onSurface = onSurface,+ surfaceVariant = surfaceContainerHigh,+ onSurfaceVariant = onSurfaceVariant,+ surfaceContainerLowest = surface,+ surfaceContainerLow = surfaceContainerLow,+ surfaceContainer = surfaceContainer,+ surfaceContainerHigh = surfaceContainerHigh,+ surfaceContainerHighest = surfaceContainerHighest,+ outline = outline,+ outlineVariant = outlineVariant,+ error = error,+ )+}++/** Shapes from the tokens: Bloom is round, Graphite is nearly square. */+private fun shapes(graphite: Boolean) = if (graphite) {+ Shapes(+ extraSmall = RoundedCornerShape(2.dp),+ small = RoundedCornerShape(3.dp),+ medium = RoundedCornerShape(4.dp),+ large = RoundedCornerShape(4.dp),+ extraLarge = RoundedCornerShape(6.dp),+ )+} else {+ Shapes(+ extraSmall = RoundedCornerShape(8.dp),+ small = RoundedCornerShape(12.dp),+ medium = RoundedCornerShape(16.dp),+ large = RoundedCornerShape(20.dp),+ extraLarge = RoundedCornerShape(28.dp),+ )+}++@Composable+fun NectarlinkTheme(appearance: Appearance = Appearance(), content: @Composable () -> Unit) {+ val dark = when (appearance.mode) {+ "light" -> false+ "dark" -> true+ else -> isSystemInDarkTheme()+ }+ val graphite = appearance.theme == "graphite"+ val error = if (dark) Tokens.errorDark else Tokens.errorLight+ val scheme = when {+ graphite -> (if (dark) Tokens.graphiteSlate else Tokens.graphitePaper).toScheme(dark, error)+ appearance.dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {+ val context = LocalContext.current+ if (dark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)+ }+ else -> {+ val seed = Tokens.bloomSeeds[appearance.seed] ?: Tokens.bloomSeeds.getValue(Tokens.DEFAULT_SEED)+ (if (dark) seed.dark else seed.light).toScheme(dark, error)+ }+ }+ // System bar icons follow the app's theme, which can differ from the system's.+ val view = LocalView.current+ if (!view.isInEditMode) {+ SideEffect {+ val window = (view.context as? Activity)?.window ?: return@SideEffect+ WindowCompat.getInsetsController(window, view).apply {+ isAppearanceLightStatusBars = !dark+ isAppearanceLightNavigationBars = !dark+ }+ }+ }+ MaterialTheme(colorScheme = scheme, shapes = shapes(graphite), content = content)+}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.ktnew file mode 100644index 0000000..d037989--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.kt@@ -0,0 +1,223 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Generated from docs/design/tokens.json by `cargo xtask tokens`. Do not edit.+package app.nectarlink.android.ui.theme++import androidx.compose.ui.graphics.Color++/** Material color roles of one theme variant. */+data class Palette(+ val primary: Color,+ val onPrimary: Color,+ val primaryContainer: Color,+ val onPrimaryContainer: Color,+ val secondaryContainer: Color,+ val onSecondaryContainer: Color,+ val surface: Color,+ val surfaceContainerLow: Color,+ val surfaceContainer: Color,+ val surfaceContainerHigh: Color,+ val surfaceContainerHighest: Color,+ val onSurface: Color,+ val onSurfaceVariant: Color,+ val outline: Color,+ val outlineVariant: Color,+)++/** A Bloom color preset: its seed swatch and light and dark palettes. */+data class Seed(val color: Color, val light: Palette, val dark: Palette)++object Tokens {+ const val DEFAULT_SEED = "honey"++ val bloomSeeds: Map<String, Seed> = linkedMapOf(+ "honey" to Seed(+ color = Color(0xFFB7791F),+ light = Palette(+ primary = Color(0xFF8A5100),+ onPrimary = Color(0xFFFFFFFF),+ primaryContainer = Color(0xFFFFDDB8),+ onPrimaryContainer = Color(0xFF2C1600),+ secondaryContainer = Color(0xFFF3E0CB),+ onSecondaryContainer = Color(0xFF261A0C),+ surface = Color(0xFFFFF8F3),+ surfaceContainerLow = Color(0xFFFBF2EB),+ surfaceContainer = Color(0xFFF5ECE4),+ surfaceContainerHigh = Color(0xFFEFE6DE),+ surfaceContainerHighest = Color(0xFFE9E1D9),+ onSurface = Color(0xFF1F1B16),+ onSurfaceVariant = Color(0xFF51453A),+ outline = Color(0xFF837468),+ outlineVariant = Color(0xFFD5C3B5),+ ),+ dark = Palette(+ primary = Color(0xFFFFB95F),+ onPrimary = Color(0xFF4A2800),+ primaryContainer = Color(0xFF693C00),+ onPrimaryContainer = Color(0xFFFFDDB8),+ secondaryContainer = Color(0xFF574330),+ onSecondaryContainer = Color(0xFFF3E0CB),+ surface = Color(0xFF17130E),+ surfaceContainerLow = Color(0xFF120E0A),+ surfaceContainer = Color(0xFF241F1A),+ surfaceContainerHigh = Color(0xFF2E2924),+ surfaceContainerHighest = Color(0xFF39342E),+ onSurface = Color(0xFFEBE1D9),+ onSurfaceVariant = Color(0xFFD5C3B5),+ outline = Color(0xFF9E8E81),+ outlineVariant = Color(0xFF51453A),+ ),+ ),+ "lavender" to Seed(+ color = Color(0xFF7E6AA8),+ light = Palette(+ primary = Color(0xFF65558F),+ onPrimary = Color(0xFFFFFFFF),+ primaryContainer = Color(0xFFE9DDFF),+ onPrimaryContainer = Color(0xFF201047),+ secondaryContainer = Color(0xFFE8DEF8),+ onSecondaryContainer = Color(0xFF1D192B),+ surface = Color(0xFFFDF7FF),+ surfaceContainerLow = Color(0xFFF7F2FA),+ surfaceContainer = Color(0xFFF2ECF4),+ surfaceContainerHigh = Color(0xFFECE6EE),+ surfaceContainerHighest = Color(0xFFE6E0E9),+ onSurface = Color(0xFF1D1B20),+ onSurfaceVariant = Color(0xFF49454E),+ outline = Color(0xFF7A757F),+ outlineVariant = Color(0xFFCAC4CF),+ ),+ dark = Palette(+ primary = Color(0xFFCFBDFE),+ onPrimary = Color(0xFF36275D),+ primaryContainer = Color(0xFF4D3D75),+ onPrimaryContainer = Color(0xFFE9DDFF),+ secondaryContainer = Color(0xFF4A4458),+ onSecondaryContainer = Color(0xFFE8DEF8),+ surface = Color(0xFF141218),+ surfaceContainerLow = Color(0xFF0F0D13),+ surfaceContainer = Color(0xFF211F24),+ surfaceContainerHigh = Color(0xFF2B292F),+ surfaceContainerHighest = Color(0xFF36343A),+ onSurface = Color(0xFFE6E0E9),+ onSurfaceVariant = Color(0xFFCAC4CF),+ outline = Color(0xFF948F99),+ outlineVariant = Color(0xFF49454E),+ ),+ ),+ "ocean" to Seed(+ color = Color(0xFF3D7DA8),+ light = Palette(+ primary = Color(0xFF2F628C),+ onPrimary = Color(0xFFFFFFFF),+ primaryContainer = Color(0xFFCEE5FF),+ onPrimaryContainer = Color(0xFF001D33),+ secondaryContainer = Color(0xFFD5E4F7),+ onSecondaryContainer = Color(0xFF0E1D2A),+ surface = Color(0xFFF7F9FF),+ surfaceContainerLow = Color(0xFFF1F4FA),+ surfaceContainer = Color(0xFFECEEF4),+ surfaceContainerHigh = Color(0xFFE6E8EE),+ surfaceContainerHighest = Color(0xFFE0E2E8),+ onSurface = Color(0xFF181C20),+ onSurfaceVariant = Color(0xFF42474E),+ outline = Color(0xFF72777F),+ outlineVariant = Color(0xFFC2C7CF),+ ),+ dark = Palette(+ primary = Color(0xFF9BCBFB),+ onPrimary = Color(0xFF003354),+ primaryContainer = Color(0xFF0F4A73),+ onPrimaryContainer = Color(0xFFCEE5FF),+ secondaryContainer = Color(0xFF3B4858),+ onSecondaryContainer = Color(0xFFD5E4F7),+ surface = Color(0xFF101418),+ surfaceContainerLow = Color(0xFF0B0F13),+ surfaceContainer = Color(0xFF1C2024),+ surfaceContainerHigh = Color(0xFF262A2F),+ surfaceContainerHighest = Color(0xFF31353A),+ onSurface = Color(0xFFE0E2E8),+ onSurfaceVariant = Color(0xFFC2C7CF),+ outline = Color(0xFF8C9199),+ outlineVariant = Color(0xFF42474E),+ ),+ ),+ "sage" to Seed(+ color = Color(0xFF5B8C5A),+ light = Palette(+ primary = Color(0xFF3B6939),+ onPrimary = Color(0xFFFFFFFF),+ primaryContainer = Color(0xFFBCF0B4),+ onPrimaryContainer = Color(0xFF002204),+ secondaryContainer = Color(0xFFD6E8CF),+ onSecondaryContainer = Color(0xFF111F0F),+ surface = Color(0xFFF7FBF1),+ surfaceContainerLow = Color(0xFFF1F5EB),+ surfaceContainer = Color(0xFFEBEFE5),+ surfaceContainerHigh = Color(0xFFE6E9E0),+ surfaceContainerHighest = Color(0xFFE0E4DA),+ onSurface = Color(0xFF191D17),+ onSurfaceVariant = Color(0xFF424940),+ outline = Color(0xFF72796F),+ outlineVariant = Color(0xFFC2C8BD),+ ),+ dark = Palette(+ primary = Color(0xFFA1D39A),+ onPrimary = Color(0xFF0A390F),+ primaryContainer = Color(0xFF234F24),+ onPrimaryContainer = Color(0xFFBCF0B4),+ secondaryContainer = Color(0xFF3B4B38),+ onSecondaryContainer = Color(0xFFD6E8CF),+ surface = Color(0xFF10140F),+ surfaceContainerLow = Color(0xFF0C100B),+ surfaceContainer = Color(0xFF1D211B),+ surfaceContainerHigh = Color(0xFF272B25),+ surfaceContainerHighest = Color(0xFF32362F),+ onSurface = Color(0xFFE0E4DA),+ onSurfaceVariant = Color(0xFFC2C8BD),+ outline = Color(0xFF8C9388),+ outlineVariant = Color(0xFF424940),+ ),+ ),+ )++ val graphitePaper = Palette(+ primary = Color(0xFF1A1918),+ onPrimary = Color(0xFFF5F2EB),+ primaryContainer = Color(0xFFE8E3D7),+ onPrimaryContainer = Color(0xFF1A1918),+ secondaryContainer = Color(0xFFE8E3D7),+ onSecondaryContainer = Color(0xFF1A1918),+ surface = Color(0xFFF5F2EB),+ surfaceContainerLow = Color(0xFFF1EDE4),+ surfaceContainer = Color(0xFFF5F2EB),+ surfaceContainerHigh = Color(0xFFEFEBE2),+ surfaceContainerHighest = Color(0xFFE8E3D7),+ onSurface = Color(0xFF1A1918),+ onSurfaceVariant = Color(0xFF5E5A54),+ outline = Color(0xFF4A4743),+ outlineVariant = Color(0xFFD5CFC2),+ )++ val graphiteSlate = Palette(+ primary = Color(0xFFE8EAED),+ onPrimary = Color(0xFF0D0D0E),+ primaryContainer = Color(0xFF1A1A1D),+ onPrimaryContainer = Color(0xFFE8EAED),+ secondaryContainer = Color(0xFF1A1A1D),+ onSecondaryContainer = Color(0xFFE8EAED),+ surface = Color(0xFF0D0D0E),+ surfaceContainerLow = Color(0xFF0B0B0C),+ surfaceContainer = Color(0xFF0D0D0E),+ surfaceContainerHigh = Color(0xFF141416),+ surfaceContainerHighest = Color(0xFF1A1A1D),+ onSurface = Color(0xFFE8EAED),+ onSurfaceVariant = Color(0xFF9A9CA1),+ outline = Color(0xFF7E8084),+ outlineVariant = Color(0xFF26272A),+ )++ val warningLight = Color(0xFF9A6700)+ val warningDark = Color(0xFFF2C14E)+ val errorLight = Color(0xFFBA1A1A)+ val errorDark = Color(0xFFFFB4AB)+}diff --git a/android/app/src/main/res/drawable/ic_home.xml b/android/app/src/main/res/drawable/ic_home.xmlnew file mode 100644index 0000000..1b08702--- /dev/null+++ b/android/app/src/main/res/drawable/ic_home.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+ <path android:pathData="M3,11l9,-7 9,7M5,10v10h14V10" android:strokeColor="#FF000000" android:strokeWidth="1.8"+ android:strokeLineCap="round" android:strokeLineJoin="round" android:fillColor="#00000000" />+</vector>diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xmlnew file mode 100644index 0000000..b5bb2aa--- /dev/null+++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<!-- Adaptive icon foreground: the mark centered in the 108dp safe zone. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">+ <group android:translateX="36" android:translateY="36" android:scaleX="1.5" android:scaleY="1.5">+ <path android:pathData="M12,2.5l8.2,4.75v9.5L12,21.5l-8.2,-4.75v-9.5zM9,12h6"+ android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round"+ android:strokeLineJoin="round" android:fillColor="#00000000" />+ </group>+</vector>diff --git a/android/app/src/main/res/drawable/ic_launcher_monochrome.xml b/android/app/src/main/res/drawable/ic_launcher_monochrome.xmlnew file mode 100644index 0000000..8feb4d6--- /dev/null+++ b/android/app/src/main/res/drawable/ic_launcher_monochrome.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<!-- Themed-icon version (Android 13+). -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">+ <group android:translateX="36" android:translateY="36" android:scaleX="1.5" android:scaleY="1.5">+ <path android:pathData="M12,2.5l8.2,4.75v9.5L12,21.5l-8.2,-4.75v-9.5zM9,12h6"+ android:strokeColor="#FF000000" android:strokeWidth="1.8" android:strokeLineCap="round"+ android:strokeLineJoin="round" android:fillColor="#00000000" />+ </group>+</vector>diff --git a/android/app/src/main/res/drawable/ic_notification.xml b/android/app/src/main/res/drawable/ic_notification.xmlnew file mode 100644index 0000000..9bea4f9--- /dev/null+++ b/android/app/src/main/res/drawable/ic_notification.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<!-- The Nectarlink mark: a hexagon with a bar. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+ <path android:pathData="M12,2.5l8.2,4.75v9.5L12,21.5l-8.2,-4.75v-9.5zM9,12h6"+ android:strokeColor="#FFFFFFFF" android:strokeWidth="2" android:strokeLineCap="round"+ android:strokeLineJoin="round" android:fillColor="#00000000" />+</vector>diff --git a/android/app/src/main/res/drawable/ic_settings.xml b/android/app/src/main/res/drawable/ic_settings.xmlnew file mode 100644index 0000000..90dfc9b--- /dev/null+++ b/android/app/src/main/res/drawable/ic_settings.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">+ <path android:pathData="M12,9a3,3 0,1 0,0 6,3 3,0 0,0 0,-6zM12,2v3M12,19v3M4.9,4.9l2.1,2.1M17,17l2.1,2.1M2,12h3M19,12h3M4.9,19.1L7,17M17,7l2.1,-2.1"+ android:strokeColor="#FF000000" android:strokeWidth="1.8" android:strokeLineCap="round"+ android:strokeLineJoin="round" android:fillColor="#00000000" />+</vector>diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmlnew file mode 100644index 0000000..5e31f61--- /dev/null+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/primary" />+ <foreground android:drawable="@drawable/ic_launcher_foreground" />+ <monochrome android:drawable="@drawable/ic_launcher_monochrome" />+</adaptive-icon>diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xmlnew file mode 100644index 0000000..bf858b5--- /dev/null+++ b/android/app/src/main/res/values/colors.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<resources>+ <!-- Bloom honey (docs/design/tokens.json). -->+ <color name="surface">#FFF8F3</color>+ <color name="primary">#8A5100</color>+</resources>diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlnew file mode 100644index 0000000..a78be6d--- /dev/null+++ b/android/app/src/main/res/values/strings.xml@@ -0,0 +1,83 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<resources>+ <string name="app_name">Nectarlink</string>++ <!-- Pairing -->+ <string name="pair_title">Pair with your PC</string>+ <string name="pair_scan_hint">On your PC, open Nectarlink. Point the camera at the code it shows.</string>+ <string name="pair_nearby_title">Pair nearby</string>+ <string name="pair_nearby_hint">On your PC, open Nectarlink and keep its pairing screen open. It shows up here.</string>+ <string name="pair_looking">Looking for PCs…</string>+ <string name="pair_joining">Pairing…</string>+ <string name="pair_connecting">Connecting to %1$s…</string>+ <string name="pair_waiting">Waiting for %1$s…</string>+ <string name="pair_check_code">Check the code</string>+ <string name="pair_compare_hint">Make sure %1$s shows the same code. This keeps anyone else from pairing in between.</string>+ <string name="pair_done_title">Paired</string>+ <string name="pair_done">%1$s is paired with this phone.</string>+ <string name="pair_failed_title">Pairing didn\'t work</string>+ <string name="pair_failed_rejected">The codes didn\'t match, so nothing was paired.</string>+ <string name="pair_failed_declined">Pairing was declined on one of the devices.</string>+ <string name="pair_failed_expired">The code expired. Show a new one on your PC.</string>+ <string name="pair_failed_unreachable">Couldn\'t reach the PC. Make sure both are on the same network.</string>+ <string name="pair_failed_other">That isn\'t a Nectarlink pairing code, or something went wrong.</string>+ <string name="your_pc">your PC</string>+ <string name="camera_permission_needed">Nectarlink needs the camera to scan the pairing code. Nothing is recorded.</string>++ <!-- Home -->+ <string name="home_title">Home</string>+ <string name="link_online">Connected</string>+ <string name="link_online_rtt">Connected · %1$d ms</string>+ <string name="link_away">Connected while away</string>+ <string name="link_connecting">Connecting…</string>+ <string name="link_offline_seen">Offline · seen %1$s</string>+ <string name="link_never">Not connected yet</string>+ <string name="battery_level">%1$d%%</string>+ <string name="battery_charging">%1$d%% · charging</string>+ <string name="ringing_title">%1$s is ringing your phone</string>+ <string name="ringing_title_unknown">Your PC is ringing your phone</string>+ <string name="connected">Connected</string>+ <string name="not_connected">Not connected</string>++ <!-- Settings -->+ <string name="settings_title">Settings</string>+ <string name="settings_appearance">Appearance</string>+ <string name="settings_theme">Theme</string>+ <string name="settings_mode">Mode</string>+ <string name="settings_dynamic_color">Colors from wallpaper</string>+ <string name="settings_dynamic_color_hint">Your PC follows the same colors.</string>+ <string name="settings_devices">PCs</string>+ <string name="settings_about">About</string>+ <string name="theme_bloom">Bloom</string>+ <string name="theme_graphite">Graphite</string>+ <string name="mode_system">System</string>+ <string name="mode_light">Light</string>+ <string name="mode_dark">Dark</string>+ <string name="about_version">Nectarlink %1$s</string>+ <string name="unpair_title">Unpair %1$s?</string>+ <string name="unpair_text">Both devices forget each other. You can pair them again any time.</string>+ <string name="core_failed">Nectarlink couldn\'t start: %1$s</string>++ <!-- Actions -->+ <string name="action_pair">Pair</string>+ <string name="action_pair_nearby">Pair nearby instead</string>+ <string name="action_scan_instead">Scan a code instead</string>+ <string name="action_codes_match">Codes match</string>+ <string name="action_codes_differ">They don\'t match</string>+ <string name="action_try_again">Try again</string>+ <string name="action_cancel">Cancel</string>+ <string name="action_allow_camera">Allow camera</string>+ <string name="action_ring_pc">Ring PC</string>+ <string name="action_stop_ringing">Stop ringing</string>+ <string name="action_unpair">Unpair</string>+ <string name="action_pair_new">Pair another PC</string>++ <!-- Notifications -->+ <string name="channel_connection">Connection</string>+ <string name="channel_ringing">Find my phone</string>+ <string name="notification_connected_to">Connected to %1$s</string>+ <string name="notification_connected_many">Connected to %1$d PCs</string>+ <string name="notification_waiting">Waiting for your PC</string>+ <string name="notification_not_paired">Not paired with a PC yet</string>+</resources>diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xmlnew file mode 100644index 0000000..20c4a66--- /dev/null+++ b/android/app/src/main/res/values/themes.xml@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<resources>+ <!-- The window behind Compose; Compose draws the real theme. -->+ <style name="Theme.Nectarlink" parent="android:Theme.Material.Light.NoActionBar">+ <item name="android:windowBackground">@color/surface</item>+ <item name="android:statusBarColor">@android:color/transparent</item>+ <item name="android:navigationBarColor">@android:color/transparent</item>+ </style>+</resources>diff --git a/android/app/src/main/res/xml/backup_rules.xml b/android/app/src/main/res/xml/backup_rules.xmlnew file mode 100644index 0000000..556ab05--- /dev/null+++ b/android/app/src/main/res/xml/backup_rules.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<!-- The device identity lives in no_backup and is never backed up: a+ restored copy on another phone would impersonate this one. -->+<full-backup-content>+ <include domain="sharedpref" path="appearance.xml" />+</full-backup-content>diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000..55d42e5--- /dev/null+++ b/android/app/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- SPDX-License-Identifier: GPL-3.0-or-later -->+<data-extraction-rules>+ <cloud-backup>+ <include domain="sharedpref" path="appearance.xml" />+ </cloud-backup>+ <device-transfer>+ <include domain="sharedpref" path="appearance.xml" />+ </device-transfer>+</data-extraction-rules>diff --git a/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.ktnew file mode 100644index 0000000..74e6492--- /dev/null+++ b/android/app/src/test/kotlin/app/nectarlink/android/core/CoreStateTest.kt@@ -0,0 +1,75 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.core++import app.nectarlink.core.Battery+import app.nectarlink.core.DeviceInfo+import app.nectarlink.core.DeviceKind+import app.nectarlink.core.DiscoveredDevice+import app.nectarlink.core.Event+import app.nectarlink.core.Link+import app.nectarlink.core.PairedDevice+import app.nectarlink.core.PairingFailure+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class CoreStateTest {+ private fun pc(id: String, name: String, pairedAt: Long) = PairedDevice(+ id = id,+ info = DeviceInfo(name, DeviceKind.DESKTOP, "windows", "10.0.26200", null, null),+ pairedAt = pairedAt,+ link = Link.Offline(null),+ )++ @Test+ fun devicesFollowEventsInPairingOrder() {+ var state = CoreState()+ .reduce(Event.DeviceAdded(pc("b", "Laptop", 20)))+ .reduce(Event.DeviceAdded(pc("a", "Desk", 10)))+ assertEquals(listOf("Desk", "Laptop"), state.devices.map { it.name })++ state = state.reduce(Event.LinkChanged("a", Link.Online(false, 5u)))+ .reduce(Event.Battery("a", Battery(42u, true, "ac")))+ assertTrue(state.device("a")!!.online)+ assertEquals(42.toUByte(), state.device("a")!!.battery!!.level)++ // Unknown devices are ignored; removal drops the device.+ state = state.reduce(Event.LinkChanged("zz", Link.Connecting)).reduce(Event.DeviceRemoved("b"))+ assertEquals(listOf("a"), state.devices.map { it.id })+ }++ @Test+ fun pairingFlow() {+ var state = CoreState()+ // A failure the user isn't looking at doesn't open the pairing screen.+ state = state.reduce(Event.PairingFailed(PairingFailure.Rejected))+ assertEquals(PairingState.Idle, state.pairing)++ state = state.copy(pairing = PairingState.Connecting("a"))+ .reduce(Event.PairingCode("a", "123456"))+ assertEquals(PairingState.Comparing("a", "123456"), state.pairing)++ state = state.reduce(Event.Paired(pc("a", "Desk", 1)))+ assertEquals(PairingState.Paired("Desk"), state.pairing)++ state = state.copy(pairing = PairingState.Joining).reduce(Event.PairingFailed(PairingFailure.Expired))+ assertEquals(PairingState.Failed(PairingFailure.Expired), state.pairing)+ }++ @Test+ fun ringingAndDiscovery() {+ var state = CoreState().withDevices(listOf(pc("a", "Desk", 1)))+ state = state.reduce(Event.Ring("a", true))+ assertEquals("Desk", state.ringingFrom)+ state = state.reduce(Event.Ring("a", false))+ assertNull(state.ringingFrom)++ val found = DiscoveredDevice("n", "Nearby PC")+ state = state.reduce(Event.Discovered(found)).reduce(Event.Discovered(found))+ assertEquals(1, state.discovered.size)+ assertEquals("Nearby PC", state.nameOf("n"))+ state = state.reduce(Event.DiscoveryExpired("n"))+ assertTrue(state.discovered.isEmpty())+ }+}diff --git a/android/build.gradle.kts b/android/build.gradle.ktsnew file mode 100644index 0000000..c94f7ec--- /dev/null+++ b/android/build.gradle.kts@@ -0,0 +1,5 @@+// SPDX-License-Identifier: GPL-3.0-or-later+plugins {+ alias(libs.plugins.android.application) apply false+ alias(libs.plugins.kotlin.compose) apply false+}diff --git a/android/gradle.properties b/android/gradle.propertiesnew file mode 100644index 0000000..16eaa9c--- /dev/null+++ b/android/gradle.properties@@ -0,0 +1,7 @@+# SPDX-License-Identifier: GPL-3.0-or-later+org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8+org.gradle.parallel=true+org.gradle.caching=true+android.useAndroidX=true+android.nonTransitiveRClass=true+kotlin.code.style=officialdiff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.tomlnew file mode 100644index 0000000..7f05cd1--- /dev/null+++ b/android/gradle/libs.versions.toml@@ -0,0 +1,36 @@+# SPDX-License-Identifier: GPL-3.0-or-later+[versions]+agp = "9.4.1"+kotlin = "2.4.20"+compose-bom = "2026.09.00"+activity-compose = "1.13.0"+lifecycle = "2.11.0"+core-ktx = "1.19.1"+coroutines = "1.11.0"+camerax = "1.6.2"+zxing = "3.5.4"+jna = "5.19.1"+junit = "4.13.2"++[libraries]+androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "core-ktx" }+androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activity-compose" }+androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }+androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }+androidx-lifecycle-service = { module = "androidx.lifecycle:lifecycle-service", version.ref = "lifecycle" }+compose-bom = { module = "androidx.compose:compose-bom", version.ref = "compose-bom" }+compose-ui = { module = "androidx.compose.ui:ui" }+compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }+compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }+compose-material3 = { module = "androidx.compose.material3:material3" }+kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" }+camerax-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camerax" }+camerax-lifecycle = { module = "androidx.camera:camera-lifecycle", version.ref = "camerax" }+camerax-view = { module = "androidx.camera:camera-view", version.ref = "camerax" }+zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" }+jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }+junit = { module = "junit:junit", version.ref = "junit" }++[plugins]+android-application = { id = "com.android.application", version.ref = "agp" }+kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 0000000..5097068Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 0000000..9f3a241--- /dev/null+++ b/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,10 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip+networkTimeout=10000+retries=0+retryBackOffMs=500+validateDistributionUrl=true+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/dists+distributionSha256Sum=bafd5ce9cfaea0fbccfdc8439a1ac42fbd4cd9c89dc9a988228d8a2639a58e6cdiff --git a/android/gradlew b/android/gradlewnew file mode 100644index 0000000..249efbb--- /dev/null+++ b/android/gradlew@@ -0,0 +1,248 @@+#!/bin/sh++#+# Copyright © 2015 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# SPDX-License-Identifier: Apache-2.0+#++##############################################################################+#+# gradlew start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh gradlew+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;+# * compound commands having a testable exit status, especially «case»;+# * various built-in commands including «command», «set», and «ulimit».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++# This is normally unused+# shellcheck disable=SC2034+APP_BASE_NAME=${0##*/}+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# 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 ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++++# 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+ if ! command -v java >/dev/null 2>&1+ then+ 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+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi+++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'++# Collect all arguments for the java command:+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,+# and any embedded shellness will be escaped.+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be+# treated as '${Hostname}' itself on the command line.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \+ "$@"++# Stop when "xargs" is not available.+if ! command -v xargs >/dev/null 2>&1+then+ die "xargs is not available"+fi++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/android/gradlew.bat b/android/gradlew.batnew file mode 100644index 0000000..3185a43--- /dev/null+++ b/android/gradlew.bat@@ -0,0 +1,112 @@+@rem+@rem Copyright 2015 the original author or authors.+@rem+@rem Licensed under the Apache License, Version 2.0 (the "License");+@rem you may not use this file except in compliance with the License.+@rem You may obtain a copy of the License at+@rem+@rem https://www.apache.org/licenses/LICENSE-2.0+@rem+@rem Unless required by applicable law or agreed to in writing, software+@rem distributed under the License is distributed on an "AS IS" BASIS,+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+@rem See the License for the specific language governing permissions and+@rem limitations under the License.+@rem+@rem SPDX-License-Identifier: Apache-2.0+@rem++@if "%DEBUG%"=="" @echo off+@rem ##########################################################################+@rem+@rem gradlew startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables, and ensure extensions are enabled+setlocal EnableExtensions++@rem Catch executions from older scripts and ensure they exit cleanly.+@rem This can be removed once we can be reasonably confident that few people+@rem will be migrating directly to this new wrapper.+goto afterSafetyNet+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::+goto exitWithErrorLevel+:afterSafetyNet++set DIRNAME=%~dp0+if "%DIRNAME%"=="" set DIRNAME=.+@rem This is normally unused+set APP_BASE_NAME=%~n0+set APP_HOME=%DIRNAME%++@rem Resolve any "." and ".." in APP_HOME to make it shorter.+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi++@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="-Xmx64m" "-Xms64m"++@rem Find java.exe+if defined JAVA_HOME goto findJavaFromJavaHome++set JAVA_EXE=java.exe+%JAVA_EXE% -version >NUL 2>&1+if %ERRORLEVEL% equ 0 goto execute++1>&2 echo.+1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.+1>&2 echo.+1>&2 echo Please set the JAVA_HOME variable in your environment to match the+1>&2 echo location of your Java installation.++"%COMSPEC%" /c exit 1+goto exitWithErrorLevel++:findJavaFromJavaHome+set JAVA_HOME=%JAVA_HOME:"=%+set JAVA_EXE=%JAVA_HOME%/bin/java.exe++if exist "%JAVA_EXE%" goto execute++1>&2 echo.+1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%+1>&2 echo.+1>&2 echo Please set the JAVA_HOME variable in your environment to match the+1>&2 echo location of your Java installation.++"%COMSPEC%" /c exit 1+goto exitWithErrorLevel++:execute+@rem Setup the command line++++@rem Execute gradlew+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded+@rem which allows us to clear the local environment before executing the java command+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel++@rem This label must not be changed. We rely on old scripts being able to jump to this point.+:exitWithErrorLevel+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts+"%COMSPEC%" /c exit %ERRORLEVEL%diff --git a/android/settings.gradle.kts b/android/settings.gradle.ktsnew file mode 100644index 0000000..dc12acb--- /dev/null+++ b/android/settings.gradle.kts@@ -0,0 +1,19 @@+// SPDX-License-Identifier: GPL-3.0-or-later+pluginManagement {+ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}++dependencyResolutionManagement {+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)+ repositories {+ google()+ mavenCentral()+ }+}++rootProject.name = "Nectarlink"+include(":app")diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 9860bf4..34868bf 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -217,12 +217,12 @@ pub enum NectarlinkError {InvalidPairingLink,#[error("invalid device ID")]InvalidDeviceId,- #[error("network error: {message}")]- Network { message: String },- #[error("storage error: {message}")]- Storage { message: String },- #[error("internal error: {message}")]- Internal { message: String },+ #[error("network error: {reason}")]+ Network { reason: String },+ #[error("storage error: {reason}")]+ Storage { reason: String },+ #[error("internal error: {reason}")]+ Internal { reason: String },}impl From<core::Error> for NectarlinkError {@@ -239,11 +239,11 @@ impl From<core::Error> for NectarlinkError {core::Error::Unsupported => NectarlinkError::Unsupported,core::Error::NotPairing => NectarlinkError::NotPairing,core::Error::InvalidPairingLink(_) => NectarlinkError::InvalidPairingLink,- core::Error::Network(message) => NectarlinkError::Network { message },- core::Error::Storage(message) => NectarlinkError::Storage { message },- core::Error::Io(e) => NectarlinkError::Storage { message: e.to_string() },- core::Error::Protocol(message) | core::Error::Internal(message) => {- NectarlinkError::Internal { message }+ core::Error::Network(reason) => NectarlinkError::Network { reason },+ core::Error::Storage(reason) => NectarlinkError::Storage { reason },+ core::Error::Io(e) => NectarlinkError::Storage { reason: e.to_string() },+ core::Error::Protocol(reason) | core::Error::Internal(reason) => {+ NectarlinkError::Internal { reason }}}}@@ -549,7 +549,7 @@ impl NectarlinkNode {.thread_name("nectarlink-core").enable_all().build()- .map_err(|e| NectarlinkError::Internal { message: e.to_string() })?;+ .map_err(|e| NectarlinkError::Internal { reason: e.to_string() })?;let mut config =NodeConfig::new(PathBuf::from(options.data_dir), options.device.into(), options.app_version);config.power = options.power.into();@@ -689,7 +689,7 @@ pub fn init_logging(filter: String) {use tracing_subscriber::{EnvFilter, prelude::*};let filter = EnvFilter::try_new(&filter).unwrap_or_else(|_| EnvFilter::new("info"));#[cfg(target_os = "android")]- let layer = paranoid_android::layer("Nectarlink");+ let layer = paranoid_android::layer("Nectarlink").with_ansi(false);#[cfg(not(target_os = "android"))]let layer = tracing_subscriber::fmt::layer();let _ = tracing_subscriber::registry().with(filter).with(layer).try_init();@@ -708,7 +708,7 @@ mod tests {);assert!(matches!(NectarlinkError::from(core::Error::Internal("x".into())),- NectarlinkError::Internal { message } if message == "x"+ NectarlinkError::Internal { reason } if reason == "x"));}diff --git a/scripts/check.ps1 b/scripts/check.ps1index caef1e8..8686d40 100644--- a/scripts/check.ps1+++ b/scripts/check.ps1@@ -13,6 +13,10 @@.PARAMETER Arm64Also cross-compiles the workspace for Windows ARM64.+.PARAMETER Android+ Also builds the Android app and runs its unit tests (needs the Android+ SDK, NDK and cargo-ndk; see android/README.md).+.PARAMETER FastSkips the slow steps (tests and the dependency audit).@@ -22,6 +26,7 @@#>param([switch]$Arm64,+ [switch]$Android,[switch]$Fast)$ErrorActionPreference = "Stop"@@ -115,6 +120,17 @@ try {}}}+ if ($Android) {+ Invoke-Step "Android" {+ Push-Location (Join-Path $root "android")+ try {+ if (-not $env:JAVA_HOME) { $env:JAVA_HOME = "C:\Program Files\Android\Android Studio\jbr" }+ & .\gradlew.bat --console=plain -q testDebugUnitTest assembleDebug+ } finally {+ Pop-Location+ }+ }+ }} finally {Pop-Location}diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rsindex 94c72ac..0955ccb 100644--- a/tools/xtask/src/main.rs+++ b/tools/xtask/src/main.rs@@ -1,8 +1,9 @@// SPDX-License-Identifier: GPL-3.0-or-later//! Repository automation. Run as `cargo xtask <task>`.//!-//! - `tokens`: generates the desktop theme (`desktop/app/qml/Tokens.qml`)-//! from `docs/design/tokens.json`, the single source of truth.+//! - `tokens`: generates the desktop and Android themes+//! (`desktop/app/qml/Tokens.qml`, `android/.../ui/theme/Tokens.kt`) from+//! `docs/design/tokens.json`, the single source of truth.//! - `tokens --check`: fails if the generated files are out of date (CI).use std::{@@ -16,6 +17,7 @@ use serde_json::{Map, Value};const TOKENS: &str = "docs/design/tokens.json";const QML_OUT: &str = "desktop/app/qml/Tokens.qml";+const KOTLIN_OUT: &str = "android/app/src/main/kotlin/app/nectarlink/android/ui/theme/Tokens.kt";fn main() -> ExitCode {let args: Vec<String> = std::env::args().skip(1).collect();@@ -46,18 +48,28 @@ fn tokens(check: bool) -> Result<()> {let source = fs::read_to_string(root.join(TOKENS)).with_context(|| format!("reading {TOKENS}"))?;let tokens: Value = serde_json::from_str(&source).with_context(|| format!("parsing {TOKENS}"))?;validate(&tokens)?;- let qml = render_qml(&tokens)?;+ let outputs = [(QML_OUT, render_qml(&tokens)?), (KOTLIN_OUT, render_kotlin(&tokens)?)];- let out = root.join(QML_OUT);- if check {- let current = fs::read_to_string(&out).unwrap_or_default();- if current != qml {- bail!("{QML_OUT} is out of date; run `cargo xtask tokens`");+ let mut stale = Vec::new();+ for (path, content) in outputs {+ let out = root.join(path);+ if check {+ if fs::read_to_string(&out).unwrap_or_default() != content {+ stale.push(path);+ }+ } else {+ if let Some(dir) = out.parent() {+ fs::create_dir_all(dir)?;+ }+ fs::write(&out, content).with_context(|| format!("writing {path}"))?;+ println!("wrote {path}");}- println!("{QML_OUT} is up to date");- } else {- fs::write(&out, qml).with_context(|| format!("writing {QML_OUT}"))?;- println!("wrote {QML_OUT}");+ }+ if !stale.is_empty() {+ bail!("out of date: {}; run `cargo xtask tokens`", stale.join(", "));+ }+ if check {+ println!("generated theme files are up to date");}Ok(())}@@ -145,6 +157,85 @@ fn render_qml(tokens: &Value) -> Result<String> {))}+/// `#RRGGBB` as a Compose color literal.+fn kotlin_color(hex: &str) -> String {+ format!("Color(0xFF{})", hex.trim_start_matches('#').to_ascii_uppercase())+}++/// A `Palette(...)` expression, its lines indented by `indent` spaces.+fn kotlin_palette(palette: &Value, indent: usize) -> Result<String> {+ let pad = " ".repeat(indent);+ let mut lines = vec!["Palette(".to_owned()];+ for role in ROLES {+ let hex = palette.get(*role).and_then(Value::as_str).with_context(|| format!("missing {role}"))?;+ lines.push(format!("{pad} {role} = {},", kotlin_color(hex)));+ }+ lines.push(format!("{pad})"));+ Ok(lines.join(+ "+",+ ))+}++fn render_kotlin(tokens: &Value) -> Result<String> {+ let bloom = tokens.pointer("/themes/bloom").context("missing bloom")?;+ let seeds = bloom.get("seeds").and_then(Value::as_object).context("missing seeds")?;+ let default_seed = bloom.get("defaultSeed").and_then(Value::as_str).context("missing defaultSeed")?;+ let variants = tokens.pointer("/themes/graphite/variants").context("missing graphite variants")?;+ let status = bloom.get("status").context("missing bloom status")?;+ let status_color = |mode: &str, key: &str| -> Result<String> {+ let hex = status+ .pointer(&format!("/{mode}/{key}"))+ .and_then(Value::as_str)+ .context("missing status color")?;+ Ok(kotlin_color(hex))+ };++ let mut out: Vec<String> = vec![+ "// SPDX-License-Identifier: GPL-3.0-or-later".into(),+ "// Generated from docs/design/tokens.json by `cargo xtask tokens`. Do not edit.".into(),+ "package app.nectarlink.android.ui.theme".into(),+ String::new(),+ "import androidx.compose.ui.graphics.Color".into(),+ String::new(),+ "/** Material color roles of one theme variant. */".into(),+ "data class Palette(".into(),+ ];+ out.extend(ROLES.iter().map(|r| format!(" val {r}: Color,")));+ out.extend([+ ")".into(),+ String::new(),+ "/** A Bloom color preset: its seed swatch and light and dark palettes. */".into(),+ "data class Seed(val color: Color, val light: Palette, val dark: Palette)".into(),+ String::new(),+ "object Tokens {".into(),+ format!(" const val DEFAULT_SEED = \"{default_seed}\""),+ String::new(),+ " val bloomSeeds: Map<String, Seed> = linkedMapOf(".into(),+ ]);+ for (name, def) in seeds {+ let seed = def.get("seed").and_then(Value::as_str).context("missing seed color")?;+ out.push(format!(" \"{name}\" to Seed("));+ out.push(format!(" color = {},", kotlin_color(seed)));+ out.push(format!(" light = {},", kotlin_palette(&def["light"], 12)?));+ out.push(format!(" dark = {},", kotlin_palette(&def["dark"], 12)?));+ out.push(" ),".into());+ }+ out.push(" )".into());+ out.push(String::new());+ out.push(format!(" val graphitePaper = {}", kotlin_palette(&variants["paper"], 4)?));+ out.push(String::new());+ out.push(format!(" val graphiteSlate = {}", kotlin_palette(&variants["slate"], 4)?));+ out.push(String::new());+ out.push(format!(" val warningLight = {}", status_color("light", "warning")?));+ out.push(format!(" val warningDark = {}", status_color("dark", "warning")?));+ out.push(format!(" val errorLight = {}", status_color("light", "error")?));+ out.push(format!(" val errorDark = {}", status_color("dark", "error")?));+ out.push("}".into());+ out.push(String::new());+ Ok(out.join("\n"))+}+#[cfg(test)]mod tests {use super::*;@@ -168,6 +259,17 @@ mod tests {assert!(check_palette(Some(&Value::Object(palette)), "missing").is_err());}+ #[test]+ fn kotlin_theme_has_every_seed() {+ let source = fs::read_to_string(repo_root().join(TOKENS)).unwrap();+ let tokens: Value = serde_json::from_str(&source).unwrap();+ let kotlin = render_kotlin(&tokens).unwrap();+ for seed in tokens.pointer("/themes/bloom/seeds").unwrap().as_object().unwrap().keys() {+ assert!(kotlin.contains(&format!("\"{seed}\" to Seed(")), "{seed}");+ }+ assert!(kotlin.contains("primary = Color(0xFF8A5100)"));+ }+#[test]fn documentation_keys_are_dropped() {let v: Value = serde_json::json!({"$note": 1, "a": {"$x": 2, "b": [ {"$y": 3, "c": 4} ]}});