diff --git a/.github/workflows/publish_api_docs.yml b/.github/workflows/publish_api_docs.yml index b21398c7f..9f009acba 100644 --- a/.github/workflows/publish_api_docs.yml +++ b/.github/workflows/publish_api_docs.yml @@ -80,7 +80,7 @@ jobs: # ANDROID_SDK_ROOT is exported into the process env by setup-android above. run: | export NDK_PATH="${ANDROID_SDK_ROOT}/android-ndk-r27c" - ./gradlew kotlin:dokkaHtml + ./gradlew kotlin:dokkaGenerate # v5 specifically: it sends session tags on AssumeRoleWithWebIdentity, which # the deploy role's trust policy allows (sts:TagSession). v2 would not tag. diff --git a/CHANGELOG.md b/CHANGELOG.md index 27a555c72..f8640d8e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,56 @@ All notable changes to this project will be documented in this file. Dates are d Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). +#### Unreleased (next major) — Kotlin Multiplatform + +The runtime is now a Kotlin Multiplatform library built around the Compose API. +The legacy View-based API has been removed. + +**Coordinates** + +- New umbrella coordinate `app.rive:rive` for multiplatform consumers. +- Android consumers keep resolving `app.rive:rive-android` (published as the + KMP Android target; still an AAR with all four ABIs). +- New `app.rive:rive-jvm` desktop target with real rendering on macOS + (Vulkan via bundled MoltenVK). `iosArm64`/`iosSimulatorArm64`/`wasmJs` + publish as compiling stubs; rendering support is planned. + +**Removed** + +- The entire View-based API (`app.rive.runtime.kotlin.*`): `RiveAnimationView`, + `RiveArtboardRenderer`, controllers, listeners, and the XML attributes. + Use the Compose API (`app.rive.Rive`). +- ReLinker-based native loading (plain `System.loadLibrary` at minSdk 23). + +**Breaking changes** + +- minSdk raised from 21 to 23. +- Gradle consumers need Kotlin 2.2+ to resolve the KMP metadata; the Android + AAR remains consumable from plain Maven/AGP builds. +- Compose dependencies moved from `androidx.compose` to `org.jetbrains.compose` + (Compose Multiplatform 1.11). +- Package moves: `app.rive.runtime.kotlin.core.File.Enum` → + `app.rive.core.FileEnum`; `ViewModel.Property` / `ViewModel.PropertyDataType` → + `app.rive.core.ViewModelProperty` / `app.rive.core.ViewModelPropertyDataType`; + font helpers → `app.rive.fonts`; `ImageDecoder` → `app.rive.core.ImageDecoder`; + `RiveInitializer` → `app.rive.RiveInitializer`. Resource namespace is now + `app.rive`. +- `RiveFileSource` is an interface with `suspend fun load(): ByteArray` + (was a sealed class); `Bytes` is common, `RawRes` is Android-only. +- `Rive()`'s first-frame callback is `onFrameCaptured: ((ImageBitmap) -> Unit)?` + (was `onBitmapAvailable` with an Android `Bitmap`). +- The default frame ticker uses the Compose frame clock when the calling + context has one, and a ~60 Hz delay otherwise (was `Choreographer`). + `ChoreographerFrameTicker` remains available on Android for vsync-aligned + ticking outside Compose. + +**Added** + +- Desktop JVM rendering (offscreen Vulkan/MoltenVK), enabling Compose Desktop + apps and real rendering inside Android Studio previews when the desktop + natives are on the preview classpath. +- `RiveLog` is common; `LogcatLogger` remains available on Android. + #### [11.7.2](https://github.com/rive-app/rive-android/compare/11.7.1...11.7.2) - fix(Android): Lock mutation APIs (#13024) 3c0e143d93 [`dfd4f2f`](https://github.com/rive-app/rive-android/commit/dfd4f2fba6d36e8d71395a91daab6a53ab34e24f) diff --git a/app/build.gradle b/app/build.gradle index 8f666ab21..71a76e867 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,6 +1,7 @@ plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) } android { @@ -10,7 +11,7 @@ android { defaultConfig { applicationId "app.rive.runtime.example" - minSdkVersion 21 + minSdkVersion 23 targetSdk = 36 versionCode 1 versionName "1.0" @@ -38,14 +39,6 @@ android { profileable true signingConfig = signingConfigs.debug } - preview { - debuggable true - minifyEnabled false - shrinkResources = false - proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" - getIsDefault().set(true) - signingConfig = signingConfigs.debug - } } def javaVersion = JavaVersion.VERSION_11 @@ -58,14 +51,8 @@ android { } buildFeatures { - viewBinding = true compose = true } - composeOptions { - // Chosen to match Kotlin version - // https://developer.android.com/jetpack/androidx/releases/compose-kotlin - kotlinCompilerExtensionVersion = libs.versions.composeCompiler.get() - } packagingOptions { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" @@ -83,23 +70,19 @@ dependencies { def composeBom = platform(libs.androidx.compose.bom) implementation(composeBom) - implementation(libs.android.volley) implementation(libs.androidx.activity.compose) implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons.core) implementation(libs.androidx.compose.ui.tooling.preview.android) - implementation(libs.androidx.fragment.ktx) implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.startup.runtime) implementation(libs.google.material) - debugImplementation project(path: ":kotlin") - benchmarkImplementation project(path: ":kotlin") - releaseImplementation project(path: ":kotlin") - previewImplementation(libs.rive.android.preview) - - androidTestImplementation(libs.androidx.test.ext.junit) - androidTestImplementation(libs.androidx.test.runner) - androidTestImplementation project(path: ":kotlin") + implementation project(path: ":kotlin") + // Desktop natives so Android Studio previews can really render Rive + debugImplementation project(path: ":rive-preview") + // Hosts @Preview composables in the Studio preview pane (ComposeViewAdapter) + debugImplementation(libs.androidx.compose.ui.tooling) debugImplementation(libs.leakcanary) } diff --git a/app/src/androidTest/kotlin/app/rive/runtime/example/RiveActivityLifecycleTest.kt b/app/src/androidTest/kotlin/app/rive/runtime/example/RiveActivityLifecycleTest.kt deleted file mode 100644 index 291d7367f..000000000 --- a/app/src/androidTest/kotlin/app/rive/runtime/example/RiveActivityLifecycleTest.kt +++ /dev/null @@ -1,215 +0,0 @@ -package app.rive.runtime.example - -import android.view.ViewGroup -import android.widget.Button -import androidx.core.view.doOnLayout -import androidx.core.view.updateLayoutParams -import androidx.test.core.app.ActivityScenario -import androidx.test.ext.junit.runners.AndroidJUnit4 -import app.rive.runtime.example.TestUtils.Companion.waitUntil -import app.rive.runtime.kotlin.RiveAnimationView -import app.rive.runtime.kotlin.controllers.RiveFileController -import app.rive.runtime.kotlin.core.ContextAssetLoader -import app.rive.runtime.kotlin.core.File -import app.rive.runtime.kotlin.core.FileAsset -import app.rive.runtime.kotlin.core.FileAssetLoader -import app.rive.runtime.kotlin.core.RendererType -import app.rive.runtime.kotlin.core.errors.RiveException -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNotNull -import org.junit.Assert.assertNull -import org.junit.Assert.assertThrows -import org.junit.Assert.assertTrue -import org.junit.Test -import org.junit.runner.RunWith -import java.util.concurrent.CountDownLatch -import java.util.concurrent.TimeUnit -import kotlin.time.Duration.Companion.milliseconds - -@RunWith(AndroidJUnit4::class) -class RiveActivityLifecycleTest { - @Test - fun activityWithRiveView() { - val activityScenario = ActivityScenario.launch(SingleActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - // Start the Activity. - activityScenario.onActivity { - riveView = it.findViewById(R.id.rive_single) - controller = riveView.controller - - assertEquals(2, controller.refCount) - assertTrue(controller.isActive) - assertNotNull(controller.file) - assertNotNull(controller.activeArtboard) - // Defaults to Rive Renderer. - assertEquals(RendererType.Rive, riveView.rendererAttributes.rendererType) - assertEquals(riveView.rendererAttributes.rendererType, controller.file?.rendererType) - } - // Close it down. - activityScenario.close() - // Background thread deallocates asynchronously. - waitUntil(1500.milliseconds) { - controller.refCount == 0 && !controller.isActive && controller.file == null && controller.activeArtboard == null - } - assertFalse(controller.isActive) - assertNull(controller.file) - assertNull(controller.activeArtboard) - } - - @Test - fun withCustomLoader() { - val activityScenario = ActivityScenario.launch(SingleActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - lateinit var ogAssetLoader: FileAssetLoader - lateinit var replacedAssetLoader: FileAssetLoader - // Start the Activity. - activityScenario.onActivity { - riveView = it.findViewById(R.id.rive_single) - controller = riveView.controller - - ogAssetLoader = riveView.rendererAttributes.assetLoader!! - assertTrue(ogAssetLoader.hasCppObject) - - replacedAssetLoader = object : ContextAssetLoader(it) { - override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean = true - } - assertEquals(2, ogAssetLoader.refCount) - riveView.setAssetLoader(replacedAssetLoader) - // The old asset loader is still referenced by the old file - assertEquals(1, ogAssetLoader.refCount) - assertEquals( - replacedAssetLoader, - riveView.rendererAttributes.assetLoader - ) - // One ref from the owner (this test) and one from the View. - assertEquals(2, replacedAssetLoader.refCount) - } - // Close it down. - activityScenario.close() - // Background thread deallocates asynchronously. - waitUntil(1500.milliseconds) { - controller.refCount == 0 && - !controller.isActive && - controller.file == null && - controller.activeArtboard == null && - !ogAssetLoader.hasCppObject - } - assertFalse(controller.isActive) - assertNull(controller.file) - assertNull(controller.activeArtboard) - assertFalse(ogAssetLoader.hasCppObject) - - // New assetLoader needs to be freed by the creator - assertTrue(replacedAssetLoader.hasCppObject) - replacedAssetLoader.release() - assertFalse(replacedAssetLoader.hasCppObject) - } - - @Test - fun activityWithRiveViewSetsWrongFileType() { - val activityScenario = ActivityScenario.launch(SingleActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - // Start the Activity. - activityScenario.onActivity { - riveView = it.findViewById(R.id.rive_single) - controller = riveView.controller - - assertEquals(2, controller.refCount) - assertTrue(controller.isActive) - assertNotNull(controller.file) - assertNotNull(controller.activeArtboard) - // Defaults to Rive Renderer. - assertEquals(RendererType.Rive, riveView.rendererAttributes.rendererType) - assertEquals(riveView.rendererAttributes.rendererType, controller.file?.rendererType) - // Set wrong file type throws! - val customRendererFile = File( - it.resources.openRawResource(R.raw.off_road_car_blog).readBytes(), - RendererType.Canvas - ) - assertEquals(RendererType.Canvas, customRendererFile.rendererType) - val wrongFileTypeException = assertThrows(RiveException::class.java) { - // Boom! - riveView.setRiveFile(customRendererFile) - } - assertEquals( - "Incompatible Renderer types: file initialized with ${customRendererFile.rendererType.name}" + - " but View is set up for ${riveView.rendererAttributes.rendererType.name}", - wrongFileTypeException.message - ) - } - // Close it down. - activityScenario.close() - // Background thread deallocates asynchronously. - waitUntil(1500.milliseconds) { controller.refCount == 0 && !controller.isActive && controller.file == null && controller.activeArtboard == null } - assertFalse(controller.isActive) - assertNull(controller.file) - assertNull(controller.activeArtboard) - } - - @Test - fun resizeRiveView() { - val activityScenario = ActivityScenario.launch(SingleActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var ogWidth = 0f - - val layoutCompleteLatch = CountDownLatch(1) - // Start the Activity. - activityScenario.onActivity { activity -> - riveView = activity.findViewById(R.id.rive_single) - controller = riveView.controller - - assertEquals(2, controller.refCount) - assertTrue(controller.isActive) - assertNotNull(controller.file) - assertNotNull(controller.activeArtboard) - - ogWidth = riveView.artboardRenderer!!.width - - // This block runs after the initial layout - riveView.doOnLayout { - ogWidth = riveView.artboardRenderer!!.width - - val button = Button(activity).apply { - text = "RESIZE" - setOnClickListener { - riveView.updateLayoutParams { width = (ogWidth - 1).toInt() } - } - - // After requesting resize, wait for the next layout pass to confirm it - riveView.doOnLayout { layoutCompleteLatch.countDown() } - } - - (riveView.parent as ViewGroup).addView(button) - button.performClick() - } - } - - assertTrue( - "Timed out waiting for view to be re-laid out.", - layoutCompleteLatch.await(3, TimeUnit.SECONDS) - ) - - var finalWidth: Float? = null - activityScenario.onActivity { finalWidth = riveView.artboardRenderer?.width } - - assertEquals(ogWidth - 1f, finalWidth) - - // Close it down. - activityScenario.close() - - // Background thread deallocates asynchronously, so let's wait for it. - waitUntil(1500.milliseconds) { - controller.refCount == 0 && - controller.file == null && - controller.activeArtboard == null - } - assertFalse(controller.isActive) - assertNull(controller.file) - assertNull(controller.activeArtboard) - } -} diff --git a/app/src/androidTest/kotlin/app/rive/runtime/example/RiveBuilderTest.kt b/app/src/androidTest/kotlin/app/rive/runtime/example/RiveBuilderTest.kt deleted file mode 100644 index c7406928c..000000000 --- a/app/src/androidTest/kotlin/app/rive/runtime/example/RiveBuilderTest.kt +++ /dev/null @@ -1,392 +0,0 @@ -package app.rive.runtime.example - -import androidx.test.core.app.ActivityScenario -import androidx.test.ext.junit.runners.AndroidJUnit4 -import app.rive.runtime.example.TestUtils.Companion.waitUntil -import app.rive.runtime.kotlin.RiveAnimationView -import app.rive.runtime.kotlin.controllers.RiveFileController -import app.rive.runtime.kotlin.core.Alignment -import app.rive.runtime.kotlin.core.CDNAssetLoader -import app.rive.runtime.kotlin.core.FallbackAssetLoader -import app.rive.runtime.kotlin.core.File -import app.rive.runtime.kotlin.core.FileAsset -import app.rive.runtime.kotlin.core.FileAssetLoader -import app.rive.runtime.kotlin.core.Fit -import app.rive.runtime.kotlin.core.Loop -import app.rive.runtime.kotlin.core.RendererType -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNotNull -import org.junit.Assert.assertTrue -import org.junit.Test -import org.junit.runner.RunWith -import java.util.concurrent.TimeoutException -import kotlin.time.Duration.Companion.milliseconds - -@RunWith(AndroidJUnit4::class) -class RiveBuilderTest { - private val cleanupTimeout = 1500.milliseconds - - @Test - fun withIdResource() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var capturedAssetLoader: FileAssetLoader? = null - - activityScenario.onActivity { - riveView = RiveAnimationView.Builder(it) - .setResource(R.raw.off_road_car_blog) - .build() - it.container.addView(riveView) - controller = riveView.controller - capturedAssetLoader = riveView.rendererAttributes.assetLoader - assertTrue(controller.isActive) - assertEquals("New Artboard", controller.activeArtboard?.name) - assertEquals( - listOf("idle"), - controller.playingAnimations.toList().map { anim -> anim.name }) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val assetLoaderCppObjectGone = capturedAssetLoader?.hasCppObject == false - - refCountZero && isInactive && artboardIsNull && fileIsNull && assetLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for withIdResource within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "assetLoader?.hasCppObject=${capturedAssetLoader?.hasCppObject}", e - ) - } - } - - @Test - fun withFileResource() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var capturedAssetLoader: FileAssetLoader? = null - - activityScenario.onActivity { activity -> - val file = activity - .resources - .openRawResource(R.raw.basketball) - .use { res -> File(res.readBytes()) } - - riveView = RiveAnimationView.Builder(activity) - .setResource(file) - .build() - activity.container.addView(riveView) - controller = riveView.controller - capturedAssetLoader = riveView.rendererAttributes.assetLoader - assertTrue(controller.isActive) - assertEquals("New Artboard", controller.activeArtboard?.name) - assertEquals( - listOf("idle"), - controller.playingAnimations.toList().map { anim -> anim.name }) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val assetLoaderCppObjectGone = capturedAssetLoader?.hasCppObject == false - - refCountZero && isInactive && artboardIsNull && fileIsNull && assetLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for withFileResource within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "assetLoader?.hasCppObject=${capturedAssetLoader?.hasCppObject}", e - ) - } - } - - @Test - fun withBytesResource() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var capturedAssetLoader: FileAssetLoader? = null - - activityScenario.onActivity { activity -> - val fileBytes = activity - .resources - .openRawResource(R.raw.basketball) - .use { res -> res.readBytes() } - riveView = RiveAnimationView.Builder(activity) - .setResource(fileBytes) - .build() - activity.container.addView(riveView) - controller = riveView.controller - capturedAssetLoader = riveView.rendererAttributes.assetLoader - assertTrue(controller.isActive) - assertEquals("New Artboard", controller.activeArtboard?.name) - assertEquals( - listOf("idle"), - controller.playingAnimations.toList().map { anim -> anim.name }) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val assetLoaderCppObjectGone = capturedAssetLoader?.hasCppObject == false - - refCountZero && isInactive && artboardIsNull && fileIsNull && assetLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for withBytesResource within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "assetLoader?.hasCppObject=${capturedAssetLoader?.hasCppObject}", e - ) - } - } - - @Test - fun manyParameters() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var capturedAssetLoader: FileAssetLoader? = null - - activityScenario.onActivity { activity -> - riveView = RiveAnimationView.Builder(activity) - .setAlignment(Alignment.BOTTOM_CENTER) - .setFit(Fit.FIT_HEIGHT) - .setLoop(Loop.PINGPONG) - .setAutoplay(false) - .setAutoBind(true) - .setTraceAnimations(true) - .setArtboardName("artboard2") - .setAnimationName("artboard2animation1") - .setResource(R.raw.multipleartboards) - .build() - activity.container.addView(riveView) - controller = riveView.controller - capturedAssetLoader = riveView.rendererAttributes.assetLoader - assertTrue(controller.isActive) - assertFalse(controller.autoplay) - assertNotNull(controller.activeArtboard?.viewModelInstance) - assertEquals(Alignment.BOTTOM_CENTER, controller.alignment) - assertEquals(Fit.FIT_HEIGHT, controller.fit) - assertEquals(Loop.PINGPONG, controller.loop) - assertTrue(riveView.artboardRenderer!!.trace) - assertEquals("artboard2", controller.activeArtboard?.name) - assertEquals( - emptyList(), - controller.playingAnimations.toList().map { anim -> anim.name }) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val assetLoaderCppObjectGone = capturedAssetLoader?.hasCppObject == false - refCountZero && isInactive && artboardIsNull && fileIsNull && assetLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for manyParameters within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "assetLoader?.hasCppObject=${capturedAssetLoader?.hasCppObject}", e - ) - } - } - - @Test - fun assetLoader() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - val assetStore = mutableListOf() - val customLoader = object : FileAssetLoader() { - override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean { - return assetStore.add(asset) - } - } - - activityScenario.onActivity { activity -> - riveView = RiveAnimationView.Builder(activity) - .setResource(R.raw.walle) - .setAssetLoader(customLoader) - .build() - activity.container.addView(riveView) - controller = riveView.controller - - val actualLoader = riveView.rendererAttributes.assetLoader - assertTrue(actualLoader is FallbackAssetLoader) - val fallbackLoader = actualLoader as FallbackAssetLoader - assertEquals(2, fallbackLoader.loaders.size) - assertEquals(customLoader, fallbackLoader.loaders.first()) - assertTrue(fallbackLoader.loaders.last() is CDNAssetLoader) - assertEquals(2, assetStore.size) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val customLoaderCppObjectGone = !customLoader.hasCppObject - - refCountZero && isInactive && artboardIsNull && fileIsNull && customLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for assetLoader within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "customLoader.hasCppObject=${customLoader.hasCppObject}", e - ) - } - } - - @Test - fun noCDNLoader() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var capturedAssetLoader: FileAssetLoader? = null - - activityScenario.onActivity { activity -> - riveView = RiveAnimationView.Builder(activity) - .setResource(R.raw.walle) - .setShouldLoadCDNAssets(false) - .build() - activity.container.addView(riveView) - controller = riveView.controller - capturedAssetLoader = riveView.rendererAttributes.assetLoader - - val actualLoader = riveView.rendererAttributes.assetLoader - assertTrue(actualLoader is FallbackAssetLoader) - val fallbackLoader = actualLoader as FallbackAssetLoader - assertTrue(fallbackLoader.loaders.isEmpty()) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val assetLoaderCppObjectGone = capturedAssetLoader?.hasCppObject == false - - refCountZero && isInactive && artboardIsNull && fileIsNull && assetLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for noCDNLoader within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "assetLoader?.hasCppObject=${capturedAssetLoader?.hasCppObject}", e - ) - } - } - - @Test - fun withRendererType() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var capturedAssetLoader: FileAssetLoader? = null - - activityScenario.onActivity { activity -> - riveView = RiveAnimationView.Builder(activity) - .setResource(R.raw.basketball) - .setRendererType(RendererType.Canvas) - .build() - activity.container.addView(riveView) - controller = riveView.controller - capturedAssetLoader = riveView.rendererAttributes.assetLoader - assertNotNull(riveView.artboardRenderer) - assertEquals(RendererType.Canvas, riveView.artboardRenderer?.type) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val assetLoaderCppObjectGone = capturedAssetLoader?.hasCppObject == false - - refCountZero && isInactive && artboardIsNull && fileIsNull && assetLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for withRendererType within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "assetLoader?.hasCppObject=${capturedAssetLoader?.hasCppObject}", e - ) - } - } - - @Test - fun withStateMachineName() { - val activityScenario = ActivityScenario.launch(EmptyActivity::class.java) - lateinit var riveView: RiveAnimationView - lateinit var controller: RiveFileController - var capturedAssetLoader: FileAssetLoader? = null - - activityScenario.onActivity { activity -> - riveView = RiveAnimationView.Builder(activity) - .setResource(R.raw.what_a_state) - .setStateMachineName("State Machine 2") - .build() - activity.container.addView(riveView) - controller = riveView.controller - capturedAssetLoader = riveView.rendererAttributes.assetLoader - assertEquals(1, controller.playingStateMachines.size) - assertEquals("State Machine 2", controller.playingStateMachines.first().name) - } - activityScenario.close() - - try { - waitUntil(cleanupTimeout) { - val refCountZero = controller.refCount == 0 - val isInactive = !controller.isActive - val artboardIsNull = controller.activeArtboard == null - val fileIsNull = controller.file == null - val assetLoaderCppObjectGone = capturedAssetLoader?.hasCppObject == false - - refCountZero && isInactive && artboardIsNull && fileIsNull && assetLoaderCppObjectGone - } - } catch (e: TimeoutException) { - throw AssertionError( - "Cleanup conditions not met for withStateMachineName within $cleanupTimeout. Current state: " + - "controller.refCount=${controller.refCount}, controller.isActive=${controller.isActive}, " + - "controller.file=${controller.file}, controller.activeArtboard=${controller.activeArtboard}, " + - "assetLoader?.hasCppObject=${capturedAssetLoader?.hasCppObject}", e - ) - } - } -} diff --git a/app/src/androidTest/kotlin/app/rive/runtime/example/TestUtils.kt b/app/src/androidTest/kotlin/app/rive/runtime/example/TestUtils.kt deleted file mode 100644 index 7a958a504..000000000 --- a/app/src/androidTest/kotlin/app/rive/runtime/example/TestUtils.kt +++ /dev/null @@ -1,99 +0,0 @@ -package app.rive.runtime.example - -import android.annotation.SuppressLint -import android.os.Build -import java.io.BufferedReader -import java.io.IOException -import java.io.InputStreamReader -import java.lang.reflect.Method -import java.util.concurrent.TimeoutException -import kotlin.time.Duration - -class TestUtils { - companion object { - fun waitUntil( - atMost: Duration, - condition: () -> Boolean - ) { - val maxTime = atMost.inWholeMilliseconds - - val interval: Long = 50 - var elapsed: Long = 0 - do { - elapsed += interval - Thread.sleep(interval) - - if (elapsed > maxTime) { - throw TimeoutException("Took too long.") - } - } while (!condition()) - } - - // Helper function to check whether it's running on an emulator - // Found on: https://stackoverflow.com/a/21505193 - val isProbablyRunningOnEmulator: Boolean by lazy { - // Android SDK emulator - return@lazy ((Build.MANUFACTURER == "Google" && Build.BRAND == "google" && - ((Build.FINGERPRINT.startsWith("google/sdk_gphone_") - && Build.FINGERPRINT.endsWith(":user/release-keys") - && Build.PRODUCT.startsWith("sdk_gphone_") - && Build.MODEL.startsWith("sdk_gphone_")) - //alternative - || (Build.FINGERPRINT.startsWith("google/sdk_gphone64_") - && (Build.FINGERPRINT.endsWith(":userdebug/dev-keys") || Build.FINGERPRINT.endsWith( - ":user/release-keys" - )) - && Build.PRODUCT.startsWith("sdk_gphone64_") - && Build.MODEL.startsWith("sdk_gphone64_")))) - // - || Build.FINGERPRINT.startsWith("generic") - || Build.FINGERPRINT.startsWith("unknown") - || Build.MODEL.contains("google_sdk") - || Build.MODEL.contains("Emulator") - || Build.MODEL.contains("Android SDK built for x86") - //bluestacks - || "QC_Reference_Phone" == Build.BOARD && !"Xiaomi".equals( - Build.MANUFACTURER, - ignoreCase = true - ) - //bluestacks - || Build.MANUFACTURER.contains("Genymotion") - || Build.HOST.startsWith("Build") - //MSI App Player - || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic") - || Build.PRODUCT == "google_sdk" - // another Android SDK emulator check - || SystemProperties.getProp("ro.kernel.qemu") == "1") - } - } - - object SystemProperties { - private var failedUsingReflection = false - private var getPropMethod: Method? = null - - @SuppressLint("PrivateApi") - fun getProp(propName: String, defaultResult: String = ""): String { - if (!failedUsingReflection) try { - if (getPropMethod == null) { - val clazz = Class.forName("android.os.SystemProperties") - getPropMethod = clazz.getMethod("get", String::class.java, String::class.java) - } - return getPropMethod!!.invoke(null, propName, defaultResult) as String? - ?: defaultResult - } catch (_: Exception) { - getPropMethod = null - failedUsingReflection = true - } - var process: Process? = null - try { - process = Runtime.getRuntime().exec("getprop \"$propName\" \"$defaultResult\"") - val reader = BufferedReader(InputStreamReader(process.inputStream)) - return reader.readLine() - } catch (_: IOException) { - } finally { - process?.destroy() - } - return defaultResult - } - } -} diff --git a/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkComposeActivity.kt b/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkComposeActivity.kt index 652f69b17..af0644229 100644 --- a/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkComposeActivity.kt +++ b/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkComposeActivity.kt @@ -12,6 +12,7 @@ import androidx.compose.ui.graphics.Color import app.rive.Fit import app.rive.Result import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource import app.rive.rememberRiveFile import app.rive.rememberRiveWorker @@ -30,7 +31,7 @@ class BenchmarkComposeActivity : ComponentActivity() { private fun BenchmarkComposeScreen() { val riveWorker = rememberRiveWorker() val riveFileResult = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.basketball), + RawRes.from(R.raw.basketball), riveWorker ) diff --git a/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkHardwareBitmapCanvasActivity.kt b/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkHardwareBitmapCanvasActivity.kt index c01c7daca..7b05584da 100644 --- a/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkHardwareBitmapCanvasActivity.kt +++ b/app/src/benchmark/kotlin/app/rive/benchmark/BenchmarkHardwareBitmapCanvasActivity.kt @@ -17,6 +17,7 @@ import app.rive.Fit import app.rive.HardwareRenderBuffer import app.rive.Result import app.rive.RiveFile +import app.rive.RawRes import app.rive.RiveFileSource import app.rive.StateMachine import app.rive.core.RiveWorker @@ -50,7 +51,7 @@ class BenchmarkHardwareBitmapCanvasActivity : ComponentActivity() { lifecycleScope.launch { when ( val riveFile = RiveFile.fromSource( - RiveFileSource.RawRes(R.raw.basketball, resources), + RawRes(R.raw.basketball, resources), riveWorker ) ) { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 9388e1d67..4ab3aece9 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,9 +2,6 @@ - - - @@ -68,132 +65,12 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/src/main/java/app/rive/runtime/example/AndroidPlayerActivity.kt b/app/src/main/java/app/rive/runtime/example/AndroidPlayerActivity.kt deleted file mode 100644 index 06a1ae749..000000000 --- a/app/src/main/java/app/rive/runtime/example/AndroidPlayerActivity.kt +++ /dev/null @@ -1,430 +0,0 @@ -package app.rive.runtime.example - -import android.graphics.Color -import android.os.Bundle -import android.view.Gravity -import android.view.View -import android.widget.AdapterView -import android.widget.ArrayAdapter -import android.widget.LinearLayout -import android.widget.RadioButton -import android.widget.Spinner -import android.widget.TextView -import androidx.activity.ComponentActivity -import androidx.appcompat.widget.AppCompatButton -import androidx.appcompat.widget.AppCompatCheckBox -import androidx.appcompat.widget.AppCompatEditText -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.RiveAnimationView -import app.rive.runtime.kotlin.controllers.RiveFileController -import app.rive.runtime.kotlin.core.Artboard -import app.rive.runtime.kotlin.core.Direction -import app.rive.runtime.kotlin.core.LinearAnimationInstance -import app.rive.runtime.kotlin.core.Loop -import app.rive.runtime.kotlin.core.PlayableInstance -import app.rive.runtime.kotlin.core.SMIBoolean -import app.rive.runtime.kotlin.core.SMINumber -import app.rive.runtime.kotlin.core.StateMachineInstance - -class AndroidPlayerActivity : ComponentActivity() { - var loop: Loop = Loop.AUTO - var direction: Direction = Direction.AUTO - var playButtonMap: HashMap = HashMap() - var pauseButtonMap: HashMap = HashMap() - var stopButtonMap: HashMap = HashMap() - - private val animationResources = listOf( - R.raw.artboard_animations, - R.raw.basketball, - R.raw.circle_move, - R.raw.clipping, - R.raw.explorer, - R.raw.f22, - R.raw.flux_capacitor, - R.raw.loopy, - R.raw.mascot, - R.raw.neostream, - R.raw.off_road_car_blog, - R.raw.progress, - R.raw.pull, - R.raw.rope, - R.raw.skills, - R.raw.trailblaze, - R.raw.ui_swipe_left_to_delete, - R.raw.vader, - R.raw.wacky, - R.raw.what_a_state, - R.raw.two_bone_ik, - R.raw.constrained, - ) - - val animationView by lazy(LazyThreadSafetyMode.NONE) { - findViewById(R.id.android_player_view) - } - - val resourceNames: List - get() { - return animationResources.map { resources.getResourceName(it).split('/').last() } - } - - fun loadResource(index: Int) { - animationView.setRiveResource(animationResources[index], artboardName = null) - setSpinner() - - playButtonMap.clear() - pauseButtonMap.clear() - stopButtonMap.clear() - - animationView.controller.file?.firstArtboard?.name?.let { - loadArtboard(it) - } - } - - fun onLoopModeSelected(view: View) { - if (view is RadioButton && view.isChecked) { - // Check which radio button was clicked - when (view.id) { - R.id.loop_auto -> - loop = Loop.AUTO - - R.id.loop_loop -> - loop = Loop.LOOP - - R.id.loop_oneshot -> - loop = Loop.ONESHOT - - R.id.loop_pingpong -> - loop = Loop.PINGPONG - } - } - } - - fun onDirectionSelected(view: View) { - if (view is RadioButton && view.isChecked) { - // Check which radio button was clicked - when (view.id) { - R.id.direction_auto -> - direction = Direction.AUTO - - R.id.direction_backwards -> - direction = Direction.BACKWARDS - - R.id.direction_forwards -> - direction = Direction.FORWARDS - } - } - } - - fun onReset(view: View) { - if (view is AppCompatButton) { - animationView.reset() - } - } - - fun addAnimationControl(animationName: String): View { - val layout = LinearLayout(this) - layout.orientation = LinearLayout.HORIZONTAL - layout.gravity = Gravity.END - - val text = TextView(this) - text.text = animationName - - val playButton = AppCompatButton(this) - playButton.text = ">" - playButton.background.setTint(Color.WHITE) - playButton.setOnClickListener { - animationView.play(animationName, loop, direction) - } - playButtonMap[animationName] = playButton - - val pauseButton = AppCompatButton(this) - pauseButton.text = "||" - pauseButton.background.setTint(Color.WHITE) - pauseButton.setOnClickListener { - animationView.pause(animationName) - } - pauseButtonMap[animationName] = pauseButton - - val stopButton = AppCompatButton(this) - stopButton.text = "[]" - stopButton.background.setTint(Color.RED) - stopButton.setOnClickListener { - animationView.stop(animationName) - } - stopButtonMap[animationName] = stopButton - - layout.addView(text) - layout.addView(playButton) - layout.addView(pauseButton) - layout.addView(stopButton) - return layout - } - - fun addStateMachineControl(artboard: Artboard, stateMachineName: String): List { - val views = mutableListOf() - val layout = LinearLayout(this) - layout.orientation = LinearLayout.HORIZONTAL - layout.gravity = Gravity.END - - val text = TextView(this) - text.text = stateMachineName - - val playButton = AppCompatButton(this) - playButton.text = ">" - playButton.background.setTint(Color.WHITE) - playButton.setOnClickListener { - animationView.play(stateMachineName, loop, direction, isStateMachine = true) - } - playButtonMap[stateMachineName] = playButton - - val pauseButton = AppCompatButton(this) - pauseButton.text = "||" - pauseButton.background.setTint(Color.WHITE) - pauseButton.setOnClickListener { - animationView.pause(stateMachineName, isStateMachine = true) - } - pauseButtonMap[stateMachineName] = pauseButton - - val stopButton = AppCompatButton(this) - stopButton.text = "[]" - stopButton.background.setTint(Color.RED) - stopButton.setOnClickListener { - animationView.stop(stateMachineName, isStateMachine = true) - } - stopButtonMap[stateMachineName] = stopButton - - val stateMachine = artboard.stateMachine(stateMachineName) - - layout.addView(text) - layout.addView(playButton) - layout.addView(pauseButton) - layout.addView(stopButton) - views.add(layout) - - stateMachine.inputs.forEach { - val innerLayout = LinearLayout(this) - innerLayout.orientation = LinearLayout.HORIZONTAL - innerLayout.gravity = Gravity.END - - val innerText = TextView(this) - innerText.text = it.name - innerLayout.addView(innerText) - - if (it.isTrigger) { - val triggerButton = AppCompatButton(this) - triggerButton.text = "Fire" - triggerButton.background.setTint(Color.WHITE) - triggerButton.setOnClickListener { _ -> - animationView.fireState(stateMachineName, it.name) - } - innerLayout.addView(triggerButton) - } - - if (it.isBoolean) { - val boolBox = AppCompatCheckBox(this) - if ((it as SMIBoolean).value) { - boolBox.isChecked = true - } - boolBox.setOnCheckedChangeListener { _, b -> - animationView.setBooleanState(stateMachineName, it.name, b) - } - innerLayout.addView(boolBox) - } - - if (it.isNumber) { - val editText = AppCompatEditText(this) - editText.setText((it as SMINumber).value.toString()) - val editTriggerButton = AppCompatButton(this) - editTriggerButton.text = "Apply" - editTriggerButton.background.setTint(Color.WHITE) - editTriggerButton.setOnClickListener { _ -> - try { - val value = editText.text.toString().toFloat() - animationView.setNumberState(stateMachineName, it.name, value) - } catch (e: Error) { - - } - } - - innerLayout.addView(editText) - innerLayout.addView(editTriggerButton) - } - - views.add(innerLayout) - } - - return views - } - - fun loadArtboard(artboardName: String) { - val controls = findViewById(R.id.controls) - controls.removeAllViews() - animationView.controller.file?.artboard(artboardName)?.let { artboard -> - if (artboard.stateMachineNames.isNotEmpty()) { - val stateMachineHeader = TextView(this) - stateMachineHeader.text = "State Machines:" - controls.addView(stateMachineHeader) - artboard.stateMachineNames.forEach { - addStateMachineControl(artboard, it).forEach { - controls.addView(it) - } - } - } - if (artboard.animationNames.isNotEmpty()) { - val animationsHeader = TextView(this) - animationsHeader.text = "Animations:" - controls.addView(animationsHeader) - artboard.animationNames.forEach { - controls.addView(addAnimationControl(it)) - } - } - } - - } - - fun setSpinner() { - animationView.controller.file?.artboardNames?.let { artboardNames -> - val dropdown = findViewById(R.id.artboards) - val adapter = ArrayAdapter( - this, - android.R.layout.simple_spinner_dropdown_item, - artboardNames - ) - dropdown.adapter = adapter - dropdown.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected( - arg0: AdapterView<*>?, - arg1: View?, - arg2: Int, - arg3: Long - ) { - val item = dropdown.selectedItem.toString() - - animationView.artboardName = item - loadArtboard(item) - } - - override fun onNothingSelected(arg0: AdapterView<*>?) {} - } - } - } - - fun setResourceSpinner() { - animationResources.let { _ -> - val dropdown = findViewById(R.id.resources) - val adapter = ArrayAdapter( - this, - android.R.layout.simple_spinner_dropdown_item, - resourceNames - ) - dropdown.adapter = adapter - dropdown.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected( - arg0: AdapterView<*>?, - arg1: View?, - arg2: Int, - arg3: Long - ) { - loadResource(arg2) - } - - override fun onNothingSelected(arg0: AdapterView<*>?) {} - } - } - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.android_player) - - setResourceSpinner() - loadResource(0) - val that = this - val events = findViewById(R.id.events) - val elapsedTextView = findViewById(R.id.elapsed_text_view) - val listener = object : RiveFileController.Listener { - override fun notifyPlay(animation: PlayableInstance) { - var text: String? = null - if (animation is LinearAnimationInstance) { - text = animation.name - } else if (animation is StateMachineInstance) { - text = animation.name - } - text?.let { theText -> - runOnUiThread { - val textView = TextView(that) - textView.text = "Play $theText" - events.addView(textView, 0) - playButtonMap[theText]?.background?.setTint(Color.GREEN) - pauseButtonMap[theText]?.background?.setTint(Color.WHITE) - stopButtonMap[theText]?.background?.setTint(Color.WHITE) - } - } - } - - override fun notifyPause(animation: PlayableInstance) { - var text: String? = null - if (animation is LinearAnimationInstance) { - text = animation.name - } else if (animation is StateMachineInstance) { - text = animation.name - } - text?.let { - runOnUiThread { - val textView = TextView(that) - textView.text = "Pause $text" - events.addView(textView, 0) - playButtonMap[text]?.background?.setTint(Color.WHITE) - pauseButtonMap[text]?.background?.setTint(Color.BLUE) - stopButtonMap[text]?.background?.setTint(Color.WHITE) - } - } - } - - override fun notifyStop(animation: PlayableInstance) { - var text: String? = null - if (animation is LinearAnimationInstance) { - text = animation.name - } else if (animation is StateMachineInstance) { - text = animation.name - } - text?.let { - runOnUiThread { - val textView = TextView(that) - textView.text = "Stop $text" - events.addView(textView, 0) - playButtonMap[text]?.background?.setTint(Color.WHITE) - pauseButtonMap[text]?.background?.setTint(Color.WHITE) - stopButtonMap[text]?.background?.setTint(Color.RED) - } - } - } - - override fun notifyLoop(animation: PlayableInstance) { - if (animation is LinearAnimationInstance) { - runOnUiThread { - val text = TextView(that) - text.text = "Loop ${animation.name}" - events.addView(text, 0) - } - } - } - - override fun notifyStateChanged(stateMachineName: String, stateName: String) { - runOnUiThread { - val text = TextView(that) - text.text = "$stateMachineName: State Changed: $stateName" - events.addView(text, 0) - } - } - - override fun notifyAdvance(elapsed: Float) { - runOnUiThread { - elapsedTextView.text = "Delta time: $elapsed" - } - } - } - - animationView.registerListener(listener) - } -} diff --git a/app/src/main/java/app/rive/runtime/example/AssetLoaderActivity.kt b/app/src/main/java/app/rive/runtime/example/AssetLoaderActivity.kt deleted file mode 100644 index 58880fd29..000000000 --- a/app/src/main/java/app/rive/runtime/example/AssetLoaderActivity.kt +++ /dev/null @@ -1,93 +0,0 @@ -package app.rive.runtime.example - -import android.content.Context -import android.os.Bundle -import android.util.Log -import androidx.fragment.app.Fragment -import androidx.fragment.app.FragmentActivity -import androidx.viewpager2.adapter.FragmentStateAdapter -import app.rive.runtime.example.databinding.ActivityAssetLoaderBinding -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.core.BytesRequest -import app.rive.runtime.kotlin.core.ContextAssetLoader -import app.rive.runtime.kotlin.core.FileAsset -import app.rive.runtime.kotlin.core.FileAssetLoader -import com.android.volley.toolbox.Volley -import com.google.android.material.tabs.TabLayoutMediator -import kotlin.random.Random - -class AssetLoaderActivity : FragmentActivity() { - private lateinit var binding: ActivityAssetLoaderBinding - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - binding = ActivityAssetLoaderBinding.inflate(layoutInflater) - setEdgeToEdgeContent(binding.root) - - binding.viewPager.adapter = object : FragmentStateAdapter(this) { - override fun getItemCount(): Int = 3 - - override fun createFragment(position: Int): Fragment { - return when (position) { - 0 -> AssetLoaderFragment() - 1 -> AssetButtonFragment() - else -> FontAssetFragment() - } - } - } - - TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position -> - tab.text = when (position) { - 0 -> "Asset Loader" - 1 -> "Change Images" - else -> "Fonts" - } - }.attach() - } -} - -/** - * [FileAssetLoader] tailored for the two assets in the walle.riv file. - * - * The main purpose of this class is to demonstrate how create a custom [ContextAssetLoader] via - * XML. - */ -class WalleAssetLoader(context: Context) : ContextAssetLoader(context) { - override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean { - val identifier = - if (asset.uniqueFilename.contains("eve")) R.raw.walle_img_eve - else R.raw.walle_img_walle - - context.resources.openRawResource(identifier).use { - asset.decode(it.readBytes()) - } - return true - } -} - -/** Loads a random image from picsum.photos. */ -class RandomNetworkLoader(context: Context) : FileAssetLoader() { - private val loremImage = "https://picsum.photos" - private val queue = Volley.newRequestQueue(context) - private val minSize = 150 - private val maxSize = 500 - private val maxId = 1084 - - override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean { - val randomWidth = Random.nextInt(minSize, maxSize) - val randomHeight = Random.nextInt(minSize, maxSize) - val imgId = Random.nextInt(maxId) - - val url = "$loremImage/id/$imgId/$randomWidth/$randomHeight" - val request = BytesRequest( - url, - { bytes -> asset.decode(bytes) }, - { - Log.e("Request", "onAssetLoaded: failed to load image from $url") - it.printStackTrace() - } - ) - queue.add(request) - return true - } -} diff --git a/app/src/main/java/app/rive/runtime/example/AssetLoaderFragment.kt b/app/src/main/java/app/rive/runtime/example/AssetLoaderFragment.kt deleted file mode 100644 index d3c52d6e6..000000000 --- a/app/src/main/java/app/rive/runtime/example/AssetLoaderFragment.kt +++ /dev/null @@ -1,240 +0,0 @@ -package app.rive.runtime.example - -import android.content.Context -import android.os.Bundle -import android.util.Log -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import android.widget.Button -import android.widget.FrameLayout -import androidx.fragment.app.Fragment -import app.rive.runtime.example.databinding.FragmentAssetButtonBinding -import app.rive.runtime.example.databinding.FragmentAssetLoaderBinding -import app.rive.runtime.kotlin.RiveAnimationView -import app.rive.runtime.kotlin.core.BytesRequest -import app.rive.runtime.kotlin.core.FileAsset -import app.rive.runtime.kotlin.core.FileAssetLoader -import app.rive.runtime.kotlin.core.FontAsset -import app.rive.runtime.kotlin.core.ImageAsset -import app.rive.runtime.kotlin.core.Loop -import app.rive.runtime.kotlin.core.RiveFont -import app.rive.runtime.kotlin.core.RiveRenderImage -import com.android.volley.RequestQueue -import com.android.volley.toolbox.Volley -import kotlin.random.Random - -private fun makeContainer(context: Context): FrameLayout { - return FrameLayout(context).apply { - layoutParams = FrameLayout.LayoutParams( - FrameLayout.LayoutParams.WRAP_CONTENT, - FrameLayout.LayoutParams.WRAP_CONTENT, - ).apply { - // 16dp equivalent - val dpPadding = (16 * resources.displayMetrics.density).toInt() - topMargin = dpPadding - } - } -} - -private fun makeButton( - context: Context, - label: String, - clickListener: View.OnClickListener -): Button { - return Button(context).apply { - layoutParams = ViewGroup.LayoutParams( - ViewGroup.LayoutParams.WRAP_CONTENT, - ViewGroup.LayoutParams.WRAP_CONTENT, - ) - text = label - setOnClickListener(clickListener) - } -} - -class AssetLoaderFragment : Fragment() { - private var _binding: FragmentAssetLoaderBinding? = null - private val binding get() = _binding!! - private lateinit var networkLoader: RandomNetworkLoader - - override fun onCreateView( - inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? - ): View { - _binding = FragmentAssetLoaderBinding.inflate(inflater, container, false) - val view = binding.root - val ctx = view.context - networkLoader = RandomNetworkLoader(ctx) - - makeContainer(ctx).let { - val riveView = RiveAnimationView.Builder(ctx) - .setAssetLoader(networkLoader) - .setResource(R.raw.walle) - .build() - it.addView(riveView) - binding.fragmentLoaderContainer.addView(it) - } - - makeContainer(ctx).let { - val cdnRiveView = RiveAnimationView.Builder(ctx) - .setResource(R.raw.cdn_image) - .build() - it.addView(cdnRiveView) - binding.fragmentLoaderContainer.addView(it) - } - - return view - } -} - -class AssetButtonFragment : Fragment() { - private var _binding: FragmentAssetButtonBinding? = null - private val binding get() = _binding!! - - private val loremImage = "https://picsum.photos" - private lateinit var queue: RequestQueue - private lateinit var assetStore: ImageAssetStore - private val minSize = 750 - private val maxSize = 1000 - private val maxId = 1084 - - private fun randomImageButton(context: Context): Button { - return makeButton(context, "Change Image") { - val randomWidth = Random.nextInt(minSize, maxSize) - val randomHeight = Random.nextInt(minSize, maxSize) - val imgId = Random.nextInt(maxId) - val url = "$loremImage/id/$imgId/$randomWidth/$randomHeight" - val request = BytesRequest( - url, - { bytes -> - assetStore.nextAsset.image = RiveRenderImage.fromEncoded(bytes) - }, - { - Log.e("Request", "onAssetLoaded: failed to load $url.") - it.printStackTrace() - } - ) - queue.add(request) - } - } - - override fun onCreateView( - inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? - ): View { - - _binding = FragmentAssetButtonBinding.inflate(inflater, container, false) - val view = binding.root - val ctx = view.context - queue = Volley.newRequestQueue(ctx) - - assetStore = ImageAssetStore() - val riveView = RiveAnimationView.Builder(ctx) - .setAssetLoader(assetStore) - .setResource(R.raw.asset_load_check) - .build() - - makeContainer(ctx).let { - it.addView(riveView) - binding.fragmentButtonContainer.addView(it) - } - - randomImageButton(ctx).let { - binding.fragmentButtonContainer.addView(it) - } - - return view - } - - private class ImageAssetStore : FileAssetLoader() { - private var lastAssetChanged = 0 - val assetList = mutableListOf() - - val nextAsset: ImageAsset - get() = assetList[lastAssetChanged++ % assetList.size] - - override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean { - if (asset is ImageAsset) { - return assetList.add(asset) - } - return false - } - } -} - -class FontAssetFragment : Fragment() { - private var _binding: FragmentAssetButtonBinding? = null - private lateinit var queue: RequestQueue - private val binding get() = _binding!! - - private lateinit var fontDecoder: RandomFontDecoder - - private val fontUrls = listOf( - "https://cdn.rive.app/runtime/flutter/IndieFlower-Regular.ttf", - "https://cdn.rive.app/runtime/flutter/comic-neue.ttf", - "https://cdn.rive.app/runtime/flutter/inter.ttf", - "https://cdn.rive.app/runtime/flutter/inter-tight.ttf", - "https://cdn.rive.app/runtime/flutter/josefin-sans.ttf", - "https://cdn.rive.app/runtime/flutter/send-flowers.ttf", - ) - - private fun randomFontButton(context: Context): Button { - return makeButton(context, "Change Font") { - val url = fontUrls.random() - val request = BytesRequest( - url, - { bytes -> fontDecoder.fontAsset.font = RiveFont.make(bytes) }, - { - Log.e("Request", "onAssetLoaded: failed to load $url.") - it.printStackTrace() - } - ) - queue.add(request) - } - } - - override fun onCreateView( - inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle? - ): View { - - _binding = FragmentAssetButtonBinding.inflate(inflater, container, false) - val view = binding.root - val ctx = view.context - queue = Volley.newRequestQueue(ctx) - - fontDecoder = RandomFontDecoder(ctx) - val riveView = RiveAnimationView.Builder(ctx) - .setAssetLoader(fontDecoder) - .setAnimationName("Bounce") - .setLoop(Loop.PINGPONG) - .setResource(R.raw.fontz_oob) - .build() - - makeContainer(ctx).let { - it.addView(riveView) - binding.fragmentButtonContainer.addView(it) - } - randomFontButton(ctx).let { - binding.fragmentButtonContainer.addView(it) - } - - return view - } - - private class RandomFontDecoder(private val context: Context) : FileAssetLoader() { - lateinit var fontAsset: FontAsset - override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean { - if (asset is FontAsset) { - // Store a reference to the asset. - fontAsset = asset - - // Load the original font - context.resources.openRawResource(R.raw.roboto).use { - return asset.decode(it.readBytes()) - } - } - return false - } - } -} diff --git a/app/src/main/java/app/rive/runtime/example/AssetsActivity.kt b/app/src/main/java/app/rive/runtime/example/AssetsActivity.kt deleted file mode 100644 index beff6cadf..000000000 --- a/app/src/main/java/app/rive/runtime/example/AssetsActivity.kt +++ /dev/null @@ -1,13 +0,0 @@ -package app.rive.runtime.example - -import android.os.Bundle -import androidx.activity.ComponentActivity -import app.rive.runtime.example.utils.setEdgeToEdgeContent - -class AssetsActivity : ComponentActivity() { - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.assets) - } -} diff --git a/app/src/main/java/app/rive/runtime/example/AudioAssetActivity.kt b/app/src/main/java/app/rive/runtime/example/AudioAssetActivity.kt deleted file mode 100644 index 12f68b973..000000000 --- a/app/src/main/java/app/rive/runtime/example/AudioAssetActivity.kt +++ /dev/null @@ -1,69 +0,0 @@ -package app.rive.runtime.example - -import android.content.Context -import android.os.Bundle -import androidx.activity.ComponentActivity -import app.rive.runtime.example.databinding.ActivityAudioExternalAssetBinding -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.RiveAnimationView -import app.rive.runtime.kotlin.core.AudioAsset -import app.rive.runtime.kotlin.core.FileAsset -import app.rive.runtime.kotlin.core.FileAssetLoader -import app.rive.runtime.kotlin.core.RiveAudio - -class AudioAssetActivity : ComponentActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.activity_audio_asset) - } -} - -class AudioExternalAssetActivity : ComponentActivity() { - - private lateinit var binding: ActivityAudioExternalAssetBinding - private val audioDecoder = AudioDecoder(this) - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - binding = ActivityAudioExternalAssetBinding.inflate(layoutInflater) - setEdgeToEdgeContent(binding.root) - - val riveView = RiveAnimationView.Builder(this) - .setAssetLoader(audioDecoder) - .setResource(R.raw.ping_pong_audio_demo) - .build() - - riveView.setVolume(0.75f) // Set the volume for the active artboard - - binding.main.addView(riveView) - } - - private class AudioDecoder(private val context: Context) : FileAssetLoader() { - override fun loadContents(asset: FileAsset, inBandBytes: ByteArray): Boolean { - if (asset is AudioAsset) { - val audioFilename = asset.uniqueFilename - val rawResource = when { - audioFilename.startsWith("racket1") -> R.raw.racket1 - audioFilename.startsWith("racket2") -> R.raw.racket2 - audioFilename.startsWith("table") -> R.raw.table - else -> 0 - } - - if (rawResource <= 0) { - // Unknown resource... - return false - } - - val audio = context - .resources - .openRawResource(rawResource) - .use { - RiveAudio.make(it.readBytes()) - } - asset.audio = audio - return true - } - return false - } - } -} diff --git a/app/src/main/java/app/rive/runtime/example/BindArtboardWithDataActivity.kt b/app/src/main/java/app/rive/runtime/example/BindArtboardWithDataActivity.kt deleted file mode 100644 index 62a33ff52..000000000 --- a/app/src/main/java/app/rive/runtime/example/BindArtboardWithDataActivity.kt +++ /dev/null @@ -1,43 +0,0 @@ -package app.rive.runtime.example - -import android.os.Bundle -import android.util.Log -import androidx.activity.ComponentActivity -import androidx.lifecycle.lifecycleScope -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.RiveAnimationView -import kotlinx.coroutines.launch - -class BindArtboardWithDataActivity : ComponentActivity() { - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - - val rive = RiveAnimationView(this) - rive.setRiveResource( - R.raw.data_bind_test_impl, - "Bindable Artboard Host", - autoBind = true, - autoplay = true - ) - - setEdgeToEdgeContent(rive) - - val file = rive.file!! - val vmi = file.getViewModelByName("Test Bound Artboard Child VM") - .createInstanceFromName("Override") - val bindableArtboard = file.createBindableArtboardByName("Bindable Artboard With VM", vmi) - - lifecycleScope.launch { - vmi.getStringProperty("Echo String").valueFlow.collect { - Log.i("BindArtboard", "New echo string: $it") - } - } - - val artboardProperty = - rive.controller.stateMachines.first().viewModelInstance!!.getArtboardProperty("Child Artboard") - - artboardProperty.set(bindableArtboard) - bindableArtboard.release() // Release the reference we hold from creation - } -} diff --git a/app/src/main/java/app/rive/runtime/example/BlendActivity.kt b/app/src/main/java/app/rive/runtime/example/BlendActivity.kt deleted file mode 100644 index 6be19f0d6..000000000 --- a/app/src/main/java/app/rive/runtime/example/BlendActivity.kt +++ /dev/null @@ -1,12 +0,0 @@ -package app.rive.runtime.example - -import android.os.Bundle -import androidx.activity.ComponentActivity -import app.rive.runtime.example.utils.setEdgeToEdgeContent - -class BlendActivity : ComponentActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.blend) - } -} diff --git a/app/src/main/java/app/rive/runtime/example/ButtonActivity.kt b/app/src/main/java/app/rive/runtime/example/ButtonActivity.kt deleted file mode 100644 index bb671be09..000000000 --- a/app/src/main/java/app/rive/runtime/example/ButtonActivity.kt +++ /dev/null @@ -1,20 +0,0 @@ -package app.rive.runtime.example - -import android.os.Bundle -import android.widget.TextView -import androidx.activity.ComponentActivity -import app.rive.runtime.example.utils.RiveButton -import app.rive.runtime.example.utils.setEdgeToEdgeContent - -class ButtonActivity : ComponentActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.button) - - val button = findViewById(R.id.myButton) - button.setOnClickListener { - val counterText = findViewById(R.id.myButtonCounter) - counterText.text = (counterText.text.toString().toInt() + 1).toString() - } - } -} diff --git a/app/src/main/java/app/rive/runtime/example/ComposeActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeActivity.kt index e14a41400..44f2837e0 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeActivity.kt @@ -46,7 +46,9 @@ import app.rive.Fit import app.rive.Result import app.rive.Result.Loading.andThen import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.ViewModelSource import app.rive.rememberArtboard @@ -65,7 +67,7 @@ class ComposeActivity : ComponentActivity() { enableEdgeToEdge() // Enable Logcat logging - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val context = LocalContext.current @@ -103,7 +105,7 @@ class ComposeActivity : ComponentActivity() { val riveFileResult = font.andThen { rememberRiveFile( // Point to the Rive raw resource file - RiveFileSource.RawRes.from(R.raw.rating_animation_all), + RawRes.from(R.raw.rating_animation_all), riveWorker ) } diff --git a/app/src/main/java/app/rive/runtime/example/ComposeArtboardBindingActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeArtboardBindingActivity.kt index 24c4f2ca7..fb1d98d2c 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeArtboardBindingActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeArtboardBindingActivity.kt @@ -29,7 +29,9 @@ import app.rive.Fit import app.rive.Result import app.rive.Result.Loading.zip import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.rememberArtboard import app.rive.rememberRiveFile @@ -44,16 +46,16 @@ class ComposeArtboardBindingActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val riveWorker = rememberRiveWorker() val mainRiveFile = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.swap_character_main), + RawRes.from(R.raw.swap_character_main), riveWorker ) val assetRiveFile = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.swap_character_assets), + RawRes.from(R.raw.swap_character_assets), riveWorker ) val bothFiles = mainRiveFile.zip(assetRiveFile) diff --git a/app/src/main/java/app/rive/runtime/example/ComposeAudioActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeAudioActivity.kt index d2d34e267..7f3ad25c2 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeAudioActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeAudioActivity.kt @@ -11,7 +11,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import app.rive.Result import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.rememberRiveFile import app.rive.rememberRiveWorker @@ -24,12 +26,12 @@ class ComposeAudioActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val riveWorker = rememberRiveWorker() val riveFile = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.lip_sync_test), + RawRes.from(R.raw.lip_sync_test), riveWorker ) diff --git a/app/src/main/java/app/rive/runtime/example/ComposeCappedFPSActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeCappedFPSActivity.kt index 97033f90f..4c1f1124c 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeCappedFPSActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeCappedFPSActivity.kt @@ -34,8 +34,10 @@ import androidx.compose.ui.unit.dp import app.rive.Fit import app.rive.Result import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource import app.rive.RiveFrameRate +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.rememberRiveFile import app.rive.rememberRiveWorker @@ -55,11 +57,11 @@ class ComposeCappedFPSActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val riveWorker = rememberRiveWorker() - val riveFile = rememberRiveFile(RiveFileSource.RawRes.from(R.raw.marty), riveWorker) + val riveFile = rememberRiveFile(RawRes.from(R.raw.marty), riveWorker) var framesPerSecond by rememberSaveable { mutableFloatStateOf(30f) } var isUncapped by rememberSaveable { mutableStateOf(false) } val frameRate = if (isUncapped) { diff --git a/app/src/main/java/app/rive/runtime/example/ComposeDataBindingActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeDataBindingActivity.kt index 020d960a3..eb10e7663 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeDataBindingActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeDataBindingActivity.kt @@ -27,7 +27,9 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import app.rive.Fit import app.rive.Result import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.rememberRiveFile import app.rive.rememberRiveWorker @@ -55,12 +57,12 @@ class ComposeDataBindingActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(backgroundColor), navigationBarStyle = SystemBarStyle.dark(backgroundColor) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val riveWorker = rememberRiveWorker() val riveFileResult = - rememberRiveFile(RiveFileSource.RawRes.from(R.raw.rewards_demo), riveWorker) + rememberRiveFile(RawRes.from(R.raw.rewards_demo), riveWorker) var showBottomPanel by remember { mutableStateOf(false) } Scaffold( diff --git a/app/src/main/java/app/rive/runtime/example/ComposeImageBindingActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeImageBindingActivity.kt index f3db9f83d..18a95da9f 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeImageBindingActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeImageBindingActivity.kt @@ -21,7 +21,9 @@ import app.rive.Result.Loading.andThen import app.rive.Result.Loading.sequence import app.rive.Result.Loading.zip import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.rememberImage import app.rive.rememberRiveFile @@ -40,14 +42,14 @@ class ComposeImageBindingActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val context = LocalContext.current val riveWorker = rememberRiveWorker() val riveFile = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.image_db_cats), + RawRes.from(R.raw.image_db_cats), riveWorker ) diff --git a/app/src/main/java/app/rive/runtime/example/ComposeLayoutActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeLayoutActivity.kt index 72ba0eee6..52de11414 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeLayoutActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeLayoutActivity.kt @@ -28,7 +28,9 @@ import androidx.compose.ui.unit.dp import app.rive.Fit import app.rive.Result import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.rememberRiveFile import app.rive.rememberRiveWorker @@ -42,12 +44,12 @@ class ComposeLayoutActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val riveWorker = rememberRiveWorker() val riveFile = - rememberRiveFile(RiveFileSource.RawRes.from(R.raw.layouts_demo), riveWorker) + rememberRiveFile(RawRes.from(R.raw.layouts_demo), riveWorker) var useLayout by rememberSaveable { mutableStateOf(true) } var scaleFactor by rememberSaveable { mutableStateOf(1f) } diff --git a/app/src/main/java/app/rive/runtime/example/ComposeListActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeListActivity.kt index ec6ef443e..f0ca16352 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeListActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeListActivity.kt @@ -35,7 +35,9 @@ import androidx.compose.ui.unit.dp import app.rive.Fit import app.rive.Result import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.ViewModelInstance import app.rive.ViewModelInstanceSource @@ -54,12 +56,12 @@ class ComposeListActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val riveWorker = rememberRiveWorker() val riveFile = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.lists_demo), + RawRes.from(R.raw.lists_demo), riveWorker ) diff --git a/app/src/main/java/app/rive/runtime/example/ComposeScrollActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeScrollActivity.kt index 5148bd982..29b9c0684 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeScrollActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeScrollActivity.kt @@ -36,7 +36,9 @@ import app.rive.Fit import app.rive.Result import app.rive.Rive import app.rive.RiveFile +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.RivePointerInputMode import app.rive.rememberRiveFile @@ -62,12 +64,12 @@ class ComposeScrollActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { val riveWorker = rememberRiveWorker() val riveFile = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.skull_scroll), + RawRes.from(R.raw.skull_scroll), riveWorker ) var consumePointerEvents by remember { mutableStateOf(true) } diff --git a/app/src/main/java/app/rive/runtime/example/ComposeTouchPassThroughActivity.kt b/app/src/main/java/app/rive/runtime/example/ComposeTouchPassThroughActivity.kt index 82c51497e..9f215565c 100644 --- a/app/src/main/java/app/rive/runtime/example/ComposeTouchPassThroughActivity.kt +++ b/app/src/main/java/app/rive/runtime/example/ComposeTouchPassThroughActivity.kt @@ -31,7 +31,9 @@ import androidx.compose.ui.platform.LocalContext import app.rive.Fit import app.rive.Result import app.rive.Rive +import app.rive.RawRes import app.rive.RiveFileSource +import app.rive.LogcatLogger import app.rive.RiveLog import app.rive.RivePointerInputMode import app.rive.rememberRiveFile @@ -46,14 +48,14 @@ class ComposeTouchPassThroughActivity : ComponentActivity() { statusBarStyle = SystemBarStyle.dark(AndroidColor.BLACK), navigationBarStyle = SystemBarStyle.dark(AndroidColor.BLACK) ) - RiveLog.logger = RiveLog.LogcatLogger() + RiveLog.logger = LogcatLogger() setContent { LocalContext.current val riveWorker = rememberRiveWorker() val riveFile = rememberRiveFile( - RiveFileSource.RawRes.from(R.raw.touch_passthrough), + RawRes.from(R.raw.touch_passthrough), riveWorker ) diff --git a/app/src/main/java/app/rive/runtime/example/DynamicTextActivity.kt b/app/src/main/java/app/rive/runtime/example/DynamicTextActivity.kt deleted file mode 100644 index 0aad9b63e..000000000 --- a/app/src/main/java/app/rive/runtime/example/DynamicTextActivity.kt +++ /dev/null @@ -1,55 +0,0 @@ -package app.rive.runtime.example - -import android.os.Bundle -import android.text.Editable -import android.text.TextWatcher -import android.util.Log -import android.widget.EditText -import androidx.activity.ComponentActivity -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.RiveAnimationView - -/** - * Dynamically change a Rive Text Run value. In this example the run is named: "name" For the run to - * be discoverable at runtime, the name as to be set in the editor. - * - * See: https://rive.app/community/doc/text/docn2E6y1lXo - */ -class DynamicTextActivity : ComponentActivity(), TextWatcher { - private val animationView by lazy(LazyThreadSafetyMode.NONE) { - findViewById(R.id.dynamic_text) - } - - /** Reference to a [RiveTextValueRun]. */ - private val textRun by lazy(LazyThreadSafetyMode.NONE) { - animationView.controller.activeArtboard?.textRun("name") - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.dynamic_text) - - val editText = findViewById(R.id.text_run_value) - editText.addTextChangedListener(this) - } - - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { - // get the current value of the reference - textRun?.text?.let { Log.i("text-value-run", "Run before change: $it") } - - // or you can get the current value with: - // animationView.getTextRunValue("name").let { Log.i("text-value-run", "Run before change: $it") } - } - - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { - // update the reference - textRun?.text = s.toString() - - // or update the value using: - // animationView.setTextRunValue("name", s.toString()) - } - - override fun afterTextChanged(s: Editable?) { - textRun?.text?.let { Log.i("text-value-run", "Run after change: $it") } - } -} diff --git a/app/src/main/java/app/rive/runtime/example/EventsActivity.kt b/app/src/main/java/app/rive/runtime/example/EventsActivity.kt deleted file mode 100644 index f07115dff..000000000 --- a/app/src/main/java/app/rive/runtime/example/EventsActivity.kt +++ /dev/null @@ -1,121 +0,0 @@ -package app.rive.runtime.example - -import android.content.Intent -import android.net.Uri -import android.os.Bundle -import android.util.Log -import android.widget.TextView -import androidx.activity.ComponentActivity -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.RiveAnimationView -import app.rive.runtime.kotlin.controllers.RiveFileController -import app.rive.runtime.kotlin.core.RiveEvent -import app.rive.runtime.kotlin.core.RiveGeneralEvent -import app.rive.runtime.kotlin.core.RiveOpenURLEvent - -class EventsActivity : ComponentActivity() { - - private val starRatingAnimation: RiveAnimationView by lazy(LazyThreadSafetyMode.NONE) { - findViewById(R.id.star_event_asset) - } - - private val urlButtonAnimation: RiveAnimationView by lazy(LazyThreadSafetyMode.NONE) { - findViewById(R.id.url_event_button) - } - - private val logButtonAnimation: RiveAnimationView by lazy(LazyThreadSafetyMode.NONE) { - findViewById(R.id.log_event_button) - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.events) - - setStarRating() - setUrlButton() - setLogButton() - } - - override fun onDestroy() { - starRatingAnimation.removeEventListener(starRatingListener) - urlButtonAnimation.removeEventListener(urlButtonListener) - logButtonAnimation.removeEventListener(logButtonListener) - super.onDestroy() - } - - private lateinit var starRatingListener: RiveFileController.RiveEventListener - private lateinit var urlButtonListener: RiveFileController.RiveEventListener - private lateinit var logButtonListener: RiveFileController.RiveEventListener - - private fun setStarRating() { - val starRatingTextView = findViewById(R.id.star_rating) - - starRatingListener = object : RiveFileController.RiveEventListener { - override fun notifyEvent(event: RiveEvent) { - when (event) { - is RiveGeneralEvent -> { - Log.i( - "RiveEvent", - "General event received, name: ${event.name}, delaySeconds: ${event.delay} properties: ${event.properties}" - ) - runOnUiThread { - // This event contains a number value with the name "rating" - // to indicate the star rating selected - if (event.properties.containsKey("rating")) { - starRatingTextView.text = - "Star rating: ${event.properties["rating"]}" - } - } - } - } - } - } - starRatingAnimation.addEventListener(starRatingListener) - } - - private fun setUrlButton() { - urlButtonListener = object : RiveFileController.RiveEventListener { - override fun notifyEvent(event: RiveEvent) { - when (event) { - is RiveOpenURLEvent -> { - Log.i("RiveEvent", "Open URL Rive event: ${event.url}") - runOnUiThread { - try { - val uri = Uri.parse(event.url) - val browserIntent = - Intent(Intent.ACTION_VIEW, uri) - startActivity(browserIntent) - } catch (e: Exception) { - Log.i("RiveEvent", "Not a valid URL ${event.url}") - } - } - } - } - } - } - urlButtonAnimation.addEventListener(urlButtonListener) - } - - private fun setLogButton() { - logButtonListener = object : RiveFileController.RiveEventListener { - override fun notifyEvent(event: RiveEvent) { - when (event) { - is RiveOpenURLEvent -> { - Log.i("RiveEvent", "Open URL Rive event: ${event.url}") - } - - is RiveGeneralEvent -> { - Log.i("RiveEvent", "General Rive event") - } - } - Log.i("RiveEvent", "name: ${event.name}") - Log.i("RiveEvent", "delay: ${event.delay}") - Log.i("RiveEvent", "type: ${event.type}") - Log.i("RiveEvent", "properties: ${event.properties}") - // `data` contains all information in the event - Log.i("RiveEvent", "data: ${event.data}") - } - } - logButtonAnimation.addEventListener(logButtonListener) - } -} diff --git a/app/src/main/java/app/rive/runtime/example/FontFallback.kt b/app/src/main/java/app/rive/runtime/example/FontFallback.kt deleted file mode 100644 index 82c2b6c75..000000000 --- a/app/src/main/java/app/rive/runtime/example/FontFallback.kt +++ /dev/null @@ -1,76 +0,0 @@ -package app.rive.runtime.example - -import android.os.Bundle -import androidx.activity.ComponentActivity -import app.rive.runtime.example.databinding.ActivityFontFallbackBinding -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.fonts.FontBytes -import app.rive.runtime.kotlin.fonts.FontFallbackStrategy -import app.rive.runtime.kotlin.fonts.FontHelper -import app.rive.runtime.kotlin.fonts.Fonts - -class FontFallback : ComponentActivity(), FontFallbackStrategy { - - private lateinit var binding: ActivityFontFallbackBinding - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - - binding = ActivityFontFallbackBinding.inflate(layoutInflater) - setEdgeToEdgeContent(binding.root) - - updateTextRuns() - updateThaiText() - - FontFallbackStrategy.stylePicker = this - } - - // This class is a `FontFallbackStrategy` and this override picks fonts based on weight. - override fun getFont(weight: Fonts.Weight): List { - var fontMatch = Fonts.FontOpts( - familyName = "serif", - ) - when { - // 'Invert' the weights to make the fallback chars more prominent. - weight.weight < 400 -> fontMatch = - Fonts.FontOpts(familyName = "sans-serif", weight = Fonts.Weight(900)) - - weight.weight > 400 -> fontMatch = - Fonts.FontOpts(familyName = "sans-serif", weight = Fonts.Weight(100)) - } - val fonts = listOf( - fontMatch, - // Tag a Thai font along so our second view can draw the glyphs - Fonts.FontOpts("NotoSansThai-Regular.ttf") - ) - return fonts.mapNotNull { FontHelper.getFallbackFontBytes(it) } - } - - /** - * The Rive file displayed here contains four blocks of text each with three different runs - * Also, the Rive file only exported the glyphs that have been specified in the file, and each - * line is made of three runs: | ABC | DEF | GHI | - * - * Modifying these runs with glyphs that are not part of the { ABCDEFGHI } set will require a - * fallback. - */ - private fun updateTextRuns() { - binding.riveViewStylePicker.setTextRunValue("ultralight_start", "aBc ") - binding.riveViewStylePicker.setTextRunValue("ultralight_mid", "DeF") - binding.riveViewStylePicker.setTextRunValue("ultralight_end", " gHi") - - binding.riveViewStylePicker.setTextRunValue("regular_mid", " def ") - - binding.riveViewStylePicker.setTextRunValue("bold_start", "PQR ") - binding.riveViewStylePicker.setTextRunValue("bold_end", "XYZ") - - binding.riveViewStylePicker.setTextRunValue("black_mid", " def ") - } - - private fun updateThaiText() { - val thaiHelloText = "สวัสดี " - val thaiWorldText = " โลก" - binding.riveViewThai.setTextRunValue("regular_start", thaiHelloText) - binding.riveViewThai.setTextRunValue("regular_end", thaiWorldText) - } -} diff --git a/app/src/main/java/app/rive/runtime/example/FrameActivity.kt b/app/src/main/java/app/rive/runtime/example/FrameActivity.kt deleted file mode 100644 index b3578aa7d..000000000 --- a/app/src/main/java/app/rive/runtime/example/FrameActivity.kt +++ /dev/null @@ -1,69 +0,0 @@ -package app.rive.runtime.example - -import android.os.Bundle -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import android.widget.Button -import androidx.fragment.app.Fragment -import androidx.fragment.app.FragmentActivity -import androidx.fragment.app.commit -import app.rive.runtime.example.utils.setEdgeToEdgeContent -import app.rive.runtime.kotlin.RiveAnimationView - -class FrameActivity : FragmentActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setEdgeToEdgeContent(R.layout.activity_frame) - - // Don't do anything if restoring a previous state. - if (savedInstanceState != null) { - return - } - - supportFragmentManager.commit { - setReorderingAllowed(true) - add(R.id.frame_fragment_container, TextFragment()) - } - - findViewById