diff --git a/CHANGELOG.md b/CHANGELOG.md index 9aa3a05..cca0598 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### 2026-07-21 + +- Add a Native Islands Location Button component with grant, position, and error + events. + ### 2026-10-30 - Chore: Update dependencies and build tooling (Gradle 8.14.3, AGP 8.13.0, minSdk 24, androidx libraries, coroutines 1.9.0, test libraries). +### 2026-11-16 + +- BREAKING CHANGE: The library is now a single AAR that includes the Location Button, built with `compileSdk` 37. Consumers must build with `compileSdk` 37 or higher (the AAR declares `minCompileSdk = 37`). Builds on `compileSdk` 36 (MABS 12) can no longer use this library, including for the existing geolocation methods. +- BREAKING CHANGE: The minimum supported Android version is now API 26 (`minSdk` 26, previously 24). +- BREAKING CHANGE: Consuming builds now need Android Gradle Plugin 9.1 or higher and Kotlin 2.1 or higher, as required by `androidx.core.locationbutton`. The library is built with Kotlin 2.2 and depends on `kotlin-stdlib` 2.2.x. +- Feature: Depend on `androidx.core.locationbutton:locationbutton-compose:1.0.0-alpha01`, which is still an alpha release (the latest published), so its API may change incompatibly. The `android.permission.USE_LOCATION_BUTTON` permission is now added to the merged manifest. +- Chore: Update build tooling (Gradle 9.4.1, AGP 9.2.1, nexus publish plugin 2.0.0, SonarQube plugin 7.6.0). The publishing script no longer uses the `-b` Gradle flag, which Gradle 9 removed. + +### 2026-11-18 + +- Feature: The Location Button is the Jetpack Compose `LocationButton` (`androidx.core.locationbutton:locationbutton-compose:1.0.0-alpha01`, still an alpha release), hosted in a `ComposeView`, instead of the Views `LocationButton`, which can show Google's compat button next to the system button on Android 17 ([issue tracker](https://issuetracker.google.com/issues/567953859)). +- BREAKING CHANGE: The host Activity must be a `ComponentActivity` (`AppCompatActivity` is one), as the Compose button finds its Activity and permission launcher through it. + ## [2.2.2] ### 2026-08-04 diff --git a/README.md b/README.md index 5aed36e..09ab349 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ The `IONGLOCController` class provides the main features of the Library, which a - [Motivation](#motivation) - [Usage](#usage) +- [Location Button](#location-button) - [Methods](#methods) - [Obtain the current location of the device](#obtain-the-current-location-of-the-device) - [Add a watch for periodic location updates](#add-a-watch-for-periodic-location-updates) @@ -35,6 +36,36 @@ In your app-level gradle file, import the `ion-android-geolocation` library like } ``` +## Location Button + +`IONGLOCLocationButtonRegistry.register(controller, ...)` registers the +`os.locationButton` native component. The host plugin exposes the corresponding web +component. The button is the Jetpack Compose `LocationButton` from +`androidx.core.locationbutton:locationbutton-compose`, hosted in a `ComposeView`. The permission +flow is handled by that `LocationButton` itself: the system button on Android 17+, and a locally +rendered button with its default permission flow on older versions (see the Activity requirement +below). + +The component emits `grant`, `position`, and `buttonError` events. + +### Requirements + +Since version 4.0.0, the library ships as a single AAR that includes the Location Button, so it requires: + +- `compileSdk` 37 or higher (apps built with MABS 13). `aarMetadata` enforces this. +- Android Gradle Plugin 9.1 or higher and Kotlin 2.1 or higher in the consuming build, because + `androidx.core.locationbutton` requires them. +- `minSdk` 26 or higher. +- The host Activity must be a `ComponentActivity` (`AppCompatActivity` is one), because the + Compose button finds its Activity and the permission launcher (an `ActivityResultRegistryOwner`) + through it. + +`androidx.core.locationbutton:locationbutton-compose` is still an **alpha** release +(`1.0.0-alpha01`, the latest published at the time of writing) and its API may change +incompatibly. The version is pinned, not a range. Expect +roughly 1 MB more in an APK built with R8, and several MB more without it. The `core.locationbutton` library should +be reviewed regularly and updated when newer (more stable) ones are published. + ## Methods As mentioned before, the library offers the `IONGLOCController` class that provides the following methods to interact with: @@ -119,4 +150,4 @@ Common issues and solutions: ## Support -- Report issues on our [Issue Tracker](https://github.com/ionic-team/ion-android-geolocation/issues) \ No newline at end of file +- Report issues on our [Issue Tracker](https://github.com/ionic-team/ion-android-geolocation/issues) diff --git a/build.gradle b/build.gradle index be609c1..c29bcfc 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,4 @@ buildscript { - ext.kotlin_version = "1.9.25" ext.jacocoVersion = '0.8.7' repositories { google() @@ -10,16 +9,16 @@ buildscript { } dependencies { if (System.getenv("SHOULD_PUBLISH") == "true") { - classpath("io.github.gradle-nexus:publish-plugin:1.1.0") + classpath("io.github.gradle-nexus:publish-plugin:2.0.0") } - classpath 'com.android.tools.build:gradle:8.13.0' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath 'com.android.tools.build:gradle:9.2.1' + classpath 'org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.2.10' classpath "org.jacoco:org.jacoco.core:$jacocoVersion" } } plugins { - id "org.sonarqube" version "3.5.0.2730" + id "org.sonarqube" version "7.6.0.18749" } sonarqube { @@ -36,22 +35,28 @@ if (System.getenv("SHOULD_PUBLISH") == "true") { } apply plugin: "com.android.library" -apply plugin: "kotlin-android" apply plugin: "jacoco" +apply plugin: "org.jetbrains.kotlin.plugin.compose" android { namespace "io.ionic.libs.iongeolocationlib" - compileSdk 36 + compileSdk 37 + + buildFeatures { + compose true + } defaultConfig { - minSdk 24 - targetSdk 36 + minSdk 26 + targetSdk 37 versionCode 5 versionName "2.2.2" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - vectorDrawables { - useSupportLibrary true + + // androidx.core.locationbutton needs compileSdk 37 (MABS 13 / Capacitor 9), so consumers must too. + aarMetadata { + minCompileSdk = 37 } } @@ -65,9 +70,6 @@ android { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } - kotlinOptions { - jvmTarget = '17' - } task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) { @@ -98,8 +100,8 @@ android { unitTests.returnDefaultValues = true } - lintOptions { - abortOnError false + lint { + abortOnError = false } publishing { @@ -110,10 +112,21 @@ android { repositories { google() mavenCentral() + flatDir { dirs 'libs' } } dependencies { implementation 'androidx.core:core-ktx:1.16.0' + // Using compose androidx library instead of views because Views has UI issues + // See https://issuetracker.google.com/issues/567953859 + implementation 'androidx.core.locationbutton:locationbutton-compose:1.0.0-alpha01' + implementation 'androidx.compose.foundation:foundation:1.12.1' + if (System.getenv("SHOULD_PUBLISH") == "true") { + api 'io.ionic.libs:ionnativeislands-android:1.0.0' + } else { + compileOnly(name: 'ionnativeislands-android-release', ext: 'aar') + testImplementation(name: 'ionnativeislands-android-release', ext: 'aar') + } implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0' @@ -131,4 +144,4 @@ dependencies { if (System.getenv("SHOULD_PUBLISH") == "true") { apply from: file("./scripts/publish-module.gradle") -} \ No newline at end of file +} diff --git a/gradle.properties b/gradle.properties index 7ef2f28..00a6ca7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -12,4 +12,3 @@ # org.gradle.parallel=true #Fri Apr 08 09:41:39 WEST 2022 android.useAndroidX=true -android.enableJetifier=true diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index d4081da..c61a118 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/libs/ionnativeislands-android-release.aar b/libs/ionnativeislands-android-release.aar new file mode 100644 index 0000000..fb32521 Binary files /dev/null and b/libs/ionnativeislands-android-release.aar differ diff --git a/pom.xml b/pom.xml index 11665ef..d8e08e4 100644 --- a/pom.xml +++ b/pom.xml @@ -6,5 +6,5 @@ 4.0.0 io.ionic.libs iongeolocation-android - 2.2.2 + 4.0.0-alpha.2 \ No newline at end of file diff --git a/scripts/publish-android.sh b/scripts/publish-android.sh index 570501f..d4299e2 100755 --- a/scripts/publish-android.sh +++ b/scripts/publish-android.sh @@ -21,9 +21,9 @@ else printf %"s\n" "Attempting to build and publish version $THE_VERSION" # Publish a release to the Maven repo - "$ANDROID_PATH"/gradlew clean build publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepository --no-daemon --max-workers 1 -b "$ANDROID_PATH"/build.gradle -Pandroid.useAndroidX=true > $LOG_OUTPUT 2>&1 + (cd "$ANDROID_PATH" && ./gradlew clean build publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepository --no-daemon --max-workers 1 -Pandroid.useAndroidX=true) > $LOG_OUTPUT 2>&1 # Stage a version - # "$ANDROID_PATH"/gradlew clean build publishReleasePublicationToSonatypeRepository --no-daemon --max-workers 1 -b "$ANDROID_PATH"/build.gradle -Pandroid.useAndroidX=true > $LOG_OUTPUT 2>&1 + # (cd "$ANDROID_PATH" && ./gradlew clean build publishReleasePublicationToSonatypeRepository --no-daemon --max-workers 1 -Pandroid.useAndroidX=true) > $LOG_OUTPUT 2>&1 echo $RESULT diff --git a/scripts/publish-module.gradle b/scripts/publish-module.gradle index 13527c0..f0ddc23 100644 --- a/scripts/publish-module.gradle +++ b/scripts/publish-module.gradle @@ -9,10 +9,6 @@ task androidSourcesJar(type: Jar) { from android.sourceSets.main.kotlin.srcDirs } -artifacts { - archives androidSourcesJar -} - group = 'io.ionic.libs' version = LIB_VERSION diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml index f0f34af..cabd695 100644 --- a/src/main/AndroidManifest.xml +++ b/src/main/AndroidManifest.xml @@ -1,4 +1,5 @@ + \ No newline at end of file diff --git a/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/IONGLOCController.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/IONGLOCController.kt index 663610b..b9839cd 100644 --- a/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/IONGLOCController.kt +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/IONGLOCController.kt @@ -25,7 +25,6 @@ import io.ionic.libs.iongeolocationlib.model.internal.LocationHandler import io.ionic.libs.iongeolocationlib.model.internal.LocationSettingsResult import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.flow.Flow @@ -142,7 +141,7 @@ class IONGLOCController internal constructor( * @param watchId a unique id identifying the watch * @return Flow in which location updates will be emitted, or failure if something went wrong in retrieving updates */ - @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class) + @OptIn(ExperimentalCoroutinesApi::class) fun addWatch( activity: Activity, options: IONGLOCLocationOptions, diff --git a/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/helper/IONGLOCExtensions.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/helper/IONGLOCExtensions.kt index 45714e0..c1c7178 100644 --- a/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/helper/IONGLOCExtensions.kt +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/controller/helper/IONGLOCExtensions.kt @@ -1,5 +1,6 @@ package io.ionic.libs.iongeolocationlib.controller.helper +import android.annotation.SuppressLint import android.location.Location import android.location.LocationManager import android.net.ConnectivityManager @@ -55,6 +56,7 @@ internal fun sendResultWithGoogleServicesException( * Extension function to convert Location object into OSLocationResult object * @return OSLocationResult object */ +@SuppressLint("NewApi") internal fun Location.toOSLocationResult( magneticHeading: Float? = null, trueHeading: Float? = null, @@ -106,4 +108,4 @@ fun Flow>.emitOrTimeoutBeforeFirstEmission(timeoutMillis: Long): F ) job.cancel() } - } \ No newline at end of file + } diff --git a/src/main/kotlin/io/ionic/libs/iongeolocationlib/model/IONGLOCException.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/model/IONGLOCException.kt index bc6ba8e..ed5af25 100644 --- a/src/main/kotlin/io/ionic/libs/iongeolocationlib/model/IONGLOCException.kt +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/model/IONGLOCException.kt @@ -23,4 +23,7 @@ sealed class IONGLOCException(message: String, cause: Throwable?) : Exception(me class IONGLOCLocationAndNetworkDisabledException( message: String, cause: Throwable? = null ) : IONGLOCException(message, cause) + class IONGLOCLocationButtonException( + message: String, cause: Throwable? = null + ) : IONGLOCException(message, cause) } \ No newline at end of file diff --git a/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegate.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegate.kt new file mode 100644 index 0000000..df8bd2c --- /dev/null +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegate.kt @@ -0,0 +1,149 @@ +package io.ionic.libs.iongeolocationlib.view + +import android.app.Activity +import io.ionic.libs.iongeolocationlib.controller.IONGLOCController +import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationOptions +import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationResult +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch + +/** + * Non-View state and logic of the LocationButton island: permission result handling, + * `fetchPosition()` delegation, lifecycle-aware cancellation, and event emission. + * The island owns one instance and wires the widget's callbacks to it. + */ +internal class IONGLOCLocationButtonDelegate( + private val activity: Activity, + private val controller: IONGLOCController, + private val errorCodeMapper: ((Throwable) -> String?)? = null, + private val positionMapper: ((IONGLOCLocationResult) -> Map)? = null, + private val eventSink: (name: String, payload: Map) -> Unit, +) { + private companion object { + /** Used when the host plugin's error code mapper has no code for an error. */ + const val DEFAULT_ERROR_CODE = "OS-PLUG-GLOC-0002" + } + + private val coroutineScope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob()) + + private var resumed = false + private var destroyed = false + private var pendingPermissionResult: Boolean? = null + private var pendingFetchResult: Result? = null + private var currentFetchJob: Job? = null + + var timeout = 10_000L + var maximumAge = 0L + var enableLocationManagerFallback = true + + fun onResume() { + if (destroyed) return + resumed = true + pendingPermissionResult?.let { granted -> + pendingPermissionResult = null + deliverPermissionResult(granted) + } + pendingFetchResult?.let { result -> + pendingFetchResult = null + deliverFetchResult(result) + } + } + + fun onPause() { + resumed = false + } + + fun onDestroy() { + destroyed = true + resumed = false + cancelOutstandingWork() + coroutineScope.cancel() + } + + /** Entry point for the permission result reported by the widget (system or library dialog). */ + fun permissionGranted(granted: Boolean) { + activity.runOnUiThread { + if (destroyed) return@runOnUiThread + if (resumed) { + deliverPermissionResult(granted) + } else { + pendingPermissionResult = granted + } + } + } + + fun emitError(reason: String, code: String? = null) { + emit("buttonError", mapOf("reason" to reason, "code" to (code ?: DEFAULT_ERROR_CODE))) + } + + /** Reports an error of the button itself, with the host plugin's code for it when it has one. */ + fun emitButtonError(error: Throwable) { + emitError(error.message ?: "location button session failed", errorCodeMapper?.invoke(error)) + } + + private fun deliverPermissionResult(granted: Boolean) { + emit("grant", mapOf("granted" to granted)) + if (granted) fetchPosition() + } + + private fun fetchPosition() { + if (!resumed || destroyed || currentFetchJob?.isActive == true) return + val job = coroutineScope.launch(start = CoroutineStart.LAZY) { + val options = IONGLOCLocationOptions( + timeout = timeout, + maximumAge = maximumAge, + enableHighAccuracy = true, // fixed: a precise-location button should not fetch imprecisely + enableLocationManagerFallback = enableLocationManagerFallback, + ) + val result = controller.getCurrentPosition(activity, options) + if (destroyed) return@launch + if (resumed) deliverFetchResult(result) else pendingFetchResult = result + } + currentFetchJob = job + job.invokeOnCompletion { if (currentFetchJob === job) currentFetchJob = null } + job.start() + } + + private fun deliverFetchResult(result: Result) { + result.fold( + onSuccess = { emitPosition(it) }, + onFailure = { emitError(it.message ?: "location fetch failed", errorCodeMapper?.invoke(it)) }, + ) + } + + private fun cancelOutstandingWork() { + pendingPermissionResult = null + pendingFetchResult = null + currentFetchJob?.cancel() + currentFetchJob = null + } + + private fun emitPosition(location: IONGLOCLocationResult) { + emit("position", positionMapper?.invoke(location) ?: defaultPositionPayload(location)) + } + + /** Flat shape used when no consumer supplies its own [positionMapper]. */ + private fun defaultPositionPayload(location: IONGLOCLocationResult): Map = mapOf( + "latitude" to location.latitude, + "longitude" to location.longitude, + "altitude" to location.altitude, + "accuracy" to location.accuracy.toDouble(), + "altitudeAccuracy" to location.altitudeAccuracy, + "heading" to location.heading, + "speed" to location.speed, + "timestamp" to location.timestamp, + "magneticHeading" to location.magneticHeading, + "trueHeading" to location.trueHeading, + "headingAccuracy" to location.headingAccuracy, + "course" to location.course, + ) + + private fun emit(name: String, payload: Map) { + if (!destroyed) eventSink(name, payload) + } +} diff --git a/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt new file mode 100644 index 0000000..dc9491f --- /dev/null +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt @@ -0,0 +1,270 @@ +package io.ionic.libs.iongeolocationlib.view + +import android.app.Activity +import android.graphics.Color +import android.graphics.Rect +import android.os.Build +import android.view.SurfaceView +import android.view.View +import android.view.ViewGroup +import android.view.ViewTreeObserver +import android.widget.FrameLayout +import androidx.annotation.ChecksSdkIntAtLeast +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color as ComposeColor +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.unit.dp +import androidx.core.graphics.toColorInt +import androidx.core.locationbutton.compose.LocationButton +import androidx.core.locationbutton.compose.LocationButtonTextType +import io.ionic.libs.iongeolocationlib.controller.IONGLOCController +import io.ionic.libs.iongeolocationlib.model.IONGLOCException +import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationResult +import io.ionic.libs.ionnativeislandslib.NativeIsland +import io.ionic.libs.ionnativeislandslib.NativeIslandEventEmitting +import io.ionic.libs.ionnativeislandslib.NativeIslandSurfaceClip + +internal class IONGLOCLocationButtonIsland( + private val activity: Activity, + controller: IONGLOCController, + errorCodeMapper: ((Throwable) -> String?)? = null, + positionMapper: ((IONGLOCLocationResult) -> Map)? = null, +) : NativeIsland, NativeIslandEventEmitting, NativeIslandSurfaceClip { + + companion object { + @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.CINNAMON_BUN) + @JvmStatic + fun requiresUnobscuredSurface() = Build.VERSION.SDK_INT >= 37 + } + + override var eventSink: ((String, Map) -> Unit)? = null + + private val delegate = IONGLOCLocationButtonDelegate( + activity, + controller, + errorCodeMapper, + positionMapper, + ) { name, payload -> + eventSink?.invoke(name, payload) + } + + // Sizes are in dp, which equals CSS px: the runtime lays the host out from CSS px. + private data class ButtonConfig( + val textType: String = "precise-location", + val backgroundColor: Int = Color.rgb(11, 87, 208), + val textColor: Int = Color.WHITE, + val iconTint: Int = Color.WHITE, + val strokeColor: Int = Color.BLACK, + val cornerRadius: Float = 16f, + val strokeWidth: Float = 0f, + ) + + private var config by mutableStateOf(ButtonConfig()) + private var visibleRect: Rect? = null + private val clipListener = ViewTreeObserver.OnGlobalLayoutListener { applySurfaceClip() } + + private val button = ComposeView(activity).apply { + setContent { + val current = config + LocationButton( + modifier = Modifier.fillMaxSize(), + backgroundColor = ComposeColor(current.backgroundColor), + strokeColor = ComposeColor(current.strokeColor), + strokeWidth = current.strokeWidth.dp, + cornerRadius = current.cornerRadius.dp, + pressedCornerRadius = current.cornerRadius.dp, + iconTint = ComposeColor(current.iconTint), + textType = LOCATION_BUTTON_TEXT_TYPES.getValue(current.textType), + textColor = ComposeColor(current.textColor), + onError = { error -> + delegate.emitButtonError( + IONGLOCException.IONGLOCLocationButtonException( + error.message ?: "location button session failed", + error, + ), + ) + }, + onPermissionResult = { granted -> delegate.permissionGranted(granted) }, + ) + } + } + + private val buttonHost = object : FrameLayout(activity) { + private var attachPending = false + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + viewTreeObserver.addOnGlobalLayoutListener(clipListener) + attachButtonWhenReady() + } + + override fun onDetachedFromWindow() { + viewTreeObserver.removeOnGlobalLayoutListener(clipListener) + super.onDetachedFromWindow() + } + + override fun onVisibilityAggregated(isVisible: Boolean) { + super.onVisibilityAggregated(isVisible) + if (isVisible) attachButtonWhenReady() + } + + override fun onSizeChanged( + width: Int, + height: Int, + oldWidth: Int, + oldHeight: Int, + ) { + super.onSizeChanged(width, height, oldWidth, oldHeight) + attachButtonWhenReady() + } + + private fun attachButtonWhenReady() { + if ( + attachPending || + button.parent != null || + width < minimumTouchTarget || + height < minimumTouchTarget + ) return + + attachPending = true + postOnAnimation { + attachPending = false + if ( + button.parent == null && + isAttachedToWindow && + isShown && + width >= minimumTouchTarget && + height >= minimumTouchTarget + ) { + addView( + button, + LayoutParams( + LayoutParams.MATCH_PARENT, + LayoutParams.MATCH_PARENT, + ), + ) + applySurfaceClip() + } + } + } + } + + override val view: View get() = buttonHost + + override fun setVisibleRect(rect: Rect?) { + if (visibleRect == rect) return + visibleRect = rect?.let(::Rect) + applySurfaceClip() + } + + private fun applySurfaceClip() { + if (button.clipBounds != visibleRect) button.clipBounds = visibleRect + val surface = button.findSurfaceView() + if (surface != null && surface.clipBounds != visibleRect) surface.clipBounds = visibleRect + } + + override fun create(properties: Map) = applyConfig(properties) + + override fun update(properties: Map) = applyConfig(properties) + + override fun onResume() = delegate.onResume() + + override fun onPause() = delegate.onPause() + + override fun onDestroy() { + delegate.onDestroy() + button.disposeComposition() + buttonHost.removeAllViews() + } + + private fun applyConfig(params: Map) { + // Parse and validate every property first (each throws on an invalid value), then apply them together, + // so an invalid update changes nothing. + val textType = params.string("textType")?.also { + require(it in LOCATION_BUTTON_TEXT_TYPES) { "unsupported Location Button text type" } + } + val newConfig = config.copy( + textType = textType ?: config.textType, + backgroundColor = params.color("backgroundColor") ?: config.backgroundColor, + textColor = params.color("textColor") ?: config.textColor, + iconTint = params.color("iconTint") ?: config.iconTint, + strokeColor = params.color("strokeColor") ?: config.strokeColor, + cornerRadius = params.dimension("cornerRadius", 0.0, 68.0) ?: config.cornerRadius, + strokeWidth = params.dimension("strokeWidth", 0.0, 3.0) ?: config.strokeWidth, + ) + val timeout = params.long("timeout", minimum = 1) + val maximumAge = params.long("maximumAge", minimum = 0) + val enableLocationFallback = params.boolean("enableLocationFallback") + + config = newConfig + timeout?.let { delegate.timeout = it } + maximumAge?.let { delegate.maximumAge = it } + enableLocationFallback?.let { delegate.enableLocationManagerFallback = it } + } + + private fun Map.string(name: String): String? { + val value = this[name] ?: return null + require(value is String) { "$name must be a string" } + return value + } + + private fun Map.color(name: String): Int? { + val value = string(name) ?: return null + require(HEX_COLOR.matches(value)) { "$name must use #RRGGBB" } + return value.toColorInt() + } + + private fun Map.dimension( + name: String, + minimum: Double, + maximum: Double, + ): Float? { + val value = this[name] ?: return null + require(value is Number) { "$name must be a number" } + val cssPixels = value.toDouble() + require(cssPixels.isFinite() && cssPixels in minimum..maximum) { + "$name must be between $minimum and $maximum CSS pixels" + } + return cssPixels.toFloat() + } + + private val minimumTouchTarget: Int + get() = (48f * button.resources.displayMetrics.density).toInt() + + private fun View.findSurfaceView(): SurfaceView? { + if (this is SurfaceView) return this + if (this is ViewGroup) { + for (i in 0 until childCount) getChildAt(i).findSurfaceView()?.let { return it } + } + return null + } +} + +private val LOCATION_BUTTON_TEXT_TYPES = mapOf( + "precise-location" to LocationButtonTextType.PreciseLocation, + "use-precise-location" to LocationButtonTextType.UsePreciseLocation, + "share-precise-location" to LocationButtonTextType.SharePreciseLocation, + "near-my-precise-location" to LocationButtonTextType.NearMyPreciseLocation, + "near-your-precise-location" to LocationButtonTextType.NearYourPreciseLocation, + "none" to LocationButtonTextType.None, +) + +private val HEX_COLOR = Regex("^#[0-9A-Fa-f]{6}$") + +internal fun Map.long(name: String, minimum: Long): Long? { + val value = this[name] ?: return null + require(value is Number) { "$name must be a number" } + val number = value.toDouble() + require(number.isFinite() && number >= minimum) { "$name must be at least $minimum" } + return value.toLong() +} + +internal fun Map.boolean(name: String): Boolean? { + val value = this[name] ?: return null + require(value is Boolean) { "$name must be a boolean" } + return value +} diff --git a/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonRegistry.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonRegistry.kt new file mode 100644 index 0000000..dff7569 --- /dev/null +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonRegistry.kt @@ -0,0 +1,29 @@ +package io.ionic.libs.iongeolocationlib.view + +import io.ionic.libs.iongeolocationlib.controller.IONGLOCController +import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationResult +import io.ionic.libs.ionnativeislandslib.NativeIslandAccessibility +import io.ionic.libs.ionnativeislandslib.NativeIslandsRegistry + +/** Registers the location button island. */ +object IONGLOCLocationButtonRegistry { + @JvmStatic + fun register( + controller: IONGLOCController, + errorCodeMapper: ((Throwable) -> String?)? = null, + positionMapper: ((IONGLOCLocationResult) -> Map)? = null, + ) { + NativeIslandsRegistry.register( + componentName = "os.locationButton", + accessibility = NativeIslandAccessibility.NATIVE, + requiresUnobscuredSurface = requiresUnobscuredSurface(), + factory = { _, activity -> + IONGLOCLocationButtonIsland(activity, controller, errorCodeMapper, positionMapper) + }, + ) + } + + @JvmStatic + fun requiresUnobscuredSurface(): Boolean = + IONGLOCLocationButtonIsland.requiresUnobscuredSurface() +} diff --git a/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegateTest.kt b/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegateTest.kt new file mode 100644 index 0000000..e69fb99 --- /dev/null +++ b/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegateTest.kt @@ -0,0 +1,392 @@ +package io.ionic.libs.iongeolocationlib.view + +import android.app.Activity +import io.ionic.libs.iongeolocationlib.controller.IONGLOCController +import io.ionic.libs.iongeolocationlib.model.IONGLOCException +import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationOptions +import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationResult +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestCoroutineScheduler +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class IONGLOCLocationButtonDelegateTest { + + private val testScheduler = TestCoroutineScheduler() + private val testDispatcher = StandardTestDispatcher(testScheduler) + + private val activity = mockk() + private val controller = mockk() + private val events = mutableListOf>>() + + private lateinit var delegate: IONGLOCLocationButtonDelegate + + @Before + fun setUp() { + Dispatchers.setMain(testDispatcher) + every { activity.runOnUiThread(any()) } answers { firstArg().run() } + + delegate = createDelegate() + delegate.onResume() + } + + private fun createDelegate( + errorCodeMapper: ((Throwable) -> String?)? = null, + positionMapper: ((IONGLOCLocationResult) -> Map)? = null, + ): IONGLOCLocationButtonDelegate = + IONGLOCLocationButtonDelegate(activity, controller, errorCodeMapper, positionMapper) { name, payload -> + events += name to payload + } + + @After + fun tearDown() { + Dispatchers.resetMain() + } + + private fun sampleResult() = IONGLOCLocationResult( + latitude = 1.0, + longitude = 2.0, + altitude = 3.0, + accuracy = 4f, + altitudeAccuracy = 5f, + heading = 6f, + speed = 7f, + timestamp = 8L, + magneticHeading = 9f, + trueHeading = 10f, + headingAccuracy = 11f, + course = 12f, + ) + + // region getCurrentPosition() options + + @Test + fun `given permission is granted, getCurrentPosition receives the configured options`() { + coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(sampleResult()) + delegate.timeout = 5_000L + delegate.maximumAge = 60_000L + delegate.enableLocationManagerFallback = false + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + coVerify { + controller.getCurrentPosition( + activity, + IONGLOCLocationOptions( + timeout = 5_000L, + maximumAge = 60_000L, + enableHighAccuracy = true, + enableLocationManagerFallback = false, + ), + ) + } + } + + // endregion + + // region success/failure -> event mapping + + @Test + fun `given no position mapper is supplied, when the fetch succeeds, position event carries the flat default shape`() { + val result = sampleResult() + coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(result) + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + assertEquals("grant" to mapOf("granted" to true), events[0]) + assertEquals( + "position" to mapOf( + "latitude" to result.latitude, + "longitude" to result.longitude, + "altitude" to result.altitude, + "accuracy" to result.accuracy.toDouble(), + "altitudeAccuracy" to result.altitudeAccuracy, + "heading" to result.heading, + "speed" to result.speed, + "timestamp" to result.timestamp, + "magneticHeading" to result.magneticHeading, + "trueHeading" to result.trueHeading, + "headingAccuracy" to result.headingAccuracy, + "course" to result.course, + ), + events[1], + ) + } + + @Test + fun `given a position mapper is supplied, when the fetch succeeds, position event carries the mapper's shape`() { + delegate = createDelegate( + positionMapper = { location -> + mapOf("timestamp" to location.timestamp, "coords" to mapOf("latitude" to location.latitude)) + }, + ) + delegate.onResume() + val result = sampleResult() + coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(result) + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + assertEquals("grant" to mapOf("granted" to true), events[0]) + assertEquals( + "position" to mapOf("timestamp" to result.timestamp, "coords" to mapOf("latitude" to result.latitude)), + events[1], + ) + } + + @Test + fun `given no error code mapper is supplied, when the fetch fails, buttonError carries the default code`() { + coEvery { controller.getCurrentPosition(any(), any()) } returns + Result.failure(IONGLOCException.IONGLOCLocationRetrievalTimeoutException("timed out")) + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + assertEquals("grant" to mapOf("granted" to true), events[0]) + assertEquals( + "buttonError" to mapOf("reason" to "timed out", "code" to "OS-PLUG-GLOC-0002"), + events[1], + ) + } + + @Test + fun `given an error code mapper is supplied, when the fetch fails, buttonError carries the mapper's code`() { + delegate = createDelegate(errorCodeMapper = { exception -> + (exception as? IONGLOCException.IONGLOCLocationRetrievalTimeoutException)?.let { "OS-PLUG-GLOC-0010" } + }) + delegate.onResume() + coEvery { controller.getCurrentPosition(any(), any()) } returns + Result.failure(IONGLOCException.IONGLOCLocationRetrievalTimeoutException("timed out")) + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + assertEquals("grant" to mapOf("granted" to true), events[0]) + assertEquals( + "buttonError" to mapOf("reason" to "timed out", "code" to "OS-PLUG-GLOC-0010"), + events[1], + ) + } + + @Test + fun `given an error code mapper is supplied but returns null for this exception, buttonError carries the default code`() { + delegate = createDelegate(errorCodeMapper = { null }) + delegate.onResume() + coEvery { controller.getCurrentPosition(any(), any()) } returns + Result.failure(IONGLOCException.IONGLOCLocationRetrievalTimeoutException("timed out")) + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + assertEquals( + "buttonError" to mapOf("reason" to "timed out", "code" to "OS-PLUG-GLOC-0002"), + events[1], + ) + } + + @Test + fun `given the button reports an error, buttonError carries the mapper's code for it`() { + delegate = createDelegate(errorCodeMapper = { exception -> + (exception as? IONGLOCException.IONGLOCLocationButtonException)?.let { "OS-PLUG-GLOC-0019" } + }) + + delegate.emitButtonError(IONGLOCException.IONGLOCLocationButtonException("session closed")) + + assertEquals( + listOf("buttonError" to mapOf("reason" to "session closed", "code" to "OS-PLUG-GLOC-0019")), + events, + ) + } + + @Test + fun `given the button reports an error and no mapper is supplied, buttonError carries the default code`() { + delegate.emitButtonError(IONGLOCException.IONGLOCLocationButtonException("session closed")) + + assertEquals( + listOf("buttonError" to mapOf("reason" to "session closed", "code" to "OS-PLUG-GLOC-0002")), + events, + ) + } + + // endregion + + @Test + fun `given permission is denied, grant(false) is emitted and no fetch happens`() { + delegate.permissionGranted(false) + testScheduler.advanceUntilIdle() + + assertEquals(listOf("grant" to mapOf("granted" to false)), events) + coVerify(exactly = 0) { controller.getCurrentPosition(any(), any()) } + } + + // region re-entrancy guard + + @Test + fun `given a fetch is already in flight, a second permissionGranted(true) does not start another fetch`() { + coEvery { controller.getCurrentPosition(any(), any()) } coAnswers { + delay(10_000) + Result.success(sampleResult()) + } + + delegate.permissionGranted(true) + testScheduler.runCurrent() + + delegate.permissionGranted(true) + + testScheduler.advanceUntilIdle() + + coVerify(exactly = 1) { controller.getCurrentPosition(any(), any()) } + } + + @Test + fun `given a fetch completes without suspending, a later permissionGranted(true) still fetches`() { + // Main.immediate runs the launched block eagerly in production; an unconfined dispatcher reproduces it. + Dispatchers.setMain(UnconfinedTestDispatcher(testScheduler)) + val eagerDelegate = createDelegate() + eagerDelegate.onResume() + coEvery { controller.getCurrentPosition(any(), any()) } returns + Result.failure(IONGLOCException.IONGLOCLocationRetrievalTimeoutException("fast failure")) + + eagerDelegate.permissionGranted(true) + eagerDelegate.permissionGranted(true) + + coVerify(exactly = 2) { controller.getCurrentPosition(any(), any()) } + } + + // endregion + + // region lifecycle + + @Test + fun `given a fetch is suspended mid-flight, onPause does not cancel it and its position is delivered on resume`() { + coEvery { controller.getCurrentPosition(any(), any()) } coAnswers { + delay(10_000) // e.g. waiting for the "turn on location" dialog, which pauses the Activity + Result.success(sampleResult()) + } + + delegate.permissionGranted(true) + testScheduler.runCurrent() // reach the suspension point inside the launched coroutine + + delegate.onPause() + testScheduler.advanceUntilIdle() // the fetch completes while paused + + assertTrue(events.none { it.first == "position" }) + + delegate.onResume() + + assertEquals(1, events.count { it.first == "position" }) + coVerify(exactly = 1) { controller.getCurrentPosition(any(), any()) } + } + + @Test + fun `given a fetch fails while the island is paused, buttonError is delivered on resume`() { + coEvery { controller.getCurrentPosition(any(), any()) } coAnswers { + delay(10_000) + Result.failure(IONGLOCException.IONGLOCLocationRetrievalTimeoutException("timed out")) + } + + delegate.permissionGranted(true) + testScheduler.runCurrent() + delegate.onPause() + testScheduler.advanceUntilIdle() + + assertTrue(events.none { it.first == "buttonError" }) + + delegate.onResume() + + assertEquals(1, events.count { it.first == "buttonError" }) + } + + @Test + fun `given a fetch finished while paused, onDestroy drops its result and a later onResume does not deliver it`() { + coEvery { controller.getCurrentPosition(any(), any()) } coAnswers { + delay(10_000) + Result.success(sampleResult()) + } + + delegate.permissionGranted(true) + testScheduler.runCurrent() + delegate.onPause() + testScheduler.advanceUntilIdle() + + delegate.onDestroy() + delegate.onResume() + + assertTrue(events.none { it.first == "position" }) + } + + @Test + fun `given a fetch is suspended mid-flight, onDestroy cancels it and a later onResume does not revive it`() { + coEvery { controller.getCurrentPosition(any(), any()) } coAnswers { + delay(10_000) + Result.success(sampleResult()) + } + + delegate.permissionGranted(true) + testScheduler.runCurrent() + + delegate.onDestroy() + testScheduler.advanceUntilIdle() + delegate.onResume() + + assertTrue(events.none { it.first == "position" }) + } + + @Test + fun `given onDestroy has already been called, permissionGranted is a no-op`() { + delegate.onDestroy() + + delegate.permissionGranted(true) + + assertTrue(events.isEmpty()) + coVerify(exactly = 0) { controller.getCurrentPosition(any(), any()) } + } + + // endregion + + // region permissionGranted() external entry point + + @Test + fun `given the island is resumed, permissionGranted delivers immediately`() { + coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(sampleResult()) + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + assertEquals("grant" to mapOf("granted" to true), events[0]) + } + + @Test + fun `given the island is paused, permissionGranted defers delivery to the next onResume`() { + delegate.onPause() + coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(sampleResult()) + + delegate.permissionGranted(true) + testScheduler.advanceUntilIdle() + + assertTrue(events.isEmpty()) + + delegate.onResume() + testScheduler.advanceUntilIdle() + + assertEquals("grant" to mapOf("granted" to true), events[0]) + } + + // endregion +} diff --git a/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIslandTest.kt b/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIslandTest.kt new file mode 100644 index 0000000..350bdac --- /dev/null +++ b/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIslandTest.kt @@ -0,0 +1,86 @@ +package io.ionic.libs.iongeolocationlib.view + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Test + +class IONGLOCLocationButtonIslandTest { + + @Test + fun `when long property is a valid number at or above minimum, value is returned`() { + val params = mapOf("timeout" to 5_000L) + + assertEquals(5_000L, params.long("timeout", minimum = 1)) + } + + @Test + fun `when long property is missing, null is returned`() { + val params = emptyMap() + + assertNull(params.long("timeout", minimum = 1)) + } + + @Test + fun `when long property is below minimum, it is rejected`() { + val params = mapOf("timeout" to -1L) + + assertThrows(IllegalArgumentException::class.java) { params.long("timeout", minimum = 1) } + } + + @Test + fun `when long property is zero and minimum is one, it is rejected`() { + val params = mapOf("timeout" to 0L) + + assertThrows(IllegalArgumentException::class.java) { params.long("timeout", minimum = 1) } + } + + @Test + fun `when long property is not a number, it is rejected`() { + val params = mapOf("timeout" to "5000") + + assertThrows(IllegalArgumentException::class.java) { params.long("timeout", minimum = 1) } + } + + @Test + fun `when long property is not finite, it is rejected`() { + val params = mapOf("maximumAge" to Double.NaN) + + assertThrows(IllegalArgumentException::class.java) { params.long("maximumAge", minimum = 0) } + } + + @Test + fun `when boolean property is not a boolean, it is rejected`() { + val params = mapOf("enableLocationFallback" to "true") + + assertThrows(IllegalArgumentException::class.java) { params.boolean("enableLocationFallback") } + } + + @Test + fun `when long property is zero and minimum is zero, zero is returned`() { + val params = mapOf("maximumAge" to 0L) + + assertEquals(0L, params.long("maximumAge", minimum = 0)) + } + + @Test + fun `when boolean property is true, true is returned`() { + val params = mapOf("enableLocationFallback" to true) + + assertEquals(true, params.boolean("enableLocationFallback")) + } + + @Test + fun `when boolean property is false, false is returned`() { + val params = mapOf("enableLocationFallback" to false) + + assertEquals(false, params.boolean("enableLocationFallback")) + } + + @Test + fun `when boolean property is missing, null is returned`() { + val params = emptyMap() + + assertNull(params.boolean("enableLocationFallback")) + } +}