diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ff8513..b6f6023 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ 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. @@ -13,6 +15,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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: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. + ## [2.2.2] ### 2026-08-04 diff --git a/README.md b/README.md index 68d1c2a..2bdd4fd 100644 --- a/README.md +++ b/README.md @@ -38,12 +38,28 @@ In your app-level gradle file, import the `ion-android-geolocation` library like ## Location Button -`IONGLOCLocationButtonRegistry.register(activity, requester)` registers the -`os.locationButton` native component. The host plugin supplies the precise-location -permission requester and exposes the corresponding web component. +`IONGLOCLocationButtonRegistry.register(controller, ...)` registers the +`os.locationButton` native component. The host plugin exposes the corresponding web +component. The permission flow is handled by the `androidx.core.locationbutton` +`LocationButton` itself: the system button on Android 17+, and the library's own locally +rendered button with its default permission flow on older versions (the host Activity must +be an `ActivityResultRegistryOwner`, which `AppCompatActivity` is). The component emits `grant`, `position`, and `buttonError` events. +### Requirements + +Since version 3.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. + +`androidx.core.locationbutton:locationbutton` 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. + ## Methods As mentioned before, the library offers the `IONGLOCController` class that provides the following methods to interact with: diff --git a/api37/build.gradle b/api37/build.gradle deleted file mode 100644 index 2cac087..0000000 --- a/api37/build.gradle +++ /dev/null @@ -1,62 +0,0 @@ -plugins { - id 'com.android.library' version '9.2.1' -} - -android { - namespace = "io.ionic.libs.iongeolocationlib" - compileSdk = 37 - - sourceSets { - main { - kotlin.srcDirs = ['../src/main/kotlin', 'src/main/kotlin'] - manifest.srcFile 'src/main/AndroidManifest.xml' - } - } - - defaultConfig { - minSdk = 24 - targetSdk = 37 - versionCode = 4 - versionName = "2.2.1" - - aarMetadata { - minCompileSdk = 37 - } - } - - buildTypes { - release { - minifyEnabled = false - proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), '../proguard-rules.pro' - } - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - packaging { - resources { - excludes += '/META-INF/{AL2.0,LGPL2.1}' - } - } - - lint { - abortOnError = false - } -} - -dependencies { - compileOnly files('../libs/ionnativeislands-android-release.aar') - - implementation 'androidx.core:core-ktx:1.18.0' - implementation 'androidx.core.locationbutton:locationbutton:1.0.0-alpha01' - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4' - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3' - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.4' - implementation 'com.google.android.gms:play-services-location:21.3.0' - implementation 'com.google.android.gms:play-services-base:18.5.0' - implementation 'androidx.activity:activity:1.6.0' - implementation 'androidx.activity:activity-ktx:1.9.3' -} diff --git a/api37/gradle/wrapper/gradle-wrapper.jar b/api37/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 1b33c55..0000000 Binary files a/api37/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/api37/gradle/wrapper/gradle-wrapper.properties b/api37/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index c61a118..0000000 --- a/api37/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/api37/gradlew b/api37/gradlew deleted file mode 100755 index 23d15a9..0000000 --- a/api37/gradlew +++ /dev/null @@ -1,251 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 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 -# - -############################################################################## -# -# Gradle 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 Gradle -# -# 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/HEAD/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 - -CLASSPATH="\\\"\\\"" - - -# 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" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - 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" \ - -classpath "$CLASSPATH" \ - -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/api37/gradlew.bat b/api37/gradlew.bat deleted file mode 100644 index 5eed7ee..0000000 --- a/api37/gradlew.bat +++ /dev/null @@ -1,94 +0,0 @@ -@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 Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@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 - -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. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -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. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH= - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/api37/settings.gradle b/api37/settings.gradle deleted file mode 100644 index 278fe6e..0000000 --- a/api37/settings.gradle +++ /dev/null @@ -1,17 +0,0 @@ -pluginManagement { - repositories { - google() - mavenCentral() - gradlePluginPortal() - } -} - -dependencyResolutionManagement { - repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) - repositories { - google() - mavenCentral() - } -} - -rootProject.name = "IONGeolocationLibApi37" diff --git a/api37/src/main/AndroidManifest.xml b/api37/src/main/AndroidManifest.xml deleted file mode 100644 index 12c6f93..0000000 --- a/api37/src/main/AndroidManifest.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/build.gradle b/build.gradle index 7f912ee..ae1975a 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,15 @@ 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.jacoco:org.jacoco.core:$jacocoVersion" } } plugins { - id "org.sonarqube" version "3.5.0.2730" + id "org.sonarqube" version "7.6.0.18749" } sonarqube { @@ -36,26 +34,23 @@ if (System.getenv("SHOULD_PUBLISH") == "true") { } apply plugin: "com.android.library" -apply plugin: "kotlin-android" apply plugin: "jacoco" android { namespace "io.ionic.libs.iongeolocationlib" - compileSdk 36 - - sourceSets { - main.java.srcDir 'src/compat/kotlin' - } + compileSdk 37 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 } } @@ -69,9 +64,6 @@ android { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } - kotlinOptions { - jvmTarget = '17' - } task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest']) { @@ -102,8 +94,8 @@ android { unitTests.returnDefaultValues = true } - lintOptions { - abortOnError false + lint { + abortOnError = false } publishing { @@ -119,7 +111,7 @@ repositories { dependencies { implementation 'androidx.core:core-ktx:1.16.0' - implementation 'androidx.appcompat:appcompat:1.7.1' + implementation 'androidx.core.locationbutton:locationbutton:1.0.0-alpha01' if (System.getenv("SHOULD_PUBLISH") == "true") { api 'io.ionic.libs:ionnativeislands-android:1.0.0' } else { 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/pom.xml b/pom.xml index 11665ef..f1a008b 100644 --- a/pom.xml +++ b/pom.xml @@ -6,5 +6,5 @@ 4.0.0 io.ionic.libs iongeolocation-android - 2.2.2 + 3.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/compat/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt b/src/compat/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt deleted file mode 100644 index d0a0551..0000000 --- a/src/compat/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt +++ /dev/null @@ -1,217 +0,0 @@ -package io.ionic.libs.iongeolocationlib.view - -import android.app.Activity -import android.content.Context -import android.graphics.Color -import android.graphics.Typeface -import android.graphics.drawable.GradientDrawable -import android.graphics.drawable.StateListDrawable -import android.util.TypedValue -import android.view.Gravity -import android.view.View -import android.widget.LinearLayout -import androidx.appcompat.content.res.AppCompatResources -import androidx.appcompat.widget.AppCompatImageView -import androidx.appcompat.widget.AppCompatTextView -import androidx.core.graphics.ColorUtils -import androidx.core.graphics.toColorInt -import androidx.core.graphics.drawable.DrawableCompat -import io.ionic.libs.iongeolocationlib.R -import io.ionic.libs.iongeolocationlib.controller.IONGLOCController -import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationResult -import io.ionic.libs.ionnativeislandslib.NativeIsland -import io.ionic.libs.ionnativeislandslib.NativeIslandEventEmitting - -/** - * AppCompat implementation of `os.locationButton`. It requests precise - * permission through its adapter and delegates location retrieval to - * [IONGLOCController.getCurrentPosition]. - */ -class IONGLOCLocationButtonIsland( - private val context: Context, - activity: Activity, - controller: IONGLOCController, - errorCodeMapper: ((Throwable) -> String?)? = null, - positionMapper: ((IONGLOCLocationResult) -> Map)? = null, -) : NativeIsland, NativeIslandEventEmitting { - - companion object { - @JvmStatic - fun requiresUnobscuredSurface() = false - } - - override var eventSink: ((String, Map) -> Unit)? = null - - private val density = context.resources.displayMetrics.density - private val delegate = IONGLOCLocationButtonDelegate( - activity, - controller, - errorCodeMapper, - positionMapper, - ) { name, payload -> - eventSink?.invoke(name, payload) - } - - private var textType = "precise-location" - private var backgroundColor = Color.rgb(11, 87, 208) - private var textColor = Color.WHITE - private var iconTint = Color.WHITE - private var strokeColor = Color.BLACK - private var cornerRadius = 16f * density - private var pressedCornerRadius = 12f * density - private var strokeWidth = 0f - private var clickablePadding = 6f * density - - private val iconView = AppCompatImageView(context) - private val labelView = AppCompatTextView(context).apply { - gravity = Gravity.CENTER - includeFontPadding = false - setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f) - typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) - } - private val button = LinearLayout(context).apply { - orientation = LinearLayout.HORIZONTAL - gravity = Gravity.CENTER - isClickable = true - isFocusable = true - minimumWidth = minimumTouchTarget - minimumHeight = minimumTouchTarget - setOnClickListener { delegate.requestPreciseLocation() } - addView(iconView, LinearLayout.LayoutParams(20f.dp, 20f.dp)) - addView(labelView, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 20f.dp)) - } - - init { - renderButton() - } - - override val view: View get() = button - - 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.setOnClickListener(null) - } - - private fun applyConfig(params: Map) { - params.string("textType")?.let { - require(it in LOCATION_BUTTON_TEXT) { - "unsupported Location Button text type" - } - textType = it - } - params.color("backgroundColor")?.let { backgroundColor = it } - params.color("textColor")?.let { textColor = it } - params.color("iconTint")?.let { iconTint = it } - params.color("strokeColor")?.let { strokeColor = it } - params.dimension("cornerRadius", 0.0, 68.0)?.let { cornerRadius = it } - params.dimension("pressedCornerRadius", 0.0, 68.0)?.let { - pressedCornerRadius = it - } - params.dimension("strokeWidth", 0.0, 3.0)?.let { strokeWidth = it } - params.dimension("clickablePadding", 4.0, 8.0)?.let { - clickablePadding = it - } - params.long("timeout", minimum = 1)?.let { delegate.timeout = it } - params.long("maximumAge", minimum = 0)?.let { delegate.maximumAge = it } - params.boolean("enableLocationFallback")?.let { delegate.enableLocationManagerFallback = it } - renderButton() - } - - private fun renderButton() { - val label = LOCATION_BUTTON_TEXT.getValue(textType) - labelView.text = if (textType == "none") "" else label - button.contentDescription = label - labelView.setTextColor(textColor) - - val padding = clickablePadding.toInt() - button.setPadding(padding, padding, padding, padding) - button.backgroundTintList = null - button.background = StateListDrawable().apply { - addState( - intArrayOf(android.R.attr.state_pressed), - buttonBackground( - color = ColorUtils.blendARGB(backgroundColor, Color.BLACK, 0.12f), - radius = pressedCornerRadius, - ), - ) - addState( - intArrayOf(), - buttonBackground(backgroundColor, cornerRadius), - ) - } - - val icon = requireNotNull( - AppCompatResources.getDrawable(context, R.drawable.iongloc_ic_location), - ).mutate() - DrawableCompat.setTint(icon, iconTint) - iconView.setImageDrawable(icon) - labelView.layoutParams = - (labelView.layoutParams as LinearLayout.LayoutParams).apply { - marginStart = if (textType == "none") 0 else 8f.dp - } - } - - private fun buttonBackground(color: Int, radius: Float) = - GradientDrawable().apply { - shape = GradientDrawable.RECTANGLE - setColor(color) - cornerRadius = radius - setStroke(strokeWidth.toInt(), strokeColor) - } - - 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 * density).toFloat() - } - - private val minimumTouchTarget: Int get() = (48f * density).toInt() - private val Float.dp: Int get() = (this * density).toInt() -} - -private val LOCATION_BUTTON_TEXT = mapOf( - "precise-location" to "Precise location", - "use-precise-location" to "Use precise location", - "share-precise-location" to "Share precise location", - "near-my-precise-location" to "Near my precise location", - "near-your-precise-location" to "Near your precise location", - "none" to "Share location", -) - -private val HEX_COLOR = Regex("^#[0-9A-Fa-f]{6}$") - -internal fun Map.long(name: String, minimum: Long): Long? { - val value = this[name] as? Number ?: return null - val long = value.toLong() - return if (long >= minimum) long else null -} - -internal fun Map.boolean(name: String): Boolean? = this[name] as? Boolean 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/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 index 0214fc2..88b9f38 100644 --- a/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegate.kt +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegate.kt @@ -1,9 +1,6 @@ package io.ionic.libs.iongeolocationlib.view -import android.Manifest import android.app.Activity -import android.content.pm.PackageManager -import androidx.core.content.ContextCompat import io.ionic.libs.iongeolocationlib.controller.IONGLOCController import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationOptions import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationResult @@ -15,9 +12,9 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.launch /** - * Non-View state and logic shared by both LocationButton islands: permission requesting, + * Non-View state and logic of the LocationButton island: permission result handling, * `fetchPosition()` delegation, lifecycle-aware cancellation, and event emission. - * Each island owns one instance and wires its own View/widget callbacks to it. + * The island owns one instance and wires the widget's callbacks to it. */ internal class IONGLOCLocationButtonDelegate( private val activity: Activity, @@ -26,12 +23,15 @@ internal class IONGLOCLocationButtonDelegate( 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 permissionRequestPending = false - private var permissionRequestGeneration = 0L private var pendingPermissionResult: Boolean? = null private var currentFetchJob: Job? = null @@ -60,50 +60,7 @@ internal class IONGLOCLocationButtonDelegate( coroutineScope.cancel() } - /** Runs the manual precise-location permission request flow, and fetches a position if granted. */ - fun requestPreciseLocation() { - if (!resumed || destroyed || permissionRequestPending || currentFetchJob != null) return - - if (hasFineLocationPermission()) { - deliverPermissionResult(true) - return - } - - val requester = IONGLOCLocationButtonRegistry.permissionRequester(activity) - if (requester == null) { - emitError("precise location permission requester unavailable") - return - } - - permissionRequestPending = true - val generation = ++permissionRequestGeneration - try { - requester.requestPreciseLocation { preciseGranted -> - activity.runOnUiThread { - if ( - destroyed || - !permissionRequestPending || - generation != permissionRequestGeneration - ) { - return@runOnUiThread - } - permissionRequestPending = false - permissionGranted(preciseGranted && hasFineLocationPermission()) - } - } - } catch (error: Exception) { - if ( - permissionRequestPending && - generation == permissionRequestGeneration && - !destroyed - ) { - permissionRequestPending = false - emitError(error.message ?: "precise location permission request failed") - } - } - } - - /** Entry point for a grant result that happened elsewhere (api37's native widget dialog). */ + /** Entry point for the permission result reported by the widget (system or library dialog). */ fun permissionGranted(granted: Boolean) { activity.runOnUiThread { if (destroyed) return@runOnUiThread @@ -116,14 +73,13 @@ internal class IONGLOCLocationButtonDelegate( } fun emitError(reason: String, code: String? = null) { - emit("buttonError", mapOf("reason" to reason, "code" to code)) + emit("buttonError", mapOf("reason" to reason, "code" to (code ?: DEFAULT_ERROR_CODE))) } - private fun hasFineLocationPermission(): Boolean = - ContextCompat.checkSelfPermission( - activity, - Manifest.permission.ACCESS_FINE_LOCATION, - ) == PackageManager.PERMISSION_GRANTED + /** 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)) @@ -150,8 +106,6 @@ internal class IONGLOCLocationButtonDelegate( } private fun cancelOutstandingWork() { - permissionRequestPending = false - permissionRequestGeneration += 1 pendingPermissionResult = null cancelLocationFetch() } diff --git a/api37/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt similarity index 91% rename from api37/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt rename to src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt index 00091ef..831d41c 100644 --- a/api37/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonIsland.kt @@ -9,9 +9,11 @@ import android.view.SurfaceView import android.view.View import android.view.ViewGroup import android.widget.FrameLayout +import androidx.annotation.ChecksSdkIntAtLeast import androidx.core.graphics.toColorInt import androidx.core.locationbutton.LocationButton 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 @@ -26,6 +28,7 @@ class IONGLOCLocationButtonIsland( ) : NativeIsland, NativeIslandEventEmitting, NativeIslandSurfaceClip { companion object { + @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.CINNAMON_BUN) @JvmStatic fun requiresUnobscuredSurface() = Build.VERSION.SDK_INT >= 37 } @@ -48,9 +51,7 @@ class IONGLOCLocationButtonIsland( private var iconTint = Color.WHITE private var strokeColor = Color.BLACK private var cornerRadius = 16f * density - private var pressedCornerRadius = 12f * density private var strokeWidth = 0f - private var clickablePadding = 6f * density private var visibleRect: Rect? = null private val button = LocationButton(context).apply { @@ -61,11 +62,13 @@ class IONGLOCLocationButtonIsland( setOnPermissionResultListener { granted -> delegate.permissionGranted(granted) } - setOnRequestPermissionsListener { - delegate.requestPreciseLocation() - } setOnErrorListener { error -> - delegate.emitError(error.message ?: "location button session failed") + delegate.emitButtonError( + IONGLOCException.IONGLOCLocationButtonException( + error.message ?: "location button session failed", + error, + ), + ) } } @@ -153,7 +156,6 @@ class IONGLOCLocationButtonIsland( override fun onDestroy() { delegate.onDestroy() button.setOnPermissionResultListener(null) - button.setOnRequestPermissionsListener(null) button.setOnErrorListener(null) button.parentActivity = null buttonHost.removeAllViews() @@ -171,13 +173,7 @@ class IONGLOCLocationButtonIsland( params.color("iconTint")?.let { iconTint = it } params.color("strokeColor")?.let { strokeColor = it } params.dimension("cornerRadius", 0.0, 68.0)?.let { cornerRadius = it } - params.dimension("pressedCornerRadius", 0.0, 68.0)?.let { - pressedCornerRadius = it - } params.dimension("strokeWidth", 0.0, 3.0)?.let { strokeWidth = it } - params.dimension("clickablePadding", 4.0, 8.0)?.let { - clickablePadding = it - } params.long("timeout", minimum = 1)?.let { delegate.timeout = it } params.long("maximumAge", minimum = 0)?.let { delegate.maximumAge = it } params.boolean("enableLocationFallback")?.let { delegate.enableLocationManagerFallback = it } @@ -191,11 +187,8 @@ class IONGLOCLocationButtonIsland( button.setIconTint(iconTint) button.setStrokeColor(strokeColor) button.setCornerRadius(cornerRadius) - button.setPressedCornerRadius(pressedCornerRadius) + button.setPressedCornerRadius(cornerRadius) button.setStrokeWidth(strokeWidth.toInt()) - - val padding = clickablePadding.toInt() - button.setPadding(padding, padding, padding, padding) } private fun Map.string(name: String): String? { diff --git a/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonRegistry.kt b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonRegistry.kt index 2726e00..55c819a 100644 --- a/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonRegistry.kt +++ b/src/main/kotlin/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonRegistry.kt @@ -1,23 +1,12 @@ package io.ionic.libs.iongeolocationlib.view -import android.app.Activity 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 -import java.lang.ref.WeakReference -import java.util.WeakHashMap -/** Adapter callback that reports whether precise location was granted. */ -fun interface IONGLOCLocationButtonPermissionRequester { - fun requestPreciseLocation(callback: (Boolean) -> Unit) -} - -/** Registers the location button and its host permission callback. */ +/** Registers the location button island. */ object IONGLOCLocationButtonRegistry { - private val permissionRequesters = - WeakHashMap>() - @JvmStatic fun register( controller: IONGLOCController, @@ -37,37 +26,4 @@ object IONGLOCLocationButtonRegistry { @JvmStatic fun requiresUnobscuredSurface(): Boolean = IONGLOCLocationButtonIsland.requiresUnobscuredSurface() - - @JvmStatic - fun register( - activity: Activity, - controller: IONGLOCController, - requester: IONGLOCLocationButtonPermissionRequester, - errorCodeMapper: ((Throwable) -> String?)? = null, - positionMapper: ((IONGLOCLocationResult) -> Map)? = null, - ) { - synchronized(permissionRequesters) { - permissionRequesters[activity] = WeakReference(requester) - } - register(controller, errorCodeMapper, positionMapper) - } - - @JvmStatic - fun unregister(activity: Activity) { - synchronized(permissionRequesters) { - permissionRequesters.remove(activity) - } - } - - internal fun permissionRequester( - activity: Activity, - ): IONGLOCLocationButtonPermissionRequester? = - synchronized(permissionRequesters) { - val reference = permissionRequesters[activity] - val requester = reference?.get() - if (reference != null && requester == null) { - permissionRequesters.remove(activity) - } - requester - } } diff --git a/src/main/res/drawable/iongloc_ic_location.xml b/src/main/res/drawable/iongloc_ic_location.xml deleted file mode 100644 index d1ff624..0000000 --- a/src/main/res/drawable/iongloc_ic_location.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - diff --git a/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegateTest.kt b/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegateTest.kt index 7b51606..dc8605f 100644 --- a/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegateTest.kt +++ b/src/test/java/io/ionic/libs/iongeolocationlib/view/IONGLOCLocationButtonDelegateTest.kt @@ -1,9 +1,6 @@ package io.ionic.libs.iongeolocationlib.view -import android.Manifest import android.app.Activity -import android.content.pm.PackageManager -import androidx.core.content.ContextCompat import io.ionic.libs.iongeolocationlib.controller.IONGLOCController import io.ionic.libs.iongeolocationlib.model.IONGLOCException import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationOptions @@ -11,14 +8,7 @@ import io.ionic.libs.iongeolocationlib.model.IONGLOCLocationResult import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every -import io.mockk.just import io.mockk.mockk -import io.mockk.mockkObject -import io.mockk.mockkStatic -import io.mockk.runs -import io.mockk.unmockkObject -import io.mockk.unmockkStatic -import io.mockk.verify import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay @@ -40,7 +30,6 @@ class IONGLOCLocationButtonDelegateTest { private val activity = mockk() private val controller = mockk() - private val permissionRequester = mockk() private val events = mutableListOf>>() private lateinit var delegate: IONGLOCLocationButtonDelegate @@ -48,10 +37,7 @@ class IONGLOCLocationButtonDelegateTest { @Before fun setUp() { Dispatchers.setMain(testDispatcher) - mockkStatic(ContextCompat::class) - mockkObject(IONGLOCLocationButtonRegistry) every { activity.runOnUiThread(any()) } answers { firstArg().run() } - every { IONGLOCLocationButtonRegistry.permissionRequester(activity) } returns permissionRequester delegate = createDelegate() delegate.onResume() @@ -67,23 +53,9 @@ class IONGLOCLocationButtonDelegateTest { @After fun tearDown() { - unmockkObject(IONGLOCLocationButtonRegistry) - unmockkStatic(ContextCompat::class) Dispatchers.resetMain() } - private fun grantedPermission() { - every { - ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) - } returns PackageManager.PERMISSION_GRANTED - } - - private fun deniedPermission() { - every { - ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) - } returns PackageManager.PERMISSION_DENIED - } - private fun sampleResult() = IONGLOCLocationResult( latitude = 1.0, longitude = 2.0, @@ -102,14 +74,13 @@ class IONGLOCLocationButtonDelegateTest { // region getCurrentPosition() options @Test - fun `given permission already granted, when requestPreciseLocation is called, getCurrentPosition receives the configured options`() { - grantedPermission() + 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.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.advanceUntilIdle() coVerify { @@ -131,11 +102,10 @@ class IONGLOCLocationButtonDelegateTest { @Test fun `given no position mapper is supplied, when the fetch succeeds, position event carries the flat default shape`() { - grantedPermission() val result = sampleResult() coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(result) - delegate.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.advanceUntilIdle() assertEquals("grant" to mapOf("granted" to true), events[0]) @@ -166,11 +136,10 @@ class IONGLOCLocationButtonDelegateTest { }, ) delegate.onResume() - grantedPermission() val result = sampleResult() coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(result) - delegate.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.advanceUntilIdle() assertEquals("grant" to mapOf("granted" to true), events[0]) @@ -181,17 +150,16 @@ class IONGLOCLocationButtonDelegateTest { } @Test - fun `given no error code mapper is supplied, when the fetch fails, buttonError carries a null code`() { - grantedPermission() + 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.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.advanceUntilIdle() assertEquals("grant" to mapOf("granted" to true), events[0]) assertEquals( - "buttonError" to mapOf("reason" to "timed out", "code" to null), + "buttonError" to mapOf("reason" to "timed out", "code" to "OS-PLUG-GLOC-0002"), events[1], ) } @@ -202,11 +170,10 @@ class IONGLOCLocationButtonDelegateTest { (exception as? IONGLOCException.IONGLOCLocationRetrievalTimeoutException)?.let { "OS-PLUG-GLOC-0010" } }) delegate.onResume() - grantedPermission() coEvery { controller.getCurrentPosition(any(), any()) } returns Result.failure(IONGLOCException.IONGLOCLocationRetrievalTimeoutException("timed out")) - delegate.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.advanceUntilIdle() assertEquals("grant" to mapOf("granted" to true), events[0]) @@ -217,112 +184,73 @@ class IONGLOCLocationButtonDelegateTest { } @Test - fun `given an error code mapper is supplied but returns null for this exception, buttonError carries a null code`() { + 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() - grantedPermission() coEvery { controller.getCurrentPosition(any(), any()) } returns Result.failure(IONGLOCException.IONGLOCLocationRetrievalTimeoutException("timed out")) - delegate.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.advanceUntilIdle() assertEquals( - "buttonError" to mapOf("reason" to "timed out", "code" to null), + "buttonError" to mapOf("reason" to "timed out", "code" to "OS-PLUG-GLOC-0002"), events[1], ) } @Test - fun `given permission is denied by the requester, grant(false) is emitted and no fetch happens`() { - deniedPermission() - every { permissionRequester.requestPreciseLocation(any()) } answers { - firstArg<(Boolean) -> Unit>().invoke(false) - } - - delegate.requestPreciseLocation() - testScheduler.advanceUntilIdle() - - assertEquals(listOf("grant" to mapOf("granted" to false)), events) - coVerify(exactly = 0) { controller.getCurrentPosition(any(), any()) } - } - - @Test - fun `given permission is not yet granted, when the requester eventually grants it, grant and position events are emitted`() { - every { - ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) - } returnsMany listOf(PackageManager.PERMISSION_DENIED, PackageManager.PERMISSION_GRANTED) - every { permissionRequester.requestPreciseLocation(any()) } answers { - firstArg<(Boolean) -> Unit>().invoke(true) - } - coEvery { controller.getCurrentPosition(any(), any()) } returns Result.success(sampleResult()) - - delegate.requestPreciseLocation() - testScheduler.advanceUntilIdle() - - assertEquals("grant" to mapOf("granted" to true), events[0]) - } - - @Test - fun `given no permission requester is registered, buttonError is emitted`() { - deniedPermission() - every { IONGLOCLocationButtonRegistry.permissionRequester(activity) } returns null + 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.requestPreciseLocation() + delegate.emitButtonError(IONGLOCException.IONGLOCLocationButtonException("session closed")) assertEquals( - listOf( - "buttonError" to mapOf( - "reason" to "precise location permission requester unavailable", - "code" to null, - ), - ), + listOf("buttonError" to mapOf("reason" to "session closed", "code" to "OS-PLUG-GLOC-0019")), events, ) } @Test - fun `given the requester throws, buttonError is emitted`() { - deniedPermission() - every { permissionRequester.requestPreciseLocation(any()) } throws RuntimeException("boom") - - delegate.requestPreciseLocation() + 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 "boom", "code" to null)), + listOf("buttonError" to mapOf("reason" to "session closed", "code" to "OS-PLUG-GLOC-0002")), events, ) } // endregion - // region re-entrancy guard - @Test - fun `given a permission request is already pending, a second requestPreciseLocation call does not invoke the requester again`() { - deniedPermission() - every { permissionRequester.requestPreciseLocation(any()) } just runs // never resolves -> stays pending - - delegate.requestPreciseLocation() - delegate.requestPreciseLocation() + fun `given permission is denied, grant(false) is emitted and no fetch happens`() { + delegate.permissionGranted(false) + testScheduler.advanceUntilIdle() - verify(exactly = 1) { permissionRequester.requestPreciseLocation(any()) } + 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 requestPreciseLocation call is a no-op`() { - grantedPermission() + 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.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.runCurrent() - delegate.requestPreciseLocation() + delegate.permissionGranted(true) + + testScheduler.advanceUntilIdle() - verify(exactly = 1) { ContextCompat.checkSelfPermission(any(), any()) } + coVerify(exactly = 1) { controller.getCurrentPosition(any(), any()) } } // endregion @@ -331,13 +259,12 @@ class IONGLOCLocationButtonDelegateTest { @Test fun `given a fetch is suspended mid-flight, onPause cancels it and no position event is ever emitted`() { - grantedPermission() coEvery { controller.getCurrentPosition(any(), any()) } coAnswers { delay(10_000) Result.success(sampleResult()) } - delegate.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.runCurrent() // reach the suspension point inside the launched coroutine delegate.onPause() @@ -348,13 +275,12 @@ class IONGLOCLocationButtonDelegateTest { @Test fun `given a fetch is suspended mid-flight, onDestroy cancels it and a later onResume does not revive it`() { - grantedPermission() coEvery { controller.getCurrentPosition(any(), any()) } coAnswers { delay(10_000) Result.success(sampleResult()) } - delegate.requestPreciseLocation() + delegate.permissionGranted(true) testScheduler.runCurrent() delegate.onDestroy() @@ -365,13 +291,13 @@ class IONGLOCLocationButtonDelegateTest { } @Test - fun `given onDestroy has already been called, requestPreciseLocation is a no-op`() { + fun `given onDestroy has already been called, permissionGranted is a no-op`() { delegate.onDestroy() - delegate.requestPreciseLocation() + delegate.permissionGranted(true) assertTrue(events.isEmpty()) - verify(exactly = 0) { permissionRequester.requestPreciseLocation(any()) } + coVerify(exactly = 0) { controller.getCurrentPosition(any(), any()) } } // endregion