diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..98af668 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*.{kt,kts}] +indent_style = space +indent_size = 4 +max_line_length = 120 +end_of_line = lf +insert_final_newline = true +charset = utf-8 + +ktlint_code_style = android_studio +ij_kotlin_allow_trailing_comma_on_call_site = true +ij_kotlin_allow_trailing_comma = true diff --git a/.github/workflows/android-check.yaml b/.github/workflows/android-check.yaml new file mode 100644 index 0000000..eecc444 --- /dev/null +++ b/.github/workflows/android-check.yaml @@ -0,0 +1,87 @@ +name: Android SDK Samples +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + inputs: + sdk_version: + description: Published Maven Central SDK version for a release check + type: string + sdk_ref: + description: SDK source ref for development checks (ignored when sdk_version is set) + type: string + +env: + # Baseline for source integration checks; release checks use sdk_version. + SDK_REF: 49a72dc936db4e27b65673100680677680c736ee + SAMPLES_SDK_VERSION: ${{ inputs.sdk_version || '0.0.0-sdk-check' }} + SAMPLES_SDK_REPOSITORY: ${{ inputs.sdk_version && 'https://repo.maven.apache.org/maven2' || format('{0}/engine/android/build/sdk-check/repository', github.workspace) }} + +permissions: + contents: read + +concurrency: + # SDK releases and source revisions have independent compatibility results. + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ inputs.sdk_version || inputs.sdk_ref || 'baseline' }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + samples: + runs-on: ubuntu-latest + env: + CMAKE_C_COMPILER_LAUNCHER: ccache + CMAKE_CXX_COMPILER_LAUNCHER: ccache + steps: + - uses: actions/checkout@v6 + with: + path: samples + - uses: actions/checkout@v6 + if: ${{ !inputs.sdk_version }} + with: + repository: organicmaps/organicmaps + ref: ${{ inputs.sdk_ref || env.SDK_REF }} + path: engine + fetch-depth: 200 + - name: Initialize SDK dependencies + if: ${{ !inputs.sdk_version }} + working-directory: engine + run: git submodule update --init --recursive --depth 1 --jobs 8 + - uses: gradle/actions/wrapper-validation@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 + - name: Cache native compilation + if: ${{ !inputs.sdk_version }} + uses: hendrikmuhs/ccache-action@v1.2.24 + with: + key: sdk-samples + save: ${{ github.ref == 'refs/heads/master' }} + - name: Publish fresh SDK artifacts for the samples + if: ${{ !inputs.sdk_version }} + working-directory: engine/android + run: ./gradlew -Px86_64 -PsdkVersion="$SAMPLES_SDK_VERSION" publishSdkForChecks + - name: Build, lint and check Kotlin style for all samples + working-directory: samples + run: ./gradlew -PsdkRepository="$SAMPLES_SDK_REPOSITORY" -PsdkVersion="$SAMPLES_SDK_VERSION" checkSamples + - name: Enable KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: Exercise sample lifecycle and result-list gestures + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 35 + arch: x86_64 + target: default + profile: pixel_2 + working-directory: samples + script: ./gradlew --continue -PsdkRepository="$SAMPLES_SDK_REPOSITORY" -PsdkVersion="$SAMPLES_SDK_VERSION" connectedSamples + - uses: actions/upload-artifact@v7 + if: always() + with: + name: sample-reports + path: samples/app/build/reports diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3f31d91 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +*.iml +.gradle/ +.kotlin/ +build/ +local.properties +.idea/ +.DS_Store +captures/ +.externalNativeBuild/ +.cxx/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c94bfbf --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,50 @@ +# Repository Guidelines + +## Project Structure & Module Organization + +This repository demonstrates the Organic Maps Android SDK in one `app` module with independently installable `basic`, `offline`, and `routing` flavors. + +- `app/src/main/java/app/organicmaps/example/`: Kotlin activities and `ExampleApplication`, which owns SDK initialization and readiness. +- `app/src/main/res/`: layouts, strings, themes, and drawable assets; the manifest is in `app/src/main/`. +- `gradle/libs.versions.toml`: dependency versions; `.github/workflows/android-check.yaml`: CI. + +## Build, Test, and Development Commands + +Use JDK 21, Android SDK Platform 37, and an API 21+ device or emulator. The sample consumes native libraries from SDK AARs and needs no NDK. + +Build fresh SDK artifacts from a sibling Organic Maps checkout: + +```sh +(cd ../organicmaps/android && ./gradlew -Parm64 -PsdkVersion=0.0.0-sdk-check publishSdkForChecks) +./gradlew -PsdkRepository=../organicmaps/android/build/sdk-check/repository -PsdkVersion=0.0.0-sdk-check checkSamples +``` + +`checkSamples` checks Kotlin style, builds debug and minified release APKs for all flavors, and runs Android lint. Keep the same repository/version flags when running other sample tasks: + +- `./gradlew :app:assembleBasicDebug`: build the basic sample. +- `./gradlew :app:installOfflineDebug`: install offline search; use `installRoutingDebug` for routing. +- `./gradlew ktlintCheck` / `./gradlew ktlintFormat`: check or fix Kotlin formatting. + +## Coding Style & Naming Conventions + +Follow `.editorconfig`: four-space indentation for Kotlin and Gradle Kotlin scripts, 120-character lines, UTF-8, LF, and a final newline. Use ktlint's `android_studio` style and trailing commas. Name classes/files in PascalCase, functions/properties in camelCase, and Android resources in snake_case. Keep UI text in `res/values/strings.xml`. + +## Testing Guidelines + +AndroidX instrumentation tests live in `app/src/androidTest/`, `app/src/androidTestOffline/`, and `app/src/androidTestRouting/`. Run `checkSamples` before submitting changes and `connectedSamples` on a matching device or emulator. Verify rotation, light/dark themes, location permissions, cancelled downloads, offline search, missing-map routing, and background/foreground transitions. Repeat relevant checks with minified release APKs. See `README.md` for sample walkthroughs. + +## Commit & Pull Request Guidelines + +Use short imperative commit subjects, such as `Add offline search and routing SDK samples`. Existing commits include `Signed-off-by` trailers; use `git commit -s`. Describe behavior changes, link relevant issues, report validation and SDK source/version, and attach screenshots for UI changes. + +## Integration & Agent Instructions + +Preserve lifecycle forwarding, core-library desugaring, and uncompressed `mwm`, `ttf`, and `packed_polygons.bin` assets. Keep machine-specific SDK paths in ignored `local.properties`. + +## SDK compatibility and releases + +- The SDK is a side product of the main Organic Maps app; the application and SDK implementation are the source of truth and may break consumers +- Keep consumer applications, tests, and compatibility CI in this repository; do not gate `organicmaps/organicmaps` changes on consumer compatibility +- After every SDK release is available on Maven Central, run `android-check.yaml` here with `sdk_version` set to the published version +- Fix consumers to match the SDK when needed, rerun the release check, and update the baseline SDK version/source pin +- `sdk_ref` selects an optional source integration check only when `sdk_version` is empty diff --git a/README.md b/README.md new file mode 100644 index 0000000..c69fdd5 --- /dev/null +++ b/README.md @@ -0,0 +1,94 @@ +# Organic Maps Android SDK examples + +Three independently installable Android apps demonstrate the SDK: + +| Variant | Try it | +| --- | --- | +| `basic` | Pan and zoom the map, select a place, and enable your position. | +| `offline` | Find a region such as Liechtenstein, select it, and download it. Then search installed maps for a place or category. Download and search feedback are independent. | +| `routing` | Select an origin and destination, choose walking/cycling/driving, and build a route. Download missing maps when prompted. For navigation, obtain a fix and use your position as the origin. | + +Each app has separate map storage. Route planning survives rotation and backgrounding; +foreground navigation ends on arrival, Stop, backgrounding, or closing the activity. +Downloads continue independently of the screen and offer cancellation and retry. + +The SDK is a side product of the main Organic Maps application. Its application +and SDK implementation are the source of truth; API stability is not guaranteed. +These examples must adapt when SDK changes break integration. See the +[SDK integration guide](https://github.com/organicmaps/organicmaps/blob/49a72dc936db4e27b65673100680677680c736ee/android/sdk/README.md) +for initialization, lifecycle, permissions, packaging, and API contracts. + +## Build and run + +Use **JDK 21**, **Android SDK Platform 37**, and an **API 21+** device or emulator. +The examples consume native libraries from SDK AARs and do not need an NDK. + +For development with SDK source, publish its artifacts locally. The merged revision +below provides `publishSdkForChecks`, documented in +[organicmaps/organicmaps#14025](https://github.com/organicmaps/organicmaps/pull/14025). +Building that checkout requires the upstream +[native build environment](https://github.com/organicmaps/organicmaps/blob/49a72dc936db4e27b65673100680677680c736ee/docs/INSTALL.md). +With an Organic Maps checkout in the sibling `organicmaps` directory: + +```sh +git -C ../organicmaps fetch origin 49a72dc936db4e27b65673100680677680c736ee +git -C ../organicmaps checkout --detach FETCH_HEAD +git -C ../organicmaps submodule update --init --recursive --depth 1 +(cd ../organicmaps/android && ./gradlew -Parm64 -PsdkVersion=0.0.0-sdk-check publishSdkForChecks) +./gradlew -PsdkRepository=../organicmaps/android/build/sdk-check/repository -PsdkVersion=0.0.0-sdk-check checkSamples +./gradlew -PsdkRepository=../organicmaps/android/build/sdk-check/repository -PsdkVersion=0.0.0-sdk-check :app:installBasicDebug +``` + +Use `installOfflineDebug` or `installRoutingDebug` for the other samples. Keep the same +`sdkRepository` and `sdkVersion` options for every command. `-Parm64` builds SDK AARs +for arm64; use `-Px86_64` in the producer for an Intel emulator. Examples package the +ABIs supplied by those AARs. Release APKs are minified and signed with the debug key +for local installation. + +`sdkRepository` restricts the SDK group to the supplied repository. Without it, +Google, Maven Central, and `mavenLocal()` are available. Local Maven publication also +requires `-PsdkVersion=0.0.0-sdk-check` in the producer to match the default consumer +version; published releases can be selected with `-PsdkVersion=`. + +## Checks + +`checkSamples` runs Kotlin style checks and Android lint, builds all debug/minified +release APKs, and builds the instrumentation tests. Run `ktlintFormat` to format Kotlin. +On a matching connected device or emulator: + +```sh +./gradlew -PsdkRepository=../organicmaps/android/build/sdk-check/repository -PsdkVersion=0.0.0-sdk-check connectedSamples +``` + +For source integration checks, CI publishes the pinned SDK into an isolated +repository and runs these checks on an API 35 emulator. The manual workflow's +`sdk_ref` input selects another source revision when `sdk_version` is empty. +For device checks, also exercise denied/disabled location, rotation during loading, +light/dark themes, cancelled downloads, missing-map routing, and navigation arrival; +repeat with minified release APKs. + +## Check every SDK release + +After each SDK release is available on Maven Central, run this repository's +`Android SDK Samples` workflow with that published version: + +```sh +gh workflow run android-check.yaml --repo organicmaps/sdk-android -f 'sdk_version=' +``` + +This mode resolves the SDK group exclusively from Maven Central and skips SDK +source checkout, native compilation, and local publication. It builds and lints +debug/minified release examples and runs their instrumentation tests. The same +check can be started by release automation with access to this repository. + +If SDK changes require consumer updates, fix the examples here and rerun the check. +Consumer compatibility does not gate changes in `organicmaps/organicmaps`. +Keep the baseline SDK version/source pin current after adopting a release and +exercise minified release APKs on a device for JNI/R8 checks. Resource shrinking +is disabled here and needs separate validation of resources resolved by name. + +## License and support + +See [LICENSE](LICENSE). Report sample issues in +[organicmaps/sdk-android](https://github.com/organicmaps/sdk-android/issues) and SDK or +engine issues in [organicmaps/organicmaps](https://github.com/organicmaps/organicmaps/issues). diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..3068a56 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,88 @@ +plugins { + alias(libs.plugins.android.application) +} + +android { + namespace = "app.organicmaps.example" + compileSdk = providers.gradleProperty("propCompileSdkVersion").get().toInt() + + // Use the built-in Kotlin support of the Android Gradle Plugin 9+. + enableKotlin = true + + buildFeatures { + buildConfig = true + resValues = true + } + + defaultConfig { + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + applicationId = "app.organicmaps.example" + minSdk = providers.gradleProperty("propMinSdkVersion").get().toInt() + targetSdk = providers.gradleProperty("propTargetSdkVersion").get().toInt() + versionCode = 1 + versionName = "1.0" + } + + flavorDimensions += "sample" + productFlavors { + create("basic") { + dimension = "sample" + applicationIdSuffix = ".basic" + manifestPlaceholders["sampleActivity"] = "app.organicmaps.example.MainActivity" + resValue("string", "app_name", "OM SDK Map") + } + create("offline") { + dimension = "sample" + applicationIdSuffix = ".offline" + manifestPlaceholders["sampleActivity"] = "app.organicmaps.example.OfflineSearchActivity" + resValue("string", "app_name", "OM SDK Offline Search") + } + create("routing") { + dimension = "sample" + applicationIdSuffix = ".routing" + manifestPlaceholders["sampleActivity"] = "app.organicmaps.example.RoutingActivity" + resValue("string", "app_name", "OM SDK Routing") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + // Required by the Organic Maps SDK (it is built with desugaring enabled). + isCoreLibraryDesugaringEnabled = true + } + + // The native core reads .mwm maps, fonts and packed polygons directly from + // the APK using random access, so they must be stored uncompressed. + androidResources { + noCompress += listOf("png", "mwm", "ttf", "packed_polygons.bin") + } + + buildTypes { + release { + // Minification works out of the box: the SDK ships consumer R8 rules + // that keep the classes accessed from the native code via JNI. + isMinifyEnabled = true + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) + // Sign with the debug key so the example can be installed right away. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +dependencies { + val sdkVersion = providers.gradleProperty("sdkVersion").getOrElse(libs.versions.organicmaps.sdk.get()) + // The Organic Maps SDK: rendering engine, offline maps framework, location. + implementation("app.organicmaps.sdk:sdk:$sdkVersion") + // Bundles overview maps; detailed offline search and routing still require region downloads. + implementation("app.organicmaps.sdk:maps-world:$sdkVersion") + + coreLibraryDesugaring(libs.android.tools.desugaring) + + implementation(libs.androidx.appcompat) + implementation(libs.google.material) + + androidTestImplementation(libs.androidx.test.core) + androidTestImplementation(libs.androidx.test.runner) + androidTestImplementation(libs.androidx.test.junit) +} diff --git a/app/src/androidTest/AndroidManifest.xml b/app/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000..15d60a7 --- /dev/null +++ b/app/src/androidTest/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/app/src/androidTest/java/app/organicmaps/example/LocationResolutionTest.kt b/app/src/androidTest/java/app/organicmaps/example/LocationResolutionTest.kt new file mode 100644 index 0000000..5367905 --- /dev/null +++ b/app/src/androidTest/java/app/organicmaps/example/LocationResolutionTest.kt @@ -0,0 +1,101 @@ +package app.organicmaps.example + +import android.app.Activity +import android.app.AppOpsManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.location.Criteria +import android.location.LocationManager +import android.os.Bundle +import android.os.ParcelFileDescriptor +import android.os.Process +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.SdkSuppress +import androidx.test.platform.app.InstrumentationRegistry +import app.organicmaps.sdk.Map as OMMap +import app.organicmaps.sdk.location.LocationState +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +class LocationResolutionActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setResult(intent.getIntExtra("result", RESULT_CANCELED)) + finish() + } +} + +@RunWith(AndroidJUnit4::class) +@SdkSuppress(minSdkVersion = 23) // Per-app mock-location selection requires Android M. +class LocationResolutionTest { + private lateinit var locationManager: LocationManager + private var mockLocationMode = "default" + private var testGpsInstalled = false + + @Before + @Suppress("DEPRECATION") // The ProviderProperties overload requires API 31. + fun installTestGps() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val context = instrumentation.targetContext + val appOps = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager + val mode = appOps.checkOpNoThrow("android:mock_location", Process.myUid(), context.packageName) + mockLocationMode = listOf("allow", "ignore", "deny", "default", "foreground")[mode] + setMockLocationMode("allow") + locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager + // Resolution tests need polling state, without depending on physical fixes or the emulator's GNSS HAL. + locationManager.addTestProvider( + LocationManager.GPS_PROVIDER, false, true, false, false, true, true, true, + Criteria.POWER_LOW, Criteria.ACCURACY_FINE, + ) + testGpsInstalled = true + locationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true) + } + + @After + fun removeTestGps() { + if (testGpsInstalled) locationManager.removeTestProvider(LocationManager.GPS_PROVIDER) + setMockLocationMode(mockLocationMode) + } + + private fun setMockLocationMode(mode: String) { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val command = instrumentation.uiAutomation.executeShellCommand( + "appops set ${instrumentation.targetContext.packageName} android:mock_location $mode", + ) + ParcelFileDescriptor.AutoCloseInputStream(command).use { it.readBytes() } + } + + @Test + fun acceptedResolutionRestartsLocation() = resolveLocation(Activity.RESULT_OK) + + @Test + fun cancelledResolutionKeepsLocationStopped() = resolveLocation(Activity.RESULT_CANCELED) + + private fun resolveLocation(result: Int) { + launchSample().use { scenario -> + scenario.await { OMMap.isEngineCreated() } + scenario.onActivity { activity -> + val helper = (activity.application as ExampleApplication).organicMaps.locationHelper + helper.start() + val testPackage = InstrumentationRegistry.getInstrumentation().context.packageName + val intent = Intent().setClassName(testPackage, LocationResolutionActivity::class.java.name) + .putExtra("result", result) + val resolution = PendingIntent.getActivity(activity, result, intent, PendingIntent.FLAG_IMMUTABLE) + helper.onLocationResolutionRequired(resolution) + assertFalse(helper.isActive) + } + if (result == Activity.RESULT_OK) { + scenario.await { (it.application as ExampleApplication).organicMaps.locationHelper.isActive } + } else { + scenario.await { LocationState.getMode() == LocationState.NOT_FOLLOW_NO_POSITION } + scenario.onActivity { + assertFalse((it.application as ExampleApplication).organicMaps.locationHelper.isActive) + } + } + } + } +} diff --git a/app/src/androidTest/java/app/organicmaps/example/MapLifecycleTest.kt b/app/src/androidTest/java/app/organicmaps/example/MapLifecycleTest.kt new file mode 100644 index 0000000..b9f77db --- /dev/null +++ b/app/src/androidTest/java/app/organicmaps/example/MapLifecycleTest.kt @@ -0,0 +1,50 @@ +package app.organicmaps.example + +import android.view.View +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import androidx.lifecycle.Lifecycle +import androidx.test.ext.junit.runners.AndroidJUnit4 +import app.organicmaps.sdk.Map as OMMap +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class MapLifecycleTest { + @Test + fun compassSubscriptionFollowsActivityVisibilityAndRecreation() { + launchSample().use { scenario -> + scenario.await { OMMap.isEngineCreated() } + scenario.await { activity -> + val button = activity.findViewById(R.id.my_position) + val insets = ViewCompat.getRootWindowInsets(button) + ?.getInsets(WindowInsetsCompat.Type.systemBars()) ?: return@await false + val position = IntArray(2) + button.getLocationOnScreen(position) + button.height > 0 && position[1] + button.height <= activity.window.decorView.height - insets.bottom + } + scenario.onActivity { + val helper = (it.application as ExampleApplication).organicMaps.sensorHelper + val listeners = helper.javaClass.getDeclaredField("mListeners").apply { isAccessible = true } + assertEquals(setOf(it), listeners.get(helper)) + it.onCompassUpdated(0.5) + } + scenario.moveToState(Lifecycle.State.CREATED) + scenario.onActivity { + val helper = (it.application as ExampleApplication).organicMaps.sensorHelper + val listeners = helper.javaClass.getDeclaredField("mListeners").apply { isAccessible = true } + assertTrue((listeners.get(helper) as Set<*>).isEmpty()) + } + scenario.moveToState(Lifecycle.State.RESUMED) + scenario.recreate() + scenario.await { OMMap.isEngineCreated() } + scenario.onActivity { + val helper = (it.application as ExampleApplication).organicMaps.sensorHelper + val listeners = helper.javaClass.getDeclaredField("mListeners").apply { isAccessible = true } + assertEquals(setOf(it), listeners.get(helper)) + } + } + } +} diff --git a/app/src/androidTest/java/app/organicmaps/example/SampleTestSupport.kt b/app/src/androidTest/java/app/organicmaps/example/SampleTestSupport.kt new file mode 100644 index 0000000..2a393bc --- /dev/null +++ b/app/src/androidTest/java/app/organicmaps/example/SampleTestSupport.kt @@ -0,0 +1,50 @@ +package app.organicmaps.example + +import android.Manifest +import android.os.ParcelFileDescriptor +import android.os.SystemClock +import android.view.View +import android.view.ViewGroup +import android.widget.Button +import androidx.annotation.StringRes +import androidx.test.core.app.ActivityScenario +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertTrue + +internal fun launchSample(): ActivityScenario { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val context = instrumentation.targetContext + for (permission in listOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)) { + val command = instrumentation.uiAutomation.executeShellCommand("pm grant ${context.packageName} $permission") + ParcelFileDescriptor.AutoCloseInputStream(command).use { it.readBytes() } + } + val intent = requireNotNull(context.packageManager.getLaunchIntentForPackage(context.packageName)) + return ActivityScenario.launch(intent).also { scenario -> + scenario.await { it.findViewById(R.id.my_position)?.isShown == true } + } +} + +internal fun ActivityScenario.await(condition: (MainActivity) -> Boolean) { + val deadline = SystemClock.uptimeMillis() + 15_000 + do { + var matched = false + onActivity { matched = condition(it) } + if (matched) return + SystemClock.sleep(50) + } while (SystemClock.uptimeMillis() < deadline) + throw AssertionError("Sample did not reach the expected UI state") +} + +internal fun View.descendants(): Sequence = sequence { + yield(this@descendants) + if (this@descendants is ViewGroup) { + for (index in 0 until childCount) yieldAll(getChildAt(index).descendants()) + } +} + +internal fun MainActivity.click(@StringRes label: Int) { + val button = findViewById(R.id.sample_panel).descendants() + .filterIsInstance