Merge "Remove Jetsnack microbenchmark" into androidx-main
diff --git a/OWNERS b/OWNERS index 0eef768..f878fc9 100644 --- a/OWNERS +++ b/OWNERS
@@ -49,7 +49,7 @@ # MediaRouter * per-file *libraryversions.toml = aquilescanta@google.com, asargent@google.com, asapperstein@google.com, halliwell@google.com, taesuny@google.com, tanaykhemani@google.com, tkourim@google.com # PDF * -per-file *libraryversions.toml = anuragadarsh@google.com, rahulkanojia@google.com +per-file *libraryversions.toml =rahulkanojia@google.com # Camera * per-file *libraryversions.toml = wujulie@google.com, scottnien@google.com, trevormcguire@google.com # Health Connect
diff --git a/camera/camera-testing/src/androidTest/java/androidx/camera/testing/impl/RequireForegroundRuleDeviceTest.kt b/camera/camera-testing/src/androidTest/java/androidx/camera/testing/impl/RequireForegroundRuleDeviceTest.kt index c23611d..721135f 100644 --- a/camera/camera-testing/src/androidTest/java/androidx/camera/testing/impl/RequireForegroundRuleDeviceTest.kt +++ b/camera/camera-testing/src/androidTest/java/androidx/camera/testing/impl/RequireForegroundRuleDeviceTest.kt
@@ -16,9 +16,19 @@ package androidx.camera.testing.impl +import android.content.Context +import android.hardware.display.DisplayManager +import android.os.Build +import android.view.Display +import android.view.Surface +import androidx.camera.testing.impl.activity.EmptyActivity +import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.uiautomator.UiDevice import com.google.common.truth.Truth.assertThat +import org.junit.Assume.assumeTrue import org.junit.Test import org.junit.runner.Description import org.junit.runner.RunWith @@ -102,4 +112,60 @@ rule.apply(statement, description).evaluate() assertThat(executionOrder).containsExactly(3, 2, 1).inOrder() } + + @Test + fun apply_restoresAndLocksNaturalOrientationBeforeEvaluatingStatement() { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val device = UiDevice.getInstance(instrumentation) + val displayManager = + instrumentation.targetContext.getSystemService(Context.DISPLAY_SERVICE) + as DisplayManager + val rule = RequireForegroundRule() + val description = + Description.createTestDescription( + RequireForegroundRuleDeviceTest::class.java, + "apply_restoresAndLocksNaturalOrientationBeforeEvaluatingStatement", + ) + var preTestRotation: Int? = null + var rotationDuringTest: Int? = null + + try { + RequireForegroundRule.clearDeviceUI(instrumentation) + ActivityScenario.launch(EmptyActivity::class.java).use { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + device.setOrientationLeft(Display.DEFAULT_DISPLAY) + } else { + device.setOrientationLeft() + } + RequireForegroundRule.awaitDefaultDisplayRotation( + displayManager = displayManager, + expectedRotation = Surface.ROTATION_90, + timeoutMs = 5000L, + ) + preTestRotation = RequireForegroundRule.getDefaultDisplayRotation(displayManager) + } + assumeTrue( + "Device display does not rotate away from ROTATION_0 under setOrientationLeft", + preTestRotation != null && preTestRotation != Surface.ROTATION_0, + ) + + val statement = + object : Statement() { + override fun evaluate() { + // Launch an unspecified-orientation Activity so portrait-locked Home + // launchers cannot mask an unlocked or non-natural user_rotation state. + ActivityScenario.launch(EmptyActivity::class.java).use { + instrumentation.waitForIdleSync() + rotationDuringTest = + RequireForegroundRule.getDefaultDisplayRotation(displayManager) + } + } + } + rule.apply(statement, description).evaluate() + } finally { + RequireForegroundRule.unfreezeRotation(device) + } + + assertThat(rotationDuringTest).isEqualTo(Surface.ROTATION_0) + } }
diff --git a/camera/camera-testing/src/main/AndroidManifest.xml b/camera/camera-testing/src/main/AndroidManifest.xml index 2ecef51..5001a0b4 100644 --- a/camera/camera-testing/src/main/AndroidManifest.xml +++ b/camera/camera-testing/src/main/AndroidManifest.xml
@@ -22,7 +22,7 @@ <application> <activity android:name="androidx.camera.testing.impl.activity.ForegroundTestActivity" - android:configChanges="orientation|screenSize" + android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize" android:exported="true" android:label="ForegroundTestActivity" /> <activity @@ -37,7 +37,7 @@ android:label="Camera2 TestActivity" /> <activity android:name="androidx.camera.testing.impl.activity.EmptyActivity" - android:configChanges="orientation|screenSize" + android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize" android:exported="true" android:label="EmptyActivity" android:theme="@style/Theme.AppCompat" />
diff --git a/camera/camera-testing/src/main/java/androidx/camera/testing/impl/RequireForegroundRule.kt b/camera/camera-testing/src/main/java/androidx/camera/testing/impl/RequireForegroundRule.kt index 8c0490d..21fc21e 100644 --- a/camera/camera-testing/src/main/java/androidx/camera/testing/impl/RequireForegroundRule.kt +++ b/camera/camera-testing/src/main/java/androidx/camera/testing/impl/RequireForegroundRule.kt
@@ -19,20 +19,28 @@ import android.annotation.SuppressLint import android.app.Instrumentation import android.content.ActivityNotFoundException +import android.content.Context import android.content.Intent +import android.hardware.display.DisplayManager import android.os.Build +import android.os.Handler +import android.os.Looper import android.os.RemoteException import android.util.Log +import android.view.Display +import android.view.Surface import androidx.camera.core.Logger import androidx.camera.testing.impl.activity.ForegroundTestActivity import androidx.test.espresso.Espresso import androidx.test.espresso.IdlingRegistry import androidx.test.platform.app.InstrumentationRegistry import androidx.test.runner.lifecycle.ActivityLifecycleCallback +import androidx.test.runner.lifecycle.ActivityLifecycleMonitor import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry import androidx.test.runner.lifecycle.Stage import androidx.test.uiautomator.UiDevice import java.io.IOException +import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.Future import java.util.concurrent.RejectedExecutionException @@ -52,37 +60,55 @@ * * This rule automates the "clean room" setup required for Activity and Fragment tests: * 1. **Device Preparation**: Wakes the screen, dismisses the keyguard, and enables "stay on." - * 2. **Orientation Lock**: Freezes the device in natural orientation to prevent unexpected - * recreations. + * 2. **Orientation Lock**: Freezes the default display in natural orientation + * (`Surface.ROTATION_0`) and awaits display-rotation settlement while [ForegroundTestActivity] + * holds foreground focus to prevent delayed mid-test Activity recreations. * 3. **Foreground Verification**: Verifies that the app can actually obtain window focus before the * test starts, and monitors mid-test activity lifecycle transitions for unsolicited foreign * packages stealing window focus. If a system dialog, notification shade, or third-party/OEM app * blocks or steals the foreground, the rule throws a [ForegroundOccupiedError] in lab * environments (or skips the test via [AssumptionViolatedException] outside the lab). * + * ### Rule Ordering Guidance (`@get:Rule(order = ...)`) + * When combining [RequireForegroundRule] with Activity/Compose launch rules + * (`ActivityScenarioRule`, `CameraTestActivityScenarioRule`, `createComposeRule`, + * `createAndroidComposeRule`), specify explicit `order` values so [RequireForegroundRule] runs + * **before** (lower `order` than) the Activity/Compose launch rule, while keeping fast skip gates + * (`LabTestRule`, `Ignore*ProblematicDeviceRule`, screenshot rules) and + * `PostTestCameraAvailability` (when `cameraProvider.shutdownAsync()` runs in [deferCleanup]) outer + * to [RequireForegroundRule]. + * + * Note: Activities launched under test should not declare `android:screenOrientation="sensor"` or + * `"fullSensor"` unless explicitly testing sensor-driven rotation, because sensor orientation modes + * ignore the user-rotation lock. + * * ### Why use this instead of @Before/@After? * Standard `@After` blocks execute while the test Activity might still be visible or active. If you * shut down a singleton dependency (like `ProcessCameraProvider`) in `@After`, the Activity might * crash while trying to access that provider during its own destruction. * * This rule provides [withCleanup] and [deferCleanup] to ensure that teardown happens **only - * after** the device has successfully returned to the Home screen and the Activity is gone. + * after** the device has returned to the Home screen, target Activities have stopped, and rotation + * has been unfrozen. * * ### Call Sequence Diagram * 1. **Rule Setup**: [preTestCheck] runs (Kotlin suspend or Java Runnable). - * 2. **Device Prep**: Screen wakes -> Orientation locked -> Navigates to Home. - * 3. **Focus Check**: Launches a hidden activity to verify foreground focus is obtainable. + * 2. **Device Prep**: Screen wakes -> Keyguard dismissed -> Navigates Home. + * 3. **Focus & Orientation Lock**: Launches [ForegroundTestActivity] to verify foreground focus is + * obtainable, locks natural orientation (`Surface.ROTATION_0`), and awaits rotation settlement + * before finishing it (avoiding fixed-orientation Home launcher stalls). * 4. **Test Body**: Your actual test code (and any `@Before` methods) executes while monitoring for * mid-test foreground loss to foreign packages. * 5. **Rule Reset**: Any foreign foreground occupier is force-stopped (in lab environments), the - * device returns Home, and rotation is unfrozen. + * device returns Home, target/test Activities await `STOPPED`/`DESTROYED`, and rotation is + * unfrozen. * 6. **Cleanup Tasks**: All tasks registered via [withCleanup] are executed in **LIFO** (Last-In, * First-Out) order. * * ### Example: Kotlin (Suspend + Chaining) * * ```kotlin - * @get:Rule + * @get:Rule(order = 0) * val foregroundRule = RequireForegroundRule { * // Runs before UI prep. Good for initialization/assumptions. * cameraProvider = ProcessCameraProvider.getInstance(context).await() @@ -95,7 +121,7 @@ * ### Example: Java (Runnable) * * ```java - * @Rule + * @Rule(order = 0) * public RequireForegroundRule foregroundRule = new RequireForegroundRule(() -> { * // Standard setup logic * }).withCleanup(() -> { @@ -164,6 +190,7 @@ object : Statement() { override fun evaluate() { var testError: Throwable? = null + var lockedDevice: UiDevice? = null try { // Run early assumptions BEFORE heavy UI operations. @@ -172,9 +199,42 @@ val instrumentation = InstrumentationRegistry.getInstrumentation() val device = runBlocking { getUiDevice(instrumentation) } - device.setOrientationNatural() - device.waitForIdle(INITIAL_IDLE_TIMEOUT_MS) - prepareDeviceUI(instrumentation) + clearDeviceUI(instrumentation) + prepareForegroundActivity(instrumentation) { + // Lock and settle while ForegroundTestActivity holds focus so + // fixed-orientation / NOSENSOR Home launchers do not stall rotation. + lockedDevice = device + val displayManager = + instrumentation.targetContext.getSystemService(Context.DISPLAY_SERVICE) + as? DisplayManager + val settled = + lockAndSettleNaturalOrientation( + lockDisplayScoped = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + { device.setOrientationNatural(Display.DEFAULT_DISPLAY) } + } else { + null + }, + lockUiAutomation = { device.setOrientationNatural() }, + awaitSettled = { + displayManager == null || + awaitDefaultDisplayRotation(displayManager) + }, + ) + if (displayManager != null) { + if (settled) { + instrumentation.waitForIdleSync() + } else { + Logger.w( + TAG, + "Display rotation did not settle to ROTATION_0 within " + + "${ROTATION_SETTLE_TIMEOUT_MS}ms (current=" + + "${getDefaultDisplayRotation(displayManager)}, " + + "interrupted=${Thread.currentThread().isInterrupted})", + ) + } + } + } val testPackage = instrumentation.context.packageName val targetPackage = instrumentation.targetContext.packageName @@ -259,8 +319,7 @@ foregroundCheckExecutor.shutdownNow() try { backToHome(instrumentation) - device.unfreezeRotation() - device.waitForIdle(UI_STABILIZATION_TIMEOUT_MS) + awaitTargetActivitiesStopped(monitor = lifecycleMonitor) } catch (t: Throwable) { Log.w(TAG, "Failed to gracefully clean up device state", t) } @@ -269,6 +328,15 @@ // Capture failures from preTestCheck or prepareDeviceUI if test hasn't run if (testError == null) testError = t } finally { + lockedDevice?.let { + try { + unfreezeRotation(it) + it.waitForIdle(UI_STABILIZATION_TIMEOUT_MS) + } catch (t: Throwable) { + Logger.w(TAG, "Failed to unfreeze rotation", t) + } + } + // Deferred Cleanup Tasks val cleanupErrors = mutableListOf<Throwable>() cleanupTasks.reversed().forEach { task -> @@ -299,11 +367,14 @@ public companion object { private const val TAG = "RequireForegroundRule" private const val MH_TAG = "MH" - private const val INITIAL_IDLE_TIMEOUT_MS: Long = 2000 private const val UI_STABILIZATION_TIMEOUT_MS: Long = 3000 private const val FOREGROUND_ACTIVITY_DESTROY_TIMEOUT_MS: Long = 5000 + private const val ROTATION_SETTLE_TIMEOUT_MS: Long = 10000 + private const val TEARDOWN_STOP_TIMEOUT_MS: Long = 3000 private const val FOREGROUND_CHECK_DELAY_MS: Long = 200 private const val DISMISS_LOCK_SCREEN_CODE = 82 + private val VISIBLE_ACTIVITY_STAGES: Set<Stage> = + setOf(Stage.STARTED, Stage.RESUMED, Stage.PAUSED, Stage.RESTARTED) private const val ADB_SHELL_DISMISS_KEYGUARD_API23_AND_ABOVE = "wm dismiss-keyguard" private const val ADB_SHELL_SCREEN_ALWAYS_ON = "svc power stayon true" private const val ADB_SHELL_DISABLE_CAMERA_SENSOR_PRIVACY_API31_AND_ABOVE = @@ -359,40 +430,123 @@ @Throws(ForegroundOccupiedError::class) public fun prepareDeviceUI(instrumentation: Instrumentation) { clearDeviceUI(instrumentation) + prepareForegroundActivity(instrumentation) + } - var activityRef: ForegroundTestActivity? = null - try { - val context = InstrumentationRegistry.getInstrumentation().targetContext - val startIntent = - Intent(Intent.ACTION_MAIN).apply { - setClassName(context.packageName, ForegroundTestActivity::class.java.name) - addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - } - - var retryCount = 0 - while (retryCount < 3) { - try { - activityRef = - instrumentation.startActivitySync(startIntent) as ForegroundTestActivity - break - } catch (e: RuntimeException) { - Logger.w( - TAG, - "Failed to launch ForegroundTestActivity on attempt $retryCount", - e, - ) - retryCount++ - if (retryCount >= 3) throw e - clearDeviceUI(instrumentation) - } + /** + * Locks the default display in its natural orientation (`Surface.ROTATION_0`) and awaits + * settlement. + * + * On API 30+, attempts the `Display.DEFAULT_DISPLAY` overload (`cmd window user-rotation`, + * per b/559546730) and falls back to `UiAutomation` rotation freeze if the display-scoped + * call throws or silently fails to settle; on older APIs, uses `UiAutomation` directly. + */ + internal fun lockAndSettleNaturalOrientation( + lockDisplayScoped: (() -> Unit)?, + lockUiAutomation: () -> Unit, + awaitSettled: () -> Boolean, + isInterrupted: () -> Boolean = { Thread.currentThread().isInterrupted }, + ): Boolean { + var usedDisplayScoped = false + if (lockDisplayScoped != null) { + try { + lockDisplayScoped() + usedDisplayScoped = true + } catch (e: RuntimeException) { + Logger.w( + TAG, + "Display-scoped setOrientationNatural failed; falling back to UiAutomation", + e, + ) + lockUiAutomation() } - instrumentation.waitForIdleSync() + } else { + lockUiAutomation() + } + var settled = awaitSettled() + if (!settled && usedDisplayScoped && !isInterrupted()) { + Logger.w( + TAG, + "Display-scoped rotation lock did not settle to ROTATION_0; " + + "falling back to UiAutomation", + ) + lockUiAutomation() + settled = awaitSettled() + } + return settled + } - IdlingRegistry.getInstance().register(activityRef!!.viewReadyIdlingResource) - Espresso.onIdle() - return - } catch (e: Exception) { - Logger.d(TAG, "Fail to get foreground", e) + /** + * Unfreezes display rotation on the default display, clearing both the API 30+ per-display + * `user-rotation` lock (b/559546730) and the `UiAutomation` rotation freeze. + */ + @Throws(RemoteException::class) + internal fun unfreezeRotation(device: UiDevice) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + device.unfreezeRotation(Display.DEFAULT_DISPLAY) + } catch (e: RuntimeException) { + Logger.w( + TAG, + "Display-scoped unfreezeRotation failed; continuing with default unfreeze", + e, + ) + } + } + device.unfreezeRotation() + } + + @Throws(ForegroundOccupiedError::class) + private fun prepareForegroundActivity( + instrumentation: Instrumentation, + onForegroundReady: (() -> Unit)? = null, + ) { + var activityRef: ForegroundTestActivity? = null + var foregroundVerified = false + val context = instrumentation.targetContext + try { + try { + val startIntent = + Intent(Intent.ACTION_MAIN).apply { + setClassName( + context.packageName, + ForegroundTestActivity::class.java.name, + ) + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + + var retryCount = 0 + while (retryCount < 3) { + try { + activityRef = + instrumentation.startActivitySync(startIntent) + as ForegroundTestActivity + break + } catch (e: RuntimeException) { + Logger.w( + TAG, + "Failed to launch ForegroundTestActivity on attempt $retryCount", + e, + ) + retryCount++ + if (retryCount >= 3) throw e + clearDeviceUI(instrumentation) + } + } + instrumentation.waitForIdleSync() + + val foregroundActivity = checkNotNull(activityRef) + IdlingRegistry.getInstance() + .register(foregroundActivity.viewReadyIdlingResource) + Espresso.onIdle() + foregroundVerified = true + } catch (e: Exception) { + Logger.d(TAG, "Fail to get foreground", e) + } + + if (foregroundVerified) { + onForegroundReady?.invoke() + } } finally { activityRef?.let { activity -> IdlingRegistry.getInstance().unregister(activity.viewReadyIdlingResource) @@ -413,12 +567,115 @@ } } + if (foregroundVerified) { + return + } + // Throw AssumptionViolatedException to skip the test if not in the CameraX lab // environment. The loggable tag will be set when running the CameraX daily testing. assumeTrue(Log.isLoggable(MH_TAG, Log.DEBUG)) throw ForegroundOccupiedError("CameraX_fail_to_start_foreground, model: ${Build.MODEL}") } + internal fun getDefaultDisplayRotation(displayManager: DisplayManager): Int? = + displayManager.getDisplay(Display.DEFAULT_DISPLAY)?.rotation + + internal fun awaitDefaultDisplayRotation( + displayManager: DisplayManager, + expectedRotation: Int = Surface.ROTATION_0, + timeoutMs: Long = ROTATION_SETTLE_TIMEOUT_MS, + ): Boolean { + val initialRotation = getDefaultDisplayRotation(displayManager) ?: return false + if (initialRotation == expectedRotation) { + return true + } + check(Looper.myLooper() != Looper.getMainLooper()) { + "awaitDefaultDisplayRotation must not block the main thread" + } + val settledLatch = CountDownLatch(1) + val listener = + object : DisplayManager.DisplayListener { + override fun onDisplayAdded(displayId: Int) {} + + override fun onDisplayRemoved(displayId: Int) {} + + override fun onDisplayChanged(displayId: Int) { + if ( + displayId == Display.DEFAULT_DISPLAY && + getDefaultDisplayRotation(displayManager) == expectedRotation + ) { + settledLatch.countDown() + } + } + } + displayManager.registerDisplayListener(listener, Handler(Looper.getMainLooper())) + try { + if (getDefaultDisplayRotation(displayManager) == expectedRotation) { + return true + } + val awaited = + try { + settledLatch.await(timeoutMs, TimeUnit.MILLISECONDS) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + return false + } + return awaited || getDefaultDisplayRotation(displayManager) == expectedRotation + } finally { + displayManager.unregisterDisplayListener(listener) + } + } + + internal fun hasVisibleActivity(monitor: ActivityLifecycleMonitor): Boolean = + VISIBLE_ACTIVITY_STAGES.any { stage -> + monitor.getActivitiesInStage(stage).isNotEmpty() + } + + internal fun awaitTargetActivitiesStopped( + timeoutMs: Long = TEARDOWN_STOP_TIMEOUT_MS, + monitor: ActivityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(), + ): Boolean { + check(Looper.myLooper() != Looper.getMainLooper()) { + "awaitTargetActivitiesStopped must not block the main thread" + } + val stoppedLatch = CountDownLatch(1) + val callback = ActivityLifecycleCallback { _, _ -> + if (!hasVisibleActivity(monitor)) { + stoppedLatch.countDown() + } + } + monitor.addLifecycleCallback(callback) + try { + if ( + !Handler(Looper.getMainLooper()).post { + if (!hasVisibleActivity(monitor)) { + stoppedLatch.countDown() + } + } + ) { + return false + } + val stopped = + try { + stoppedLatch.await(timeoutMs, TimeUnit.MILLISECONDS) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + false + } + if (!stopped) { + Logger.w( + TAG, + "Target/test Activities did not stop within ${timeoutMs}ms before " + + "unfreezing rotation " + + "(interrupted=${Thread.currentThread().isInterrupted})", + ) + } + return stopped + } finally { + monitor.removeLifecycleCallback(callback) + } + } + @JvmStatic @SuppressLint("MissingPermission", "ObsoleteSdkInt") @Suppress("DEPRECATION")
diff --git a/camera/camera-testing/src/test/java/androidx/camera/testing/impl/RequireForegroundRuleTest.kt b/camera/camera-testing/src/test/java/androidx/camera/testing/impl/RequireForegroundRuleTest.kt index 8e7a61c..de4df56 100644 --- a/camera/camera-testing/src/test/java/androidx/camera/testing/impl/RequireForegroundRuleTest.kt +++ b/camera/camera-testing/src/test/java/androidx/camera/testing/impl/RequireForegroundRuleTest.kt
@@ -16,13 +16,25 @@ package androidx.camera.testing.impl +import android.app.Activity +import android.content.Context +import android.hardware.display.DisplayManager +import android.os.Looper +import android.view.Display +import android.view.Surface import androidx.camera.testing.impl.RequireForegroundRule.Companion.ForegroundOccupiedError import androidx.camera.testing.impl.activity.ForegroundTestActivity +import androidx.test.core.app.ApplicationProvider +import androidx.test.runner.lifecycle.ActivityLifecycleCallback +import androidx.test.runner.lifecycle.ActivityLifecycleMonitor import androidx.test.runner.lifecycle.Stage import com.google.common.truth.Truth.assertThat +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.Future import java.util.concurrent.FutureTask +import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference import org.junit.Assert.assertThrows @@ -31,8 +43,10 @@ import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import org.robolectric.annotation.internal.DoNotInstrument +import org.robolectric.shadows.ShadowDisplayManager /** Unit tests for [RequireForegroundRule]. */ @RunWith(RobolectricTestRunner::class) @@ -509,4 +523,332 @@ controller.pause().stop().destroy() } } + + @Test + fun lockAndSettleNaturalOrientation_fallsBackToUiAutomationOnApi30FailureOrTimeout() { + // API 30+ happy path: display-scoped lock settles without calling UiAutomation fallback. + var displayCalls = 0 + var uiAutomationCalls = 0 + var awaitCalls = 0 + assertThat( + RequireForegroundRule.lockAndSettleNaturalOrientation( + lockDisplayScoped = { displayCalls++ }, + lockUiAutomation = { uiAutomationCalls++ }, + awaitSettled = { + awaitCalls++ + true + }, + ) + ) + .isTrue() + assertThat(displayCalls).isEqualTo(1) + assertThat(uiAutomationCalls).isEqualTo(0) + assertThat(awaitCalls).isEqualTo(1) + + // API 30+ exception path: falls back once and does not re-invoke UiAutomation on timeout. + uiAutomationCalls = 0 + awaitCalls = 0 + assertThat( + RequireForegroundRule.lockAndSettleNaturalOrientation( + lockDisplayScoped = { throw RuntimeException("shell failed") }, + lockUiAutomation = { uiAutomationCalls++ }, + awaitSettled = { + awaitCalls++ + false + }, + isInterrupted = { false }, + ) + ) + .isFalse() + assertThat(uiAutomationCalls).isEqualTo(1) + assertThat(awaitCalls).isEqualTo(1) + + // API 30+ silent-ignore path: falls back lazily when display-scoped lock fails to settle. + displayCalls = 0 + uiAutomationCalls = 0 + awaitCalls = 0 + assertThat( + RequireForegroundRule.lockAndSettleNaturalOrientation( + lockDisplayScoped = { displayCalls++ }, + lockUiAutomation = { uiAutomationCalls++ }, + awaitSettled = { ++awaitCalls >= 2 }, + isInterrupted = { false }, + ) + ) + .isTrue() + assertThat(displayCalls).isEqualTo(1) + assertThat(uiAutomationCalls).isEqualTo(1) + assertThat(awaitCalls).isEqualTo(2) + + // Interrupted caller skips fallback so interruption returns promptly. + uiAutomationCalls = 0 + awaitCalls = 0 + assertThat( + RequireForegroundRule.lockAndSettleNaturalOrientation( + lockDisplayScoped = {}, + lockUiAutomation = { uiAutomationCalls++ }, + awaitSettled = { + awaitCalls++ + false + }, + isInterrupted = { true }, + ) + ) + .isFalse() + assertThat(uiAutomationCalls).isEqualTo(0) + assertThat(awaitCalls).isEqualTo(1) + + // Pre-API 30 path: invokes UiAutomation directly without double fallback. + uiAutomationCalls = 0 + awaitCalls = 0 + assertThat( + RequireForegroundRule.lockAndSettleNaturalOrientation( + lockDisplayScoped = null, + lockUiAutomation = { uiAutomationCalls++ }, + awaitSettled = { + awaitCalls++ + false + }, + isInterrupted = { false }, + ) + ) + .isFalse() + assertThat(uiAutomationCalls).isEqualTo(1) + assertThat(awaitCalls).isEqualTo(1) + } + + @Test + @Suppress("DEPRECATION") + fun awaitDefaultDisplayRotation_handlesFastPathTransitionTimeoutAndInterrupt() { + val context = ApplicationProvider.getApplicationContext<Context>() + val displayManager = context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager + val defaultDisplay = requireNotNull(displayManager.getDisplay(Display.DEFAULT_DISPLAY)) + + // Fast-path: already at ROTATION_0, returns true immediately even on the main thread. + shadowOf(defaultDisplay).setRotation(Surface.ROTATION_0) + assertThat( + RequireForegroundRule.awaitDefaultDisplayRotation( + displayManager = displayManager, + expectedRotation = Surface.ROTATION_0, + timeoutMs = 50L, + ) + ) + .isTrue() + + // Guard: when rotation has not settled, blocking the main thread is rejected. + shadowOf(defaultDisplay).setRotation(Surface.ROTATION_90) + assertThrows(IllegalStateException::class.java) { + RequireForegroundRule.awaitDefaultDisplayRotation( + displayManager = displayManager, + expectedRotation = Surface.ROTATION_0, + timeoutMs = 50L, + ) + } + + val executor = Executors.newSingleThreadExecutor() + try { + // Timeout path: stays at ROTATION_90 -> returns false cleanly. + val timeoutFuture = + executor.submit<Boolean> { + RequireForegroundRule.awaitDefaultDisplayRotation( + displayManager = displayManager, + expectedRotation = Surface.ROTATION_0, + timeoutMs = 25L, + ) + } + pumpMainLooperUntilDone(timeoutFuture) + assertThat(timeoutFuture.get(2, TimeUnit.SECONDS)).isFalse() + + // Pre-interrupted caller thread: returns false and preserves interrupt flag. + val interruptedPreservedFuture = + executor.submit<Boolean> { + Thread.currentThread().interrupt() + try { + val settled = + RequireForegroundRule.awaitDefaultDisplayRotation( + displayManager = displayManager, + expectedRotation = Surface.ROTATION_0, + timeoutMs = 5000L, + ) + assertThat(settled).isFalse() + Thread.currentThread().isInterrupted + } finally { + Thread.interrupted() + } + } + pumpMainLooperUntilDone(interruptedPreservedFuture) + assertThat(interruptedPreservedFuture.get(2, TimeUnit.SECONDS)).isTrue() + + // Event-driven transition path: wait until the worker is blocked in settledLatch.await + // (after registering DisplayListener) before triggering ROTATION_0. Use a 60s timeout + // well above the 5s looper-pump window so removing DisplayListener fails by timeout. + val workerThreadRef = AtomicReference<Thread?>(null) + val settleFuture = + executor.submit<Boolean> { + workerThreadRef.set(Thread.currentThread()) + RequireForegroundRule.awaitDefaultDisplayRotation( + displayManager = displayManager, + expectedRotation = Surface.ROTATION_0, + timeoutMs = 60_000L, + ) + } + val awaitBlockedDeadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(2) + while ( + workerThreadRef.get()?.state != Thread.State.TIMED_WAITING && + System.nanoTime() < awaitBlockedDeadlineNs + ) { + Thread.yield() + } + assertThat(workerThreadRef.get()?.state).isEqualTo(Thread.State.TIMED_WAITING) + assertThat(settleFuture.isDone).isFalse() + + shadowOf(defaultDisplay).setRotation(Surface.ROTATION_0) + ShadowDisplayManager.changeDisplay(Display.DEFAULT_DISPLAY, "") + pumpMainLooperUntilDone(settleFuture) + assertThat(settleFuture.get(2, TimeUnit.SECONDS)).isTrue() + } finally { + shadowOf(defaultDisplay).setRotation(Surface.ROTATION_0) + executor.shutdownNow() + } + } + + @Test + fun hasVisibleActivity_treatsPausedAsVisibleAndStoppedAsNotVisible() { + val controller = Robolectric.buildActivity(ForegroundTestActivity::class.java).setup() + val activity = controller.get() + val monitor = FakeActivityLifecycleMonitor() + try { + for (visibleStage in + listOf(Stage.STARTED, Stage.RESUMED, Stage.PAUSED, Stage.RESTARTED)) { + monitor.setActivityStage(activity, visibleStage) + assertThat(RequireForegroundRule.hasVisibleActivity(monitor)).isTrue() + } + + for (nonVisibleStage in + listOf(Stage.PRE_ON_CREATE, Stage.CREATED, Stage.STOPPED, Stage.DESTROYED)) { + monitor.setActivityStage(activity, nonVisibleStage) + assertThat(RequireForegroundRule.hasVisibleActivity(monitor)).isFalse() + } + } finally { + controller.pause().stop().destroy() + } + } + + @Test + fun awaitTargetActivitiesStopped_waitsUntilPausedActivityReachesStopped() { + val controller = Robolectric.buildActivity(ForegroundTestActivity::class.java).setup() + val activity = controller.get() + val monitor = FakeActivityLifecycleMonitor() + + val executor = Executors.newSingleThreadExecutor() + try { + // Guard: blocking the main thread is rejected. + monitor.setActivityStage(activity, Stage.PAUSED) + assertThrows(IllegalStateException::class.java) { + RequireForegroundRule.awaitTargetActivitiesStopped( + timeoutMs = 50L, + monitor = monitor, + ) + } + monitor.setActivityStage(activity, Stage.STOPPED) + + // Fast-path when already STOPPED on background thread. + val fastFuture = + executor.submit<Boolean> { + RequireForegroundRule.awaitTargetActivitiesStopped( + timeoutMs = 500L, + monitor = monitor, + ) + } + pumpMainLooperUntilDone(fastFuture) + assertThat(fastFuture.get(2, TimeUnit.SECONDS)).isTrue() + assertThat(monitor.callbacks).isEmpty() + + // Slow-path when PAUSED during Home transition: blocks until STOPPED arrives. + val slowCallbackLatch = monitor.resetCallbackAddedLatch() + monitor.setActivityStage(activity, Stage.PAUSED) + val awaitFuture = + executor.submit<Boolean> { + RequireForegroundRule.awaitTargetActivitiesStopped( + timeoutMs = 5000L, + monitor = monitor, + ) + } + assertThat(slowCallbackLatch.await(2, TimeUnit.SECONDS)).isTrue() + shadowOf(Looper.getMainLooper()).idle() + assertThat(awaitFuture.isDone).isFalse() + + monitor.dispatchStage(activity, Stage.STOPPED) + pumpMainLooperUntilDone(awaitFuture) + assertThat(awaitFuture.get(2, TimeUnit.SECONDS)).isTrue() + assertThat(monitor.callbacks).isEmpty() + + // Pre-interrupted caller thread: returns false, preserves interrupt, removes callback. + monitor.setActivityStage(activity, Stage.PAUSED) + val interruptPreservedFuture = + executor.submit<Boolean> { + Thread.currentThread().interrupt() + try { + val stopped = + RequireForegroundRule.awaitTargetActivitiesStopped( + timeoutMs = 5000L, + monitor = monitor, + ) + assertThat(stopped).isFalse() + Thread.currentThread().isInterrupted + } finally { + Thread.interrupted() + } + } + pumpMainLooperUntilDone(interruptPreservedFuture) + assertThat(interruptPreservedFuture.get(2, TimeUnit.SECONDS)).isTrue() + assertThat(monitor.callbacks).isEmpty() + } finally { + executor.shutdownNow() + controller.pause().stop().destroy() + } + } + + private fun pumpMainLooperUntilDone(future: Future<*>) { + val deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (!future.isDone && System.nanoTime() < deadlineNs) { + shadowOf(Looper.getMainLooper()).idle() + Thread.yield() + } + } + + private class FakeActivityLifecycleMonitor : ActivityLifecycleMonitor { + val callbacks = CopyOnWriteArrayList<ActivityLifecycleCallback>() + private val callbackAddedLatchRef = AtomicReference(CountDownLatch(1)) + private val stages = mutableMapOf<Activity, Stage>() + + fun resetCallbackAddedLatch(): CountDownLatch = + CountDownLatch(1).also { callbackAddedLatchRef.set(it) } + + fun setActivityStage(activity: Activity, stage: Stage) { + stages[activity] = stage + } + + fun dispatchStage(activity: Activity, stage: Stage) { + stages[activity] = stage + for (callback in callbacks) { + callback.onActivityLifecycleChanged(activity, stage) + } + } + + override fun addLifecycleCallback(callback: ActivityLifecycleCallback) { + callbacks.add(callback) + callbackAddedLatchRef.get().countDown() + } + + override fun removeLifecycleCallback(callback: ActivityLifecycleCallback) { + callbacks.remove(callback) + } + + override fun getLifecycleStageOf(activity: Activity): Stage = + stages[activity] ?: Stage.PRE_ON_CREATE + + override fun getActivitiesInStage(stage: Stage): Collection<Activity> = + stages.filterValues { it == stage }.keys + } }
diff --git a/camera/camera-video/src/androidTest/java/androidx/camera/video/VideoCaptureDeviceTest.kt b/camera/camera-video/src/androidTest/java/androidx/camera/video/VideoCaptureDeviceTest.kt index 45ddce0..779fec1 100644 --- a/camera/camera-video/src/androidTest/java/androidx/camera/video/VideoCaptureDeviceTest.kt +++ b/camera/camera-video/src/androidTest/java/androidx/camera/video/VideoCaptureDeviceTest.kt
@@ -19,6 +19,7 @@ import android.content.Context import android.graphics.SurfaceTexture import android.os.Build +import android.util.Size import android.view.Surface import androidx.camera.camera2.Camera2Config import androidx.camera.core.CameraInfo @@ -31,6 +32,7 @@ import androidx.camera.core.Preview import androidx.camera.core.SurfaceRequest import androidx.camera.core.impl.CameraInfoInternal +import androidx.camera.core.impl.ImageFormatConstants.INTERNAL_DEFINED_IMAGE_FORMAT_PRIVATE import androidx.camera.core.impl.MutableStateObservable import androidx.camera.core.impl.Observable import androidx.camera.core.internal.CameraUseCaseAdapter @@ -134,7 +136,7 @@ cameraUseCaseAdapter = CameraUtil.createCameraUseCaseAdapter(context, cameraSelector) cameraInfo = cameraUseCaseAdapter.cameraInfo as CameraInfoInternal - videoCapabilities = Recorder.getVideoCapabilities(cameraInfo) + videoCapabilities = createCameraVideoCapabilities(cameraInfo) } @After @@ -503,6 +505,42 @@ .build() } + /** + * Creates [VideoCapabilities] from what the camera supports, so the tests only depend on + * [VideoCapture] and the camera, not on the capabilities of a specific [VideoOutput] such as + * [Recorder]. + * + * All dynamic ranges supported by the camera are supported, each with the [FHD], [HD] and [SD] + * qualities whose typical size is supported by the camera. + */ + private fun createCameraVideoCapabilities(cameraInfo: CameraInfoInternal): VideoCapabilities { + val cameraSupportedSizes = + cameraInfo.getSupportedResolutions(INTERNAL_DEFINED_IMAGE_FORMAT_PRIVATE).toSet() + val qualityToSize: Map<Quality, Size> = + listOf(FHD, HD, SD) + .mapNotNull { quality -> + (quality as Quality.ConstantQuality) + .typicalSizes + .firstOrNull { it in cameraSupportedSizes } + ?.let { quality to it } + } + .toMap() + val supportedDynamicRanges = cameraInfo.supportedDynamicRanges + return object : VideoCapabilities { + override fun getSupportedDynamicRanges(): Set<DynamicRange> = supportedDynamicRanges + + override fun getSupportedQualities(dynamicRange: DynamicRange): List<Quality> = + if (dynamicRange in supportedDynamicRanges) qualityToSize.keys.toList() + else emptyList() + + override fun isQualitySupported(quality: Quality, dynamicRange: DynamicRange): Boolean = + quality in getSupportedQualities(dynamicRange) + + override fun getResolution(quality: Quality, dynamicRange: DynamicRange): Size? = + if (isQualitySupported(quality, dynamicRange)) qualityToSize[quality] else null + } + } + private class TestVideoOutput( streamInfo: StreamInfo, mediaSpec: MediaSpec,
diff --git a/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncodedDataImpl.java b/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncodedDataImpl.java index 7310f55..5d8ed39 100644 --- a/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncodedDataImpl.java +++ b/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncodedDataImpl.java
@@ -42,7 +42,7 @@ private final AtomicBoolean mClosed = new AtomicBoolean(false); EncodedDataImpl(@NonNull MediaCodec mediaCodec, int bufferIndex, - MediaCodec.@NonNull BufferInfo bufferInfo) throws MediaCodec.CodecException { + MediaCodec.@NonNull BufferInfo bufferInfo) throws IllegalStateException { mMediaCodec = Preconditions.checkNotNull(mediaCodec); mBufferIndex = bufferIndex; mByteBuffer = mediaCodec.getOutputBuffer(bufferIndex);
diff --git a/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncoderImpl.java b/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncoderImpl.java index f29da8e..b89cf20 100644 --- a/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncoderImpl.java +++ b/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/EncoderImpl.java
@@ -225,6 +225,7 @@ private MediaCodecCallback mMediaCodecCallback = null; private boolean mIsFlushedAfterEndOfStream = false; + private boolean mIsCodecConfigured = false; private boolean mSourceStoppedSignalled = false; boolean mMediaCodecEosSignalled = false; private @Nullable Future<?> mSignalEosTimeoutFuture; @@ -245,58 +246,79 @@ Preconditions.checkNotNull(executor); mMediaCodec = createCodec(encoderConfig); - MediaCodecInfo mediaCodecInfo = mMediaCodec.getCodecInfo(); - mEncoderExecutor = CameraXExecutors.newSequentialExecutor(executor); - mMediaFormat = encoderConfig.toMediaFormat(); - mInputTimebase = encoderConfig.getInputTimebase(); - mTimeProvider = transformTimeProvider(new SystemTimeProvider(), - this::toPresentationTimeUsByCaptureEncodeRatio); + boolean initialized = false; boolean isHighSpeedCapture = false; - if (encoderConfig instanceof AudioEncoderConfig) { - AudioEncoderConfig audioEncoderConfig = (AudioEncoderConfig) encoderConfig; - mTag = "AudioEncoder"; - mIsVideoEncoder = false; - mEncoderInput = new ByteBufferInput(); - AudioEncoderInfo audioEncoderInfo = new AudioEncoderInfoImpl(mediaCodecInfo, - encoderConfig.getMimeType()); - clampBitrateIfNotSupported(audioEncoderInfo, mMediaFormat); - mEncoderInfo = audioEncoderInfo; - mCaptureToEncodeFrameRateRatio = new Rational(audioEncoderConfig.getCaptureSampleRate(), - audioEncoderConfig.getEncodeSampleRate()); - mResumeInputSurfaceOnStart = false; - } else if (encoderConfig instanceof VideoEncoderConfig) { - VideoEncoderConfig videoEncoderConfig = (VideoEncoderConfig) encoderConfig; - mTag = "VideoEncoder"; - mIsVideoEncoder = true; - mEncoderInput = new SurfaceInput(); - VideoEncoderInfo videoEncoderInfo = new VideoEncoderInfoImpl(mediaCodecInfo, - encoderConfig.getMimeType()); - clampBitrateIfNotSupported(videoEncoderInfo, mMediaFormat); - mEncoderInfo = videoEncoderInfo; - mCaptureToEncodeFrameRateRatio = new Rational(videoEncoderConfig.getCaptureFrameRate(), - videoEncoderConfig.getEncodeFrameRate()); - isHighSpeedCapture = videoEncoderConfig.isHighSpeedCapture(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - // Connect the persistent input surface suspended so frames rendered while the - // encoder is configured are dropped instead of held and submitted during - // MediaCodec.start() (b/579234725). - mMediaFormat.setInteger(MediaFormat.KEY_CREATE_INPUT_SURFACE_SUSPENDED, 1); - mResumeInputSurfaceOnStart = true; - } else { - mResumeInputSurfaceOnStart = false; - } - } else { - throw new InvalidConfigException("Unknown encoder config type"); - } - - Logger.d(mTag, "mInputTimebase = " + mInputTimebase); - Logger.d(mTag, "mMediaFormat = " + mMediaFormat); - Logger.d(mTag, "mCaptureToEncodeFrameRateRatio = " + mCaptureToEncodeFrameRateRatio); - + EncoderInput encoderInput = null; try { + MediaCodecInfo mediaCodecInfo = mMediaCodec.getCodecInfo(); + mEncoderExecutor = CameraXExecutors.newSequentialExecutor(executor); + mMediaFormat = encoderConfig.toMediaFormat(); + mInputTimebase = encoderConfig.getInputTimebase(); + mTimeProvider = transformTimeProvider(new SystemTimeProvider(), + this::toPresentationTimeUsByCaptureEncodeRatio); + if (encoderConfig instanceof AudioEncoderConfig) { + AudioEncoderConfig audioEncoderConfig = (AudioEncoderConfig) encoderConfig; + mTag = "AudioEncoder"; + mIsVideoEncoder = false; + encoderInput = new ByteBufferInput(); + mEncoderInput = encoderInput; + AudioEncoderInfo audioEncoderInfo = new AudioEncoderInfoImpl(mediaCodecInfo, + encoderConfig.getMimeType()); + clampBitrateIfNotSupported(audioEncoderInfo, mMediaFormat); + mEncoderInfo = audioEncoderInfo; + mCaptureToEncodeFrameRateRatio = new Rational( + audioEncoderConfig.getCaptureSampleRate(), + audioEncoderConfig.getEncodeSampleRate()); + mResumeInputSurfaceOnStart = false; + } else if (encoderConfig instanceof VideoEncoderConfig) { + VideoEncoderConfig videoEncoderConfig = (VideoEncoderConfig) encoderConfig; + mTag = "VideoEncoder"; + mIsVideoEncoder = true; + encoderInput = new SurfaceInput(); + mEncoderInput = encoderInput; + VideoEncoderInfo videoEncoderInfo = new VideoEncoderInfoImpl(mediaCodecInfo, + encoderConfig.getMimeType()); + clampBitrateIfNotSupported(videoEncoderInfo, mMediaFormat); + mEncoderInfo = videoEncoderInfo; + mCaptureToEncodeFrameRateRatio = new Rational( + videoEncoderConfig.getCaptureFrameRate(), + videoEncoderConfig.getEncodeFrameRate()); + isHighSpeedCapture = videoEncoderConfig.isHighSpeedCapture(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + // Connect the persistent input surface suspended so frames rendered while the + // encoder is configured are dropped instead of held and submitted during + // MediaCodec.start() (b/579234725). + mMediaFormat.setInteger(MediaFormat.KEY_CREATE_INPUT_SURFACE_SUSPENDED, 1); + mResumeInputSurfaceOnStart = true; + } else { + mResumeInputSurfaceOnStart = false; + } + } else { + throw new InvalidConfigException("Unknown encoder config type"); + } + + Logger.d(mTag, "mInputTimebase = " + mInputTimebase); + Logger.d(mTag, "mMediaFormat = " + mMediaFormat); + Logger.d(mTag, "mCaptureToEncodeFrameRateRatio = " + mCaptureToEncodeFrameRateRatio); + + // Set state before reset() registers MediaCodecCallback so async callbacks never see + // null. + setState(CONFIGURED); reset(); - } catch (MediaCodec.CodecException e) { + initialized = true; + } catch (IllegalStateException e) { throw new InvalidConfigException(e); + } finally { + if (!initialized) { + try { + mMediaCodec.release(); + } catch (RuntimeException e) { + Logger.w("EncoderImpl", "Failed to release MediaCodec on init failure", e); + } + if (encoderInput instanceof SurfaceInput) { + ((SurfaceInput) encoderInput).releaseSurface(); + } + } } AtomicReference<Completer<Void>> releaseFutureRef = new AtomicReference<>(); @@ -309,8 +331,6 @@ mCodecStopAsFlushWorkaroundEnabled = shouldEnableCodecStopAsFlushWorkaround(isHighSpeedCapture); - - setState(CONFIGURED); } /** @@ -342,31 +362,15 @@ private void reset() { mStartStopTimeRangeUs = NO_RANGE; mActivePauseResumeTimeRanges.clear(); - mFreeInputBufferIndexQueue.clear(); + stopDispatchingBuffers(); - // Cancel incomplete acquisitions if exists. - for (Completer<InputBuffer> completer : mAcquisitionQueue) { - completer.setCancelled(); - } - mAcquisitionQueue.clear(); - - Logger.d(mTag, "mMediaCodec.reset()"); - mMediaCodec.reset(); mIsFlushedAfterEndOfStream = false; mSourceStoppedSignalled = false; mMediaCodecEosSignalled = false; - mPendingCodecStop = false; - if (mStopTimeoutFuture != null) { - mStopTimeoutFuture.cancel(true); - mStopTimeoutFuture = null; - } - if (mSignalEosTimeoutFuture != null) { - mSignalEosTimeoutFuture.cancel(false); - mSignalEosTimeoutFuture = null; - } - if (mMediaCodecCallback != null) { - mMediaCodecCallback.stop(); - } + + mIsCodecConfigured = false; + Logger.d(mTag, "mMediaCodec.reset()"); + mMediaCodec.reset(); mMediaCodecCallback = new MediaCodecCallback(); Logger.d(mTag, "mMediaCodec.setCallback()"); mMediaCodec.setCallback(mMediaCodecCallback); @@ -377,6 +381,7 @@ if (mEncoderInput instanceof SurfaceInput) { ((SurfaceInput) mEncoderInput).resetSurface(); } + mIsCodecConfigured = true; } /** Gets the {@link EncoderInput} of the encoder */ @@ -413,10 +418,9 @@ Logger.d(mTag, "Start on " + DebugUtils.readableUs(startTriggerTimeUs)); try { - if (mIsFlushedAfterEndOfStream) { - // If the codec is flushed after an end-of-stream, it was never - // signaled that the source stopped, so we will reset the codec - // before starting it again. + if (mIsFlushedAfterEndOfStream || !mIsCodecConfigured) { + // Reset before starting if the codec was left flushed after + // end-of-stream or if a previous reset/configure attempt failed. reset(); } mStartStopTimeRangeUs = Range.create(startTriggerTimeUs, NO_LIMIT_LONG); @@ -425,7 +429,7 @@ if (mResumeInputSurfaceOnStart) { setMediaCodecPaused(false); } - } catch (MediaCodec.CodecException e) { + } catch (IllegalStateException e) { handleEncodeError(e); return; } @@ -435,6 +439,11 @@ setState(STARTED); break; case PAUSED: + if (mIsStoppingMediaCodec) { + // The codec reached end of stream on its own and is stopping; the session + // is ending and onEncodeStop() will follow, so ignore the resume. + break; + } // Resume // The Encoder has been resumed, so reset the stop timestamp flags. @@ -455,25 +464,32 @@ (startTriggerTimeUs - pauseTimeUs)) ); - if (!mIsVideoEncoder && DeviceQuirks.get( - AudioEncoderIgnoresInputTimestampQuirk.class) != null) { - // Do nothing. Since we keep handling audio data in the codec after - // paused, we don't have to resume the codec and the input source. - } else if (mIsVideoEncoder && DeviceQuirks.get( - VideoEncoderSuspendDoesNotIncludeSuspendTimeQuirk.class) != null) { - // Do nothing. Since we don't pause the codec when paused, we don't have - // to resume the codec. - } else { - setMediaCodecPaused(false); - if (mEncoderInput instanceof ByteBufferInput) { - ((ByteBufferInput) mEncoderInput).setActive(true); + boolean resumeByteBufferInput = false; + try { + if (!mIsVideoEncoder && DeviceQuirks.get( + AudioEncoderIgnoresInputTimestampQuirk.class) != null) { + // Do nothing. Since we keep handling audio data in the codec after + // paused, we don't have to resume the codec and the input source. + } else if (mIsVideoEncoder && DeviceQuirks.get( + VideoEncoderSuspendDoesNotIncludeSuspendTimeQuirk.class) != null) { + // Do nothing. Since we don't pause the codec when paused, we don't have + // to resume the codec. + } else { + setMediaCodecPaused(false); + resumeByteBufferInput = mEncoderInput instanceof ByteBufferInput; } + // If this is a video encoder, then request a key frame in order to complete + // the resume process as soon as possible in MediaCodec.Callback + // .onOutputBufferAvailable(). + if (mIsVideoEncoder) { + requestKeyFrameToMediaCodec(); + } + } catch (IllegalStateException e) { + handleEncodeError(e); + return; } - // If this is a video encoder, then request a key frame in order to complete - // the resume process as soon as possible in MediaCodec.Callback - // .onOutputBufferAvailable(). - if (mIsVideoEncoder) { - requestKeyFrameToMediaCodec(); + if (resumeByteBufferInput) { + ((ByteBufferInput) mEncoderInput).setActive(true); } setState(STARTED); break; @@ -534,6 +550,11 @@ // that has a timestamp equal or greater than the stop time. mStartStopTimeRangeUs = Range.create(startTimeUs, stopTimeUs); Logger.d(mTag, "Stop on " + DebugUtils.readableUs(stopTimeUs)); + // If the codec is already stopping (e.g. unexpected EOS), wait for it to + // finish without arming a new stop timeout or signalling EOS again. + if (mIsStoppingMediaCodec) { + break; + } // If the Encoder is paused and has received enough data, directly signal // the codec to stop. if (currentState == PAUSED && mLastDataStopTimestamp != null) { @@ -594,7 +615,7 @@ Logger.d(mTag, "mMediaCodec.signalEndOfInputStream()"); mMediaCodec.signalEndOfInputStream(); mMediaCodecEosSignalled = true; - } catch (MediaCodec.CodecException e) { + } catch (IllegalStateException e) { handleEncodeError(e); } } @@ -619,6 +640,10 @@ setState(PENDING_START_PAUSED); break; case STARTED: + if (mIsStoppingMediaCodec) { + // The codec is already stopping after an unexpected end of stream. + break; + } // Create and insert a pause/resume range. Logger.d(mTag, "Pause on " + DebugUtils.readableUs(pauseTriggerTimeUs)); mActivePauseResumeTimeRanges.addLast( @@ -661,20 +686,19 @@ // The codec is already being stopped after the error. Release the codec // once the dispatched buffers are returned. See handleStopped(). setState(PENDING_RELEASE); - stopDispatchingBuffers(); } else { - // No stop is in progress, e.g. resetting the codec failed after the - // error. No buffers are dispatched in ERROR, so release it directly. + // No stop is in progress. No buffers are dispatched in ERROR, so release + // it directly. releaseInternal(); } break; case STARTED: case PAUSED: // The encoder is released without being stopped, e.g. the encoder of a - // persistent recording. Stop dispatching new buffers, then release the codec - // once the dispatched buffers are returned. See handleStopped(). + // persistent recording. Stop dispatching new buffers via stopMediaCodec(), then + // release the codec once the dispatched buffers are returned. See + // handleStopped(). setState(PENDING_RELEASE); - stopDispatchingBuffers(); stopMediaCodec(); break; case STOPPING: @@ -758,9 +782,17 @@ // stop() should have been called before if workaround is enabled. if (!mCodecStopAsFlushWorkaroundEnabled) { Logger.d(mTag, "mMediaCodec.stop()"); - mMediaCodec.stop(); + try { + mMediaCodec.stop(); + } catch (IllegalStateException e) { + Logger.w(mTag, "Failed to stop MediaCodec on source stop", e); + } } - reset(); + try { + reset(); + } catch (IllegalStateException e) { + Logger.w(mTag, "Failed to reset MediaCodec on source stop", e); + } } }); } @@ -768,9 +800,9 @@ @ExecutedBy("mEncoderExecutor") private void releaseInternal() { Logger.d(mTag, "releaseInternal"); - // The encoder may be released while it is stopping, so cancel the stop timeouts to avoid - // acting on the released codec, as reset() does. - cancelStopTimeouts(); + // The encoder may be released while it is stopping, so stop dispatching buffers, + // deactivate ByteBufferInput, and cancel stop timeouts before releasing the codec. + stopDispatchingBuffers(); // Must be evaluated before the flush handling below, which resets // mIsFlushedAfterEndOfStream. boolean startCodecBeforeRelease = shouldStartCodecBeforeRelease(); @@ -778,7 +810,11 @@ // stop() should have been called before if workaround is enabled. if (!mCodecStopAsFlushWorkaroundEnabled) { Logger.d(mTag, "mMediaCodec.stop()"); - mMediaCodec.stop(); + try { + mMediaCodec.stop(); + } catch (IllegalStateException e) { + Logger.w(mTag, "Failed to stop MediaCodec before release", e); + } } mIsFlushedAfterEndOfStream = false; } @@ -787,10 +823,6 @@ // See VideoEncoderLeaksThreadOnReleaseWithoutStartQuirk. Releasing a surface-input // codec that was never started leaks a native thread, so start it before release. Logger.d(mTag, "mMediaCodec.start() before release to avoid thread leak"); - if (mMediaCodecCallback != null) { - // Ignore any callbacks triggered by this start. - mMediaCodecCallback.stop(); - } try { mMediaCodec.start(); } catch (RuntimeException e) { @@ -799,7 +831,11 @@ } Logger.d(mTag, "mMediaCodec.release()"); - mMediaCodec.release(); + try { + mMediaCodec.release(); + } catch (RuntimeException e) { + Logger.w(mTag, "Failed to release MediaCodec", e); + } if (mEncoderInput instanceof SurfaceInput) { ((SurfaceInput) mEncoderInput).releaseSurface(); @@ -820,6 +856,7 @@ @ExecutedBy("mEncoderExecutor") private boolean shouldStartCodecBeforeRelease() { return mState == CONFIGURED + && mIsCodecConfigured && !mIsFlushedAfterEndOfStream && mEncoderInput instanceof SurfaceInput && DeviceQuirks.get(VideoEncoderLeaksThreadOnReleaseWithoutStartQuirk.class) @@ -848,7 +885,15 @@ mEncoderExecutor.execute(() -> { switch (mState) { case STARTED: - requestKeyFrameToMediaCodec(); + if (mIsStoppingMediaCodec) { + // The codec is already stopping after an unexpected end of stream. + break; + } + try { + requestKeyFrameToMediaCodec(); + } catch (IllegalStateException e) { + handleEncodeError(e); + } break; case CONFIGURED: case PAUSED: @@ -908,6 +953,10 @@ @ExecutedBy("mEncoderExecutor") private void signalEndOfInputStream() { + if (mIsStoppingMediaCodec || (mState != STOPPING && mState != PENDING_START + && mState != PENDING_START_PAUSED && mState != PENDING_RELEASE)) { + return; + } Logger.d(mTag, "signalEndOfInputStream"); Futures.addCallback(acquireInputBuffer(), new FutureCallback<>() { @@ -916,31 +965,15 @@ inputBuffer.setPresentationTimeUs(generatePresentationTimeUs()); inputBuffer.setEndOfStream(true); inputBuffer.submit(); - - Futures.addCallback(inputBuffer.getTerminationFuture(), - new FutureCallback<>() { - @ExecutedBy("mEncoderExecutor") - @Override - public void onSuccess(@Nullable Void result) { - // Do nothing. - } - - @ExecutedBy("mEncoderExecutor") - @Override - public void onFailure(@NonNull Throwable t) { - if (t instanceof MediaCodec.CodecException) { - handleEncodeError( - (MediaCodec.CodecException) t); - } else { - handleEncodeError(EncodeException.ERROR_UNKNOWN, - t.getMessage(), t); - } - } - }, mEncoderExecutor); } @Override public void onFailure(@NonNull Throwable t) { + if (t instanceof IllegalStateException) { + // Cancelled by stopDispatchingBuffers(), or already reported by + // matchAcquisitionsAndFreeBufferIndexes(). + return; + } handleEncodeError(EncodeException.ERROR_UNKNOWN, "Unable to acquire InputBuffer.", t); } @@ -979,9 +1012,10 @@ } } + /** Handles an error from {@link MediaCodec}, including {@link MediaCodec.CodecException}. */ @SuppressWarnings("WeakerAccess") // synthetic accessor @ExecutedBy("mEncoderExecutor") - void handleEncodeError(MediaCodec.@NonNull CodecException e) { + void handleEncodeError(@NonNull IllegalStateException e) { handleEncodeError(EncodeException.ERROR_CODEC, e.getMessage(), e); } @@ -991,9 +1025,16 @@ @Nullable Throwable throwable) { switch (mState) { case CONFIGURED: - // Unable to start MediaCodec. This is a fatal error. Try to reset the encoder. + // Unable to start MediaCodec. This is a fatal error. Try to reset the encoder if + // it was already configured. notifyError(new EncodeException(error, message, throwable)); - reset(); + if (mIsCodecConfigured) { + try { + reset(); + } catch (IllegalStateException e) { + Logger.w(mTag, "Failed to reset MediaCodec after start error", e); + } + } break; case STARTED: case PAUSED: @@ -1007,11 +1048,10 @@ case PENDING_RELEASE: // Keep the PENDING_RELEASE state so that the encoder is released rather than // reset once the codec is stopped. The release won't wait for the end of stream - // anymore, so stop dispatching new buffers. + // anymore, so stopMediaCodec() stops dispatching new buffers. if (mStopError == null) { mStopError = new EncodeException(error, message, throwable); } - stopDispatchingBuffers(); stopMediaCodec(); break; case ERROR: @@ -1056,6 +1096,8 @@ return; } mIsStoppingMediaCodec = true; + // Don't dispatch new buffers while waiting for the dispatched ones, see the Javadoc. + stopDispatchingBuffers(); /* * MediaCodec#stop will free all its input/output ByteBuffers. Therefore, before calling * MediaCodec#stop, it must ensure all dispatched EncodedData(output ByteBuffers) and @@ -1116,21 +1158,14 @@ // end-of-stream buffer the codec sent on its own and isEndOfStream() doesn't // skip. Stop the codec like a requested stop. Logger.w(mTag, "The codec reached the end of stream unexpectedly in " + mState); - if (mEncoderInput instanceof ByteBufferInput) { - ((ByteBufferInput) mEncoderInput).setActive(false); - } // Fall-through case STOPPING: - stopOrFlushMediaCodec(); - notifyStopped(); - resetStoppedCodec(); + finishCodecStop(); break; case PENDING_START: case PENDING_START_PAUSED: { boolean startPaused = mState == PENDING_START_PAUSED; - stopOrFlushMediaCodec(); - notifyStopped(); - resetStoppedCodec(); + finishCodecStop(); start(); if (startPaused) { pause(); @@ -1158,6 +1193,21 @@ } } + /** Stops or flushes the codec after end of stream, notifies the stop, and resets if needed. */ + @ExecutedBy("mEncoderExecutor") + private void finishCodecStop() { + try { + stopOrFlushMediaCodec(); + } catch (IllegalStateException e) { + // All data up to EOS has been delivered; reset() below recovers the codec from any + // state. + Logger.w(mTag, "Failed to stop/flush MediaCodec after end of stream", e); + mIsFlushedAfterEndOfStream = false; + } + notifyStopped(); + resetStoppedCodec(); + } + /** Resets the stopped codec, if needed, and transitions to {@link InternalState#CONFIGURED}. */ @ExecutedBy("mEncoderExecutor") private void resetStoppedCodec() { @@ -1165,7 +1215,11 @@ // Only reset if the codec is stopped (not flushed). If the codec is flushed, we // want it to continue to discard buffers. We will reset before starting the // codec again. - reset(); + try { + reset(); + } catch (IllegalStateException e) { + Logger.w(mTag, "Failed to reset MediaCodec in " + mState, e); + } } setState(CONFIGURED); } @@ -1302,21 +1356,46 @@ : toPresentationTimeUsByCaptureEncodeRatio(presentationTimeUs)); } }; - } catch (MediaCodec.CodecException e) { + } catch (IllegalStateException e) { + completer.setException(e); handleEncodeError(e); return; } - if (completer.set(inputBuffer)) { - mInputBufferSet.add(inputBuffer); - inputBuffer.getTerminationFuture().addListener( - () -> mInputBufferSet.remove(inputBuffer), mEncoderExecutor); - } else { + trackDispatchedBuffer(mInputBufferSet, inputBuffer, + inputBuffer.getTerminationFuture()); + if (!completer.set(inputBuffer)) { inputBuffer.cancel(); } } } @SuppressWarnings("WeakerAccess") // synthetic accessor + @ExecutedBy("mEncoderExecutor") + <T> void trackDispatchedBuffer(@NonNull Set<T> bufferSet, @NonNull T buffer, + @NonNull ListenableFuture<Void> completionFuture) { + bufferSet.add(buffer); + Futures.addCallback(completionFuture, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable Void result) { + bufferSet.remove(buffer); + } + + @Override + public void onFailure(@NonNull Throwable t) { + bufferSet.remove(buffer); + if (t instanceof CancellationException) { + return; + } + if (t instanceof IllegalStateException) { + handleEncodeError((IllegalStateException) t); + } else { + handleEncodeError(EncodeException.ERROR_UNKNOWN, t.getMessage(), t); + } + } + }, mEncoderExecutor); + } + + @SuppressWarnings("WeakerAccess") // synthetic accessor long generatePresentationTimeUs() { return mTimeProvider.uptimeUs(); } @@ -1502,21 +1581,23 @@ ); } mLastSentPresentationTimeUs = bufferInfo.presentationTimeUs; + final EncodedDataImpl encodedData; try { - EncodedDataImpl encodedData = new EncodedDataImpl(mediaCodec, index, - bufferInfo); - sendEncodedData(encodedData, encoderCallback, executor); - } catch (MediaCodec.CodecException e) { + encodedData = new EncodedDataImpl(mediaCodec, index, bufferInfo); + } catch (IllegalStateException e) { + handleEncodeError(e); + return; + } + sendEncodedData(encodedData, encoderCallback, executor); + } else if (!mStopped) { + try { + mMediaCodec.releaseOutputBuffer(index, false); + } catch (IllegalStateException e) { handleEncodeError(e); return; } } else { - try { - mMediaCodec.releaseOutputBuffer(index, false); - } catch (MediaCodec.CodecException e) { - handleEncodeError(e); - return; - } + return; } // Handle end of stream @@ -1560,36 +1641,13 @@ return; } mHasEndData = true; - if (mSignalEosTimeoutFuture != null) { - mSignalEosTimeoutFuture.cancel(false); - mSignalEosTimeoutFuture = null; - } stopMediaCodec(); } @ExecutedBy("mEncoderExecutor") private void sendEncodedData(@NonNull EncodedDataImpl encodedData, @NonNull EncoderCallback callback, @NonNull Executor executor) { - mEncodedDataSet.add(encodedData); - Futures.addCallback(encodedData.getClosedFuture(), - new FutureCallback<>() { - @Override - public void onSuccess(@Nullable Void result) { - mEncodedDataSet.remove(encodedData); - } - - @Override - public void onFailure(@NonNull Throwable t) { - mEncodedDataSet.remove(encodedData); - if (t instanceof MediaCodec.CodecException) { - handleEncodeError( - (MediaCodec.CodecException) t); - } else { - handleEncodeError(EncodeException.ERROR_UNKNOWN, - t.getMessage(), t); - } - } - }, mEncoderExecutor); + trackDispatchedBuffer(mEncodedDataSet, encodedData, encodedData.getClosedFuture()); try { executor.execute(() -> callback.onEncodedData(encodedData)); } catch (RejectedExecutionException e) { @@ -1676,7 +1734,11 @@ if (mIsKeyFrameRequired) { if (!isKeyFrame(bufferInfo)) { Logger.d(mTag, "Drop buffer by not a key frame."); - requestKeyFrameToMediaCodec(); + try { + requestKeyFrameToMediaCodec(); + } catch (IllegalStateException e) { + handleEncodeError(e); + } return false; } mIsKeyFrameRequired = false; @@ -1743,7 +1805,12 @@ if (mEncoderInput instanceof ByteBufferInput) { ((ByteBufferInput) mEncoderInput).setActive(false); } - setMediaCodecPaused(true); + try { + setMediaCodecPaused(true); + } catch (IllegalStateException e) { + handleEncodeError(e); + return true; + } } } @@ -1774,6 +1841,11 @@ @Override public void onError(@NonNull MediaCodec mediaCodec, MediaCodec.@NonNull CodecException e) { tryExecuteOnEncoderExecutor("onError", () -> { + if (this != mMediaCodecCallback) { + // Ignore stale error callbacks from a previous codec session after reset(). + Logger.w(mTag, "Receives onError after codec is reset."); + return; + } switch (mState) { case STARTED: case PAUSED:
diff --git a/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/InputBufferImpl.java b/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/InputBufferImpl.java index 5c8709e..ef8b70d 100644 --- a/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/InputBufferImpl.java +++ b/camera/camera-video/src/main/java/androidx/camera/video/internal/encoder/InputBufferImpl.java
@@ -43,7 +43,7 @@ private boolean mIsEndOfStream = false; InputBufferImpl(@NonNull MediaCodec mediaCodec, @IntRange(from = 0) int bufferIndex) - throws MediaCodec.CodecException { + throws IllegalStateException { mMediaCodec = Preconditions.checkNotNull(mediaCodec); mBufferIndex = Preconditions.checkArgumentNonnegative(bufferIndex); mByteBuffer = mediaCodec.getInputBuffer(bufferIndex);
diff --git a/camera/camera-video/src/test/java/androidx/camera/video/internal/encoder/EncoderImplTest.kt b/camera/camera-video/src/test/java/androidx/camera/video/internal/encoder/EncoderImplTest.kt index c5f50f3..9f45d3c 100644 --- a/camera/camera-video/src/test/java/androidx/camera/video/internal/encoder/EncoderImplTest.kt +++ b/camera/camera-video/src/test/java/androidx/camera/video/internal/encoder/EncoderImplTest.kt
@@ -16,28 +16,45 @@ package androidx.camera.video.internal.encoder +import android.graphics.SurfaceTexture +import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaFormat.MIMETYPE_AUDIO_AAC +import android.media.MediaFormat.MIMETYPE_VIDEO_AVC +import android.os.Bundle import android.os.Looper.getMainLooper +import android.util.Size +import android.view.Surface import androidx.camera.core.impl.Observable import androidx.camera.core.impl.Timebase import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.video.internal.BufferProvider import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage +import com.google.common.util.concurrent.ListenableFuture +import java.nio.ByteBuffer +import java.util.concurrent.CancellationException +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executor import java.util.concurrent.TimeUnit import org.junit.After +import org.junit.Assert.assertThrows import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.annotation.RealObject +import org.robolectric.shadow.api.Shadow import org.robolectric.shadows.MediaCodecInfoBuilder import org.robolectric.shadows.ShadowLog import org.robolectric.shadows.ShadowMediaCodec import org.robolectric.shadows.ShadowMediaCodecList +import org.robolectric.util.ReflectionHelpers.ClassParameter private const val SAMPLE_RATE = 44100 private const val CHANNEL_COUNT = 1 @@ -46,8 +63,8 @@ /** * Tests the state machine of [EncoderImpl] with a fake codec. * - * The tests use an audio encoder, since a video encoder requires a persistent input surface that is - * not available on the JVM. The state machine is shared by both. + * Most tests use an audio encoder, while surface-specific paths use + * [FaultInjectingShadowMediaCodec] to stub persistent input surface APIs on the JVM. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [Config.ALL_SDKS]) @@ -108,6 +125,7 @@ @After fun tearDown() { + FaultInjectingShadowMediaCodec.resetFlags() if (::encoder.isInitialized) { encoderCallback.heldData.forEach { it.close() } encoder.release() @@ -515,6 +533,1030 @@ assertThat(encoderCallback.errors).isEmpty() } + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun outputBufferIllegalStateException_notifiesEncodeErrorAndCanRestart() { + encoder.start() + FaultInjectingShadowMediaCodec.throwOnGetOutputBuffer = true + + feedInput(1) + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat(encoderCallback.errors.single().cause) + .isInstanceOf(IllegalStateException::class.java) + + FaultInjectingShadowMediaCodec.throwOnGetOutputBuffer = false + encoder.start() + feedInput(5) + assertThat(encoderCallback.encodedData).hasSize(5) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun droppedOutputBufferIllegalStateException_notifiesEncodeError() { + // Start in the future so output frames are dropped via releaseOutputBuffer(index, false). + encoder.start(Long.MAX_VALUE / 2) + FaultInjectingShadowMediaCodec.throwOnReleaseOutputBuffer = true + + feedInput(1) + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun encodedDataCloseIllegalStateException_notifiesEncodeError() { + val heldData = startAndHoldEncodedData() + FaultInjectingShadowMediaCodec.throwOnReleaseOutputBuffer = true + + heldData.close() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun inputBufferIllegalStateException_completesAcquisitionAndNotifiesSingleError() { + encoder.start() + idle() + val input = encoder.input as Encoder.ByteBufferInput + val (heldInputs, pendingAcquire) = drainAvailableInputBuffers(input) + FaultInjectingShadowMediaCodec.throwOnGetInputBuffer = true + + submitAndCancelRemaining(heldInputs) + + assertNoExceptionOnEncoderExecutor() + assertThat(pendingAcquire.isDone).isTrue() + val thrown = assertThrows(ExecutionException::class.java) { pendingAcquire.get() } + assertThat(thrown.cause).isInstanceOf(IllegalStateException::class.java) + assertThat(thrown.cause).isNotInstanceOf(CancellationException::class.java) + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun endOfStreamAcquisitionIllegalStateException_notifiesSingleError() { + encoder.start() + idle() + val input = encoder.input as Encoder.ByteBufferInput + val (heldInputs, pendingAcquire) = drainAvailableInputBuffers(input) + pendingAcquire.cancel(true) + encoder.stop() + idle(1_000L) + FaultInjectingShadowMediaCodec.throwOnGetInputBuffer = true + + submitAndCancelRemaining(heldInputs) + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun syncEndOfStreamAcquisitionIllegalStateException_notifiesSingleError() { + encoder.start() + idle() + encoder.stop() + FaultInjectingShadowMediaCodec.throwOnGetInputBuffer = true + + // Stop timeout invokes signalCodecStop() -> signalEndOfInputStream() while a free input + // buffer index is already queued and no EncodedData is outstanding. + idle(1_000L) + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun queueInputBufferAndStartIllegalStateException_notifyEncodeErrorAndDeactivateInput() { + encoder.start() + val input = encoder.input as Encoder.ByteBufferInput + val inputBuffer = input.acquireBuffer().apply { idle() }.get(0, TimeUnit.MILLISECONDS) + FaultInjectingShadowMediaCodec.throwOnQueueInputBuffer = true + + inputBuffer.byteBuffer.put(ByteArray(BUFFER_SIZE / 2)).flip() + inputBuffer.submit() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat(input.fetchData().get(0, TimeUnit.MILLISECONDS)) + .isEqualTo(BufferProvider.State.INACTIVE) + + FaultInjectingShadowMediaCodec.throwOnQueueInputBuffer = false + FaultInjectingShadowMediaCodec.throwOnStart = true + encoder.start() + idle() + + assertThat(encoderCallback.errors).hasSize(2) + assertThat(encoderCallback.errors.last().errorType).isEqualTo(EncodeException.ERROR_CODEC) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun resumeAndRequestKeyFrameSetParametersIllegalStateException_notifyEncodeError() { + encoder.start() + feedInput(5) + encoder.pause() + feedInputUntil { encoderCallback.pauseCount > 0 } + FaultInjectingShadowMediaCodec.throwOnSetParameters = true + + encoder.start() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat( + (encoder.input as Encoder.ByteBufferInput).fetchData().get(0, TimeUnit.MILLISECONDS) + ) + .isEqualTo(BufferProvider.State.INACTIVE) + + FaultInjectingShadowMediaCodec.throwOnSetParameters = false + encoder.start() + FaultInjectingShadowMediaCodec.throwOnSetParameters = true + encoder.requestKeyFrame() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(2) + assertThat(encoderCallback.errors.last().errorType).isEqualTo(EncodeException.ERROR_CODEC) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun pauseSetParametersIllegalStateExceptionInCheckBufferInfo_skipsReleaseOutputBuffer() { + encoder.start() + feedInput(1) + encoder.pause() + FaultInjectingShadowMediaCodec.throwOnSetParameters = true + FaultInjectingShadowMediaCodec.throwOnReleaseOutputBuffer = true + + feedInput(1) + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat( + ShadowLog.getLogsForTag("AudioEncoder").none { + it.msg.contains("Get more than one error") + } + ) + .isTrue() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun stopMediaCodecIllegalStateExceptionInHandleStopped_notifiesStopAndResets() { + encoder.start() + feedInput(5) + encoder.stop() + FaultInjectingShadowMediaCodec.throwOnStop = true + + feedInputUntil { encoderCallback.stopCount > 0 } + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.stopCount).isEqualTo(1) + assertThat(encoderCallback.errors).isEmpty() + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + FaultInjectingShadowMediaCodec.throwOnStop = false + encoderCallback.encodedData.clear() + encoder.start() + feedInput(5) + assertThat(encoderCallback.encodedData).isNotEmpty() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun flushedVideoEncoderStopAndFlushIllegalStateException_recoverAndCompleteRelease() = + withVideoEncoder { videoEncoder, videoCallback -> + // Flush failure during handleStopped() still notifies stop and resets to CONFIGURED. + videoEncoder.start() + FaultInjectingShadowMediaCodec.throwOnFlush = true + videoEncoder.stop() + idle(1_000L) + + assertNoExceptionOnEncoderExecutor() + assertThat(videoCallback.stopCount).isEqualTo(1) + assertThat(videoCallback.errors).isEmpty() + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + // Successful stop leaves SurfaceInput codec flushed; stop() ISE on + // signalSourceStopped() still runs reset(), and stop() ISE on release() still + // completes releasedFuture. + FaultInjectingShadowMediaCodec.throwOnFlush = false + videoEncoder.start() + videoEncoder.stop() + idle(1_000L) + assertThat(videoCallback.stopCount).isEqualTo(2) + + FaultInjectingShadowMediaCodec.throwOnStop = true + videoEncoder.signalSourceStopped() + idle() + assertNoExceptionOnEncoderExecutor() + + FaultInjectingShadowMediaCodec.throwOnStop = false + videoEncoder.start() + videoEncoder.stop() + idle(1_000L) + assertThat(videoCallback.stopCount).isEqualTo(3) + + FaultInjectingShadowMediaCodec.throwOnStop = true + videoEncoder.release() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(videoEncoder.releasedFuture.isDone).isTrue() + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.RELEASED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun videoNonKeyFrameRequestKeyFrameIllegalStateException_skipsReleaseOutputBuffer() = + withVideoEncoder { videoEncoder, videoCallback -> + videoEncoder.start() + + FaultInjectingShadowMediaCodec.throwOnSetParameters = true + FaultInjectingShadowMediaCodec.throwOnReleaseOutputBuffer = true + val shadowCodec = + Shadow.extract<FaultInjectingShadowMediaCodec>(videoEncoder.mMediaCodec) + shadowCodec.emitOutputBuffer( + index = 1, + size = 16, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 1_000L, + flags = 0, + ) + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(videoCallback.errors).hasSize(1) + assertThat(videoCallback.errors.single().errorType) + .isEqualTo(EncodeException.ERROR_CODEC) + assertThat( + ShadowLog.getLogsForTag("VideoEncoder").none { + it.msg.contains("Get more than one error") + } + ) + .isTrue() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun videoStartResumeInputSurfaceSetParametersIllegalStateException_notifiesErrorAndResets() = + withVideoEncoder { videoEncoder, videoCallback -> + FaultInjectingShadowMediaCodec.throwOnSetParameters = true + + videoEncoder.start() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(videoCallback.errors).hasSize(1) + assertThat(videoCallback.errors.single().errorType) + .isEqualTo(EncodeException.ERROR_CODEC) + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + FaultInjectingShadowMediaCodec.throwOnSetParameters = false + videoEncoder.start() + idle() + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.STARTED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun constructorResetIllegalStateException_throwsInvalidConfigExceptionAndReleasesResources() { + // 1. Fail in reset() before Surface allocation -> MediaCodec is still released. + FaultInjectingShadowMediaCodec.throwOnReset = true + assertThrows(InvalidConfigException::class.java) { createVideoEncoder() } + assertThat(FaultInjectingShadowMediaCodec.releaseCount).isEqualTo(1) + + // 2. Fail in setInputSurface() after persistent Surface allocation -> both released, and + // any async onError arriving on the registered callback does not throw on null mState. + FaultInjectingShadowMediaCodec.resetFlags() + FaultInjectingShadowMediaCodec.throwOnSetInputSurface = true + assertThrows(InvalidConfigException::class.java) { createVideoEncoder() } + assertThat(FaultInjectingShadowMediaCodec.releaseCount).isEqualTo(1) + assertThat(FaultInjectingShadowMediaCodec.lastCreatedPersistentSurface?.isValid).isFalse() + val failedShadow = FaultInjectingShadowMediaCodec.lastCreatedShadow + assertThat(failedShadow).isNotNull() + failedShadow!!.emitErrorTo(failedShadow.capturedCallback) + idle() + assertNoExceptionOnEncoderExecutor() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun startAndResetIllegalStateException_staysConfiguredAndRecoversOnRetry() { + FaultInjectingShadowMediaCodec.throwOnStart = true + FaultInjectingShadowMediaCodec.throwOnReset = true + encoder.start() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + // Next start() while still broken reports a fresh ERROR_CODEC (never hangs). + encoder.start() + idle() + assertThat(encoderCallback.errors).hasSize(2) + + // Once transient fault clears, start() re-runs reset() and encodes normally. + FaultInjectingShadowMediaCodec.resetFlags() + encoderCallback.encodedData.clear() + encoder.start() + feedInput(5) + assertThat(encoderCallback.encodedData).isNotEmpty() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun errorAndResetIllegalStateException_skipsPreReleaseStartAndCompletesRelease() = + withVideoEncoder { videoEncoder, videoCallback -> + videoEncoder.start() + FaultInjectingShadowMediaCodec.throwOnSetParameters = true + FaultInjectingShadowMediaCodec.throwOnReset = true + + videoEncoder.requestKeyFrame() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(videoCallback.errors).hasSize(1) + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + videoEncoder.start() + idle() + assertThat(videoCallback.errors).hasSize(2) + + val startCountBeforeRelease = FaultInjectingShadowMediaCodec.startCount + videoEncoder.release() + idle() + assertThat(videoEncoder.releasedFuture.isDone).isTrue() + assertThat(FaultInjectingShadowMediaCodec.startCount).isEqualTo(startCountBeforeRelease) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun resetIllegalStateExceptionAfterStop_recoversOnRestartAndDeactivatesInputOnRelease() { + encoder.start() + feedInput(5) + FaultInjectingShadowMediaCodec.throwOnReset = true + encoder.stop() + feedInputUntil { encoderCallback.stopCount == 1 } + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + assertThat( + (encoder.input as Encoder.ByteBufferInput).fetchData().get(0, TimeUnit.MILLISECONDS) + ) + .isEqualTo(BufferProvider.State.INACTIVE) + + FaultInjectingShadowMediaCodec.throwOnReset = false + encoderCallback.encodedData.clear() + encoder.start() + feedInput(5) + assertThat(encoderCallback.encodedData).isNotEmpty() + + // STOPPING -> release() (PENDING_RELEASE) -> spontaneous EOS -> ByteBufferInput becomes + // INACTIVE on RELEASED. + encoder.stop() + encoder.release() + val shadowCodec = Shadow.extract<FaultInjectingShadowMediaCodec>(encoder.mMediaCodec) + shadowCodec.emitOutputBuffer( + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 10_000L, + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + idle() + assertThat(encoder.releasedFuture.isDone).isTrue() + assertThat( + (encoder.input as Encoder.ByteBufferInput).fetchData().get(0, TimeUnit.MILLISECONDS) + ) + .isEqualTo(BufferProvider.State.INACTIVE) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun pendingStartResetIllegalStateException_notifiesErrorAndRecoversOnRetry() { + encoder.start() + feedInput(5) + encoder.stop() + encoder.start() // Transitions STOPPING -> PENDING_START + FaultInjectingShadowMediaCodec.throwOnReset = true + feedInputUntil { encoderCallback.errors.isNotEmpty() } + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.stopCount).isEqualTo(1) + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + FaultInjectingShadowMediaCodec.throwOnReset = false + encoderCallback.encodedData.clear() + encoder.start() + feedInput(5) + assertThat(encoderCallback.encodedData).isNotEmpty() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun pendingStartStopIllegalStateException_notifiesStopAndStartsNextSession() { + encoder.start() + feedInput(5) + encoder.stop() + encoder.start() // Transitions STOPPING -> PENDING_START + FaultInjectingShadowMediaCodec.throwOnStop = true + feedInputUntil { encoderCallback.stopCount == 1 } + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.stopCount).isEqualTo(1) + assertThat(encoderCallback.errors).isEmpty() + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.STARTED) + + FaultInjectingShadowMediaCodec.throwOnStop = false + encoderCallback.encodedData.clear() + feedInput(5) + assertThat(encoderCallback.encodedData).isNotEmpty() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun unexpectedEndOfStream_stopsDispatchingBuffersImmediatelyAndWaitsForPreEosBuffer() { + encoder.start() + idle() + val input = encoder.input as Encoder.ByteBufferInput + val preEosInputBuffer = input.acquireBuffer().apply { idle() }.get(0, TimeUnit.MILLISECONDS) + val shadowCodec = Shadow.extract<FaultInjectingShadowMediaCodec>(encoder.mMediaCodec) + + // Spontaneous EOS triggers reachEndData() -> stopMediaCodec(), which must immediately + // stop dispatching new buffers while still waiting on preEosInputBuffer. + shadowCodec.emitOutputBuffer( + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 10_000L, + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + idle() + + assertThat(input.fetchData().get(0, TimeUnit.MILLISECONDS)) + .isEqualTo(BufferProvider.State.INACTIVE) + val postEosAcquire = input.acquireBuffer().apply { idle() } + val thrown = assertThrows(ExecutionException::class.java) { postEosAcquire.get() } + assertThat(thrown.cause).isInstanceOf(IllegalStateException::class.java) + assertThat(encoderCallback.stopCount).isEqualTo(0) + + FaultInjectingShadowMediaCodec.throwOnQueueInputBuffer = true + preEosInputBuffer.cancel() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.stopCount).isEqualTo(0) + assertThat(encoderCallback.errors).hasSize(1) + assertThat(encoderCallback.errors.single().errorType).isEqualTo(EncodeException.ERROR_CODEC) + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + FaultInjectingShadowMediaCodec.throwOnQueueInputBuffer = false + encoderCallback.encodedData.clear() + encoder.start() + feedInput(5) + assertThat(encoderCallback.encodedData).isNotEmpty() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun unexpectedEndOfStreamDuringVideoStop_cancelsStopTimeoutAndIgnoresLateOnError() = + withVideoEncoder { videoEncoder, videoCallback -> + videoEncoder.start() + videoEncoder.stop() + val shadowCodec = + Shadow.extract<FaultInjectingShadowMediaCodec>(videoEncoder.mMediaCodec) + val oldCallback = shadowCodec.capturedCallback + + shadowCodec.emitOutputBuffer( + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 10_000L, + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + idle() + + assertThat(videoCallback.stopCount).isEqualTo(1) + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + // Advancing past STOP_TIMEOUT_MS must not fire signalCodecStop() on the flushed codec. + idle(1_000L) + assertThat(videoCallback.errors).isEmpty() + + // A late onError from the previous MediaCodecCallback must be ignored after restart. + videoEncoder.start() + idle() + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.STARTED) + shadowCodec.emitErrorTo(oldCallback) + idle() + assertThat(videoCallback.errors).isEmpty() + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.STARTED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun resumeWhileStoppingAfterUnexpectedEos_stopsWithoutRestarting() { + encoder.start() + idle() + val input = encoder.input as Encoder.ByteBufferInput + val held = input.acquireBuffer().apply { idle() }.get(0, TimeUnit.MILLISECONDS) + encoder.pause() + idle() + + Shadow.extract<FaultInjectingShadowMediaCodec>(encoder.mMediaCodec) + .emitOutputBuffer( + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 10_000L, + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + idle() + + // Resuming during an unexpected-EOS stop must not restart on the old callback. + encoder.start() + idle() + held.cancel() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.stopCount).isEqualTo(1) + assertThat(encoderCallback.errors).isEmpty() + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun stopWhileStoppingAfterUnexpectedEos_cancelsTimeoutAndStopsOnce() { + encoder.start() + idle() + val input = encoder.input as Encoder.ByteBufferInput + val held = input.acquireBuffer().apply { idle() }.get(0, TimeUnit.MILLISECONDS) + + Shadow.extract<FaultInjectingShadowMediaCodec>(encoder.mMediaCodec) + .emitOutputBuffer( + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 10_000L, + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + idle() + + // Calling stop() during an unexpected-EOS stop must not arm a new stop timeout. + encoder.stop() + idle(1_000L) + held.cancel() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.stopCount).isEqualTo(1) + assertThat(encoderCallback.errors).isEmpty() + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun pauseWhileStoppingAfterUnexpectedEos_doesNotLeaveStalePauseRange() { + encoder.start() + idle() + val input = encoder.input as Encoder.ByteBufferInput + val held = input.acquireBuffer().apply { idle() }.get(0, TimeUnit.MILLISECONDS) + + Shadow.extract<FaultInjectingShadowMediaCodec>(encoder.mMediaCodec) + .emitOutputBuffer( + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 10_000L, + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + idle() + + // Pausing during an unexpected-EOS stop must be a no-op rather than adding a pause range. + encoder.pause() + idle() + assertThat(encoder.mActivePauseResumeTimeRanges).isEmpty() + + held.cancel() + idle() + assertThat(encoderCallback.stopCount).isEqualTo(1) + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun requestKeyFrameWhileStoppingAfterUnexpectedEos_isIgnoredAndStopsOnce() { + encoder.start() + idle() + val input = encoder.input as Encoder.ByteBufferInput + val held = input.acquireBuffer().apply { idle() }.get(0, TimeUnit.MILLISECONDS) + + Shadow.extract<FaultInjectingShadowMediaCodec>(encoder.mMediaCodec) + .emitOutputBuffer( + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()) + 10_000L, + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + idle() + + // Requesting a key frame during an unexpected-EOS stop must be a no-op rather than + // calling setParameters() on a stopping codec and turning stop into an error. + FaultInjectingShadowMediaCodec.throwOnSetParameters = true + encoder.requestKeyFrame() + idle() + held.cancel() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(encoderCallback.stopCount).isEqualTo(1) + assertThat(encoderCallback.errors).isEmpty() + assertThat(encoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun videoSignalEndOfInputStreamAndReleaseExceptions_notifyErrorAndCompleteRelease() = + withVideoEncoder { videoEncoder, videoCallback -> + videoEncoder.start() + videoEncoder.stop() + FaultInjectingShadowMediaCodec.throwOnSignalEndOfInputStream = true + idle(1_000L) + + assertNoExceptionOnEncoderExecutor() + assertThat(videoCallback.errors).hasSize(1) + assertThat(videoCallback.errors.single().errorType) + .isEqualTo(EncodeException.ERROR_CODEC) + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + + FaultInjectingShadowMediaCodec.throwOnSignalEndOfInputStream = false + FaultInjectingShadowMediaCodec.throwOnRelease = true + videoEncoder.release() + idle() + + assertNoExceptionOnEncoderExecutor() + assertThat(FaultInjectingShadowMediaCodec.lastCreatedPersistentSurface?.isValid) + .isFalse() + assertThat(videoEncoder.mState).isEqualTo(EncoderImpl.InternalState.RELEASED) + assertThat(videoEncoder.releasedFuture.isDone).isTrue() + } + + @Test + @Config(sdk = [Config.TARGET_SDK], shadows = [FaultInjectingShadowMediaCodec::class]) + fun cancelledAcquisitionCancelIllegalStateException_notifiesEncodeErrorDuringStopping() { + val tasks = ArrayDeque<Runnable>() + val queuedExecutor = Executor { tasks.addLast(it) } + fun drainTasks() { + while (tasks.isNotEmpty()) { + tasks.removeFirst().run() + } + } + val queuedCallback = FakeEncoderCallback() + val queuedEncoder = + EncoderImpl( + queuedExecutor, + AudioEncoderConfig.builder() + .setMimeType(MIMETYPE_AUDIO_AAC) + .setProfile(MediaCodecInfo.CodecProfileLevel.AACObjectLC) + .setInputTimebase(Timebase.UPTIME) + .setBitrate(64000) + .setCaptureSampleRate(SAMPLE_RATE) + .setEncodeSampleRate(SAMPLE_RATE) + .setChannelCount(CHANNEL_COUNT) + .build(), + ) + try { + queuedEncoder.setEncoderCallback(queuedCallback, CameraXExecutors.directExecutor()) + queuedEncoder.start() + drainTasks() + idle() + drainTasks() + + val input = queuedEncoder.input as Encoder.ByteBufferInput + val heldInputs = mutableListOf<InputBuffer>() + lateinit var pendingAcquire: ListenableFuture<InputBuffer> + while (true) { + val future = input.acquireBuffer() + drainTasks() + idle() + drainTasks() + if (future.isDone) { + heldInputs.add(future.get(0, TimeUnit.MILLISECONDS)) + } else { + pendingAcquire = future + break + } + } + + queuedEncoder.stop() + drainTasks() + + // Submitting one buffer schedules onOutputBufferAvailable; running that task releases + // the output buffer so the next idle() queues onInputBufferAvailable before + // pendingAcquire.cancel(true) queues mAcquisitionQueue.remove(completer). + heldInputs.first().apply { + byteBuffer.put(ByteArray(BUFFER_SIZE / 2)).flip() + setPresentationTimeUs(TimeUnit.NANOSECONDS.toMicros(System.nanoTime())) + submit() + } + idle() + tasks.removeFirst().run() + idle() + pendingAcquire.cancel(true) + FaultInjectingShadowMediaCodec.throwOnQueueInputBuffer = true + drainTasks() + heldInputs.drop(1).forEach { it.cancel() } + drainTasks() + + assertNoExceptionOnEncoderExecutor() + assertThat(queuedCallback.errors).hasSize(1) + assertThat(queuedCallback.errors.single().errorType) + .isEqualTo(EncodeException.ERROR_CODEC) + assertThat(queuedEncoder.mState).isEqualTo(EncoderImpl.InternalState.CONFIGURED) + } finally { + FaultInjectingShadowMediaCodec.resetFlags() + queuedEncoder.release() + drainTasks() + } + } + + private fun drainAvailableInputBuffers( + input: Encoder.ByteBufferInput + ): Pair<List<InputBuffer>, ListenableFuture<InputBuffer>> { + val heldInputs = mutableListOf<InputBuffer>() + while (true) { + val future = input.acquireBuffer() + idle() + if (future.isDone) { + heldInputs.add(future.get(0, TimeUnit.MILLISECONDS)) + } else { + return heldInputs to future + } + } + } + + private fun submitAndCancelRemaining(heldInputs: List<InputBuffer>) { + heldInputs.first().apply { + byteBuffer.put(ByteArray(BUFFER_SIZE / 2)).flip() + setPresentationTimeUs(TimeUnit.NANOSECONDS.toMicros(System.nanoTime())) + submit() + } + heldInputs.drop(1).forEach { it.cancel() } + idle() + } + + private fun withVideoEncoder(block: (EncoderImpl, FakeEncoderCallback) -> Unit) { + val videoEncoder = createVideoEncoder() + try { + val videoCallback = FakeEncoderCallback() + videoEncoder.setEncoderCallback(videoCallback, CameraXExecutors.directExecutor()) + block(videoEncoder, videoCallback) + } finally { + FaultInjectingShadowMediaCodec.resetFlags() + videoEncoder.release() + idle() + } + } + + private fun createVideoEncoder(): EncoderImpl { + ShadowMediaCodecList.reset() + ShadowMediaCodecList.addCodec( + MediaCodecInfoBuilder.newBuilder() + .setName("fake.avc.encoder") + .setIsEncoder(true) + .setCapabilities( + MediaCodecInfoBuilder.CodecCapabilitiesBuilder.newBuilder() + .setMediaFormat(MediaFormat.createVideoFormat(MIMETYPE_VIDEO_AVC, 640, 480)) + .setIsEncoder(true) + .setColorFormats( + intArrayOf(MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface) + ) + .build() + ) + .build() + ) + return EncoderImpl( + CameraXExecutors.directExecutor(), + VideoEncoderConfig.builder() + .setMimeType(MIMETYPE_VIDEO_AVC) + .setInputTimebase(Timebase.UPTIME) + .setResolution(Size(640, 480)) + .setColorFormat(MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface) + .setDataSpace(VideoEncoderDataSpace.ENCODER_DATA_SPACE_UNSPECIFIED) + .setCaptureFrameRate(30) + .setEncodeFrameRate(30) + .setIFrameInterval(1) + .setBitrate(1_000_000) + .build(), + ) + } + + @Implements(MediaCodec::class) + class FaultInjectingShadowMediaCodec : ShadowMediaCodec() { + @RealObject private lateinit var realMediaCodec: MediaCodec + var capturedCallback: MediaCodec.Callback? = null + + companion object { + var throwOnGetInputBuffer = false + var throwOnGetOutputBuffer = false + var throwOnReleaseOutputBuffer = false + var throwOnQueueInputBuffer = false + var throwOnStart = false + var throwOnStop = false + var throwOnFlush = false + var throwOnSetParameters = false + var throwOnReset = false + var throwOnSetInputSurface = false + var throwOnSignalEndOfInputStream = false + var throwOnRelease = false + var startCount = 0 + var releaseCount = 0 + var lastCreatedShadow: FaultInjectingShadowMediaCodec? = null + var lastCreatedPersistentSurface: Surface? = null + private var lastCreatedSurfaceTexture: SurfaceTexture? = null + + fun resetFlags() { + throwOnGetInputBuffer = false + throwOnGetOutputBuffer = false + throwOnReleaseOutputBuffer = false + throwOnQueueInputBuffer = false + throwOnStart = false + throwOnStop = false + throwOnFlush = false + throwOnSetParameters = false + throwOnReset = false + throwOnSetInputSurface = false + throwOnSignalEndOfInputStream = false + throwOnRelease = false + startCount = 0 + releaseCount = 0 + lastCreatedShadow = null + lastCreatedPersistentSurface = null + lastCreatedSurfaceTexture?.release() + lastCreatedSurfaceTexture = null + } + + @Implementation + @JvmStatic + fun createPersistentInputSurface(): Surface = + Surface(SurfaceTexture(0).also { lastCreatedSurfaceTexture = it }).also { + lastCreatedPersistentSurface = it + } + } + + @Implementation + public override fun native_setCallback(callback: MediaCodec.Callback?) { + this.capturedCallback = callback + lastCreatedShadow = this + super.native_setCallback(callback) + } + + @Implementation + public fun setInputSurface(surface: Surface) { + if (throwOnSetInputSurface) { + throw IllegalStateException("Simulated setInputSurface IllegalStateException") + } + } + + @Implementation + public fun release() { + releaseCount++ + if (throwOnRelease) { + throw IllegalStateException("Simulated release IllegalStateException") + } + Shadow.directlyOn<Any?, MediaCodec>(realMediaCodec, MediaCodec::class.java, "release") + } + + @Implementation + public fun signalEndOfInputStream() { + if (throwOnSignalEndOfInputStream) { + throw IllegalStateException( + "Simulated signalEndOfInputStream IllegalStateException" + ) + } + emitOutputBuffer( + // Buffer index 0 is already queued by ShadowMediaCodec.native_start(), so use 1 + // to avoid ShadowMediaCodec.releaseOutputBuffer throwing on double-queue. + index = 1, + size = 0, + presentationTimeUs = TimeUnit.NANOSECONDS.toMicros(System.nanoTime()), + flags = MediaCodec.BUFFER_FLAG_END_OF_STREAM, + ) + } + + fun emitOutputBuffer(index: Int, size: Int, presentationTimeUs: Long, flags: Int) { + capturedCallback?.onOutputBufferAvailable( + realMediaCodec, + index, + MediaCodec.BufferInfo().apply { set(0, size, presentationTimeUs, flags) }, + ) + } + + fun emitErrorTo(targetCallback: MediaCodec.Callback?) { + targetCallback?.onError( + realMediaCodec, + Shadow.newInstanceOf(MediaCodec.CodecException::class.java), + ) + } + + @Implementation + public override fun getBuffer(input: Boolean, index: Int): ByteBuffer? { + if ((input && throwOnGetInputBuffer) || (!input && throwOnGetOutputBuffer)) { + throw IllegalStateException("Simulated MediaCodec.getBuffer IllegalStateException") + } + return super.getBuffer(input, index) + } + + @Implementation + public override fun releaseOutputBuffer(index: Int, render: Boolean) { + if (throwOnReleaseOutputBuffer) { + throw IllegalStateException("Simulated releaseOutputBuffer IllegalStateException") + } + super.releaseOutputBuffer(index, render) + } + + @Implementation + public override fun native_queueInputBuffer( + index: Int, + offset: Int, + size: Int, + presentationTimeUs: Long, + flags: Int, + ) { + if (throwOnQueueInputBuffer) { + throw IllegalStateException("Simulated queueInputBuffer IllegalStateException") + } + super.native_queueInputBuffer(index, offset, size, presentationTimeUs, flags) + } + + @Implementation + public override fun native_start() { + startCount++ + if (throwOnStart) { + throw IllegalStateException("Simulated start IllegalStateException") + } + super.native_start() + } + + @Implementation + public fun stop() { + if (throwOnStop) { + throw IllegalStateException("Simulated stop IllegalStateException") + } + Shadow.directlyOn<Any?, MediaCodec>(realMediaCodec, MediaCodec::class.java, "stop") + } + + @Implementation + public override fun native_flush() { + if (throwOnFlush) { + throw IllegalStateException("Simulated flush IllegalStateException") + } + super.native_flush() + } + + @Implementation + public fun reset() { + if (throwOnReset) { + throw IllegalStateException("Simulated reset IllegalStateException") + } + Shadow.directlyOn<Any?, MediaCodec>(realMediaCodec, MediaCodec::class.java, "reset") + } + + @Implementation + public fun setParameters(params: Bundle?) { + if (throwOnSetParameters) { + throw IllegalStateException("Simulated setParameters IllegalStateException") + } + Shadow.directlyOn<Any?, MediaCodec>( + realMediaCodec, + MediaCodec::class.java, + "setParameters", + ClassParameter.from(Bundle::class.java, params), + ) + } + } + /** * Starts the encoder and holds the first encoded data without closing it. *
diff --git a/camera/camera-view/src/androidTest/java/androidx/camera/view/VideoCaptureDeviceTest.kt b/camera/camera-view/src/androidTest/java/androidx/camera/view/VideoCaptureDeviceTest.kt index 2c47761..110e7c2 100644 --- a/camera/camera-view/src/androidTest/java/androidx/camera/view/VideoCaptureDeviceTest.kt +++ b/camera/camera-view/src/androidTest/java/androidx/camera/view/VideoCaptureDeviceTest.kt
@@ -70,7 +70,7 @@ import org.junit.Assume import org.junit.Assume.assumeTrue import org.junit.Before -import org.junit.BeforeClass +import org.junit.ClassRule import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -128,11 +128,11 @@ private const val VIDEO_SAVED_COUNT_DOWN = 1 private const val TAG = "VideoCaptureDeviceTest" - @JvmStatic - @BeforeClass - fun classSetUp() { - RequireForegroundRule.prepareDeviceUI(InstrumentationRegistry.getInstrumentation()) - } + // Class-scoped so natural orientation is locked once across all parameterized cases + // without per-test UI prep overhead. + @ClassRule + @JvmField + val requireForegroundRule: RequireForegroundRule = RequireForegroundRule() @JvmStatic @Parameterized.Parameters(name = "initialQuality={0}, nextQuality={1}, lensFacing={3}") @@ -151,8 +151,7 @@ } } } else { - // Return empty list since prepareDeviceUI will skip the test if not in the CameraX - // lab environment. + // Return empty list if not in the CameraX lab environment. emptyList() } }
diff --git a/camera/integration-tests/coretestapp/src/androidTest/java/androidx/camera/integration/core/UseCaseCombinationTest.kt b/camera/integration-tests/coretestapp/src/androidTest/java/androidx/camera/integration/core/UseCaseCombinationTest.kt index 5f73b6d..71c7e39 100644 --- a/camera/integration-tests/coretestapp/src/androidTest/java/androidx/camera/integration/core/UseCaseCombinationTest.kt +++ b/camera/integration-tests/coretestapp/src/androidTest/java/androidx/camera/integration/core/UseCaseCombinationTest.kt
@@ -135,7 +135,9 @@ companion object { private const val FRAME_TIMEOUT_MS = 5000L + private const val REOPEN_FRAME_TIMEOUT_MS = 15_000L private const val NO_FRAME_TIMEOUT_MS = 1000L + private const val STREAM_IDLE_WINDOW_MS = 2000L // Preview frames to wait for after a mode switch, so that the frames of the previous // repeating request that were still in flight are delivered. private const val DRAIN_FRAME_COUNT = 10 @@ -1117,10 +1119,10 @@ assertThat(stoppedException.cause) .isInstanceOf(androidx.camera.core.CameraControl.OperationCanceledException::class.java) instrumentation.runOnMainSync { fakeLifecycleOwner.startAndResume() } - assertWithMessage("ImageAnalysis received no frames after ON_STOP -> ON_START") - .that(analyzer.awaitFrames(count = 10)) + assertWithMessage("ImageAnalysis did not receive 10 frames after ON_STOP -> ON_START") + .that(analyzer.awaitFrames(count = 10, timeoutMs = REOPEN_FRAME_TIMEOUT_MS)) .isTrue() - previewMonitor.waitForStream() + previewMonitor.waitForStream(timeMillis = REOPEN_FRAME_TIMEOUT_MS) // After unbindAll(), setEnabledUseCasesAsync fails with IllegalStateException. instrumentation.runOnMainSync { cameraProvider.unbindAll() } @@ -1729,47 +1731,49 @@ class PreviewMonitor { private var countDown: CountDownLatch? = null private val surfaceProvider = createAutoDrainingSurfaceTextureProvider { - countDown?.countDown() + synchronized(this) { countDown?.countDown() } } fun getSurfaceProvider(): Preview.SurfaceProvider = surfaceProvider - fun waitForStream(count: Int = 10, timeMillis: Long = TimeUnit.SECONDS.toMillis(5)) { + fun waitForStream(count: Int = 10, timeMillis: Long = FRAME_TIMEOUT_MS) { Truth.assertWithMessage("Preview doesn't start") - .that( - synchronized(this) { - countDown = CountDownLatch(count) - countDown - }!! - .await(timeMillis, TimeUnit.MILLISECONDS) - ) + .that(waitForCaptureResultReceived(count = count, timeMillis = timeMillis)) .isTrue() } fun assertNoResultReceived() = Truth.assertWithMessage("There is still some capture results received unexpectedly.") - .that(waitForCaptureResultReceived(/* count= */ 1, /* timeSeconds= */ 2)) + .that(waitForCaptureResultReceived(count = 1, timeMillis = STREAM_IDLE_WINDOW_MS)) .isFalse() - fun waitForStreamIdle() { - // Monitor 2 seconds to confirm that less than 10 capture results are received. (It - // might take some time to stop the preview) - Truth.assertWithMessage( - "There are still more than 10 capture results received in the" + - " recent 2 seconds." - ) - .that(waitForCaptureResultReceived()) - .isFalse() - // Monitor 2 seconds to confirm that no any capture result can be received. - assertNoResultReceived() + /** + * Drains in-flight preview frames after unbind up to [drainTimeoutMs], then confirms no + * further frame arrives during a continuous [idleWindowMs] quiet window. + */ + fun waitForStreamIdle( + drainTimeoutMs: Long = FRAME_TIMEOUT_MS, + idleWindowMs: Long = STREAM_IDLE_WINDOW_MS, + ) { + val drainDeadlineNs = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(drainTimeoutMs) + var drainWakeups = 0 + while (waitForCaptureResultReceived(count = 1, timeMillis = idleWindowMs)) { + drainWakeups++ + Truth.assertWithMessage( + "Preview stream did not become idle within ${drainTimeoutMs}ms " + + "(drainWakeups=$drainWakeups)." + ) + .that(System.nanoTime() < drainDeadlineNs) + .isTrue() + } } - private fun waitForCaptureResultReceived(count: Int = 10, timeSeconds: Long = 2) = - synchronized(this) { - countDown = CountDownLatch(count) - countDown - }!! - .await(timeSeconds, TimeUnit.SECONDS) + private fun waitForCaptureResultReceived( + count: Int = 10, + timeMillis: Long = STREAM_IDLE_WINDOW_MS, + ) = + synchronized(this) { CountDownLatch(count).also { countDown = it } } + .await(timeMillis, TimeUnit.MILLISECONDS) } class AnalysisMonitor : ImageAnalysis.Analyzer {
diff --git a/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderScreenshotTest.kt b/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderScreenshotTest.kt index 5c03c21..43cf600 100644 --- a/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderScreenshotTest.kt +++ b/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderScreenshotTest.kt
@@ -16,6 +16,7 @@ package androidx.camera.viewfinder.compose +import androidx.camera.testing.impl.RequireForegroundRule import androidx.camera.viewfinder.core.ImplementationMode import androidx.camera.viewfinder.core.TransformationInfo import androidx.camera.viewfinder.core.TransformationMode @@ -36,12 +37,14 @@ @RunWith(AndroidJUnit4::class) class ViewfinderScreenshotTest { - // Evaluate screenshotRule before composeTestRule so non-supported devices skip without - // launching ComponentActivity. + // Evaluate screenshotRule before requireForegroundRule and composeTestRule so non-supported + // devices skip without UI preparation or launching ComponentActivity. @get:Rule(order = 0) val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_CAMERA_VIEWFINDER_COMPOSE) - @get:Rule(order = 1) val composeTestRule = createComposeRule() + @get:Rule(order = 1) val requireForegroundRule = RequireForegroundRule() + + @get:Rule(order = 2) val composeTestRule = createComposeRule() @Test fun embeddedImplementationDrawsUpright_from0DegreeSource() = runBlocking {
diff --git a/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderTransformsScreenshotTest.kt b/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderTransformsScreenshotTest.kt index 2a62c9d..92b1ad3 100644 --- a/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderTransformsScreenshotTest.kt +++ b/camera/viewfinder/viewfinder-compose/src/androidTest/kotlin/androidx/camera/viewfinder/compose/ViewfinderTransformsScreenshotTest.kt
@@ -17,6 +17,7 @@ package androidx.camera.viewfinder.compose import android.util.Size +import androidx.camera.testing.impl.RequireForegroundRule import androidx.camera.viewfinder.core.ImplementationMode import androidx.compose.ui.Alignment import androidx.compose.ui.layout.ContentScale @@ -63,12 +64,14 @@ } } - // Evaluate screenshotRule before composeTestRule so non-supported devices skip without - // launching ComponentActivity. + // Evaluate screenshotRule before requireForegroundRule and composeTestRule so non-supported + // devices skip without UI preparation or launching ComponentActivity. @get:Rule(order = 0) val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_CAMERA_VIEWFINDER_COMPOSE) - @get:Rule(order = 1) val composeTestRule = createComposeRule() + @get:Rule(order = 1) val requireForegroundRule = RequireForegroundRule() + + @get:Rule(order = 2) val composeTestRule = createComposeRule() @Test fun viewfinderTransformsCorrectly() = runBlocking {
diff --git a/camera/viewfinder/viewfinder-view/src/androidTest/java/androidx/camera/viewfinder/view/ViewfinderViewBitmapTest.kt b/camera/viewfinder/viewfinder-view/src/androidTest/java/androidx/camera/viewfinder/view/ViewfinderViewBitmapTest.kt index 33ef906..cf48d72 100644 --- a/camera/viewfinder/viewfinder-view/src/androidTest/java/androidx/camera/viewfinder/view/ViewfinderViewBitmapTest.kt +++ b/camera/viewfinder/viewfinder-view/src/androidTest/java/androidx/camera/viewfinder/view/ViewfinderViewBitmapTest.kt
@@ -20,6 +20,7 @@ import android.graphics.Color import android.graphics.Matrix import android.graphics.RectF +import androidx.camera.testing.impl.RequireForegroundRule import androidx.camera.viewfinder.core.ImplementationMode import androidx.camera.viewfinder.core.ScaleType import androidx.camera.viewfinder.core.ViewfinderSurfaceRequest @@ -63,7 +64,10 @@ } } - @get:Rule val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_CAMERA_VIEWFINDER_VIEW) + @get:Rule(order = 0) + val screenshotRule = AndroidXScreenshotTestRule(GOLDEN_CAMERA_VIEWFINDER_VIEW) + + @get:Rule(order = 1) val requireForegroundRule = RequireForegroundRule() private val context = ApplicationProvider.getApplicationContext<Context>()
diff --git a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutAnimationParityTest.kt b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutAnimationParityTest.kt index e53cbd4..c92e812 100644 --- a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutAnimationParityTest.kt +++ b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutAnimationParityTest.kt
@@ -39,12 +39,14 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.requiredSize +import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.animateItemWithTransitions import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.draw.drawBehind @@ -75,6 +77,8 @@ protected var visible by mutableStateOf(false) + protected var resizedItemSize: IntSize? by mutableStateOf(null) + @OptIn(ExperimentalFoundationApi::class) @Before fun setUpParityTest() { @@ -89,6 +93,7 @@ layoutDirection: LayoutDirection = LayoutDirection.Ltr, frames: Int = TotalFrames, maxChannelDifference: Int = 0, + withTrailingItem: Boolean = false, ) { setParityContent( initiallyVisible = false, @@ -96,6 +101,7 @@ exit = ExitTransition.None, itemSize = itemSize, layoutDirection = layoutDirection, + withTrailingItem = withTrailingItem, ) toggleAndAssertParity(frames, maxChannelDifference) @@ -127,6 +133,7 @@ exit: ExitTransition, itemSize: IntSize = defaultItemSize, layoutDirection: LayoutDirection = LayoutDirection.Ltr, + withTrailingItem: Boolean = false, ) { visible = initiallyVisible rule.setContent { @@ -145,6 +152,12 @@ visible = isVisible, contentPadding = PaddingValues(horizontal = itemWidth, vertical = itemHeight), + trailingItemContent = + if (withTrailingItem) { + { TrailingItem(itemSize) } + } else { + null + }, ) { ParityItem( itemSize = itemSize, @@ -163,6 +176,7 @@ itemSize = itemSize, enter = enter, exit = exit, + withTrailingItem = withTrailingItem, ) } } @@ -175,6 +189,7 @@ protected abstract fun LazyLayoutUnderTest( visible: Boolean, contentPadding: PaddingValues, + trailingItemContent: (@Composable () -> Unit)?, itemContent: @Composable () -> Unit, ) @@ -253,6 +268,7 @@ itemSize: IntSize, enter: EnterTransition, exit: ExitTransition, + withTrailingItem: Boolean, ) { val density = rule.density Box(modifier) { @@ -263,20 +279,42 @@ vertical = with(density) { itemSize.height.toDp() }, ) ) { - AnimatedVisibility(visible = visible, enter = enter, exit = exit) { - ParityItem(itemSize = itemSize) + if (withTrailingItem) { + Column(Modifier.wrapContentSize(Alignment.TopStart, unbounded = true)) { + AnimatedVisibility(visible = visible, enter = enter, exit = exit) { + ParityItem(itemSize = itemSize) + } + TrailingItem(itemSize) + } + } else { + AnimatedVisibility(visible = visible, enter = enter, exit = exit) { + ParityItem(itemSize = itemSize) + } } } } } @Composable + private fun TrailingItem(itemSize: IntSize) { + val density = rule.density + Box( + Modifier.requiredSize( + with(density) { itemSize.width.toDp() }, + with(density) { itemSize.height.toDp() }, + ) + .aliasedBackground(TrailingItemColor) + ) + } + + @Composable private fun ParityItem(itemSize: IntSize, modifier: Modifier = Modifier) { val density = rule.density + val size = resizedItemSize ?: itemSize Column( modifier.requiredSize( - with(density) { itemSize.width.toDp() }, - with(density) { itemSize.height.toDp() }, + with(density) { size.width.toDp() }, + with(density) { size.height.toDp() }, ) ) { Row(Modifier.weight(1f).fillMaxWidth()) { @@ -338,6 +376,8 @@ const val SpringFrames = 60 const val ContainerScale = 3 const val ItemKey = 0 + const val TrailingItemKey = 1 + val TrailingItemColor = Color.Magenta const val LazyTag = "lazy" const val AnimatedVisibilityTag = "animatedVisibility"
diff --git a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutItemAnimationTest.kt b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutItemAnimationTest.kt index 1e3b4b1..42884c6 100644 --- a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutItemAnimationTest.kt +++ b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/layout/BaseLazyLayoutItemAnimationTest.kt
@@ -21,6 +21,8 @@ import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.core.FiniteAnimationSpec +import androidx.compose.animation.expandHorizontally +import androidx.compose.animation.expandVertically import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutHorizontally @@ -33,12 +35,14 @@ import androidx.compose.foundation.lazy.list.BaseLazyListTestWithOrientation import androidx.compose.runtime.Composable import androidx.compose.testutils.assertPixels +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize import kotlin.math.roundToInt @RequiresApi(Build.VERSION_CODES.O) @@ -51,10 +55,12 @@ enter: EnterTransition? = null, exit: ExitTransition? = null, placementSpec: FiniteAnimationSpec<IntOffset>? = null, + modifier: Modifier = Modifier, ) { val density = rule.density Box( - Modifier.animateItemWithTransitions( + modifier + .animateItemWithTransitions( enterTransition = enter, exitTransition = exit, placementSpec = placementSpec, @@ -85,6 +91,28 @@ slideInVertically(animationSpec, initialOffset) } + protected fun expandMainAxis( + animationSpec: FiniteAnimationSpec<IntSize>, + fromEnd: Boolean = true, + clip: Boolean = true, + initialSize: (fullSize: Int) -> Int = { 0 }, + ): EnterTransition = + if (vertical) { + expandVertically( + animationSpec, + expandFrom = if (fromEnd) Alignment.Bottom else Alignment.Top, + clip = clip, + initialHeight = initialSize, + ) + } else { + expandHorizontally( + animationSpec, + expandFrom = if (fromEnd) Alignment.End else Alignment.Start, + clip = clip, + initialWidth = initialSize, + ) + } + protected fun slideOutCrossAxis( animationSpec: FiniteAnimationSpec<IntOffset>, targetOffset: (crossAxisSize: Int) -> Int = { -it / 2 },
diff --git a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutChangeSizeAnimationParityTest.kt b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutChangeSizeAnimationParityTest.kt new file mode 100644 index 0000000..70eaca1 --- /dev/null +++ b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutChangeSizeAnimationParityTest.kt
@@ -0,0 +1,420 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.foundation.lazy.list + +import android.os.Build +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.core.FiniteAnimationSpec +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.VisibilityThreshold +import androidx.compose.animation.core.keyframes +import androidx.compose.animation.core.snap +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.animation.expandHorizontally +import androidx.compose.animation.expandIn +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideInVertically +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.layout.BaseLazyLayoutAnimationParityTest +import androidx.compose.foundation.lazy.layout.BaseLazyLayoutAnimationParityTest.Companion.DurationMillis +import androidx.compose.foundation.lazy.layout.BaseLazyLayoutAnimationParityTest.Companion.delayedSpec +import androidx.compose.foundation.lazy.layout.BaseLazyLayoutAnimationParityTest.Companion.easedSpec +import androidx.compose.foundation.lazy.layout.BaseLazyLayoutAnimationParityTest.Companion.linearSpec +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.test.filters.LargeTest +import androidx.test.filters.SdkSuppress +import org.junit.Test + +@LargeTest +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) +class LazyLayoutChangeSizeAnimationParityTest : BaseLazyLayoutAnimationParityTest(DefaultItemSize) { + + @Test + fun expandIn_default() { + assertEnterParity(expandIn(LinearSpec)) + } + + @Test + fun expandVertically_default() { + assertEnterParity(expandVertically(LinearSpec)) + } + + @Test + fun expandHorizontally_default() { + assertEnterParity(expandHorizontally(LinearSpec)) + } + + @Test + fun expandIn_fromTopStart() { + assertEnterParity(expandIn(LinearSpec, expandFrom = Alignment.TopStart)) + } + + @Test + fun expandIn_fromCenter() { + assertEnterParity(expandIn(LinearSpec, expandFrom = Alignment.Center)) + } + + @Test + fun expandIn_fromBottomCenter() { + assertEnterParity(expandIn(LinearSpec, expandFrom = Alignment.BottomCenter)) + } + + @Test + fun expandVertically_fromTop() { + assertEnterParity(expandVertically(LinearSpec, expandFrom = Alignment.Top)) + } + + @Test + fun expandVertically_fromCenter() { + assertEnterParity(expandVertically(LinearSpec, expandFrom = Alignment.CenterVertically)) + } + + @Test + fun expandHorizontally_fromStart() { + assertEnterParity(expandHorizontally(LinearSpec, expandFrom = Alignment.Start)) + } + + @Test + fun expandHorizontally_fromCenter() { + assertEnterParity(expandHorizontally(LinearSpec, expandFrom = Alignment.CenterHorizontally)) + } + + @Test + fun expandIn_partialInitialSize() { + assertEnterParity(expandIn(LinearSpec) { IntSize(it.width / 2, it.height / 4) }) + } + + @Test + fun expandVertically_partialInitialHeight() { + assertEnterParity(expandVertically(LinearSpec) { it / 3 }) + } + + @Test + fun expandHorizontally_partialInitialWidth() { + assertEnterParity(expandHorizontally(LinearSpec) { it / 3 }) + } + + @Test + fun expandIn_initialSizeIsFullSize() { + assertEnterParity(expandIn(LinearSpec) { it }) + } + + @Test + fun expandIn_withoutClip() { + assertEnterParity(expandIn(LinearSpec, clip = false)) + } + + @Test + fun expandIn_withoutClip_fromTopStart() { + assertEnterParity(expandIn(LinearSpec, expandFrom = Alignment.TopStart, clip = false)) + } + + @Test + fun expandIn_oddItemSize() { + assertEnterParity(expandIn(LinearSpec), itemSize = OddItemSize) + } + + @Test + fun expandIn_fromCenter_oddItemSize() { + assertEnterParity( + expandIn(LinearSpec, expandFrom = Alignment.Center), + itemSize = OddItemSize, + ) + } + + @Test + fun expandIn_nonLinearEasing() { + assertEnterParity(expandIn(EasedSpec)) + } + + @Test + fun expandHorizontally_springSpec() { + assertEnterParity(expandHorizontally(SpringSpec), frames = SpringFrames) + } + + @Test + fun expandIn_delayedTween() { + assertEnterParity(expandIn(DelayedSpec), frames = DelayedFrames) + } + + @Test + fun expandIn_keyframes() { + assertEnterParity(expandIn(KeyframesSpec)) + } + + @Test + fun expandIn_zeroDuration() { + assertEnterParity(expandIn(tween(0))) + } + + @Test + fun expandIn_snapSpec() { + assertEnterParity(expandIn(snap())) + } + + @Test + fun expandIn_rtl() { + assertEnterParity( + expandIn(LinearSpec, expandFrom = Alignment.TopStart), + layoutDirection = LayoutDirection.Rtl, + ) + } + + @Test + fun expandHorizontally_fromStart_rtl() { + assertEnterParity( + expandHorizontally(LinearSpec, expandFrom = Alignment.Start), + layoutDirection = LayoutDirection.Rtl, + ) + } + + @Test + fun expandHorizontally_fromEnd_rtl() { + assertEnterParity( + expandHorizontally(LinearSpec, expandFrom = Alignment.End), + layoutDirection = LayoutDirection.Rtl, + ) + } + + @Test + fun expandVertically_pushesTrailingItem() { + assertEnterParity(expandVertically(LinearSpec), withTrailingItem = true) + } + + @Test + fun expandVertically_fromTop_pushesTrailingItem() { + assertEnterParity( + expandVertically(LinearSpec, expandFrom = Alignment.Top), + withTrailingItem = true, + ) + } + + @Test + fun expandVertically_partialInitialHeight_pushesTrailingItem() { + assertEnterParity(expandVertically(LinearSpec) { it / 2 }, withTrailingItem = true) + } + + @Test + fun expandVertically_withoutClip_overlapsTrailingItem() { + assertEnterParity(expandVertically(LinearSpec, clip = false), withTrailingItem = true) + } + + @Test + fun expandVertically_springSpec_pushesTrailingItem() { + assertEnterParity( + expandVertically(SpringSpec), + frames = SpringFrames, + withTrailingItem = true, + ) + } + + @Test + fun expandHorizontally_doesNotMoveTrailingItem() { + assertEnterParity(expandHorizontally(LinearSpec), withTrailingItem = true) + } + + @Test + fun expandInCombinedWithFadeIn() { + assertEnterParity( + fadeIn(FloatLinearSpec) + expandIn(LinearSpec), + maxChannelDifference = FadeChannelTolerance, + ) + } + + @Test + fun expandInCombinedWithSlideIn_slideIsClippedToExpandedBounds() { + assertEnterParity( + slideInHorizontally(IntOffsetLinearSpec) { -it } + + expandIn(LinearSpec, expandFrom = Alignment.TopStart) + ) + } + + @Test + fun expandVerticallyCombinedWithSlideInVertically() { + assertEnterParity( + slideInVertically(IntOffsetLinearSpec) { -it / 2 } + expandVertically(LinearSpec), + withTrailingItem = true, + ) + } + + @Test + fun noAnimation_initiallyVisible() { + setParityContent( + initiallyVisible = true, + enter = expandIn(LinearSpec), + exit = fadeOut(FloatLinearSpec), + withTrailingItem = true, + ) + + runFramesAndAssertParity(TotalFrames) + } + + @Test + fun noAnimation_initiallyHidden() { + setParityContent( + initiallyVisible = false, + enter = expandIn(LinearSpec), + exit = fadeOut(FloatLinearSpec), + withTrailingItem = true, + ) + + runFramesAndAssertParity(TotalFrames) + } + + @Test + fun enterThenExit_fullCycle() { + setParityContent( + initiallyVisible = false, + enter = expandIn(LinearSpec), + exit = fadeOut(FloatLinearSpec), + ) + + toggleAndAssertParity(TotalFrames) + toggleAndAssertParity(TotalFrames) + } + + @Test + fun expandVertically_itemGrowsWhileExpanding_expansionIsRetargeted() { + assertExpandParityWhenItemIsResized( + expandVertically(LinearSpec), + initialSize = IntSize(DefaultItemSize.width, DefaultItemSize.height / 2), + newSize = DefaultItemSize, + ) + } + + @Test + fun expandVertically_itemShrinksWhileExpanding_expansionIsRetargeted() { + assertExpandParityWhenItemIsResized( + expandVertically(LinearSpec), + initialSize = DefaultItemSize, + newSize = IntSize(DefaultItemSize.width, DefaultItemSize.height / 4), + ) + } + + @Test + fun expandIn_itemGrowsOnBothAxesWhileExpanding_expansionIsRetargeted() { + assertExpandParityWhenItemIsResized( + expandIn(LinearSpec), + initialSize = IntSize(DefaultItemSize.width / 2, DefaultItemSize.height / 2), + newSize = DefaultItemSize, + ) + } + + @Test + fun expandVertically_itemShrinksWhileExpanding_trailingItemFollows() { + assertExpandParityWhenItemIsResized( + expandVertically(LinearSpec), + initialSize = DefaultItemSize, + newSize = IntSize(DefaultItemSize.width, DefaultItemSize.height / 4), + withTrailingItem = true, + ) + } + + @Test + fun expandVertically_itemResizedTwiceWhileExpanding_expansionIsRetargetedTwice() { + setParityContent( + initiallyVisible = false, + enter = expandVertically(LinearSpec), + exit = ExitTransition.None, + ) + + toggleAndAssertParity(TotalFrames * 3) { frame -> + if (frame == InterruptFrame) { + resizedItemSize = IntSize(DefaultItemSize.width, DefaultItemSize.height / 4) + } + if (frame == InterruptFrame + 2) resizedItemSize = DefaultItemSize + } + } + + @Test + fun expandVertically_itemResizedAfterExpanding_takesItsNewSizeAtOnce() { + assertExpandParityWhenItemIsResized( + expandVertically(LinearSpec), + initialSize = IntSize(DefaultItemSize.width, DefaultItemSize.height / 2), + newSize = DefaultItemSize, + resizeFrame = TotalFrames, + ) + } + + private fun assertExpandParityWhenItemIsResized( + enter: EnterTransition, + initialSize: IntSize, + newSize: IntSize, + resizeFrame: Int = InterruptFrame, + frames: Int = TotalFrames * 3, + withTrailingItem: Boolean = false, + ) { + resizedItemSize = initialSize + setParityContent( + initiallyVisible = false, + enter = enter, + exit = ExitTransition.None, + withTrailingItem = withTrailingItem, + ) + + toggleAndAssertParity(frames) { frame -> + if (frame == resizeFrame) resizedItemSize = newSize + } + } + + @Composable + override fun LazyLayoutUnderTest( + visible: Boolean, + contentPadding: PaddingValues, + trailingItemContent: (@Composable () -> Unit)?, + itemContent: @Composable () -> Unit, + ) { + LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = contentPadding) { + if (trailingItemContent != null) item(key = LeadingItemKey) {} + if (visible) item(key = ItemKey) { itemContent() } + if (trailingItemContent != null) item(key = TrailingItemKey) { trailingItemContent() } + } + } +} + +private const val LeadingItemKey = -1 +private val DefaultItemSize = IntSize(20, 12) +private val OddItemSize = IntSize(21, 13) +private const val FadeChannelTolerance = 2 +private val LinearSpec: FiniteAnimationSpec<IntSize> = linearSpec() +private val FloatLinearSpec: FiniteAnimationSpec<Float> = linearSpec() +private val IntOffsetLinearSpec: FiniteAnimationSpec<IntOffset> = linearSpec() +private val EasedSpec: FiniteAnimationSpec<IntSize> = easedSpec() +private val DelayedSpec: FiniteAnimationSpec<IntSize> = delayedSpec() +private val SpringSpec: FiniteAnimationSpec<IntSize> = + spring( + dampingRatio = Spring.DampingRatioMediumBouncy, + stiffness = Spring.StiffnessMediumLow, + visibilityThreshold = IntSize.VisibilityThreshold, + ) +private val KeyframesSpec: FiniteAnimationSpec<IntSize> = keyframes { + durationMillis = DurationMillis + IntSize(4, 2) at DurationMillis / 4 + IntSize(16, 4) at DurationMillis / 2 +}
diff --git a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutScaleAnimationParityTest.kt b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutScaleAnimationParityTest.kt index 89ae75c..7c130c6 100644 --- a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutScaleAnimationParityTest.kt +++ b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutScaleAnimationParityTest.kt
@@ -404,10 +404,12 @@ override fun LazyLayoutUnderTest( visible: Boolean, contentPadding: PaddingValues, + trailingItemContent: (@Composable () -> Unit)?, itemContent: @Composable () -> Unit, ) { LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = contentPadding) { if (visible) item(key = ItemKey) { itemContent() } + if (trailingItemContent != null) item(key = TrailingItemKey) { trailingItemContent() } } }
diff --git a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutSlideAnimationParityTest.kt b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutSlideAnimationParityTest.kt index 9aa7ed3..dc027cf 100644 --- a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutSlideAnimationParityTest.kt +++ b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyLayoutSlideAnimationParityTest.kt
@@ -405,10 +405,12 @@ override fun LazyLayoutUnderTest( visible: Boolean, contentPadding: PaddingValues, + trailingItemContent: (@Composable () -> Unit)?, itemContent: @Composable () -> Unit, ) { LazyColumn(modifier = Modifier.fillMaxSize(), contentPadding = contentPadding) { if (visible) item(key = ItemKey) { itemContent() } + if (trailingItemContent != null) item(key = TrailingItemKey) { trailingItemContent() } } }
diff --git a/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListItemChangeSizeAnimationTest.kt b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListItemChangeSizeAnimationTest.kt new file mode 100644 index 0000000..332d21e --- /dev/null +++ b/compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListItemChangeSizeAnimationTest.kt
@@ -0,0 +1,2900 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.foundation.lazy.list + +import android.os.Build +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.core.FiniteAnimationSpec +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.Spring +import androidx.compose.animation.core.TweenSpec +import androidx.compose.animation.core.spring +import androidx.compose.animation.core.tween +import androidx.compose.animation.expandHorizontally +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.ComposeFoundationFlags +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.Orientation +import androidx.compose.foundation.gestures.scrollBy +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyItemScope +import androidx.compose.foundation.lazy.LazyListItemInfo +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.animateItemWithTransitions +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.layout.BaseLazyLayoutItemAnimationTest +import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow +import androidx.compose.foundation.lazy.layout.LazyLayoutItemAnimation +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.graphics.toPixelMap +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.LocalPinnableContainer +import androidx.compose.ui.layout.LookaheadScope +import androidx.compose.ui.layout.onPlaced +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.test.filters.LargeTest +import androidx.test.filters.SdkSuppress +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import kotlin.math.roundToInt +import kotlinx.coroutines.runBlocking +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.Parameterized + +@LargeTest +@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) +@RunWith(Parameterized::class) +class LazyListItemChangeSizeAnimationTest(orientation: Orientation) : + BaseLazyLayoutItemAnimationTest(orientation) { + private lateinit var state: LazyListState + + @OptIn(ExperimentalFoundationApi::class) + @Before + fun before() { + rule.mainClock.autoAdvance = false + assumeTrue(ComposeFoundationFlags.isLazyLayoutItemAnimationEnterExitTransitionsEnabled) + } + + @Test + fun expandMainAxis_oneItemAdded() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { ExpandingItem(enter = expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(StartColor) } + + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem(size = interpolate(0, ItemMainAxisSize, fraction)), + ) + } + } + + @Test + fun expandMainAxis_fromStart_revealsContentStartFirst() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { + ExpandingItem(enter = expandMainAxis(fromEnd = false)) + } + } + } + + rule.runOnUiThread { list = listOf(StartColor) } + + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem( + size = interpolate(0, ItemMainAxisSize, fraction), + alignToEnd = false, + ), + ) + } + } + + @Test + fun expandMainAxis_partialInitialSize() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { + ExpandingItem(enter = expandMainAxis(initialSize = { it / 2 })) + } + } + } + + rule.runOnUiThread { list = listOf(StartColor) } + + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem( + size = interpolate(ItemMainAxisSize / 2, ItemMainAxisSize, fraction) + ), + ) + } + } + + @Test + fun expandMainAxis_onlyFollowingItemsMove() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 3) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 3, + ExpectedItem(Color.Black), + *expandingItem(mainAxis = ItemMainAxisSize, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size), + ) + } + } + + @Test + fun expandMainAxis_itemsAddedWithoutExpandAreFullSizeImmediately() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + *expandingItem(size = size), + ExpectedItem(Color.Black, mainAxis = size), + ) + } + } + + @Test + fun expandCrossAxis_oneItemAdded() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { Item(it, enter = expandCrossAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black) } + + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize, + ExpectedItem( + Color.Black, + crossAxisSize = interpolate(0, ItemCrossAxisSize, fraction), + ), + ) + } + } + + @Test + fun expandCrossAxis_doesNotMoveFollowingItems() { + var list by mutableStateOf(listOf(Color.Blue)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + Item(it, enter = if (it == Color.Black) expandCrossAxis() else null) + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, Color.Blue) } + + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem( + Color.Black, + crossAxisSize = interpolate(0, ItemCrossAxisSize, fraction), + ), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize), + ) + } + } + + @Test + fun noAnimationForInitialItems() { + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(listOf(StartColor, Color.Black), key = { it.toArgb() }) { + ItemOrExpandingItem(it, expandMainAxis()) + } + } + } + + onAnimationFrame { + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + *expandingItem(size = ItemMainAxisSize), + ExpectedItem(Color.Black, mainAxis = ItemMainAxisSize), + ) + } + } + + @Test + fun itemScrolledIntoView_isNotExpanded() { + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items( + listOf(Color.Black, Color.Blue, StartColor, Color.Yellow), + key = { it.toArgb() }, + ) { + ItemOrExpandingItem(it, expandMainAxis()) + } + } + } + + rule.runOnIdle { runBlocking { state.scrollBy(ItemMainAxisSize * 2f) } } + + onAnimationFrame { + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + *expandingItem(size = ItemMainAxisSize), + ExpectedItem(Color.Yellow, mainAxis = ItemMainAxisSize), + ) + } + } + + @Test + fun itemAddedOutsideOfViewport_isNotExpandedWhenScrolledIntoView() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, Color.Blue, StartColor, Color.Yellow) } + + rule.runOnIdle { runBlocking { state.scrollBy(ItemMainAxisSize * 1.5f) } } + + onAnimationFrame { + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Blue, mainAxis = -ItemMainAxisSize / 2), + *expandingItem(mainAxis = ItemMainAxisSize / 2, size = ItemMainAxisSize), + ExpectedItem(Color.Yellow, mainAxis = ItemMainAxisSize * 3 / 2), + ) + } + } + + @Test + fun fadeIn_listIsNotMeasuredAgainWhileItemFadesIn() { + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { Item(it, enter = fadeIn(FadeSpec)) } + } + } + + rule.runOnUiThread { list = listOf(Color.Blue, Color.Black) } + + var layoutInfo: Any? = null + onAnimationStep(steps = Steps - 1) { step -> + rule.runOnIdle { + if (step > 0) assertThat(state.layoutInfo).isSameInstanceAs(layoutInfo) + layoutInfo = state.layoutInfo + } + } + } + + @Test + fun expandCombinedWithFadeIn() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { + ExpandingItem(enter = fadeIn(FadeSpec) + expandMainAxis()) + } + } + } + + rule.runOnUiThread { list = listOf(StartColor) } + + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem( + size = interpolate(0, ItemMainAxisSize, fraction), + startColor = StartColor.copy(alpha = fraction), + endColor = EndColor.copy(alpha = fraction), + ), + ) + } + } + + @Test + fun withoutClip_contentIsDrawnOutsideExpandedBounds() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + ItemOrExpandingItem(it, expandMainAxis(fromEnd = false, clip = false)) + } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + *expandingItem(size = size, alignToEnd = false, clip = false), + ExpectedItem(Color.Black, mainAxis = size), + ) + } + } + + @Test + fun reAddItemAfterExpandFinished_expandsFromInitialSize() { + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { ExpandingItem(enter = expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(StartColor) } + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem(size = interpolate(0, ItemMainAxisSize, fraction)), + ) + } + + rule.runOnUiThread { list = emptyList() } + rule.mainClock.advanceTimeByFrame() + assertItems(containerMainAxisSize = ItemMainAxisSize) + + rule.runOnUiThread { list = listOf(StartColor) } + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem(size = interpolate(0, ItemMainAxisSize, fraction)), + ) + } + } + + @Test + fun reAddItemBeingFadedOut_doesNotExpandAgain() { + var list by mutableStateOf(listOf(StartColor)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { + ExpandingItem(enter = expandMainAxis(), exit = fadeOut(FadeSpec)) + } + } + } + + rule.runOnUiThread { list = emptyList() } + onAnimationStep(steps = Steps / 2) { step -> + val alpha = 1f - step / Steps.toFloat() + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem( + size = ItemMainAxisSize, + startColor = StartColor.copy(alpha = alpha), + endColor = EndColor.copy(alpha = alpha), + ), + ) + } + + rule.runOnUiThread { list = listOf(StartColor) } + + onAnimationFrame { + assertItems( + containerMainAxisSize = ItemMainAxisSize, + *expandingItem(size = ItemMainAxisSize), + ) + } + } + + @Test + fun scrollingDuringExpand_expandContinuesRelativeToItemPosition() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow) } + + val scrollAmount = ItemMainAxisSize / 2 + onAnimationStep { step -> + if (step == Steps / 2) { + rule.runOnIdle { runBlocking { state.scrollBy(scrollAmount.toFloat()) } } + } + val scrolled = if (step >= Steps / 2) scrollAmount else 0 + val size = interpolate(0, ItemMainAxisSize, step / Steps.toFloat()) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Black, mainAxis = -scrolled), + *expandingItem(mainAxis = ItemMainAxisSize - scrolled, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size - scrolled), + ) + } + } + + @Test + fun expandMainAxis_itemWithSeveralRootComposables() { + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 3) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + ExpandingItem(enter = expandMainAxis()) + } else { + Item(it) + } + } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 3, + *expandingItem(size = size), + *expandingItem(mainAxis = size, size = size), + ExpectedItem(Color.Black, mainAxis = size * 2), + ) + } + } + + @Test + fun expandMainAxis_itemWithSeveralRootComposables_onlyOneAnimated() { + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 3) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + ExpandingItem() + } else { + Item(it) + } + } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 3, + *expandingItem(size = size), + *expandingItem(mainAxis = size, size = ItemMainAxisSize), + ExpectedItem(Color.Black, mainAxis = size + ItemMainAxisSize), + ) + } + } + + @Test + fun expandWithOvershootingSpring_followingItemStaysNextToTheItem() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue)) + val overshootingSpec: FiniteAnimationSpec<IntSize> = + spring(dampingRatio = 0.2f, stiffness = Spring.StiffnessMedium) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 4) { + items(list, key = { it.toArgb() }) { + ItemOrExpandingItem(it, expandMainAxis(animationSpec = overshootingSpec)) + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue) } + + var maxFollowingItemOffset = 0 + onAnimationStep(steps = 80) { + val followingItemOffset = mainAxisRangeOf(Color.Blue)!!.first + val contentEnd = mainAxisRangeOf(EndColor)?.last + if (contentEnd != null) assertThat(followingItemOffset).isEqualTo(contentEnd + 1) + maxFollowingItemOffset = maxOf(maxFollowingItemOffset, followingItemOffset) + } + assertThat(maxFollowingItemOffset).isGreaterThan(ItemMainAxisSize * 2) + assertThat(mainAxisRangeOf(Color.Blue)!!.first).isEqualTo(ItemMainAxisSize * 2) + } + + @Test + fun expandCrossAxisWithOvershootingSpring_boundsAreNoLargerThanTheListAllows() { + var list by mutableStateOf(emptyList<Color>()) + val overshootingSpec: FiniteAnimationSpec<IntSize> = + spring(dampingRatio = 0.2f, stiffness = Spring.StiffnessMedium) + val expand = + if (vertical) { + expandHorizontally(overshootingSpec, initialWidth = { 0 }) + } else { + expandVertically(overshootingSpec, initialHeight = { 0 }) + } + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize) { + items(list, key = { it.toArgb() }) { Item(it, enter = expand) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black) } + + onAnimationStep(steps = 80) { + val range = crossAxisRangeOf(Color.Black) + if (range != null) assertThat(range.first).isEqualTo(0) + } + assertThat(crossAxisRangeOf(Color.Black)).isEqualTo(0 until ItemCrossAxisSize) + } + + @Test + fun expandingItem_doesNotTakeInputMeantForThePreviousItem() { + var list by mutableStateOf(listOf(Color.Black)) + var hitItem: Color? + fun Modifier.recordHits(color: Color) = + pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + awaitPointerEvent() + hitItem = color + } + } + } + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem( + enter = expandMainAxis(), + modifier = Modifier.recordHits(it), + ) + } else { + Item(it, modifier = Modifier.recordHits(it)) + } + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor) } + onAnimationStep(steps = Steps / 2) {} + + val overPreviousItem = ItemMainAxisSize * 3 / 4 + val withinBounds = ItemMainAxisSize + ItemMainAxisSize / 4 + fun hitAt(mainAxis: Int): Color? { + hitItem = null + val crossAxis = ItemCrossAxisSize / 2f + rule.onNodeWithTag(ContainerTag).performTouchInput { + down( + if (vertical) { + Offset(crossAxis, mainAxis.toFloat()) + } else { + Offset(mainAxis.toFloat(), crossAxis) + } + ) + up() + } + return rule.runOnIdle { hitItem } + } + assertThat(hitAt(overPreviousItem)).isEqualTo(Color.Black) + assertThat(hitAt(withinBounds)).isEqualTo(StartColor) + } + + @Test + fun expandMainAxis_withPaddingBeforeAnimateItem_paddingExpandsWithItem() { + val padding = ItemMainAxisSize / 4 + val fullSize = ItemMainAxisSize + padding * 2 + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList( + containerMainAxisSize = fullSize, + containerCrossAxisSize = ItemCrossAxisSize + padding * 2, + ) { + items(list, key = { it.toArgb() }) { + ExpandingItem( + enter = expandMainAxis(), + modifier = Modifier.background(PaddingColor).padding(padding.toDp()), + ) + } + } + } + + rule.runOnUiThread { list = listOf(StartColor) } + + onAnimationFrame { fraction -> + assertItems( + containerMainAxisSize = fullSize, + *paddedExpandingItem(size = interpolate(0, fullSize, fraction), padding), + containerCrossAxisSize = ItemCrossAxisSize + padding * 2, + ) + } + } + + private fun paddedExpandingItem(size: Int, padding: Int): Array<ExpectedItem> { + val fullSize = ItemMainAxisSize + padding * 2 + return arrayOf( + ExpectedItem( + PaddingColor, + mainAxisSize = size, + crossAxisSize = ItemCrossAxisSize + padding * 2, + ), + *expandingItem(mainAxis = size - fullSize + padding, size = ItemMainAxisSize) + .mapNotNull { it.clippedTo(mainAxisEnd = size, crossAxis = padding) } + .toTypedArray(), + ) + } + + private fun ExpectedItem.clippedTo(mainAxisEnd: Int, crossAxis: Int): ExpectedItem? { + val start = maxOf(mainAxis, 0) + val end = minOf(mainAxis + mainAxisSize, mainAxisEnd) + return if (end > start) { + ExpectedItem(color, mainAxis = start, crossAxis = crossAxis, mainAxisSize = end - start) + } else { + null + } + } + + @Test + fun scrollingDuringExpand_itemBeingPushedOutScrollsWithTheOtherItems() { + val containerSize = ItemMainAxisSize * 3 / 2 + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + rule.setContent { + LazyList(containerMainAxisSize = containerSize) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow) } + onAnimationStep(steps = 1) {} + + val scrollAmount = ItemMainAxisSize / 4 + rule.runOnIdle { runBlocking { state.scrollBy(scrollAmount.toFloat()) } } + + val size = interpolate(0, ItemMainAxisSize, 1 / Steps.toFloat()) + assertItems( + containerMainAxisSize = containerSize, + ExpectedItem(Color.Black, mainAxis = -scrollAmount), + *expandingItem(mainAxis = ItemMainAxisSize - scrollAmount, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size - scrollAmount), + ) + } + + @Test + fun inLookaheadScope_followingItemsArePushed() { + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LookaheadScope { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + ItemOrExpandingItem(it, expandMainAxis()) + } + } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + *expandingItem(size = size), + ExpectedItem(Color.Black, mainAxis = size), + ) + } + } + + @Test + fun inLookaheadScope_followingItemsWithAnimationsArePushed() { + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LookaheadScope { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + } else { + Item(it, enter = fadeIn(FadeSpec)) + } + } + } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + *expandingItem(size = size), + ExpectedItem(Color.Black, mainAxis = size), + ) + } + } + + @Test + fun itemsChangedAgainWhileItemIsPushed_itemNeverMovesBack() { + assertItemNeverMovesBackWhenItemsChangeAgain(isInLookaheadScope = false) + } + + @Test + fun inLookaheadScope_itemsChangedAgainWhileItemIsPushed_itemNeverMovesBack() { + assertItemNeverMovesBackWhenItemsChangeAgain(isInLookaheadScope = true) + } + + private fun assertItemNeverMovesBackWhenItemsChangeAgain(isInLookaheadScope: Boolean) { + var list by mutableStateOf(listOf(Color.Black)) + setContent(isInLookaheadScope) { + LazyList(containerMainAxisSize = ItemMainAxisSize * 3) { + items(list, key = { it.toArgb() }) { + when (it) { + StartColor -> ExpandingItem(enter = expandMainAxis()) + Color.Black -> Item(it, placementSpec = SlowPlacementSpec) + else -> Item(it) + } + } + } + } + + val offsets = mutableListOf<Int>() + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + onAnimationStep(steps = Steps / 2) { offsets += mainAxisRangeOf(Color.Black)!!.first } + rule.runOnUiThread { list = listOf(Color.Blue, StartColor, Color.Black) } + onAnimationStep(steps = 60) { offsets += mainAxisRangeOf(Color.Black)!!.first } + + assertThat(offsets).isInOrder() + assertThat(offsets.first()).isEqualTo(0) + assertThat(offsets.last()).isEqualTo(ItemMainAxisSize * 2) + assertWithMessage("Offsets: $offsets") + .that(offsets.zipWithNext { offset, next -> next - offset }.max()) + .isLessThan(ItemMainAxisSize * 3 / 4) + } + + @Test + fun inLookaheadScope_itemPushedOutOfViewport_staysUntilItIsPushedOut() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue)) + rule.setContent { + LookaheadScope { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + } else { + Item(it, enter = fadeIn(FadeSpec)) + } + } + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Black), + *expandingItem(mainAxis = ItemMainAxisSize, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size), + ) + } + } + + @Test + fun inLookaheadScope_itemPushedOutOfViewport_keepsItsAnimation() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue)) + rule.setContent { + LookaheadScope { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + } else { + Item(it, enter = fadeIn(FadeSpec)) + } + } + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue) } + + var animation: LazyLayoutItemAnimation? = null + onAnimationStep(steps = Steps - 1) { step -> + val current = rule.runOnIdle { state.itemAnimator.getAnimation(Color.Blue.toArgb(), 0) } + assertThat(current).isNotNull() + if (step > 0) assertThat(current).isSameInstanceAs(animation) + animation = current + } + } + + @Test + fun inLookaheadScope_itemPushedOutOfViewport_keepsItsAnimationWhenLookaheadPassRunsAgain() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + rule.setContent { + LookaheadScope { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + } else { + Item(it, enter = fadeIn(FadeSpec)) + } + } + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow) } + onAnimationStep(steps = 1) {} + val animation = rule.runOnIdle { state.itemAnimator.getAnimation(Color.Blue.toArgb(), 0) } + assertThat(animation).isNotNull() + + rule.runOnUiThread { + list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow, Color.Magenta) + } + onAnimationStep(steps = 0) {} + + rule.runOnIdle { + assertThat(state.itemAnimator.getAnimation(Color.Blue.toArgb(), 0)) + .isSameInstanceAs(animation) + } + } + + @Test + fun itemsAddedThatFit_existingItemsStayUntilTheyArePushedOut() { + assertExistingItemsStayUntilTheyArePushedOut(isInLookaheadScope = false) + } + + @Test + fun inLookaheadScope_itemsAddedThatFit_existingItemsStayUntilTheyArePushedOut() { + assertExistingItemsStayUntilTheyArePushedOut(isInLookaheadScope = true) + } + + @Test + fun itemsAddedThatFit_itemsComposedBeyondTheViewportStayBeyondIt() { + assertExistingItemsStayUntilTheyArePushedOut( + isInLookaheadScope = false, + beyondBoundsItemCount = 1, + ) + } + + @Test + fun moreItemsAddedThanFit_allAddedItemsExpandAndExistingItemsStayUntilPushedOut() { + assertAllAddedItemsExpand(isInLookaheadScope = false) + } + + @Test + fun inLookaheadScope_moreItemsAddedThanFit_allAddedItemsExpand() { + assertAllAddedItemsExpand(isInLookaheadScope = true) + } + + private fun assertAllAddedItemsExpand(isInLookaheadScope: Boolean) { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + setContent(isInLookaheadScope) { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + Item(it, enter = expandMainAxis(), exit = ExitTransition.None) + } + } + } + + rule.runOnUiThread { + list = + listOf( + Color.Black, + Color.Red, + Color.Green, + Color.Magenta, + Color.Blue, + Color.Yellow, + ) + } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Black), + ExpectedItem(Color.Red, mainAxis = ItemMainAxisSize, mainAxisSize = size), + ExpectedItem(Color.Green, mainAxis = ItemMainAxisSize + size, mainAxisSize = size), + ExpectedItem( + Color.Magenta, + mainAxis = ItemMainAxisSize + size * 2, + mainAxisSize = size, + ), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size * 3), + ) + } + } + + private fun assertExistingItemsStayUntilTheyArePushedOut( + isInLookaheadScope: Boolean, + beyondBoundsItemCount: Int? = null, + ) { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + setContent(isInLookaheadScope) { + LazyList( + containerMainAxisSize = ItemMainAxisSize * 2, + beyondBoundsItemCount = beyondBoundsItemCount, + ) { + items(list, key = { it.toArgb() }) { + Item(it, enter = expandMainAxis(), exit = ExitTransition.None) + } + } + } + + rule.runOnUiThread { + list = listOf(Color.Black, Color.Red, Color.Green, Color.Blue, Color.Yellow) + } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Black), + ExpectedItem(Color.Red, mainAxis = ItemMainAxisSize, mainAxisSize = size), + ExpectedItem(Color.Green, mainAxis = ItemMainAxisSize + size, mainAxisSize = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size * 2), + ) + } + } + + @Test + fun itemsAddedThatFit_existingItemIsReleasedOnceItIsPushedOut() { + assertExistingItemIsReleasedOncePushedOut(isInLookaheadScope = false) + } + + @Test + fun inLookaheadScope_itemsAddedThatFit_existingItemIsReleasedOnceItIsPushedOut() { + assertExistingItemIsReleasedOncePushedOut(isInLookaheadScope = true) + } + + private fun assertExistingItemIsReleasedOncePushedOut(isInLookaheadScope: Boolean) { + val containerSize = ItemMainAxisSize * 3 / 2 + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + setContent(isInLookaheadScope) { + LazyList(containerMainAxisSize = containerSize) { + items(list, key = { it.toArgb() }) { + Item(it, enter = expandMainAxis(), exit = ExitTransition.None) + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, Color.Red, Color.Blue, Color.Yellow) } + + onAnimationStep(steps = Steps - 1) { step -> + val blueOffset = + ItemMainAxisSize + interpolate(0, ItemMainAxisSize, step / Steps.toFloat()) + val animation = rule.runOnIdle { + state.itemAnimator.getAnimation(Color.Blue.toArgb(), 0) + } + if (blueOffset < containerSize) { + assertThat(animation).isNotNull() + } else { + assertThat(animation).isNull() + } + } + } + + @Test + fun itemsWithoutItemAnimations_arePushedAndStayUntilTheyArePushedOut() { + assertItemsWithoutItemAnimationsArePushed(isInLookaheadScope = false) + } + + @Test + fun inLookaheadScope_itemsWithoutItemAnimations_arePushedAndStayUntilTheyArePushedOut() { + assertItemsWithoutItemAnimationsArePushed(isInLookaheadScope = true) + } + + private fun assertItemsWithoutItemAnimationsArePushed(isInLookaheadScope: Boolean) { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + var blueCompositions = 0 + setContent(isInLookaheadScope) { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + } else { + ItemWithoutItemAnimations( + color = it, + onComposed = { if (it == Color.Blue) blueCompositions++ }, + ) + } + } + } + } + rule.runOnIdle { assertThat(blueCompositions).isEqualTo(1) } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Black), + *expandingItem(mainAxis = ItemMainAxisSize, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size), + ) + rule.runOnIdle { assertThat(blueCompositions).isEqualTo(1) } + } + } + + @Test + fun replacedItem_itemsAfterTheViewportFillIt() { + assertItemsAfterTheViewportFillIt(isInLookaheadScope = false) + } + + @Test + fun inLookaheadScope_replacedItem_itemsAfterTheViewportFillIt() { + assertItemsAfterTheViewportFillIt(isInLookaheadScope = true) + } + + private fun assertItemsAfterTheViewportFillIt(isInLookaheadScope: Boolean) { + var list by + mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow, Color.Magenta, Color.Cyan)) + setContent(isInLookaheadScope) { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + rule.runOnIdle { runBlocking { state.scrollBy(ItemMainAxisSize.toFloat()) } } + + rule.runOnUiThread { + list = listOf(Color.Black, StartColor, Color.Yellow, Color.Magenta, Color.Cyan) + } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + *expandingItem(size = size), + ExpectedItem(Color.Yellow, mainAxis = size), + ExpectedItem(Color.Magenta, mainAxis = size + ItemMainAxisSize), + ) + } + } + + @Test + fun firstVisibleItemReplaced_itemComposedBeforeTheViewportStaysWhereItWas() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow, Color.Magenta)) + var blackPosition = Int.MIN_VALUE + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2, beyondBoundsItemCount = 1) { + items(list, key = { it.toArgb() }) { + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + } else { + Item( + it, + modifier = + if (it == Color.Black) { + Modifier.onPlaced { coordinates -> + val position = + coordinates.parentLayoutCoordinates!!.localPositionOf( + coordinates + ) + blackPosition = + (if (vertical) position.y else position.x).roundToInt() + } + } else { + Modifier + }, + ) + } + } + } + } + rule.runOnIdle { runBlocking { state.scrollBy(ItemMainAxisSize * 1.5f) } } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Yellow, Color.Magenta) } + + onAnimationFrame { + rule.runOnIdle { assertThat(blackPosition).isEqualTo(-ItemMainAxisSize * 3 / 2) } + } + } + + @Test + fun itemPushedOut_thatIsAlsoComposedBeyondTheViewport_staysUntilItIsPushedOut() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2, beyondBoundsItemCount = 1) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Black), + *expandingItem(mainAxis = ItemMainAxisSize, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size), + ) + } + } + + @Test + fun inLookaheadScope_itemPushedOutByLargerItemThatReplacesAnother_keepsItsAnimation() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue)) + rule.setContent { + LookaheadScope { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + if (it == Color.Yellow) { + Box( + Modifier.animateItemWithTransitions( + enterTransition = expandMainAxis(), + exitTransition = ExitTransition.None, + placementSpec = null, + ) + .background(it) + .requiredMainAxisSize((ItemMainAxisSize * 2).toDp()) + .requiredCrossAxisSize(ItemCrossAxisSize.toDp()) + ) + } else { + Item(it, enter = fadeIn(FadeSpec), exit = ExitTransition.None) + } + } + } + } + } + val animation = rule.runOnIdle { state.itemAnimator.getAnimation(Color.Blue.toArgb(), 0) } + assertThat(animation).isNotNull() + + rule.runOnUiThread { list = listOf(Color.Yellow, Color.Blue) } + + onAnimationStep(steps = Steps - 1) { step -> + val size = interpolate(0, ItemMainAxisSize * 2, step / Steps.toFloat()) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Yellow, mainAxisSize = size), + ExpectedItem(Color.Blue, mainAxis = size), + ) + rule.runOnIdle { + assertThat(state.itemAnimator.getAnimation(Color.Blue.toArgb(), 0)) + .isSameInstanceAs(animation) + } + } + } + + @Test + fun inLookaheadScope_itemPushedOutOfViewport_isDisposedAfterLookaheadPassRanAgain() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + val composed = mutableSetOf<Color>() + rule.setContent { + LookaheadScope { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + DisposableEffect(it) { + composed += it + onDispose { composed -= it } + } + if (it == StartColor) { + ExpandingItem(enter = expandMainAxis()) + } else { + Item(it, enter = fadeIn(FadeSpec)) + } + } + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow) } + onAnimationStep(steps = 1) {} + rule.runOnUiThread { + list = listOf(Color.Black, StartColor, Color.Blue, Color.Yellow, Color.Magenta) + } + onAnimationStep(steps = Steps + 2) {} + + rule.runOnIdle { + assertThat(composed).containsExactly(Color.Black, StartColor) + assertThat(state.itemAnimator.getAnimation(Color.Blue.toArgb(), 0)).isNull() + } + } + + @Test + fun firstVisibleItemReplaced_pinnedItemBeforeTheViewportStaysWhereItWas() { + val colors = + listOf(Color.Black, Color.Gray, Color.Blue, Color.Yellow, Color.Magenta, Color.Cyan) + var list by mutableStateOf(colors) + var blackPosition = Int.MIN_VALUE + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2) { + items(list, key = { it.toArgb() }) { + when (it) { + StartColor -> ExpandingItem(enter = expandMainAxis()) + Color.Black -> { + PinItem() + Item( + it, + modifier = + Modifier.onMainAxisPositionInList { position -> + blackPosition = position + }, + ) + } + else -> Item(it) + } + } + } + } + rule.runOnIdle { runBlocking { state.scrollBy(ItemMainAxisSize * 2.5f) } } + + rule.runOnUiThread { list = colors.map { if (it == Color.Blue) StartColor else it } } + + onAnimationFrame { + rule.runOnIdle { assertThat(blackPosition).isEqualTo(-ItemMainAxisSize * 3 / 2) } + } + } + + @Test + fun pinnedItemAfterTheViewport_staysBeyondIt() { + val containerSize = ItemMainAxisSize * 2 + val colors = listOf(Color.Black, Color.Blue, Color.Yellow, Color.Magenta, Color.Cyan) + var list by mutableStateOf(colors) + var cyanPosition = Int.MIN_VALUE + rule.setContent { + LazyList(containerMainAxisSize = containerSize) { + items(list, key = { it.toArgb() }) { + when (it) { + StartColor -> ExpandingItem(enter = expandMainAxis()) + Color.Cyan -> { + PinItem() + Item( + it, + modifier = + Modifier.onMainAxisPositionInList { position -> + cyanPosition = position + }, + ) + } + else -> Item(it) + } + } + } + } + rule.runOnIdle { runBlocking { state.scrollToItem(colors.lastIndex) } } + rule.runOnIdle { runBlocking { state.scrollToItem(0) } } + rule.runOnIdle { assertThat(cyanPosition).isEqualTo(containerSize) } + + rule.runOnUiThread { list = colors.take(1) + StartColor + colors.drop(1) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = containerSize, + ExpectedItem(Color.Black), + *expandingItem(mainAxis = ItemMainAxisSize, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size), + ) + rule.runOnIdle { assertThat(cyanPosition).isAtLeast(containerSize) } + } + } + + @OptIn(ExperimentalFoundationApi::class) + @Test + fun expandMainAxis_wrapContentContainerGrows() { + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LazyList(containerMainAxisSize = null) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor) } + + onAnimationFrame { fraction -> + val containerSize = ItemMainAxisSize + interpolate(0, ItemMainAxisSize, fraction) + rule + .onNodeWithTag(ContainerTag) + .assertMainAxisSizeIsEqualTo(containerSize.toDp(), tolerance = PixelTolerance) + assertItems( + containerMainAxisSize = containerSize, + ExpectedItem(Color.Black), + *expandingItem( + mainAxis = ItemMainAxisSize, + size = containerSize - ItemMainAxisSize, + ), + ) + } + } + + @Test + fun expandCrossAxis_wrapContentContainerGrows() { + val otherItemCrossAxisSize = ItemCrossAxisSize / 2 + var list by mutableStateOf(listOf(Color.Blue)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 2, containerCrossAxisSize = null) { + items(list, key = { it.toArgb() }) { + if (it == Color.Black) { + Item(it, enter = expandCrossAxis()) + } else { + Item(it, crossAxisSize = otherItemCrossAxisSize) + } + } + } + } + + rule.runOnUiThread { list = listOf(Color.Blue, Color.Black) } + + onAnimationFrame { fraction -> + val itemCrossAxisSize = interpolate(0, ItemCrossAxisSize, fraction) + val containerCrossAxisSize = maxOf(otherItemCrossAxisSize, itemCrossAxisSize) + rule + .onNodeWithTag(ContainerTag) + .assertCrossAxisSizeIsEqualTo( + containerCrossAxisSize.toDp(), + tolerance = PixelTolerance, + ) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem(Color.Blue, crossAxisSize = otherItemCrossAxisSize), + ExpectedItem( + Color.Black, + mainAxis = ItemMainAxisSize, + crossAxisSize = itemCrossAxisSize, + ), + containerCrossAxisSize = containerCrossAxisSize, + ) + } + } + + @Test + fun reverseLayout_followingItemsArePushedTowardsTheStart() { + val containerSize = ItemMainAxisSize * 2 + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LazyList(containerMainAxisSize = containerSize, reverseLayout = true) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = containerSize, + *expandingItem(mainAxis = containerSize - size, size = size), + ExpectedItem(Color.Black, mainAxis = containerSize - size - ItemMainAxisSize), + ) + } + } + + @Test + fun contentPadding_expandIsRelativeToPaddedItemPosition() { + val padding = ItemMainAxisSize / 2 + val containerMainAxisSize = ItemMainAxisSize * 2 + padding * 2 + val containerCrossAxisSize = ItemCrossAxisSize + padding * 2 + var list by mutableStateOf(emptyList<Color>()) + rule.setContent { + LazyList( + containerMainAxisSize = containerMainAxisSize, + containerCrossAxisSize = containerCrossAxisSize, + contentPadding = + with(rule.density) { + PaddingValues(mainAxis = padding.toDp(), crossAxis = padding.toDp()) + }, + ) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = containerMainAxisSize, + *expandingItem(mainAxis = padding, size = size, crossAxis = padding), + ExpectedItem(Color.Black, mainAxis = padding + size, crossAxis = padding), + containerCrossAxisSize = containerCrossAxisSize, + ) + } + } + + @Test + fun expandMainAxis_belowStickingHeader() { + assertItemExpandsBelowStickingHeader(isInLookaheadScope = false) + } + + @Test + fun inLookaheadScope_expandMainAxis_belowStickingHeader() { + assertItemExpandsBelowStickingHeader(isInLookaheadScope = true) + } + + private fun assertItemExpandsBelowStickingHeader(isInLookaheadScope: Boolean) { + val halfSize = ItemMainAxisSize / 2 + var list by mutableStateOf(listOf(Color.Blue, Color.Yellow, Color.Magenta, Color.Cyan)) + setContent(isInLookaheadScope) { + LazyList(containerMainAxisSize = ItemMainAxisSize * 3) { + stickyHeader(key = "header") { Item(Color.Black) } + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + rule.runOnIdle { runBlocking { state.scrollBy(halfSize.toFloat()) } } + + rule.runOnUiThread { + list = listOf(Color.Blue, StartColor, Color.Yellow, Color.Magenta, Color.Cyan) + } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 3, + ExpectedItem(Color.Blue, mainAxis = halfSize), + *expandingItem(mainAxis = halfSize + ItemMainAxisSize, size = size), + ExpectedItem(Color.Yellow, mainAxis = halfSize + ItemMainAxisSize + size), + ExpectedItem(Color.Magenta, mainAxis = halfSize + ItemMainAxisSize * 2 + size), + ExpectedItem(Color.Black), + ) + } + } + + @Test + fun centerArrangement_itemsAreArrangedWithTheirAnimatedSizes() { + val containerSize = ItemMainAxisSize * 4 + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + val modifier = + Modifier.requiredMainAxisSize(containerSize.toDp()) + .requiredCrossAxisSize(ItemCrossAxisSize.toDp()) + .background(Color.White) + .testTag(ContainerTag) + val content: LazyListScope.() -> Unit = { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + if (vertical) { + LazyColumn(modifier, verticalArrangement = Arrangement.Center, content = content) + } else { + LazyRow(modifier, horizontalArrangement = Arrangement.Center, content = content) + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + val start = (containerSize - size - ItemMainAxisSize) / 2 + assertItems( + containerMainAxisSize = containerSize, + *expandingItem(mainAxis = start, size = size), + ExpectedItem(Color.Black, mainAxis = start + size), + ) + } + } + + @Test + fun spacing_isNotAnimated() { + val spacing = ItemMainAxisSize / 4 + val containerSize = ItemMainAxisSize * 3 + spacing * 2 + var list by mutableStateOf(listOf(Color.Black, Color.Blue)) + rule.setContent { + LazyList(containerMainAxisSize = containerSize, spacing = spacing.toDp()) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + val itemStart = ItemMainAxisSize + spacing + assertItems( + containerMainAxisSize = containerSize, + ExpectedItem(Color.Black), + *expandingItem(mainAxis = itemStart, size = size), + ExpectedItem(Color.Blue, mainAxis = itemStart + size + spacing), + ) + } + } + + @Test + fun reverseLayout_wrapContentContainerGrows() { + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + LazyList(containerMainAxisSize = null, reverseLayout = true) { + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + val containerSize = ItemMainAxisSize + size + rule + .onNodeWithTag(ContainerTag) + .assertMainAxisSizeIsEqualTo(containerSize.toDp(), tolerance = PixelTolerance) + assertItems( + containerMainAxisSize = containerSize, + *expandingItem(size = size), + ExpectedItem(Color.Black, mainAxis = size), + ) + } + } + + @Test + fun expandCrossAxis_wrapContentContainer_itemsStayCentred() { + val otherItemCrossAxisSize = ItemCrossAxisSize / 2 + var list by mutableStateOf(listOf(Color.Blue)) + rule.setContent { + val modifier = + Modifier.requiredMainAxisSize((ItemMainAxisSize * 2).toDp()) + .background(Color.White) + .testTag(ContainerTag) + val content: LazyListScope.() -> Unit = { + items(list, key = { it.toArgb() }) { + if (it == Color.Black) { + Item(it, enter = expandCrossAxis()) + } else { + Item(it, crossAxisSize = otherItemCrossAxisSize) + } + } + } + if (vertical) { + LazyColumn( + modifier, + horizontalAlignment = Alignment.CenterHorizontally, + content = content, + ) + } else { + LazyRow(modifier, verticalAlignment = Alignment.CenterVertically, content = content) + } + } + + rule.runOnUiThread { list = listOf(Color.Blue, Color.Black) } + + onAnimationFrame { fraction -> + val itemCrossAxisSize = interpolate(0, ItemCrossAxisSize, fraction) + val containerCrossAxisSize = maxOf(otherItemCrossAxisSize, itemCrossAxisSize) + rule + .onNodeWithTag(ContainerTag) + .assertCrossAxisSizeIsEqualTo( + containerCrossAxisSize.toDp(), + tolerance = PixelTolerance, + ) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 2, + ExpectedItem( + Color.Blue, + crossAxis = (containerCrossAxisSize - otherItemCrossAxisSize) / 2, + crossAxisSize = otherItemCrossAxisSize, + ), + ExpectedItem( + Color.Black, + mainAxis = ItemMainAxisSize, + crossAxis = (containerCrossAxisSize - itemCrossAxisSize) / 2, + crossAxisSize = itemCrossAxisSize, + ), + containerCrossAxisSize = containerCrossAxisSize, + ) + } + } + + @Test + fun wrapContentContainer_wrapsItemsThatAreBeingPushedOut() { + var list by mutableStateOf(listOf(Color.Black, Color.Blue, Color.Yellow)) + val maxSize = ItemMainAxisSize * 2 + rule.setContent { + Box(Modifier.requiredMainAxisSize(maxSize.toDp()), propagateMinConstraints = false) { + LazyList(containerMainAxisSize = null) { + items(list, key = { it.toArgb() }) { + Item(it, enter = expandMainAxis(), exit = ExitTransition.None) + } + } + } + } + + rule.runOnUiThread { + list = listOf(Color.Black, Color.Red, Color.Green, Color.Blue, Color.Yellow) + } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + rule + .onNodeWithTag(ContainerTag) + .assertMainAxisSizeIsEqualTo(maxSize.toDp(), tolerance = PixelTolerance) + assertItems( + containerMainAxisSize = maxSize, + ExpectedItem(Color.Black), + ExpectedItem(Color.Red, mainAxis = ItemMainAxisSize, mainAxisSize = size), + ExpectedItem(Color.Green, mainAxis = ItemMainAxisSize + size, mainAxisSize = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size * 2), + ) + } + } + + @Test + fun rtl_expandMainAxis_followingItemsArePushedTowardsTheLeft() { + assumeTrue(!vertical) + val containerSize = ItemMainAxisSize * 2 + var list by mutableStateOf(listOf(Color.Black)) + rule.setContent { + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { + LazyList(containerMainAxisSize = containerSize) { + items(list, key = { it.toArgb() }) { + ItemOrExpandingItem(it, expandMainAxis()) + } + } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + val halfSize = ItemMainAxisSize / 2 + val boundsStart = containerSize - size + assertItems( + containerMainAxisSize = containerSize, + ExpectedItem( + StartColor, + mainAxis = maxOf(boundsStart, containerSize - halfSize), + mainAxisSize = minOf(size, halfSize), + ), + ExpectedItem( + EndColor, + mainAxis = boundsStart, + mainAxisSize = maxOf(size - halfSize, 0), + ), + ExpectedItem(Color.Black, mainAxis = boundsStart - ItemMainAxisSize), + ) + } + } + + @Test + fun expandMainAxis_belowStickyHeader() { + var list by mutableStateOf(listOf(Color.Blue)) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 3) { + stickyHeader(key = "header") { Item(Color.Black) } + items(list, key = { it.toArgb() }) { ItemOrExpandingItem(it, expandMainAxis()) } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Blue) } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 3, + ExpectedItem(Color.Black), + *expandingItem(mainAxis = ItemMainAxisSize, size = size), + ExpectedItem(Color.Blue, mainAxis = ItemMainAxisSize + size), + ) + } + } + + @Test + fun stickingHeaderAdded_expands() { + var hasHeader by mutableStateOf(false) + rule.setContent { + LazyList(containerMainAxisSize = ItemMainAxisSize * 3) { + if (hasHeader) { + stickyHeader(key = "header") { ExpandingItem(enter = expandMainAxis()) } + } + items(listOf(Color.Black, Color.Blue), key = { it.toArgb() }) { Item(it) } + } + } + + rule.runOnUiThread { hasHeader = true } + + onAnimationFrame { fraction -> + val size = interpolate(0, ItemMainAxisSize, fraction) + assertItems( + containerMainAxisSize = ItemMainAxisSize * 3, + *expandingItem(size = size), + ExpectedItem(Color.Black, mainAxis = size), + ExpectedItem(Color.Blue, mainAxis = size + ItemMainAxisSize), + ) + } + } + + @Test + fun rtl_wrapContentContainer_itemRemovedWhileAnotherExpands_disappearsWhereItWas() { + assumeTrue(!vertical) + var list by mutableStateOf(listOf(Color.Black, Color.Blue)) + rule.setContent { + CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { + LazyList(containerMainAxisSize = null) { + items(list, key = { it.toArgb() }) { + when (it) { + StartColor -> ExpandingItem(enter = expandMainAxis()) + Color.Blue -> Item(it, exit = fadeOut(SlowFadeSpec)) + else -> Item(it) + } + } + } + } + } + + rule.runOnUiThread { list = listOf(Color.Black, StartColor, Color.Blue) } + onAnimationStep(steps = Steps / 2) {} + assertThat(mainAxisRangeOf(Color.Blue)!!.first).isEqualTo(0) + + rule.runOnUiThread { list = listOf(Color.Black, StartColor) } + rule.waitForIdle() + rule.mainClock.advanceTimeByFrame() + + assertThat(mainAxisRangeOf(Color.Blue)!!.first).isEqualTo(0) + } + + @Test + fun expandWithOvershootingSpring_wrapContentContainerWithCenterArrangement_wrapsItems() { + val maxSize = ItemMainAxisSize * 4 + var list by mutableStateOf(listOf(Color.Black)) + val overshootingSpec: FiniteAnimationSpec<IntSize> = + spring(dampingRatio = 0.2f, stiffness = Spring.StiffnessMedium) + rule.setContent { + Box(Modifier.requiredMainAxisSize(maxSize.toDp()), propagateMinConstraints = false) { + val modifier = + Modifier.requiredCrossAxisSize(ItemCrossAxisSize.toDp()) + .background(Color.White) + .testTag(ContainerTag) + val content: LazyListScope.() -> Unit = { + items(list, key = { it.toArgb() }) { + ItemOrExpandingItem(it, expandMainAxis(animationSpec = overshootingSpec)) + } + } + if (vertical) { + LazyColumn( + modifier, + verticalArrangement = Arrangement.Center, + content = content, + ) + } else { + LazyRow(modifier, horizontalArrangement = Arrangement.Center, content = content) + } + } + } + + rule.runOnUiThread { list = listOf(StartColor, Color.Black) } + + var maxContainerSize = 0 + var containerSize = 0 + onAnimationStep(steps = 80) { + val image = rule.onNodeWithTag(ContainerTag).captureToImage() + containerSize = if (vertical) image.height else image.width + maxContainerSize = maxOf(maxContainerSize, containerSize) + val blackRange = mainAxisRangeOf(Color.Black)!! + assertThat(blackRange.last + 1).isEqualTo(containerSize) + assertThat(blackRange.first).isEqualTo(containerSize - ItemMainAxisSize) + val contentEnd = mainAxisRangeOf(EndColor)?.last + if (contentEnd != null) assertThat(blackRange.first).isEqualTo(contentEnd + 1) + } + assertThat(maxContainerSize).isGreaterThan(ItemMainAxisSize * 2) + assertThat(containerSize).isEqualTo(ItemMainAxisSize * 2) + } + + private var config = ListConfig() + + private val animatedState = LazyListState() + private val plainState = LazyListState() + + private val composedKeys = mutableSetOf<Int>() + + private val plainComposedKeys = mutableSetOf<Int>() + + private val placedPositions = mutableMapOf<Int, Int>() + + private var items by mutableStateOf(emptyList<Int>()) + + @Test + fun manyItemsAddedToEmptyList() { + setScrollingContent(initialItems = emptyList()) + + changeItems { NewItems } + + onEachFrame { assertLayout() } + assertAtRest() + } + + @Test + fun manyItemsAddedInFullList_allAddedItemsExpand() { + setScrollingContent(initialItems = List(20) { it }) + val keysBefore = rule.runOnIdle { visibleItems().map { it.key } } + + changeItems { it.take(1) + NewItems + it.drop(1) } + + var isFirstFrame = true + onEachFrame { + assertLayout() + if (isFirstFrame) { + val addedItems = visibleItems().filter { (it.key as Int) >= FirstNewItem } + assertThat(addedItems).isNotEmpty() + assertWithMessage("Added items that are not expanding") + .that(addedItems.filter { it.size == ScrollingItemSize }.map { it.key }) + .isEmpty() + if (config.spacing <= 0) { + assertWithMessage("Added items") + .that(addedItems.map { it.key }) + .isEqualTo(NewItems) + assertWithMessage("Existing items") + .that(visibleItems().map { it.key }) + .containsAtLeastElementsIn(keysBefore) + } + isFirstFrame = false + } + } + assertAtRest() + } + + @Test + fun manyItemsAddedBeforeShortList_addedItemsFillTheViewport() { + setScrollingContent(initialItems = listOf(0, 1)) + + changeItems { NewItems + it } + + onEachFrame { assertLayout() } + assertAtRest(isSameAsPlainList = false) + } + + @Test + fun manyItemsAddedAfterShortList() { + setScrollingContent(initialItems = listOf(0, 1)) + + changeItems { it + NewItems } + + onEachFrame { assertLayout() } + assertAtRest() + } + + @Test + fun allItemsReplaced_listScrollsBackWhileNewItemsAreTooSmallToFillIt() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 3 + ScrollingItemSize / 4) + + changeItems { NewItems } + + onEachFrame { assertLayout() } + assertAtRest(isSameAsPlainList = config.spacing > 0) + if (config.spacing <= 0) { + rule.runOnIdle { + assertThat(animatedState.firstVisibleItemIndex).isEqualTo(0) + assertThat(animatedState.firstVisibleItemScrollOffset).isEqualTo(0) + } + } + } + + @Test + fun itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() { + setScrollingContent(initialItems = listOf(0, 1)) + val offsetBefore = rule.runOnIdle { visibleItem(0)!!.offset } + + changeItems { listOf(100, 101, 102) + it } + + var previousOffset = offsetBefore + var isFirstFrame = true + onEachFrame { + assertLayout() + val offset = visibleItem(0)!!.offset + if (isFirstFrame && config.spacing == 0) { + assertWithMessage("Offset of the first existing item in the first frame") + .that(offset) + .isEqualTo(offsetBefore) + } + isFirstFrame = false + assertWithMessage("Offset of the first existing item") + .that(offset) + .isAtLeast(previousOffset) + previousOffset = offset + } + assertWithMessage("Offset the first existing item was pushed to") + .that(previousOffset) + .isGreaterThan(offsetBefore) + assertAtRest(isSameAsPlainList = fitsInViewport(itemCount = 5)) + } + + @Test + fun itemsAddedBeforeAndAfterShortList_existingItemIsOnlyPushedAway() { + setScrollingContent(initialItems = listOf(0)) + val offsetBefore = rule.runOnIdle { visibleItem(0)!!.offset } + + changeItems { listOf(100, 101) + it + listOf(103, 104) } + + var previousOffset = offsetBefore + onEachFrame { + assertLayout() + val offset = visibleItem(0)!!.offset + assertWithMessage("Offset of the existing item").that(offset).isAtLeast(previousOffset) + previousOffset = offset + } + assertAtRest(isSameAsPlainList = fitsInViewport(itemCount = 5)) + } + + @Test + fun itemsAddedInFullList_followingItemsStayUntilTheyArePushedOut() { + setScrollingContent(initialItems = List(20) { it }) + val keysBefore = rule.runOnIdle { visibleItems().map { it.key } } + + changeItems { it.take(2) + 100 + 101 + it.drop(2) } + + var isFirstFrame = true + onEachFrame { + assertLayout() + val visibleKeys = visibleItems().map { it.key } + assertThat(visibleKeys).containsAtLeast(100, 101) + val existingKeys = visibleKeys.filter { (it as Int) < FirstNewItem } + assertWithMessage("Existing items that are visible") + .that(existingKeys) + .isEqualTo(keysBefore.take(existingKeys.size)) + if (isFirstFrame) { + assertWithMessage("Existing items that are visible in the first frame") + .that(existingKeys) + .isEqualTo(keysBefore) + isFirstFrame = false + } + } + assertAtRest() + } + + @Test + fun itemAddedBeforeShortList() { + setScrollingContent(initialItems = listOf(0, 1)) + + changeItems { listOf(100) + it } + + onEachFrame { assertLayout() } + assertAtRest() + } + + @Test + fun itemsAddedBeforeListThatThenOverflows_addedItemsFillTheViewport() { + setScrollingContent(initialItems = listOf(0, 1, 2)) + + changeItems { listOf(100, 101, 102, 103) + it } + + onEachFrame { assertLayout() } + assertAtRest(isSameAsPlainList = false) + rule.runOnIdle { + assertThat(animatedState.firstVisibleItemIndex).isEqualTo(0) + assertThat(animatedState.firstVisibleItemScrollOffset).isEqualTo(0) + } + } + + @Test + fun itemAddedAfterShortList() { + setScrollingContent(initialItems = listOf(0, 1)) + + changeItems { it + 100 } + + onEachFrame { assertLayout() } + assertAtRest() + } + + @Test + fun itemAddedInScrolledList() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 3 + ScrollingItemSize / 4) + + changeItems { it.take(5) + 100 + it.drop(5) } + + var wasExpanding = false + onEachFrame { + assertLayout() + if (visibleItem(100)!!.size in 1 until ScrollingItemSize) wasExpanding = true + } + assertThat(wasExpanding).isTrue() + assertAtRest() + } + + @Test + fun firstVisibleItemReplacedInScrolledList_newItemHasItsFullSize() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 3 + ScrollingItemSize / 4) + val firstKey = rule.runOnIdle { items[animatedState.firstVisibleItemIndex] } + + changeItems { items -> items.map { if (it == firstKey) 100 else it } } + + onEachFrame { + assertLayout() + assertSameLayoutInfoAsPlainList() + } + assertAtRest() + } + + @Test + fun firstVisibleItemReplacedInListScrolledToItsStart_newItemExpands() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy((ScrollingItemSize + config.spacing) * 3) + + changeItems { items -> items.map { if (it == 3) 100 else it } } + + var wasExpanding = false + onEachFrame { + assertLayout() + val item = visibleItem(100) + assertWithMessage("The new first item should be laid out").that(item).isNotNull() + if (item!!.size in 1 until ScrollingItemSize) wasExpanding = true + } + assertThat(wasExpanding).isTrue() + assertAtRest() + } + + @Test + fun itemAddedAtEndOfListScrolledToEnd() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 20) + + changeItems { it + 100 } + + onEachFrame { + assertLayout() + assertSameLayoutInfoAsPlainList() + } + assertAtRest() + } + + @Test + fun itemAddedInsideViewportOfListScrolledToEnd_newItemHasItsFullSize() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 20) + + changeItems { it.dropLast(2) + 100 + it.takeLast(2) } + + onEachFrame { + assertLayout() + assertSameLayoutInfoAsPlainList() + } + } + + @Test + fun itemAddedInsideViewportOfListOnePixelBeforeItsEnd_newItemExpands() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 20) + scrollBothBy(-1) + + changeItems { it.dropLast(2) + 100 + it.takeLast(2) } + + var wasExpanding = false + onEachFrame { + assertLayout() + if (visibleItem(100)!!.size in 1 until ScrollingItemSize) wasExpanding = true + } + assertThat(wasExpanding).isTrue() + assertAtRest() + } + + @Test + fun itemsRemovedAndItemAddedAtEndOfListScrolledToEnd_newItemHasItsFullSize() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 20) + + changeItems { it.dropLast(2) + 100 } + + onEachFrame { + assertLayout() + assertSameLayoutInfoAsPlainList() + } + assertAtRest() + } + + @Test + fun lastItemReplacedInListScrolledToEnd_newItemHasItsFullSize() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 20) + + changeItems { it.dropLast(1) + 100 } + + onEachFrame { + assertLayout() + assertSameLayoutInfoAsPlainList() + } + assertAtRest() + } + + @Test + fun itemsChangedAgainWhileExpanding() { + setScrollingContent(initialItems = List(20) { it }) + + changeItems { it.take(2) + 100 + it.drop(2) } + advanceToMiddleOfExpand { assertLayout() } + changeItems { items -> listOf(101) + items.filter { it != 1 } + 102 } + + onEachFrame { assertLayout() } + assertAtRest(isSameAsPlainList = config.contentPadding == 0 && config.spacing >= 0) + } + + @Test + fun itemsChangedAgainAfterExpanding() { + setScrollingContent(initialItems = listOf(0, 1)) + + changeItems { listOf(100) + it } + onEachFrame { assertLayout() } + assertAtRest() + changeItems { listOf(101, 102) + it } + + onEachFrame { assertLayout() } + assertAtRest(isSameAsPlainList = fitsInViewport(itemCount = 5)) + } + + @Test + fun expandingItemRemoved() { + setScrollingContent(initialItems = List(20) { it }) + + changeItems { it.take(2) + 100 + it.drop(2) } + advanceToMiddleOfExpand { assertLayout() } + changeItems { items -> items.filter { it != 100 } } + + onEachFrame { assertLayout() } + assertAtRest() + } + + @Test + fun scrollingForwardWhileExpanding_itemsReachedByScrollingHaveTheirFullSize() { + setScrollingContent(initialItems = List(20) { it }) + changeItems { it.take(1) + NewItems + it.drop(1) } + advanceToMiddleOfExpand { assertLayout() } + val keysBefore = rule.runOnIdle { visibleItems().map { it.key } } + + scrollBothBy(ScrollingItemSize * 2, clearComposedKeys = false) + + if (!config.usesPlacementSpec) { + rule.runOnIdle { + val reached = visibleItems().filter { it.key !in keysBefore } + reached.forEach { + assertWithMessage("Size of item ${it.key}") + .that(it.size) + .isEqualTo(ScrollingItemSize) + } + } + } + onEachFrame { assertLayout() } + assertAtRest(isSameAsPlainList = false) + } + + @Test + fun scrollingBackwardWhileExpanding() { + setScrollingContent(initialItems = List(20) { it }) + scrollBothBy(ScrollingItemSize * 3 + ScrollingItemSize / 4) + changeItems { it.take(5) + 100 + 101 + it.drop(5) } + advanceToMiddleOfExpand { assertLayout() } + + scrollBothBy(-(ScrollingItemSize + ScrollingItemSize / 2), clearComposedKeys = false) + + onEachFrame { assertLayout() } + assertAtRest() + } + + @Test + fun scrollingToItemWhileExpanding() { + setScrollingContent(initialItems = List(20) { it }) + changeItems { it.take(1) + NewItems + it.drop(1) } + advanceToMiddleOfExpand { assertLayout() } + + rule.runOnUiThread { + runBlocking { + animatedState.scrollToItem(10, ScrollingItemSize / 4) + plainState.scrollToItem(10, ScrollingItemSize / 4) + } + } + rule.mainClock.advanceTimeByFrame() + + onEachFrame { assertLayout() } + assertAtRest() + } + + @Test + fun itemAddedWhileItemAnimationsAreSkipped_appearsAtItsFullSize() { + setScrollingContent(initialItems = List(20) { it }) + + rule.runOnUiThread { animatedState.skipItemPlacementAnimation = true } + changeItems { it.take(2) + 100 + it.drop(2) } + + onEachFrame { + assertSameLayoutInfoAsPlainList() + assertThat(visibleItem(100)!!.size).isEqualTo(ScrollingItemSize) + } + } + + @Test + fun inLookaheadScope_manyItemsAddedInFullList_allAddedItemsExpand() { + config = ListConfig(isInLookaheadScope = true) + manyItemsAddedInFullList_allAddedItemsExpand() + } + + @Test + fun inLookaheadScope_itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() { + config = ListConfig(isInLookaheadScope = true) + itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() + } + + @Test + fun inLookaheadScope_itemAddedInScrolledList() { + config = ListConfig(isInLookaheadScope = true) + itemAddedInScrolledList() + } + + @Test + fun inLookaheadScope_itemsChangedAgainWhileExpanding() { + config = ListConfig(isInLookaheadScope = true) + itemsChangedAgainWhileExpanding() + } + + @Test + fun inLookaheadScope_scrollingBackwardWhileExpanding() { + config = ListConfig(isInLookaheadScope = true) + scrollingBackwardWhileExpanding() + } + + @Test + fun reverseLayout_manyItemsAddedInFullList_allAddedItemsExpand() { + config = ListConfig(reverseLayout = true) + manyItemsAddedInFullList_allAddedItemsExpand() + } + + @Test + fun reverseLayout_itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() { + config = ListConfig(reverseLayout = true) + itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() + } + + @Test + fun reverseLayout_itemAddedInScrolledList() { + config = ListConfig(reverseLayout = true) + itemAddedInScrolledList() + } + + @Test + fun reverseLayout_itemsChangedAgainWhileExpanding() { + config = ListConfig(reverseLayout = true) + itemsChangedAgainWhileExpanding() + } + + @Test + fun reverseLayout_scrollingBackwardWhileExpanding() { + config = ListConfig(reverseLayout = true) + scrollingBackwardWhileExpanding() + } + + @Test + fun contentPadding_manyItemsAddedInFullList_allAddedItemsExpand() { + config = ListConfig(contentPadding = ScrollingItemSize / 2) + manyItemsAddedInFullList_allAddedItemsExpand() + } + + @Test + fun contentPadding_itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() { + config = ListConfig(contentPadding = ScrollingItemSize / 2) + itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() + } + + @Test + fun contentPadding_itemAddedInScrolledList() { + config = ListConfig(contentPadding = ScrollingItemSize / 2) + itemAddedInScrolledList() + } + + @Test + fun contentPadding_itemsChangedAgainWhileExpanding() { + config = ListConfig(contentPadding = ScrollingItemSize / 2) + itemsChangedAgainWhileExpanding() + } + + @Test + fun contentPadding_scrollingBackwardWhileExpanding() { + config = ListConfig(contentPadding = ScrollingItemSize / 2) + scrollingBackwardWhileExpanding() + } + + @Test + fun spacing_manyItemsAddedInFullList_allAddedItemsExpand() { + config = ListConfig(spacing = 4) + manyItemsAddedInFullList_allAddedItemsExpand() + } + + @Test + fun spacing_itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() { + config = ListConfig(spacing = 4) + itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() + } + + @Test + fun spacing_itemAddedInScrolledList() { + config = ListConfig(spacing = 4) + itemAddedInScrolledList() + } + + @Test + fun spacing_itemsChangedAgainWhileExpanding() { + config = ListConfig(spacing = 4) + itemsChangedAgainWhileExpanding() + } + + @Test + fun spacing_scrollingBackwardWhileExpanding() { + config = ListConfig(spacing = 4) + scrollingBackwardWhileExpanding() + } + + @Test + fun negativeSpacing_manyItemsAddedInFullList_allAddedItemsExpand() { + config = ListConfig(spacing = -4) + manyItemsAddedInFullList_allAddedItemsExpand() + } + + @Test + fun negativeSpacing_itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() { + config = ListConfig(spacing = -4) + itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() + } + + @Test + fun negativeSpacing_itemAddedInScrolledList() { + config = ListConfig(spacing = -4) + itemAddedInScrolledList() + } + + @Test + fun negativeSpacing_itemsChangedAgainWhileExpanding() { + config = ListConfig(spacing = -4) + itemsChangedAgainWhileExpanding() + } + + @Test + fun negativeSpacing_scrollingBackwardWhileExpanding() { + config = ListConfig(spacing = -4) + scrollingBackwardWhileExpanding() + } + + @Test + fun placementSpec_manyItemsAddedInFullList_allAddedItemsExpand() { + config = ListConfig(usesPlacementSpec = true) + manyItemsAddedInFullList_allAddedItemsExpand() + } + + @Test + fun placementSpec_itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() { + config = ListConfig(usesPlacementSpec = true) + itemsAddedBeforeShortList_existingItemsAreOnlyPushedAway() + } + + @Test + fun placementSpec_itemAddedInScrolledList() { + config = ListConfig(usesPlacementSpec = true) + itemAddedInScrolledList() + } + + @Test + fun placementSpec_itemsChangedAgainWhileExpanding() { + config = ListConfig(usesPlacementSpec = true) + itemsChangedAgainWhileExpanding() + } + + @Test + fun placementSpec_scrollingBackwardWhileExpanding() { + config = ListConfig(usesPlacementSpec = true) + scrollingBackwardWhileExpanding() + } + + private fun setScrollingContent(initialItems: List<Int>) { + items = initialItems + rule.setContent { + val content = + @Composable { + Column { + TestList(animatedState, isAnimated = true) + TestList(plainState, isAnimated = false) + } + } + if (config.isInLookaheadScope) LookaheadScope { content() } else content() + } + rule.runOnIdle { clearComposedKeys() } + } + + private fun clearComposedKeys() { + composedKeys.clear() + plainComposedKeys.clear() + } + + @OptIn(ExperimentalFoundationApi::class) + @Composable + private fun TestList(state: LazyListState, isAnimated: Boolean) { + val density = rule.density + LazyColumnOrRow( + state = state, + reverseLayout = config.reverseLayout, + contentPadding = + with(density) { PaddingValues(mainAxis = config.contentPadding.toDp()) }, + spacedBy = with(density) { config.spacing.toDp() }, + cacheWindow = + LazyLayoutCacheWindow( + behindFraction = 0f, + aheadFraction = 0f, + isNonScrollCachingEnabled = false, + ), + modifier = + Modifier.requiredMainAxisSize(with(density) { ScrollingViewportSize.toDp() }), + ) { + items(items, key = { it }) { key -> + SideEffect { (if (isAnimated) composedKeys else plainComposedKeys).add(key) } + Box( + Modifier.then( + if (isAnimated) { + Modifier.onPlaced { + val position = + it.parentLayoutCoordinates!!.localPositionOf(it) + placedPositions[key] = + (if (vertical) position.y else position.x).roundToInt() + } + .animateItemWithTransitions( + enterTransition = expandMainAxis(ExpandSpec), + exitTransition = null, + placementSpec = + if (config.usesPlacementSpec) SlowPlacementSpec + else null, + ) + } else { + Modifier + } + ) + .requiredMainAxisSize(with(density) { ScrollingItemSize.toDp() }) + .requiredCrossAxisSize(with(density) { ScrollingItemSize.toDp() }) + ) + } + } + } + + private fun changeItems(change: (List<Int>) -> List<Int>) { + rule.runOnUiThread { + clearComposedKeys() + items = change(items) + } + } + + private fun scrollBothBy(distance: Int, clearComposedKeys: Boolean = true) { + rule.runOnUiThread { + runBlocking { + animatedState.scrollBy(distance.toFloat()) + plainState.scrollBy(distance.toFloat()) + } + } + rule.mainClock.advanceTimeByFrame() + rule.runOnIdle { if (clearComposedKeys) clearComposedKeys() } + } + + private fun onEachFrame(onFrame: () -> Unit) { + rule.waitForIdle() + rule.mainClock.advanceTimeByFrame() + repeat(Steps * 2 + 4) { + rule.runOnIdle(onFrame) + rule.mainClock.advanceTimeBy(FrameDuration) + } + } + + private fun advanceToMiddleOfExpand(onFrame: () -> Unit) { + rule.waitForIdle() + rule.mainClock.advanceTimeByFrame() + repeat(Steps / 2) { + rule.runOnIdle(onFrame) + rule.mainClock.advanceTimeBy(FrameDuration) + } + rule.runOnIdle(onFrame) + } + + private fun fitsInViewport(itemCount: Int) = + itemCount * (ScrollingItemSize + config.spacing) - config.spacing <= + ScrollingViewportSize - config.contentPadding * 2 + + private fun visibleItems(): List<LazyListItemInfo> = animatedState.layoutInfo.visibleItemsInfo + + private fun visibleItem(key: Int): LazyListItemInfo? = + visibleItems().firstOrNull { it.key == key } + + private fun assertLayout() { + assertVisibleItemsFollowEachOther() + assertVisibleItemsFillViewport() + if (!config.usesPlacementSpec) assertItemsArePlacedWhereTheyAreLaidOut() + } + + private fun assertItemsArePlacedWhereTheyAreLaidOut() { + visibleItems().forEach { + val boundsStart = + if (config.reverseLayout) { + ScrollingViewportSize - config.contentPadding - it.offset - it.size + } else { + config.contentPadding + it.offset + } + assertWithMessage("Position of item ${it.key}") + .that(placedPositions[it.key]) + .isEqualTo(boundsStart + it.size - ScrollingItemSize) + } + } + + private fun assertVisibleItemsFillViewport() { + val visible = visibleItems() + val layoutInfo = animatedState.layoutInfo + val last = visible.last() + if (last.index < items.lastIndex) { + assertWithMessage("End of the visible items, the last of which has key ${last.key}") + .that(last.offset + last.size + config.spacing) + .isAtLeast(layoutInfo.viewportEndOffset) + } + val first = visible.first() + if (first.index > 0) { + assertWithMessage("Start of the visible items, the first of which has key ${first.key}") + .that(first.offset) + .isAtMost(layoutInfo.viewportStartOffset) + } + } + + private fun assertSameLayoutInfoAsPlainList() { + val animated = animatedState.layoutInfo + val plain = plainState.layoutInfo + assertWithMessage("Visible items") + .that(animated.visibleItemsInfo.map { it.describe() }) + .isEqualTo(plain.visibleItemsInfo.map { it.describe() }) + assertWithMessage("First visible item index") + .that(animatedState.firstVisibleItemIndex) + .isEqualTo(plainState.firstVisibleItemIndex) + assertWithMessage("First visible item scroll offset") + .that(animatedState.firstVisibleItemScrollOffset) + .isEqualTo(plainState.firstVisibleItemScrollOffset) + assertWithMessage("Can scroll forward") + .that(animatedState.canScrollForward) + .isEqualTo(plainState.canScrollForward) + assertWithMessage("Can scroll backward") + .that(animatedState.canScrollBackward) + .isEqualTo(plainState.canScrollBackward) + } + + private fun assertVisibleItemsFollowEachOther() { + val visible = visibleItems() + assertThat(visible).isNotEmpty() + visible.forEach { + val minSize = if (it.index == items.lastIndex) 0 else maxOf(-config.spacing, 0) + assertWithMessage("Size of item ${it.key}") + .that(it.size) + .isIn(minSize..ScrollingItemSize) + } + visible.zipWithNext { item, next -> + assertWithMessage("Index of the item after item ${item.key}") + .that(next.index) + .isEqualTo(item.index + 1) + assertWithMessage("Offset of item ${next.key}, after item ${item.key}") + .that(next.offset) + .isEqualTo(item.offset + item.size + config.spacing) + } + } + + private fun assertAtRest(isSameAsPlainList: Boolean = true) { + if (config.usesPlacementSpec) { + repeat(Steps * 4) { rule.mainClock.advanceTimeBy(FrameDuration) } + } + rule.runOnIdle { + assertVisibleItemsFollowEachOther() + assertVisibleItemsFillViewport() + assertItemsArePlacedWhereTheyAreLaidOut() + visibleItems().forEach { + assertWithMessage("Size of item ${it.key}") + .that(it.size) + .isEqualTo(ScrollingItemSize) + } + if (isSameAsPlainList) assertSameLayoutInfoAsPlainList() + val visibleKeys = visibleItems().map { it.key } + items.forEach { key -> + val animation = animatedState.itemAnimator.getAnimation(key, 0) + if (key in visibleKeys) { + assertWithMessage("Animation of visible item $key").that(animation).isNotNull() + } else { + assertWithMessage("Animation of item $key").that(animation).isNull() + } + } + } + } + + private fun LazyListItemInfo.describe() = "key $key, index $index at $offset, size $size" + + private fun expandCrossAxis(): EnterTransition = + if (vertical) { + expandHorizontally(ExpandSpec, initialWidth = { 0 }) + } else { + expandVertically(ExpandSpec, initialHeight = { 0 }) + } + + @Composable + private fun LazyItemScope.ItemOrExpandingItem(color: Color, expand: EnterTransition) { + if (color == StartColor) ExpandingItem(enter = expand) else Item(color) + } + + @Composable + private fun LazyItemScope.ExpandingItem( + enter: EnterTransition? = null, + exit: ExitTransition? = null, + modifier: Modifier = Modifier, + ) { + val density = rule.density + Box( + modifier + .animateItemWithTransitions( + enterTransition = enter, + exitTransition = exit, + placementSpec = null, + ) + .requiredMainAxisSize(with(density) { ItemMainAxisSize.toDp() }) + .requiredCrossAxisSize(with(density) { ItemCrossAxisSize.toDp() }) + ) { + if (vertical) { + Column(Modifier.fillMaxSize()) { + Box(Modifier.weight(1f).fillMaxWidth().background(StartColor)) + Box(Modifier.weight(1f).fillMaxWidth().background(EndColor)) + } + } else { + Row(Modifier.fillMaxSize()) { + Box(Modifier.weight(1f).fillMaxHeight().background(StartColor)) + Box(Modifier.weight(1f).fillMaxHeight().background(EndColor)) + } + } + } + } + + private fun expandingItem( + mainAxis: Int = 0, + size: Int, + alignToEnd: Boolean = true, + clip: Boolean = true, + crossAxis: Int = 0, + startColor: Color = StartColor, + endColor: Color = EndColor, + ): Array<ExpectedItem> { + val contentStart = if (alignToEnd) mainAxis + size - ItemMainAxisSize else mainAxis + val halfSize = ItemMainAxisSize / 2 + fun part(color: Color, start: Int, end: Int): ExpectedItem? { + val visibleStart = if (clip) maxOf(start, mainAxis) else start + val visibleEnd = if (clip) minOf(end, mainAxis + size) else end + return if (visibleEnd > visibleStart) { + ExpectedItem( + color, + mainAxis = visibleStart, + crossAxis = crossAxis, + mainAxisSize = visibleEnd - visibleStart, + ) + } else { + null + } + } + return listOfNotNull( + part(startColor, contentStart, contentStart + halfSize), + part(endColor, contentStart + halfSize, contentStart + ItemMainAxisSize), + ) + .toTypedArray() + } + + private fun Int.toDp(): Dp = with(rule.density) { this@toDp.toDp() } + + @Composable + private fun ItemWithoutItemAnimations(color: Color, onComposed: () -> Unit) { + remember { onComposed() } + Box( + Modifier.background(color) + .requiredMainAxisSize(ItemMainAxisSize.toDp()) + .requiredCrossAxisSize(ItemCrossAxisSize.toDp()) + ) + } + + private fun setContent(isInLookaheadScope: Boolean, content: @Composable () -> Unit) { + rule.setContent { if (isInLookaheadScope) LookaheadScope { content() } else content() } + } + + private fun mainAxisRangeOf(color: Color): IntRange? { + val pixels = rule.onNodeWithTag(ContainerTag).captureToImage().toPixelMap() + val crossAxis = ItemCrossAxisSize / 2 + var first = -1 + var last = -1 + for (mainAxis in 0 until if (vertical) pixels.height else pixels.width) { + val pixel = if (vertical) pixels[crossAxis, mainAxis] else pixels[mainAxis, crossAxis] + if (pixel == color) { + if (first == -1) first = mainAxis + last = mainAxis + } + } + return if (first == -1) null else first..last + } + + private fun crossAxisRangeOf(color: Color): IntRange? { + val pixels = rule.onNodeWithTag(ContainerTag).captureToImage().toPixelMap() + val mainAxis = ItemMainAxisSize / 2 + var first = -1 + var last = -1 + for (crossAxis in 0 until if (vertical) pixels.width else pixels.height) { + val pixel = if (vertical) pixels[crossAxis, mainAxis] else pixels[mainAxis, crossAxis] + if (pixel == color) { + if (first == -1) first = crossAxis + last = crossAxis + } + } + return if (first == -1) null else first..last + } + + @Composable + private fun PinItem() { + val container = LocalPinnableContainer.current + DisposableEffect(container) { + val handle = container?.pin() + onDispose { handle?.release() } + } + } + + private fun Modifier.onMainAxisPositionInList(onPosition: (Int) -> Unit): Modifier = + onPlaced { coordinates -> + val position = coordinates.parentLayoutCoordinates!!.localPositionOf(coordinates) + onPosition((if (vertical) position.y else position.x).roundToInt()) + } + + private val PixelTolerance: Dp + get() = with(rule.density) { 0.5f.toDp() } + + @Composable + private fun LazyList( + containerMainAxisSize: Int?, + containerCrossAxisSize: Int? = ItemCrossAxisSize, + reverseLayout: Boolean = false, + contentPadding: PaddingValues = PaddingValues(0.dp), + beyondBoundsItemCount: Int? = null, + spacing: Dp = 0.dp, + content: LazyListScope.() -> Unit, + ) { + state = rememberLazyListState() + val density = rule.density + val modifier = + Modifier.then( + if (containerMainAxisSize != null) { + Modifier.requiredMainAxisSize( + with(density) { containerMainAxisSize.toDp() } + ) + } else { + Modifier + } + ) + .then( + if (containerCrossAxisSize != null) { + Modifier.requiredCrossAxisSize( + with(density) { containerCrossAxisSize.toDp() } + ) + } else { + Modifier + } + ) + .background(Color.White) + .testTag(ContainerTag) + if (beyondBoundsItemCount == null) { + LazyColumnOrRow( + state = state, + contentPadding = contentPadding, + reverseLayout = reverseLayout, + spacedBy = spacing, + modifier = modifier, + content = content, + ) + } else { + LazyColumnOrRow( + state = state, + contentPadding = contentPadding, + reverseLayout = reverseLayout, + spacedBy = spacing, + beyondBoundsItemCount = beyondBoundsItemCount, + modifier = modifier, + content = content, + ) + } + } + + private fun expandMainAxis( + animationSpec: TweenSpec<IntSize> = ExpandSpec, + fromEnd: Boolean = true, + clip: Boolean = true, + initialSize: (fullSize: Int) -> Int = { 0 }, + ) = + this.expandMainAxis( + animationSpec = animationSpec as FiniteAnimationSpec<IntSize>, + fromEnd = fromEnd, + clip = clip, + initialSize = initialSize, + ) + + private val ExpandSpec = tween<IntSize>(DurationMillis, easing = LinearEasing) + private val FadeSpec = tween<Float>(DurationMillis, easing = LinearEasing) + private val SlowFadeSpec = tween<Float>(DurationMillis * 4, easing = LinearEasing) + private val SlowPlacementSpec = tween<IntOffset>(DurationMillis * 2, easing = LinearEasing) + + private class ListConfig( + val reverseLayout: Boolean = false, + val contentPadding: Int = 0, + val spacing: Int = 0, + val usesPlacementSpec: Boolean = false, + val isInLookaheadScope: Boolean = false, + ) + + companion object { + private const val ScrollingItemSize = 20 + private const val ScrollingViewportSize = 110 + + private const val FirstNewItem = 100 + private val NewItems = List(40) { FirstNewItem + it } + + private val StartColor = Color.Red + private val EndColor = Color.Green + private val PaddingColor = Color.Blue + + @JvmStatic + @Parameterized.Parameters(name = "{0}") + fun params() = arrayOf(Orientation.Vertical, Orientation.Horizontal) + } +}
diff --git a/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextContextMenuToolbarTest.kt b/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextContextMenuToolbarTest.kt index 4a5356f..5e27e99 100644 --- a/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextContextMenuToolbarTest.kt +++ b/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextContextMenuToolbarTest.kt
@@ -35,9 +35,15 @@ import androidx.compose.foundation.text.FocusedWindowTest import androidx.compose.foundation.text.Handle import androidx.compose.foundation.text.TEST_FONT_FAMILY +import androidx.compose.foundation.text.contextmenu.data.TextContextMenuItem +import androidx.compose.foundation.text.contextmenu.data.TextContextMenuKeys +import androidx.compose.foundation.text.contextmenu.data.TextContextMenuSession import androidx.compose.foundation.text.contextmenu.internal.ProvidePlatformTextContextMenuToolbar +import androidx.compose.foundation.text.contextmenu.provider.LocalTextContextMenuToolbarProvider +import androidx.compose.foundation.text.contextmenu.provider.TextContextMenuDataProvider import androidx.compose.foundation.text.contextmenu.test.ContextMenuFlagFlipperRunner import androidx.compose.foundation.text.contextmenu.test.ContextMenuFlagSuppress +import androidx.compose.foundation.text.contextmenu.test.FakeTextContextMenuProvider import androidx.compose.foundation.text.contextmenu.test.SpyTextActionModeCallback import androidx.compose.foundation.text.contextmenu.test.assertNotNull import androidx.compose.foundation.text.contextmenu.test.assertShown @@ -53,6 +59,7 @@ import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester @@ -348,6 +355,73 @@ assertTextToolbarHasItem(AUTOFILL) } + // Regression test for b/481087608 + @SdkSuppress(minSdkVersion = 26) + @Test + fun autofillItemClick_afterTextFieldRemoved_doesNotCrash() = + runTest(readOnly = false) { + clickOffset(2) + Handle.Cursor.click() + assertTextToolbarHasItem(AUTOFILL) + val autofillItem = rule.runOnIdle { + assertNotNull(latestDataProvider) + .data() + .components + .filterIsInstance<TextContextMenuItem>() + .single { it.key == TextContextMenuKeys.AutofillKey } + } + + showTextField = false + assertTextToolbarNotShown() + + var sessionClosed = false + val session = + object : TextContextMenuSession { + override fun close() { + sessionClosed = true + } + } + // Invoke the pre-detach item directly (matching a queued FloatingToolbar button click) + // because onPrepareActionMode may have already cleared MenuBuilder by id. + rule.runOnUiThread { autofillItem.onClick(session) } + assertThat(sessionClosed).isTrue() + } + + // Regression test for b/481087608 + @SdkSuppress(minSdkVersion = 26) + @Test + fun autofillItemClick_afterTextFieldStateSwappedAndRemoved_doesNotCrash() = + runTest(readOnly = false) { + clickOffset(2) + Handle.Cursor.click() + assertTextToolbarHasItem(AUTOFILL) + val autofillItem = rule.runOnIdle { + assertNotNull(latestDataProvider) + .data() + .components + .filterIsInstance<TextContextMenuItem>() + .single { it.key == TextContextMenuKeys.AutofillKey } + } + + textFieldState = TextFieldState("World") + assertTextToolbarNotShown() + + showTextField = false + assertTextToolbarNotShown() + + var sessionClosed = false + val session = + object : TextContextMenuSession { + override fun close() { + sessionClosed = true + } + } + // Invoke the pre-swap item directly (matching a queued FloatingToolbar button click) + // because onPrepareActionMode may have already cleared MenuBuilder by id. + rule.runOnUiThread { autofillItem.onClick(session) } + assertThat(sessionClosed).isTrue() + } + @Test fun toolbarDoesNotShowSelectAll_whenAllTextIsAlreadySelected() = runTest(singleLine = true) { @@ -728,6 +802,7 @@ private lateinit var view: View val spyTextActionModeCallback = SpyTextActionModeCallback() + var latestDataProvider: TextContextMenuDataProvider? = null init { rule.setTextFieldTestContent { @@ -736,7 +811,20 @@ ProvidePlatformTextContextMenuToolbar( callbackInjector = { spyTextActionModeCallback.apply { delegate = it } } ) { + val platformToolbarProvider = + checkNotNull(LocalTextContextMenuToolbarProvider.current) + val recordingToolbarProvider = + remember(platformToolbarProvider) { + FakeTextContextMenuProvider { dataProvider -> + latestDataProvider = dataProvider + platformToolbarProvider.showTextContextMenu(dataProvider) + } + } val providedValues = buildList { + add( + LocalTextContextMenuToolbarProvider provides + recordingToolbarProvider + ) add(LocalClipboard provides clipboard) inputMode?.let { targetInputMode -> add(
diff --git a/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextToolbarTest.kt b/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextToolbarTest.kt index 0204bc0..62df9ab 100644 --- a/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextToolbarTest.kt +++ b/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/input/internal/selection/TextFieldTextToolbarTest.kt
@@ -37,6 +37,7 @@ import androidx.compose.foundation.text.TEST_FONT_FAMILY import androidx.compose.foundation.text.contextmenu.test.ContextMenuFlagFlipperRunner import androidx.compose.foundation.text.contextmenu.test.ContextMenuFlagSuppress +import androidx.compose.foundation.text.contextmenu.test.assertNotNull import androidx.compose.foundation.text.input.InputTransformation import androidx.compose.foundation.text.input.TextFieldLineLimits import androidx.compose.foundation.text.input.TextFieldState @@ -121,6 +122,8 @@ private var enabled by mutableStateOf(true) + private var showTextField by mutableStateOf(true) + private lateinit var view: View @Test @@ -495,6 +498,34 @@ rule.runOnIdle { assertThat(autofillOptionAvailable).isTrue() } } + // Regression test for b/481087608 + @Test + fun autofillItemClick_afterTextFieldRemoved_doesNotCrash() { + var autofillOption: (() -> Unit)? = null + val textToolbar = + FakeTextToolbar( + onShowMenu = { _, _, _, _, _, onAutofillRequested -> + autofillOption = onAutofillRequested + }, + onHideMenu = {}, + ) + val state = TextFieldState("Hello") + setupContent(state, textToolbar, readOnly = false) + + rule.onNodeWithTag(TAG).performTouchInput { click(Offset(fontSizePx * 2, fontSizePx / 2)) } + rule.onNode(isSelectionHandle(Handle.Cursor)).performClick() + + val action = rule.runOnIdle { + assertThat(textToolbar.status).isEqualTo(TextToolbarStatus.Shown) + assertNotNull(autofillOption) + } + + showTextField = false + rule.runOnIdle { assertThat(textToolbar.status).isEqualTo(TextToolbarStatus.Hidden) } + + rule.runOnUiThread { action.invoke() } + } + @Test fun toolbarDoesNotShowSelectAll_whenAllTextIsAlreadySelected() { var selectAllOption: (() -> Unit)? = null @@ -1075,15 +1106,17 @@ } .toTypedArray() CompositionLocalProvider(*providedValues) { - BasicTextField( - state = state, - modifier = modifier.width(100.dp).testTag(TAG), - textStyle = TextStyle(fontFamily = TEST_FONT_FAMILY, fontSize = fontSize), - enabled = enabled, - lineLimits = lineLimits, - inputTransformation = filter, - readOnly = readOnly, - ) + if (showTextField) { + BasicTextField( + state = state, + modifier = modifier.width(100.dp).testTag(TAG), + textStyle = TextStyle(fontFamily = TEST_FONT_FAMILY, fontSize = fontSize), + enabled = enabled, + lineLimits = lineLimits, + inputTransformation = filter, + readOnly = readOnly, + ) + } } } }
diff --git a/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldToolbarTest.kt b/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldToolbarTest.kt index 87ed931..f4652d1 100644 --- a/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldToolbarTest.kt +++ b/compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldToolbarTest.kt
@@ -21,18 +21,45 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.FocusedWindowTest +import androidx.compose.foundation.text.Handle +import androidx.compose.foundation.text.TEST_FONT_FAMILY +import androidx.compose.foundation.text.contextmenu.data.TextContextMenuItem +import androidx.compose.foundation.text.contextmenu.data.TextContextMenuKeys +import androidx.compose.foundation.text.contextmenu.data.TextContextMenuSession +import androidx.compose.foundation.text.contextmenu.internal.ProvidePlatformTextContextMenuToolbar +import androidx.compose.foundation.text.contextmenu.provider.LocalTextContextMenuToolbarProvider +import androidx.compose.foundation.text.contextmenu.provider.TextContextMenuDataProvider +import androidx.compose.foundation.text.contextmenu.test.FakeTextContextMenuProvider +import androidx.compose.foundation.text.contextmenu.test.SpyTextActionModeCallback +import androidx.compose.foundation.text.contextmenu.test.assertNotNull +import androidx.compose.foundation.text.contextmenu.test.assertShown import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.foundation.text.selection.isSelectionHandle +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.click import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.longClick import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.SdkSuppress +import com.google.common.truth.Truth.assertThat import org.junit.Assume.assumeTrue import org.junit.Before import org.junit.Rule @@ -40,7 +67,7 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) -class TextFieldToolbarTest { +class TextFieldToolbarTest : FocusedWindowTest { @get:Rule val rule = createComposeRule() val TAG = "TestBasicTextField" @@ -83,4 +110,76 @@ rule.onNodeWithTag(TAG).performTouchInput { longClick() } // Long click won't crash, no assertion needed. } + + // Regression test for b/516844145 + @SdkSuppress(minSdkVersion = 26) + @Test + fun btf1_autofillItemClick_afterTextFieldRemoved_doesNotCrash() { + val fontSize = 10.sp + val fontSizePx = with(rule.density) { fontSize.toPx() } + var value by mutableStateOf(TextFieldValue("Hello")) + var showTextField by mutableStateOf(true) + val spyCallback = SpyTextActionModeCallback() + var latestDataProvider: TextContextMenuDataProvider? = null + + rule.setTextFieldTestContent { + ProvidePlatformTextContextMenuToolbar( + callbackInjector = { spyCallback.apply { delegate = it } } + ) { + val platformToolbarProvider = + checkNotNull(LocalTextContextMenuToolbarProvider.current) + val recordingToolbarProvider = + remember(platformToolbarProvider) { + FakeTextContextMenuProvider { dataProvider -> + latestDataProvider = dataProvider + platformToolbarProvider.showTextContextMenu(dataProvider) + } + } + CompositionLocalProvider( + LocalTextContextMenuToolbarProvider provides recordingToolbarProvider + ) { + if (showTextField) { + @Suppress("DEPRECATION") // b/552879150 + BasicTextField( + value = value, + onValueChange = { value = it }, + modifier = Modifier.width(100.dp).testTag(TAG), + textStyle = + TextStyle(fontFamily = TEST_FONT_FAMILY, fontSize = fontSize), + ) + } + } + } + } + + rule.onNodeWithTag(TAG).performTouchInput { click(Offset(fontSizePx * 2, fontSizePx / 2)) } + rule.onNode(isSelectionHandle(Handle.Cursor)).performClick() + rule.waitForIdle() + spyCallback.assertShown(true) + val menu = assertNotNull(spyCallback.menu) + assertNotNull(menu.findItem(android.R.id.autofill)) + val autofillItem = rule.runOnIdle { + assertNotNull(latestDataProvider) + .data() + .components + .filterIsInstance<TextContextMenuItem>() + .single { it.key == TextContextMenuKeys.AutofillKey } + } + + showTextField = false + rule.waitForIdle() + spyCallback.assertShown(false) + + var sessionClosed = false + val session = + object : TextContextMenuSession { + override fun close() { + sessionClosed = true + } + } + // Invoke the pre-detach item directly (matching a queued FloatingToolbar button click) + // because onPrepareActionMode may have already cleared MenuBuilder by id. + rule.runOnUiThread { autofillItem.onClick(session) } + assertThat(sessionClosed).isTrue() + } }
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyList.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyList.kt index afecced..cce72a9 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyList.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyList.kt
@@ -352,6 +352,19 @@ ) } + val firstVisibleItemIndex: Int + val firstVisibleScrollOffset: Int + val isScrolledToEnd: Boolean + Snapshot.withoutReadObservation { + firstVisibleItemIndex = + state.updateScrollPositionIfTheFirstItemWasMoved( + itemProvider, + state.firstVisibleItemIndex, + ) + firstVisibleScrollOffset = state.firstVisibleItemScrollOffset + isScrolledToEnd = state.canScrollBackward && !state.canScrollForward + } + val measuredItemProvider = object : LazyListMeasuredItemProvider( @@ -387,21 +400,15 @@ contentType = contentType, animator = state.itemAnimator, constraints = constraints, + canExpandWhenAppearing = + !state.skipItemPlacementAnimation && + !isScrolledToEnd && + (index != firstVisibleItemIndex || + firstVisibleScrollOffset == 0), ) } } - val firstVisibleItemIndex: Int - val firstVisibleScrollOffset: Int - Snapshot.withoutReadObservation { - firstVisibleItemIndex = - state.updateScrollPositionIfTheFirstItemWasMoved( - itemProvider, - state.firstVisibleItemIndex, - ) - firstVisibleScrollOffset = state.firstVisibleItemScrollOffset - } - val pinnedItems = itemProvider.calculateLazyLayoutPinnedIndices( pinnedItemList = state.pinnedItems,
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasure.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasure.kt index a77025d..1d77200 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasure.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasure.kt
@@ -235,14 +235,32 @@ val measuredItem = measuredItemProvider.getAndMeasure(index) currentMainAxisOffset += measuredItem.mainAxisSizeWithSpacings - if (currentMainAxisOffset <= minOffset && index != itemsCount - 1) { - // this item is offscreen and will not be visible. advance firstVisibleItemIndex - currentFirstItemIndex = index + 1 - currentFirstItemScrollOffset -= measuredItem.mainAxisSizeWithSpacings - remeasureNeeded = true - } else { - maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize) - visibleItems.add(measuredItem) + val endsBeforeViewportStart = currentMainAxisOffset < minOffset + val endsAtViewportStart = currentMainAxisOffset == minOffset + val isExpandingFromNoSize = + measuredItem.hasAnimatedSize && measuredItem.mainAxisSizeWithSpacings == 0 + val isOffscreen = + endsBeforeViewportStart || (endsAtViewportStart && !isExpandingFromNoSize) + + val isLastItem = index == itemsCount - 1 + + when { + endsAtViewportStart && isExpandingFromNoSize -> { + // An item with an expand in animation from zero must be + // positioned for the expansion to start, If it is at the + // border, we must include the item. + maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize) + visibleItems.add(measuredItem) + } + isOffscreen && !isLastItem -> { + currentFirstItemIndex = index + 1 + currentFirstItemScrollOffset -= measuredItem.mainAxisSizeWithSpacings + remeasureNeeded = true + } + else -> { + maxCrossAxis = maxOf(maxCrossAxis, measuredItem.crossAxisSize) + visibleItems.add(measuredItem) + } } index++
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasuredItem.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasuredItem.kt index 86b724a..db59be7 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasuredItem.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListMeasuredItem.kt
@@ -18,9 +18,12 @@ import androidx.compose.foundation.internal.requirePrecondition import androidx.compose.foundation.internal.requirePreconditionNotNull +import androidx.compose.foundation.lazy.layout.LazyLayoutAnimationSpecsNode import androidx.compose.foundation.lazy.layout.LazyLayoutItemAnimation.Companion.NotInitialized import androidx.compose.foundation.lazy.layout.LazyLayoutItemAnimator import androidx.compose.foundation.lazy.layout.LazyLayoutMeasuredItem +import androidx.compose.foundation.lazy.layout.StateBasedLazyLayoutItemAnimation +import androidx.compose.foundation.lazy.layout.UnspecifiedSize import androidx.compose.foundation.lazy.layout.mirroredForRtl import androidx.compose.foundation.lazy.layout.placeablesCount import androidx.compose.ui.Alignment @@ -28,8 +31,8 @@ import androidx.compose.ui.layout.Placeable import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection -import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastForEachIndexed /** @@ -61,6 +64,7 @@ override val contentType: Any?, private val animator: LazyLayoutItemAnimator<LazyListMeasuredItem>, override val constraints: Constraints, + canExpandWhenAppearing: Boolean, ) : LazyListItemInfo, LazyLayoutMeasuredItem { override var offset: Int = 0 private set @@ -92,19 +96,53 @@ private var maxMainAxisOffset: Int = 0 // optimized for storing x and y offsets for each placeable one by one. - // array's size == placeables.size * 2, first we store x, then y. + // the first placeables.size * 2 elements are the offsets, first we store x, then y. + // when a placeable has an animated size they are followed by the width and height of the + // bounds of each placeable, so the array's size == placeables.size * 4. private val placeableOffsets: IntArray + override val hasAnimatedSize: Boolean + get() = placeableOffsets.size > placeables.size * 2 + init { var mainAxisSize = 0 var maxCrossAxis = 0 - placeables.fastForEach { - mainAxisSize += if (isVertical) it.height else it.width - maxCrossAxis = maxOf(maxCrossAxis, if (!isVertical) it.height else it.width) + var offsetsAndBounds: IntArray? = null + placeables.fastForEachIndexed { placeableIndex, placeable -> + var width = placeable.width + var height = placeable.height + val specs = placeable.parentData as? LazyLayoutAnimationSpecsNode + if (specs?.enterTransition?.config?.changeSize != null) { + val boundsSize = + animator.animatedBoundsSize( + key, + placeableIndex, + placeable, + constraints, + canExpandWhenAppearing, + ) + if (boundsSize != UnspecifiedSize) { + val array = + offsetsAndBounds + ?: offsetsWithMeasuredSizes().also { offsetsAndBounds = it } + if (isVertical) { + width = boundsSize.width + height = maxOf(boundsSize.height, minOf(-spacing, height)) + } else { + width = maxOf(boundsSize.width, minOf(-spacing, width)) + height = boundsSize.height + } + val boundsIndex = (placeables.size + placeableIndex) * 2 + array[boundsIndex] = width + array[boundsIndex + 1] = height + } + } + mainAxisSize += if (isVertical) height else width + maxCrossAxis = maxOf(maxCrossAxis, if (!isVertical) height else width) } + placeableOffsets = offsetsAndBounds ?: IntArray(placeables.size * 2) size = mainAxisSize crossAxisSize = maxCrossAxis - placeableOffsets = IntArray(placeables.size * 2) if (isVertical) { verticalAxisSpacing = spacing verticalAxisSize = size @@ -152,24 +190,27 @@ this.offset = mainAxisOffset mainAxisLayoutSize = if (isVertical) layoutHeight else layoutWidth @Suppress("NAME_SHADOWING") var mainAxisOffset = mainAxisOffset + val hasBounds = hasAnimatedSize placeables.fastForEachIndexed { index, placeable -> val indexInArray = index * 2 + val width = if (hasBounds) boundsWidth(index) else placeable.width + val height = if (hasBounds) boundsHeight(index) else placeable.height if (isVertical) { placeableOffsets[indexInArray] = requirePreconditionNotNull(horizontalAlignment) { "null horizontalAlignment when isVertical == true" } - .align(placeable.width, layoutWidth, layoutDirection) + .align(width, layoutWidth, layoutDirection) placeableOffsets[indexInArray + 1] = mainAxisOffset - mainAxisOffset += placeable.height + mainAxisOffset += height } else { placeableOffsets[indexInArray] = mainAxisOffset placeableOffsets[indexInArray + 1] = requirePreconditionNotNull(verticalAlignment) { "null verticalAlignment when isVertical == false" } - .align(placeable.height, layoutHeight) - mainAxisOffset += placeable.width + .align(height, layoutHeight) + mainAxisOffset += width } } minMainAxisOffset = -beforeContentPadding @@ -200,7 +241,7 @@ return } offset += delta - repeat(placeableOffsets.size) { index -> + repeat(placeables.size * 2) { index -> // placeableOffsets consist of x and y pairs for each placeable. // if isVertical is true then the main axis offsets are located at indexes 1, 3, 5 etc. // 1 when odd, 0 when even @@ -223,6 +264,7 @@ fun place(scope: Placeable.PlacementScope, isLookingAhead: Boolean) = with(scope) { requirePrecondition(mainAxisLayoutSize != Unset) { "position() should be called first" } + val hasBounds = hasAnimatedSize repeat(placeablesCount) { index -> val placeable = placeables[index] val minOffset = minMainAxisOffset - placeable.mainAxisSize @@ -258,12 +300,29 @@ } else { layer = null } + val boundsMainAxisSize = + if (hasBounds) { + if (isVertical) boundsHeight(index) else boundsWidth(index) + } else { + placeable.mainAxisSize + } if (reverseLayout) { offset = offset.copy { mainAxisOffset -> - mainAxisLayoutSize - mainAxisOffset - placeable.mainAxisSize + mainAxisLayoutSize - mainAxisOffset - boundsMainAxisSize } } offset += visualOffset + var zIndex = 0f + if (hasBounds && animation is StateBasedLazyLayoutItemAnimation) { + offset += + animation.placeWithinBounds( + placeable, + IntSize(boundsWidth(index), boundsHeight(index)), + ) + if (animation.isClippedToBounds && !nonScrollableItem) { + zIndex = ClippedItemZIndex + } + } if (!isLookingAhead) { animation?.placementOffset = if (!isVertical && layoutDirection == LayoutDirection.Rtl) { @@ -278,13 +337,13 @@ } if (isVertical) { if (layer != null) { - placeable.placeWithLayer(offset, layer) + placeable.placeWithLayer(offset, layer, zIndex) } else { placeable.placeWithLayer(offset) } } else { if (layer != null) { - placeable.placeRelativeWithLayer(offset, layer) + placeable.placeRelativeWithLayer(offset, layer, zIndex) } else { placeable.placeRelativeWithLayer(offset) } @@ -292,6 +351,33 @@ } } + private fun StateBasedLazyLayoutItemAnimation.placeWithinBounds( + placeable: Placeable, + boundsSize: IntSize, + ): IntOffset { + val contentOffset = contentOffsetIn(boundsSize) + onPlaced(boundsSize, contentOffset) + return if (!isVertical && layoutDirection == LayoutDirection.Rtl) { + IntOffset(boundsSize.width - placeable.width - contentOffset.x, contentOffset.y) + } else { + contentOffset + } + } + + private fun offsetsWithMeasuredSizes(): IntArray { + val array = IntArray(placeables.size * 4) + placeables.fastForEachIndexed { index, placeable -> + val boundsIndex = (placeables.size + index) * 2 + array[boundsIndex] = placeable.width + array[boundsIndex + 1] = placeable.height + } + return array + } + + private fun boundsWidth(index: Int) = placeableOffsets[(placeables.size + index) * 2] + + private fun boundsHeight(index: Int) = placeableOffsets[(placeables.size + index) * 2 + 1] + private val IntOffset.mainAxis get() = if (isVertical) y else x @@ -303,3 +389,5 @@ } private const val Unset = Int.MIN_VALUE + +private const val ClippedItemZIndex = -1f
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/InterruptibleItemAnimation.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/InterruptibleItemAnimation.kt index 745317a..51c4681 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/InterruptibleItemAnimation.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/InterruptibleItemAnimation.kt
@@ -16,6 +16,7 @@ package androidx.compose.foundation.lazy.layout +import androidx.compose.animation.ChangeSizeConfig import androidx.compose.animation.FadeConfig import androidx.compose.animation.ScaleConfig import androidx.compose.animation.SlideConfig @@ -24,8 +25,13 @@ import androidx.compose.animation.core.AnimationVector import androidx.compose.animation.core.AnimationVector1D import androidx.compose.animation.core.AnimationVector2D +import androidx.compose.animation.core.SpringSpec import androidx.compose.animation.core.VectorConverter +import androidx.compose.animation.core.VisibilityThreshold +import androidx.compose.animation.core.spring +import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Alignment import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize @@ -49,7 +55,7 @@ Finished, } - private var appliedValue: T = animatable.value + private var appliedValue: T = Snapshot.withoutReadObservation { animatable.value } private fun applyValue(value: T) { appliedValue = value @@ -75,6 +81,12 @@ animatable.animateTo(targetValue, animationSpec) { applyValue(value) } } + protected suspend fun retargetEnter(targetValue: T, animationSpec: AnimationSpec<T>) { + if (state != State.Entering || animatable.targetValue == targetValue) return + animatable.animateTo(targetValue, animationSpec) { applyValue(value) } + state = State.Idle + } + protected suspend fun animateEnter( initialValue: T?, targetValue: T, @@ -125,7 +137,7 @@ } val value: T? - get() = if (state == State.New) null else appliedValue + get() = if (state == State.New || state == State.Idle) null else appliedValue } internal class EnterExitFadeAnimation(onAlphaChange: () -> Unit) : @@ -204,3 +216,49 @@ ) } } + +internal class EnterExitSizeAnimation(onSizeChange: () -> Unit) : + InterruptibleItemAnimation<IntSize, AnimationVector2D>( + animatable = Animatable(IntSize.Zero, IntSize.VectorConverter), + onValueChange = onSizeChange, + ) { + var alignment: Alignment? = null + private set + + private var clip = false + + val shouldClip: Boolean + get() = clip && value != null + + suspend fun animateExpandIn( + expandConfig: ChangeSizeConfig?, + itemSize: IntSize, + isReentering: Boolean, + ) { + if (isReentering && value == null) return + animateEnter( + initialValue = expandConfig?.size?.invoke(itemSize), + targetValue = itemSize, + animationSpec = expandConfig?.animationSpec, + onStart = { wasAnimating -> + if (expandConfig != null) { + if (wasAnimating) { + clip = clip && expandConfig.clip + } else { + alignment = expandConfig.alignment + clip = expandConfig.clip + } + } + }, + ) + } + + suspend fun retargetExpandIn(expandConfig: ChangeSizeConfig?, itemSize: IntSize) = + retargetEnter( + targetValue = itemSize, + animationSpec = expandConfig?.animationSpec as? SpringSpec<IntSize> ?: SizeRetargetSpec, + ) +} + +private val SizeRetargetSpec: AnimationSpec<IntSize> = + spring(visibilityThreshold = IntSize.VisibilityThreshold)
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimation.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimation.kt index 4c2bfff..a3ac5a6 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimation.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimation.kt
@@ -31,12 +31,15 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.Snapshot import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.GraphicsContext import androidx.compose.ui.graphics.layer.GraphicsLayer import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection +import kotlin.math.abs import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart @@ -157,7 +160,7 @@ /** Animate the placement by the given [delta] offset. */ fun animatePlacementDelta(delta: IntOffset, isMovingAway: Boolean) - fun animateEnterTransition() + fun animateEnterTransition(expands: Boolean) fun animateExitTransition() @@ -188,6 +191,34 @@ override var reverseLayout: Boolean = false override var isVertical: Boolean = true var itemSize: IntSize = IntSize.Zero + set(value) { + if (field != value) { + field = value + enterTransitionScope?.launchUndispatched { + sizeAnimation.retargetExpandIn(enterTransition?.config?.changeSize, value) + } + } + } + + private var enterTransitionScope: CoroutineScope? = null + + private val scopeInvalidator = ObservableScopeInvalidator() + + var animatedSize: IntSize = UnspecifiedSize + get() { + scopeInvalidator.attachToScope() + return field + } + private set(value) { + if (field != value) { + field = value + scopeInvalidator.invalidateScope() + } + } + + fun observeAnimatedSize() { + scopeInvalidator.attachToScope() + } private var transitionState by mutableStateOf(TransitionState.New) @@ -199,6 +230,28 @@ private val scaleAnimation = EnterExitScaleAnimation(::updateLayerProperties) + private val sizeAnimation = EnterExitSizeAnimation(::updateLayerProperties) + + private var placedSize = UnspecifiedSize + + private var placedContentOffset = IntOffset.Zero + + val isClippedToBounds: Boolean + get() = sizeAnimation.shouldClip + + fun onPlaced(size: IntSize, contentOffset: IntOffset) { + if (placedSize != size || placedContentOffset != contentOffset) { + placedSize = size + placedContentOffset = contentOffset + updateLayerProperties() + } + } + + fun contentOffsetIn(size: IntSize): IntOffset { + val alignment = sizeAnimation.alignment ?: return IntOffset.Zero + return alignment.align(itemSize, size, LayoutDirection.Ltr) + } + override var isRunningMovingAwayAnimation = false private set @@ -280,19 +333,34 @@ } } - override fun animateEnterTransition() { - if (layer == null || transitionState == TransitionState.Entering) return + override fun animateEnterTransition(expands: Boolean) = Snapshot.withoutReadObservation { + if (layer == null || transitionState == TransitionState.Entering) { + return@withoutReadObservation + } val config = enterTransition?.config val size = containerSize + val isReentering = + transitionState == TransitionState.Exiting || + transitionState == TransitionState.Finished runTransition(TransitionState.Entering, TransitionState.Placed) { + enterTransitionScope = this launchUndispatched { fadeAnimation.animateFadeIn(config?.fade) } launchUndispatched { slideAnimation.animateSlideIn(config?.slide, size) } launchUndispatched { scaleAnimation.animateScaleIn(config?.scale) } + launchUndispatched { + sizeAnimation.animateExpandIn( + config?.changeSize?.takeIf { expands }, + itemSize, + isReentering, + ) + } } } - override fun animateExitTransition() { - if (layer == null || transitionState == TransitionState.Exiting) return + override fun animateExitTransition() = Snapshot.withoutReadObservation { + if (layer == null || transitionState == TransitionState.Exiting) { + return@withoutReadObservation + } val config = exitTransition?.config val size = containerSize runTransition(TransitionState.Exiting, TransitionState.Finished) { @@ -310,10 +378,12 @@ crossinline animations: CoroutineScope.() -> Unit, ) { transitionJob?.cancel() + enterTransitionScope = null transitionState = startState updateLayerProperties() transitionJob = coroutineScope.launchUndispatched { coroutineScope { animations() } + enterTransitionScope = null transitionState = endState updateLayerProperties() } @@ -330,10 +400,12 @@ val job = transitionJob transitionJob = null job?.cancel() + enterTransitionScope = null transitionState = TransitionState.New fadeAnimation.release() slideAnimation.release() scaleAnimation.release() + sizeAnimation.release() isRunningMovingAwayAnimation = false placementDelta = IntOffset.Zero targetOffset = NotInitialized @@ -343,9 +415,14 @@ exitTransition = null placementSpec = null itemSize = IntSize.Zero + animatedSize = UnspecifiedSize + placedSize = UnspecifiedSize + placedContentOffset = IntOffset.Zero } private fun updateLayerProperties() { + val boundsSize = sizeAnimation.value + animatedSize = boundsSize ?: UnspecifiedSize val layer = layer ?: return val offset = slideAnimation.value ?: IntOffset.Zero val scale = scaleAnimation.value ?: 1f @@ -360,6 +437,25 @@ layer.pivotOffset = Offset(origin.pivotFractionX * size.width, origin.pivotFractionY * size.height) + if (boundsSize != null && sizeAnimation.shouldClip) { + val clipSize = if (placedSize == UnspecifiedSize) boundsSize else placedSize + val pivot = layer.pivotOffset + val inverseScale = if (scale > 0f) 1f / scale else 1f + val boundsLeft = -(offset.x + placedContentOffset.x).toFloat() + val boundsTop = -(offset.y + placedContentOffset.y).toFloat() + val left = pivot.x + (boundsLeft - pivot.x) * inverseScale + val top = pivot.y + (boundsTop - pivot.y) * inverseScale + val right = pivot.x + (boundsLeft + clipSize.width - pivot.x) * inverseScale + val bottom = pivot.y + (boundsTop + clipSize.height - pivot.y) * inverseScale + layer.setRectOutline( + topLeft = Offset(minOf(left, right), minOf(top, bottom)), + size = Size(abs(right - left), abs(bottom - top)), + ) + layer.clip = true + } else { + layer.clip = false + } + onLayerPropertyChanged() } } @@ -466,7 +562,7 @@ } } - override fun animateEnterTransition() { + override fun animateEnterTransition(expands: Boolean) { layer?.let { layer -> animateFadeIn(layer) } } @@ -557,5 +653,7 @@ visibilityThreshold = IntOffset.VisibilityThreshold, ) +internal val UnspecifiedSize = IntSize(Int.MIN_VALUE, Int.MIN_VALUE) + internal fun IntOffset.mirroredForRtl(layoutWidth: Int, itemWidth: Int): IntOffset = IntOffset(layoutWidth - x - itemWidth, y)
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimator.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimator.kt index 4b7a6df..d1ecd24 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimator.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemAnimator.kt
@@ -18,16 +18,20 @@ import androidx.collection.mutableScatterMapOf import androidx.collection.mutableScatterSetOf +import androidx.compose.foundation.ComposeFoundationFlags +import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.ui.graphics.GraphicsContext import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.layer.drawLayer +import androidx.compose.ui.layout.Placeable import androidx.compose.ui.node.DrawModifierNode import androidx.compose.ui.node.invalidateDraw import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.constrain import androidx.compose.ui.util.fastAny import androidx.compose.ui.util.fastForEach import kotlinx.coroutines.CoroutineScope @@ -165,7 +169,13 @@ isVertical, ) if (shouldAnimateAppearance) { - newItemInfo.animations.forEach { it?.animateEnterTransition() } + val expands = item.hasAnimatedSize + newItemInfo.animations.forEach { + it?.animateEnterTransition(expands) + if (expands && it is StateBasedLazyLayoutItemAnimation) { + it.observeAnimatedSize() + } + } } } } else { @@ -198,11 +208,14 @@ disappearingItems.remove(it) displayingNode?.invalidateDraw() } - it.animateEnterTransition() + it.animateEnterTransition(item.hasAnimatedSize) } } } - startPlacementAnimationsIfNeeded(item, layoutSizeOffset = layoutSizeOffset) + startPlacementAnimationsIfNeeded( + item, + layoutSizeOffset = layoutSizeOffset, + ) } } } else { @@ -392,6 +405,42 @@ movingAwayKeys.clear() } + @OptIn(ExperimentalFoundationApi::class) + fun animatedBoundsSize( + key: Any, + placeableIndex: Int, + placeable: Placeable, + constraints: Constraints, + canExpandWhenAppearing: Boolean, + ): IntSize { + if (!ComposeFoundationFlags.isLazyLayoutItemAnimationEnterExitTransitionsEnabled) { + return UnspecifiedSize + } + val itemInfo = keyToItemInfoMap[key] + val animatedSize = + if (itemInfo != null) { + val animation = + itemInfo.animations.getOrNull(placeableIndex) + as? StateBasedLazyLayoutItemAnimation + animation?.animatedSize ?: UnspecifiedSize + } else if (canExpandWhenAppearing && keyIndexMap?.getIndex(key) == -1) { + val measuredSize = IntSize(placeable.width, placeable.height) + placeable.parentData.specs + ?.enterTransition + ?.config + ?.changeSize + ?.size + ?.invoke(measuredSize) ?: UnspecifiedSize + } else { + UnspecifiedSize + } + return if (animatedSize == UnspecifiedSize) { + UnspecifiedSize + } else { + constraints.constrain(animatedSize) + } + } + private fun removeInfoForKey(key: Any) { keyToItemInfoMap.remove(key)?.animations?.forEach { it?.release() } }
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutMeasuredItem.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutMeasuredItem.kt index 418b8ee..236d9ef 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutMeasuredItem.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutMeasuredItem.kt
@@ -70,6 +70,9 @@ /** The number of lanes this item's spans. */ val span: Int + val hasAnimatedSize: Boolean + get() = false + /** * The offset applied to the placeable in [placeableIndex]. *
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/CoreTextFieldSemanticsModifier.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/CoreTextFieldSemanticsModifier.kt index d85a9e33..cb0aa0e 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/CoreTextFieldSemanticsModifier.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/CoreTextFieldSemanticsModifier.kt
@@ -122,8 +122,16 @@ var imeOptions: ImeOptions, var focusRequester: FocusRequester, ) : DelegatingNode(), SemanticsModifierNode { - init { - manager.requestAutofillAction = { requestAutofill() } + private val requestAutofillAction: () -> Unit = { requestAutofill() } + + override fun onAttach() { + manager.requestAutofillAction = requestAutofillAction + } + + override fun onDetach() { + if (manager.requestAutofillAction === requestAutofillAction) { + manager.requestAutofillAction = null + } } override val shouldMergeDescendantSemantics: Boolean @@ -333,7 +341,12 @@ } if (manager != previousManager) { - manager.requestAutofillAction = { requestAutofill() } + if (previousManager.requestAutofillAction === requestAutofillAction) { + previousManager.requestAutofillAction = null + } + if (isAttached) { + manager.requestAutofillAction = requestAutofillAction + } } }
diff --git a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/TextFieldDecoratorModifier.kt b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/TextFieldDecoratorModifier.kt index 569ed7d..90812e1 100644 --- a/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/TextFieldDecoratorModifier.kt +++ b/compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/input/internal/TextFieldDecoratorModifier.kt
@@ -215,10 +215,6 @@ LayoutAwareModifierNode, FocusPropertiesModifierNode { - init { - textFieldSelectionState.requestAutofillAction = { requestAutofill() } - } - private val focusableNode = FocusableNode( interactionSource = interactionSource, @@ -415,6 +411,8 @@ getReceiveContentConfiguration() } + private val requestAutofillAction: () -> Unit = { requestAutofill() } + // Mutable state to hold the autofillHighlightOn value private var autofillHighlightOn by mutableStateOf(false) @@ -511,9 +509,13 @@ if (textFieldSelectionState != previousTextFieldSelectionState) { pointerInputNode.resetPointerInputHandler() + if (previousTextFieldSelectionState.requestAutofillAction === requestAutofillAction) { + previousTextFieldSelectionState.requestAutofillAction = null + } if (isAttached) { textFieldSelectionState.receiveContentConfiguration = receiveContentConfigurationProvider + textFieldSelectionState.requestAutofillAction = requestAutofillAction if (isFocused && toolbarAndHandlesVisibilityObserverJob != null) { toolbarAndHandlesVisibilityObserverJob?.cancel() @@ -522,7 +524,6 @@ } } } - textFieldSelectionState.requestAutofillAction = { requestAutofill() } } if (interactionSource != previousInteractionSource) { @@ -757,6 +758,7 @@ override fun onAttach() { onObservedReadsChanged() textFieldSelectionState.receiveContentConfiguration = receiveContentConfigurationProvider + textFieldSelectionState.requestAutofillAction = requestAutofillAction if (enabled) { delegate(focusableNode) @@ -766,6 +768,9 @@ override fun onDetach() { disposeInputSession() textFieldSelectionState.receiveContentConfiguration = null + if (textFieldSelectionState.requestAutofillAction === requestAutofillAction) { + textFieldSelectionState.requestAutofillAction = null + } } override fun onGloballyPositioned(coordinates: LayoutCoordinates) {
diff --git a/compose/remote/integration-tests/demos/src/main/java/androidx/compose/remote/integration/demos/main/Screens.kt b/compose/remote/integration-tests/demos/src/main/java/androidx/compose/remote/integration/demos/main/Screens.kt index 70389db..b20ae3e 100644 --- a/compose/remote/integration-tests/demos/src/main/java/androidx/compose/remote/integration/demos/main/Screens.kt +++ b/compose/remote/integration-tests/demos/src/main/java/androidx/compose/remote/integration/demos/main/Screens.kt
@@ -33,6 +33,7 @@ import androidx.compose.remote.integration.demos.modifier.AlphaDemo import androidx.compose.remote.integration.demos.modifier.ClickableDemo import androidx.compose.remote.integration.demos.modifier.CombinedClickableDemo +import androidx.compose.remote.integration.demos.modifier.ComponentIdDemo import androidx.compose.remote.integration.demos.modifier.PaddingDemo import androidx.compose.remote.integration.demos.modifier.RotateDemo import androidx.compose.remote.integration.demos.modifier.ScaleDemo @@ -70,6 +71,7 @@ const val CONTROLLED_SCROLL = "CONTROLLED_SCROLL" const val NESTED_SNAP_SCROLL = "NESTED_SNAP_SCROLL" const val TOUCH_ACTION = "TOUCH_ACTION" + const val COMPONENT_ID = "COMPONENT_ID" const val BITMAP_LOADER = "BITMAP_LOADER" const val REMOTE_ANNOTATED_STRING = "REMOTE_ANNOTATED_STRING" const val GESTURE_PROPAGATION = "GESTURE_PROPAGATION" @@ -110,6 +112,7 @@ ScreenKeys.CLICKABLE -> ClickableDemo(onDocument) ScreenKeys.COMBINED_CLICKABLE -> CombinedClickableDemo(onDocument) ScreenKeys.TOUCH_ACTION -> TouchActionDemo(onDocument) + ScreenKeys.COMPONENT_ID -> ComponentIdDemo(onDocument) ScreenKeys.BITMAP_LOADER -> BitmapLoaderDemo(onDocument) ScreenKeys.REMOTE_ANNOTATED_STRING -> RemoteAnnotatedStringDemo(onDocument) ScreenKeys.GESTURE_PROPAGATION -> GesturePropagationDemo(onDocument) @@ -202,6 +205,7 @@ title = "CombinedClickable", ), ComposableScreen(key = ScreenKeys.TOUCH_ACTION, title = "TouchAction"), + ComposableScreen(key = ScreenKeys.COMPONENT_ID, title = "ComponentId"), ), ), Category(
diff --git a/compose/remote/integration-tests/demos/src/main/java/androidx/compose/remote/integration/demos/modifier/ComponentIdDemo.kt b/compose/remote/integration-tests/demos/src/main/java/androidx/compose/remote/integration/demos/modifier/ComponentIdDemo.kt new file mode 100644 index 0000000..588447e --- /dev/null +++ b/compose/remote/integration-tests/demos/src/main/java/androidx/compose/remote/integration/demos/modifier/ComponentIdDemo.kt
@@ -0,0 +1,228 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.integration.demos.modifier + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.creation.compose.layout.RemoteAlignment +import androidx.compose.remote.creation.compose.layout.RemoteArrangement +import androidx.compose.remote.creation.compose.layout.RemoteBox +import androidx.compose.remote.creation.compose.layout.RemoteColumn +import androidx.compose.remote.creation.compose.layout.RemoteComposable +import androidx.compose.remote.creation.compose.layout.RemoteRow +import androidx.compose.remote.creation.compose.layout.RemoteText +import androidx.compose.remote.creation.compose.modifier.RemoteModifier +import androidx.compose.remote.creation.compose.modifier.background +import androidx.compose.remote.creation.compose.modifier.componentId +import androidx.compose.remote.creation.compose.modifier.fillMaxSize +import androidx.compose.remote.creation.compose.modifier.fillMaxWidth +import androidx.compose.remote.creation.compose.modifier.height +import androidx.compose.remote.creation.compose.modifier.padding +import androidx.compose.remote.creation.compose.state.rc +import androidx.compose.remote.creation.compose.state.rdp +import androidx.compose.remote.creation.compose.state.rs +import androidx.compose.remote.integration.demos.common.RemoteDemo +import androidx.compose.remote.tooling.preview.RemoteComponentPreview +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp + +private const val COLUMN_ID = 100 +private const val BOX_ID = 101 +private const val ROW_ID = 102 +private const val TEXT_ID = 103 +private const val OUTER_CHAINED_ID = 200 +private const val INNER_CHAINED_ID = 201 + +private val LookupIds = + listOf( + COLUMN_ID to "RemoteColumn", + BOX_ID to "RemoteBox", + ROW_ID to "RemoteRow", + TEXT_ID to "RemoteText", + OUTER_CHAINED_ID to "Chained outermost ($OUTER_CHAINED_ID then $INNER_CHAINED_ID)", + INNER_CHAINED_ID to "Chained inner (overridden by $OUTER_CHAINED_ID)", + ) + +@Suppress("RestrictedApiAndroidX") // Referring to CoreDocument +@Composable +fun ComponentIdDemo(onDocument: (CoreDocument) -> Unit = {}) { + var capturedDocument by remember { mutableStateOf<CoreDocument?>(null) } + val handleDocument = + remember(onDocument) { + { doc: CoreDocument -> + capturedDocument = doc + onDocument(doc) + } + } + + Column( + modifier = Modifier.fillMaxSize().padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + RemoteDemo(modifier = Modifier.fillMaxSize(), onDocument = handleDocument) { + ComponentIdDemoContent() + } + } + + val doc = capturedDocument + if (doc != null) { + ComponentLookupPanel(document = doc) + } + } +} + +@Suppress("RestrictedApiAndroidX") // Referring to CoreDocument +@Composable +private fun ComponentLookupPanel(document: CoreDocument, modifier: Modifier = Modifier) { + Surface( + modifier = modifier.fillMaxWidth(), + color = MaterialTheme.colorScheme.surfaceVariant, + shape = MaterialTheme.shapes.medium, + ) { + Column( + modifier = Modifier.padding(12.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + text = "CoreDocument.getComponent(id)", + style = MaterialTheme.typography.titleSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + HorizontalDivider() + LookupIds.forEach { (id, description) -> + val resolvedName = document.getComponent(id)?.javaClass?.simpleName ?: "null" + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = "$id ($description)", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f).padding(end = 8.dp), + ) + Text( + text = resolvedName, + style = + MaterialTheme.typography.bodySmall.copy( + fontFamily = FontFamily.Monospace + ), + color = MaterialTheme.colorScheme.primary, + ) + } + } + HorizontalDivider() + Text( + text = "Tap the Document icon in the top bar to inspect all component IDs.", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +@Suppress("RestrictedApiAndroidX") // Referring to RemoteComponentPreview, componentId +@RemoteComponentPreview +@Composable +@RemoteComposable +private fun ComponentIdDemoContent() { + RemoteColumn( + modifier = RemoteModifier.fillMaxSize().componentId(COLUMN_ID), + verticalArrangement = RemoteArrangement.spacedBy(12.rdp), + ) { + RemoteText( + text = "RemoteColumn (componentId = $COLUMN_ID)".rs, + color = Color.Black.rc, + ) + + RemoteBox( + modifier = + RemoteModifier.componentId(BOX_ID) + .fillMaxWidth() + .height(56.rdp) + .background(Color(0xFF1565C0).rc), + contentAlignment = RemoteAlignment.Center, + ) { + RemoteText( + text = "RemoteBox (componentId = $BOX_ID)".rs, + color = Color.White.rc, + ) + } + + RemoteRow( + modifier = + RemoteModifier.componentId(ROW_ID) + .fillMaxWidth() + .background(Color(0xFFE8F5E9).rc) + .padding(12.rdp), + verticalAlignment = RemoteAlignment.CenterVertically, + ) { + RemoteText( + text = "RemoteRow (id = $ROW_ID) > RemoteText (id = $TEXT_ID)".rs, + modifier = RemoteModifier.componentId(TEXT_ID), + color = Color(0xFF1B5E20).rc, + ) + } + + RemoteBox( + modifier = + RemoteModifier.componentId(OUTER_CHAINED_ID) + .componentId(INNER_CHAINED_ID) + .fillMaxWidth() + .height(56.rdp) + .background(Color(0xFF6A1B9A).rc), + contentAlignment = RemoteAlignment.Center, + ) { + RemoteText( + text = + "Chained ($OUTER_CHAINED_ID then $INNER_CHAINED_ID) -> id = $OUTER_CHAINED_ID" + .rs, + color = Color.White.rc, + ) + } + + RemoteBox( + modifier = RemoteModifier.fillMaxWidth().height(56.rdp).background(Color.LightGray.rc), + contentAlignment = RemoteAlignment.Center, + ) { + RemoteText( + text = "No componentId modifier (auto-generated < -1)".rs, + color = Color.Black.rc, + ) + } + } +}
diff --git a/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/BenchTemplates.kt b/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/BenchTemplates.kt index f3505c0..6360e66 100644 --- a/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/BenchTemplates.kt +++ b/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/BenchTemplates.kt
@@ -17,6 +17,7 @@ package androidx.compose.remote.integration.macrobenchmark.target import android.content.Context +import android.graphics.Color as AndroidColor import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat @@ -40,6 +41,15 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.RcProfiles +import androidx.compose.remote.core.RcResolver +import androidx.compose.remote.core.operations.layout.managers.BoxLayout +import androidx.compose.remote.core.operations.layout.managers.ColumnLayout +import androidx.compose.remote.core.operations.layout.managers.CoreText +import androidx.compose.remote.core.operations.layout.managers.RowLayout +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.RemoteComposeWriterAndroid import androidx.compose.remote.creation.compose.layout.RemoteAlignment import androidx.compose.remote.creation.compose.layout.RemoteAllStatesLayout import androidx.compose.remote.creation.compose.layout.RemoteArrangement @@ -70,6 +80,10 @@ import androidx.compose.remote.creation.compose.state.rf import androidx.compose.remote.creation.compose.state.rs import androidx.compose.remote.creation.compose.state.rsp +import androidx.compose.remote.creation.modifiers.RecordingModifier +import androidx.compose.remote.creation.modifiers.RoundedRectShape +import androidx.compose.remote.creation.platform.AndroidxRcPlatformServices +import androidx.compose.remote.player.compose.embedded.RcDocumentResolver import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember @@ -89,6 +103,123 @@ Poll("poll"), Live("live"), Stateful("stateful"), + EmbeddedDoc("embeddedDoc"), +} + +private const val EMBEDDED_BADGE_URL = "bench://badge" + +internal fun createFeedRcResolver(): RcResolver { + val badgeBytes = buildEmbeddedFeedBadgeBytes() + return RcResolver { url -> if (url == EMBEDDED_BADGE_URL) badgeBytes else null } +} + +internal fun createFeedDocumentResolver(): RcDocumentResolver { + val badgeBytes = buildEmbeddedFeedBadgeBytes() + return RcDocumentResolver { url -> if (url == EMBEDDED_BADGE_URL) badgeBytes else null } +} + +private fun buildEmbeddedFeedBadgeBytes(): ByteArray { + val writer = + RemoteComposeWriterAndroid( + 180, + 72, + "BenchEmbeddedBadge", + CoreDocument.DOCUMENT_API_LEVEL, + RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL, + AndroidxRcPlatformServices(), + ) + val labelId = writer.addNamedString("label", "EMBED") + writer.root { + writer.box( + RecordingModifier() + .fillMaxSize() + .clip(RoundedRectShape(16f, 16f, 16f, 16f)) + .background(0xFF1D4ED8.toInt()) + .padding(8), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + writer.textComponent( + RecordingModifier(), + labelId, + AndroidColor.WHITE, + 26f, + 0, + 600f, + null, + CoreText.TEXT_ALIGN_CENTER, + CoreText.OVERFLOW_CLIP, + 1, + ) {} + } + } + return writer.encodeToByteArray() +} + +private fun buildEmbeddedFeedCardBytes(): ByteArray { + val writer = + RemoteComposeWriterAndroid( + 1000, + 280, + "BenchEmbeddedCard", + CoreDocument.DOCUMENT_API_LEVEL, + RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL, + AndroidxRcPlatformServices(), + ) + val titleId = writer.addText("Embedded Doc Card") + val subtitleId = writer.addText("Feed item with nested rcDoc badge") + val badgeTextId = writer.addNamedString("badgeLabel", "NESTED") + writer.root { + writer.row( + RecordingModifier() + .fillMaxSize() + .padding(24, 12, 24, 12) + .clip(RoundedRectShape(24f, 24f, 24f, 24f)) + .background(0xFFF3F4F6.toInt()) + .padding(24), + RowLayout.START, + RowLayout.CENTER, + ) { + writer.column( + RecordingModifier().horizontalWeight(1f), + ColumnLayout.START, + ColumnLayout.CENTER, + ) { + writer.textComponent( + RecordingModifier(), + titleId, + 0xFF111827.toInt(), + 34f, + 0, + 600f, + null, + CoreText.TEXT_ALIGN_LEFT, + CoreText.OVERFLOW_CLIP, + 1, + ) {} + writer.textComponent( + RecordingModifier().padding(0, 8, 0, 0), + subtitleId, + 0xFF4B5563.toInt(), + 26f, + 0, + 400f, + null, + CoreText.TEXT_ALIGN_LEFT, + CoreText.OVERFLOW_CLIP, + 1, + ) {} + } + val docId = writer.rcDoc(EMBEDDED_BADGE_URL, RecordingModifier().size(180, 72)) + writer.mapRcDocVariables( + docId, + RemoteComposeWriter.MAP_FORWARD, + badgeTextId, + "label", + ) + } + } + return writer.encodeToByteArray() } internal val FEED_CARD_HEIGHT = 112.dp @@ -102,12 +233,16 @@ val result = LinkedHashMap<BenchTemplate, ByteArray>() for (template in templates.distinct()) { result[template] = - BenchDocuments.getOrCapture( - context = context, - name = "feed_${template.key}", - globalScope = globalScope, - ) { - RemoteTemplateContent(template, globalScope = globalScope) + if (template == BenchTemplate.EmbeddedDoc) { + buildEmbeddedFeedCardBytes() + } else { + BenchDocuments.getOrCapture( + context = context, + name = "feed_${template.key}", + globalScope = globalScope, + ) { + RemoteTemplateContent(template, globalScope = globalScope) + } } } return result @@ -117,7 +252,8 @@ @Composable private fun RemoteTemplateContent(template: BenchTemplate, globalScope: Boolean) { when (template) { - BenchTemplate.AppCard -> RemoteAppCard() + BenchTemplate.AppCard, + BenchTemplate.EmbeddedDoc -> RemoteAppCard() BenchTemplate.Headline -> RemoteHeadlineCard() BenchTemplate.Poll -> RemotePollCard(liveBadge = false, globalScope = globalScope) BenchTemplate.Live -> RemotePollCard(liveBadge = true, globalScope = globalScope) @@ -353,7 +489,8 @@ stateIndex: Int, ) { when (template) { - BenchTemplate.AppCard -> { + BenchTemplate.AppCard, + BenchTemplate.EmbeddedDoc -> { Row( modifier = Modifier.fillMaxWidth()
diff --git a/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/RemoteFeedActivity.kt b/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/RemoteFeedActivity.kt index 69a5f27..6538b8d 100644 --- a/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/RemoteFeedActivity.kt +++ b/compose/remote/integration-tests/macrobenchmark-target/src/main/java/androidx/compose/remote/integration/macrobenchmark/target/RemoteFeedActivity.kt
@@ -38,10 +38,12 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.RcResolver import androidx.compose.remote.core.operations.Theme import androidx.compose.remote.player.compose.ExperimentalRemotePlayerApi import androidx.compose.remote.player.compose.RemoteComposePlayerFlags import androidx.compose.remote.player.compose.RemoteDocumentPlayer +import androidx.compose.remote.player.compose.embedded.RcDocumentResolver import androidx.compose.remote.player.compose.embedded.RcPlayer import androidx.compose.remote.player.compose.embedded.rememberRcPlayerState import androidx.compose.remote.player.core.RemoteDocument @@ -151,6 +153,7 @@ "poll" -> listOf(BenchTemplate.AppCard, BenchTemplate.AppCard, BenchTemplate.Poll) "stateful" -> listOf(BenchTemplate.Stateful) + "embeddedDoc" -> listOf(BenchTemplate.EmbeddedDoc) else -> listOf(BenchTemplate.AppCard) } val parse = @@ -179,6 +182,8 @@ @Composable private fun FeedScreen(config: FeedConfig) { val context = LocalContext.current + val rcResolver = remember { createFeedRcResolver() } + val documentResolver = remember { createFeedDocumentResolver() } var templateBytes by remember { mutableStateOf<Map<BenchTemplate, ByteArray>?>(null) } LaunchedEffect(config.templates, config.player) { @@ -356,6 +361,7 @@ index = index, tick = tick, eased = config.eased, + documentResolver = documentResolver, ) } } @@ -370,6 +376,7 @@ template = template, index = index, tick = tick, + rcResolver = rcResolver, ) } } @@ -379,7 +386,11 @@ if (bytes == null) { PlaceholderCard(index) } else { - DocumentPlayerFeedCard(bytes = bytes, index = index) + DocumentPlayerFeedCard( + bytes = bytes, + index = index, + rcResolver = rcResolver, + ) } } } @@ -395,6 +406,7 @@ index: Int, tick: Int, eased: Boolean, + documentResolver: RcDocumentResolver, ) { val state = rememberRcPlayerState(doc) if ((template == BenchTemplate.Poll || template == BenchTemplate.Live) && tick > 0) { @@ -426,7 +438,11 @@ trace("RemoteBench:hostUpdate") { state.intState("state").value = (tick + index) % 3 } } } - RcPlayer(state = state, modifier = Modifier.fillMaxWidth().height(FEED_CARD_HEIGHT)) + RcPlayer( + state = state, + modifier = Modifier.fillMaxWidth().height(FEED_CARD_HEIGHT), + documentResolver = documentResolver, + ) } @Composable @@ -436,6 +452,7 @@ template: BenchTemplate, index: Int, tick: Int, + rcResolver: RcResolver, ) { val remoteDoc = remember(index, bytes, prepared) { @@ -445,6 +462,7 @@ modifier = Modifier.fillMaxWidth().height(FEED_CARD_HEIGHT), factory = { context -> RemoteComposePlayer(context).apply { + setRcResolver(rcResolver) layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, @@ -454,6 +472,7 @@ }, update = { player -> player.setTheme(Theme.LIGHT) + player.setRcResolver(rcResolver) if (prepared != null) { player.setPreparedDocument(prepared) } else { @@ -478,7 +497,7 @@ @OptIn(ExperimentalRemotePlayerApi::class) @Composable -private fun DocumentPlayerFeedCard(bytes: ByteArray, index: Int) { +private fun DocumentPlayerFeedCard(bytes: ByteArray, index: Int, rcResolver: RcResolver) { val windowInfo = LocalWindowInfo.current val remoteDoc = remember(index, bytes) { @@ -489,6 +508,7 @@ documentWidth = windowInfo.containerSize.width, documentHeight = windowInfo.containerSize.height, modifier = Modifier.fillMaxWidth().height(FEED_CARD_HEIGHT), + rcResolver = rcResolver, ) }
diff --git a/compose/remote/integration-tests/macrobenchmark/src/main/java/androidx/compose/remote/integration/macrobenchmark/RemoteFeedExtendedBenchmark.kt b/compose/remote/integration-tests/macrobenchmark/src/main/java/androidx/compose/remote/integration/macrobenchmark/RemoteFeedExtendedBenchmark.kt index 53b19ce..d742391 100644 --- a/compose/remote/integration-tests/macrobenchmark/src/main/java/androidx/compose/remote/integration/macrobenchmark/RemoteFeedExtendedBenchmark.kt +++ b/compose/remote/integration-tests/macrobenchmark/src/main/java/androidx/compose/remote/integration/macrobenchmark/RemoteFeedExtendedBenchmark.kt
@@ -62,6 +62,20 @@ fun f1_mixed_empty() = runFeed("empty", defaultCompilation) { putExtra("templates", "mixed") } @Test + fun f1_embeddedDoc_embedded() = + runFeed("embedded", defaultCompilation) { + putExtra("templates", "embeddedDoc") + putExtra("count", 200) + } + + @Test + fun f1_embeddedDoc_view() = + runFeed("view", defaultCompilation) { + putExtra("templates", "embeddedDoc") + putExtra("count", 200) + } + + @Test fun f1_mixed_embedded_none() = runFeed("embedded", CompilationMode.None()) { putExtra("templates", "mixed") }
diff --git a/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/modifier/ComponentIdModifierTest.kt b/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/modifier/ComponentIdModifierTest.kt new file mode 100644 index 0000000..2e56acb --- /dev/null +++ b/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/modifier/ComponentIdModifierTest.kt
@@ -0,0 +1,333 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.modifier + +import android.content.Context +import android.graphics.Bitmap +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.RcPlatformServices +import androidx.compose.remote.core.RcProfiles +import androidx.compose.remote.core.RemoteComposeBuffer +import androidx.compose.remote.core.operations.Header +import androidx.compose.remote.core.operations.layout.managers.BoxLayout +import androidx.compose.remote.core.operations.layout.managers.CanvasLayout +import androidx.compose.remote.core.operations.layout.managers.CollapsibleColumnLayout +import androidx.compose.remote.core.operations.layout.managers.CollapsibleRowLayout +import androidx.compose.remote.core.operations.layout.managers.ColumnLayout +import androidx.compose.remote.core.operations.layout.managers.CoreText +import androidx.compose.remote.core.operations.layout.managers.Custom +import androidx.compose.remote.core.operations.layout.managers.FitBoxLayout +import androidx.compose.remote.core.operations.layout.managers.FlowLayout +import androidx.compose.remote.core.operations.layout.managers.ImageLayout +import androidx.compose.remote.core.operations.layout.managers.RowLayout +import androidx.compose.remote.core.operations.layout.managers.StateLayout +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.RemoteComposeWriterAndroid +import androidx.compose.remote.creation.compose.capture.RemoteComposeCaptureState +import androidx.compose.remote.creation.compose.capture.RemoteComposeCreationState +import androidx.compose.remote.creation.compose.capture.RemoteCreationDisplayInfo +import androidx.compose.remote.creation.compose.layout.RemoteAllStatesLayout +import androidx.compose.remote.creation.compose.layout.RemoteBox +import androidx.compose.remote.creation.compose.layout.RemoteCanvas +import androidx.compose.remote.creation.compose.layout.RemoteCollapsibleColumn +import androidx.compose.remote.creation.compose.layout.RemoteCollapsibleRow +import androidx.compose.remote.creation.compose.layout.RemoteColumn +import androidx.compose.remote.creation.compose.layout.RemoteCustomComponent +import androidx.compose.remote.creation.compose.layout.RemoteFitBox +import androidx.compose.remote.creation.compose.layout.RemoteFlowRow +import androidx.compose.remote.creation.compose.layout.RemoteImage +import androidx.compose.remote.creation.compose.layout.RemoteRow +import androidx.compose.remote.creation.compose.layout.RemoteText +import androidx.compose.remote.creation.compose.state.RemoteImageBitmap +import androidx.compose.remote.creation.compose.state.rdp +import androidx.compose.remote.creation.compose.state.ri +import androidx.compose.remote.creation.compose.state.rs +import androidx.compose.remote.creation.compose.util.TestRemoteComposeBuffer +import androidx.compose.remote.creation.modifiers.PaddingModifier as CorePaddingModifier +import androidx.compose.remote.creation.modifiers.WidthModifier as CoreWidthModifier +import androidx.compose.remote.creation.platform.AndroidxRcPlatformServices +import androidx.compose.remote.creation.platform.RCLogger +import androidx.compose.remote.creation.profile.Profile +import androidx.compose.remote.testing.RemoteCaptureTestRule +import androidx.compose.ui.graphics.asImageBitmap +import androidx.test.core.app.ApplicationProvider +import com.google.common.truth.Truth.assertThat +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlinx.coroutines.test.runTest +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Config.TARGET_SDK]) +class ComponentIdModifierTest { + + @get:Rule val captureRule = RemoteCaptureTestRule() + + private val context: Context = ApplicationProvider.getApplicationContext() + private val loggedMessages = mutableListOf<Pair<RcPlatformServices.LogCategory, String>>() + private lateinit var creationState: RemoteComposeCaptureState + + private class MyRemoteComposeWriterAndroid( + profile: Profile, + buffer: RemoteComposeBuffer, + vararg tags: RemoteComposeWriter.HTag, + ) : RemoteComposeWriterAndroid(profile, buffer, *tags) + + private val experimentalProfile: Profile + get() = + Profile( + CoreDocument.DOCUMENT_API_LEVEL, + RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL, + AndroidxRcPlatformServices(), + ) { creationDisplayInfo, profile, callback -> + RemoteComposeWriterAndroid(creationDisplayInfo, null, profile, callback) + } + + @Before + fun setUp() { + loggedMessages.clear() + val fakeBuffer = TestRemoteComposeBuffer() + val platform = + AndroidxRcPlatformServices( + object : RCLogger { + override fun log(category: RcPlatformServices.LogCategory, message: String) { + loggedMessages.add(category to message) + } + } + ) + val profile = + Profile(CoreDocument.DOCUMENT_API_LEVEL, RcProfiles.PROFILE_ANDROIDX, platform) { + creationDisplayInfo, + profile, + _ -> + MyRemoteComposeWriterAndroid( + profile, + fakeBuffer, + RemoteComposeWriter.hTag(Header.DOC_WIDTH, creationDisplayInfo.width), + RemoteComposeWriter.hTag(Header.DOC_HEIGHT, creationDisplayInfo.height), + RemoteComposeWriter.hTag(Header.DOC_PROFILES, RcProfiles.PROFILE_ANDROIDX), + ) + } + creationState = + RemoteComposeCreationState(RemoteCreationDisplayInfo(500, 500, 160, 1f), null, profile) + } + + @Test + fun standaloneComponentId_setsRecordingModifierIdWithoutWireElements() { + val modifier = RemoteModifier.componentId(42) + val recordingModifier = creationState.toRecordingModifier(modifier) + + assertThat(recordingModifier.componentId).isEqualTo(42) + assertThat(recordingModifier.list).isEmpty() + assertThat(loggedMessages).isEmpty() + } + + @Test + fun toRecordingModifierElement_throwsUnsupportedOperationException() { + val element = ComponentIdModifier(42) + assertFailsWith<UnsupportedOperationException> { + with(element) { creationState.toRecordingModifierElement() } + } + } + + @Test + fun minimumPositiveComponentId_isAllowed() { + val modifier = RemoteModifier.componentId(1) + val recordingModifier = creationState.toRecordingModifier(modifier) + + assertThat(recordingModifier.componentId).isEqualTo(1) + assertThat(recordingModifier.list).isEmpty() + } + + @Test + fun nonPositiveComponentIds_throwIllegalArgumentException() { + assertFailsWith<IllegalArgumentException> { RemoteModifier.componentId(0) } + assertFailsWith<IllegalArgumentException> { RemoteModifier.componentId(-1) } + assertFailsWith<IllegalArgumentException> { RemoteModifier.componentId(-2) } + assertFailsWith<IllegalArgumentException> { RemoteModifier.componentId(Int.MIN_VALUE) } + } + + @Test + fun componentIdChainedWithOtherModifiers_preservesIdAndElements() { + val modifier = RemoteModifier.padding(8.rdp).componentId(101).width(50.rdp) + val recordingModifier = creationState.toRecordingModifier(modifier) + + assertThat(recordingModifier.componentId).isEqualTo(101) + assertThat(recordingModifier.list).hasSize(2) + assertIs<CorePaddingModifier>(recordingModifier.list[0]) + assertIs<CoreWidthModifier>(recordingModifier.list[1]) + assertThat(loggedMessages).isEmpty() + } + + @Test + fun multipleComponentIds_firstOneWinsAndLogsWarning() { + val modifier = RemoteModifier.componentId(10).padding(4.rdp).componentId(20) + val recordingModifier = creationState.toRecordingModifier(modifier) + + assertThat(recordingModifier.componentId).isEqualTo(10) + assertThat(recordingModifier.list).hasSize(1) + assertIs<CorePaddingModifier>(recordingModifier.list[0]) + assertThat(loggedMessages) + .containsExactly( + RcPlatformServices.LogCategory.WARN to + "Ignoring duplicate ComponentIdModifier (ComponentIdModifier(id=20)); " + + "only the first instance is applied" + ) + + loggedMessages.clear() + val minFirstModifier = RemoteModifier.componentId(1).componentId(20) + assertThat(creationState.toRecordingModifier(minFirstModifier).componentId).isEqualTo(1) + assertThat(loggedMessages) + .containsExactly( + RcPlatformServices.LogCategory.WARN to + "Ignoring duplicate ComponentIdModifier (ComponentIdModifier(id=20)); " + + "only the first instance is applied" + ) + } + + @Test + fun componentId_appliedToAllStandardComponents() = runTest { + val bitmap = + RemoteImageBitmap(Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888).asImageBitmap()) + + val doc = + captureRule.captureDocument(context) { + RemoteColumn(modifier = RemoteModifier.componentId(100)) { + RemoteBox(modifier = RemoteModifier.componentId(101)) { + RemoteText("Hello".rs, modifier = RemoteModifier.componentId(102)) + } + RemoteBox(modifier = RemoteModifier.componentId(103)) + RemoteRow(modifier = RemoteModifier.componentId(104)) { + RemoteImage( + bitmap = bitmap, + contentDescription = null, + modifier = RemoteModifier.componentId(105), + ) + RemoteCanvas(modifier = RemoteModifier.componentId(106).size(20.rdp)) {} + } + RemoteFitBox(modifier = RemoteModifier.componentId(107)) { + RemoteBox(modifier = RemoteModifier.size(10.rdp)) + } + RemoteCollapsibleColumn(modifier = RemoteModifier.componentId(108)) { + RemoteBox(modifier = RemoteModifier.size(10.rdp)) + } + RemoteCollapsibleRow(modifier = RemoteModifier.componentId(109)) { + RemoteBox(modifier = RemoteModifier.size(10.rdp)) + } + RemoteAllStatesLayout( + currentState = 0.ri, + stateCount = 2, + modifier = RemoteModifier.componentId(110), + ) { _ -> + RemoteBox(modifier = RemoteModifier.size(10.rdp)) + } + } + } + + assertIs<ColumnLayout>(doc.getComponent(100)) + assertIs<BoxLayout>(doc.getComponent(101)) + assertIs<CoreText>(doc.getComponent(102)) + assertIs<BoxLayout>(doc.getComponent(103)) + assertIs<RowLayout>(doc.getComponent(104)) + assertIs<ImageLayout>(doc.getComponent(105)) + assertIs<CanvasLayout>(doc.getComponent(106)) + assertIs<FitBoxLayout>(doc.getComponent(107)) + assertIs<CollapsibleColumnLayout>(doc.getComponent(108)) + assertIs<CollapsibleRowLayout>(doc.getComponent(109)) + assertIs<StateLayout>(doc.getComponent(110)) + } + + @Test + fun componentId_minimumPositiveId_appliedInDocument() = runTest { + val doc = + captureRule.captureDocument(context) { + RemoteBox(modifier = RemoteModifier.componentId(1).size(20.rdp)) + } + + val box = assertIs<BoxLayout>(doc.getComponent(1)) + assertThat(box.componentId).isEqualTo(1) + } + + @Test + fun componentId_multipleChained_firstWinsInDocument() = runTest { + val doc = + captureRule.captureDocument(context) { + RemoteBox(modifier = RemoteModifier.componentId(10).componentId(20).size(20.rdp)) + } + + assertIs<BoxLayout>(doc.getComponent(10)) + assertThat(doc.getComponent(20)).isNull() + } + + @Test + fun componentId_appliedToExperimentalComponents() = runTest { + val doc = + captureRule.captureDocument(context, profile = experimentalProfile) { + RemoteFlowRow(modifier = RemoteModifier.componentId(300)) { + RemoteCustomComponent( + name = "test_custom", + modifier = RemoteModifier.componentId(301).size(40.rdp), + ) + } + } + + val flow = assertIs<FlowLayout>(doc.getComponent(300)) + assertThat(flow.componentId).isEqualTo(300) + val custom = assertIs<Custom>(doc.getComponent(301)) + assertThat(custom.componentId).isEqualTo(301) + } + + @Test + fun componentId_appliedToCanvasCustomAndStateLayout() = runTest { + val doc = + captureRule.captureDocument(context, profile = experimentalProfile) { + RemoteCanvas(modifier = RemoteModifier.componentId(400).size(100.rdp)) { + remoteCanvas.custom( + config = "canvas_custom", + modifier = RemoteModifier.componentId(401).size(20.rdp), + ) + remoteCanvas.startStateLayout( + modifier = RemoteModifier.componentId(402), + currentStateId = 0, + ) + remoteCanvas.endStateLayout() + } + } + + assertIs<CanvasLayout>(doc.getComponent(400)) + assertIs<Custom>(doc.getComponent(401)) + assertIs<StateLayout>(doc.getComponent(402)) + } + + @Test + fun withoutComponentId_autoGeneratesNegativeId() = runTest { + val doc = + captureRule.captureDocument(context) { + RemoteBox(modifier = RemoteModifier.size(20.rdp)) + } + + val root = assertNotNull(doc.rootLayoutComponent) + val box = root.list.filterIsInstance<BoxLayout>().single() + assertThat(box.componentId).isLessThan(-1) + } +}
diff --git a/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifierEqualityTest.kt b/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifierEqualityTest.kt index 1db22d2..7a961cb 100644 --- a/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifierEqualityTest.kt +++ b/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifierEqualityTest.kt
@@ -209,6 +209,8 @@ RemoteModifier.horizontalScroll(scrollState), RemoteModifier.horizontalScroll(scrollState), ) + assertStructurallyEqual(RemoteModifier.componentId(42), RemoteModifier.componentId(42)) + assertThat(RemoteModifier.componentId(42)).isNotEqualTo(RemoteModifier.componentId(43)) } @Test
diff --git a/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapTest.kt b/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapTest.kt index e393e19..1af34ff 100644 --- a/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapTest.kt +++ b/compose/remote/remote-creation-compose/src/androidHostTest/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapTest.kt
@@ -84,5 +84,20 @@ assertThat(bitmap).isNotNull() assertThat(bitmap.cacheKey) .isEqualTo(RemoteNamedCacheKey(RemoteValue.Domain.User, "avatar")) + assertThat(bitmap.urlOrNull).isEqualTo(url) + assertThat(bitmap.declaredWidth).isEqualTo(300) + assertThat(bitmap.declaredHeight).isEqualTo(200) + assertThat(bitmap.hasIntrinsicDimensions).isFalse() + } + + @Test + fun remoteBitmap_encodedImageBitmap_exposesDeclaredDimensions() { + val bitmap = Bitmap.createBitmap(24, 16, Bitmap.Config.ARGB_8888).asImageBitmap() + val remoteBitmap = RemoteImageBitmap(bitmap) + + assertThat(remoteBitmap.urlOrNull).isNull() + assertThat(remoteBitmap.declaredWidth).isEqualTo(24) + assertThat(remoteBitmap.declaredHeight).isEqualTo(16) + assertThat(remoteBitmap.hasIntrinsicDimensions).isFalse() } }
diff --git a/compose/remote/remote-creation-compose/src/androidMain/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapCompose.android.kt b/compose/remote/remote-creation-compose/src/androidMain/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapCompose.android.kt index 3ab8a10..4d31ede 100644 --- a/compose/remote/remote-creation-compose/src/androidMain/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapCompose.android.kt +++ b/compose/remote/remote-creation-compose/src/androidMain/kotlin/androidx/compose/remote/creation/compose/state/RemoteImageBitmapCompose.android.kt
@@ -35,6 +35,8 @@ MutableRemoteImageBitmap( constantValueOrNull = value, cacheKey = RemoteConstantCacheKey(value), + declaredWidth = value.width, + declaredHeight = value.height, idProvider = { creationState -> creationState.document.addBitmap(value.asAndroidBitmap()) }, ) @@ -57,6 +59,8 @@ MutableRemoteImageBitmap( constantValueOrNull = null, cacheKey = RemoteNamedCacheKey(domain, name), + declaredWidth = defaultValue.width, + declaredHeight = defaultValue.height, ) { creationState -> creationState.document.addNamedBitmap(domain.prefixed(name), defaultValue.asAndroidBitmap()) } @@ -72,6 +76,8 @@ MutableRemoteImageBitmap( constantValueOrNull = initialValue, cacheKey = RemoteStateInstanceKey(), + declaredWidth = initialValue.width, + declaredHeight = initialValue.height, idProvider = { creationState -> creationState.document.addBitmap(initialValue.asAndroidBitmap()) },
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/capture/CanvasOperationBuffer.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/capture/CanvasOperationBuffer.kt index 49a3f54..1aadf0e 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/capture/CanvasOperationBuffer.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/capture/CanvasOperationBuffer.kt
@@ -19,6 +19,7 @@ import androidx.collection.MutableObjectIntMap import androidx.compose.remote.creation.compose.layout.CustomPropertyEntry import androidx.compose.remote.creation.compose.modifier.RemoteModifier +import androidx.compose.remote.creation.compose.modifier.UNSET_COMPONENT_ID import androidx.compose.remote.creation.compose.modifier.prepareModifiers import androidx.compose.remote.creation.compose.state.RemoteBoolean import androidx.compose.remote.creation.compose.state.RemoteFloat @@ -524,7 +525,14 @@ corePropList.add(properties[i].toCustomProperty(creationState)) } val writeModifiers = creationState.prepareModifiers(modifier) - val componentId = writer.allocateId() + val componentId = + if (writeModifiers.componentId != UNSET_COMPONENT_ID) { + writeModifiers.componentId + } else { + // TODO(b/590744731): allocateId() returns positive IDs that can collide with an + // explicit componentId set on another component. + writer.allocateId() + } writer.startCustom(config, corePropList, componentId) { writeModifiers(writer) } childSpan?.record(writer, creationState) writer.endCustom()
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteAllStatesLayout.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteAllStatesLayout.kt index 9b20e74..41f8a5c 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteAllStatesLayout.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteAllStatesLayout.kt
@@ -45,7 +45,10 @@ val writeModifiers = scope.prepareModifiers(modifier) val currentStateId = creationState.getId(currentState) - creationState.document.startStateLayout(currentStateId) { + creationState.document.startStateLayout( + currentStateId, + componentId = writeModifiers.componentId, + ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteBox.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteBox.kt index 6a797ff..2c8839f 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteBox.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteBox.kt
@@ -37,6 +37,7 @@ creationState.document.startBox( horizontalAlignment.toRemote(layoutDirection), verticalAlignment.toRemote(), + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvas.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvas.kt index 8dadfc7..73f027e 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvas.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvas.kt
@@ -1919,7 +1919,11 @@ currentStateId: Int, ) { val writeModifiers = creationState.prepareModifiers(modifier) - recordRenderingOp { document.startStateLayout(currentStateId) { writeModifiers(document) } } + recordRenderingOp { + document.startStateLayout(currentStateId, componentId = writeModifiers.componentId) { + writeModifiers(document) + } + } } /** Ends a state layout. */
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvasComposable.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvasComposable.kt index 96444c9..3baccb8 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvasComposable.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCanvasComposable.kt
@@ -29,7 +29,9 @@ val scope = overriddenScope(remoteCanvas) val writeModifiers = scope.prepareModifiers(modifier) val canvasComponentId = - creationState.document.startCanvas { writeModifiers(creationState.document) } + creationState.document.startCanvas(componentId = writeModifiers.componentId) { + writeModifiers(creationState.document) + } val previousNode = creationState.currentRenderingNode creationState.currentRenderingNode = this
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleColumn.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleColumn.kt index c3feac6..0e89005 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleColumn.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleColumn.kt
@@ -63,6 +63,7 @@ horizontalAlignment.toRemote(layoutDirection), verticalArrangement.toRemote(), spacedBy, + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleRow.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleRow.kt index 531eab5..85dbe9d 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleRow.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCollapsibleRow.kt
@@ -63,6 +63,7 @@ horizontalArrangement.toRemote(layoutDirection), verticalAlignment.toRemote(), spacedBy, + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteColumn.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteColumn.kt index 012dd5a..2bc91f1 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteColumn.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteColumn.kt
@@ -59,6 +59,7 @@ horizontalAlignment.toRemote(layoutDirection), verticalArrangement.toRemote(), spacedBy, + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCustomComponent.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCustomComponent.kt index b0ec627e..00a8394 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCustomComponent.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteCustomComponent.kt
@@ -20,6 +20,7 @@ import androidx.compose.remote.core.operations.layout.managers.Custom.CustomProperty import androidx.compose.remote.creation.compose.capture.RemoteComposeCreationState import androidx.compose.remote.creation.compose.modifier.RemoteModifier +import androidx.compose.remote.creation.compose.modifier.UNSET_COMPONENT_ID import androidx.compose.remote.creation.compose.modifier.prepareModifiers import androidx.compose.remote.creation.compose.state.RemoteBoolean import androidx.compose.remote.creation.compose.state.RemoteColor @@ -40,7 +41,14 @@ override fun render(creationState: RemoteComposeCreationState, remoteCanvas: RemoteCanvas) { val scope = overriddenScope(remoteCanvas) val writeModifiers = scope.prepareModifiers(modifier) - val componentId = creationState.document.allocateId() + val componentId = + if (writeModifiers.componentId != UNSET_COMPONENT_ID) { + writeModifiers.componentId + } else { + // TODO(b/590744731): allocateId() returns positive IDs that can collide with an + // explicit componentId set on another component. + creationState.document.allocateId() + } val coreProperties = RemoteCustomPropertiesScope(creationState).apply(properties).properties creationState.document.startCustom(name, coreProperties, componentId) { writeModifiers(creationState.document) @@ -63,6 +71,7 @@ * @param content The remote children of the custom component. * @param properties Custom property definitions to pass to the custom component. */ +// TODO(b/590744731): Address componentId collision with allocateId() before making this public. @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Composable @RemoteComposable
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFitBox.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFitBox.kt index cf2d461..4e9ec2d 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFitBox.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFitBox.kt
@@ -30,6 +30,7 @@ creationState.document.startFitBox( contentAlignment.horizontal.toRemote(layoutDirection), contentAlignment.vertical.toRemote(), + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFlowRow.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFlowRow.kt index 4ec1374..fe4c2f2 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFlowRow.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteFlowRow.kt
@@ -39,6 +39,7 @@ maxItemsInEachRow, maxLines, spacedBy, + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteImage.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteImage.kt index 00fdc40..1be33b3 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteImage.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteImage.kt
@@ -46,6 +46,7 @@ RemoteBitmapId(bitmapId), contentScale.value, alphaValue, + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteRow.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteRow.kt index f9bbf4d..025d64b 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteRow.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteRow.kt
@@ -69,6 +69,7 @@ horizontalArrangement.toRemote(layoutDirection), verticalAlignment.toRemote(), spacedBy, + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteText.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteText.kt index 5f9a7c5..a79ceb2 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteText.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/layout/RemoteText.kt
@@ -306,6 +306,7 @@ fontAxisValues, false, // autosize 0, // flags + componentId = writeModifiers.componentId, ) { writeModifiers(creationState.document) }
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/modifier/ComponentIdModifier.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/modifier/ComponentIdModifier.kt new file mode 100644 index 0000000..e940aff --- /dev/null +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/modifier/ComponentIdModifier.kt
@@ -0,0 +1,60 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.modifier + +import androidx.annotation.IntRange +import androidx.annotation.RestrictTo +import androidx.compose.remote.creation.compose.state.RemoteStateScope +import androidx.compose.remote.creation.modifiers.RecordingModifier +import androidx.compose.runtime.Stable + +/** Sentinel component ID indicating no explicit ID was assigned (auto-generated by the writer). */ +internal const val UNSET_COMPONENT_ID: Int = -1 + +internal data class ComponentIdModifier(val id: Int) : RemoteModifier.Element { + init { + require(id > 0) { "Component ID must be greater than 0, got $id" } + } + + override fun RemoteStateScope.toRecordingModifier(): RecordingModifier = + RecordingModifier().componentId(id) + + override fun RemoteStateScope.toRecordingModifierElement(): RecordingModifier.Element = + throw UnsupportedOperationException( + "ComponentIdModifier cannot be represented as a RecordingModifier.Element; " + + "use toRecordingModifier() instead." + ) +} + +/** + * Assigns an explicit component [id] to this layout component. + * + * * Note: [id] must be strictly positive (`> 0`). `0` and negative IDs are reserved (`0` is used as + * a sentinel for unset/disabled references, `-1` is the auto-generation sentinel, and `-2`, `-3`, + * ... are auto-generated component IDs). + * * Note: If multiple `componentId` modifiers are chained, the first (outermost) one takes + * precedence. + * + * @param id positive identifier (`> 0`) to assign to this component + * @return a [RemoteModifier] that assigns [id] to the component + * @throws IllegalArgumentException if [id] is not greater than `0` + */ +// TODO(b/590744731): Address componentId collision issues before making this public. +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +@Stable +public fun RemoteModifier.componentId(@IntRange(from = 1) id: Int): RemoteModifier = + then(ComponentIdModifier(id))
diff --git a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifier.kt b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifier.kt index 378060c..c7d143c 100644 --- a/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifier.kt +++ b/compose/remote/remote-creation-compose/src/jvmAndAndroidMain/kotlin/androidx/compose/remote/creation/compose/modifier/RemoteModifier.kt
@@ -165,15 +165,16 @@ } /** - * Evaluates [modifier] in this [RemoteStateScope] eagerly (preserving expression emission order - * prior to container start) and returns a callback that emits the modifier elements into a - * [RemoteDocumentWriter]. + * Prepared modifiers resulting from eagerly evaluating a [RemoteModifier] in a [RemoteStateScope], + * carrying the resolved [componentId] (or `-1` if unset) alongside a callback to emit modifier + * elements into a [RemoteDocumentWriter]. */ -internal fun RemoteStateScope.prepareModifiers( - modifier: RemoteModifier -): (RemoteDocumentWriter) -> Unit { - val recordingModifier = toRecordingModifier(modifier) - return { writer -> +@JvmInline +internal value class PreparedModifiers(private val recordingModifier: RecordingModifier) { + val componentId: Int + get() = recordingModifier.componentId + + operator fun invoke(writer: RemoteDocumentWriter) { val adapter = writer as? RemoteComposeWriterAdapter ?: throw UnsupportedOperationException( @@ -183,6 +184,14 @@ } } +/** + * Evaluates [modifier] in this [RemoteStateScope] eagerly (preserving expression emission order + * prior to container start) and returns a [PreparedModifiers] carrying the component ID and a + * callback that emits the modifier elements into a [RemoteDocumentWriter]. + */ +internal fun RemoteStateScope.prepareModifiers(modifier: RemoteModifier): PreparedModifiers = + PreparedModifiers(toRecordingModifier(modifier)) + // Workaround for b/563261712: Modifier element types that do not support multiple instances // on the same component. When chained, the outer (first) modifier takes precedence and // subsequent duplicates are stripped with a logged warning. @@ -232,6 +241,17 @@ seenDrawWithContent = true acc.then(with(element) { scope.toRecordingModifierElement() }) } + } else if (element is ComponentIdModifier) { + if (acc.componentId == UNSET_COMPONENT_ID) { + acc.componentId(element.id) + } else { + scope.creationState.platform.log( + LogCategory.WARN, + "Ignoring duplicate ComponentIdModifier ($element); " + + "only the first instance is applied", + ) + acc + } } else { acc.then(with(element) { scope.toRecordingModifierElement() }) }
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/IntervalEnvironment.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/IntervalEnvironment.kt new file mode 100644 index 0000000..481a988 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/IntervalEnvironment.kt
@@ -0,0 +1,395 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.creation.compose.state.RemoteNamedCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateIdKey +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.document.intervals.ColorInterval +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.SlotInterval +import androidx.compose.remote.document.intervals.StringSummary + +/** + * Abstraction supplying static domain bounds for leaf [RemoteStateCacheKey]s (wire IDs, named + * variables, array dereferences, and path-sensitive key overrides) to + * [RemoteValueIntervalEvaluator] and [IntervalOptimizer]. + * + * Standalone callers can use [MapIntervalEnvironment]; document-level analyzers can implement this + * interface directly over their document slot tables without duplicating expression evaluation or + * optimization logic. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public interface IntervalEnvironment { + /** Returns the static float interval for a wire variable/context [id]. */ + public fun floatForStateId(id: Int): FloatInterval = + SlotInterval.systemGlobalOrNull(id)?.toFloatInterval() ?: FloatInterval.UNBOUNDED + + /** Returns the static integer interval for a wire variable/context [id]. */ + public fun intForStateId(id: Int): IntInterval = + SlotInterval.systemGlobalOrNull(id)?.toIntInterval() ?: IntInterval.UNBOUNDED + + /** Returns the static string summary for a wire string variable [id]. */ + public fun stringForStateId(id: Int): StringSummary = StringSummary.UNKNOWN + + /** Returns the static color interval for a wire color variable [id]. */ + public fun colorForStateId(id: Int): ColorInterval = ColorInterval.UNKNOWN + + /** Returns the static float interval for a named variable [key]. */ + public fun floatForNamed(key: RemoteNamedCacheKey): FloatInterval = FloatInterval.UNBOUNDED + + /** Returns the static integer interval for a named variable [key]. */ + public fun intForNamed(key: RemoteNamedCacheKey): IntInterval = IntInterval.UNBOUNDED + + /** Returns the static string summary for a named variable [key]. */ + public fun stringForNamed(key: RemoteNamedCacheKey): StringSummary = StringSummary.UNKNOWN + + /** Returns the static color interval for a named variable [key]. */ + public fun colorForNamed(key: RemoteNamedCacheKey): ColorInterval = ColorInterval.UNKNOWN + + /** Returns the static float interval for indexing wire float array [arrayId] at [index]. */ + public fun floatArrayElement(arrayId: Int, index: FloatInterval): FloatInterval = + FloatInterval.UNBOUNDED + + /** + * Returns `true` if a [RemoteStateIdKey] referencing [id] is eligible for point-constant + * folding (e.g., `false` if [id] belongs to an output namespace or carries an animation spec). + */ + public fun canFoldStateId(id: Int): Boolean = true + + /** Returns any path-sensitive float override installed for [key], or `null` if none. */ + public fun floatOverride(key: RemoteStateCacheKey): FloatInterval? = null + + /** Returns any path-sensitive integer override installed for [key], or `null` if none. */ + public fun intOverride(key: RemoteStateCacheKey): IntInterval? = null + + /** + * Returns a derived [IntervalEnvironment] in which [key] is narrowed to [interval] (intersected + * with any existing float bound or override on [key]). + */ + public fun withFloatNarrowing( + key: RemoteStateCacheKey, + interval: FloatInterval, + ): IntervalEnvironment { + val existing = existingFloatBoundOrNull(key) + val narrowed = if (existing != null) existing.intersect(interval) else interval + if (narrowed.isEmpty || narrowed == existing) return this + return OverlaidIntervalEnvironment(this, key, floatInterval = narrowed) + } + + /** + * Returns a derived [IntervalEnvironment] in which [key] is narrowed to [interval] (intersected + * with any existing integer bound or override on [key]). + */ + public fun withIntNarrowing( + key: RemoteStateCacheKey, + interval: IntInterval, + ): IntervalEnvironment { + val existing = existingIntBoundOrNull(key) + val narrowed = if (existing != null) existing.intersect(interval) else interval + if (narrowed.isEmpty || narrowed == existing) return this + return OverlaidIntervalEnvironment(this, key, intInterval = narrowed) + } + + /** + * Returns a derived [IntervalEnvironment] refined by assuming the boolean expression [key] + * evaluates to [holds]. + */ + public fun refine(key: RemoteStateCacheKey, holds: Boolean): IntervalEnvironment = + refineEnvironmentByBooleanKey(this, key, holds) + + /** + * Returns a derived [IntervalEnvironment] refined by assuming `lhs <comparison> rhs` holds in + * either the integer ([asInt] = `true`) or float ([asInt] = `false`) domain. + */ + public fun narrowComparison( + comparison: IntervalComparison, + lhs: RemoteStateCacheKey, + rhs: RemoteStateCacheKey, + asInt: Boolean = false, + ): IntervalEnvironment = + if (asInt) { + narrowIntOperands(this, comparison, lhs, rhs) + } else { + narrowFloatOperands(this, comparison, lhs, rhs) + } +} + +internal fun IntervalEnvironment.existingFloatBoundOrNull( + key: RemoteStateCacheKey +): FloatInterval? = + floatOverride(key) + ?: when (key) { + is RemoteNamedCacheKey -> floatForNamed(key) + is RemoteStateIdKey -> floatForStateId(key.id) + else -> null + } + +internal fun IntervalEnvironment.existingIntBoundOrNull(key: RemoteStateCacheKey): IntInterval? = + intOverride(key) + ?: when (key) { + is RemoteNamedCacheKey -> intForNamed(key) + is RemoteStateIdKey -> intForStateId(key.id) + else -> null + } + +/** + * Immutable map-backed [IntervalEnvironment] for standalone expression interval analysis and + * optimization without requiring a full document snapshot. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class MapIntervalEnvironment +@JvmOverloads +constructor( + public val canvasWidth: Float? = null, + public val canvasHeight: Float? = null, + private val stateIdFloats: Map<Int, FloatInterval> = emptyMap(), + private val stateIdInts: Map<Int, IntInterval> = emptyMap(), + private val stateIdStrings: Map<Int, StringSummary> = emptyMap(), + private val stateIdColors: Map<Int, ColorInterval> = emptyMap(), + private val namedFloats: Map<String, FloatInterval> = emptyMap(), + private val namedInts: Map<String, IntInterval> = emptyMap(), + private val namedStrings: Map<String, StringSummary> = emptyMap(), + private val namedColors: Map<String, ColorInterval> = emptyMap(), + private val keyFloatOverrides: Map<RemoteStateCacheKey, FloatInterval> = emptyMap(), + private val keyIntOverrides: Map<RemoteStateCacheKey, IntInterval> = emptyMap(), + private val nonFoldableStateIds: Set<Int> = emptySet(), +) : IntervalEnvironment { + + override fun floatForStateId(id: Int): FloatInterval = + stateIdFloats[id] + ?: stateIdInts[id]?.toFloatInterval() + ?: SlotInterval.systemGlobalOrNull(id, canvasWidth, canvasHeight)?.toFloatInterval() + ?: FloatInterval.UNBOUNDED + + override fun intForStateId(id: Int): IntInterval = + stateIdInts[id] + ?: stateIdFloats[id]?.let { SlotInterval.fromFloat(it).toIntInterval() } + ?: SlotInterval.systemGlobalOrNull(id, canvasWidth, canvasHeight)?.toIntInterval() + ?: IntInterval.UNBOUNDED + + override fun stringForStateId(id: Int): StringSummary = + stateIdStrings[id] ?: StringSummary.UNKNOWN + + override fun colorForStateId(id: Int): ColorInterval = + stateIdColors[id] ?: ColorInterval.UNKNOWN + + override fun floatForNamed(key: RemoteNamedCacheKey): FloatInterval { + val wireName = key.wireName + return namedFloats[wireName] + ?: namedInts[wireName]?.toFloatInterval() + ?: FloatInterval.UNBOUNDED + } + + override fun intForNamed(key: RemoteNamedCacheKey): IntInterval { + val wireName = key.wireName + return namedInts[wireName] + ?: namedFloats[wireName]?.let { SlotInterval.fromFloat(it).toIntInterval() } + ?: IntInterval.UNBOUNDED + } + + override fun stringForNamed(key: RemoteNamedCacheKey): StringSummary = + namedStrings[key.wireName] ?: StringSummary.UNKNOWN + + override fun colorForNamed(key: RemoteNamedCacheKey): ColorInterval = + namedColors[key.wireName] ?: ColorInterval.UNKNOWN + + override fun canFoldStateId(id: Int): Boolean = id !in nonFoldableStateIds + + override fun floatOverride(key: RemoteStateCacheKey): FloatInterval? = keyFloatOverrides[key] + + override fun intOverride(key: RemoteStateCacheKey): IntInterval? = keyIntOverrides[key] + + override fun withFloatNarrowing( + key: RemoteStateCacheKey, + interval: FloatInterval, + ): MapIntervalEnvironment { + val existing = existingFloatBoundOrNull(key) + val narrowed = if (existing != null) existing.intersect(interval) else interval + if (narrowed.isEmpty || narrowed == existing) return this + val updated = LinkedHashMap(keyFloatOverrides) + updated[key] = narrowed + return copy(keyFloatOverrides = updated) + } + + override fun withIntNarrowing( + key: RemoteStateCacheKey, + interval: IntInterval, + ): MapIntervalEnvironment { + val existing = existingIntBoundOrNull(key) + val narrowed = if (existing != null) existing.intersect(interval) else interval + if (narrowed.isEmpty || narrowed == existing) return this + val updated = LinkedHashMap(keyIntOverrides) + updated[key] = narrowed + return copy(keyIntOverrides = updated) + } + + /** Returns a copy binding named float variable `domain.prefixed(name)` to [interval]. */ + @JvmOverloads + public fun withNamedFloat( + name: String, + interval: FloatInterval, + domain: RemoteValue.Domain = RemoteValue.Domain.User, + ): MapIntervalEnvironment { + val updated = LinkedHashMap(namedFloats) + updated[domain.prefixed(name)] = interval + return copy(namedFloats = updated) + } + + /** Returns a copy binding named integer variable `domain.prefixed(name)` to [interval]. */ + @JvmOverloads + public fun withNamedInt( + name: String, + interval: IntInterval, + domain: RemoteValue.Domain = RemoteValue.Domain.User, + ): MapIntervalEnvironment { + val updated = LinkedHashMap(namedInts) + updated[domain.prefixed(name)] = interval + return copy(namedInts = updated) + } + + /** Returns a copy binding named string variable `domain.prefixed(name)` to [summary]. */ + @JvmOverloads + public fun withNamedString( + name: String, + summary: StringSummary, + domain: RemoteValue.Domain = RemoteValue.Domain.User, + ): MapIntervalEnvironment { + val updated = LinkedHashMap(namedStrings) + updated[domain.prefixed(name)] = summary + return copy(namedStrings = updated) + } + + /** Returns a copy binding named color variable `domain.prefixed(name)` to [interval]. */ + @JvmOverloads + public fun withNamedColor( + name: String, + interval: ColorInterval, + domain: RemoteValue.Domain = RemoteValue.Domain.User, + ): MapIntervalEnvironment { + val updated = LinkedHashMap(namedColors) + updated[domain.prefixed(name)] = interval + return copy(namedColors = updated) + } + + /** Returns a copy binding wire variable [id] to float [interval]. */ + public fun withStateIdFloat(id: Int, interval: FloatInterval): MapIntervalEnvironment { + val updated = LinkedHashMap(stateIdFloats) + updated[id] = interval + return copy(stateIdFloats = updated) + } + + /** Returns a copy binding wire variable [id] to integer [interval]. */ + public fun withStateIdInt(id: Int, interval: IntInterval): MapIntervalEnvironment { + val updated = LinkedHashMap(stateIdInts) + updated[id] = interval + return copy(stateIdInts = updated) + } + + /** Returns a copy marking wire variable [id] as ineligible for constant folding. */ + public fun withNonFoldableStateId(id: Int): MapIntervalEnvironment { + val updated = LinkedHashSet(nonFoldableStateIds) + updated.add(id) + return copy(nonFoldableStateIds = updated) + } + + private fun copy( + stateIdFloats: Map<Int, FloatInterval> = this.stateIdFloats, + stateIdInts: Map<Int, IntInterval> = this.stateIdInts, + stateIdStrings: Map<Int, StringSummary> = this.stateIdStrings, + stateIdColors: Map<Int, ColorInterval> = this.stateIdColors, + namedFloats: Map<String, FloatInterval> = this.namedFloats, + namedInts: Map<String, IntInterval> = this.namedInts, + namedStrings: Map<String, StringSummary> = this.namedStrings, + namedColors: Map<String, ColorInterval> = this.namedColors, + keyFloatOverrides: Map<RemoteStateCacheKey, FloatInterval> = this.keyFloatOverrides, + keyIntOverrides: Map<RemoteStateCacheKey, IntInterval> = this.keyIntOverrides, + nonFoldableStateIds: Set<Int> = this.nonFoldableStateIds, + ): MapIntervalEnvironment = + MapIntervalEnvironment( + canvasWidth = canvasWidth, + canvasHeight = canvasHeight, + stateIdFloats = stateIdFloats, + stateIdInts = stateIdInts, + stateIdStrings = stateIdStrings, + stateIdColors = stateIdColors, + namedFloats = namedFloats, + namedInts = namedInts, + namedStrings = namedStrings, + namedColors = namedColors, + keyFloatOverrides = keyFloatOverrides, + keyIntOverrides = keyIntOverrides, + nonFoldableStateIds = nonFoldableStateIds, + ) + + public companion object { + /** Empty environment providing only built-in system global bounds. */ + public val EMPTY: MapIntervalEnvironment = MapIntervalEnvironment() + } +} + +private class OverlaidIntervalEnvironment( + private val base: IntervalEnvironment, + private val key: RemoteStateCacheKey, + private val floatInterval: FloatInterval? = null, + private val intInterval: IntInterval? = null, +) : IntervalEnvironment { + override fun floatForStateId(id: Int): FloatInterval = base.floatForStateId(id) + + override fun intForStateId(id: Int): IntInterval = base.intForStateId(id) + + override fun stringForStateId(id: Int): StringSummary = base.stringForStateId(id) + + override fun colorForStateId(id: Int): ColorInterval = base.colorForStateId(id) + + override fun floatForNamed(key: RemoteNamedCacheKey): FloatInterval = base.floatForNamed(key) + + override fun intForNamed(key: RemoteNamedCacheKey): IntInterval = base.intForNamed(key) + + override fun stringForNamed(key: RemoteNamedCacheKey): StringSummary = base.stringForNamed(key) + + override fun colorForNamed(key: RemoteNamedCacheKey): ColorInterval = base.colorForNamed(key) + + override fun floatArrayElement(arrayId: Int, index: FloatInterval): FloatInterval = + base.floatArrayElement(arrayId, index) + + override fun canFoldStateId(id: Int): Boolean = base.canFoldStateId(id) + + override fun floatOverride(key: RemoteStateCacheKey): FloatInterval? { + if (key != this.key || floatInterval == null) return base.floatOverride(key) + val baseBound = base.existingFloatBoundOrNull(key) + return if (baseBound != null) { + baseBound.intersect(floatInterval).takeIf { !it.isEmpty } ?: baseBound + } else { + floatInterval + } + } + + override fun intOverride(key: RemoteStateCacheKey): IntInterval? { + if (key != this.key || intInterval == null) return base.intOverride(key) + val baseBound = base.existingIntBoundOrNull(key) + return if (baseBound != null) { + baseBound.intersect(intInterval).takeIf { !it.isEmpty } ?: baseBound + } else { + intInterval + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/IntervalOptimizer.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/IntervalOptimizer.kt new file mode 100644 index 0000000..841db9d --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/IntervalOptimizer.kt
@@ -0,0 +1,905 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.creation.compose.state.BooleanOperationKey +import androidx.compose.remote.creation.compose.state.MutableRemoteValue +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteColor +import androidx.compose.remote.creation.compose.state.RemoteDp +import androidx.compose.remote.creation.compose.state.RemoteEnum +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteFloatArray +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteIntArray +import androidx.compose.remote.creation.compose.state.RemoteNamedCacheKey +import androidx.compose.remote.creation.compose.state.RemoteOperation +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteString +import androidx.compose.remote.creation.compose.state.RemoteStringArray +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.RemoteValueKind +import androidx.compose.remote.creation.compose.state.adaptToType +import androidx.compose.remote.creation.compose.state.cacheKey +import androidx.compose.remote.creation.compose.state.rf +import androidx.compose.remote.creation.compose.state.ri +import androidx.compose.remote.creation.compose.state.valueKind +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.TriState +import java.util.HashMap +import java.util.HashSet + +/** + * Feature switches controlling which built-in optimizations [IntervalOptimizer] performs. + * + * @property pruneTernaries eliminates statically dead select/ternary branches and collapses + * identical arms + * @property refineTernaryBranches refines operand intervals inside surviving select/ternary + * branches using branch conditions + * @property foldComparisons folds statically provable relational comparisons and boolean predicates + * into constants + * @property simplifyRangeMath simplifies redundant range-clamping/rounding operations (`abs`, + * `min`, `max`, `clamp`, integer-valued `floor`/`ceil`/`round`, endpoint color `lerp`) + * @property foldPointConstants folds pure deterministic expressions whose interval collapses to a + * single point into constants + * @property foldArrayGets folds literal array lookups with statically constant/point indices into + * the selected element + * @property lowerTwoElementArraysToSelect lowers 2-element literal array lookups with indices + * bounded to `[0, 1]` into conditional selects + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class IntervalOptimizerConfig +@JvmOverloads +constructor( + public val pruneTernaries: Boolean = true, + public val refineTernaryBranches: Boolean = true, + public val foldComparisons: Boolean = true, + public val simplifyRangeMath: Boolean = true, + public val foldPointConstants: Boolean = true, + public val foldArrayGets: Boolean = true, + public val lowerTwoElementArraysToSelect: Boolean = true, +) { + /** Returns a copy of this configuration with the specified overrides. */ + public fun copy( + pruneTernaries: Boolean = this.pruneTernaries, + refineTernaryBranches: Boolean = this.refineTernaryBranches, + foldComparisons: Boolean = this.foldComparisons, + simplifyRangeMath: Boolean = this.simplifyRangeMath, + foldPointConstants: Boolean = this.foldPointConstants, + foldArrayGets: Boolean = this.foldArrayGets, + lowerTwoElementArraysToSelect: Boolean = this.lowerTwoElementArraysToSelect, + ): IntervalOptimizerConfig = + IntervalOptimizerConfig( + pruneTernaries = pruneTernaries, + refineTernaryBranches = refineTernaryBranches, + foldComparisons = foldComparisons, + simplifyRangeMath = simplifyRangeMath, + foldPointConstants = foldPointConstants, + foldArrayGets = foldArrayGets, + lowerTwoElementArraysToSelect = lowerTwoElementArraysToSelect, + ) + + override fun equals(other: Any?): Boolean = + other is IntervalOptimizerConfig && + pruneTernaries == other.pruneTernaries && + refineTernaryBranches == other.refineTernaryBranches && + foldComparisons == other.foldComparisons && + simplifyRangeMath == other.simplifyRangeMath && + foldPointConstants == other.foldPointConstants && + foldArrayGets == other.foldArrayGets && + lowerTwoElementArraysToSelect == other.lowerTwoElementArraysToSelect + + override fun hashCode(): Int { + var result = pruneTernaries.hashCode() + result = 31 * result + refineTernaryBranches.hashCode() + result = 31 * result + foldComparisons.hashCode() + result = 31 * result + simplifyRangeMath.hashCode() + result = 31 * result + foldPointConstants.hashCode() + result = 31 * result + foldArrayGets.hashCode() + result = 31 * result + lowerTwoElementArraysToSelect.hashCode() + return result + } + + override fun toString(): String = + "IntervalOptimizerConfig(pruneTernaries=$pruneTernaries, " + + "refineTernaryBranches=$refineTernaryBranches, foldComparisons=$foldComparisons, " + + "simplifyRangeMath=$simplifyRangeMath, foldPointConstants=$foldPointConstants, " + + "foldArrayGets=$foldArrayGets, " + + "lowerTwoElementArraysToSelect=$lowerTwoElementArraysToSelect)" + + public companion object { + /** Default configuration with all built-in interval optimizations enabled. */ + public val FULL: IntervalOptimizerConfig = IntervalOptimizerConfig() + } +} + +/** + * Execution context provided to [RemoteIntervalOperation.simplifyWithIntervals] and + * [IntervalOptimizationRule] callbacks during [IntervalOptimizer] traversal. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public interface IntervalOptimizationContext { + /** The active (possibly branch-refined) [IntervalEnvironment]. */ + public val environment: IntervalEnvironment + + /** The outer unrefined [IntervalEnvironment] (for preserving guards on trapping operands). */ + public val unrefinedEnvironment: IntervalEnvironment + + /** Memoized [RemoteValueIntervalEvaluator] backed by [environment]. */ + public val evaluator: RemoteValueIntervalEvaluator + + /** Active optimization feature switches. */ + public val config: IntervalOptimizerConfig + + /** Whether this context is currently optimizing inside a branch-refined environment. */ + public val isInRefinedBranch: Boolean + get() = environment !== unrefinedEnvironment + + /** Recursively optimizes [value] under [environment]. */ + public fun optimize(value: RemoteValue<*>): RemoteValue<*> + + /** Recursively optimizes [value] under [unrefinedEnvironment]. */ + public fun optimizeUnrefined(value: RemoteValue<*>): RemoteValue<*> + + /** + * Returns `true` if every operation in [key] whose interval semantics require bounded float + * operands (such as `*`, `mad`, `clamp`, `lerp`, `min`, `max`) has bounded float operands under + * [evaluator], guarding against IEEE-754 `NaN`/`Infinity` values being hidden by a bounded + * interval. + */ + public fun hasBoundedFloatOperands(key: RemoteStateCacheKey): Boolean = + IntervalOptimizer.hasBoundedFloatOperands(key, evaluator) +} + +/** + * Pluggable rewrite hook for extending [IntervalOptimizer] with domain-specific expression + * optimizations (such as wall-clock precision lowering or quantizer pushdown) without duplicating + * DAG memoization, cycle detection, type adaptation, or path-sensitive branch refinement. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public interface IntervalOptimizationRule { + /** + * Optional pre-child rewrite invoked before children of [value] are visited. Return a + * replacement [RemoteValue] to short-circuit default child traversal, or `null` to continue + * normal optimization. + */ + public fun rewriteBeforeChildren( + value: RemoteValue<*>, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = null + + /** + * Optional post-child rewrite invoked after children of [value] have been optimized and + * built-in operation simplifications have run. Return a replacement [RemoteValue], or `null` to + * keep [value]. + */ + public fun rewriteAfterChildren( + value: RemoteValue<*>, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = null +} + +/** + * Memoized, extensible bottom-up DAG optimizer for [RemoteValue] expressions guided by an + * [IntervalEnvironment]. + * + * Performs: + * 1. Pre-child custom [rules] and dead select/ternary pruning (avoiding traversal of dead + * subtrees). + * 2. Path-sensitive branch refinement on surviving selects/ternaries with isolated memoization and + * unrefined fallback on operands where the operation can fail + * ([RemoteOperation.canFailOnOperandIndex]). + * 3. Bottom-up child optimization and safe AST reconstruction ([RemoteOperation.reconstruct]). + * 4. Post-child comparison/select folding, polymorphic operation simplifications + * ([RemoteIntervalOperation.simplifyWithIntervals]), post-child custom [rules], and + * purity/IEEE-754 guarded point-constant folding. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class IntervalOptimizer +private constructor( + public val environment: IntervalEnvironment, + public val config: IntervalOptimizerConfig, + public val rules: List<IntervalOptimizationRule>, + private val refineDepth: Int, + private val unrefinedEnvironment: IntervalEnvironment, +) { + /** + * Creates an [IntervalOptimizer] configured with [environment], [config], and optional custom + * [rules]. + */ + @JvmOverloads + public constructor( + environment: IntervalEnvironment = MapIntervalEnvironment.EMPTY, + config: IntervalOptimizerConfig = IntervalOptimizerConfig.FULL, + rules: List<IntervalOptimizationRule> = emptyList(), + ) : this( + environment = environment, + config = config, + rules = rules, + refineDepth = 0, + unrefinedEnvironment = environment, + ) + + /** Memoized interval evaluator bound to [environment]. */ + public val evaluator: RemoteValueIntervalEvaluator = RemoteValueIntervalEvaluator(environment) + + // Keyed by valueKind, mutability, enumEntries identity, and cacheKey so RemoteFloat/RemoteInt/ + // RemoteBoolean, distinct RemoteEnum types, and MutableRemote* vs immutable Remote* sharing a + // cache key never collide in the memo table. + private val optimizeMemo = HashMap<OptimizeMemoKey, RemoteValue<*>>() + private val visiting = HashSet<OptimizeMemoKey>() + + private val unrefinedOptimizer: IntervalOptimizer by + lazy(LazyThreadSafetyMode.NONE) { + if (unrefinedEnvironment === environment) { + this + } else { + IntervalOptimizer( + environment = unrefinedEnvironment, + config = config, + rules = rules, + refineDepth = refineDepth, + unrefinedEnvironment = unrefinedEnvironment, + ) + } + } + + private val context: IntervalOptimizationContext = + object : IntervalOptimizationContext { + override val environment: IntervalEnvironment + get() = this@IntervalOptimizer.environment + + override val unrefinedEnvironment: IntervalEnvironment + get() = this@IntervalOptimizer.unrefinedEnvironment + + override val evaluator: RemoteValueIntervalEvaluator + get() = this@IntervalOptimizer.evaluator + + override val config: IntervalOptimizerConfig + get() = this@IntervalOptimizer.config + + override fun optimize(value: RemoteValue<*>): RemoteValue<*> = + this@IntervalOptimizer.optimize(value) + + override fun optimizeUnrefined(value: RemoteValue<*>): RemoteValue<*> = + this@IntervalOptimizer.unrefinedOptimizer.optimize(value) + } + + /** Optimizes [value] under [environment], [config], and [rules]. */ + public fun optimize(value: RemoteValue<*>): RemoteValue<*> { + if (value.hasConstantValue && !isCompositeLiteralArray(value)) return value + val memoKey = + OptimizeMemoKey( + valueKind = value.valueKind, + isMutable = value is MutableRemoteValue<*>, + enumEntries = (value as? RemoteEnum<*>)?.enumEntries, + cacheKey = value.cacheKey, + ) + optimizeMemo[memoKey]?.let { cached -> + return value.adaptToType(cached) + } + if (!visiting.add(memoKey)) return value + val result = + try { + if (value is RemoteBoolean && value.cacheKey is RemoteNamedCacheKey) { + optimizeNamedBoolean(value, value.cacheKey as RemoteNamedCacheKey) + } else { + optimizeImpl(value) + } + } finally { + visiting.remove(memoKey) + } + val adapted = value.adaptToType(result) + optimizeMemo[memoKey] = adapted + return adapted + } + + private fun optimizeNamedBoolean( + value: RemoteBoolean, + namedKey: RemoteNamedCacheKey, + ): RemoteValue<*> { + // Callers inspecting named variables may probe with a synthetic RemoteBoolean(name) on any + // NamedVariable (including float/int vars). Check path-sensitive int overrides first, then + // require an exact float 0f/1f (or an exact int 0/1 when no float bound exists) so + // non-boolean values (e.g. 5f or 1.5f) are never truncated into true/1 by a boolean probe. + for (i in 0 until rules.size) { + rules[i].rewriteBeforeChildren(value, context)?.let { rewritten -> + return rewritten + } + } + var current: RemoteValue<*> = applyAfterChildRules(value) + if (current === value && config.foldPointConstants) { + val intOverride = environment.intOverride(namedKey) + current = + when { + intOverride != null && intOverride.isPoint && intOverride.min == 0 -> + RemoteBoolean(false) + intOverride != null && intOverride.isPoint && intOverride.min == 1 -> + RemoteBoolean(true) + else -> { + val range = evaluator.evalFloatKey(namedKey) + when { + range.isPoint && range.min == 0f -> RemoteBoolean(false) + range.isPoint && range.min == 1f -> RemoteBoolean(true) + range.isUnbounded -> { + val namedInt = environment.intForNamed(namedKey) + when { + namedInt.isPoint && namedInt.min == 0 -> RemoteBoolean(false) + namedInt.isPoint && namedInt.min == 1 -> RemoteBoolean(true) + else -> value + } + } + else -> value + } + } + } + } + return current + } + + private fun optimizeImpl(value: RemoteValue<*>): RemoteValue<*> { + // 0. Pre-child custom rewrite rules. + for (i in 0 until rules.size) { + rules[i].rewriteBeforeChildren(value, context)?.let { rewritten -> + return rewritten + } + } + + val key = value.cacheKey as? RemoteOperationCacheKey + if (key == null) { + val afterRules = applyAfterChildRules(value) + return if (config.foldPointConstants) tryFoldPointConstant(afterRules) else afterRules + } + val op = key.op as? RemoteOperation + val semantics = intervalSemanticsFor(key.op) + + // 1. Pre-child dead ternary/select pruning (avoids traversing dead subtrees). + if (config.pruneTernaries && semantics != null) { + tryPruneTernaryBeforeChildren(evaluator, key.op, semantics, key.args)?.let { pruned -> + return optimize(pruned) + } + } + + // 2. Surviving ternary/select with optional path-sensitive branch refinement. + if (semantics != null && isTernarySelectOp(key.op, semantics)) { + return optimizeTernarySelect(value, key, semantics) + } + + // 3. Generic bottom-up child optimization. + val withChildren = optimizeChildren(value, key, op) ?: value + return finalizeOptimized(withChildren) + } + + private fun finalizeOptimized(value: RemoteValue<*>): RemoteValue<*> { + var current = value + if (config.pruneTernaries || config.foldComparisons) { + current = + pruneComparisonOrSelectAfterChildren( + evaluator = evaluator, + value = current, + foldComparisons = config.foldComparisons, + pruneSelects = config.pruneTernaries, + ) + } + val curKey = current.cacheKey as? RemoteOperationCacheKey + if (curKey != null) { + intervalSemanticsFor(curKey.op)?.simplifyWithIntervals(current, curKey, context)?.let { + current = it + } + } + current = applyAfterChildRules(current) + if (config.foldPointConstants) { + current = tryFoldPointConstant(current) + } + return current + } + + private fun applyAfterChildRules(value: RemoteValue<*>): RemoteValue<*> { + var current = value + for (i in 0 until rules.size) { + rules[i].rewriteAfterChildren(current, context)?.let { current = it } + } + return current + } + + private fun optimizeChildren( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + op: RemoteOperation?, + ): RemoteValue<*>? { + val args = key.args + val inEagerBranch = environment !== unrefinedEnvironment + val newArgs = ArrayList<RemoteValue<*>>(args.size) + var argsChanged = false + for (i in 0 until args.size) { + val argKey = args[i] + val argValue = argKey.getOrCreateValueOrNull() ?: return null + // RPN ifElse/select evaluates both arms eagerly, so operands on which the operation can + // fail at runtime (array indices and integer divisors) inside a branch must not drop + // bounds/zero guards using branch-only interval refinements. + val optimizedArg = + if (inEagerBranch && op?.canFailOnOperandIndex(i) == true) { + unrefinedOptimizer.optimize(argValue) + } else { + optimize(argValue) + } + if (optimizedArg.cacheKey != argKey) argsChanged = true + newArgs.add(optimizedArg) + } + if (!argsChanged) return value + // Preserve non-canonical constant ints (values outside {0, 1}) rather than reconstructing + // RemoteBoolean(constInt), which folds via != 0 into RemoteBoolean(true), corrupting + // toRemoteInt() and inverting negative conditions relative to wire I_IFELSE (> 0). + if (key.op == BooleanOperationKey.RemoteBoolean && newArgs.size == 1) { + val constInt = (newArgs[0] as? RemoteInt)?.constantValueOrNull + if (constInt != null && constInt != 0 && constInt != 1) { + return value + } + } + return key.reconstructOrNull(newArgs) ?: value + } + + private fun optimizeTernarySelect( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + semantics: RemoteOperationIntervalSemantics, + ): RemoteValue<*> { + val args = key.args + val op = key.op as? RemoteOperation + if (semantics.isBooleanSelect(key.op) && args.size >= 3) { + return optimizeBooleanSelect(value, key, args) + } + val cond = + semantics.selectCondition(key.op) + ?: return finalizeOptimized(optimizeChildren(value, key, op) ?: value) + if (args.size < 4) return finalizeOptimized(optimizeChildren(value, key, op) ?: value) + return optimizeSelectIf(value, key, semantics, cond, args) + } + + private fun optimizeBooleanSelect( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + args: List<RemoteStateCacheKey>, + ): RemoteValue<*> { + val condOrig = args[0].getOrCreateValueOrNull() ?: return finalizeOptimized(value) + val trueOrig = args[1].getOrCreateValueOrNull() ?: return finalizeOptimized(value) + val falseOrig = args[2].getOrCreateValueOrNull() ?: return finalizeOptimized(value) + val condOptimized = optimize(condOrig) + + if (config.pruneTernaries && hasBoundedFloatOperands(condOptimized.cacheKey, evaluator)) { + val condTri = + extractConstCondition(condOptimized.cacheKey)?.let { TriState.of(it) } + ?: evaluator.evalBoolKey(condOptimized.cacheKey) + when (condTri) { + TriState.TRUE -> return optimize(trueOrig) + TriState.FALSE -> return optimize(falseOrig) + TriState.UNKNOWN -> {} + } + } + + val trueOptimized = + optimizeUnderBooleanCondition(trueOrig, condOptimized.cacheKey, holds = true) + val falseOptimized = + optimizeUnderBooleanCondition(falseOrig, condOptimized.cacheKey, holds = false) + + if (config.pruneTernaries && trueOptimized.cacheKey == falseOptimized.cacheKey) { + return trueOptimized + } + val changed = + condOptimized.cacheKey != args[0] || + trueOptimized.cacheKey != args[1] || + falseOptimized.cacheKey != args[2] + val surviving = + if (changed) { + key.reconstructOrNull(listOf(condOptimized, trueOptimized, falseOptimized)) ?: value + } else { + value + } + return finalizeOptimized(surviving) + } + + private fun optimizeSelectIf( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + semantics: RemoteOperationIntervalSemantics, + comparison: IntervalComparison, + args: List<RemoteStateCacheKey>, + ): RemoteValue<*> { + val aOrig = args[0].getOrCreateValueOrNull() ?: return finalizeOptimized(value) + val bOrig = args[1].getOrCreateValueOrNull() ?: return finalizeOptimized(value) + val trueOrig = args[2].getOrCreateValueOrNull() ?: return finalizeOptimized(value) + val falseOrig = args[3].getOrCreateValueOrNull() ?: return finalizeOptimized(value) + val cmpKind = semantics.selectComparisonKind(key.op, args) + val isInt: Boolean? = + when { + cmpKind.isIntEncoded -> true + cmpKind == RemoteValueKind.FLOAT || cmpKind == RemoteValueKind.DP -> false + else -> null + } + + val aOptimized = optimize(aOrig) + val bOptimized = optimize(bOrig) + + if ( + isInt != null && + config.pruneTernaries && + hasBoundedFloatOperands(aOptimized.cacheKey, evaluator) && + hasBoundedFloatOperands(bOptimized.cacheKey, evaluator) + ) { + val cmp = + if (isInt) { + evaluator.compareIntKeys(comparison, aOptimized.cacheKey, bOptimized.cacheKey) + } else { + evaluator.compareFloatKeys(comparison, aOptimized.cacheKey, bOptimized.cacheKey) + } + when (cmp) { + TriState.TRUE -> return optimize(trueOrig) + TriState.FALSE -> return optimize(falseOrig) + TriState.UNKNOWN -> {} + } + } + + val trueOptimized = + if (isInt != null) { + optimizeUnderComparison( + trueOrig, + isInt, + comparison, + aOptimized.cacheKey, + bOptimized.cacheKey, + ) + } else { + optimize(trueOrig) + } + val falseOptimized = + if (isInt != null) { + optimizeUnderComparison( + falseOrig, + isInt, + comparison.negate(), + aOptimized.cacheKey, + bOptimized.cacheKey, + ) + } else { + optimize(falseOrig) + } + + if (config.pruneTernaries && trueOptimized.cacheKey == falseOptimized.cacheKey) { + return trueOptimized + } + val changed = + aOptimized.cacheKey != args[0] || + bOptimized.cacheKey != args[1] || + trueOptimized.cacheKey != args[2] || + falseOptimized.cacheKey != args[3] + val surviving = + if (changed) { + key.reconstructOrNull(listOf(aOptimized, bOptimized, trueOptimized, falseOptimized)) + ?: value + } else { + value + } + return finalizeOptimized(surviving) + } + + private fun optimizeUnderBooleanCondition( + branch: RemoteValue<*>, + condKey: RemoteStateCacheKey, + holds: Boolean, + ): RemoteValue<*> { + if ( + !config.refineTernaryBranches || + refineDepth >= MAX_REFINE_DEPTH || + !hasBoundedFloatOperands(condKey, evaluator) + ) { + return optimize(branch) + } + val refined = environment.refine(condKey, holds) + return if (refined !== environment) { + IntervalOptimizer( + environment = refined, + config = config, + rules = rules, + refineDepth = refineDepth + 1, + unrefinedEnvironment = unrefinedEnvironment, + ) + .optimize(branch) + } else { + optimize(branch) + } + } + + private fun optimizeUnderComparison( + branch: RemoteValue<*>, + isInt: Boolean, + comparison: IntervalComparison, + aKey: RemoteStateCacheKey, + bKey: RemoteStateCacheKey, + ): RemoteValue<*> { + if ( + !config.refineTernaryBranches || + refineDepth >= MAX_REFINE_DEPTH || + !hasBoundedFloatOperands(aKey, evaluator) || + !hasBoundedFloatOperands(bKey, evaluator) + ) { + return optimize(branch) + } + val refined = environment.narrowComparison(comparison, aKey, bKey, asInt = isInt) + return if (refined !== environment) { + IntervalOptimizer( + environment = refined, + config = config, + rules = rules, + refineDepth = refineDepth + 1, + unrefinedEnvironment = unrefinedEnvironment, + ) + .optimize(branch) + } else { + optimize(branch) + } + } + + private fun tryFoldPointConstant(value: RemoteValue<*>): RemoteValue<*> { + if (value.hasConstantValue) return value + val key = value.cacheKey + if (!key.canConstantFold(environment::canFoldStateId)) return value + if (!hasBoundedFloatOperands(key, evaluator)) return value + return when (value) { + is RemoteFloat -> evaluator.evalFloatKey(key).takeIf { it.isPoint }?.min?.rf ?: value + is RemoteDp -> + evaluator.evalFloatKey(key).takeIf { it.isPoint }?.min?.rf?.let { RemoteDp(it) } + ?: value + is RemoteInt -> evaluator.evalIntKey(key).takeIf { it.isPoint }?.min?.ri ?: value + is RemoteString -> + evaluator.evalStringKey(key).constantValue?.let { RemoteString(it) } ?: value + is RemoteColor -> + evaluator.evalColorKey(key).toArgbOrNull()?.let { RemoteColor(it) } ?: value + is RemoteBoolean -> { + val intRange = evaluator.evalIntKey(key) + if (intRange.isEmpty || intRange.min < 0 || intRange.max > 1) { + value + } else { + evaluator.evalBoolKey(key).booleanValueOrNull?.let { RemoteBoolean(it) } + ?: value + } + } + is RemoteEnum<*> -> { + val ordinal = evaluator.evalIntKey(key).takeIf { it.isPoint }?.min + if (ordinal != null && ordinal in value.enumEntries.indices) { + RemoteEnum(ordinal.ri, value.enumEntries) + } else { + value + } + } + else -> value + } + } + + private class OptimizeMemoKey( + val valueKind: RemoteValueKind, + val isMutable: Boolean, + val enumEntries: List<Enum<*>>?, + val cacheKey: RemoteStateCacheKey, + ) { + override fun equals(other: Any?): Boolean = + other is OptimizeMemoKey && + valueKind == other.valueKind && + isMutable == other.isMutable && + enumEntries === other.enumEntries && + cacheKey == other.cacheKey + + override fun hashCode(): Int { + var h = valueKind.hashCode() + h = 31 * h + isMutable.hashCode() + h = 31 * h + System.identityHashCode(enumEntries) + h = 31 * h + cacheKey.hashCode() + return h + } + } + + public companion object { + private const val MAX_REFINE_DEPTH = 6 + + private fun isCompositeLiteralArray(value: RemoteValue<*>): Boolean = + value is RemoteFloatArray || value is RemoteIntArray || value is RemoteStringArray + + internal fun isTernarySelectOp( + op: Any, + semantics: RemoteOperationIntervalSemantics, + ): Boolean = semantics.isBooleanSelect(op) || semantics.selectCondition(op) != null + + /** + * Verifies that every operation in [key] requiring bounded float operands (for example, + * `FloatInterval.times` maps `UNBOUNDED * 0f` to `[0, 0]` even though `Infinity * 0f` and + * `NaN * 0f` produce `NaN` at runtime) has bounded float inputs under [evaluator]. + * + * Uses iterative post-order traversal memoized on [evaluator] so deep expression DAGs are + * verified without recursion limits or redundant work. + */ + internal fun hasBoundedFloatOperands( + key: RemoteStateCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): Boolean = evaluator.hasBoundedFloatOperands(key) + + /** + * Attempts to resolve a ternary/select operation directly to its surviving branch before + * visiting child expressions, using [evaluator] (including self-comparison and affine + * difference checks) guarded by [hasBoundedFloatOperands]. + * + * @param evaluator Interval evaluator backing the current environment. + * @param op Operation descriptor of the select/ternary node. + * @param semantics Interval semantics handler for [op]. + * @param args Operand cache keys of the select/ternary node. + * @return The surviving branch [RemoteValue], or `null` if neither branch is dead. + */ + internal fun tryPruneTernaryBeforeChildren( + evaluator: RemoteValueIntervalEvaluator, + op: Any, + semantics: RemoteOperationIntervalSemantics, + args: List<RemoteStateCacheKey>, + ): RemoteValue<*>? { + if (semantics.isBooleanSelect(op) && args.size >= 3) { + val tri = + if (hasBoundedFloatOperands(args[0], evaluator)) { + evaluator.evalBoolKey(args[0]) + } else { + TriState.UNKNOWN + } + return selectBranchForTriState(tri, args[1], args[2]) + } + val cond = semantics.selectCondition(op) ?: return null + if (args.size < 4) return null + val cmpKind = semantics.selectComparisonKind(op, args) + val cmp = + if ( + hasBoundedFloatOperands(args[0], evaluator) && + hasBoundedFloatOperands(args[1], evaluator) + ) { + when { + cmpKind.isIntEncoded -> evaluator.compareIntKeys(cond, args[0], args[1]) + cmpKind == RemoteValueKind.FLOAT || cmpKind == RemoteValueKind.DP -> + evaluator.compareFloatKeys(cond, args[0], args[1]) + else -> TriState.UNKNOWN + } + } else { + TriState.UNKNOWN + } + return selectBranchForTriState(cmp, args[2], args[3]) + } + + /** + * Simplifies foldable boolean comparisons/predicates and constant-condition or + * identical-arm selects after their children have been optimized. + * + * @param evaluator Interval evaluator backing the current environment. + * @param value The post-child [RemoteValue] to simplify. + * @param foldComparisons Whether provable boolean predicates may fold to constants. + * @param pruneSelects Whether constant-condition or identical-arm selects may be pruned. + * @return The simplified [RemoteValue], or [value] if unchanged. + */ + internal fun pruneComparisonOrSelectAfterChildren( + evaluator: RemoteValueIntervalEvaluator, + value: RemoteValue<*>, + foldComparisons: Boolean = true, + pruneSelects: Boolean = true, + ): RemoteValue<*> { + val key = value.cacheKey as? RemoteOperationCacheKey ?: return value + val op = key.op as? RemoteOperation ?: return value + val semantics = intervalSemanticsFor(key.op) + val args = key.args + + if ( + foldComparisons && + op.resultKind == RemoteValueKind.BOOLEAN && + op != BooleanOperationKey.RemoteBoolean && + semantics?.let { isTernarySelectOp(key.op, it) } != true && + key.isDeterministic() && + hasBoundedFloatOperands(key, evaluator) + ) { + val canFoldBoolean = + if (value is RemoteBoolean) { + val intRange = evaluator.evalIntKey(key) + !intRange.isEmpty && intRange.min >= 0 && intRange.max <= 1 + } else { + true + } + if (canFoldBoolean) { + when (evaluator.evalBoolKey(key)) { + TriState.TRUE -> + return when (value) { + is RemoteBoolean -> RemoteBoolean(true) + is RemoteFloat -> 1f.rf + else -> 1.ri + } + TriState.FALSE -> + return when (value) { + is RemoteBoolean -> RemoteBoolean(false) + is RemoteFloat -> 0f.rf + else -> 0.ri + } + TriState.UNKNOWN -> {} + } + } + } + + if (pruneSelects && semantics != null) { + if (semantics.isBooleanSelect(key.op) && args.size >= 3) { + if (args[1] == args[2]) { + args[1].getOrCreateValueOrNull()?.let { + return it + } + } + extractConstCondition(args[0])?.let { constCond -> + (if (constCond) args[1] else args[2]).getOrCreateValueOrNull()?.let { + return it + } + } + } + if ( + semantics.selectCondition(key.op) != null && + args.size >= 4 && + args[2] == args[3] + ) { + args[2].getOrCreateValueOrNull()?.let { + return it + } + } + } + return value + } + + private fun selectBranchForTriState( + tri: TriState, + ifTrueKey: RemoteStateCacheKey, + ifFalseKey: RemoteStateCacheKey, + ): RemoteValue<*>? = + when (tri) { + TriState.TRUE -> ifTrueKey.getOrCreateValueOrNull() + TriState.FALSE -> ifFalseKey.getOrCreateValueOrNull() + TriState.UNKNOWN -> + if (ifTrueKey == ifFalseKey) ifTrueKey.getOrCreateValueOrNull() else null + } + + private fun extractConstCondition(condKey: RemoteStateCacheKey): Boolean? = + when (val condValue = condKey.getOrCreateValueOrNull()) { + is RemoteInt -> + condValue.constantValueOrNull?.let { + when { + it == 0 -> false + it > 0 -> true + else -> null + } + } + is RemoteBoolean -> condValue.constantValueOrNull + else -> null + } + } +} + +/** + * Optimizes this [RemoteValue] expression DAG using [IntervalOptimizer] under [environment], + * [config], and optional custom [rules]. + */ +@Suppress("UNCHECKED_CAST") +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public fun <S : RemoteValue<*>> S.optimizeWithIntervals( + environment: IntervalEnvironment = MapIntervalEnvironment.EMPTY, + config: IntervalOptimizerConfig = IntervalOptimizerConfig.FULL, + rules: List<IntervalOptimizationRule> = emptyList(), +): S = IntervalOptimizer(environment, config, rules).optimize(this) as S
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteAffineForms.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteAffineForms.kt new file mode 100644 index 0000000..470890f --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteAffineForms.kt
@@ -0,0 +1,346 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.TriState +import java.util.HashMap +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.nextDown +import kotlin.math.nextUp +import kotlin.math.ulp + +internal const val MAX_AFFINE_DEPTH: Int = 16 +internal const val EXACT_FLOAT32_INT_LIMIT: Int = FloatInterval.MAX_EXACT_INT +internal const val MAX_EXACT_INT_AFFINE_WEIGHT: Long = 1L shl 20 + +/** A symbolic affine basis variable identified by its [key] and integer/float view. */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class AffineTerm(public val key: RemoteStateCacheKey, public val isInt: Boolean) { + override fun equals(other: Any?): Boolean = + other is AffineTerm && key == other.key && isInt == other.isInt + + override fun hashCode(): Int = 31 * key.hashCode() + isInt.hashCode() + + override fun toString(): String = "AffineTerm(key=$key, isInt=$isInt)" +} + +/** + * Linear affine form `constant + sum(w_i * x_i) +/- errorBound` over symbolic [AffineTerm]s, used + * to cancel correlated variables in float expressions and comparisons. + * + * [errorBound] accumulates a conservative upper bound on IEEE-754 binary32 floating-point rounding + * error across arithmetic operations, measured in units in the last place (ULPs — the spacing + * between adjacent representable `Float` values, computed via `Float.ulp`). + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class FloatAffineForm( + public val terms: Map<AffineTerm, Double>, + public val constant: Double, + public val errorBound: Double, +) { + /** Returns `-this`. */ + public fun negate(): FloatAffineForm { + val negTerms = HashMap<AffineTerm, Double>(terms.size) + for ((k, w) in terms) negTerms[k] = -w + return FloatAffineForm(negTerms, -constant, errorBound) + } + + /** Returns `this * factor` with additional floating-point rounding error [roundingUlp]. */ + public fun scale(factor: Double, roundingUlp: Double = 0.0): FloatAffineForm { + val scaledTerms = HashMap<AffineTerm, Double>(terms.size) + for ((k, w) in terms) { + val nw = w * factor + if (nw != 0.0) scaledTerms[k] = nw + } + return FloatAffineForm( + scaledTerms, + constant * factor, + errorBound * abs(factor) + roundingUlp, + ) + } + + /** Returns `this + other` with additional floating-point rounding error [roundingUlp]. */ + public fun add(other: FloatAffineForm, roundingUlp: Double = 0.0): FloatAffineForm { + val merged = HashMap<AffineTerm, Double>(terms.size + other.terms.size) + for ((k, w) in terms) merged[k] = w + for ((k, w) in other.terms) { + val sum = (merged[k] ?: 0.0) + w + if (sum == 0.0) merged.remove(k) else merged[k] = sum + } + return FloatAffineForm( + merged, + constant + other.constant, + errorBound + other.errorBound + roundingUlp, + ) + } + + /** + * Returns the exact symbolic difference `this - other` (`roundingUlp = 0.0`, suitable for exact + * relational comparison against zero; callers modeling runtime float subtraction should add + * floating-point rounding error via [withExtraError]). + */ + public fun subtract(other: FloatAffineForm): FloatAffineForm = add(other.negate(), 0.0) + + /** Returns a copy with additional rounding error [extraUlp] added to [errorBound]. */ + public fun withExtraError(extraUlp: Double): FloatAffineForm = + FloatAffineForm(terms, constant, errorBound + extraUlp) + + /** Concretizes this affine form into a sound [FloatInterval] under [evaluator], or `null`. */ + public fun evaluate(evaluator: RemoteValueIntervalEvaluator): FloatInterval? { + if (!constant.isFinite() || !errorBound.isFinite() || errorBound < 0.0) return null + var lo = constant - errorBound + var hi = constant + errorBound + var minInc = true + var maxInc = true + for ((term, w) in terms) { + if (!w.isFinite()) return null + val termLo: Double + val termHi: Double + val termMinInc: Boolean + val termMaxInc: Boolean + if (term.isInt) { + val iv = evaluator.evalIntKey(term.key) + if (iv.isEmpty || !iv.hasFiniteMin || !iv.hasFiniteMax) return null + termLo = iv.min.toDouble() + termHi = iv.max.toDouble() + termMinInc = true + termMaxInc = true + } else { + val r = evaluator.evalFloatKey(term.key) + if (r.isEmpty || r.isUnbounded) return null + termLo = r.min.toDouble() + termHi = r.max.toDouble() + termMinInc = r.minInclusive + termMaxInc = r.maxInclusive + } + when { + w > 0.0 -> { + lo += w * termLo + hi += w * termHi + minInc = minInc && termMinInc + maxInc = maxInc && termMaxInc + } + w < 0.0 -> { + lo += w * termHi + hi += w * termLo + minInc = minInc && termMaxInc + maxInc = maxInc && termMinInc + } + } + } + if (!lo.isFinite() || !hi.isFinite()) return null + val fLo = lo.toFloat().let { if (it.toDouble() > lo) it.nextDown() else it } + val fHi = hi.toFloat().let { if (it.toDouble() < hi) it.nextUp() else it } + if (!fLo.isFinite() || !fHi.isFinite()) return null + val collapsed = fLo == fHi + return FloatInterval( + min = fLo, + max = fHi, + minInclusive = if (collapsed || errorBound > 0.0) true else minInc, + maxInclusive = if (collapsed || errorBound > 0.0) true else maxInc, + ) + } +} + +/** + * Overflow-verified 64-bit exact linear affine form `constant + sum(w_i * x_i)` over symbolic + * integer [RemoteStateCacheKey]s. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class IntAffineForm( + public val terms: Map<RemoteStateCacheKey, Long>, + public val constant: Long, +) { + /** Returns `-this`, or `null` if negating would overflow `Long`. */ + public fun negate(): IntAffineForm? { + if (constant == Long.MIN_VALUE) return null + val negTerms = HashMap<RemoteStateCacheKey, Long>(terms.size) + for ((k, w) in terms) { + if (w == Long.MIN_VALUE) return null + negTerms[k] = -w + } + return IntAffineForm(negTerms, -constant) + } + + /** Returns `this * factor`, or `null` on `Long` overflow. */ + public fun scale(factor: Long): IntAffineForm? { + val newConst = safeMulLong(constant, factor) ?: return null + val scaledTerms = HashMap<RemoteStateCacheKey, Long>(terms.size) + for ((k, w) in terms) { + val nw = safeMulLong(w, factor) ?: return null + if (nw != 0L) scaledTerms[k] = nw + } + return IntAffineForm(scaledTerms, newConst) + } + + /** Returns `this + other`, or `null` on `Long` overflow. */ + public fun add(other: IntAffineForm): IntAffineForm? { + val newConst = safeAddLong(constant, other.constant) ?: return null + val merged = HashMap<RemoteStateCacheKey, Long>(terms.size + other.terms.size) + for ((k, w) in terms) merged[k] = w + for ((k, w) in other.terms) { + val sum = safeAddLong(merged[k] ?: 0L, w) ?: return null + if (sum == 0L) merged.remove(k) else merged[k] = sum + } + return IntAffineForm(merged, newConst) + } + + /** Evaluates 64-bit bounds of `this - other` under [evaluator], or `null` on overflow. */ + public fun subtractAndEvaluateLongBounds( + other: IntAffineForm, + evaluator: RemoteValueIntervalEvaluator, + ): Pair<Long, Long>? = other.negate()?.let { add(it) }?.evaluateLongBounds(evaluator) + + /** Concretizes this affine form into an [IntInterval] if verified within `Int` bounds. */ + public fun evaluateIntInterval(evaluator: RemoteValueIntervalEvaluator): IntInterval? { + val (lo, hi) = evaluateLongBounds(evaluator) ?: return null + if (lo < Int.MIN_VALUE.toLong() || hi > Int.MAX_VALUE.toLong()) return null + return IntInterval.fromLongBounds(lo, hi) + } + + private fun evaluateLongBounds(evaluator: RemoteValueIntervalEvaluator): Pair<Long, Long>? { + var lo = constant + var hi = constant + for ((k, w) in terms) { + val r = evaluator.evalIntKey(k) + if (r.isEmpty || !r.hasFiniteMin || !r.hasFiniteMax) return null + val tLo = safeMulLong(w, if (w > 0L) r.min.toLong() else r.max.toLong()) ?: return null + val tHi = safeMulLong(w, if (w > 0L) r.max.toLong() else r.min.toLong()) ?: return null + lo = safeAddLong(lo, tLo) ?: return null + hi = safeAddLong(hi, tHi) ?: return null + } + return Pair(lo, hi) + } +} + +internal fun RemoteValueIntervalEvaluator.extractFloatAffineForm( + key: RemoteStateCacheKey, + depth: Int, +): FloatAffineForm? { + if (depth > MAX_AFFINE_DEPTH || !key.isDeterministic()) return null + floatAffineMemo[key]?.let { (cachedDepth, cachedForm) -> + if (cachedDepth <= depth) return cachedForm + } + val range = evalFloatKey(key) + val result = + when { + range.isEmpty || range.isUnbounded -> null + range.isPoint -> FloatAffineForm(emptyMap(), range.min.toDouble(), errorBound = 0.0) + key is RemoteOperationCacheKey -> + intervalSemanticsFor(key.op)?.extractFloatAffine(key, range, this, depth) + ?: FloatAffineForm( + mapOf(AffineTerm(key, isInt = false) to 1.0), + constant = 0.0, + errorBound = 0.0, + ) + else -> + FloatAffineForm( + mapOf(AffineTerm(key, isInt = false) to 1.0), + constant = 0.0, + errorBound = 0.0, + ) + } + floatAffineMemo[key] = depth to result + return result +} + +internal fun RemoteValueIntervalEvaluator.extractIntAffineForm( + key: RemoteStateCacheKey, + depth: Int, +): IntAffineForm? { + if (depth > MAX_AFFINE_DEPTH || !key.isDeterministic()) return null + intAffineMemo[key]?.let { (cachedDepth, cachedForm) -> + if (cachedDepth <= depth) return cachedForm + } + val range = evalIntKey(key) + val result = + when { + range.isEmpty -> null + range.isPoint -> IntAffineForm(emptyMap(), range.min.toLong()) + key is RemoteOperationCacheKey -> + intervalSemanticsFor(key.op)?.extractIntAffine(key, this, depth) + ?: IntAffineForm(mapOf(key to 1L), constant = 0L) + else -> IntAffineForm(mapOf(key to 1L), constant = 0L) + } + intAffineMemo[key] = depth to result + return result +} + +internal fun RemoteValueIntervalEvaluator.compareFloatAffineDiff( + comparison: IntervalComparison, + keyA: RemoteStateCacheKey, + keyB: RemoteStateCacheKey, +): TriState { + val formA = extractFloatAffineForm(keyA, depth = 0) ?: return TriState.UNKNOWN + val formB = extractFloatAffineForm(keyB, depth = 0) ?: return TriState.UNKNOWN + val diffInterval = formA.subtract(formB).evaluate(this) ?: return TriState.UNKNOWN + return diffInterval.compare(comparison, FloatInterval.ZERO) +} + +internal fun RemoteValueIntervalEvaluator.compareIntAffineDiff( + comparison: IntervalComparison, + keyA: RemoteStateCacheKey, + keyB: RemoteStateCacheKey, +): TriState { + val formA = extractIntAffineForm(keyA, depth = 0) ?: return TriState.UNKNOWN + val formB = extractIntAffineForm(keyB, depth = 0) ?: return TriState.UNKNOWN + val (diffMin, diffMax) = + formA.subtractAndEvaluateLongBounds(formB, this) ?: return TriState.UNKNOWN + return comparison.compareLongRangeAgainstZero(diffMin, diffMax) +} + +internal fun RemoteValueIntervalEvaluator.combineFloatAffineAdd( + a: FloatAffineForm, + b: FloatAffineForm, + range: FloatInterval, + negateRhs: Boolean, +): FloatAffineForm { + if ( + negateRhs && + a.errorBound == 0.0 && + b.errorBound == 0.0 && + a.constant == b.constant && + a.terms == b.terms + ) { + return FloatAffineForm(emptyMap(), constant = 0.0, errorBound = 0.0) + } + val raw = a.add(if (negateRhs) b.negate() else b, roundingUlp = 0.0) + val tightRange = raw.evaluate(this) ?: range + return raw.withExtraError(maxUlp(tightRange)) +} + +internal fun maxUlp(range: FloatInterval): Double = + max(abs(range.min), abs(range.max)).ulp.toDouble() + +private fun safeAddLong(a: Long, b: Long): Long? { + val r = a + b + return if (((a xor r) and (b xor r)) < 0L) null else r +} + +private fun safeMulLong(a: Long, b: Long): Long? { + if (a == 0L || b == 0L) return 0L + if ((a == -1L && b == Long.MIN_VALUE) || (b == -1L && a == Long.MIN_VALUE)) return null + val r = a * b + return if (r / a != b) null else r +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteArrayIntervalSemantics.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteArrayIntervalSemantics.kt new file mode 100644 index 0000000..d4099da --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteArrayIntervalSemantics.kt
@@ -0,0 +1,214 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.FloatArrayOperationKey +import androidx.compose.remote.creation.compose.state.IntArrayOperationKey +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteOperation +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateIdKey +import androidx.compose.remote.creation.compose.state.RemoteString +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.StringArrayOperationKey +import androidx.compose.remote.creation.compose.state.rf +import androidx.compose.remote.creation.compose.state.selectIfLt +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.SlotInterval +import androidx.compose.remote.document.intervals.StringSummary + +/** External interval semantics for [FloatArrayOperationKey]. */ +internal object RemoteFloatArrayIntervalSemantics : RemoteOperationIntervalSemantics { + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval { + if (key.op != FloatArrayOperationKey.Get) return FloatInterval.UNBOUNDED + val args = key.args + if (args.size < 2) return FloatInterval.UNBOUNDED + val arrayKey = args[0] + val indexKey = args[1] + val isIntIndex = indexKey.getValueKind().isIntEncoded + val indexInt = + if (isIntIndex) { + evaluator.evalIntKey(indexKey) + } else { + SlotInterval.fromFloat(evaluator.evalFloatKey(indexKey)).toIntInterval() + } + if (arrayKey is RemoteStateIdKey) { + val indexFloat = + if (isIntIndex) indexInt.toFloatInterval() else evaluator.evalFloatKey(indexKey) + return evaluator.environment.floatArrayElement(arrayKey.id, indexFloat) + } + if (arrayKey is RemoteOperationCacheKey && arrayKey.op == FloatArrayOperationKey.Create) { + return evaluator.unionFloatArrayElements(arrayKey.args, indexInt) + } + return FloatInterval.UNBOUNDED + } + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = + simplifyLiteralArrayGet( + key = key, + context = context, + getOp = FloatArrayOperationKey.Get, + createOp = FloatArrayOperationKey.Create, + allowFloatIndex = true, + castElement = { it as? RemoteFloat }, + selectInt = { isOne, elem0, elem1 -> isOne.select(elem1, elem0) }, + selectFloat = { idxValue, elem0, elem1 -> selectIfLt(idxValue, 1f.rf, elem0, elem1) }, + ) +} + +/** External interval semantics for [IntArrayOperationKey]. */ +internal object RemoteIntArrayIntervalSemantics : RemoteOperationIntervalSemantics { + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval { + if (key.op != IntArrayOperationKey.Get) return IntInterval.UNBOUNDED + val args = key.args + if (args.size < 2) return IntInterval.UNBOUNDED + val arrayKey = args[0] + val indexKey = args[1] + val idxInterval = + if (indexKey.getValueKind().isIntEncoded) { + evaluator.evalIntKey(indexKey) + } else { + SlotInterval.fromFloat(evaluator.evalFloatKey(indexKey)).toIntInterval() + } + if (arrayKey is RemoteOperationCacheKey && arrayKey.op == IntArrayOperationKey.Create) { + return evaluator.unionIntArrayElements(arrayKey.args, idxInterval) + } + return IntInterval.UNBOUNDED + } + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = + simplifyLiteralArrayGet( + key = key, + context = context, + getOp = IntArrayOperationKey.Get, + createOp = IntArrayOperationKey.Create, + allowFloatIndex = true, + castElement = { it as? RemoteInt }, + selectInt = { isOne, elem0, elem1 -> isOne.select(elem1, elem0) }, + selectFloat = { idxValue, elem0, elem1 -> + idxValue.isLessThan(1f.rf).select(elem0, elem1) + }, + ) +} + +/** External interval semantics for [StringArrayOperationKey]. */ +internal object RemoteStringArrayIntervalSemantics : RemoteOperationIntervalSemantics { + override fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary { + if (key.op != StringArrayOperationKey.Get) return StringSummary.UNKNOWN + val args = key.args + if (args.size < 2) return StringSummary.UNKNOWN + val arrayKey = args[0] + val idxInterval = evaluator.evalIntKey(args[1]) + if (arrayKey is RemoteOperationCacheKey && arrayKey.op == StringArrayOperationKey.Create) { + return evaluator.unionStringArrayElements(arrayKey.args, idxInterval) + } + return StringSummary.UNKNOWN + } + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = + simplifyLiteralArrayGet( + key = key, + context = context, + getOp = StringArrayOperationKey.Get, + createOp = StringArrayOperationKey.Create, + allowFloatIndex = false, + castElement = { it as? RemoteString }, + selectInt = { isOne, elem0, elem1 -> isOne.select(elem1, elem0) }, + ) +} + +private fun <T : RemoteValue<*>> simplifyLiteralArrayGet( + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + getOp: RemoteOperation, + createOp: RemoteOperation, + allowFloatIndex: Boolean, + castElement: (RemoteValue<*>) -> T?, + selectInt: (RemoteBoolean, T, T) -> RemoteValue<*>, + selectFloat: ((RemoteFloat, T, T) -> RemoteValue<*>)? = null, +): RemoteValue<*>? { + if (key.op != getOp) return null + val args = key.args + if (args.size < 2 || !context.hasBoundedFloatOperands(args[1])) return null + val arrayKey = args[0] as? RemoteOperationCacheKey ?: return null + if (arrayKey.op != createOp) return null + val elements = arrayKey.args + val isIntIndex = !allowFloatIndex || args[1].getValueKind().isIntEncoded + val rawFloatIndex = if (isIntIndex) null else context.evaluator.evalFloatKey(args[1]) + val idxInterval = + if (isIntIndex) { + context.evaluator.evalIntKey(args[1]) + } else { + SlotInterval.fromFloat(rawFloatIndex!!).toIntInterval() + } + if (context.config.foldArrayGets && idxInterval.isPoint) { + val idx = idxInterval.min + if (idx in elements.indices) { + return elements[idx].getOrCreateValueOrNull() + } + } + if ( + context.config.lowerTwoElementArraysToSelect && + elements.size == 2 && + !idxInterval.isEmpty && + idxInterval.hasFiniteMin && + idxInterval.hasFiniteMax && + idxInterval.min >= 0 && + idxInterval.max <= 1 + ) { + val elem0 = elements[0].getOrCreateValueOrNull()?.let(castElement) ?: return null + val elem1 = elements[1].getOrCreateValueOrNull()?.let(castElement) ?: return null + return when (val idxValue = args[1].getOrCreateValueOrNull()) { + is RemoteInt -> selectInt(RemoteBoolean.fromRemoteInt(idxValue), elem0, elem1) + is RemoteFloat -> { + if (selectFloat == null) return null + val fIdx = rawFloatIndex ?: context.evaluator.evalFloatKey(args[1]) + if (!fIdx.isEmpty && !fIdx.isUnbounded && fIdx.min >= 0f) { + selectFloat(idxValue, elem0, elem1) + } else { + null + } + } + else -> null + } + } + return null +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteBooleanIntervalSemantics.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteBooleanIntervalSemantics.kt new file mode 100644 index 0000000..362316c --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteBooleanIntervalSemantics.kt
@@ -0,0 +1,606 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.BooleanOperationKey +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteNamedCacheKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.RemoteValueKind +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.StringSummary +import androidx.compose.remote.document.intervals.TriState +import kotlin.math.min + +/** External interval semantics for [BooleanOperationKey]. */ +internal object RemoteBooleanIntervalSemantics : RemoteOperationIntervalSemantics { + override fun isBooleanSelect(op: Any): Boolean = + when (op as BooleanOperationKey) { + BooleanOperationKey.SelectString, + BooleanOperationKey.SelectFloat, + BooleanOperationKey.SelectInt, + BooleanOperationKey.SelectBoolean -> true + else -> false + } + + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval { + val op = key.op as BooleanOperationKey + val args = key.args + return when (op) { + BooleanOperationKey.SelectFloat -> + if (args.size < 3) { + FloatInterval.UNBOUNDED + } else { + when (evaluator.evalBoolKey(args[0])) { + TriState.TRUE -> evaluator.evalFloatKey(args[1]) + TriState.FALSE -> evaluator.evalFloatKey(args[2]) + TriState.UNKNOWN -> + evaluator + .evalBooleanBranch(args[0], holds = true) { + it.evalFloatKey(args[1]) + } + .union( + evaluator.evalBooleanBranch(args[0], holds = false) { + it.evalFloatKey(args[2]) + } + ) + } + } + BooleanOperationKey.Not, + BooleanOperationKey.Equal, + BooleanOperationKey.NotEqual, + BooleanOperationKey.And, + BooleanOperationKey.Or, + BooleanOperationKey.Xor, + BooleanOperationKey.ToRemoteInt, + BooleanOperationKey.RemoteBoolean, + BooleanOperationKey.SelectInt, + BooleanOperationKey.SelectBoolean -> evaluator.evalIntKey(key).toFloatInterval() + BooleanOperationKey.SelectString -> FloatInterval.UNBOUNDED + } + } + + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval { + val op = key.op as BooleanOperationKey + val args = key.args + return when (op) { + BooleanOperationKey.SelectInt, + BooleanOperationKey.SelectBoolean -> + if (args.size < 3) { + IntInterval.UNBOUNDED + } else { + when (evaluator.evalBoolKey(args[0])) { + TriState.TRUE -> evaluator.evalIntKey(args[1]) + TriState.FALSE -> evaluator.evalIntKey(args[2]) + TriState.UNKNOWN -> + evaluator + .evalBooleanBranch(args[0], holds = true) { it.evalIntKey(args[1]) } + .union( + evaluator.evalBooleanBranch(args[0], holds = false) { + it.evalIntKey(args[2]) + } + ) + } + } + BooleanOperationKey.ToRemoteInt, + BooleanOperationKey.RemoteBoolean -> + if (args.isNotEmpty()) evaluator.evalIntKey(args[0]) else IntInterval.UNBOUNDED + BooleanOperationKey.Equal, + BooleanOperationKey.NotEqual -> evaluator.evalBoolKey(key).toIntInterval() + BooleanOperationKey.Not -> + if (args.isEmpty()) { + IntInterval.UNBOUNDED + } else { + val a = evaluator.evalIntKey(args[0]) + when { + a.isEmpty -> IntInterval.EMPTY + a.isPoint -> IntInterval.point(a.min xor 1) + a.min >= 0 && a.max <= 1 -> IntInterval(0, 1) + else -> IntInterval.UNBOUNDED + } + } + BooleanOperationKey.And -> + if (args.size < 2) { + IntInterval.UNBOUNDED + } else { + val a = evaluator.evalIntKey(args[0]) + val b = evaluator.evalIntKey(args[1]) + when { + a.isEmpty || b.isEmpty -> IntInterval.EMPTY + a == IntInterval.ZERO || b == IntInterval.ZERO -> IntInterval.ZERO + a.isPoint && b.isPoint -> IntInterval.point(a.min and b.min) + a.min >= 0 && b.min >= 0 && a.hasFiniteMax && b.hasFiniteMax -> + IntInterval(0, min(a.max, b.max)) + b.min >= 0 && b.hasFiniteMax -> IntInterval(0, b.max) + a.min >= 0 && a.hasFiniteMax -> IntInterval(0, a.max) + else -> IntInterval.UNBOUNDED + } + } + BooleanOperationKey.Or -> + if (args.size < 2) { + IntInterval.UNBOUNDED + } else { + val a = evaluator.evalIntKey(args[0]) + val b = evaluator.evalIntKey(args[1]) + when { + a.isEmpty || b.isEmpty -> IntInterval.EMPTY + a.isPoint && b.isPoint -> IntInterval.point(a.min or b.min) + a.min >= 0 && a.max <= 1 && b.min >= 0 && b.max <= 1 -> + if (a.min == 1 || b.min == 1) IntInterval.point(1) + else IntInterval(0, 1) + else -> IntInterval.UNBOUNDED + } + } + BooleanOperationKey.Xor -> + if (args.size < 2) { + IntInterval.UNBOUNDED + } else { + val a = evaluator.evalIntKey(args[0]) + val b = evaluator.evalIntKey(args[1]) + when { + a.isEmpty || b.isEmpty -> IntInterval.EMPTY + a.isPoint && b.isPoint -> IntInterval.point(a.min xor b.min) + a.min >= 0 && a.max <= 1 && b.min >= 0 && b.max <= 1 -> IntInterval(0, 1) + else -> IntInterval.UNBOUNDED + } + } + BooleanOperationKey.SelectFloat, + BooleanOperationKey.SelectString -> IntInterval.UNBOUNDED + } + } + + override fun evaluateBooleanInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): TriState? { + val op = key.op as BooleanOperationKey + val args = key.args + return when (op) { + BooleanOperationKey.Not -> + if (args.isEmpty()) { + TriState.UNKNOWN + } else { + val aInt = evaluator.evalIntKey(args[0]) + if (!aInt.isEmpty && aInt.min >= 0 && aInt.max <= 1) { + !evaluator.evalBoolKey(args[0]) + } else { + null + } + } + BooleanOperationKey.Equal -> + if (args.size < 2) { + TriState.UNKNOWN + } else { + val direct = evaluator.compareIntKeys(IntervalComparison.EQ, args[0], args[1]) + when { + direct != TriState.UNKNOWN -> direct + args[0].isDeterministic() && isBooleanComplementKeys(args[0], args[1]) -> + TriState.FALSE + else -> TriState.UNKNOWN + } + } + BooleanOperationKey.NotEqual -> + if (args.size < 2) { + TriState.UNKNOWN + } else { + val direct = evaluator.compareIntKeys(IntervalComparison.NEQ, args[0], args[1]) + when { + direct != TriState.UNKNOWN -> direct + args[0].isDeterministic() && isBooleanComplementKeys(args[0], args[1]) -> + TriState.TRUE + else -> TriState.UNKNOWN + } + } + BooleanOperationKey.And -> + if (args.size < 2) { + TriState.UNKNOWN + } else { + val aInt = evaluator.evalIntKey(args[0]) + val bInt = evaluator.evalIntKey(args[1]) + if (aInt.isEmpty || bInt.isEmpty) { + TriState.UNKNOWN + } else { + val b0 = evaluator.evalBoolKey(args[0]) + val b1 = evaluator.evalBoolKey(args[1]) + val bothCanonical = + aInt.min >= 0 && aInt.max <= 1 && bInt.min >= 0 && bInt.max <= 1 + when { + b0 == TriState.FALSE || b1 == TriState.FALSE -> TriState.FALSE + b0 == TriState.TRUE && b1 == TriState.TRUE && bothCanonical -> + TriState.TRUE + bothCanonical && + b0 == TriState.UNKNOWN && + b1 == TriState.UNKNOWN && + evaluator.evalBooleanBranch(args[0], holds = true) { + it.evalBoolKey(args[1]) + } == TriState.FALSE -> TriState.FALSE + else -> null + } + } + } + BooleanOperationKey.Or -> + if (args.size < 2) { + TriState.UNKNOWN + } else { + val aInt = evaluator.evalIntKey(args[0]) + val bInt = evaluator.evalIntKey(args[1]) + if (aInt.isEmpty || bInt.isEmpty) { + TriState.UNKNOWN + } else { + val b0 = evaluator.evalBoolKey(args[0]) + val b1 = evaluator.evalBoolKey(args[1]) + val bothNonNeg = + isKnownNonNegativeBooleanOperand(args[0], aInt) && + isKnownNonNegativeBooleanOperand(args[1], bInt) + val bothCanonical = + aInt.min >= 0 && aInt.max <= 1 && bInt.min >= 0 && bInt.max <= 1 + when { + b0 == TriState.FALSE && b1 == TriState.FALSE -> TriState.FALSE + (b0 == TriState.TRUE || b1 == TriState.TRUE) && bothNonNeg -> + TriState.TRUE + bothCanonical && + b0 == TriState.UNKNOWN && + b1 == TriState.UNKNOWN && + evaluator.evalBooleanBranch(args[0], holds = false) { + it.evalBoolKey(args[1]) + } == TriState.TRUE -> TriState.TRUE + else -> null + } + } + } + BooleanOperationKey.Xor -> + if (args.size < 2) { + TriState.UNKNOWN + } else { + val aInt = evaluator.evalIntKey(args[0]) + val bInt = evaluator.evalIntKey(args[1]) + if (aInt.isEmpty || bInt.isEmpty) { + TriState.UNKNOWN + } else if (aInt.min >= 0 && aInt.max <= 1 && bInt.min >= 0 && bInt.max <= 1) { + val b0 = evaluator.evalBoolKey(args[0]) + val b1 = evaluator.evalBoolKey(args[1]) + when { + b0 != TriState.UNKNOWN && b1 != TriState.UNKNOWN -> + TriState.of(b0 != b1) + args[0] == args[1] && args[0].isDeterministic() -> TriState.FALSE + args[0].isDeterministic() && + isBooleanComplementKeys(args[0], args[1]) -> TriState.TRUE + else -> TriState.UNKNOWN + } + } else { + null + } + } + BooleanOperationKey.SelectBoolean -> + if (args.size < 3) { + null + } else { + when (evaluator.evalBoolKey(args[0])) { + TriState.TRUE -> evaluator.evalBoolKey(args[1]) + TriState.FALSE -> evaluator.evalBoolKey(args[2]) + TriState.UNKNOWN -> { + val t = + evaluator.evalBooleanBranch(args[0], holds = true) { + it.evalBoolKey(args[1]) + } + val f = + evaluator.evalBooleanBranch(args[0], holds = false) { + it.evalBoolKey(args[2]) + } + if (t == f) t else TriState.UNKNOWN + } + } + } + BooleanOperationKey.ToRemoteInt, + BooleanOperationKey.RemoteBoolean, + BooleanOperationKey.SelectString, + BooleanOperationKey.SelectFloat, + BooleanOperationKey.SelectInt -> null + } + } + + override fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary { + if (key.op != BooleanOperationKey.SelectString || key.args.size < 3) { + return StringSummary.UNKNOWN + } + val args = key.args + return when (evaluator.evalBoolKey(args[0])) { + TriState.TRUE -> evaluator.evalStringKey(args[1]) + TriState.FALSE -> evaluator.evalStringKey(args[2]) + TriState.UNKNOWN -> + evaluator + .evalBooleanBranch(args[0], holds = true) { it.evalStringKey(args[1]) } + .union( + evaluator.evalBooleanBranch(args[0], holds = false) { + it.evalStringKey(args[2]) + } + ) + } + } + + private fun isKnownNonNegativeBooleanOperand( + key: RemoteStateCacheKey, + interval: IntInterval, + ): Boolean { + if (!interval.isEmpty && interval.min >= 0) return true + return key is RemoteNamedCacheKey && + interval == IntInterval.UNBOUNDED && + key.getValueKind() == RemoteValueKind.BOOLEAN + } + + override fun extractFloatAffine( + key: RemoteOperationCacheKey, + range: FloatInterval, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? { + if (key.op != BooleanOperationKey.SelectFloat || key.args.size < 3) return null + if (!evaluator.hasBoundedFloatOperands(key.args[0])) return null + return when (evaluator.evalBoolKey(key.args[0])) { + TriState.TRUE -> evaluator.extractFloatAffineForm(key.args[1], depth + 1) + TriState.FALSE -> evaluator.extractFloatAffineForm(key.args[2], depth + 1) + TriState.UNKNOWN -> null + } + } + + override fun extractIntAffine( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? = + when (key.op as BooleanOperationKey) { + BooleanOperationKey.ToRemoteInt, + BooleanOperationKey.RemoteBoolean -> + key.args.firstOrNull()?.let { evaluator.extractIntAffineForm(it, depth + 1) } + BooleanOperationKey.SelectInt, + BooleanOperationKey.SelectBoolean -> + if (key.args.size < 3 || !evaluator.hasBoundedFloatOperands(key.args[0])) { + null + } else { + when (evaluator.evalBoolKey(key.args[0])) { + TriState.TRUE -> evaluator.extractIntAffineForm(key.args[1], depth + 1) + TriState.FALSE -> evaluator.extractIntAffineForm(key.args[2], depth + 1) + TriState.UNKNOWN -> null + } + } + else -> null + } + + override fun refineBoolean( + key: RemoteOperationCacheKey, + holds: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? { + val op = key.op as BooleanOperationKey + val args = key.args + return when (op) { + BooleanOperationKey.Not -> { + val target = args.firstOrNull() ?: return null + val r = evaluator.evalIntKey(target) + when { + !r.isEmpty && r.min >= 0 && r.max <= 1 -> environment.refine(target, !holds) + !holds && !r.isEmpty && r.min >= 0 -> + applyIntKeyNarrowing(environment, target, IntInterval.point(1)) + else -> null + } + } + BooleanOperationKey.And -> + if (holds && args.size >= 2) { + val r0 = evaluator.evalIntKey(args[0]) + val r1 = evaluator.evalIntKey(args[1]) + if (!r0.isEmpty && r0.min >= 0 && !r1.isEmpty && r1.min >= 0) { + environment.refine(args[0], true).refine(args[1], true) + } else { + null + } + } else { + null + } + BooleanOperationKey.Or -> + if (!holds && args.size >= 2) { + val r0 = evaluator.evalIntKey(args[0]) + val r1 = evaluator.evalIntKey(args[1]) + if (!r0.isEmpty && r0.min >= 0 && !r1.isEmpty && r1.min >= 0) { + environment.refine(args[0], false).refine(args[1], false) + } else { + null + } + } else { + null + } + BooleanOperationKey.Equal, + BooleanOperationKey.NotEqual -> { + if (args.size < 2) return null + val expectEqual = if (op == BooleanOperationKey.Equal) holds else !holds + val r0 = evaluator.evalIntKey(args[0]) + val r1 = evaluator.evalIntKey(args[1]) + val bothCanonical = + !r0.isEmpty && + r0.min >= 0 && + r0.max <= 1 && + !r1.isEmpty && + r1.min >= 0 && + r1.max <= 1 + if (bothCanonical) { + val b0 = evaluator.evalBoolKey(args[0]).booleanValueOrNull + val b1 = evaluator.evalBoolKey(args[1]).booleanValueOrNull + when { + b1 != null -> + return environment.refine(args[0], if (expectEqual) b1 else !b1) + b0 != null -> + return environment.refine(args[1], if (expectEqual) b0 else !b0) + } + } + val effCond = if (expectEqual) IntervalComparison.EQ else IntervalComparison.NEQ + environment.narrowComparison(effCond, args[0], args[1], asInt = true) + } + BooleanOperationKey.ToRemoteInt, + BooleanOperationKey.RemoteBoolean -> + args.firstOrNull()?.let { environment.refine(it, holds) } + else -> null + } + } + + override fun unwrapAliasKey( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): RemoteStateCacheKey? = + when (key.op as BooleanOperationKey) { + BooleanOperationKey.ToRemoteInt, + BooleanOperationKey.RemoteBoolean -> key.args.firstOrNull() + BooleanOperationKey.SelectFloat, + BooleanOperationKey.SelectInt, + BooleanOperationKey.SelectBoolean -> + if (key.args.size < 3 || !evaluator.hasBoundedFloatOperands(key.args[0])) { + null + } else { + when (evaluator.evalBoolKey(key.args[0])) { + TriState.TRUE -> key.args[1] + TriState.FALSE -> key.args[2] + TriState.UNKNOWN -> null + } + } + else -> null + } + + private fun isBooleanComplementKeys( + aKey: RemoteStateCacheKey, + bKey: RemoteStateCacheKey, + ): Boolean = + (aKey is RemoteOperationCacheKey && + aKey.op == BooleanOperationKey.Not && + aKey.args.size == 1 && + aKey.args[0] == bKey) || + (bKey is RemoteOperationCacheKey && + bKey.op == BooleanOperationKey.Not && + bKey.args.size == 1 && + bKey.args[0] == aKey) + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + if (!context.config.simplifyRangeMath) return null + val args = key.args + val evaluator = context.evaluator + return when (key.op as BooleanOperationKey) { + BooleanOperationKey.ToRemoteInt -> { + val wrapped = args.firstOrNull() as? RemoteOperationCacheKey + if ( + wrapped != null && + wrapped.op == BooleanOperationKey.RemoteBoolean && + wrapped.args.isNotEmpty() + ) { + wrapped.args[0].getOrCreateValueOrNull() + } else { + null + } + } + BooleanOperationKey.And -> + simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = true, + negateOnIdentity = false, + ) + BooleanOperationKey.Or -> + simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = false, + negateOnIdentity = false, + ) + BooleanOperationKey.Xor -> + simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = false, + negateOnIdentity = false, + ) + ?: simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = true, + negateOnIdentity = true, + ) + BooleanOperationKey.Equal -> + simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = true, + negateOnIdentity = false, + ) + ?: simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = false, + negateOnIdentity = true, + ) + BooleanOperationKey.NotEqual -> + simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = false, + negateOnIdentity = false, + ) + ?: simplifyBinaryBooleanIdentity( + args, + evaluator, + identityValue = true, + negateOnIdentity = true, + ) + else -> null + } + } + + private fun simplifyBinaryBooleanIdentity( + args: List<RemoteStateCacheKey>, + evaluator: RemoteValueIntervalEvaluator, + identityValue: Boolean, + negateOnIdentity: Boolean, + ): RemoteValue<*>? { + if (args.size < 2) return null + val c0 = (args[0] as? RemoteConstantCacheKey)?.value as? Boolean + val c1 = (args[1] as? RemoteConstantCacheKey)?.value as? Boolean + val survivingKey = + when { + c0 == identityValue -> args[1] + c1 == identityValue -> args[0] + else -> return null + } + val survivingRange = evaluator.evalIntKey(survivingKey) + if (survivingRange.isEmpty || survivingRange.min < 0 || survivingRange.max > 1) return null + val surviving = survivingKey.getOrCreateValueOrNull() as? RemoteBoolean ?: return null + return if (negateOnIdentity) !surviving else surviving + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteColorIntervalSemantics.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteColorIntervalSemantics.kt new file mode 100644 index 0000000..afd4813 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteColorIntervalSemantics.kt
@@ -0,0 +1,157 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.ColorOperationKey +import androidx.compose.remote.creation.compose.state.RemoteColor +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.document.intervals.ColorInterval +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.StringAndColorIntervalOps + +/** External interval semantics for [ColorOperationKey]. */ +internal object RemoteColorIntervalSemantics : RemoteOperationIntervalSemantics { + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval { + if (key.op != ColorOperationKey.Component || key.args.size < 2) { + return FloatInterval.UNBOUNDED + } + val component = + ((key.args[1] as? RemoteConstantCacheKey)?.value as? Number)?.toInt() + ?: return FloatInterval.UNBOUNDED + return StringAndColorIntervalOps.summarizeColorAttribute( + evaluator.evalColorKey(key.args[0]), + component, + ) + } + + override fun evaluateColorInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): ColorInterval { + val args = key.args + return when (key.op as ColorOperationKey) { + ColorOperationKey.FromArgb -> + if (args.size >= 4) { + // FromArgb cacheKey stores arguments in (red, green, blue, alpha) order. + // ColorExpression.ARGB_MODE quantizes constant alpha to signed 16-bit fixed + // point with scale 1024: ((int) (alpha * 1024)) << 16, read back as / 1024f. + val constAlpha = + ((args[3] as? RemoteConstantCacheKey)?.value as? Number)?.toFloat() + val alphaInterval = + if (constAlpha != null && constAlpha.isFinite()) { + val quantized = (((constAlpha * 1024f).toInt() shl 16) shr 16) / 1024.0f + FloatInterval.point(quantized) + } else { + evaluator.evalFloatKey(args[3]) + } + StringAndColorIntervalOps.summarizeColorArgb( + alpha = alphaInterval, + red = evaluator.evalFloatKey(args[0]), + green = evaluator.evalFloatKey(args[1]), + blue = evaluator.evalFloatKey(args[2]), + ) + } else { + ColorInterval.UNKNOWN + } + ColorOperationKey.FromHSV -> + if (args.size >= 3) { + StringAndColorIntervalOps.summarizeColorHsv( + alpha = 255, + hue = evaluator.evalFloatKey(args[0]), + saturation = evaluator.evalFloatKey(args[1]), + value = evaluator.evalFloatKey(args[2]), + ) + } else { + ColorInterval.UNKNOWN + } + ColorOperationKey.FromAHSV -> + if (args.size >= 4) { + val alphaInt = + ((args[0] as? RemoteConstantCacheKey)?.value as? Number)?.toInt() + ?: return ColorInterval.UNKNOWN + StringAndColorIntervalOps.summarizeColorHsv( + alpha = alphaInt, + hue = evaluator.evalFloatKey(args[1]), + saturation = evaluator.evalFloatKey(args[2]), + value = evaluator.evalFloatKey(args[3]), + ) + } else { + ColorInterval.UNKNOWN + } + ColorOperationKey.Tween, + ColorOperationKey.TweenInt -> + if (args.size >= 3) { + StringAndColorIntervalOps.summarizeColorTween( + evaluator.evalColorKey(args[0]), + evaluator.evalColorKey(args[1]), + evaluator.evalFloatKey(args[2]), + ) + } else { + ColorInterval.UNKNOWN + } + ColorOperationKey.Multiply -> + if (args.size >= 2) { + StringAndColorIntervalOps.summarizeColorMultiply( + evaluator.evalColorKey(args[0]), + evaluator.evalColorKey(args[1]), + ) + } else { + ColorInterval.UNKNOWN + } + ColorOperationKey.Component -> ColorInterval.UNKNOWN + } + } + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + if ( + (key.op != ColorOperationKey.Tween && key.op != ColorOperationKey.TweenInt) || + key.args.size < 3 + ) { + return null + } + if (!context.config.pruneTernaries && !context.config.simplifyRangeMath) return null + val args = key.args + if (!context.hasBoundedFloatOperands(args[2])) return null + val tRange = context.evaluator.evalFloatKey(args[2]) + fun resolveColorEndpoint(argKey: RemoteStateCacheKey): RemoteColor? = + when (val resolved = argKey.getOrCreateValueOrNull()) { + is RemoteColor -> resolved + is RemoteInt -> resolved.constantValueOrNull?.let { RemoteColor(it) } + else -> null + } + if (args[0] == args[1] && !tRange.isEmpty && !tRange.isUnbounded) { + return resolveColorEndpoint(args[0]) + } + if (!tRange.isPoint) return null + return when (tRange.min) { + 0f -> resolveColorEndpoint(args[0]) + 1f -> resolveColorEndpoint(args[1]) + else -> null + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteConditionRefinement.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteConditionRefinement.kt new file mode 100644 index 0000000..e760893 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteConditionRefinement.kt
@@ -0,0 +1,278 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import kotlin.math.ceil +import kotlin.math.floor + +private const val MAX_REFINE_DEPTH: Int = 16 +private val activeRefineDepth: ThreadLocal<Int> = ThreadLocal.withInitial { 0 } + +private inline fun withRefineDepthBudget( + fallback: IntervalEnvironment, + block: () -> IntervalEnvironment, +): IntervalEnvironment { + val depth = activeRefineDepth.get() + if (depth >= MAX_REFINE_DEPTH) return fallback + activeRefineDepth.set(depth + 1) + return try { + block() + } finally { + activeRefineDepth.set(depth) + } +} + +/** + * Refines [environment] by assuming the boolean expression [key] evaluates to [holds]. + * + * Dispatches polymorphically through [RemoteIntervalOperation.refineBoolean] for composite + * operations and falls back to narrowing direct integer/boolean variables against `0`. + */ +internal fun refineEnvironmentByBooleanKey( + environment: IntervalEnvironment, + key: RemoteStateCacheKey, + holds: Boolean, +): IntervalEnvironment = + withRefineDepthBudget(environment) { + val evaluator = RemoteValueIntervalEvaluator(environment) + if (key is RemoteOperationCacheKey) { + intervalSemanticsFor(key.op)?.refineBoolean(key, holds, environment, evaluator)?.let { + return@withRefineDepthBudget it + } + } + refineDirectBoolVar(environment, evaluator, key, holds) + } + +/** + * Narrows float operand keys [rawKeyA] and [rawKeyB] in [environment] assuming `rawKeyA + * <comparison> rawKeyB` holds. + */ +internal fun narrowFloatOperands( + environment: IntervalEnvironment, + comparison: IntervalComparison, + rawKeyA: RemoteStateCacheKey, + rawKeyB: RemoteStateCacheKey, +): IntervalEnvironment = + withRefineDepthBudget(environment) { + val baseEval = RemoteValueIntervalEvaluator(environment) + if ( + !baseEval.hasBoundedFloatOperands(rawKeyA) || !baseEval.hasBoundedFloatOperands(rawKeyB) + ) { + return@withRefineDepthBudget environment + } + val keyA = unwrapAliasKey(baseEval, rawKeyA) + val keyB = unwrapAliasKey(baseEval, rawKeyB) + if (keyA == keyB) return@withRefineDepthBudget environment + val rangeA = baseEval.evalFloatKey(keyA) + val rangeB = baseEval.evalFloatKey(keyB) + // Skip narrowing when either operand is unbounded because UNBOUNDED permits NaN, which + // enters negated relational branches (e.g. !(NaN < c)) and would violate narrowed real + // bounds. + if (rangeA.isEmpty || rangeB.isEmpty || rangeA.isUnbounded || rangeB.isUnbounded) { + return@withRefineDepthBudget environment + } + val (narrowA, narrowB) = comparison.narrowFloat(rangeA, rangeB) + var current = environment + if (!narrowA.isEmpty && narrowA != rangeA) { + current = applyFloatKeyNarrowing(current, keyA, narrowA) + if (rawKeyA != keyA) current = applyFloatKeyNarrowing(current, rawKeyA, narrowA) + } + if (!narrowB.isEmpty && narrowB != rangeB) { + current = applyFloatKeyNarrowing(current, keyB, narrowB) + if (rawKeyB != keyB) current = applyFloatKeyNarrowing(current, rawKeyB, narrowB) + } + if (keyA is RemoteOperationCacheKey) { + intervalSemanticsFor(keyA.op) + ?.refineComparison( + keyA, + comparison, + keyB, + asInt = false, + current, + RemoteValueIntervalEvaluator(current), + ) + ?.let { current = it } + } + if (keyB is RemoteOperationCacheKey) { + intervalSemanticsFor(keyB.op) + ?.refineComparison( + keyB, + comparison.flip(), + keyA, + asInt = false, + current, + RemoteValueIntervalEvaluator(current), + ) + ?.let { current = it } + } + current + } + +/** + * Narrows integer operand keys [rawKeyA] and [rawKeyB] in [environment] assuming `rawKeyA + * <comparison> rawKeyB` holds. + */ +internal fun narrowIntOperands( + environment: IntervalEnvironment, + comparison: IntervalComparison, + rawKeyA: RemoteStateCacheKey, + rawKeyB: RemoteStateCacheKey, +): IntervalEnvironment = + withRefineDepthBudget(environment) { + val baseEval = RemoteValueIntervalEvaluator(environment) + val keyA = unwrapAliasKey(baseEval, rawKeyA) + val keyB = unwrapAliasKey(baseEval, rawKeyB) + if (keyA == keyB) return@withRefineDepthBudget environment + val a = baseEval.evalIntKey(keyA) + val b = baseEval.evalIntKey(keyB) + val (narrowA, narrowB) = comparison.narrowInt(a, b) + var current = environment + if (!narrowA.isEmpty && narrowA != a) { + current = applyIntKeyNarrowing(current, keyA, narrowA) + if (rawKeyA != keyA) current = applyIntKeyNarrowing(current, rawKeyA, narrowA) + } + if (!narrowB.isEmpty && narrowB != b) { + current = applyIntKeyNarrowing(current, keyB, narrowB) + if (rawKeyB != keyB) current = applyIntKeyNarrowing(current, rawKeyB, narrowB) + } + if (keyA is RemoteOperationCacheKey) { + intervalSemanticsFor(keyA.op) + ?.refineComparison( + keyA, + comparison, + keyB, + asInt = true, + current, + RemoteValueIntervalEvaluator(current), + ) + ?.let { current = it } + } + if (keyB is RemoteOperationCacheKey) { + intervalSemanticsFor(keyB.op) + ?.refineComparison( + keyB, + comparison.flip(), + keyA, + asInt = true, + current, + RemoteValueIntervalEvaluator(current), + ) + ?.let { current = it } + } + current + } + +internal fun applyFloatKeyNarrowing( + environment: IntervalEnvironment, + key: RemoteStateCacheKey, + interval: FloatInterval, +): IntervalEnvironment = + withRefineDepthBudget(environment) { + if (!key.isDeterministic() || key is RemoteConstantCacheKey) { + return@withRefineDepthBudget environment + } + var current = environment.withFloatNarrowing(key, interval) + if (key is RemoteOperationCacheKey) { + val sem = intervalSemanticsFor(key.op) + if (sem != null) { + current = + sem.propagateFloatNarrowing( + key, + interval, + current, + RemoteValueIntervalEvaluator(current), + ) + } + } + current + } + +internal fun applyIntKeyNarrowing( + environment: IntervalEnvironment, + key: RemoteStateCacheKey, + interval: IntInterval, +): IntervalEnvironment { + if (!key.isDeterministic() || key is RemoteConstantCacheKey) return environment + return environment.withIntNarrowing(key, interval) +} + +internal fun exactIntBoundsWithinFloatInterval(interval: FloatInterval): IntInterval { + if (interval.isEmpty) return IntInterval.EMPTY + val limit = EXACT_FLOAT32_INT_LIMIT.toFloat() + val lo = + if (interval.min.isFinite() && interval.min >= -limit && interval.min <= limit) { + when { + interval.min == -limit && interval.minInclusive -> + -EXACT_FLOAT32_INT_LIMIT.toLong() - 1L + interval.minInclusive -> ceil(interval.min).toLong() + else -> floor(interval.min).toLong() + 1L + } + } else { + IntInterval.MIN_BOUND.toLong() + } + val hi = + if (interval.max.isFinite() && interval.max >= -limit && interval.max <= limit) { + when { + interval.max == limit && interval.maxInclusive -> + EXACT_FLOAT32_INT_LIMIT.toLong() + 1L + interval.maxInclusive -> floor(interval.max).toLong() + else -> ceil(interval.max).toLong() - 1L + } + } else { + IntInterval.MAX_BOUND.toLong() + } + return IntInterval.fromLongBounds(lo, hi) +} + +private fun refineDirectBoolVar( + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + key: RemoteStateCacheKey, + holds: Boolean, +): IntervalEnvironment { + val currentInt = evaluator.evalIntKey(key) + val refinedInt = + when { + !holds -> currentInt.intersect(IntInterval(IntInterval.MIN_BOUND, 0)) + currentInt.min == 0 -> currentInt.intersect(IntInterval(1, currentInt.max)) + else -> currentInt + } + return if (!refinedInt.isEmpty && refinedInt != currentInt) { + applyIntKeyNarrowing(environment, key, refinedInt) + } else { + environment + } +} + +private fun unwrapAliasKey( + evaluator: RemoteValueIntervalEvaluator, + start: RemoteStateCacheKey, +): RemoteStateCacheKey { + var cur = start + repeat(4) { + if (cur !is RemoteOperationCacheKey) return cur + val next = intervalSemanticsFor(cur.op)?.unwrapAliasKey(cur, evaluator) ?: return cur + cur = next + } + return cur +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteEnumIntervalSemantics.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteEnumIntervalSemantics.kt new file mode 100644 index 0000000..2622dc8 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteEnumIntervalSemantics.kt
@@ -0,0 +1,132 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.EnumOperationKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.StringArrayOperationKey +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.StringSummary + +/** External interval semantics for [EnumOperationKey]. */ +internal object RemoteEnumIntervalSemantics : RemoteOperationIntervalSemantics { + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = + when (key.op as EnumOperationKey) { + EnumOperationKey.Ordinal, + EnumOperationKey.RemoteEnum -> evaluator.evalIntKey(key).toFloatInterval() + EnumOperationKey.ToString -> FloatInterval.UNBOUNDED + } + + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval = + when (key.op as EnumOperationKey) { + EnumOperationKey.Ordinal, + EnumOperationKey.RemoteEnum -> + if (key.args.isNotEmpty()) { + evaluator.evalIntKey(key.args[0]) + } else { + IntInterval.UNBOUNDED + } + EnumOperationKey.ToString -> IntInterval.UNBOUNDED + } + + override fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary { + if (key.op != EnumOperationKey.ToString || key.args.size < 2) { + return StringSummary.UNKNOWN + } + val idxInterval = evaluator.evalIntKey(key.args[0]) + val arrayKey = key.args[1] + if (arrayKey is RemoteOperationCacheKey && arrayKey.op == StringArrayOperationKey.Create) { + return evaluator.unionStringArrayElements(arrayKey.args, idxInterval) + } + return StringSummary.UNKNOWN + } + + override fun extractIntAffine( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? = + when (key.op as EnumOperationKey) { + EnumOperationKey.Ordinal, + EnumOperationKey.RemoteEnum -> + key.args.firstOrNull()?.let { evaluator.extractIntAffineForm(it, depth + 1) } + EnumOperationKey.ToString -> null + } + + override fun unwrapAliasKey( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): RemoteStateCacheKey? = + when (key.op as EnumOperationKey) { + EnumOperationKey.Ordinal, + EnumOperationKey.RemoteEnum -> key.args.firstOrNull() + EnumOperationKey.ToString -> null + } + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + val args = key.args + return when (key.op as EnumOperationKey) { + EnumOperationKey.Ordinal -> { + if (!context.config.simplifyRangeMath) return null + val wrapped = args.firstOrNull() as? RemoteOperationCacheKey + if ( + wrapped != null && + wrapped.op == EnumOperationKey.RemoteEnum && + wrapped.args.isNotEmpty() + ) { + wrapped.args[0].getOrCreateValueOrNull() + } else { + null + } + } + EnumOperationKey.ToString -> { + if ( + !context.config.foldArrayGets || + args.size < 2 || + !context.hasBoundedFloatOperands(args[0]) + ) { + return null + } + val arrayKey = args[1] as? RemoteOperationCacheKey ?: return null + if (arrayKey.op != StringArrayOperationKey.Create) return null + val idxRange = context.evaluator.evalIntKey(args[0]) + if (idxRange.isPoint && idxRange.min in arrayKey.args.indices) { + arrayKey.args[idxRange.min].getOrCreateValueOrNull() + } else { + null + } + } + EnumOperationKey.RemoteEnum -> null + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteFloatIntervalSemantics.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteFloatIntervalSemantics.kt new file mode 100644 index 0000000..dc1a2fa --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteFloatIntervalSemantics.kt
@@ -0,0 +1,971 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.core.operations.utilities.AnimatedFloatExpression +import androidx.compose.remote.creation.compose.state.FloatArrayCacheKey +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteFloatOperationKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.RemoteValueKind +import androidx.compose.remote.creation.compose.state.max +import androidx.compose.remote.creation.compose.state.min +import androidx.compose.remote.document.intervals.FloatAnimationBounds +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.SlotInterval +import androidx.compose.remote.document.intervals.StringAndColorIntervalOps +import androidx.compose.remote.document.intervals.StringSummary +import androidx.compose.remote.document.intervals.TriState +import kotlin.math.PI +import kotlin.math.abs as mathAbs +import kotlin.math.cbrt as mathCbrt +import kotlin.math.exp as mathExp +import kotlin.math.ln as mathLn +import kotlin.math.log10 as mathLog10 +import kotlin.math.max as mathMax +import kotlin.math.min as mathMin +import kotlin.math.nextDown +import kotlin.math.nextUp +import kotlin.math.ulp + +/** External interval semantics for [RemoteFloatOperationKey]. */ +internal object RemoteFloatIntervalSemantics : RemoteOperationIntervalSemantics { + override fun requiresBoundedFloatOperands(op: Any): Boolean = + when (op as RemoteFloatOperationKey) { + RemoteFloatOperationKey.Times, + RemoteFloatOperationKey.Div, + RemoteFloatOperationKey.Rem, + RemoteFloatOperationKey.Mad, + RemoteFloatOperationKey.Clamp, + RemoteFloatOperationKey.Lerp, + RemoteFloatOperationKey.Min, + RemoteFloatOperationKey.Max, + RemoteFloatOperationKey.Abs, + RemoteFloatOperationKey.Round, + RemoteFloatOperationKey.Sin, + RemoteFloatOperationKey.Cos, + RemoteFloatOperationKey.Atan, + RemoteFloatOperationKey.Atan2, + RemoteFloatOperationKey.Sign, + RemoteFloatOperationKey.CopySign, + RemoteFloatOperationKey.Exp, + RemoteFloatOperationKey.Cubic, + RemoteFloatOperationKey.RandInRange -> true + else -> false + } + + override fun comparisonCondition(op: Any): IntervalComparison? = + when (op as RemoteFloatOperationKey) { + RemoteFloatOperationKey.CompareEQ -> IntervalComparison.EQ + RemoteFloatOperationKey.CompareNE -> IntervalComparison.NEQ + RemoteFloatOperationKey.CompareLT -> IntervalComparison.LT + RemoteFloatOperationKey.CompareLE -> IntervalComparison.LTE + RemoteFloatOperationKey.CompareGT -> IntervalComparison.GT + RemoteFloatOperationKey.CompareGE -> IntervalComparison.GTE + else -> null + } + + override fun selectCondition(op: Any): IntervalComparison? = + when (op as RemoteFloatOperationKey) { + RemoteFloatOperationKey.SelectIfLT -> IntervalComparison.LT + RemoteFloatOperationKey.SelectIfLE -> IntervalComparison.LTE + RemoteFloatOperationKey.SelectIfGT -> IntervalComparison.GT + RemoteFloatOperationKey.SelectIfGE -> IntervalComparison.GTE + else -> null + } + + override fun selectComparisonKind(op: Any, args: List<RemoteStateCacheKey>): RemoteValueKind = + if (selectCondition(op) != null) RemoteValueKind.FLOAT else RemoteValueKind.OTHER + + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval { + val op = key.op as RemoteFloatOperationKey + val args = key.args + selectCondition(op)?.let { cond -> + if (args.size < 4) return FloatInterval.UNBOUNDED + return when (evaluator.compareFloatKeys(cond, args[0], args[1])) { + TriState.TRUE -> evaluator.evalFloatKey(args[2]) + TriState.FALSE -> evaluator.evalFloatKey(args[3]) + TriState.UNKNOWN -> + evaluator + .evalComparisonBranch( + isInt = false, + comparison = cond, + keyA = args[0], + keyB = args[1], + holds = true, + ) { + it.evalFloatKey(args[2]) + } + .union( + evaluator.evalComparisonBranch( + isInt = false, + comparison = cond, + keyA = args[0], + keyB = args[1], + holds = false, + ) { + it.evalFloatKey(args[3]) + } + ) + } + } + comparisonCondition(op)?.let { cond -> + return if (args.size >= 2) { + evaluator.compareFloatKeys(cond, args[0], args[1]).toFloatInterval() + } else { + FloatInterval.UNIT + } + } + if (requiresBoundedFloatOperands(op)) { + var hasEmpty = false + var hasUnbounded = false + for (i in 0 until args.size) { + val operand = evaluator.evalFloatKey(args[i]) + if (operand.isEmpty) { + hasEmpty = true + } else if (operand.isUnbounded) { + hasUnbounded = true + } + } + if (hasEmpty) return FloatInterval.EMPTY + if (hasUnbounded) return FloatInterval.UNBOUNDED + } + return when (op) { + RemoteFloatOperationKey.Reference -> + if (args.isNotEmpty()) evaluator.evalFloatKey(args[0]) else FloatInterval.UNBOUNDED + RemoteFloatOperationKey.UnaryMinus -> + if (args.isNotEmpty()) -evaluator.evalFloatKey(args[0]) else FloatInterval.UNBOUNDED + RemoteFloatOperationKey.Plus -> + if (args.size >= 2) { + evaluator.evalFloatKey(args[0]) + evaluator.evalFloatKey(args[1]) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Minus -> + if (args.size >= 2) { + evaluator.evalFloatKey(args[0]) - evaluator.evalFloatKey(args[1]) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Times -> + if (args.size >= 2) { + evaluator.evalFloatKey(args[0]) * evaluator.evalFloatKey(args[1]) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Div -> + if (args.size >= 2) { + evaluator.evalFloatKey(args[0]) / evaluator.evalFloatKey(args[1]) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Rem -> + if (args.size >= 2) { + evaluator.evalFloatKey(args[0]) % evaluator.evalFloatKey(args[1]) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Min -> + if (args.size >= 2) { + evaluator.evalFloatKey(args[0]).min(evaluator.evalFloatKey(args[1])) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Max -> + if (args.size >= 2) { + evaluator.evalFloatKey(args[0]).max(evaluator.evalFloatKey(args[1])) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Abs -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]).abs() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Clamp -> + if (args.size >= 3) { + evaluator + .evalFloatKey(args[2]) + .clamp(evaluator.evalFloatKey(args[0]), evaluator.evalFloatKey(args[1])) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Mad -> + if (args.size >= 3) { + evaluator.evalFloatKey(args[0]) * evaluator.evalFloatKey(args[1]) + + evaluator.evalFloatKey(args[2]) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Lerp -> { + if (args.size < 3) { + FloatInterval.UNBOUNDED + } else { + val from = evaluator.evalFloatKey(args[0]) + val to = evaluator.evalFloatKey(args[1]) + val t = evaluator.evalFloatKey(args[2]) + when { + from.isEmpty || to.isEmpty || t.isEmpty -> FloatInterval.EMPTY + !from.isUnbounded && + !to.isUnbounded && + !t.isUnbounded && + t.min >= 0f && + t.max <= 1f -> evalLerpBox(from, to, t) + else -> from + (to - from) * t + } + } + } + RemoteFloatOperationKey.Floor -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]).floor() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Ceil -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]).ceil() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Round -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]).round() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Sqrt -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]).sqrt() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Cbrt -> { + val a = args.firstOrNull()?.let { evaluator.evalFloatKey(it) } + when { + a == null -> FloatInterval.UNBOUNDED + a.isEmpty -> FloatInterval.EMPTY + // AnimatedFloatExpression.OP_CBRT uses Math.pow(x, 1/3.), returning NaN for x < + // 0. + a.min < 0f -> FloatInterval.UNBOUNDED + else -> + FloatInterval( + if (a.min.isInfinite()) a.min else mathCbrt(a.min), + if (a.max.isInfinite()) a.max else mathCbrt(a.max), + ) + } + } + RemoteFloatOperationKey.Exp -> { + val a = args.firstOrNull()?.let { evaluator.evalFloatKey(it) } + when { + a == null -> FloatInterval.UNBOUNDED + a.isEmpty -> FloatInterval.EMPTY + else -> FloatInterval(expFloatBound(a.min), expFloatBound(a.max)) + } + } + RemoteFloatOperationKey.Ln -> evalPositiveLogInterval(args, evaluator, ::mathLn) + RemoteFloatOperationKey.Log -> evalPositiveLogInterval(args, evaluator, ::mathLog10) + RemoteFloatOperationKey.Pow -> + if (args.size >= 2) { + evaluator.evalBinaryFloatExactOrRange( + evaluator.evalFloatKey(args[0]), + evaluator.evalFloatKey(args[1]), + AnimatedFloatExpression.POW, + FloatInterval.UNBOUNDED, + ) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Rand -> + FloatInterval(0f, 1f, minInclusive = true, maxInclusive = false) + RemoteFloatOperationKey.RandInRange -> + if (args.size < 2) { + FloatInterval.UNBOUNDED + } else { + val from = evaluator.evalFloatKey(args[0]) + val to = evaluator.evalFloatKey(args[1]) + when { + from.isEmpty || to.isEmpty -> FloatInterval.EMPTY + from.isUnbounded || to.isUnbounded -> FloatInterval.UNBOUNDED + else -> evalLerpBox(from, to, FloatInterval.UNIT) + } + } + RemoteFloatOperationKey.Sin -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]).sin() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Cos -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]).cos() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Tan -> + if (args.isNotEmpty()) { + evaluator.evalUnaryFloatExactOrUnbounded( + evaluator.evalFloatKey(args[0]), + AnimatedFloatExpression.TAN, + ) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Asin -> + evalInverseTrigUnitInterval( + args, + evaluator, + AnimatedFloatExpression.ASIN, + (-PI / 2.0).toFloat(), + (PI / 2.0).toFloat(), + ) + RemoteFloatOperationKey.Acos -> + evalInverseTrigUnitInterval( + args, + evaluator, + AnimatedFloatExpression.ACOS, + 0f, + PI.toFloat(), + ) + RemoteFloatOperationKey.Atan -> + if (args.isNotEmpty()) { + val a = evaluator.evalFloatKey(args[0]) + when { + a.isEmpty -> FloatInterval.EMPTY + a.isPoint -> + evaluator.evalUnaryFloatExactOrUnbounded( + a, + AnimatedFloatExpression.ATAN, + ) + else -> FloatInterval((-PI / 2.0).toFloat(), (PI / 2.0).toFloat()) + } + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Atan2 -> + if (args.size >= 2) { + val a = evaluator.evalFloatKey(args[0]) + val b = evaluator.evalFloatKey(args[1]) + if (a.isEmpty || b.isEmpty) { + FloatInterval.EMPTY + } else { + evaluator.evalBinaryFloatExactOrRange( + a, + b, + AnimatedFloatExpression.ATAN2, + FloatInterval(-PI.toFloat(), PI.toFloat()), + ) + } + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.ToDeg -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]) * FloatInterval.point((180.0 / PI).toFloat()) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.ToRad -> + if (args.isNotEmpty()) { + evaluator.evalFloatKey(args[0]) * FloatInterval.point((PI / 180.0).toFloat()) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Sign -> { + val a = args.firstOrNull()?.let { evaluator.evalFloatKey(it) } + when { + a == null -> FloatInterval.UNBOUNDED + a.isEmpty -> FloatInterval.EMPTY + a.isAlwaysGreaterThan(FloatInterval.ZERO) -> FloatInterval.point(1f) + a.isAlwaysLessThan(FloatInterval.ZERO) -> FloatInterval.point(-1f) + a.isPoint && a.min == 0f -> FloatInterval.ZERO + else -> FloatInterval(-1f, 1f) + } + } + RemoteFloatOperationKey.CopySign -> + if (args.size < 2) { + FloatInterval.UNBOUNDED + } else { + val rawMag = evaluator.evalFloatKey(args[0]) + val signSrc = evaluator.evalFloatKey(args[1]) + if (rawMag.isEmpty || signSrc.isEmpty) { + FloatInterval.EMPTY + } else { + val absMag = rawMag.abs() + when { + signSrc.isAlwaysGreaterThan(FloatInterval.ZERO) -> absMag + signSrc.isAlwaysLessThan(FloatInterval.ZERO) -> -absMag + else -> (-absMag).union(absMag) + } + } + } + RemoteFloatOperationKey.TimeOfReferenceInSeconds -> FloatInterval(0f, 59f) + RemoteFloatOperationKey.TimeOfReferenceInMinutes -> FloatInterval(0f, 59f) + RemoteFloatOperationKey.TimeOfReferenceInHours -> FloatInterval(0f, 23f) + RemoteFloatOperationKey.DayOfMonthForReference -> FloatInterval(1f, 31f) + RemoteFloatOperationKey.MonthOfYearForReference -> FloatInterval(0f, 11f) + RemoteFloatOperationKey.DayOfWeekForReference -> FloatInterval(0f, 6f) + RemoteFloatOperationKey.ToInt, + RemoteFloatOperationKey.ToRemoteInt -> + if (args.isNotEmpty()) { + SlotInterval.fromFloat(evaluator.evalFloatKey(args[0])) + .toIntInterval() + .toFloatInterval() + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.Anim -> { + val spec = (args.getOrNull(1) as? FloatArrayCacheKey)?.floatArray + if (args.isNotEmpty() && spec != null) { + FloatAnimationBounds.boundAnimatedFloat(spec, evaluator.evalFloatKey(args[0])) + } else { + FloatInterval.UNBOUNDED + } + } + RemoteFloatOperationKey.Cubic -> + if (args.size >= 5) { + FloatAnimationBounds.evalCubicEasingInterval( + x1 = evaluator.evalFloatKey(args[0]), + y1 = evaluator.evalFloatKey(args[1]), + x2 = evaluator.evalFloatKey(args[2]), + y2 = evaluator.evalFloatKey(args[3]), + pos = evaluator.evalFloatKey(args[4]), + ) + } else { + FloatInterval.UNBOUNDED + } + RemoteFloatOperationKey.ToRemoteString, + RemoteFloatOperationKey.SelectIfLT, + RemoteFloatOperationKey.SelectIfLE, + RemoteFloatOperationKey.SelectIfGT, + RemoteFloatOperationKey.SelectIfGE, + RemoteFloatOperationKey.ComparisonOp, + RemoteFloatOperationKey.CompareEQ, + RemoteFloatOperationKey.CompareNE, + RemoteFloatOperationKey.CompareLT, + RemoteFloatOperationKey.CompareLE, + RemoteFloatOperationKey.CompareGT, + RemoteFloatOperationKey.CompareGE, + RemoteFloatOperationKey.DeltaFromReferenceInSeconds, + RemoteFloatOperationKey.DeltaFromReferenceInMinutes, + RemoteFloatOperationKey.DeltaFromReferenceInHours, + RemoteFloatOperationKey.YearForReference, + RemoteFloatOperationKey.Spline, + RemoteFloatOperationKey.SplineLoop -> FloatInterval.UNBOUNDED + } + } + + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval { + val op = key.op as RemoteFloatOperationKey + val args = key.args + comparisonCondition(op)?.let { cond -> + return if (args.size >= 2) { + evaluator.compareFloatKeys(cond, args[0], args[1]).toIntInterval() + } else { + IntInterval(0, 1) + } + } + return when (op) { + RemoteFloatOperationKey.ToInt, + RemoteFloatOperationKey.ToRemoteInt -> + if (args.isNotEmpty()) { + SlotInterval.fromFloat(evaluator.evalFloatKey(args[0])).toIntInterval() + } else { + IntInterval.UNBOUNDED + } + else -> SlotInterval.fromFloat(evaluator.evalFloatKey(key)).toIntInterval() + } + } + + override fun evaluateBooleanInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): TriState? { + val cond = comparisonCondition(key.op) ?: return null + return if (key.args.size >= 2) { + evaluator.compareFloatKeys(cond, key.args[0], key.args[1]) + } else { + TriState.UNKNOWN + } + } + + override fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary { + if (key.op != RemoteFloatOperationKey.ToRemoteString || key.args.size < 4) { + return StringSummary.UNKNOWN + } + val before = + ((key.args[1] as? RemoteConstantCacheKey)?.value as? Number)?.toInt() + ?: return StringSummary.UNKNOWN + val after = + ((key.args[2] as? RemoteConstantCacheKey)?.value as? Number)?.toInt() + ?: return StringSummary.UNKNOWN + val flags = + ((key.args[3] as? RemoteConstantCacheKey)?.value as? Number)?.toInt() + ?: return StringSummary.UNKNOWN + return StringAndColorIntervalOps.summarizeTextFromFloat( + evaluator.evalFloatKey(key.args[0]), + before, + after, + flags, + ) + } + + private fun evalPositiveLogInterval( + args: List<RemoteStateCacheKey>, + evaluator: RemoteValueIntervalEvaluator, + logFn: (Float) -> Float, + ): FloatInterval { + if (args.isEmpty()) return FloatInterval.UNBOUNDED + val a = evaluator.evalFloatKey(args[0]) + if (a.isEmpty) return FloatInterval.EMPTY + if (a.min <= 0f) return FloatInterval.UNBOUNDED + return FloatInterval( + if (a.min.isInfinite()) Float.POSITIVE_INFINITY else logFn(a.min), + if (a.max.isInfinite()) Float.POSITIVE_INFINITY else logFn(a.max), + ) + } + + private fun evalInverseTrigUnitInterval( + args: List<RemoteStateCacheKey>, + evaluator: RemoteValueIntervalEvaluator, + op: Float, + minOut: Float, + maxOut: Float, + ): FloatInterval { + if (args.isEmpty()) return FloatInterval.UNBOUNDED + val a = evaluator.evalFloatKey(args[0]) + return when { + a.isEmpty -> FloatInterval.EMPTY + a.min < -1f || a.max > 1f -> FloatInterval.UNBOUNDED + a.isPoint -> evaluator.evalUnaryFloatExactOrUnbounded(a, op) + else -> FloatInterval(minOut, maxOut) + } + } + + private fun evalLerpBox( + from: FloatInterval, + to: FloatInterval, + t: FloatInterval, + ): FloatInterval { + if (from.isPoint && to.isPoint) { + // Fixed float32 endpoints: d = fl(to - from) is constant, and fl(from + fl(d * p)) + // is monotone in p in IEEE-754 float32, so the exact extrema occur at t.min / t.max. + val diff = to.min - from.min + if (!diff.isFinite()) return FloatInterval.UNBOUNDED + val a = from.min + diff * t.min + val b = from.min + diff * t.max + if (!a.isFinite() || !b.isFinite()) return FloatInterval.UNBOUNDED + return FloatInterval(mathMin(a, b), mathMax(a, b)) + } + val fVals = floatArrayOf(from.min, from.max) + val uVals = floatArrayOf(to.min, to.max) + val tVals = floatArrayOf(t.min, t.max) + var loD = Double.POSITIVE_INFINITY + var hiD = Double.NEGATIVE_INFINITY + var maxDiffAbs = 0.0 + for (f in fVals) { + for (u in uVals) { + val diffAbs = mathAbs(u.toDouble() - f.toDouble()) + if (diffAbs > maxDiffAbs) maxDiffAbs = diffAbs + for (p in tVals) { + val dVal = f.toDouble() + (u.toDouble() - f.toDouble()) * p.toDouble() + if (!dVal.isFinite()) return FloatInterval.UNBOUNDED + if (dVal < loD) loD = dVal + if (dVal > hiD) hiD = dVal + } + } + } + val maxDiffFloat = ceilAbsToFloat(maxDiffAbs) ?: return FloatInterval.UNBOUNDED + val diffErr = 0.5 * maxDiffFloat.ulp.toDouble() + val maxTAbs = mathMax(mathAbs(t.min.toDouble()), mathAbs(t.max.toDouble())) + val maxProdAbs = (maxDiffAbs + diffErr) * maxTAbs + val maxProdFloat = ceilAbsToFloat(maxProdAbs) ?: return FloatInterval.UNBOUNDED + val prodErr = diffErr * maxTAbs + 0.5 * maxProdFloat.ulp.toDouble() + val maxValAbs = mathMax(mathAbs(loD), mathAbs(hiD)) + val maxSumAbs = maxValAbs + prodErr + val maxSumFloat = ceilAbsToFloat(maxSumAbs) ?: return FloatInterval.UNBOUNDED + val totalErr = + prodErr + 0.5 * maxSumFloat.ulp.toDouble() + 4.0 * mathMax(1.0, maxValAbs).ulp + val wideLo = loD - totalErr + val wideHi = hiD + totalErr + if (!wideLo.isFinite() || !wideHi.isFinite()) return FloatInterval.UNBOUNDED + val outLo = wideLo.toFloat().let { if (it.toDouble() > wideLo) it.nextDown() else it } + val outHi = wideHi.toFloat().let { if (it.toDouble() < wideHi) it.nextUp() else it } + if (!outLo.isFinite() || !outHi.isFinite()) return FloatInterval.UNBOUNDED + val boxHull = FloatInterval(outLo, outHi) + val intervalHull = from + (to - from) * t + return if (intervalHull.isUnbounded) boxHull else boxHull.intersect(intervalHull) + } + + private fun ceilAbsToFloat(value: Double): Float? { + if (!value.isFinite() || value > Float.MAX_VALUE.toDouble()) return null + val f = value.toFloat() + val roundedUp = if (f.toDouble() < value) f.nextUp() else f + return if (roundedUp.isFinite()) roundedUp else null + } + + private fun expFloatBound(v: Float): Float = + when (v) { + Float.NEGATIVE_INFINITY -> 0f + Float.POSITIVE_INFINITY -> Float.POSITIVE_INFINITY + else -> mathExp(v) + } + + override fun extractFloatAffine( + key: RemoteOperationCacheKey, + range: FloatInterval, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? { + val args = key.args + return when (key.op as RemoteFloatOperationKey) { + RemoteFloatOperationKey.Reference -> + args.firstOrNull()?.let { evaluator.extractFloatAffineForm(it, depth + 1) } + RemoteFloatOperationKey.UnaryMinus -> + args.firstOrNull()?.let { + evaluator.extractFloatAffineForm(it, depth + 1)?.negate() + } + RemoteFloatOperationKey.Plus -> + addFloatAffineArgs(args, range, negateRhs = false, evaluator, depth) + RemoteFloatOperationKey.Minus -> + addFloatAffineArgs(args, range, negateRhs = true, evaluator, depth) + RemoteFloatOperationKey.Times -> scaleFloatAffineTimes(args, range, evaluator, depth) + RemoteFloatOperationKey.Div -> { + if (args.size < 2) return null + val r1 = evaluator.evalFloatKey(args[1]) + if (!r1.isPoint || r1.min == 0f) return null + val raw = + evaluator + .extractFloatAffineForm(args[0], depth + 1) + ?.scale(1.0 / r1.min.toDouble(), 0.0) ?: return null + val tightRange = raw.evaluate(evaluator) ?: range + raw.withExtraError(maxUlp(tightRange)) + } + RemoteFloatOperationKey.Mad -> { + if (args.size < 3) return null + val prodRange = evaluator.evalFloatKey(args[0]) * evaluator.evalFloatKey(args[1]) + if (prodRange.isEmpty || prodRange.isUnbounded) return null + val prod = scaleFloatAffineTimes(args, prodRange, evaluator, depth) ?: return null + val addend = evaluator.extractFloatAffineForm(args[2], depth + 1) ?: return null + evaluator.combineFloatAffineAdd(prod, addend, range, negateRhs = false) + } + RemoteFloatOperationKey.Lerp -> { + if (args.size < 3) return null + val tRange = evaluator.evalFloatKey(args[2]) + if (!tRange.isPoint || !tRange.min.isFinite()) return null + val a = evaluator.extractFloatAffineForm(args[0], depth + 1) ?: return null + val b = evaluator.extractFloatAffineForm(args[1], depth + 1) ?: return null + val diffRange = evaluator.evalFloatKey(args[1]) - evaluator.evalFloatKey(args[0]) + if (diffRange.isEmpty || diffRange.isUnbounded) return null + val diff = evaluator.combineFloatAffineAdd(b, a, diffRange, negateRhs = true) + val scaledRaw = diff.scale(tRange.min.toDouble(), roundingUlp = 0.0) + val scaledRange = scaledRaw.evaluate(evaluator) ?: (diffRange * tRange) + val scaled = scaledRaw.withExtraError(maxUlp(scaledRange)) + evaluator.combineFloatAffineAdd(a, scaled, range, negateRhs = false) + } + else -> null + } + } + + override fun refineBoolean( + key: RemoteOperationCacheKey, + holds: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? { + val rawCond = comparisonCondition(key.op) ?: return null + if (key.args.size < 2) return null + val effCond = if (holds) rawCond else rawCond.negate() + return environment.narrowComparison(effCond, key.args[0], key.args[1]) + } + + override fun refineComparison( + key: RemoteOperationCacheKey, + comparison: IntervalComparison, + otherKey: RemoteStateCacheKey, + asInt: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? { + if (asInt) return null + val otherRange = evaluator.evalFloatKey(otherKey) + if (!otherRange.isPoint || otherRange.min != 0f) return null + val args = key.args + return when (key.op as RemoteFloatOperationKey) { + RemoteFloatOperationKey.Minus -> { + if (args.size < 2) return null + val lhsR = evaluator.evalFloatKey(args[0]) + val rhsR = evaluator.evalFloatKey(args[1]) + if (lhsR.isEmpty || rhsR.isEmpty || lhsR.isUnbounded || rhsR.isUnbounded) { + return null + } + environment.narrowComparison(comparison, args[0], args[1]) + } + RemoteFloatOperationKey.Plus -> { + if (args.size < 2) return null + val lhsR = evaluator.evalFloatKey(args[0]) + val rhsR = evaluator.evalFloatKey(args[1]) + if (lhsR.isEmpty || rhsR.isEmpty || lhsR.isUnbounded || rhsR.isUnbounded) { + return null + } + val negLhs = unwrapNegatedFloatKey(args[0]) + val negRhs = unwrapNegatedFloatKey(args[1]) + when { + negLhs != null -> environment.narrowComparison(comparison, args[1], negLhs) + negRhs != null -> environment.narrowComparison(comparison, args[0], negRhs) + else -> null + } + } + RemoteFloatOperationKey.Abs -> { + if (args.isEmpty()) return null + val innerR = evaluator.evalFloatKey(args[0]) + if (innerR.isEmpty || innerR.isUnbounded) return null + when (comparison) { + IntervalComparison.EQ, + IntervalComparison.LTE -> + environment.narrowComparison(IntervalComparison.EQ, args[0], otherKey) + IntervalComparison.GT -> + environment.narrowComparison(IntervalComparison.NEQ, args[0], otherKey) + else -> null + } + } + else -> null + } + } + + override fun unwrapAliasKey( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): RemoteStateCacheKey? = + if (key.op == RemoteFloatOperationKey.Reference) key.args.firstOrNull() else null + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + if (!context.config.simplifyRangeMath) return null + val args = key.args + val evaluator = context.evaluator + return when (key.op as RemoteFloatOperationKey) { + RemoteFloatOperationKey.Abs -> { + if (args.isEmpty() || !context.hasBoundedFloatOperands(args[0])) return null + val r = evaluator.evalFloatKey(args[0]) + if (r.isEmpty || r.isUnbounded) return null + when { + r.min >= 0f -> args[0].getOrCreateValueOrNull() + r.max <= 0f -> (args[0].getOrCreateValueOrNull() as? RemoteFloat)?.let { -it } + else -> null + } + } + RemoteFloatOperationKey.Min -> { + if ( + args.size < 2 || + !context.hasBoundedFloatOperands(args[0]) || + !context.hasBoundedFloatOperands(args[1]) + ) { + return null + } + val r0 = evaluator.evalFloatKey(args[0]) + val r1 = evaluator.evalFloatKey(args[1]) + if (r0.isEmpty || r1.isEmpty || r0.isUnbounded || r1.isUnbounded) return null + when { + evaluator.compareFloatKeys(IntervalComparison.LTE, args[0], args[1]) == + TriState.TRUE -> args[0].getOrCreateValueOrNull() + evaluator.compareFloatKeys(IntervalComparison.GTE, args[0], args[1]) == + TriState.TRUE -> args[1].getOrCreateValueOrNull() + else -> null + } + } + RemoteFloatOperationKey.Max -> { + if ( + args.size < 2 || + !context.hasBoundedFloatOperands(args[0]) || + !context.hasBoundedFloatOperands(args[1]) + ) { + return null + } + val r0 = evaluator.evalFloatKey(args[0]) + val r1 = evaluator.evalFloatKey(args[1]) + if (r0.isEmpty || r1.isEmpty || r0.isUnbounded || r1.isUnbounded) return null + when { + evaluator.compareFloatKeys(IntervalComparison.GTE, args[0], args[1]) == + TriState.TRUE -> args[0].getOrCreateValueOrNull() + evaluator.compareFloatKeys(IntervalComparison.LTE, args[0], args[1]) == + TriState.TRUE -> args[1].getOrCreateValueOrNull() + else -> null + } + } + RemoteFloatOperationKey.Clamp -> { + // Clamp args are stored in (min, max, value) order. + if ( + args.size < 3 || + !context.hasBoundedFloatOperands(args[0]) || + !context.hasBoundedFloatOperands(args[1]) || + !context.hasBoundedFloatOperands(args[2]) + ) { + return null + } + val rMin = evaluator.evalFloatKey(args[0]) + val rMax = evaluator.evalFloatKey(args[1]) + val rVal = evaluator.evalFloatKey(args[2]) + if ( + rMin.isEmpty || + rMax.isEmpty || + rVal.isEmpty || + rMin.isUnbounded || + rMax.isUnbounded || + rVal.isUnbounded + ) { + return null + } + if ( + evaluator.compareFloatKeys(IntervalComparison.LTE, args[0], args[1]) != + TriState.TRUE + ) { + return null + } + val geMin = + evaluator.compareFloatKeys(IntervalComparison.GTE, args[2], args[0]) == + TriState.TRUE + val leMax = + evaluator.compareFloatKeys(IntervalComparison.LTE, args[2], args[1]) == + TriState.TRUE + when { + geMin && leMax -> args[2].getOrCreateValueOrNull() + evaluator.compareFloatKeys(IntervalComparison.LTE, args[2], args[0]) == + TriState.TRUE -> args[0].getOrCreateValueOrNull() + evaluator.compareFloatKeys(IntervalComparison.GTE, args[2], args[1]) == + TriState.TRUE -> args[1].getOrCreateValueOrNull() + geMin -> { + val valState = args[2].getOrCreateValueOrNull() as? RemoteFloat + val maxState = args[1].getOrCreateValueOrNull() as? RemoteFloat + if (valState != null && maxState != null) min(valState, maxState) else null + } + leMax -> { + val valState = args[2].getOrCreateValueOrNull() as? RemoteFloat + val minState = args[0].getOrCreateValueOrNull() as? RemoteFloat + if (valState != null && minState != null) max(valState, minState) else null + } + else -> null + } + } + RemoteFloatOperationKey.Floor, + RemoteFloatOperationKey.Ceil -> { + if ( + args.isEmpty() || + !args[0].isResultWholeNumber || + !context.hasBoundedFloatOperands(args[0]) + ) { + return null + } + val r = evaluator.evalFloatKey(args[0]) + if (r.isEmpty || r.isUnbounded) null else args[0].getOrCreateValueOrNull() + } + RemoteFloatOperationKey.Round -> { + if ( + args.isEmpty() || + !args[0].isResultWholeNumber || + !context.hasBoundedFloatOperands(args[0]) + ) { + return null + } + val r = evaluator.evalFloatKey(args[0]) + // OP_ROUND delegates to (float) Math.round(x), which clamps values outside 32-bit + // Int range to Int.MIN_VALUE / Int.MAX_VALUE even when integer-valued. + if ( + r.isEmpty || + r.isUnbounded || + r.min < Int.MIN_VALUE.toFloat() || + r.max >= Int.MAX_VALUE.toFloat() + ) { + null + } else { + args[0].getOrCreateValueOrNull() + } + } + else -> null + } + } + + private fun addFloatAffineArgs( + args: List<RemoteStateCacheKey>, + range: FloatInterval, + negateRhs: Boolean, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? { + if (args.size < 2) return null + val a = evaluator.extractFloatAffineForm(args[0], depth + 1) ?: return null + val b = evaluator.extractFloatAffineForm(args[1], depth + 1) ?: return null + return evaluator.combineFloatAffineAdd(a, b, range, negateRhs) + } + + private fun scaleFloatAffineTimes( + args: List<RemoteStateCacheKey>, + range: FloatInterval, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? { + if (args.size < 2) return null + val r0 = evaluator.evalFloatKey(args[0]) + val r1 = evaluator.evalFloatKey(args[1]) + val raw = + when { + r0.isPoint -> + evaluator.extractFloatAffineForm(args[1], depth + 1)?.scale(r0.min.toDouble()) + r1.isPoint -> + evaluator.extractFloatAffineForm(args[0], depth + 1)?.scale(r1.min.toDouble()) + else -> null + } ?: return null + val tightRange = raw.evaluate(evaluator) ?: range + return raw.withExtraError(maxUlp(tightRange)) + } + + private fun unwrapNegatedFloatKey(key: RemoteStateCacheKey): RemoteStateCacheKey? { + val opKey = key as? RemoteOperationCacheKey ?: return null + val args = opKey.args + return when (opKey.op) { + RemoteFloatOperationKey.UnaryMinus -> args.firstOrNull() + RemoteFloatOperationKey.Times -> { + if (args.size < 2) return null + val c0 = ((args[0] as? RemoteConstantCacheKey)?.value as? Number)?.toFloat() + val c1 = ((args[1] as? RemoteConstantCacheKey)?.value as? Number)?.toFloat() + when { + c1 == -1f -> args[0] + c0 == -1f -> args[1] + else -> null + } + } + else -> null + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteIntIntervalSemantics.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteIntIntervalSemantics.kt new file mode 100644 index 0000000..790dfeb --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteIntIntervalSemantics.kt
@@ -0,0 +1,674 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.core.operations.utilities.IntegerExpressionEvaluator +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteIntOperationKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.RemoteValueKind +import androidx.compose.remote.creation.compose.state.max +import androidx.compose.remote.creation.compose.state.min +import androidx.compose.remote.document.TextFromFloatFlags +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.StringAndColorIntervalOps +import androidx.compose.remote.document.intervals.StringSummary +import androidx.compose.remote.document.intervals.TriState +import java.util.HashMap +import kotlin.math.min as mathMin + +/** External interval semantics for [RemoteIntOperationKey]. */ +internal object RemoteIntIntervalSemantics : RemoteOperationIntervalSemantics { + override fun comparisonCondition(op: Any): IntervalComparison? = + when (op as RemoteIntOperationKey) { + RemoteIntOperationKey.CompareEQ -> IntervalComparison.EQ + RemoteIntOperationKey.CompareNE -> IntervalComparison.NEQ + RemoteIntOperationKey.CompareLT -> IntervalComparison.LT + RemoteIntOperationKey.CompareLE -> IntervalComparison.LTE + RemoteIntOperationKey.CompareGT -> IntervalComparison.GT + RemoteIntOperationKey.CompareGE -> IntervalComparison.GTE + else -> null + } + + override fun selectCondition(op: Any): IntervalComparison? = + when (op as RemoteIntOperationKey) { + RemoteIntOperationKey.SelectIfLT -> IntervalComparison.LT + RemoteIntOperationKey.SelectIfLE -> IntervalComparison.LTE + RemoteIntOperationKey.SelectIfGT -> IntervalComparison.GT + RemoteIntOperationKey.SelectIfGE -> IntervalComparison.GTE + else -> null + } + + override fun selectComparisonKind(op: Any, args: List<RemoteStateCacheKey>): RemoteValueKind = + if (selectCondition(op) != null) RemoteValueKind.INT else RemoteValueKind.OTHER + + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = + if (key.op == RemoteIntOperationKey.ToFloat && key.args.isNotEmpty()) { + evaluator.evalIntKey(key.args[0]).toFloatInterval() + } else { + evaluator.evalIntKey(key).toFloatInterval() + } + + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval { + val op = key.op as RemoteIntOperationKey + val args = key.args + selectCondition(op)?.let { cond -> + if (args.size < 4) return IntInterval.UNBOUNDED + return when (evaluator.compareIntKeys(cond, args[0], args[1])) { + TriState.TRUE -> evaluator.evalIntKey(args[2]) + TriState.FALSE -> evaluator.evalIntKey(args[3]) + TriState.UNKNOWN -> + evaluator + .evalComparisonBranch( + isInt = true, + comparison = cond, + keyA = args[0], + keyB = args[1], + holds = true, + ) { + it.evalIntKey(args[2]) + } + .union( + evaluator.evalComparisonBranch( + isInt = true, + comparison = cond, + keyA = args[0], + keyB = args[1], + holds = false, + ) { + it.evalIntKey(args[3]) + } + ) + } + } + comparisonCondition(op)?.let { cond -> + return if (args.size >= 2) { + evaluator.compareIntKeys(cond, args[0], args[1]).toIntInterval() + } else { + IntInterval(0, 1) + } + } + return when (op) { + RemoteIntOperationKey.Reference, + RemoteIntOperationKey.Id, + RemoteIntOperationKey.ToFloat -> + if (args.isNotEmpty()) evaluator.evalIntKey(args[0]) else IntInterval.UNBOUNDED + RemoteIntOperationKey.Add -> + if (args.size >= 2) { + evaluator.evalIntKey(args[0]) + evaluator.evalIntKey(args[1]) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Sub -> + if (args.size >= 2) { + evaluator.evalIntKey(args[0]) - evaluator.evalIntKey(args[1]) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Mul -> + if (args.size >= 2) { + evaluator.evalIntKey(args[0]) * evaluator.evalIntKey(args[1]) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Div -> + if (args.size >= 2) { + evaluator.evalIntKey(args[0]) / evaluator.evalIntKey(args[1]) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Mod -> + if (args.size >= 2) { + evaluator.evalIntKey(args[0]) % evaluator.evalIntKey(args[1]) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Abs -> + if (args.isNotEmpty()) { + evaluator.evalIntKey(args[0]).abs() + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Neg -> + if (args.isNotEmpty()) -evaluator.evalIntKey(args[0]) else IntInterval.UNBOUNDED + RemoteIntOperationKey.Min -> + if (args.size >= 2) { + evaluator.evalIntKey(args[0]).min(evaluator.evalIntKey(args[1])) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Max -> + if (args.size >= 2) { + evaluator.evalIntKey(args[0]).max(evaluator.evalIntKey(args[1])) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Clamp -> + if (args.size >= 3) { + evaluator + .evalIntKey(args[2]) + .clamp(evaluator.evalIntKey(args[0]), evaluator.evalIntKey(args[1])) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Not -> + if (args.isNotEmpty()) { + evaluator.evalPointUnaryIntOp( + evaluator.evalIntKey(args[0]), + IntegerExpressionEvaluator.I_NOT, + ) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.And -> + if (args.size < 2) { + IntInterval.UNBOUNDED + } else { + val a = evaluator.evalIntKey(args[0]) + val b = evaluator.evalIntKey(args[1]) + when { + a.isEmpty || b.isEmpty -> IntInterval.EMPTY + a.isPoint && b.isPoint -> + evaluator.evalPointBinaryIntOp(a, b, IntegerExpressionEvaluator.I_AND) + a.min >= 0 && b.min >= 0 && a.hasFiniteMax && b.hasFiniteMax -> + IntInterval(0, mathMin(a.max, b.max)) + b.min >= 0 && b.hasFiniteMax -> IntInterval(0, b.max) + a.min >= 0 && a.hasFiniteMax -> IntInterval(0, a.max) + else -> IntInterval.UNBOUNDED + } + } + RemoteIntOperationKey.Or -> + evalBoolDomainOrPointBinaryInt(args, evaluator, IntegerExpressionEvaluator.I_OR) + RemoteIntOperationKey.Xor -> + evalBoolDomainOrPointBinaryInt(args, evaluator, IntegerExpressionEvaluator.I_XOR) + RemoteIntOperationKey.Shl -> + if (args.size >= 2) { + evaluator.evalPointBinaryIntOp( + evaluator.evalIntKey(args[0]), + evaluator.evalIntKey(args[1]), + IntegerExpressionEvaluator.I_SHL, + ) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.Shr -> + if (args.size >= 2) { + evaluator.evalPointBinaryIntOp( + evaluator.evalIntKey(args[0]), + evaluator.evalIntKey(args[1]), + IntegerExpressionEvaluator.I_SHR, + ) + } else { + IntInterval.UNBOUNDED + } + RemoteIntOperationKey.CopySign -> + if (args.size < 2) { + IntInterval.UNBOUNDED + } else { + val a = evaluator.evalIntKey(args[0]) + val b = evaluator.evalIntKey(args[1]) + if (a.isEmpty || b.isEmpty) { + IntInterval.EMPTY + } else if (a.isPoint && b.isPoint) { + evaluator.evalPointBinaryIntOp(a, b, IntegerExpressionEvaluator.I_COPY_SIGN) + } else { + // IntegerExpressionEvaluator.OP_COPY_SIGN returns a when b >= 0 and -a when + // b < 0 (it toggles sign rather than taking |a| first). + when { + b.min >= 0 -> a + b.max < 0 -> -a + else -> a.union(-a) + } + } + } + RemoteIntOperationKey.ToRemoteString, + RemoteIntOperationKey.CompareEQ, + RemoteIntOperationKey.CompareNE, + RemoteIntOperationKey.CompareLT, + RemoteIntOperationKey.CompareLE, + RemoteIntOperationKey.CompareGT, + RemoteIntOperationKey.CompareGE, + RemoteIntOperationKey.SelectIfLT, + RemoteIntOperationKey.SelectIfLE, + RemoteIntOperationKey.SelectIfGT, + RemoteIntOperationKey.SelectIfGE -> IntInterval.UNBOUNDED + } + } + + override fun evaluateBooleanInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): TriState? { + val op = key.op as RemoteIntOperationKey + val args = key.args + comparisonCondition(op)?.let { cond -> + return if (args.size >= 2) { + evaluator.compareIntKeys(cond, args[0], args[1]) + } else { + TriState.UNKNOWN + } + } + if ( + args.size < 2 || + (op != RemoteIntOperationKey.Xor && + op != RemoteIntOperationKey.And && + op != RemoteIntOperationKey.Or) + ) { + return null + } + val leftInt = evaluator.evalIntKey(args[0]) + val rightInt = evaluator.evalIntKey(args[1]) + if (leftInt.isEmpty || rightInt.isEmpty) return TriState.UNKNOWN + val leftIsBoolDomain = leftInt.min >= 0 && leftInt.max <= 1 + val rightIsBoolDomain = rightInt.min >= 0 && rightInt.max <= 1 + return when (op) { + RemoteIntOperationKey.Xor -> { + if (!leftIsBoolDomain || !rightIsBoolDomain) { + null + } else { + val c0 = leftInt.takeIf { it.isPoint }?.min + val c1 = rightInt.takeIf { it.isPoint }?.min + when { + c1 == 1 -> !evaluator.evalBoolKey(args[0]) + c0 == 1 -> !evaluator.evalBoolKey(args[1]) + else -> { + val b0 = evaluator.evalBoolKey(args[0]) + val b1 = evaluator.evalBoolKey(args[1]) + if (b0 != TriState.UNKNOWN && b1 != TriState.UNKNOWN) { + TriState.of(b0 != b1) + } else { + null + } + } + } + } + } + RemoteIntOperationKey.And -> { + val b0 = evaluator.evalBoolKey(args[0]) + val b1 = evaluator.evalBoolKey(args[1]) + when { + b0 == TriState.FALSE || b1 == TriState.FALSE -> TriState.FALSE + b0 == TriState.TRUE && + b1 == TriState.TRUE && + leftIsBoolDomain && + rightIsBoolDomain -> TriState.TRUE + else -> null + } + } + RemoteIntOperationKey.Or -> { + val b0 = evaluator.evalBoolKey(args[0]) + val b1 = evaluator.evalBoolKey(args[1]) + when { + b0 == TriState.FALSE && b1 == TriState.FALSE -> TriState.FALSE + (b0 == TriState.TRUE || b1 == TriState.TRUE) && + leftInt.min >= 0 && + rightInt.min >= 0 -> TriState.TRUE + else -> null + } + } + else -> null + } + } + + override fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary { + if (key.op != RemoteIntOperationKey.ToRemoteString || key.args.isEmpty()) { + return StringSummary.UNKNOWN + } + return StringAndColorIntervalOps.summarizeTextFromFloat( + evaluator.evalIntKey(key.args[0]).toFloatInterval(), + digitsBefore = 40, + digitsAfter = 0, + flags = + TextFromFloatFlags.SEPARATOR_COMMA_PERIOD or + TextFromFloatFlags.GROUPING_BY3 or + TextFromFloatFlags.PAD_AFTER_NONE or + TextFromFloatFlags.PAD_PRE_NONE, + ) + } + + private fun evalBoolDomainOrPointBinaryInt( + args: List<RemoteStateCacheKey>, + evaluator: RemoteValueIntervalEvaluator, + opCode: Int, + ): IntInterval { + if (args.size < 2) return IntInterval.UNBOUNDED + val a = evaluator.evalIntKey(args[0]) + val b = evaluator.evalIntKey(args[1]) + if (a.isEmpty || b.isEmpty) return IntInterval.EMPTY + if (a.isPoint && b.isPoint) { + return evaluator.evalPointBinaryIntOp(a, b, opCode) + } + if (!a.isEmpty && !b.isEmpty && a.min >= 0 && a.max <= 1 && b.min >= 0 && b.max <= 1) { + if (opCode == IntegerExpressionEvaluator.I_OR && (a.min == 1 || b.min == 1)) { + return IntInterval.point(1) + } + return IntInterval(0, 1) + } + return IntInterval.UNBOUNDED + } + + override fun extractFloatAffine( + key: RemoteOperationCacheKey, + range: FloatInterval, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? { + if (key.op != RemoteIntOperationKey.ToFloat || key.args.isEmpty()) return null + val intKey = key.args[0] + val intRange = evaluator.evalIntKey(intKey) + val intForm = evaluator.extractIntAffineForm(intKey, depth + 1) ?: return null + if (!intRange.hasFiniteMin || !intRange.hasFiniteMax) return null + val ulp = + if ( + intRange.min >= -EXACT_FLOAT32_INT_LIMIT && intRange.max <= EXACT_FLOAT32_INT_LIMIT + ) { + 0.0 + } else { + maxUlp(range) + } + if (intForm.constant < -(1L shl 53) || intForm.constant > (1L shl 53)) return null + val floatTerms = HashMap<AffineTerm, Double>(intForm.terms.size) + for ((k, w) in intForm.terms) { + if (w < -MAX_EXACT_INT_AFFINE_WEIGHT || w > MAX_EXACT_INT_AFFINE_WEIGHT) return null + floatTerms[AffineTerm(k, isInt = true)] = w.toDouble() + } + return FloatAffineForm(floatTerms, intForm.constant.toDouble(), ulp) + } + + override fun extractIntAffine( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? { + val args = key.args + return when (key.op as RemoteIntOperationKey) { + RemoteIntOperationKey.Reference, + RemoteIntOperationKey.Id -> + args.firstOrNull()?.let { evaluator.extractIntAffineForm(it, depth + 1) } + RemoteIntOperationKey.Neg -> { + val arg = args.firstOrNull() ?: return null + val r0 = evaluator.evalIntKey(arg) + if (!r0.hasFiniteMin || !r0.hasFiniteMax) return null + evaluator.extractIntAffineForm(arg, depth + 1)?.negate() + } + RemoteIntOperationKey.Add -> addIntAffineArgs(args, negateRhs = false, evaluator, depth) + RemoteIntOperationKey.Sub -> addIntAffineArgs(args, negateRhs = true, evaluator, depth) + RemoteIntOperationKey.Mul -> mulIntAffineArgs(args, evaluator, depth) + else -> null + } + } + + override fun refineBoolean( + key: RemoteOperationCacheKey, + holds: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? { + val op = key.op as RemoteIntOperationKey + val args = key.args + if (args.size < 2) return null + comparisonCondition(op)?.let { rawCond -> + val effCond = if (holds) rawCond else rawCond.negate() + return environment.narrowComparison(effCond, args[0], args[1], asInt = true) + } + return when (op) { + RemoteIntOperationKey.Xor -> { + val c0 = ((args[0] as? RemoteConstantCacheKey)?.value as? Number)?.toInt() + val c1 = ((args[1] as? RemoteConstantCacheKey)?.value as? Number)?.toInt() + val target = + when { + c1 == 1 -> args[0] + c0 == 1 -> args[1] + else -> null + } ?: return null + val r = evaluator.evalIntKey(target) + when { + !r.isEmpty && r.min >= 0 && r.max <= 1 -> environment.refine(target, !holds) + !holds && !r.isEmpty && r.min >= 0 -> + applyIntKeyNarrowing(environment, target, IntInterval.point(1)) + else -> null + } + } + RemoteIntOperationKey.And -> + if (holds) { + val r0 = evaluator.evalIntKey(args[0]) + val r1 = evaluator.evalIntKey(args[1]) + if (!r0.isEmpty && r0.min >= 0 && !r1.isEmpty && r1.min >= 0) { + environment.refine(args[0], true).refine(args[1], true) + } else { + null + } + } else { + null + } + RemoteIntOperationKey.Or -> + if (!holds) { + val r0 = evaluator.evalIntKey(args[0]) + val r1 = evaluator.evalIntKey(args[1]) + if (!r0.isEmpty && r0.min >= 0 && !r1.isEmpty && r1.min >= 0) { + environment.refine(args[0], false).refine(args[1], false) + } else { + null + } + } else { + null + } + else -> null + } + } + + override fun refineComparison( + key: RemoteOperationCacheKey, + comparison: IntervalComparison, + otherKey: RemoteStateCacheKey, + asInt: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? { + if (!asInt || key.op != RemoteIntOperationKey.Sub || key.args.size < 2) return null + val otherR = evaluator.evalIntKey(otherKey) + if (!otherR.isPoint || otherR.min != 0) return null + val lhsR = evaluator.evalIntKey(key.args[0]) + val rhsR = evaluator.evalIntKey(key.args[1]) + if (!lhsR.hasFiniteMin || !lhsR.hasFiniteMax || !rhsR.hasFiniteMin || !rhsR.hasFiniteMax) { + return null + } + val minDiff = lhsR.min.toLong() - rhsR.max.toLong() + val maxDiff = lhsR.max.toLong() - rhsR.min.toLong() + if (minDiff < Int.MIN_VALUE.toLong() || maxDiff > Int.MAX_VALUE.toLong()) return null + return environment.narrowComparison(comparison, key.args[0], key.args[1], asInt = true) + } + + override fun propagateFloatNarrowing( + key: RemoteOperationCacheKey, + interval: FloatInterval, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment { + if (key.op != RemoteIntOperationKey.ToFloat || key.args.isEmpty()) return environment + val intKey = key.args[0] + val existingInt = evaluator.evalIntKey(intKey) + val narrowedInt = existingInt.intersect(exactIntBoundsWithinFloatInterval(interval)) + return if (!narrowedInt.isEmpty && narrowedInt != existingInt) { + applyIntKeyNarrowing(environment, intKey, narrowedInt) + } else { + environment + } + } + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + if (!context.config.simplifyRangeMath) return null + val args = key.args + val evaluator = context.evaluator + return when (key.op as RemoteIntOperationKey) { + RemoteIntOperationKey.Abs -> { + if (args.isEmpty() || !context.hasBoundedFloatOperands(args[0])) return null + val r = evaluator.evalIntKey(args[0]) + if (r.isEmpty) return null + when { + r.hasFiniteMin && r.min >= 0 -> args[0].getOrCreateValueOrNull() + r.hasFiniteMin && r.hasFiniteMax && r.max <= 0 && r.min > Int.MIN_VALUE -> + (args[0].getOrCreateValueOrNull() as? RemoteInt)?.let { -it } + else -> null + } + } + RemoteIntOperationKey.Min -> { + if ( + args.size < 2 || + !context.hasBoundedFloatOperands(args[0]) || + !context.hasBoundedFloatOperands(args[1]) + ) { + return null + } + when { + evaluator.compareIntKeys(IntervalComparison.LTE, args[0], args[1]) == + TriState.TRUE -> args[0].getOrCreateValueOrNull() + evaluator.compareIntKeys(IntervalComparison.GTE, args[0], args[1]) == + TriState.TRUE -> args[1].getOrCreateValueOrNull() + else -> null + } + } + RemoteIntOperationKey.Max -> { + if ( + args.size < 2 || + !context.hasBoundedFloatOperands(args[0]) || + !context.hasBoundedFloatOperands(args[1]) + ) { + return null + } + when { + evaluator.compareIntKeys(IntervalComparison.GTE, args[0], args[1]) == + TriState.TRUE -> args[0].getOrCreateValueOrNull() + evaluator.compareIntKeys(IntervalComparison.LTE, args[0], args[1]) == + TriState.TRUE -> args[1].getOrCreateValueOrNull() + else -> null + } + } + RemoteIntOperationKey.Clamp -> { + // Clamp args are stored in (min, max, value) order. + if ( + args.size < 3 || + !context.hasBoundedFloatOperands(args[0]) || + !context.hasBoundedFloatOperands(args[1]) || + !context.hasBoundedFloatOperands(args[2]) + ) { + return null + } + if ( + evaluator.compareIntKeys(IntervalComparison.LTE, args[0], args[1]) != + TriState.TRUE + ) { + return null + } + val geMin = + evaluator.compareIntKeys(IntervalComparison.GTE, args[2], args[0]) == + TriState.TRUE + val leMax = + evaluator.compareIntKeys(IntervalComparison.LTE, args[2], args[1]) == + TriState.TRUE + when { + geMin && leMax -> args[2].getOrCreateValueOrNull() + evaluator.compareIntKeys(IntervalComparison.LTE, args[2], args[0]) == + TriState.TRUE -> args[0].getOrCreateValueOrNull() + evaluator.compareIntKeys(IntervalComparison.GTE, args[2], args[1]) == + TriState.TRUE -> args[1].getOrCreateValueOrNull() + geMin -> { + val valState = args[2].getOrCreateValueOrNull() as? RemoteInt + val maxState = args[1].getOrCreateValueOrNull() as? RemoteInt + if (valState != null && maxState != null) min(valState, maxState) else null + } + leMax -> { + val valState = args[2].getOrCreateValueOrNull() as? RemoteInt + val minState = args[0].getOrCreateValueOrNull() as? RemoteInt + if (valState != null && minState != null) max(valState, minState) else null + } + else -> null + } + } + else -> null + } + } + + private fun addIntAffineArgs( + args: List<RemoteStateCacheKey>, + negateRhs: Boolean, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? { + if (args.size < 2) return null + val r0 = evaluator.evalIntKey(args[0]) + val r1 = evaluator.evalIntKey(args[1]) + if (!r0.hasFiniteMin || !r0.hasFiniteMax || !r1.hasFiniteMin || !r1.hasFiniteMax) { + return null + } + val lo = + if (negateRhs) r0.min.toLong() - r1.max.toLong() else r0.min.toLong() + r1.min.toLong() + val hi = + if (negateRhs) r0.max.toLong() - r1.min.toLong() else r0.max.toLong() + r1.max.toLong() + if (lo < Int.MIN_VALUE.toLong() || hi > Int.MAX_VALUE.toLong()) return null + val a = evaluator.extractIntAffineForm(args[0], depth + 1) ?: return null + val b = evaluator.extractIntAffineForm(args[1], depth + 1) ?: return null + val rhs = if (negateRhs) b.negate() ?: return null else b + return a.add(rhs) + } + + private fun mulIntAffineArgs( + args: List<RemoteStateCacheKey>, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? { + if (args.size < 2) return null + val r0 = evaluator.evalIntKey(args[0]) + val r1 = evaluator.evalIntKey(args[1]) + if (!r0.hasFiniteMin || !r0.hasFiniteMax || !r1.hasFiniteMin || !r1.hasFiniteMax) { + return null + } + val p1 = r0.min.toLong() * r1.min.toLong() + val p2 = r0.min.toLong() * r1.max.toLong() + val p3 = r0.max.toLong() * r1.min.toLong() + val p4 = r0.max.toLong() * r1.max.toLong() + if ( + minOf(p1, p2, p3, p4) < Int.MIN_VALUE.toLong() || + maxOf(p1, p2, p3, p4) > Int.MAX_VALUE.toLong() + ) { + return null + } + return when { + r0.isPoint -> evaluator.extractIntAffineForm(args[1], depth + 1)?.scale(r0.min.toLong()) + r1.isPoint -> evaluator.extractIntAffineForm(args[0], depth + 1)?.scale(r1.min.toLong()) + else -> null + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteIntervalOperation.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteIntervalOperation.kt new file mode 100644 index 0000000..a7f1df3 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteIntervalOperation.kt
@@ -0,0 +1,419 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.creation.compose.state.BooleanOperationKey +import androidx.compose.remote.creation.compose.state.ColorOperationKey +import androidx.compose.remote.creation.compose.state.EnumOperationKey +import androidx.compose.remote.creation.compose.state.FloatArrayOperationKey +import androidx.compose.remote.creation.compose.state.IntArrayOperationKey +import androidx.compose.remote.creation.compose.state.RemoteFloatOperationKey +import androidx.compose.remote.creation.compose.state.RemoteIntOperationKey +import androidx.compose.remote.creation.compose.state.RemoteOperation +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.RemoteValueKind +import androidx.compose.remote.creation.compose.state.StringArrayOperationKey +import androidx.compose.remote.creation.compose.state.StringOperationKey +import androidx.compose.remote.document.intervals.ColorInterval +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.StringSummary +import androidx.compose.remote.document.intervals.TriState + +/** + * Optional extension of [RemoteOperation] for custom external operations that participate in + * interval analysis, condition refinement, and interval-guided expression simplification. + * + * Built-in `Remote*` operations stay decoupled from interval analysis and have their semantics + * supplied externally by isolated `Remote*IntervalSemantics` handlers. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public interface RemoteIntervalOperation : RemoteOperation { + /** + * Reports whether interval arithmetic on this operation can turn an unbounded float operand + * (which may represent `NaN` or `Infinity` at runtime) into a bounded or half-bounded interval + * even though the runtime operation may still yield `NaN` or non-finite values (for example, + * `UNBOUNDED * 0f == [0, 0]`, `clamp`, `lerp`, `min`, `max`, `sin`, or `exp`). + */ + public val requiresBoundedFloatOperands: Boolean + get() = false + + /** + * Relational [IntervalComparison] evaluated by this two-operand comparison operation, or `null` + * if this operation is not a relational comparison. + */ + public val comparisonCondition: IntervalComparison? + get() = null + + /** + * Relational [IntervalComparison] guarded by this 4-arg `selectIf*` operation, or `null` if + * this operation is not a relational select. + */ + public val selectCondition: IntervalComparison? + get() = null + + /** + * Domain ([RemoteValueKind]) in which this 4-arg `selectIf*` operation compares its first two + * arguments ([args]). Defaults to [RemoteValueKind.OTHER] so cross-type selects do not silently + * conflate their branch [resultKind] with their comparison domain. + */ + public fun selectComparisonKind(args: List<RemoteStateCacheKey>): RemoteValueKind = + RemoteValueKind.OTHER + + /** Reports whether this operation is a 3-arg boolean-condition `select(ifTrue, ifFalse)`. */ + public val isBooleanSelect: Boolean + get() = false + + /** + * Evaluates a conservative [FloatInterval] for an invocation of this operation ([key]) under + * [evaluator]. Defaults to [FloatInterval.UNBOUNDED]. + */ + public fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = FloatInterval.UNBOUNDED + + /** + * Evaluates a conservative [IntInterval] for an invocation of this operation ([key]) under + * [evaluator]. Defaults to [IntInterval.UNBOUNDED]. + */ + public fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval = IntInterval.UNBOUNDED + + /** + * Evaluates a conservative [TriState] truth value for an invocation of this operation ([key]) + * under [evaluator], or `null` to fall back to integer truthiness (`0` → [TriState.FALSE], + * strictly `> 0` → [TriState.TRUE], otherwise [TriState.UNKNOWN]). + */ + public fun evaluateBooleanInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): TriState? = null + + /** + * Evaluates a conservative [StringSummary] for an invocation of this operation ([key]) under + * [evaluator]. Defaults to [StringSummary.UNKNOWN]. + */ + public fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary = StringSummary.UNKNOWN + + /** + * Evaluates a conservative [ColorInterval] for an invocation of this operation ([key]) under + * [evaluator]. Defaults to [ColorInterval.UNKNOWN]. + */ + public fun evaluateColorInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): ColorInterval = ColorInterval.UNKNOWN + + /** + * Extracts a rounding-error-aware [FloatAffineForm] for [key] given its standard interval + * [range], [evaluator], and recursion [depth], or returns `null` if this operation does not + * have a linear float affine representation. + */ + public fun extractFloatAffine( + key: RemoteOperationCacheKey, + range: FloatInterval, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? = null + + /** + * Extracts an overflow-verified [IntAffineForm] for [key] under [evaluator] and recursion + * [depth], or returns `null` if this operation does not have a linear integer affine + * representation. + */ + public fun extractIntAffine( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? = null + + /** + * Refines [environment] assuming boolean expression [key] evaluates to [holds], or returns + * `null` to fall back to generic variable refinement. + */ + public fun refineBoolean( + key: RemoteOperationCacheKey, + holds: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? = null + + /** + * Refines [environment] assuming `key <comparison> otherKey` holds (in the integer domain when + * [asInt] is `true`, or the float domain otherwise), or returns `null` if this operation has no + * additional relational refinement. + */ + public fun refineComparison( + key: RemoteOperationCacheKey, + comparison: IntervalComparison, + otherKey: RemoteStateCacheKey, + asInt: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? = null + + /** + * Unwraps transparent wrapper operations (such as references or resolved selects) to the + * underlying operand key during condition refinement, or returns `null` if not transparent. + */ + public fun unwrapAliasKey( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): RemoteStateCacheKey? = null + + /** + * Propagates a float narrowing [interval] applied to [key] back to child operand keys in + * [environment] (e.g., exact integer back-propagation through `RemoteInt.toRemoteFloat()`). + */ + public fun propagateFloatNarrowing( + key: RemoteOperationCacheKey, + interval: FloatInterval, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment = environment + + /** + * Attempts to simplify an invocation of this operation ([value] with cache key [key]) after its + * children have been optimized, using the interval bounds and settings in [context]. + * + * Returns a simplified replacement [RemoteValue], or `null` to keep [value] unchanged. + */ + public fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = null +} + +/** + * External interval-semantics adapter for a family of [RemoteOperation]s, allowing interval + * analysis code to stay isolated from `Remote*` implementation files. + */ +internal interface RemoteOperationIntervalSemantics { + fun requiresBoundedFloatOperands(op: Any): Boolean = false + + fun comparisonCondition(op: Any): IntervalComparison? = null + + fun selectCondition(op: Any): IntervalComparison? = null + + fun selectComparisonKind(op: Any, args: List<RemoteStateCacheKey>): RemoteValueKind = + RemoteValueKind.OTHER + + fun isBooleanSelect(op: Any): Boolean = false + + fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = FloatInterval.UNBOUNDED + + fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval = IntInterval.UNBOUNDED + + fun evaluateBooleanInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): TriState? = null + + fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary = StringSummary.UNKNOWN + + fun evaluateColorInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): ColorInterval = ColorInterval.UNKNOWN + + fun extractFloatAffine( + key: RemoteOperationCacheKey, + range: FloatInterval, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? = null + + fun extractIntAffine( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? = null + + fun refineBoolean( + key: RemoteOperationCacheKey, + holds: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? = null + + fun refineComparison( + key: RemoteOperationCacheKey, + comparison: IntervalComparison, + otherKey: RemoteStateCacheKey, + asInt: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? = null + + fun unwrapAliasKey( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): RemoteStateCacheKey? = null + + fun propagateFloatNarrowing( + key: RemoteOperationCacheKey, + interval: FloatInterval, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment = environment + + fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = null +} + +internal fun intervalSemanticsFor(op: Any): RemoteOperationIntervalSemantics? = + when (op) { + is RemoteFloatOperationKey -> RemoteFloatIntervalSemantics + is RemoteIntOperationKey -> RemoteIntIntervalSemantics + is BooleanOperationKey -> RemoteBooleanIntervalSemantics + is StringOperationKey -> RemoteStringIntervalSemantics + is ColorOperationKey -> RemoteColorIntervalSemantics + is EnumOperationKey -> RemoteEnumIntervalSemantics + is FloatArrayOperationKey -> RemoteFloatArrayIntervalSemantics + is IntArrayOperationKey -> RemoteIntArrayIntervalSemantics + is StringArrayOperationKey -> RemoteStringArrayIntervalSemantics + is RemoteIntervalOperation -> CustomRemoteIntervalOperationSemantics + else -> null + } + +private object CustomRemoteIntervalOperationSemantics : RemoteOperationIntervalSemantics { + override fun requiresBoundedFloatOperands(op: Any): Boolean = + (op as RemoteIntervalOperation).requiresBoundedFloatOperands + + override fun comparisonCondition(op: Any): IntervalComparison? = + (op as RemoteIntervalOperation).comparisonCondition + + override fun selectCondition(op: Any): IntervalComparison? = + (op as RemoteIntervalOperation).selectCondition + + override fun selectComparisonKind(op: Any, args: List<RemoteStateCacheKey>): RemoteValueKind = + (op as RemoteIntervalOperation).selectComparisonKind(args) + + override fun isBooleanSelect(op: Any): Boolean = (op as RemoteIntervalOperation).isBooleanSelect + + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = (key.op as RemoteIntervalOperation).evaluateFloatInterval(key, evaluator) + + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval = (key.op as RemoteIntervalOperation).evaluateIntInterval(key, evaluator) + + override fun evaluateBooleanInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): TriState? = (key.op as RemoteIntervalOperation).evaluateBooleanInterval(key, evaluator) + + override fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary = (key.op as RemoteIntervalOperation).evaluateStringSummary(key, evaluator) + + override fun evaluateColorInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): ColorInterval = (key.op as RemoteIntervalOperation).evaluateColorInterval(key, evaluator) + + override fun extractFloatAffine( + key: RemoteOperationCacheKey, + range: FloatInterval, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): FloatAffineForm? = + (key.op as RemoteIntervalOperation).extractFloatAffine(key, range, evaluator, depth) + + override fun extractIntAffine( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + depth: Int, + ): IntAffineForm? = (key.op as RemoteIntervalOperation).extractIntAffine(key, evaluator, depth) + + override fun refineBoolean( + key: RemoteOperationCacheKey, + holds: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? = + (key.op as RemoteIntervalOperation).refineBoolean(key, holds, environment, evaluator) + + override fun refineComparison( + key: RemoteOperationCacheKey, + comparison: IntervalComparison, + otherKey: RemoteStateCacheKey, + asInt: Boolean, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment? = + (key.op as RemoteIntervalOperation).refineComparison( + key, + comparison, + otherKey, + asInt, + environment, + evaluator, + ) + + override fun unwrapAliasKey( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): RemoteStateCacheKey? = (key.op as RemoteIntervalOperation).unwrapAliasKey(key, evaluator) + + override fun propagateFloatNarrowing( + key: RemoteOperationCacheKey, + interval: FloatInterval, + environment: IntervalEnvironment, + evaluator: RemoteValueIntervalEvaluator, + ): IntervalEnvironment = + (key.op as RemoteIntervalOperation).propagateFloatNarrowing( + key, + interval, + environment, + evaluator, + ) + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = + (key.op as RemoteIntervalOperation).simplifyWithIntervals(value, key, context) +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteStringIntervalSemantics.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteStringIntervalSemantics.kt new file mode 100644 index 0000000..8ade807 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteStringIntervalSemantics.kt
@@ -0,0 +1,203 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteValueKind +import androidx.compose.remote.creation.compose.state.StringOperationKey +import androidx.compose.remote.document.TextTransformOperation +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.StringAndColorIntervalOps +import androidx.compose.remote.document.intervals.StringSummary +import androidx.compose.remote.document.intervals.TriState + +/** External interval semantics for [StringOperationKey]. */ +internal object RemoteStringIntervalSemantics : RemoteOperationIntervalSemantics { + override fun selectCondition(op: Any): IntervalComparison? = + when (op as StringOperationKey) { + StringOperationKey.SelectIfLT -> IntervalComparison.LT + StringOperationKey.SelectIfLE -> IntervalComparison.LTE + StringOperationKey.SelectIfGT -> IntervalComparison.GT + StringOperationKey.SelectIfGE -> IntervalComparison.GTE + else -> null + } + + override fun selectComparisonKind(op: Any, args: List<RemoteStateCacheKey>): RemoteValueKind { + val stringOp = op as StringOperationKey + if (selectCondition(stringOp) == null || args.size < 2) return RemoteValueKind.OTHER + val k0 = args[0].getValueKind() + val k1 = args[1].getValueKind() + return when { + (k0.isIntEncoded || k1.isIntEncoded) && + k0 != RemoteValueKind.FLOAT && + k1 != RemoteValueKind.FLOAT -> RemoteValueKind.INT + k0 == RemoteValueKind.FLOAT || k1 == RemoteValueKind.FLOAT -> RemoteValueKind.FLOAT + else -> RemoteValueKind.OTHER + } + } + + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = evaluator.evalIntKey(key).toFloatInterval() + + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval = + when (key.op as StringOperationKey) { + StringOperationKey.Length -> + if (key.args.isNotEmpty()) { + evaluator.evalStringKey(key.args[0]).length + } else { + IntInterval.NON_NEGATIVE + } + StringOperationKey.IsEmpty -> evalIsEmpty(key.args, evaluator).toIntInterval() + StringOperationKey.IsNotEmpty -> (!evalIsEmpty(key.args, evaluator)).toIntInterval() + else -> IntInterval.UNBOUNDED + } + + override fun evaluateBooleanInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): TriState? = + when (key.op as StringOperationKey) { + StringOperationKey.IsEmpty -> evalIsEmpty(key.args, evaluator) + StringOperationKey.IsNotEmpty -> !evalIsEmpty(key.args, evaluator) + else -> null + } + + override fun evaluateStringSummary( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): StringSummary { + val op = key.op as StringOperationKey + val args = key.args + selectCondition(op)?.let { cond -> + if (args.size < 4) return StringSummary.UNKNOWN + val cmpKind = selectComparisonKind(op, args) + val isIntCmp = + when { + cmpKind.isIntEncoded -> true + cmpKind == RemoteValueKind.FLOAT -> false + else -> + return evaluator + .evalStringKey(args[2]) + .union(evaluator.evalStringKey(args[3])) + } + val cmp = + if (isIntCmp) { + evaluator.compareIntKeys(cond, args[0], args[1]) + } else { + evaluator.compareFloatKeys(cond, args[0], args[1]) + } + return when (cmp) { + TriState.TRUE -> evaluator.evalStringKey(args[2]) + TriState.FALSE -> evaluator.evalStringKey(args[3]) + TriState.UNKNOWN -> + evaluator + .evalComparisonBranch( + isInt = isIntCmp, + comparison = cond, + keyA = args[0], + keyB = args[1], + holds = true, + ) { + it.evalStringKey(args[2]) + } + .union( + evaluator.evalComparisonBranch( + isInt = isIntCmp, + comparison = cond, + keyA = args[0], + keyB = args[1], + holds = false, + ) { + it.evalStringKey(args[3]) + } + ) + } + } + return when (op) { + StringOperationKey.Concat -> + if (args.size >= 2) { + StringAndColorIntervalOps.summarizeTextMerge( + evaluator.evalStringKey(args[0]), + evaluator.evalStringKey(args[1]), + ) + } else { + StringSummary.UNKNOWN + } + StringOperationKey.Substring -> + when (args.size) { + 2 -> + StringAndColorIntervalOps.summarizeSubstring( + src = evaluator.evalStringKey(args[0]), + start = evaluator.evalIntKey(args[1]).toFloatInterval(), + len = FloatInterval.point(-1f), + ) + 3 -> { + val startInt = evaluator.evalIntKey(args[1]) + val lenInt = evaluator.evalIntKey(args[2]) - startInt + StringAndColorIntervalOps.summarizeSubstring( + src = evaluator.evalStringKey(args[0]), + start = startInt.toFloatInterval(), + len = lenInt.toFloatInterval(), + ) + } + else -> StringSummary.UNKNOWN + } + StringOperationKey.Uppercase -> + evalCaseOrTrim(args, evaluator, TextTransformOperation.TO_UPPERCASE) + StringOperationKey.Lowercase -> + evalCaseOrTrim(args, evaluator, TextTransformOperation.TO_LOWERCASE) + StringOperationKey.Trim -> evalCaseOrTrim(args, evaluator, TextTransformOperation.TRIM) + else -> StringSummary.UNKNOWN + } + } + + private fun evalIsEmpty( + args: List<RemoteStateCacheKey>, + evaluator: RemoteValueIntervalEvaluator, + ): TriState { + if (args.isEmpty()) return TriState.UNKNOWN + val len = evaluator.evalStringKey(args[0]).length + return when { + len.isEmpty -> TriState.UNKNOWN + len.max == 0 -> TriState.TRUE + len.min > 0 -> TriState.FALSE + else -> TriState.UNKNOWN + } + } + + private fun evalCaseOrTrim( + args: List<RemoteStateCacheKey>, + evaluator: RemoteValueIntervalEvaluator, + operation: Int, + ): StringSummary { + if (args.isEmpty()) return StringSummary.UNKNOWN + return StringAndColorIntervalOps.summarizeTextTransform( + src = evaluator.evalStringKey(args[0]), + start = FloatInterval.ZERO, + len = FloatInterval.point(-1f), + operation = operation, + ) + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteValueIntervalEvaluator.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteValueIntervalEvaluator.kt new file mode 100644 index 0000000..0d52c37 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/intervals/RemoteValueIntervalEvaluator.kt
@@ -0,0 +1,603 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.core.operations.utilities.AnimatedFloatExpression +import androidx.compose.remote.core.operations.utilities.IntegerExpressionEvaluator +import androidx.compose.remote.creation.compose.state.BaseRemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteColor +import androidx.compose.remote.creation.compose.state.RemoteColorConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteNamedCacheKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateIdKey +import androidx.compose.remote.creation.compose.state.RemoteString +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.cacheKey +import androidx.compose.remote.document.intervals.ColorInterval +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.StringSummary +import androidx.compose.remote.document.intervals.TriState +import java.util.HashMap +import java.util.HashSet +import kotlin.math.max +import kotlin.math.min + +/** + * Memoized, polymorphic interval evaluator over [RemoteValue] expression DAGs ([RemoteFloat], + * [RemoteInt], [RemoteBoolean], [RemoteString], [RemoteColor]), backed by an [IntervalEnvironment]. + * + * Built-in operation semantics are dispatched externally via isolated `Remote*IntervalSemantics` + * handlers (`intervalSemanticsFor`), while custom external operations can opt in via + * [RemoteIntervalOperation]. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class RemoteValueIntervalEvaluator +internal constructor( + public val environment: IntervalEnvironment, + internal val selectDepth: Int, +) { + /** Creates an interval evaluator backed by [environment]. */ + @JvmOverloads + public constructor( + environment: IntervalEnvironment = MapIntervalEnvironment.EMPTY + ) : this(environment = environment, selectDepth = 0) + + private val floatMemo = HashMap<RemoteStateCacheKey, FloatInterval>() + private val intMemo = HashMap<RemoteStateCacheKey, IntInterval>() + private val boolMemo = HashMap<RemoteStateCacheKey, TriState>() + private val stringMemo = HashMap<RemoteStateCacheKey, StringSummary>() + private val colorMemo = HashMap<RemoteStateCacheKey, ColorInterval>() + internal val boundedFloatOperandsMemo = HashMap<RemoteStateCacheKey, Boolean>() + internal val floatAffineMemo = HashMap<RemoteStateCacheKey, Pair<Int, FloatAffineForm?>>() + internal val intAffineMemo = HashMap<RemoteStateCacheKey, Pair<Int, IntAffineForm?>>() + + private val visitingFloat = HashSet<RemoteStateCacheKey>() + private val visitingInt = HashSet<RemoteStateCacheKey>() + private val visitingBool = HashSet<RemoteStateCacheKey>() + private val visitingString = HashSet<RemoteStateCacheKey>() + private val visitingColor = HashSet<RemoteStateCacheKey>() + + internal val floatEvaluator: AnimatedFloatExpression = AnimatedFloatExpression() + internal val intEvaluator: IntegerExpressionEvaluator = IntegerExpressionEvaluator() + + /** Evaluates a sound [FloatInterval] bounding [value]. */ + public fun evalFloat(value: RemoteFloat): FloatInterval { + value.constantValueOrNull?.let { + return FloatInterval.point(it) + } + return evalFloatKey(value.cacheKey) + } + + /** Evaluates a sound [IntInterval] bounding [value]. */ + public fun evalInt(value: RemoteInt): IntInterval { + value.constantValueOrNull?.let { + return IntInterval.point(it) + } + return evalIntKey(value.cacheKey) + } + + /** Evaluates a sound [TriState] truth value for [value]. */ + public fun evalBoolean(value: RemoteBoolean): TriState { + value.constantValueOrNull?.let { + return TriState.of(it) + } + return evalBoolKey(value.cacheKey) + } + + /** Evaluates a sound [StringSummary] bounding [value]. */ + public fun evalString(value: RemoteString): StringSummary { + value.constantValueOrNull?.let { + return StringSummary.constant(it) + } + return evalStringKey(value.cacheKey) + } + + /** Evaluates a sound [ColorInterval] bounding [value]. */ + public fun evalColor(value: RemoteColor): ColorInterval { + value.constantValueOrNull?.let { + return ColorInterval.constant(it) + } + return evalColorKey(value.cacheKey) + } + + /** Evaluates a sound [FloatInterval] for [key] with cycle-safe DAG memoization. */ + public fun evalFloatKey(key: RemoteStateCacheKey): FloatInterval { + environment.floatOverride(key)?.let { + return it + } + floatMemo[key]?.let { + return it + } + if (!visitingFloat.add(key)) return FloatInterval.UNBOUNDED + return try { + computeFloatKey(key).also { floatMemo[key] = it } + } finally { + visitingFloat.remove(key) + } + } + + /** Evaluates a sound [IntInterval] for [key] with cycle-safe DAG memoization. */ + public fun evalIntKey(key: RemoteStateCacheKey): IntInterval { + environment.intOverride(key)?.let { + return it + } + intMemo[key]?.let { + return it + } + if (!visitingInt.add(key)) return IntInterval.UNBOUNDED + return try { + computeIntKey(key).also { intMemo[key] = it } + } finally { + visitingInt.remove(key) + } + } + + /** Evaluates a sound [TriState] truth value for [key] with cycle-safe DAG memoization. */ + public fun evalBoolKey(key: RemoteStateCacheKey): TriState { + boolMemo[key]?.let { + return it + } + if (!visitingBool.add(key)) return TriState.UNKNOWN + return try { + computeBoolKey(key).also { boolMemo[key] = it } + } finally { + visitingBool.remove(key) + } + } + + /** Evaluates a sound [StringSummary] for [key] with cycle-safe DAG memoization. */ + public fun evalStringKey(key: RemoteStateCacheKey): StringSummary { + stringMemo[key]?.let { + return it + } + if (!visitingString.add(key)) return StringSummary.UNKNOWN + return try { + computeStringKey(key).also { stringMemo[key] = it } + } finally { + visitingString.remove(key) + } + } + + /** Evaluates a sound [ColorInterval] for [key] with cycle-safe DAG memoization. */ + public fun evalColorKey(key: RemoteStateCacheKey): ColorInterval { + colorMemo[key]?.let { + return it + } + if (!visitingColor.add(key)) return ColorInterval.UNKNOWN + return try { + computeColorKey(key).also { colorMemo[key] = it } + } finally { + visitingColor.remove(key) + } + } + + /** + * Evaluates `keyA <comparison> keyB` as floats using interval bounds, deterministic + * self-comparison checks, and ULP-aware linear affine differences. + */ + public fun compareFloatKeys( + comparison: IntervalComparison, + keyA: RemoteStateCacheKey, + keyB: RemoteStateCacheKey, + ): TriState { + val intervalA = evalFloatKey(keyA) + val intervalB = evalFloatKey(keyB) + val direct = intervalA.compare(comparison, intervalB) + if (direct != TriState.UNKNOWN) return direct + if ( + keyA == keyB && !intervalA.isEmpty && !intervalA.isUnbounded && keyA.isDeterministic() + ) { + return comparison.selfComparisonResult() + } + return compareFloatAffineDiff(comparison, keyA, keyB) + } + + /** + * Evaluates `keyA <comparison> keyB` as integers using interval bounds, deterministic + * self-comparison checks, and overflow-verified linear affine differences. + */ + public fun compareIntKeys( + comparison: IntervalComparison, + keyA: RemoteStateCacheKey, + keyB: RemoteStateCacheKey, + ): TriState { + val intervalA = evalIntKey(keyA) + val intervalB = evalIntKey(keyB) + val direct = intervalA.compare(comparison, intervalB) + if (direct != TriState.UNKNOWN) return direct + if (keyA == keyB && !intervalA.isEmpty && keyA.isDeterministic()) { + return comparison.selfComparisonResult() + } + return compareIntAffineDiff(comparison, keyA, keyB) + } + + internal fun hasBoundedFloatOperands(key: RemoteStateCacheKey): Boolean { + boundedFloatOperandsMemo[key]?.let { + return it + } + if (key !is RemoteOperationCacheKey) return true + val visiting = HashSet<RemoteStateCacheKey>() + val expanded = HashSet<RemoteStateCacheKey>() + val stack = ArrayList<RemoteStateCacheKey>() + stack.add(key) + while (stack.isNotEmpty()) { + val node = stack[stack.size - 1] + if (boundedFloatOperandsMemo.containsKey(node)) { + stack.removeAt(stack.size - 1) + continue + } + if (node !is RemoteOperationCacheKey) { + boundedFloatOperandsMemo[node] = true + stack.removeAt(stack.size - 1) + continue + } + if (expanded.add(node)) { + visiting.add(node) + val sem = intervalSemanticsFor(node.op) + if (sem?.requiresBoundedFloatOperands(node.op) == true) { + var operandUnbounded = false + for (i in 0 until node.args.size) { + if (evalFloatKey(node.args[i]).isUnbounded) { + operandUnbounded = true + break + } + } + if (operandUnbounded) { + boundedFloatOperandsMemo[node] = false + visiting.remove(node) + stack.removeAt(stack.size - 1) + continue + } + } + var hasCycle = false + for (i in 0 until node.args.size) { + if (node.args[i] in visiting) { + hasCycle = true + break + } + } + if (hasCycle) { + boundedFloatOperandsMemo[node] = false + visiting.remove(node) + stack.removeAt(stack.size - 1) + continue + } + for (i in 0 until node.args.size) { + val child = node.args[i] + if ( + child is RemoteOperationCacheKey && + !boundedFloatOperandsMemo.containsKey(child) + ) { + stack.add(child) + } + } + } else { + stack.removeAt(stack.size - 1) + visiting.remove(node) + if (!boundedFloatOperandsMemo.containsKey(node)) { + var allOk = true + for (i in 0 until node.args.size) { + val child = node.args[i] + if ( + child is RemoteOperationCacheKey && + boundedFloatOperandsMemo[child] == false + ) { + allOk = false + break + } + } + boundedFloatOperandsMemo[node] = allOk + } + } + } + return boundedFloatOperandsMemo[key] ?: false + } + + internal fun evalUnaryFloatExactOrUnbounded(x: FloatInterval, op: Float): FloatInterval { + if (x.isPoint) { + val v = floatEvaluator.eval(floatArrayOf(x.min, op)) + if (v.isFinite()) return FloatInterval.point(v) + } + return FloatInterval.UNBOUNDED + } + + internal fun evalBinaryFloatExactOrRange( + a: FloatInterval, + b: FloatInterval, + op: Float, + fallback: FloatInterval, + ): FloatInterval { + if (a.isPoint && b.isPoint) { + val v = floatEvaluator.eval(floatArrayOf(a.min, b.min, op)) + if (v.isFinite()) return FloatInterval.point(v) + } + return fallback + } + + internal fun evalPointUnaryIntOp(a: IntInterval, opCode: Int): IntInterval = + when { + a.isEmpty -> IntInterval.EMPTY + a.isPoint -> IntInterval.point(intEvaluator.eval(1 shl 1, intArrayOf(a.min, opCode))) + else -> IntInterval.UNBOUNDED + } + + internal fun evalPointBinaryIntOp(a: IntInterval, b: IntInterval, opCode: Int): IntInterval = + when { + a.isEmpty || b.isEmpty -> IntInterval.EMPTY + a.isPoint && b.isPoint -> + IntInterval.point(intEvaluator.eval(1 shl 2, intArrayOf(a.min, b.min, opCode))) + else -> IntInterval.UNBOUNDED + } + + internal fun unionFloatArrayElements( + elems: List<RemoteStateCacheKey>, + idxInterval: IntInterval, + ): FloatInterval { + if (idxInterval.isEmpty) return FloatInterval.EMPTY + if (elems.isEmpty()) return FloatInterval.ZERO + val start = if (idxInterval.hasFiniteMin) max(0, idxInterval.min) else 0 + val end = + if (idxInterval.hasFiniteMax) min(elems.size - 1, idxInterval.max) else elems.size - 1 + var acc: FloatInterval? = null + for (i in start..end) { + val elem = evalFloatKey(elems[i]) + acc = acc?.union(elem) ?: elem + } + if ( + !idxInterval.hasFiniteMin || + idxInterval.min < 0 || + !idxInterval.hasFiniteMax || + idxInterval.max >= elems.size + ) { + acc = acc?.union(FloatInterval.ZERO) ?: FloatInterval.ZERO + } + return acc ?: FloatInterval.ZERO + } + + internal fun unionIntArrayElements( + elems: List<RemoteStateCacheKey>, + idxInterval: IntInterval, + ): IntInterval { + if (idxInterval.isEmpty) return IntInterval.EMPTY + if (elems.isEmpty()) return IntInterval.ZERO + val start = if (idxInterval.hasFiniteMin) max(0, idxInterval.min) else 0 + val end = + if (idxInterval.hasFiniteMax) min(elems.size - 1, idxInterval.max) else elems.size - 1 + var acc: IntInterval? = null + for (i in start..end) { + val elem = evalIntKey(elems[i]) + acc = acc?.union(elem) ?: elem + } + if ( + !idxInterval.hasFiniteMin || + idxInterval.min < 0 || + !idxInterval.hasFiniteMax || + idxInterval.max >= elems.size + ) { + acc = acc?.union(IntInterval.ZERO) ?: IntInterval.ZERO + } + return acc ?: IntInterval.ZERO + } + + internal fun unionStringArrayElements( + elems: List<RemoteStateCacheKey>, + idxInterval: IntInterval, + ): StringSummary { + if ( + elems.isEmpty() || + idxInterval.isEmpty || + !idxInterval.hasFiniteMin || + idxInterval.min < 0 || + !idxInterval.hasFiniteMax || + idxInterval.max >= elems.size + ) { + return StringSummary.UNKNOWN + } + var acc: StringSummary? = null + for (i in idxInterval.min..idxInterval.max) { + val elem = evalStringKey(elems[i]) + acc = acc?.union(elem) ?: elem + } + return acc ?: StringSummary.UNKNOWN + } + + internal inline fun <T> evalBooleanBranch( + condKey: RemoteStateCacheKey, + holds: Boolean, + evalFn: (RemoteValueIntervalEvaluator) -> T, + ): T { + val refined = refineEnvironmentForBooleanBranch(condKey, holds) + return if (refined !== environment) { + evalFn(RemoteValueIntervalEvaluator(refined, selectDepth + 1)) + } else { + evalFn(this) + } + } + + internal inline fun <T> evalComparisonBranch( + isInt: Boolean, + comparison: IntervalComparison, + keyA: RemoteStateCacheKey, + keyB: RemoteStateCacheKey, + holds: Boolean, + evalFn: (RemoteValueIntervalEvaluator) -> T, + ): T { + val refined = refineEnvironmentForComparisonBranch(isInt, comparison, keyA, keyB, holds) + return if (refined !== environment) { + evalFn(RemoteValueIntervalEvaluator(refined, selectDepth + 1)) + } else { + evalFn(this) + } + } + + internal fun refineEnvironmentForBooleanBranch( + condKey: RemoteStateCacheKey, + holds: Boolean, + ): IntervalEnvironment { + if (selectDepth >= MAX_SELECT_REFINE_DEPTH) return environment + return environment.refine(condKey, holds) + } + + internal fun refineEnvironmentForComparisonBranch( + isInt: Boolean, + comparison: IntervalComparison, + keyA: RemoteStateCacheKey, + keyB: RemoteStateCacheKey, + holds: Boolean, + ): IntervalEnvironment { + if (selectDepth >= MAX_SELECT_REFINE_DEPTH) return environment + val effComparison = if (holds) comparison else comparison.negate() + return environment.narrowComparison(effComparison, keyA, keyB, asInt = isInt) + } + + private fun computeFloatKey(key: RemoteStateCacheKey): FloatInterval { + return when (key) { + is RemoteConstantCacheKey -> + when (val v = key.value) { + is Number -> FloatInterval.point(v.toFloat()) + is Boolean -> FloatInterval.point(if (v) 1f else 0f) + else -> FloatInterval.UNBOUNDED + } + is RemoteStateIdKey -> environment.floatForStateId(key.id) + is RemoteNamedCacheKey -> environment.floatForNamed(key) + is RemoteOperationCacheKey -> { + val sem = intervalSemanticsFor(key.op) ?: return FloatInterval.UNBOUNDED + val standard = sem.evaluateFloatInterval(key, this) + if (!standard.isEmpty && !standard.isPoint && !standard.isUnbounded) { + val affine = + sem.extractFloatAffine(key, standard, this, depth = 0)?.evaluate(this) + if (affine != null && !affine.isEmpty) { + val tightened = standard.intersect(affine) + if (!tightened.isEmpty) return tightened + } + } + standard + } + else -> { + val constVal = (key as? BaseRemoteStateCacheKey)?.getState()?.constantValueOrNull + if (constVal is Number) { + FloatInterval.point(constVal.toFloat()) + } else { + FloatInterval.UNBOUNDED + } + } + } + } + + private fun computeIntKey(key: RemoteStateCacheKey): IntInterval { + return when (key) { + is RemoteConstantCacheKey -> + when (val v = key.value) { + is Number -> IntInterval.point(v.toInt()) + is Boolean -> IntInterval.point(if (v) 1 else 0) + is Enum<*> -> IntInterval.point(v.ordinal) + else -> IntInterval.UNBOUNDED + } + is RemoteStateIdKey -> environment.intForStateId(key.id) + is RemoteNamedCacheKey -> environment.intForNamed(key) + is RemoteOperationCacheKey -> { + val sem = intervalSemanticsFor(key.op) ?: return IntInterval.UNBOUNDED + val standard = sem.evaluateIntInterval(key, this) + if (!standard.isEmpty && !standard.isPoint) { + val affine = + sem.extractIntAffine(key, this, depth = 0)?.evaluateIntInterval(this) + if (affine != null && !affine.isEmpty) { + val tightened = standard.intersect(affine) + if (!tightened.isEmpty) return tightened + } + } + standard + } + else -> { + when ( + val constVal = + (key as? BaseRemoteStateCacheKey)?.getState()?.constantValueOrNull + ) { + is Number -> IntInterval.point(constVal.toInt()) + is Boolean -> IntInterval.point(if (constVal) 1 else 0) + is Enum<*> -> IntInterval.point(constVal.ordinal) + else -> IntInterval.UNBOUNDED + } + } + } + } + + private fun computeBoolKey(key: RemoteStateCacheKey): TriState { + if (key is RemoteConstantCacheKey) { + (key.value as? Boolean)?.let { + return TriState.of(it) + } + } + if (key is RemoteOperationCacheKey) { + intervalSemanticsFor(key.op)?.evaluateBooleanInterval(key, this)?.let { + return it + } + } + val intRange = evalIntKey(key) + return when { + intRange.isEmpty -> TriState.UNKNOWN + intRange.isPoint && intRange.min == 0 -> TriState.FALSE + // Require strictly positive so truthiness agrees with both != 0 and wire I_IFELSE (> + // 0). + intRange.min > 0 -> TriState.TRUE + else -> TriState.UNKNOWN + } + } + + private fun computeStringKey(key: RemoteStateCacheKey): StringSummary = + when (key) { + is RemoteConstantCacheKey -> + (key.value as? String)?.let { StringSummary.constant(it) } ?: StringSummary.UNKNOWN + is RemoteStateIdKey -> environment.stringForStateId(key.id) + is RemoteNamedCacheKey -> environment.stringForNamed(key) + is RemoteOperationCacheKey -> + intervalSemanticsFor(key.op)?.evaluateStringSummary(key, this) + ?: StringSummary.UNKNOWN + else -> { + val constVal = (key as? BaseRemoteStateCacheKey)?.getState()?.constantValueOrNull + if (constVal is String) StringSummary.constant(constVal) else StringSummary.UNKNOWN + } + } + + private fun computeColorKey(key: RemoteStateCacheKey): ColorInterval = + when (key) { + is RemoteColorConstantCacheKey -> ColorInterval.constant(key.color) + is RemoteConstantCacheKey -> + (key.value as? Int)?.let { ColorInterval.constant(it) } ?: ColorInterval.UNKNOWN + is RemoteStateIdKey -> environment.colorForStateId(key.id) + is RemoteNamedCacheKey -> environment.colorForNamed(key) + is RemoteOperationCacheKey -> + intervalSemanticsFor(key.op)?.evaluateColorInterval(key, this) + ?: ColorInterval.UNKNOWN + else -> { + val constVal = (key as? BaseRemoteStateCacheKey)?.getState()?.constantValueOrNull + if (constVal is Int) ColorInterval.constant(constVal) else ColorInterval.UNKNOWN + } + } + + private companion object { + private const val MAX_SELECT_REFINE_DEPTH = 4 + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteColor.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteColor.kt index 9e093da..e38c1dd 100644 --- a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteColor.kt +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteColor.kt
@@ -280,6 +280,9 @@ // ColorExpression requires alpha to be constant in the range [0..255] val fixedAlpha = floatComponentToByte(alpha.constantValueOrNull ?: 1f) + if (alpha.hasConstantValue && fixedAlpha != 255) { + return fromAHSV(fixedAlpha, hue, saturation, value) + } val colorWithConstantAlpha = RemoteColorImpl( @@ -592,7 +595,7 @@ ?: colorComponent(ColorAttribute.COLOR_BRIGHTNESS) } -private enum class ColorOperationKey : RemoteOperation { +internal enum class ColorOperationKey : RemoteOperation { FromHSV, FromAHSV, FromArgb,
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteFloatArray.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteFloatArray.kt index b3c771b..66d0486 100644 --- a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteFloatArray.kt +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteFloatArray.kt
@@ -106,7 +106,7 @@ } } -private enum class FloatArrayOperationKey : RemoteOperation { +internal enum class FloatArrayOperationKey : RemoteOperation { Create { override val resultKind: RemoteValueKind get() = RemoteValueKind.FLOAT_ARRAY
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteImageBitmap.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteImageBitmap.kt index 207afa36..88849cb 100644 --- a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteImageBitmap.kt +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteImageBitmap.kt
@@ -51,6 +51,41 @@ /** The height of the bitmap as represented in the remote document. */ public val height: RemoteFloat + /** + * The backing image URL if this bitmap was created from a URL (via [RemoteImageBitmap] or + * [createNamedRemoteImageBitmap]), or `null` otherwise. + */ + @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) + public val urlOrNull: String? + get() = null + + /** + * The explicitly declared width in pixels for this bitmap (such as from a URL factory, + * offscreen bitmap, or encoded bitmap), or `null` when unknown (such as [createForId]) or when + * the bitmap uses intrinsic dimensions (see [hasIntrinsicDimensions]). + */ + @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) + public val declaredWidth: Int? + get() = null + + /** + * The explicitly declared height in pixels for this bitmap (such as from a URL factory, + * offscreen bitmap, or encoded bitmap), or `null` when unknown (such as [createForId]) or when + * the bitmap uses intrinsic dimensions (see [hasIntrinsicDimensions]). + */ + @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) + public val declaredHeight: Int? + get() = null + + /** + * Returns `true` if this bitmap was configured to use the loaded image's intrinsic dimensions + * (such as a URL bitmap created with `0x0` dimensions), in which case [declaredWidth] and + * [declaredHeight] are `null`. + */ + @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) + public val hasIntrinsicDimensions: Boolean + get() = false + public companion object { /** * Creates a [RemoteImageBitmap] referencing a remote ID. @@ -110,6 +145,10 @@ RemoteImageBitmapImpl( constantValueOrNull = null, cacheKey = RemoteNamedCacheKey(domain, name), + urlOrNull = url, + declaredWidth = width.takeIf { it > 0 }, + declaredHeight = height.takeIf { it > 0 }, + hasIntrinsicDimensions = width == 0 && height == 0, idProvider = { creationState -> val bitmapId = creationState.document.addBitmapUrl(url, width, height) creationState.document.setNamedVariable( @@ -133,6 +172,8 @@ RemoteImageBitmapImpl( constantValueOrNull = null, cacheKey = RemoteStateInstanceKey(), + declaredWidth = width, + declaredHeight = height, idProvider = { creationState -> creationState.document.createBitmap(width, height) }, @@ -142,28 +183,54 @@ private enum class ImageBitmapOperationKey : RemoteOperation { Width, - Height; + Height, + Url; override fun toDebugString(args: List<RemoteStateCacheKey>): String = when (this) { Width -> "${args[0].toOperandString(100)}.width" Height -> "${args[0].toOperandString(100)}.height" + Url -> + "url(${args[0].toOperandString(100)}, " + + "${args[1].toOperandString(100)}, " + + "${args[2].toOperandString(100)})" } override fun reconstruct(args: List<RemoteValue<*>>): RemoteValue<*> = when (this) { Width -> (args[0] as RemoteImageBitmap).width Height -> (args[0] as RemoteImageBitmap).height + Url -> + RemoteImageBitmap( + url = (args[0] as RemoteString).constantValue, + width = (args[1] as RemoteInt).constantValue, + height = (args[2] as RemoteInt).constantValue, + ) } override val resultKind: RemoteValueKind - get() = RemoteValueKind.FLOAT + get() = + when (this) { + Width, + Height -> RemoteValueKind.FLOAT + Url -> RemoteValueKind.IMAGE_BITMAP + } - override fun isResultWholeNumber(args: List<RemoteStateCacheKey>): Boolean = true + override fun isResultWholeNumber(args: List<RemoteStateCacheKey>): Boolean = + this == Width || this == Height } -private abstract class BaseRemoteImageBitmap(cacheKey: RemoteStateCacheKey) : - BaseRemoteValue<Any>(cacheKey), RemoteImageBitmap { +private abstract class BaseRemoteImageBitmap( + cacheKey: RemoteStateCacheKey, + override val urlOrNull: String? = null, + declaredWidth: Int? = null, + declaredHeight: Int? = null, + override val hasIntrinsicDimensions: Boolean = false, +) : BaseRemoteValue<Any>(cacheKey), RemoteImageBitmap { + override val declaredWidth: Int? = declaredWidth?.takeIf { it > 0 } + + override val declaredHeight: Int? = declaredHeight?.takeIf { it > 0 } + override val equalityType: KClass<*> get() = RemoteImageBitmap::class @@ -204,8 +271,19 @@ private class RemoteImageBitmapImpl( override val constantValueOrNull: Any?, cacheKey: RemoteStateCacheKey, + urlOrNull: String? = null, + declaredWidth: Int? = null, + declaredHeight: Int? = null, + hasIntrinsicDimensions: Boolean = false, private val idProvider: BitmapIdProvider, -) : BaseRemoteImageBitmap(cacheKey) { +) : + BaseRemoteImageBitmap( + cacheKey = cacheKey, + urlOrNull = urlOrNull, + declaredWidth = declaredWidth, + declaredHeight = declaredHeight, + hasIntrinsicDimensions = hasIntrinsicDimensions, + ) { override fun writeToDocument(creationState: RemoteComposeCreationState): Int = idProvider.provide(creationState).id } @@ -240,8 +318,16 @@ private class MutableRemoteImageBitmapImpl( cacheKey: RemoteStateCacheKey, override val constantValueOrNull: Any?, + declaredWidth: Int? = null, + declaredHeight: Int? = null, private val idProvider: BitmapIdProvider, -) : BaseRemoteImageBitmap(cacheKey), MutableRemoteImageBitmap { +) : + BaseRemoteImageBitmap( + cacheKey = cacheKey, + declaredWidth = declaredWidth, + declaredHeight = declaredHeight, + ), + MutableRemoteImageBitmap { override fun writeToDocument(creationState: RemoteComposeCreationState): Int = idProvider.provide(creationState).id @@ -250,19 +336,23 @@ } /** - * Creates a [MutableRemoteImageBitmap] with the given [constantValueOrNull], [cacheKey], and - * [idProvider]. + * Creates a [MutableRemoteImageBitmap] with the given [constantValueOrNull], [cacheKey], optional + * [declaredWidth] and [declaredHeight], and [idProvider]. */ @RememberInComposition @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun MutableRemoteImageBitmap( constantValueOrNull: Any?, cacheKey: RemoteStateCacheKey? = null, + declaredWidth: Int? = null, + declaredHeight: Int? = null, idProvider: BitmapIdProvider, ): MutableRemoteImageBitmap = MutableRemoteImageBitmapImpl( cacheKey = cacheKey ?: RemoteStateInstanceKey(), constantValueOrNull = constantValueOrNull, + declaredWidth = declaredWidth, + declaredHeight = declaredHeight, idProvider = idProvider, ) @@ -273,8 +363,30 @@ * @return A [RemoteImageBitmap] representing the image from the URL. */ public fun RemoteImageBitmap(url: String): RemoteImageBitmap = + RemoteImageBitmap(url = url, width = 1, height = 1) + +/** + * Creates a [RemoteImageBitmap] from a [url] with explicit [width] and [height]. + * + * @param url The URL of the image. + * @param width Expected width of the bitmap in pixels, or `0` to use the loaded image's dimensions. + * @param height Expected height of the bitmap in pixels, or `0` to use the loaded image's + * dimensions. + * @return A [RemoteImageBitmap] representing the image from the URL. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public fun RemoteImageBitmap(url: String, width: Int, height: Int): RemoteImageBitmap = RemoteImageBitmapImpl( constantValueOrNull = null, - cacheKey = RemoteConstantCacheKey(url), - idProvider = { creationState -> creationState.document.addBitmapUrl(url) }, + cacheKey = + if (width == 1 && height == 1) { + RemoteConstantCacheKey(url) + } else { + RemoteOperationCacheKey.create(ImageBitmapOperationKey.Url, url, width, height) + }, + urlOrNull = url, + declaredWidth = width.takeIf { it > 0 }, + declaredHeight = height.takeIf { it > 0 }, + hasIntrinsicDimensions = width == 0 && height == 0, + idProvider = { creationState -> creationState.document.addBitmapUrl(url, width, height) }, )
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteIntArray.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteIntArray.kt index aaadf78..fec63d5 100644 --- a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteIntArray.kt +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteIntArray.kt
@@ -48,7 +48,7 @@ } } -private enum class IntArrayOperationKey : RemoteOperation { +internal enum class IntArrayOperationKey : RemoteOperation { Create { override val resultKind: RemoteValueKind get() = RemoteValueKind.INT_ARRAY
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteString.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteString.kt index aecfa2b..a932259 100644 --- a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteString.kt +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteString.kt
@@ -202,7 +202,7 @@ } } -private enum class StringOperationKey(override val precedence: Int = 100) : RemoteOperation { +internal enum class StringOperationKey(override val precedence: Int = 100) : RemoteOperation { Concat(3), Substring, Uppercase,
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteStringArray.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteStringArray.kt index 573df18..4fe9f27 100644 --- a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteStringArray.kt +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/creation/compose/state/RemoteStringArray.kt
@@ -40,7 +40,7 @@ } } -private enum class StringArrayOperationKey : RemoteOperation { +internal enum class StringArrayOperationKey : RemoteOperation { Create { override val resultKind: RemoteValueKind get() = RemoteValueKind.STRING_ARRAY
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/ProfileOperationRegistry.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/ProfileOperationRegistry.kt new file mode 100644 index 0000000..2b466f9 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/ProfileOperationRegistry.kt
@@ -0,0 +1,107 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document + +import androidx.annotation.RestrictTo + +/** + * Thread-safe registry supplying supported operation IDs for externally defined RemoteCompose + * profile bitmasks beyond the built-in [RcProfiles] opcodes. + * + * Each RemoteCompose client or document builder may hold its own [ProfileOperationRegistry] + * instance so registrations do not leak across unrelated clients in the same process. + * + * Registered providers use additive union semantics: for documents at `apiLevel >= 7`, an opcode is + * considered supported if either [RcProfiles.isOpcodeSupported] returns `true` or any provider + * whose registered `profileMask` is satisfied by `profileFlags` includes the opcode. (Unlike + * built-in [RcProfiles] platform flags, external providers never restrict built-in opcodes.) + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class ProfileOperationRegistry() { + @Volatile private var providers: Map<Int, (profileFlags: Int) -> Set<Int>> = emptyMap() + + /** + * Registers [operationsProvider] for documents whose header profile bitmask includes all bits + * in [profileMask] (`(profileFlags and profileMask) == profileMask`). + * + * Re-registering the same [profileMask] replaces the previous provider. Thread-safe via + * synchronized copy-on-write updates. + * + * @throws IllegalArgumentException if [profileMask] is `0` + */ + public fun register(profileMask: Int, operationsProvider: (profileFlags: Int) -> Set<Int>) { + require(profileMask != 0) { "profileMask must be non-zero" } + synchronized(this) { + val updated = LinkedHashMap(providers) + updated[profileMask] = operationsProvider + providers = updated + } + } + + /** + * Removes any provider previously registered for [profileMask]. No-op if [profileMask] is not + * registered. + */ + public fun unregister(profileMask: Int) { + synchronized(this) { + if (!providers.containsKey(profileMask)) return + val updated = LinkedHashMap(providers) + updated.remove(profileMask) + providers = updated + } + } + + /** + * Returns the union of operation IDs supplied by every registered provider whose `profileMask` + * matches [profileFlags]. + */ + public fun resolveOperationIds(profileFlags: Int): Set<Int> { + val snapshot = providers + if (profileFlags == 0 || snapshot.isEmpty()) return emptySet() + var result: MutableSet<Int>? = null + for ((mask, provider) in snapshot) { + if ((profileFlags and mask) == mask) { + val ops = provider(profileFlags) + if (ops.isNotEmpty()) { + if (result == null) result = LinkedHashSet() + result.addAll(ops) + } + } + } + return result ?: emptySet() + } + + /** + * Returns true if [opcode] is supported for [apiLevel] and [profileFlags] by either built-in + * [RcProfiles] rules or (when `apiLevel >= 7`) any registered external profile provider. + * + * For `apiLevel <= 6`, profile bitmasks are not supported and this delegates solely to + * [RcProfiles.isOpcodeSupported]. + */ + public fun isOpcodeSupported(opcode: Int, apiLevel: Int, profileFlags: Int): Boolean { + if (RcProfiles.isOpcodeSupported(opcode, apiLevel, profileFlags)) return true + if (apiLevel <= 6 || profileFlags == 0) return false + val snapshot = providers + if (snapshot.isEmpty()) return false + for ((mask, provider) in snapshot) { + if ((profileFlags and mask) == mask && opcode in provider(profileFlags)) { + return true + } + } + return false + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/RemoteIds.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/RemoteIds.kt index 5fe0f26..0241e11 100644 --- a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/RemoteIds.kt +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/RemoteIds.kt
@@ -101,6 +101,60 @@ } /** + * Type-safe wrapper for a RemoteCompose operation ID (such as a bitmap or path ID) that may + * represent either a direct 16-bit static resource ID or a [PTR_DEREFERENCE]-flagged indirect + * pointer variable ID resolved dynamically at runtime. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +@JvmInline +public value class MaybeDereferencedId private constructor(public val raw: Int) { + /** Returns true if [raw] carries the [PTR_DEREFERENCE] indirection flag. */ + public val isDereferenced: Boolean + get() = (raw and PTR_DEREFERENCE) != 0 + + /** Returns the masked 16-bit ID (`raw and VALUE_MASK`), either direct or pointer variable. */ + public val unmaskedId: Int + get() = raw and VALUE_MASK + + /** + * Returns the direct static resource ID (`raw and VALUE_MASK`) if [isDereferenced] is false, or + * `null` otherwise. + */ + public val directId: Int? + get() = if (!isDereferenced) unmaskedId else null + + /** + * Returns the pointer variable ID (`raw and VALUE_MASK`) if [isDereferenced] is true, or `null` + * otherwise. + */ + public val pointerId: Int? + get() = if (isDereferenced) unmaskedId else null + + public companion object { + /** Bit flag matching `PaintOperation.PTR_DEREFERENCE` (`1 << 30`). */ + public const val PTR_DEREFERENCE: Int = IdEncoding.PTR_DEREFERENCE + + /** 16-bit payload mask matching `PaintOperation.VALUE_MASK` (`0xFFFF`). */ + public const val VALUE_MASK: Int = IdEncoding.VALUE_MASK + + /** + * Wraps a raw encoded wire integer [raw] verbatim, preserving any [PTR_DEREFERENCE] flag + * bit. + */ + @JvmStatic public fun fromRawInt(raw: Int): MaybeDereferencedId = MaybeDereferencedId(raw) + + /** Creates a [MaybeDereferencedId] representing a direct static 16-bit ID. */ + @JvmStatic + public fun direct(id: Int): MaybeDereferencedId = MaybeDereferencedId(id and VALUE_MASK) + + /** Creates a [MaybeDereferencedId] representing a dereferenced 16-bit pointer ID. */ + @JvmStatic + public fun dereferenced(pointerId: Int): MaybeDereferencedId = + MaybeDereferencedId((pointerId and VALUE_MASK) or PTR_DEREFERENCE) + } +} + +/** * Pure-Kotlin NaN-boxing and `Long`-encoded ID utilities matching `Utils` and `NanMap` in * `remote-core`. * @@ -108,12 +162,23 @@ */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public object NanEncoding { - /** Negative NaN prefix (`0xFF800000`) used for all NaN-boxed IDs and RPN tokens. */ + /** Negative NaN prefix (`0xFF800000`) used when encoding NaN-boxed IDs and RPN tokens. */ public const val NAN_PREFIX: Int = IdEncoding.NAN_PREFIX + /** + * IEEE-754 exponent mask (`0x7F800000`) used when decoding NaN-boxed IDs regardless of sign. + */ + public const val NAN_EXPONENT: Int = IdEncoding.NAN_EXPONENT + /** 22-bit payload mask (`0x003FFFFF`) matching `Utils.idFromNan`. */ public const val ID_MASK: Int = IdEncoding.PAYLOAD_MASK + /** Sentinel integer (`-1`) representing the absence of an ID. */ + public const val NO_ID: Int = IdEncoding.NO_ID + + /** 2-bit region mask (`0x00300000`) selecting the `NanMap` namespace. */ + public const val REGION_MASK: Int = IdEncoding.REGION_MASK + /** 20-bit sub-ID mask (`0x000FFFFF`) within a `NanMap` region. */ public const val REGION_SUB_ID_MASK: Int = IdEncoding.REGION_SUB_ID_MASK @@ -135,6 +200,12 @@ /** First user-allocated array/list/map ID (`NanMap.START_ARRAY = 0x20002A`). */ public const val START_ARRAY_ID: Int = IdEncoding.START_ARRAY_ID + /** First macro-local ID (`0x4000`) matching `Utils.isMacroLocal`. */ + public const val MACRO_LOCAL_START_ID: Int = IdEncoding.MACRO_LOCAL_START_ID + + /** Last macro-local ID (`0x4FFF`) matching `Utils.isMacroLocal`. */ + public const val MACRO_LOCAL_END_ID: Int = IdEncoding.MACRO_LOCAL_END_ID + /** Offset (`0x100000000L`) added to integer IDs when encoded in a 64-bit `Long` slot. */ public const val LONG_ID_OFFSET: Long = IdEncoding.LONG_ID_OFFSET @@ -144,29 +215,62 @@ } internal fun isNanBits(rawBits: Int): Boolean = - (rawBits and NAN_PREFIX) == NAN_PREFIX && (rawBits and ID_MASK) != 0 + (rawBits and NAN_EXPONENT) == NAN_EXPONENT && (rawBits and ID_MASK) != 0 internal fun idFromNanBits(rawBits: Int): Int = - if (isNanBits(rawBits)) rawBits and ID_MASK else -1 + if (isNanBits(rawBits)) rawBits and ID_MASK else NO_ID /** Encodes a 22-bit [id] (`1..0x3FFFFF`) into a NaN-boxed [Float]. */ @JvmStatic public fun asNan(id: Int): Float = Float.fromBits(asNanBits(id)) /** - * Returns true if [value] carries the RemoteCompose NaN-boxed ID prefix (`0xFF800000`) and a - * non-zero 22-bit ID payload (excluding negative infinity `0xFF800000` and negative quiet NaN - * `0xFFC00000`). + * Returns true if [value] is an IEEE-754 NaN (either sign bit) with a non-zero 22-bit ID + * payload (excluding infinities `0x7F800000` / `0xFF800000` and zero-payload quiet NaNs + * `0x7FC00000` / `0xFFC00000`). */ @JvmStatic public fun isNan(value: Float): Boolean = isNanBits(value.toRawBits()) + /** + * Returns true if [value] is an IEEE-754 `NaN` with zero 22-bit ID payload (such as canonical + * `Float.NaN` `0x7FC00000` or negative quiet NaN `0xFFC00000`) rather than a RemoteCompose + * NaN-boxed variable or operator ID. + */ + @JvmStatic public fun isNonIdFloatNan(value: Float): Boolean = value.isNaN() && !isNan(value) + /** Extracts the 22-bit payload ID from a NaN-boxed [value], or `-1` if [value] is literal. */ @JvmStatic public fun idFromNan(value: Float): Int = idFromNanBits(value.toRawBits()) + /** + * Extracts the 22-bit payload ID from a NaN-boxed [value], or `null` if [value] is numeric or a + * non-ID `NaN`. + */ + @JvmStatic + public fun decodeIdOrNull(value: Float): Int? { + val id = idFromNan(value) + return if (id == -1) null else id + } + + /** + * Returns true if [id] is a built-in Tier 1 system global ID (`0 until START_ID`, i.e. + * `0..41`). + */ + @JvmStatic public fun isSystemGlobalId(id: Int): Boolean = id in 0 until START_ID + + /** Returns true if [id] is a Tier 2 macro-local ID (`0x4000..0x4FFF`). */ + @JvmStatic + public fun isMacroLocalId(id: Int): Boolean = id in MACRO_LOCAL_START_ID..MACRO_LOCAL_END_ID + + /** + * Returns the `NanMap` region ([REGION_SYSTEM], [REGION_VARIABLE], [REGION_ARRAY], or + * [REGION_OPERATION]) containing [id], or `-1` if [id] is negative. + */ + @JvmStatic public fun idRegion(id: Int): Int = if (id < 0) -1 else id and REGION_MASK + /** Returns true if [value] is a NaN-boxed array/collection ID in [REGION_ARRAY]. */ @JvmStatic public fun isArrayNan(value: Float): Boolean { val id = idFromNan(value) - return id != -1 && (id and 0x300000) == REGION_ARRAY + return id != NO_ID && (id and REGION_MASK) == REGION_ARRAY } /** Encodes a 32-bit integer variable [id] into a `Long` (`id + 0x100000000L`). */ @@ -192,6 +296,14 @@ } return (encoded - LONG_ID_OFFSET).toInt() } + + /** + * Extracts the 32-bit integer variable ID from [encoded], or `null` if [encoded] is not a valid + * `Long`-encoded ID. + */ + @JvmStatic + public fun decodeLongIdOrNull(encoded: Long): Int? = + if (isLongId(encoded)) (encoded - LONG_ID_OFFSET).toInt() else null } /** @@ -199,7 +311,7 @@ */ @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public val MaybeVariableFloat.isArrayVariable: Boolean - get() = isVariable && (variableId and 0x300000) == NanEncoding.REGION_ARRAY + get() = isVariable && (variableId and NanEncoding.REGION_MASK) == NanEncoding.REGION_ARRAY /** Returns true if this [MaybeVariableFloat] encodes a float RPN operator token. */ @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/TextFromFloatFormatter.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/TextFromFloatFormatter.kt new file mode 100644 index 0000000..b2bb495 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/TextFromFloatFormatter.kt
@@ -0,0 +1,508 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document + +import androidx.annotation.RestrictTo +import java.util.Objects +import kotlin.math.min + +/** + * Decoded formatting specification for `TextFromFloatNode` matching `TextFromFloat` and + * `StringUtils` in `remote-core`. + * + * @property digitsBefore maximum number of integer digits (and grouping separators) before the + * decimal point (in `0..TextFromFloatFormatter.MAX_DIGITS`) + * @property digitsAfter maximum number of fractional digits after the decimal point (in + * `0..TextFromFloatFormatter.MAX_DIGITS`) + * @property padBefore decoded leading padding character ([TextFromFloatFormatter.PAD_NONE], + * [TextFromFloatFormatter.PAD_ZERO], or [TextFromFloatFormatter.PAD_SPACE]) + * @property padAfter decoded trailing padding character ([TextFromFloatFormatter.PAD_NONE], + * [TextFromFloatFormatter.PAD_ZERO], or [TextFromFloatFormatter.PAD_SPACE]) + * @property grouping decoded grouping mode (`TextFromFloatFormatter.GROUPING_*`, unshifted `0..3`) + * @property separator decoded separator style (`TextFromFloatFormatter.SEPARATOR_*`, unshifted + * `0..3`) + * @property isRounding whether half-up rounding is applied before digit extraction + * @property isNegativeParentheses whether negative numbers are wrapped in parentheses instead of a + * leading minus sign + * @property isLegacyMode whether legacy `StringUtils.floatToString` formatting is used + * @property isFullFormat whether raw [Float.toString] output is used directly + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class FloatFormatSpec( + public val digitsBefore: Int, + public val digitsAfter: Int, + public val padBefore: Char, + public val padAfter: Char, + public val grouping: Int, + public val separator: Int, + public val isRounding: Boolean, + public val isNegativeParentheses: Boolean, + public val isLegacyMode: Boolean, + public val isFullFormat: Boolean, +) { + init { + require(digitsBefore in 0..TextFromFloatFormatter.MAX_DIGITS) { + "digitsBefore must be in 0..${TextFromFloatFormatter.MAX_DIGITS}, was $digitsBefore" + } + require(digitsAfter in 0..TextFromFloatFormatter.MAX_DIGITS) { + "digitsAfter must be in 0..${TextFromFloatFormatter.MAX_DIGITS}, was $digitsAfter" + } + } + + override fun equals(other: Any?): Boolean = + other is FloatFormatSpec && + digitsBefore == other.digitsBefore && + digitsAfter == other.digitsAfter && + padBefore == other.padBefore && + padAfter == other.padAfter && + grouping == other.grouping && + separator == other.separator && + isRounding == other.isRounding && + isNegativeParentheses == other.isNegativeParentheses && + isLegacyMode == other.isLegacyMode && + isFullFormat == other.isFullFormat + + override fun hashCode(): Int = + Objects.hash( + digitsBefore, + digitsAfter, + padBefore, + padAfter, + grouping, + separator, + isRounding, + isNegativeParentheses, + isLegacyMode, + isFullFormat, + ) + + override fun toString(): String = + "FloatFormatSpec(digitsBefore=$digitsBefore, digitsAfter=$digitsAfter, " + + "padBefore=${padBefore.code}, padAfter=${padAfter.code}, grouping=$grouping, " + + "separator=$separator, isRounding=$isRounding, " + + "isNegativeParentheses=$isNegativeParentheses, isLegacyMode=$isLegacyMode, " + + "isFullFormat=$isFullFormat)" +} + +/** + * Pure-Kotlin port of `TextFromFloat` flag decoding and `StringUtils.floatToString` matching + * `remote-core` bit-for-bit. + * + * Note: The `GROUPING_*`, `SEPARATOR_*`, and `PAD_*` constants on this object represent **decoded, + * unshifted** values stored on [FloatFormatSpec]. Do **not** pass them directly into + * `TextFromFloatNode.flags`; use the shifted bitfield constants on [TextFromFloatFlags] instead. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public object TextFromFloatFormatter { + /** + * Maximum allowed value for `digitsBefore` and `digitsAfter`, guarding against excessive + * padding allocations and unbounded power-of-10 loops on untrusted wire inputs. + */ + public const val MAX_DIGITS: Int = 256 + + /** + * Decoded grouping mode (`0`): no grouping separators. Do not pass into [TextFromFloatFlags]. + */ + public const val GROUPING_NONE: Int = 0 + + /** Decoded grouping mode (`1`): group by 3 digits. Do not pass into [TextFromFloatFlags]. */ + public const val GROUPING_BY3: Int = 1 + + /** Decoded grouping mode (`2`): group by 4 digits. Do not pass into [TextFromFloatFlags]. */ + public const val GROUPING_BY4: Int = 2 + + /** + * Decoded grouping mode (`3`): Indian 3-then-2 grouping. Do not pass into [TextFromFloatFlags]. + */ + public const val GROUPING_BY32: Int = 3 + + /** + * Decoded separator (`0`): comma grouping, period decimal. Do not pass into + * [TextFromFloatFlags]. + */ + public const val SEPARATOR_COMMA_PERIOD: Int = 0 + + /** + * Decoded separator (`1`): period grouping, comma decimal. Do not pass into + * [TextFromFloatFlags]. + */ + public const val SEPARATOR_PERIOD_COMMA: Int = 1 + + /** + * Decoded separator (`2`): space grouping, comma decimal. Do not pass into + * [TextFromFloatFlags]. + */ + public const val SEPARATOR_SPACE_COMMA: Int = 2 + + /** + * Decoded separator (`3`): underscore grouping, period decimal. Do not pass into + * [TextFromFloatFlags]. + */ + public const val SEPARATOR_UNDER_PERIOD: Int = 3 + + /** Decoded padding character (`\u0000`): omit padding. */ + public const val PAD_NONE: Char = '\u0000' + + /** Decoded padding character (`'0'`): pad with zeros. */ + public const val PAD_ZERO: Char = '0' + + /** Decoded padding character (`' '`): pad with spaces. */ + public const val PAD_SPACE: Char = ' ' + + /** + * Decodes [digitsBefore], [digitsAfter], and [TextFromFloatFlags] bitfield [flags] into a + * [FloatFormatSpec]. + * + * @throws IllegalArgumentException if [digitsBefore] or [digitsAfter] is outside + * `0..MAX_DIGITS` + */ + @JvmStatic + public fun parseSpec(digitsBefore: Int, digitsAfter: Int, flags: Int): FloatFormatSpec { + require(digitsBefore in 0..MAX_DIGITS) { + "digitsBefore must be in 0..$MAX_DIGITS, was $digitsBefore" + } + require(digitsAfter in 0..MAX_DIGITS) { + "digitsAfter must be in 0..$MAX_DIGITS, was $digitsAfter" + } + val padAfter = + when (flags and 3) { + TextFromFloatFlags.PAD_AFTER_SPACE -> PAD_SPACE + TextFromFloatFlags.PAD_AFTER_NONE -> PAD_NONE + TextFromFloatFlags.PAD_AFTER_ZERO -> PAD_ZERO + else -> PAD_SPACE + } + val padBefore = + when (flags and (3 shl 2)) { + TextFromFloatFlags.PAD_PRE_SPACE -> PAD_SPACE + TextFromFloatFlags.PAD_PRE_NONE -> PAD_NONE + TextFromFloatFlags.PAD_PRE_ZERO -> PAD_ZERO + else -> PAD_SPACE + } + val grouping = + when (flags and (3 shl 4)) { + TextFromFloatFlags.GROUPING_BY3 -> GROUPING_BY3 + TextFromFloatFlags.GROUPING_BY4 -> GROUPING_BY4 + TextFromFloatFlags.GROUPING_BY32 -> GROUPING_BY32 + else -> GROUPING_NONE + } + val separator = + when (flags and (3 shl 6)) { + TextFromFloatFlags.SEPARATOR_PERIOD_COMMA -> SEPARATOR_PERIOD_COMMA + TextFromFloatFlags.SEPARATOR_COMMA_PERIOD -> SEPARATOR_COMMA_PERIOD + TextFromFloatFlags.SEPARATOR_SPACE_COMMA -> SEPARATOR_SPACE_COMMA + else -> SEPARATOR_UNDER_PERIOD + } + val isRounding = (flags and TextFromFloatFlags.OPTIONS_ROUNDING) != 0 + val isNegativeParentheses = (flags and TextFromFloatFlags.OPTIONS_NEGATIVE_PARENTHESES) != 0 + val isLegacyMode = (flags and TextFromFloatFlags.LEGACY_MODE) != 0 + val isFullFormat = (flags and TextFromFloatFlags.FULL_FORMAT) != 0 + return FloatFormatSpec( + digitsBefore = digitsBefore, + digitsAfter = digitsAfter, + padBefore = padBefore, + padAfter = padAfter, + grouping = grouping, + separator = separator, + isRounding = isRounding, + isNegativeParentheses = isNegativeParentheses, + isLegacyMode = isLegacyMode, + isFullFormat = isFullFormat, + ) + } + + /** Formats [value] according to [digitsBefore], [digitsAfter], and [flags]. */ + @JvmStatic + public fun format(value: Float, digitsBefore: Int, digitsAfter: Int, flags: Int): String = + format(value, parseSpec(digitsBefore, digitsAfter, flags)) + + /** Formats [value] according to a parsed [FloatFormatSpec]. */ + @JvmStatic + public fun format(value: Float, spec: FloatFormatSpec): String { + if (spec.isFullFormat) { + return value.toString() + } + return if (spec.isLegacyMode) { + formatLegacy(value, spec.digitsBefore, spec.digitsAfter, spec.padBefore, spec.padAfter) + } else { + formatModern( + rawValue = value, + beforeDecimalPoint = spec.digitsBefore, + afterDecimalPoint = spec.digitsAfter, + pre = spec.padBefore, + post = spec.padAfter, + separator = spec.separator, + grouping = spec.grouping, + rounding = spec.isRounding, + useParenthesesForNeg = spec.isNegativeParentheses, + ) + } + } + + private fun formatLegacy( + rawValue: Float, + beforeDecimalPoint: Int, + afterDecimalPoint: Int, + pre: Char, + post: Char, + ): String { + val isNeg = rawValue < 0f + val value = if (isNeg) -rawValue else rawValue + val integerPart = value.toInt() + var fractionalPart = value % 1f + + var integerPartString = integerPart.toString() + val iLen = integerPartString.length + if (iLen < beforeDecimalPoint) { + val spacesToPad = beforeDecimalPoint - iLen + if (pre != PAD_NONE) { + integerPartString = + CharArray(spacesToPad) { pre }.concatToString() + integerPartString + } + } else if (iLen > beforeDecimalPoint) { + integerPartString = integerPartString.substring(iLen - beforeDecimalPoint) + } + if (afterDecimalPoint == 0) { + return (if (isNeg) "-" else "") + integerPartString + } + + repeat(afterDecimalPoint) { fractionalPart *= 10f } + fractionalPart = Math.round(fractionalPart).toFloat() + repeat(afterDecimalPoint) { fractionalPart *= 0.1f } + + var fact = fractionalPart.toString() + fact = fact.substring(2, min(fact.length, afterDecimalPoint + 2)) + var trim = fact.length + for (i in fact.length - 1 downTo 0) { + if (fact[i] != '0') break + trim-- + } + if (trim != fact.length) { + fact = fact.substring(0, trim) + } + val len = fact.length + if (post != PAD_NONE && len < afterDecimalPoint) { + fact += CharArray(afterDecimalPoint - len) { post }.concatToString() + } + return (if (isNeg) "-" else "") + integerPartString + "." + fact + } + + private fun formatModern( + rawValue: Float, + beforeDecimalPoint: Int, + afterDecimalPoint: Int, + pre: Char, + post: Char, + separator: Int, + grouping: Int, + rounding: Boolean, + useParenthesesForNeg: Boolean, + ): String { + val groupSep: Char + val decSep: Char + when (separator) { + SEPARATOR_PERIOD_COMMA -> { + groupSep = '.' + decSep = ',' + } + SEPARATOR_SPACE_COMMA -> { + groupSep = ' ' + decSep = ',' + } + SEPARATOR_UNDER_PERIOD -> { + groupSep = '_' + decSep = '.' + } + else -> { + groupSep = ',' + decSep = '.' + } + } + val isNeg = rawValue < 0f + val value = if (isNeg) -rawValue else rawValue + val chars = toChars(value, beforeDecimalPoint, afterDecimalPoint, rounding) + val str = chars.concatToString() + var fractionalPart = value % 1f + + var integerPartString = str.substring(0, str.indexOf('.')) + if (grouping != GROUPING_NONE) { + val len = integerPartString.length + when (grouping) { + GROUPING_BY3 -> { + var i = len - 3 + while (i > 0) { + integerPartString = + integerPartString.substring(0, i) + + groupSep + + integerPartString.substring(i) + i -= 3 + } + } + GROUPING_BY4 -> { + var i = len - 4 + while (i > 0) { + integerPartString = + integerPartString.substring(0, i) + + groupSep + + integerPartString.substring(i) + i -= 4 + } + } + GROUPING_BY32 -> { + var i = len - 3 + while (i > 0) { + integerPartString = + integerPartString.substring(0, i) + + groupSep + + integerPartString.substring(i) + i -= 2 + } + } + } + } + val iLen = integerPartString.length + if (iLen < beforeDecimalPoint) { + val spacesToPad = beforeDecimalPoint - iLen + if (pre != PAD_NONE) { + integerPartString = + CharArray(spacesToPad) { pre }.concatToString() + integerPartString + } + } else if (iLen > beforeDecimalPoint) { + integerPartString = integerPartString.substring(iLen - beforeDecimalPoint) + } + var effectiveAfter = afterDecimalPoint + var trimAfter = effectiveAfter + if (iLen + effectiveAfter > 9) { + trimAfter = maxOf(1, 9 - iLen) + } + if (post == PAD_NONE) { + effectiveAfter = trimAfter + } + + if (effectiveAfter == 0) { + if (!isNeg) return integerPartString + return if (useParenthesesForNeg) "($integerPartString)" else "-$integerPartString" + } + + repeat(trimAfter) { fractionalPart *= 10f } + fractionalPart = Math.round(fractionalPart).toFloat() + repeat(trimAfter) { fractionalPart *= 0.1f } + + var fact = fractionalPart.toString() + fact = fact.substring(2, min(fact.length, effectiveAfter + 2)) + var trim = fact.length + for (i in fact.length - 1 downTo 1) { + if (fact[i] != '0') break + trim-- + } + if (trim != fact.length) { + fact = fact.substring(0, trim) + } + val len = fact.length + if (post != PAD_NONE && len < effectiveAfter) { + fact += CharArray(effectiveAfter - len) { post }.concatToString() + } + if (!isNeg) return "$integerPartString$decSep$fact" + return if (useParenthesesForNeg) { + "($integerPartString$decSep$fact)" + } else { + "-$integerPartString$decSep$fact" + } + } + + private fun toChars( + rawValue: Float, + beforeDecimalPoint: Int, + afterDecimalPoint: Int, + rounding: Boolean, + ): CharArray { + val isNegative = rawValue < 0f + var value = if (isNegative) -rawValue else rawValue + + var powerOf10 = 1L + repeat(afterDecimalPoint) { powerOf10 *= 10L } + + if (rounding) { + var roundingFactor = 0.5f + repeat(afterDecimalPoint) { roundingFactor /= 10.0f } + value += roundingFactor + } + + val integerPart = value.toLong() + val fractionalPart = value - integerPart + + var intLength = 1 + if (integerPart > 0L) { + var tempInt = integerPart + intLength = 0 + while (tempInt > 0L) { + tempInt /= 10L + intLength++ + } + } + val actualBefore = min(beforeDecimalPoint, intLength) + + val integerChars = CharArray(actualBefore) + var tempInt = integerPart + for (i in actualBefore - 1 downTo 0) { + integerChars[i] = ('0'.code + (tempInt % 10L).toInt()).toChar() + tempInt /= 10L + } + + var tempFrac = (fractionalPart * powerOf10).toLong() + var fracLength = 0 + if (afterDecimalPoint > 0) { + var temp = tempFrac + if (temp == 0L) { + fracLength = 1 + } else { + while (temp > 0L && temp % 10L == 0L) { + temp /= 10L + } + if (temp > 0L) { + var t = temp + while (t > 0L) { + t /= 10L + fracLength++ + } + } + } + } + + val actualAfter = min(afterDecimalPoint, fracLength) + val fractionalChars = CharArray(actualAfter) + tempFrac = (fractionalPart * powerOf10).toLong() + for (i in actualAfter - 1 downTo 0) { + fractionalChars[i] = ('0'.code + (tempFrac % 10L).toInt()).toChar() + tempFrac /= 10L + } + + val totalLength = (if (isNegative) 1 else 0) + actualBefore + 1 + actualAfter + val result = CharArray(totalLength) + var currentIndex = 0 + if (isNegative) { + result[currentIndex++] = '-' + } + for (i in 0 until actualBefore) { + result[currentIndex++] = integerChars[i] + } + result[currentIndex++] = '.' + for (i in 0 until actualAfter) { + result[currentIndex++] = fractionalChars[i] + } + return result + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/FloatAnimationBounds.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/FloatAnimationBounds.kt new file mode 100644 index 0000000..3f8e5e6 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/FloatAnimationBounds.kt
@@ -0,0 +1,397 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.document.AnimationEasing +import androidx.compose.remote.document.isSpringAnimationSpec +import androidx.compose.remote.document.unpackAnimationSpec +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.math.nextDown +import kotlin.math.nextUp +import kotlin.math.sqrt +import kotlin.math.ulp +import kotlin.math.withSign + +/** + * Unpacked finite progress range and optional initial value extracted from a packed RemoteCompose + * `FloatAnimation` description array. + * + * @property progressRange Sound range of the easing curve over normalized time `[0, 1]`. + * @property initialValue Optional finite initial animation value, or `null` if unspecified. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class ParsedAnimationSpec( + public val progressRange: FloatInterval, + public val initialValue: Float?, +) { + override fun equals(other: Any?): Boolean = + other is ParsedAnimationSpec && + progressRange == other.progressRange && + canonicalNullableFloatBits(initialValue) == + canonicalNullableFloatBits(other.initialValue) + + override fun hashCode(): Int { + var result = progressRange.hashCode() + result = 31 * result + (canonicalNullableFloatBits(initialValue) ?: 0) + return result + } + + override fun toString(): String = + "ParsedAnimationSpec(progressRange=$progressRange, initialValue=$initialValue)" + + private companion object { + private fun canonicalNullableFloatBits(value: Float?): Int? = + when { + value == null -> null + value == 0f -> 0 + value.isNaN() -> Float.NaN.toBits() + else -> value.toBits() + } + } +} + +/** + * Pure-Kotlin sound interval bounds for RemoteCompose float animations and CSS cubic-bezier easing + * curves, matching `FloatAnimation` and `CubicEasing` in `remote-core`. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public object FloatAnimationBounds { + private const val QUADRATIC_EPS = 1e-12 + private const val CUBIC_OVERSHOOT_ROUNDING_TOL = 1e-5 + private const val CUBIC_EASING_ERROR = 0.01f + + /** + * Returns `true` when [spec] requires conservative fallback to [FloatInterval.UNBOUNDED] (such + * as spring, wrap, elastic/spline, non-positive duration, or non-monotonic cubic `x1`/`x2`). + */ + @JvmStatic + public fun isConservativelyTaintedAnimation(spec: FloatArray): Boolean = + parseAnimationSpec(spec) == null + + /** + * Unpacks [spec] into its progress range and optional initial value, or returns `null` when + * conservative fallback to [FloatInterval.UNBOUNDED] is required. + */ + @JvmStatic + public fun parseAnimationSpec(spec: FloatArray): ParsedAnimationSpec? { + if (isSpringAnimationSpec(spec)) return null + if (spec.isNotEmpty() && (!spec[0].isFinite() || spec[0] <= 0f)) return null + if (spec.size <= 1) { + return ParsedAnimationSpec(progressRange = FloatInterval.UNIT, initialValue = null) + } + + val unpacked = + try { + unpackAnimationSpec(spec) + } catch (_: IllegalArgumentException) { + return null + } + if (!unpacked.wrap.isNaN()) return null + val initialValue = + if (!unpacked.initialValue.isNaN()) { + if (unpacked.initialValue.isInfinite()) return null + unpacked.initialValue + } else { + null + } + val pRange = progressRangeForEasingType(unpacked.type, unpacked.params) ?: return null + return ParsedAnimationSpec(progressRange = pRange, initialValue = initialValue) + } + + /** + * Computes a sound interval bound for an animated float expression with packed [spec] and + * statically bounded [targetInterval]. + */ + @JvmStatic + public fun boundAnimatedFloat( + spec: FloatArray, + targetInterval: FloatInterval, + ): FloatInterval { + val parsed = parseAnimationSpec(spec) ?: return FloatInterval.UNBOUNDED + if (targetInterval.isEmpty) return FloatInterval.EMPTY + if (targetInterval.isUnbounded) return FloatInterval.UNBOUNDED + + val startInterval = + parsed.initialValue?.let { targetInterval.union(FloatInterval.point(it)) } + ?: targetInterval + return interpolateBox(startInterval, targetInterval, parsed.progressRange) + } + + /** + * Evaluates `CubicEasing(x1, y1, x2, y2).get(x)` in pure Kotlin matching `remote-core` + * bit-for-bit. + */ + @JvmStatic + public fun evaluateCubicEasing(x1: Float, y1: Float, x2: Float, y2: Float, x: Float): Float { + if (x <= 0.0f) return 0f + if (x >= 1.0f) return 1.0f + var t = 0.5f + var range = 0.5f + while (range > CUBIC_EASING_ERROR) { + val tx = bezierCoord(x1, x2, t) + range *= 0.5f + if (tx < x) { + t += range + } else { + t -= range + } + } + val bx1 = bezierCoord(x1, x2, t - range) + val bx2 = bezierCoord(x1, x2, t + range) + val by1 = bezierCoord(y1, y2, t - range) + val by2 = bezierCoord(y1, y2, t + range) + return (by2 - by1) * (x - bx1) / (bx2 - bx1) + by1 + } + + /** + * Soundly bounds `CubicEasing(x1, y1, x2, y2).get(pos)` matching + * `AnimatedFloatExpression.CUBIC`. + */ + @JvmStatic + public fun evalCubicEasingInterval( + x1: FloatInterval, + y1: FloatInterval, + x2: FloatInterval, + y2: FloatInterval, + pos: FloatInterval, + ): FloatInterval { + if (x1.isEmpty || y1.isEmpty || x2.isEmpty || y2.isEmpty || pos.isEmpty) { + return FloatInterval.EMPTY + } + if (x1.isUnbounded || y1.isUnbounded || x2.isUnbounded || y2.isUnbounded) { + return FloatInterval.UNBOUNDED + } + if (x1.min < 0f || x1.max > 1f || x2.min < 0f || x2.max > 1f) { + return FloatInterval.UNBOUNDED + } + if (pos.max <= 0f) return FloatInterval.ZERO + if (pos.min >= 1f) return FloatInterval.point(1f) + + if (x1.isPoint && y1.isPoint && x2.isPoint && y2.isPoint) { + if (pos.isPoint) { + val exact = evaluateCubicEasing(x1.min, y1.min, x2.min, y2.min, pos.min) + return if (exact.isFinite()) FloatInterval.point(exact) else FloatInterval.UNBOUNDED + } else if (y1.min in 0f..1f && y2.min in 0f..1f) { + val lo = evaluateCubicEasing(x1.min, y1.min, x2.min, y2.min, pos.min) + val hi = evaluateCubicEasing(x1.min, y1.min, x2.min, y2.min, pos.max) + if (!lo.isFinite() || !hi.isFinite()) return FloatInterval.UNBOUNDED + val minOut = if (lo <= 0f) 0f else max(0f, min(lo, hi).nextDown()) + val maxOut = if (hi >= 1f) 1f else min(1f, max(lo, hi).nextUp()) + return FloatInterval(minOut, maxOut) + } + } + + val loBounds = cubicBezierYBounds(y1.min, y2.min) + val hiBounds = cubicBezierYBounds(y1.max, y2.max) + return FloatInterval(min(loBounds.min, hiBounds.min), max(loBounds.max, hiBounds.max)) + } + + /** + * Soundly bounds the y-coordinate of cubic Bezier `(0, 0) -> (x1, y1) -> (x2, y2) -> (1, 1)` + * over `t in [0, 1]` using closed-form derivative roots. + */ + @JvmStatic + public fun cubicBezierYBounds(y1: Float, y2: Float): FloatInterval { + if (!y1.isFinite() || !y2.isFinite()) return FloatInterval.UNBOUNDED + if (y1 in 0f..1f && y2 in 0f..1f) return FloatInterval.UNIT + + val dy1 = y1.toDouble() + val dy2 = y2.toDouble() + var lo = 0.0 + var hi = 1.0 + + val a = 3.0 * dy1 - 3.0 * dy2 + 1.0 + val b = 2.0 * (dy2 - 2.0 * dy1) + val c = dy1 + + fun checkRoot(t: Double) { + if (t <= 0.0 || t >= 1.0) return + val t1 = 1.0 - t + val y = 3.0 * t1 * t1 * t * dy1 + 3.0 * t1 * t * t * dy2 + t * t * t + if (y < lo) lo = y + if (y > hi) hi = y + } + + if (abs(a) < QUADRATIC_EPS) { + if (abs(b) > QUADRATIC_EPS) checkRoot(-c / b) + } else { + val disc = b * b - 4.0 * a * c + if (disc >= 0.0) { + val root = sqrt(disc) + // Citardauq stable root formula avoids catastrophic cancellation when b^2 >> 4ac. + val q = -0.5 * (b + root.withSign(b)) + if (q != 0.0) { + checkRoot(q / a) + checkRoot(c / q) + } + } + } + + val paddedLo = if (lo < 0.0) lo - CUBIC_OVERSHOOT_ROUNDING_TOL * max(1.0, abs(lo)) else lo + val paddedHi = + if (hi > 1.0 || dy1 < 0.0 || dy2 < 0.0) { + hi + CUBIC_OVERSHOOT_ROUNDING_TOL * max(1.0, max(abs(hi), abs(lo))) + } else { + hi + } + val fLo = paddedLo.toFloat().let { if (it.toDouble() > paddedLo) it.nextDown() else it } + val fHi = paddedHi.toFloat().let { if (it.toDouble() < paddedHi) it.nextUp() else it } + if (!fLo.isFinite() || !fHi.isFinite()) return FloatInterval.UNBOUNDED + return FloatInterval(fLo, fHi) + } + + private fun bezierCoord(c1: Float, c2: Float, t: Float): Float { + val t1 = 1f - t + val f1 = 3f * t1 * t1 * t + val f2 = 3f * t1 * t * t + val f3 = t * t * t + return c1 * f1 + c2 * f2 + f3 + } + + private fun progressRangeForEasingType(type: Int, params: FloatArray): FloatInterval? { + return when (type) { + AnimationEasing.CUBIC_STANDARD, + AnimationEasing.CUBIC_ACCELERATE, + AnimationEasing.CUBIC_DECELERATE, + AnimationEasing.CUBIC_LINEAR, + AnimationEasing.EASE_OUT_BOUNCE -> FloatInterval.UNIT + AnimationEasing.CUBIC_ANTICIPATE, + AnimationEasing.CUBIC_OVERSHOOT -> { + val pts = AnimationEasing.cubicControlPoints(type) ?: return null + cubicBezierYBounds(pts[1], pts[3]) + } + AnimationEasing.CUBIC_CUSTOM -> { + if (params.size < 4) return null + val x1 = params[0] + val y1 = params[1] + val x2 = params[2] + val y2 = params[3] + if (x1 !in 0f..1f || x2 !in 0f..1f || !y1.isFinite() || !y2.isFinite()) return null + if (y1 in 0f..1f && y2 in 0f..1f) FloatInterval.UNIT else cubicBezierYBounds(y1, y2) + } + else -> null + } + } + + private fun interpolateBox( + start: FloatInterval, + target: FloatInterval, + progress: FloatInterval, + ): FloatInterval { + if (start.isPoint && target.isPoint && progress.isPoint) { + val fVal = progress.min * (target.min - start.min) + start.min + return if (fVal.isFinite()) FloatInterval(fVal, fVal) else FloatInterval.UNBOUNDED + } + if ( + start.isPoint && + target.isPoint && + start.min == target.min && + progress.min.isFinite() && + progress.max.isFinite() + ) { + return FloatInterval(start.min, start.min) + } + + // Exact real-valued hull over the trilinear box s + p * (t - s) in Double. + val sVals = floatArrayOf(start.min, start.max) + val tVals = floatArrayOf(target.min, target.max) + val pVals = floatArrayOf(progress.min, progress.max) + var loD = Double.POSITIVE_INFINITY + var hiD = Double.NEGATIVE_INFINITY + for (s in sVals) { + for (t in tVals) { + for (p in pVals) { + val dVal = s.toDouble() + p.toDouble() * (t.toDouble() - s.toDouble()) + if (!dVal.isFinite()) return FloatInterval.UNBOUNDED + if (dVal < loD) loD = dVal + if (dVal > hiD) hiD = dVal + } + } + } + + // Sterbenz's Lemma: if all s, t share a strict sign and max(|s|, |t|) <= 2 * min(|s|, |t|), + // then d = fl(t - s) is exact in IEEE-754 binary32. Combined with p in [0, 1], rounding + // monotonicity guarantees fl(fl(p * d) + s) lies inside [min(s, t), max(s, t)]. + val sterbenz = + (start.min > 0f && + target.min > 0f && + max(start.max.toDouble(), target.max.toDouble()) <= + 2.0 * min(start.min.toDouble(), target.min.toDouble())) || + (start.max < 0f && + target.max < 0f && + max(-start.min.toDouble(), -target.min.toDouble()) <= + 2.0 * min(-start.max.toDouble(), -target.max.toDouble())) + val unitProgress = progress.min >= 0f && progress.max <= 1f + if (sterbenz && unitProgress) { + return FloatInterval(min(start.min, target.min), max(start.max, target.max)) + } + + // Bound worst-case IEEE-754 binary32 rounding error across the three operations: + // d = fl(t - s), m = fl(p * d), r = fl(m + s). + val floatMaxD = Float.MAX_VALUE.toDouble() + val dLo = target.min.toDouble() - start.max.toDouble() + val dHi = target.max.toDouble() - start.min.toDouble() + val maxAbsD = max(abs(dLo), abs(dHi)) + if (!maxAbsD.isFinite() || maxAbsD > floatMaxD) return FloatInterval.UNBOUNDED + val e1 = + if (sterbenz || maxAbsD == 0.0) { + 0.0 + } else { + val maxDF = + maxAbsD.toFloat().let { if (it.toDouble() < maxAbsD) it.nextUp() else it } + if (!maxDF.isFinite()) return FloatInterval.UNBOUNDED + 0.5 * maxDF.ulp.toDouble() + } + val dMax = (maxAbsD + e1).nextUp() + if (!dMax.isFinite() || dMax > floatMaxD) return FloatInterval.UNBOUNDED + + val maxP = max(abs(progress.min.toDouble()), abs(progress.max.toDouble())) + val prodMax = (maxP * dMax).nextUp() + if (!prodMax.isFinite() || prodMax > floatMaxD) return FloatInterval.UNBOUNDED + val prodMaxF = prodMax.toFloat().let { if (it.toDouble() < prodMax) it.nextUp() else it } + if (!prodMaxF.isFinite()) return FloatInterval.UNBOUNDED + val mulRoundErr = 0.5 * prodMaxF.ulp.toDouble() + val e2 = (maxP * e1 + mulRoundErr).nextUp() + val mMax = (prodMax + mulRoundErr).nextUp() + if (!mMax.isFinite() || mMax > floatMaxD) return FloatInterval.UNBOUNDED + + val maxS = max(abs(start.min.toDouble()), abs(start.max.toDouble())) + val sumMax = (mMax + maxS).nextUp() + if (!sumMax.isFinite() || sumMax > floatMaxD) return FloatInterval.UNBOUNDED + val sumMaxF = sumMax.toFloat().let { if (it.toDouble() < sumMax) it.nextUp() else it } + if (!sumMaxF.isFinite()) return FloatInterval.UNBOUNDED + // Include 4 * sumMax.ulp to soundly cover any Double rounding in loD/hiD. + val e3 = (e2 + 0.5 * sumMaxF.ulp.toDouble() + 4.0 * sumMax.ulp).nextUp() + + val rawLo = (loD - e3).nextDown() + val rawHi = (hiD + e3).nextUp() + var outLo = rawLo.toFloat().let { if (it.toDouble() > rawLo) it.nextDown() else it } + var outHi = rawHi.toFloat().let { if (it.toDouble() < rawHi) it.nextUp() else it } + if (!outLo.isFinite() || !outHi.isFinite()) return FloatInterval.UNBOUNDED + + // When p in [0, 1] and s, t >= 0 (resp. <= 0) without overflow, rounding monotonicity + // guarantees fl(fl(p * fl(t - s)) + s) >= 0f (resp. <= 0f). + if (unitProgress) { + if (start.min >= 0f && target.min >= 0f) outLo = max(outLo, 0f) + if (start.max <= 0f && target.max <= 0f) outHi = min(outHi, 0f) + } + return FloatInterval(outLo, outHi) + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/FloatInterval.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/FloatInterval.kt new file mode 100644 index 0000000..d7a9045 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/FloatInterval.kt
@@ -0,0 +1,613 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.annotation.RestrictTo +import kotlin.math.PI +import kotlin.math.ceil +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min +import kotlin.math.nextDown +import kotlin.math.nextUp +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * An immutable extended-real interval between [min] and [max] with configurable open or closed + * endpoint inclusivity, representing a conservative bounding range guaranteed to contain every + * non-`NaN` RemoteCompose float value reachable at runtime. + * + * Models the non-`NaN` extended real line `[-Infinity, +Infinity]` so IEEE-754 float overflow or + * division by zero that yields infinities remains contained in [UNBOUNDED]; `NaN` is never a member + * of any interval, and operations that may produce `NaN` widen to [UNBOUNDED]. Implements interval + * arithmetic for expressions involving time, periodic waveforms, remainder, trigonometry, rounding, + * and three-valued relational comparisons. + * + * @property min The infimum (lower bound) of this interval, or [Float.NEGATIVE_INFINITY] if + * unbounded below. + * @property max The supremum (upper bound) of this interval, or [Float.POSITIVE_INFINITY] if + * unbounded above. + * @property minInclusive Whether [min] itself is included (`true` for `[`, `false` for `(`). + * @property maxInclusive Whether [max] itself is included (`true` for `]`, `false` for `)`). + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class FloatInterval +@JvmOverloads +constructor( + public val min: Float, + public val max: Float, + public val minInclusive: Boolean = true, + public val maxInclusive: Boolean = true, +) { + /** + * Whether this non-empty interval has at least one infinite endpoint ([Float.NEGATIVE_INFINITY] + * or [Float.POSITIVE_INFINITY]). + */ + public val isUnbounded: Boolean + get() = !isEmpty && (min.isInfinite() || max.isInfinite()) + + /** + * Whether this interval contains no real values (for example, `min > max`, either bound is + * `NaN`, or `min == max` with at least one open endpoint). + */ + public val isEmpty: Boolean + get() = + min.isNaN() || + max.isNaN() || + min > max || + (min == max && (!minInclusive || !maxInclusive)) + + /** Whether this interval represents a single finite constant value `[v, v]`. */ + public val isPoint: Boolean + get() = !isEmpty && !isUnbounded && min == max && minInclusive && maxInclusive + + /** + * Returns an interval soundly bounding `a + b` for all `a in this` and `b in other`, or [EMPTY] + * if either operand is empty. Computed bounds are closed because IEEE-754 rounding can map + * interior values onto a rounded endpoint. + */ + public operator fun plus(other: FloatInterval): FloatInterval { + if (isEmpty || other.isEmpty) return EMPTY + val newMin = min + other.min + val newMax = max + other.max + if (newMin.isNaN() || newMax.isNaN()) return UNBOUNDED + return FloatInterval(newMin, newMax) + } + + /** + * Returns an interval soundly bounding `a - b` for all `a in this` and `b in other`, or [EMPTY] + * if either operand is empty. Computed bounds are closed because IEEE-754 rounding can map + * interior values onto a rounded endpoint. + */ + public operator fun minus(other: FloatInterval): FloatInterval { + if (isEmpty || other.isEmpty) return EMPTY + val newMin = min - other.max + val newMax = max - other.min + if (newMin.isNaN() || newMax.isNaN()) return UNBOUNDED + return FloatInterval(newMin, newMax) + } + + /** + * Returns an interval soundly bounding `a * b` for all `a in this` and `b in other`, or [EMPTY] + * if either operand is empty. + * + * Singleton [ZERO] absorbs any non-empty interval to [ZERO] (preserving axis independence in + * affine expressions when multiplying a zero matrix entry by an unbounded coordinate); + * indeterminate corner products from non-point intervals containing `0f` and infinity widen + * soundly to [UNBOUNDED]. + */ + public operator fun times(other: FloatInterval): FloatInterval { + if (isEmpty || other.isEmpty) return EMPTY + if ((isPoint && min == 0f) || (other.isPoint && other.min == 0f)) return ZERO + if (isPoint && other.isPoint) { + val product = min * other.min + return if (product.isNaN()) UNBOUNDED else FloatInterval(product, product) + } + return combineCornerBounds( + min * other.min, + min * other.max, + max * other.min, + max * other.max, + ) + } + + /** + * Returns an interval soundly bounding `a / b` for all `a in this` and `b in other`, or [EMPTY] + * if either operand is empty. Widens soundly to [UNBOUNDED] if [other] contains `0f` or + * produces indeterminate bounds. + */ + public operator fun div(other: FloatInterval): FloatInterval { + if (isEmpty || other.isEmpty) return EMPTY + if (other.min <= 0f && other.max >= 0f) return UNBOUNDED + return combineCornerBounds( + min / other.min, + min / other.max, + max / other.min, + max / other.max, + ) + } + + /** + * Returns an interval soundly bounding `-a` for all `a in this`, or [EMPTY] if this interval is + * empty. + */ + public operator fun unaryMinus(): FloatInterval { + if (isEmpty) return EMPTY + return FloatInterval(-max, -min, minInclusive = maxInclusive, maxInclusive = minInclusive) + } + + /** + * Returns an interval soundly bounding `|a|` for all `a in this`, or [EMPTY] if this interval + * is empty. + */ + public fun abs(): FloatInterval { + if (isEmpty) return EMPTY + return when { + min >= 0f -> this + max <= 0f -> + FloatInterval(-max, -min, minInclusive = maxInclusive, maxInclusive = minInclusive) + else -> { + val negMin = -min + val outMax = max(negMin, max) + val outMaxInc = + when { + negMin > max -> minInclusive + max > negMin -> maxInclusive + else -> minInclusive || maxInclusive + } + FloatInterval(0f, outMax, minInclusive = true, maxInclusive = outMaxInc) + } + } + } + + /** + * Returns an interval soundly bounding `min(a, b)` for all `a in this` and `b in other`, or + * [EMPTY] if either operand is empty. + */ + public fun min(other: FloatInterval): FloatInterval { + if (isEmpty || other.isEmpty) return EMPTY + return FloatInterval( + min = min(min, other.min), + max = min(max, other.max), + minInclusive = lowerInclusiveForUnion(other), + maxInclusive = upperInclusiveForIntersection(other), + ) + } + + /** + * Returns an interval soundly bounding `max(a, b)` for all `a in this` and `b in other`, or + * [EMPTY] if either operand is empty. + */ + public fun max(other: FloatInterval): FloatInterval { + if (isEmpty || other.isEmpty) return EMPTY + return FloatInterval( + min = max(min, other.min), + max = max(max, other.max), + minInclusive = lowerInclusiveForIntersection(other), + maxInclusive = upperInclusiveForUnion(other), + ) + } + + /** + * Returns an interval soundly bounding `min(max(minimum, a), maximum)` for all `a in this`, + * matching RemoteCompose `OP_CLAMP` semantics, or [EMPTY] if any operand is empty. + * + * @param minimum Interval bounding the lower clamp limit. + * @param maximum Interval bounding the upper clamp limit. + * @return The clamped interval, or [EMPTY] if any input interval is empty. + */ + public fun clamp(minimum: FloatInterval, maximum: FloatInterval): FloatInterval { + if (isEmpty || minimum.isEmpty || maximum.isEmpty) return EMPTY + return max(minimum).min(maximum) + } + + /** + * Returns an interval guaranteed to contain `sqrt(a)` for all `a in this`, or [EMPTY] if this + * interval is empty. + * + * Widens to [UNBOUNDED] if this interval may contain negative values (`min < 0f`), because + * RemoteCompose `OP_SQRT` evaluates `(float) Math.sqrt(a)` and yields `NaN` for negative inputs + * rather than clamping them. Computed bounds are closed because IEEE-754 rounding can map + * interior values onto the endpoint square root. + */ + public fun sqrt(): FloatInterval { + if (isEmpty) return EMPTY + if (min < 0f) return UNBOUNDED + val minRoot = if (min == 0f) 0f else sqrt(min) + return FloatInterval(minRoot, sqrt(max)) + } + + /** Returns an interval soundly bounding `floor(a)` for all `a in this`, or [EMPTY] if empty. */ + public fun floor(): FloatInterval = applyMonotonicRounding(::floor) + + /** Returns an interval soundly bounding `ceil(a)` for all `a in this`, or [EMPTY] if empty. */ + public fun ceil(): FloatInterval = applyMonotonicRounding(::ceil) + + /** + * Returns an interval soundly bounding `(float) Math.round(a)` (matching RemoteCompose + * `OP_ROUND`, which rounds ties toward `+Infinity` and saturates to 32-bit `Int` bounds) for + * all `a in this`, or [EMPTY] if empty. + */ + public fun round(): FloatInterval { + if (isEmpty) return EMPTY + val effectiveMin = if (minInclusive || min.isInfinite()) min else min.nextUp() + val effectiveMax = if (maxInclusive || max.isInfinite()) max else max.nextDown() + val outMin = Math.round(effectiveMin).toFloat() + val outMax = Math.round(effectiveMax).toFloat() + return if (outMin > outMax) EMPTY else FloatInterval(outMin, outMax) + } + + /** Returns an interval soundly bounding `sin(a)` (radians) for all `a in this`, or [EMPTY]. */ + public fun sin(): FloatInterval = + evaluatePeriodicTrig( + fn = { sin(it).toFloat() }, + maxPeakPhase = PI / 2.0, + minPeakPhase = 3.0 * PI / 2.0, + ) + + /** Returns an interval soundly bounding `cos(a)` (radians) for all `a in this`, or [EMPTY]. */ + public fun cos(): FloatInterval = + evaluatePeriodicTrig(fn = { cos(it).toFloat() }, maxPeakPhase = 0.0, minPeakPhase = PI) + + /** + * Returns an interval soundly bounding IEEE-754 truncated remainder `a % b` for all `a in this` + * and `b in divisor`, or [EMPTY] if either operand is empty. + * + * @param divisor Interval bounding the right-hand divisor. + * @return Sound bounding interval for `this % divisor`. + */ + public operator fun rem(divisor: FloatInterval): FloatInterval { + if (isEmpty || divisor.isEmpty) return EMPTY + if (divisor.min <= 0f && divisor.max <= 0f) return UNBOUNDED + if (divisor.isPoint && divisor.min > 0f) return remByPositivePoint(divisor.min) + if (divisor.min > 0f) { + val maxInf = divisor.max.isInfinite() + return when { + min >= 0f -> + FloatInterval(0f, divisor.max, minInclusive = true, maxInclusive = maxInf) + max <= 0f -> + FloatInterval(-divisor.max, 0f, minInclusive = maxInf, maxInclusive = true) + else -> + FloatInterval( + -divisor.max, + divisor.max, + minInclusive = maxInf, + maxInclusive = maxInf, + ) + } + } + return UNBOUNDED + } + + /** + * Returns the tightest interval hull containing both this interval and [other]. If either + * operand is [EMPTY], returns the other operand. + */ + public fun union(other: FloatInterval): FloatInterval { + if (isEmpty) return other + if (other.isEmpty) return this + return FloatInterval( + min = min(min, other.min), + max = max(max, other.max), + minInclusive = lowerInclusiveForUnion(other), + maxInclusive = upperInclusiveForUnion(other), + ) + } + + /** + * Returns the exact set intersection of this interval and [other], or [EMPTY] if the intervals + * are disjoint or either is empty. + */ + public fun intersect(other: FloatInterval): FloatInterval { + if (isEmpty || other.isEmpty) return EMPTY + val lower = max(min, other.min) + val upper = min(max, other.max) + val lowerInc = lowerInclusiveForIntersection(other) + val upperInc = upperInclusiveForIntersection(other) + if (lower > upper || (lower == upper && (!lowerInc || !upperInc))) return EMPTY + return FloatInterval(lower, upper, lowerInc, upperInc) + } + + /** + * Returns `true` if [value] lies within this interval respecting endpoint inclusivity, or + * `false` if [value] is `NaN` or outside the interval. + */ + public operator fun contains(value: Float): Boolean { + if (isEmpty || value.isNaN()) return false + val geMin = if (minInclusive) value >= min else value > min + val leMax = if (maxInclusive) value <= max else value < max + return geMin && leMax + } + + /** + * Returns `true` if this interval and [other] share no common values (always `true` when either + * interval is empty). + */ + public fun isDisjoint(other: FloatInterval): Boolean { + if (isEmpty || other.isEmpty) return true + if (max < other.min || (max == other.min && (!maxInclusive || !other.minInclusive))) { + return true + } + if (min > other.max || (min == other.max && (!minInclusive || !other.maxInclusive))) { + return true + } + return false + } + + /** + * Evaluates the three-valued relational predicate `this < other` across all value pairs in + * `this x other`. + */ + public fun compareLessThan(other: FloatInterval): TriState { + if (isEmpty || other.isEmpty) return TriState.UNKNOWN + if (max < other.min || (max == other.min && (!maxInclusive || !other.minInclusive))) { + return TriState.TRUE + } + if (min >= other.max) return TriState.FALSE + return TriState.UNKNOWN + } + + /** + * Evaluates the three-valued relational predicate `this <= other` across all value pairs in + * `this x other`. + */ + public fun compareLessThanOrEqual(other: FloatInterval): TriState { + if (isEmpty || other.isEmpty) return TriState.UNKNOWN + if (max <= other.min) return TriState.TRUE + if (min > other.max || (min == other.max && (!minInclusive || !other.maxInclusive))) { + return TriState.FALSE + } + return TriState.UNKNOWN + } + + /** + * Evaluates the three-valued relational predicate `this > other` across all value pairs in + * `this x other`. + */ + public fun compareGreaterThan(other: FloatInterval): TriState = other.compareLessThan(this) + + /** + * Evaluates the three-valued relational predicate `this >= other` across all value pairs in + * `this x other`. + */ + public fun compareGreaterThanOrEqual(other: FloatInterval): TriState = + other.compareLessThanOrEqual(this) + + /** + * Evaluates the three-valued relational predicate `this == other` across all value pairs in + * `this x other`. + */ + public fun compareEqualTo(other: FloatInterval): TriState { + if (isEmpty || other.isEmpty) return TriState.UNKNOWN + if (isPoint && other.isPoint && min == other.min) return TriState.TRUE + if (isDisjoint(other)) return TriState.FALSE + return TriState.UNKNOWN + } + + /** + * Evaluates the three-valued relational predicate `this != other` across all value pairs in + * `this x other`. + */ + public fun compareNotEqualTo(other: FloatInterval): TriState = !compareEqualTo(other) + + /** Evaluates [comparison] between `this` and [other]. */ + public fun compare(comparison: IntervalComparison, other: FloatInterval): TriState = + when (comparison) { + IntervalComparison.EQ -> compareEqualTo(other) + IntervalComparison.NEQ -> compareNotEqualTo(other) + IntervalComparison.LT -> compareLessThan(other) + IntervalComparison.LTE -> compareLessThanOrEqual(other) + IntervalComparison.GT -> compareGreaterThan(other) + IntervalComparison.GTE -> compareGreaterThanOrEqual(other) + } + + /** + * Returns `true` if every value in this interval is strictly less than every value in [other]. + */ + public fun isAlwaysLessThan(other: FloatInterval): Boolean = + compareLessThan(other) == TriState.TRUE + + /** Returns `true` if every value in this interval is `<=` every value in [other]. */ + public fun isAlwaysLessThanOrEqual(other: FloatInterval): Boolean = + compareLessThanOrEqual(other) == TriState.TRUE + + /** + * Returns `true` if every value in this interval is strictly greater than every value in + * [other]. + */ + public fun isAlwaysGreaterThan(other: FloatInterval): Boolean = + compareGreaterThan(other) == TriState.TRUE + + /** Returns `true` if every value in this interval is `>=` every value in [other]. */ + public fun isAlwaysGreaterThanOrEqual(other: FloatInterval): Boolean = + compareGreaterThanOrEqual(other) == TriState.TRUE + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is FloatInterval) return false + if (isEmpty && other.isEmpty) return true + if (isEmpty || other.isEmpty) return false + return min == other.min && + max == other.max && + minInclusive == other.minInclusive && + maxInclusive == other.maxInclusive + } + + override fun hashCode(): Int { + if (isEmpty) return 0 + var result = canonicalFloatBits(min) + result = 31 * result + canonicalFloatBits(max) + result = 31 * result + minInclusive.hashCode() + result = 31 * result + maxInclusive.hashCode() + return result + } + + override fun toString(): String { + val open = if (minInclusive) "[" else "(" + val close = if (maxInclusive) "]" else ")" + return "FloatInterval($open$min, $max$close)" + } + + private fun combineCornerBounds(c1: Float, c2: Float, c3: Float, c4: Float): FloatInterval { + if (c1.isNaN() || c2.isNaN() || c3.isNaN() || c4.isNaN()) return UNBOUNDED + return FloatInterval(minOf(c1, c2, c3, c4), maxOf(c1, c2, c3, c4)) + } + + private fun intervalPreservingNonEmpty( + min: Float, + max: Float, + minInclusive: Boolean, + maxInclusive: Boolean, + ): FloatInterval { + val collapsed = min == max + return FloatInterval( + min = min, + max = max, + minInclusive = collapsed || minInclusive, + maxInclusive = collapsed || maxInclusive, + ) + } + + private fun applyMonotonicRounding(op: (Float) -> Float): FloatInterval { + if (isEmpty) return EMPTY + val effectiveMin = if (minInclusive || min.isInfinite()) min else min.nextUp() + val effectiveMax = if (maxInclusive || max.isInfinite()) max else max.nextDown() + val outMin = if (effectiveMin.isInfinite()) effectiveMin else op(effectiveMin) + val outMax = if (effectiveMax.isInfinite()) effectiveMax else op(effectiveMax) + return if (outMin > outMax) EMPTY else FloatInterval(outMin, outMax) + } + + private fun evaluatePeriodicTrig( + fn: (Double) -> Float, + maxPeakPhase: Double, + minPeakPhase: Double, + ): FloatInterval { + if (isEmpty) return EMPTY + val twoPi = 2.0 * PI + if (isUnbounded || (max - min) >= twoPi.toFloat()) { + return FloatInterval(-1f, 1f) + } + val vMin = fn(min.toDouble()) + val vMax = fn(max.toDouble()) + var low = min(vMin, vMax) + var high = max(vMin, vMax) + + val kMax = ceil((min.toDouble() - maxPeakPhase) / twoPi) + if (maxPeakPhase + kMax * twoPi <= max.toDouble()) { + high = 1f + } + val kMin = ceil((min.toDouble() - minPeakPhase) / twoPi) + if (minPeakPhase + kMin * twoPi <= max.toDouble()) { + low = -1f + } + return FloatInterval(low.coerceIn(-1f, 1f), high.coerceIn(-1f, 1f)) + } + + private fun remByPositivePoint(m: Float): FloatInterval { + if (min < 0f) { + return if (max <= 0f) { + FloatInterval(-m, 0f, minInclusive = false, maxInclusive = true) + } else { + FloatInterval(-m, m, minInclusive = false, maxInclusive = false) + } + } + if (max.isInfinite() || (max - min) >= m) { + return FloatInterval(0f, m, minInclusive = true, maxInclusive = false) + } + val effectiveMax = if (maxInclusive) max else max.nextDown() + val k1 = floor(min.toDouble() / m.toDouble()) + val k2 = floor(effectiveMax.toDouble() / m.toDouble()) + if (k1 != k2) { + return FloatInterval(0f, m, minInclusive = true, maxInclusive = false) + } + val remMin = min % m + val rawRemMax = max % m + return when { + !maxInclusive && rawRemMax == 0f && max > min -> + FloatInterval(remMin, m, minInclusive = minInclusive, maxInclusive = false) + remMin <= rawRemMax -> + intervalPreservingNonEmpty(remMin, rawRemMax, minInclusive, maxInclusive) + else -> FloatInterval(0f, m, minInclusive = true, maxInclusive = false) + } + } + + private fun lowerInclusiveForUnion(other: FloatInterval): Boolean = + when { + min < other.min -> minInclusive + other.min < min -> other.minInclusive + else -> minInclusive || other.minInclusive + } + + private fun upperInclusiveForUnion(other: FloatInterval): Boolean = + when { + max > other.max -> maxInclusive + other.max > max -> other.maxInclusive + else -> maxInclusive || other.maxInclusive + } + + private fun lowerInclusiveForIntersection(other: FloatInterval): Boolean = + when { + min > other.min -> minInclusive + other.min > min -> other.minInclusive + else -> minInclusive && other.minInclusive + } + + private fun upperInclusiveForIntersection(other: FloatInterval): Boolean = + when { + max < other.max -> maxInclusive + other.max < max -> other.maxInclusive + else -> maxInclusive && other.maxInclusive + } + + public companion object { + /** Largest integer magnitude representable exactly in IEEE-754 binary32 (`2^24`). */ + public const val MAX_EXACT_INT: Int = 1 shl 24 + + /** The full extended-real interval `[-Infinity, +Infinity]`. */ + public val UNBOUNDED: FloatInterval = + FloatInterval(Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY) + + /** The singleton interval `[0f, 0f]`. */ + public val ZERO: FloatInterval = FloatInterval(0f, 0f) + + /** The empty interval containing no values. */ + public val EMPTY: FloatInterval = + FloatInterval(Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY) + + /** The closed unit interval `[0f, 1f]`. */ + public val UNIT: FloatInterval = FloatInterval(0f, 1f) + + /** + * Returns a singleton interval `[value, value]`, or [UNBOUNDED] if [value] is `NaN`. + * + * @param value The constant float value to wrap. + * @return Point interval `[value, value]`, or [UNBOUNDED] for `NaN`. + */ + @JvmStatic + public fun point(value: Float): FloatInterval = + if (value.isNaN()) UNBOUNDED else FloatInterval(value, value) + + private fun canonicalFloatBits(value: Float): Int = + when { + value == 0f -> 0 + value.isNaN() -> Float.NaN.toBits() + else -> value.toBits() + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/IntInterval.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/IntInterval.kt new file mode 100644 index 0000000..5374995 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/IntInterval.kt
@@ -0,0 +1,417 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.annotation.RestrictTo +import kotlin.math.max +import kotlin.math.min + +/** + * An immutable overflow-safe closed 32-bit signed integer interval `[min, max]`. + * + * Uses [MIN_BOUND] and [MAX_BOUND] as negative and positive infinity sentinels representing + * `[Int.MIN_VALUE, MIN_BOUND]` and `[MAX_BOUND, Int.MAX_VALUE]` respectively. Arithmetic operators + * (`+`, `-`, `*`, `/`, unary `-`, `abs`) model 32-bit two's-complement wrap-around soundly by + * widening to [UNBOUNDED] whenever the exact 64-bit result exits `[Int.MIN_VALUE, Int.MAX_VALUE]`. + * + * Constructor arguments with `min > max` normalize to [EMPTY] (`[1, 0]`), and finite bounds outside + * `[MIN_BOUND, MAX_BOUND]` normalize to the corresponding sentinel. + * + * @property min The lower endpoint of this interval (values `<= MIN_BOUND` represent `-Infinity`). + * @property max The upper endpoint of this interval (values `>= MAX_BOUND` represent `+Infinity`). + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class IntInterval(min: Int, max: Int) { + /** The lower endpoint of this interval ([MIN_BOUND] represents unbounded below). */ + public val min: Int = if (min > max) 1 else min.coerceIn(MIN_BOUND, MAX_BOUND) + + /** The upper endpoint of this interval ([MAX_BOUND] represents unbounded above). */ + public val max: Int = if (min > max) 0 else max.coerceIn(MIN_BOUND, MAX_BOUND) + + /** Whether this interval contains no integers (`min > max`). */ + public val isEmpty: Boolean + get() = min > max + + /** + * Whether either endpoint is represented by an infinity sentinel ([MIN_BOUND] or [MAX_BOUND]). + */ + public val isUnbounded: Boolean + get() = !isEmpty && (min <= MIN_BOUND || max >= MAX_BOUND) + + /** Whether this interval represents a single finite integer `[v, v]`. */ + public val isPoint: Boolean + get() = min == max && !isUnbounded && !isEmpty + + /** Whether this non-empty interval has a finite lower bound (`min > MIN_BOUND`). */ + public val hasFiniteMin: Boolean + get() = !isEmpty && min > MIN_BOUND + + /** Whether this non-empty interval has a finite upper bound (`max < MAX_BOUND`). */ + public val hasFiniteMax: Boolean + get() = !isEmpty && max < MAX_BOUND + + private val actualMinLong: Long + get() = if (hasFiniteMin) min.toLong() else Int.MIN_VALUE.toLong() + + private val actualMaxLong: Long + get() = if (hasFiniteMax) max.toLong() else Int.MAX_VALUE.toLong() + + /** + * Widens this integer interval to a [FloatInterval], mapping infinity sentinels to + * [Float.NEGATIVE_INFINITY] and [Float.POSITIVE_INFINITY]. + */ + public fun toFloatInterval(): FloatInterval = + when { + isEmpty -> FloatInterval.EMPTY + isUnbounded -> + FloatInterval( + if (min <= MIN_BOUND) Float.NEGATIVE_INFINITY else min.toFloat(), + if (max >= MAX_BOUND) Float.POSITIVE_INFINITY else max.toFloat(), + ) + else -> FloatInterval(min.toFloat(), max.toFloat()) + } + + /** + * Returns an interval soundly bounding 32-bit `a + b` for all `a in this` and `b in other`, + * widening to [UNBOUNDED] if 32-bit signed overflow can occur, or [EMPTY] if either operand is + * empty. + */ + public operator fun plus(other: IntInterval): IntInterval { + if (isEmpty || other.isEmpty) return EMPTY + return fromInt32ArithmeticBounds( + actualMinLong + other.actualMinLong, + actualMaxLong + other.actualMaxLong, + ) + } + + /** + * Returns an interval soundly bounding 32-bit `a - b` for all `a in this` and `b in other`, + * widening to [UNBOUNDED] if 32-bit signed overflow can occur, or [EMPTY] if either operand is + * empty. + */ + public operator fun minus(other: IntInterval): IntInterval { + if (isEmpty || other.isEmpty) return EMPTY + return fromInt32ArithmeticBounds( + actualMinLong - other.actualMaxLong, + actualMaxLong - other.actualMinLong, + ) + } + + /** + * Returns an interval soundly bounding 32-bit `a * b` for all `a in this` and `b in other`, + * widening to [UNBOUNDED] if 32-bit signed overflow can occur, or [EMPTY] if either operand is + * empty. + */ + public operator fun times(other: IntInterval): IntInterval { + if (isEmpty || other.isEmpty) return EMPTY + if ((isPoint && min == 0) || (other.isPoint && other.min == 0)) return ZERO + val aMin = actualMinLong + val aMax = actualMaxLong + val bMin = other.actualMinLong + val bMax = other.actualMaxLong + val p1 = aMin * bMin + val p2 = aMin * bMax + val p3 = aMax * bMin + val p4 = aMax * bMax + return fromInt32ArithmeticBounds(minOf(p1, p2, p3, p4), maxOf(p1, p2, p3, p4)) + } + + /** + * Returns an interval soundly bounding 32-bit truncating integer division `a / b` for all `a in + * this` and `b in other`, or [EMPTY] if either operand is empty. Widens to [UNBOUNDED] if + * [other] contains `0` or `Int.MIN_VALUE / -1` wrap-around is possible. + */ + public operator fun div(other: IntInterval): IntInterval { + if (isEmpty || other.isEmpty) return EMPTY + if (other.min <= 0 && other.max >= 0) return UNBOUNDED + val aMin = actualMinLong + val aMax = actualMaxLong + val bMin = other.actualMinLong + val bMax = other.actualMaxLong + val d1 = aMin / bMin + val d2 = aMin / bMax + val d3 = aMax / bMin + val d4 = aMax / bMax + return fromInt32ArithmeticBounds(minOf(d1, d2, d3, d4), maxOf(d1, d2, d3, d4)) + } + + /** + * Returns an interval soundly bounding 32-bit `-a` for all `a in this`, widening to [UNBOUNDED] + * if [Int.MIN_VALUE] is reachable (`-Int.MIN_VALUE == Int.MIN_VALUE`), or [EMPTY] if empty. + */ + public operator fun unaryMinus(): IntInterval { + if (isEmpty) return EMPTY + return fromInt32ArithmeticBounds(-actualMaxLong, -actualMinLong) + } + + /** + * Returns an interval soundly bounding `min(a, b)` for all `a in this` and `b in other`, or + * [EMPTY] if either operand is empty. + */ + public fun min(other: IntInterval): IntInterval { + if (isEmpty || other.isEmpty) return EMPTY + return IntInterval(min(min, other.min), min(max, other.max)) + } + + /** + * Returns an interval soundly bounding `max(a, b)` for all `a in this` and `b in other`, or + * [EMPTY] if either operand is empty. + */ + public fun max(other: IntInterval): IntInterval { + if (isEmpty || other.isEmpty) return EMPTY + return IntInterval(max(min, other.min), max(max, other.max)) + } + + /** + * Returns an interval soundly bounding 32-bit `Math.abs(a)` for all `a in this`, widening to + * [UNBOUNDED] if [Int.MIN_VALUE] is reachable (`Math.abs(Int.MIN_VALUE) == Int.MIN_VALUE`), or + * [EMPTY] if empty. + */ + public fun abs(): IntInterval { + if (isEmpty) return EMPTY + return when { + min >= 0 -> this + !hasFiniteMin -> UNBOUNDED + max <= 0 -> -this + !hasFiniteMax -> IntInterval(0, MAX_BOUND) + else -> fromLongBounds(0L, max(-min.toLong(), max.toLong())) + } + } + + /** + * Returns an interval soundly bounding `min(max(minimum, a), maximum)` for all `a in this`, + * matching RemoteCompose integer `I_CLAMP` semantics, or [EMPTY] if any operand is empty. + * + * @param minimum Interval bounding the lower clamp limit. + * @param maximum Interval bounding the upper clamp limit. + * @return The clamped interval, or [EMPTY] if any operand is empty. + */ + public fun clamp(minimum: IntInterval, maximum: IntInterval): IntInterval { + if (isEmpty || minimum.isEmpty || maximum.isEmpty) return EMPTY + return max(minimum).min(maximum) + } + + /** + * Clamps this interval to the fixed closed range `[minimum, maximum]`, or returns [EMPTY] if + * this interval is empty. + * + * @param minimum Fixed inclusive lower bound. + * @param maximum Fixed inclusive upper bound. + * @return The clamped interval, or [EMPTY] if this interval is empty. + * @throws IllegalArgumentException if `minimum > maximum`. + */ + public fun clampToRange(minimum: Int, maximum: Int): IntInterval { + require(minimum <= maximum) { "minimum ($minimum) must be <= maximum ($maximum)" } + if (isEmpty) return EMPTY + return IntInterval(min.coerceIn(minimum, maximum), max.coerceIn(minimum, maximum)) + } + + /** + * Returns an interval soundly bounding integer remainder `a % b` for all `a in this` and `b in + * divisor`, or [EMPTY] if either operand is empty. + */ + public operator fun rem(divisor: IntInterval): IntInterval { + if (isEmpty || divisor.isEmpty) return EMPTY + if (divisor.isUnbounded) return UNBOUNDED + if (divisor.min > 0 && divisor.min == divisor.max) { + return remByPositivePoint(divisor.min.toLong()) + } + if (divisor.min > 0) { + val maxRem = divisor.max.toLong() - 1L + return when { + min >= 0 -> fromLongBounds(0L, maxRem) + max <= 0 -> fromLongBounds(-maxRem, 0L) + else -> fromLongBounds(-maxRem, maxRem) + } + } + return UNBOUNDED + } + + /** + * Returns the tightest interval hull containing both this interval and [other]. If either + * operand is [EMPTY], returns the other operand. + */ + public fun union(other: IntInterval): IntInterval { + if (isEmpty) return other + if (other.isEmpty) return this + return IntInterval(min(min, other.min), max(max, other.max)) + } + + /** + * Returns the exact set intersection of this interval and [other], or [EMPTY] if the intervals + * are disjoint or either is empty. + */ + public fun intersect(other: IntInterval): IntInterval { + if (isEmpty || other.isEmpty) return EMPTY + val l = max(min, other.min) + val u = min(max, other.max) + return if (l <= u) IntInterval(l, u) else EMPTY + } + + /** + * Returns `true` if [value] lies within this interval, treating [MIN_BOUND] and [MAX_BOUND] + * endpoints as unbounded below and above respectively. + */ + public operator fun contains(value: Int): Boolean = + !isEmpty && (!hasFiniteMin || value >= min) && (!hasFiniteMax || value <= max) + + /** + * Returns `true` if this interval and [other] share no common integers (always `true` when + * either interval is empty). + */ + public fun isDisjoint(other: IntInterval): Boolean { + if (isEmpty || other.isEmpty) return true + if (hasFiniteMax && other.hasFiniteMin && max < other.min) return true + if (hasFiniteMin && other.hasFiniteMax && min > other.max) return true + return false + } + + /** Evaluates `this < other` across all integer pairs in `this x other`. */ + public fun compareLessThan(other: IntInterval): TriState { + if (isEmpty || other.isEmpty) return TriState.UNKNOWN + if (hasFiniteMax && other.hasFiniteMin && max < other.min) return TriState.TRUE + if (hasFiniteMin && other.hasFiniteMax && min >= other.max) return TriState.FALSE + return TriState.UNKNOWN + } + + /** Evaluates `this <= other` across all integer pairs in `this x other`. */ + public fun compareLessThanOrEqual(other: IntInterval): TriState { + if (isEmpty || other.isEmpty) return TriState.UNKNOWN + if (hasFiniteMax && other.hasFiniteMin && max <= other.min) return TriState.TRUE + if (hasFiniteMin && other.hasFiniteMax && min > other.max) return TriState.FALSE + return TriState.UNKNOWN + } + + /** Evaluates `this > other` across all integer pairs in `this x other`. */ + public fun compareGreaterThan(other: IntInterval): TriState = other.compareLessThan(this) + + /** Evaluates `this >= other` across all integer pairs in `this x other`. */ + public fun compareGreaterThanOrEqual(other: IntInterval): TriState = + other.compareLessThanOrEqual(this) + + /** Evaluates `this == other` across all integer pairs in `this x other`. */ + public fun compareEqualTo(other: IntInterval): TriState { + if (isEmpty || other.isEmpty) return TriState.UNKNOWN + if (isPoint && other.isPoint && min == other.min) return TriState.TRUE + if (isDisjoint(other)) return TriState.FALSE + return TriState.UNKNOWN + } + + /** Evaluates `this != other` across all integer pairs in `this x other`. */ + public fun compareNotEqualTo(other: IntInterval): TriState = !compareEqualTo(other) + + /** Evaluates [comparison] between `this` and [other]. */ + public fun compare(comparison: IntervalComparison, other: IntInterval): TriState = + when (comparison) { + IntervalComparison.EQ -> compareEqualTo(other) + IntervalComparison.NEQ -> compareNotEqualTo(other) + IntervalComparison.LT -> compareLessThan(other) + IntervalComparison.LTE -> compareLessThanOrEqual(other) + IntervalComparison.GT -> compareGreaterThan(other) + IntervalComparison.GTE -> compareGreaterThanOrEqual(other) + } + + /** Returns `true` if every integer in `this` is strictly less than every integer in [other]. */ + public fun isAlwaysLessThan(other: IntInterval): Boolean = + compareLessThan(other) == TriState.TRUE + + /** Returns `true` if every integer in `this` is `<=` every integer in [other]. */ + public fun isAlwaysLessThanOrEqual(other: IntInterval): Boolean = + compareLessThanOrEqual(other) == TriState.TRUE + + /** + * Returns `true` if every integer in `this` is strictly greater than every integer in [other]. + */ + public fun isAlwaysGreaterThan(other: IntInterval): Boolean = + compareGreaterThan(other) == TriState.TRUE + + /** Returns `true` if every integer in `this` is `>=` every integer in [other]. */ + public fun isAlwaysGreaterThanOrEqual(other: IntInterval): Boolean = + compareGreaterThanOrEqual(other) == TriState.TRUE + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is IntInterval) return false + return min == other.min && max == other.max + } + + override fun hashCode(): Int = 31 * min + max + + override fun toString(): String = "IntInterval([$min, $max])" + + private fun remByPositivePoint(m: Long): IntInterval { + if (min < 0) { + return if (max <= 0) fromLongBounds(-m + 1L, 0L) else fromLongBounds(-m + 1L, m - 1L) + } + if (isUnbounded || max.toLong() - min.toLong() >= m) { + return fromLongBounds(0L, m - 1L) + } + val k1 = min.toLong() / m + val k2 = max.toLong() / m + return if (k1 == k2) { + fromLongBounds(min.toLong() % m, max.toLong() % m) + } else { + fromLongBounds(0L, m - 1L) + } + } + + public companion object { + /** Sentinel lower endpoint representing negative infinity in [IntInterval]. */ + public const val MIN_BOUND: Int = Int.MIN_VALUE / 2 + + /** Sentinel upper endpoint representing positive infinity in [IntInterval]. */ + public const val MAX_BOUND: Int = Int.MAX_VALUE / 2 + + /** The unbounded integer interval `[MIN_BOUND, MAX_BOUND]`. */ + public val UNBOUNDED: IntInterval = IntInterval(MIN_BOUND, MAX_BOUND) + + /** The singleton interval `[0, 0]`. */ + public val ZERO: IntInterval = IntInterval(0, 0) + + /** The non-negative integer interval `[0, MAX_BOUND]`. */ + public val NON_NEGATIVE: IntInterval = IntInterval(0, MAX_BOUND) + + /** The empty interval containing no integers. */ + public val EMPTY: IntInterval = IntInterval(1, 0) + + /** + * Returns a singleton interval `[value, value]`, saturating values outside `(MIN_BOUND, + * MAX_BOUND)` to a sound non-point sentinel range (`[MIN_BOUND, MIN_BOUND]` or `[MAX_BOUND, + * MAX_BOUND]`). + */ + @JvmStatic + public fun point(value: Int): IntInterval = fromLongBounds(value.toLong(), value.toLong()) + + /** + * Constructs an [IntInterval] from 64-bit bounds `[lo, hi]`, clamping values outside + * `(MIN_BOUND, MAX_BOUND)` to the infinity sentinels. + */ + @JvmStatic + public fun fromLongBounds(lo: Long, hi: Long): IntInterval { + if (lo > hi) return EMPTY + val minInt = lo.coerceIn(MIN_BOUND.toLong(), MAX_BOUND.toLong()).toInt() + val maxInt = hi.coerceIn(MIN_BOUND.toLong(), MAX_BOUND.toLong()).toInt() + return IntInterval(minInt, maxInt) + } + + private fun fromInt32ArithmeticBounds(lo: Long, hi: Long): IntInterval { + if (lo > hi) return EMPTY + if (lo < Int.MIN_VALUE.toLong() || hi > Int.MAX_VALUE.toLong()) return UNBOUNDED + return fromLongBounds(lo, hi) + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/SlotInterval.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/SlotInterval.kt new file mode 100644 index 0000000..19f0c37 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/SlotInterval.kt
@@ -0,0 +1,216 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.document.RemoteContextIds +import kotlin.math.max +import kotlin.math.min +import kotlin.math.nextDown +import kotlin.math.nextUp + +/** + * Coupled 4-bound slot matching `RemoteComposeState`'s coupled `mFloatMap[id]` and + * `mIntegerMap[id]` storage. + * + * At runtime: + * - Updating a float slot writes `mFloatMap[id] = v` and `mIntegerMap[id] = (int) v`. + * - Updating an integer slot writes `mIntegerMap[id] = v` and `mFloatMap[id] = (float) v`. + * + * Keeping all four bounds in a single slot makes float and integer updates atomic and preserves + * tight bounds across mixed-type reads. + * + * Integer bounds with `intMin > intMax` normalize to [IntInterval.EMPTY] (`[1, 0]`), and finite + * bounds outside `[IntInterval.MIN_BOUND, IntInterval.MAX_BOUND]` normalize to the corresponding + * infinity sentinel. + * + * @property floatMin Lower float bound (or [Float.NEGATIVE_INFINITY] if unbounded below). + * @property floatMax Upper float bound (or [Float.POSITIVE_INFINITY] if unbounded above). + * @property intMin Lower integer bound ([IntInterval.MIN_BOUND] if unbounded below). + * @property intMax Upper integer bound ([IntInterval.MAX_BOUND] if unbounded above). + * @property isFloatMinInclusive Whether [floatMin] is included in the float view. + * @property isFloatMaxInclusive Whether [floatMax] is included in the float view. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class SlotInterval +@JvmOverloads +constructor( + public val floatMin: Float, + public val floatMax: Float, + intMin: Int, + intMax: Int, + public val isFloatMinInclusive: Boolean = true, + public val isFloatMaxInclusive: Boolean = true, +) { + /** Lower integer bound ([IntInterval.MIN_BOUND] if unbounded below). */ + public val intMin: Int = + if (intMin > intMax) 1 else intMin.coerceIn(IntInterval.MIN_BOUND, IntInterval.MAX_BOUND) + + /** Upper integer bound ([IntInterval.MAX_BOUND] if unbounded above). */ + public val intMax: Int = + if (intMin > intMax) 0 else intMax.coerceIn(IntInterval.MIN_BOUND, IntInterval.MAX_BOUND) + + /** Returns the float view of this coupled slot. */ + public fun toFloatInterval(): FloatInterval = + FloatInterval(floatMin, floatMax, isFloatMinInclusive, isFloatMaxInclusive) + + /** Returns the integer view of this coupled slot. */ + public fun toIntInterval(): IntInterval = IntInterval(intMin, intMax) + + /** Joins this slot with [other] component-wise across both float and integer views. */ + public fun union(other: SlotInterval): SlotInterval { + val f = toFloatInterval().union(other.toFloatInterval()) + val i = toIntInterval().union(other.toIntInterval()) + return SlotInterval(f.min, f.max, i.min, i.max, f.minInclusive, f.maxInclusive) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is SlotInterval) return false + return toFloatInterval() == other.toFloatInterval() && + toIntInterval() == other.toIntInterval() + } + + override fun hashCode(): Int = 31 * toFloatInterval().hashCode() + toIntInterval().hashCode() + + override fun toString(): String = + "SlotInterval(float=${toFloatInterval()}, int=${toIntInterval()})" + + public companion object { + /** Unbounded coupled slot across both float and integer views. */ + public val UNBOUNDED: SlotInterval = + SlotInterval( + floatMin = Float.NEGATIVE_INFINITY, + floatMax = Float.POSITIVE_INFINITY, + intMin = IntInterval.MIN_BOUND, + intMax = IntInterval.MAX_BOUND, + ) + + /** + * Constructs a coupled [SlotInterval] from a float write, truncating toward zero for the + * integer bounds identically to Java `(int) float`. Widens [FloatInterval.EMPTY] + * conservatively to [UNBOUNDED]. + */ + @JvmStatic + public fun fromFloat(interval: FloatInterval): SlotInterval { + if (interval.isEmpty) return UNBOUNDED + val effectiveMin = + if (interval.minInclusive || interval.min.isInfinite()) { + interval.min + } else { + interval.min.nextUp() + } + val effectiveMax = + if (interval.maxInclusive || interval.max.isInfinite()) { + interval.max + } else { + interval.max.nextDown() + } + val iMin = floatToIntBound(effectiveMin) + val iMax = floatToIntBound(effectiveMax) + return SlotInterval( + floatMin = interval.min, + floatMax = interval.max, + intMin = min(iMin, iMax), + intMax = max(iMin, iMax), + isFloatMinInclusive = interval.minInclusive, + isFloatMaxInclusive = interval.maxInclusive, + ) + } + + /** + * Constructs a coupled [SlotInterval] from an integer write, promoting bounds to `Float`. + * Widens [IntInterval.EMPTY] conservatively to [UNBOUNDED]. + */ + @JvmStatic + public fun fromInt(interval: IntInterval): SlotInterval { + if (interval.isEmpty) return UNBOUNDED + val fi = interval.toFloatInterval() + return SlotInterval( + floatMin = fi.min, + floatMax = fi.max, + intMin = interval.min, + intMax = interval.max, + isFloatMinInclusive = fi.minInclusive, + isFloatMaxInclusive = fi.maxInclusive, + ) + } + + /** Constructs a coupled point [SlotInterval] from a float constant. */ + @JvmStatic + public fun fromFloatPoint(value: Float): SlotInterval = + fromFloat(FloatInterval.point(value)) + + /** Constructs a coupled point [SlotInterval] from an integer constant. */ + @JvmStatic + public fun fromIntPoint(value: Int): SlotInterval = fromInt(IntInterval.point(value)) + + /** + * Returns the canonical runtime range for built-in [RemoteContextIds] system globals, or + * `null` if [id] has no built-in static bound. + * + * Matches `RemoteClock.TimeSnapshot` and `RemoteContext` runtime semantics. + * + * @param id The [RemoteContextIds] global identifier. + * @param canvasWidth Optional fixed viewport width for [RemoteContextIds.ID_WINDOW_WIDTH]. + * Callers must only provide a non-null value when the document runs with + * `RootContentBehavior.SIZING_SCALE` (or otherwise guarantees fixed, integer-truncated + * runtime window dimensions), because `CoreDocument.paint()` overwrites `ID_WINDOW_WIDTH` + * with `(int) context.mWidth` whenever `mContentSizing != SIZING_SCALE` (the default is + * `NONE`). + * @param canvasHeight Optional fixed viewport height for + * [RemoteContextIds.ID_WINDOW_HEIGHT], subject to the same `SIZING_SCALE` and + * integer-dimension precondition as [canvasWidth]. + */ + @JvmStatic + @JvmOverloads + public fun systemGlobalOrNull( + id: Int, + canvasWidth: Float? = null, + canvasHeight: Float? = null, + ): SlotInterval? = + when (id) { + RemoteContextIds.ID_CONTINUOUS_SEC -> + fromFloat(FloatInterval(0f, 3600f, minInclusive = true, maxInclusive = false)) + RemoteContextIds.ID_TIME_IN_SEC -> fromInt(IntInterval(0, 3599)) + RemoteContextIds.ID_TIME_IN_MIN -> fromInt(IntInterval(0, 1439)) + RemoteContextIds.ID_TIME_IN_HR -> fromInt(IntInterval(0, 23)) + RemoteContextIds.ID_CALENDAR_MONTH -> fromInt(IntInterval(1, 12)) + RemoteContextIds.ID_WEEK_DAY -> fromInt(IntInterval(1, 7)) + RemoteContextIds.ID_DAY_OF_MONTH -> fromInt(IntInterval(1, 31)) + RemoteContextIds.ID_DAY_OF_YEAR -> fromInt(IntInterval(1, 366)) + RemoteContextIds.ID_WINDOW_WIDTH -> canvasWidth?.let { fromFloatPoint(it) } + RemoteContextIds.ID_WINDOW_HEIGHT -> canvasHeight?.let { fromFloatPoint(it) } + RemoteContextIds.ID_COMPONENT_WIDTH, + RemoteContextIds.ID_COMPONENT_HEIGHT, + RemoteContextIds.ID_ANIMATION_TIME -> + fromFloat(FloatInterval(0f, Float.POSITIVE_INFINITY)) + // Players initialize lastAnimationTime = 0.1f and compute animationTime - + // lastAnimationTime, which can be negative on frame 1 or after setDocument resets. + RemoteContextIds.ID_ANIMATION_DELTA_TIME -> UNBOUNDED + else -> null + } + + private fun floatToIntBound(value: Float): Int = + when { + value.isNaN() -> IntInterval.MIN_BOUND + value <= IntInterval.MIN_BOUND.toFloat() -> IntInterval.MIN_BOUND + value >= IntInterval.MAX_BOUND.toFloat() -> IntInterval.MAX_BOUND + else -> value.toInt() + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/StringAndColorIntervals.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/StringAndColorIntervals.kt new file mode 100644 index 0000000..f9e9939 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/StringAndColorIntervals.kt
@@ -0,0 +1,724 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.document.ColorAttributeType +import androidx.compose.remote.document.FloatFormatSpec +import androidx.compose.remote.document.RemoteColorMath +import androidx.compose.remote.document.TextFromFloatFormatter +import androidx.compose.remote.document.TextTransformOperation +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min +import kotlin.math.nextDown +import kotlin.math.nextUp + +/** + * Conservative summary of a RemoteCompose string value across all reachable runtime states, + * guaranteed to encompass every string value the expression can produce at runtime. + * + * @property length Non-negative character (UTF-16 code unit) length range `[minLen, maxLen]`. + * @property isAsciiOnly Whether every reachable character is guaranteed to lie in `0x00..0x7F` + * (used so case conversions preserve UTF-16 length). + * @property constantValue The exact constant string if all reachable executions yield one string, + * or `null` otherwise. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class StringSummary +@JvmOverloads +constructor( + public val length: IntInterval, + public val isAsciiOnly: Boolean, + public val constantValue: String? = null, +) { + /** Joins this string summary with [other] over alternative runtime paths. */ + public fun union(other: StringSummary): StringSummary = + StringSummary( + length = length.union(other.length), + isAsciiOnly = isAsciiOnly && other.isAsciiOnly, + constantValue = + if (constantValue != null && constantValue == other.constantValue) { + constantValue + } else { + null + }, + ) + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is StringSummary) return false + return length == other.length && + isAsciiOnly == other.isAsciiOnly && + constantValue == other.constantValue + } + + override fun hashCode(): Int { + var result = length.hashCode() + result = 31 * result + isAsciiOnly.hashCode() + result = 31 * result + (constantValue?.hashCode() ?: 0) + return result + } + + override fun toString(): String = + "StringSummary(length=$length, isAsciiOnly=$isAsciiOnly, constantValue=$constantValue)" + + public companion object { + /** Conservative summary for an unknown or host-overridden string (length is still >= 0). */ + public val UNKNOWN: StringSummary = + StringSummary( + length = IntInterval.NON_NEGATIVE, + isAsciiOnly = false, + constantValue = null, + ) + + /** Returns an exact summary for a known literal string [value]. */ + @JvmStatic + public fun constant(value: String): StringSummary = + StringSummary( + length = IntInterval.point(value.length), + isAsciiOnly = value.all { it.code < 128 }, + constantValue = value, + ) + } +} + +/** + * Conservative per-channel 8-bit ARGB interval `[0, 255]^4` guaranteed to enclose every color value + * a RemoteCompose expression can produce at runtime. + * + * Matches wire `RemoteComposeState.mColorMap`, which stores every color as a packed 32-bit + * `0xAARRGGBB` integer. + * + * @property alpha 8-bit alpha channel interval in `[0, 255]`. + * @property red 8-bit red channel interval in `[0, 255]`. + * @property green 8-bit green channel interval in `[0, 255]`. + * @property blue 8-bit blue channel interval in `[0, 255]`. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class ColorInterval( + public val alpha: IntInterval, + public val red: IntInterval, + public val green: IntInterval, + public val blue: IntInterval, +) { + /** Whether all four ARGB channels represent single constant integers. */ + public val isPoint: Boolean + get() = alpha.isPoint && red.isPoint && green.isPoint && blue.isPoint + + /** Returns the packed `0xAARRGGBB` integer if all four channels are single points, or null. */ + public fun toArgbOrNull(): Int? { + if (!isPoint) return null + return RemoteColorMath.argb(alpha.min, red.min, green.min, blue.min) + } + + /** Component-wise channel union over alternative runtime colors. */ + public fun union(other: ColorInterval): ColorInterval = + ColorInterval( + alpha = alpha.union(other.alpha), + red = red.union(other.red), + green = green.union(other.green), + blue = blue.union(other.blue), + ) + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is ColorInterval) return false + return alpha == other.alpha && + red == other.red && + green == other.green && + blue == other.blue + } + + override fun hashCode(): Int { + var result = alpha.hashCode() + result = 31 * result + red.hashCode() + result = 31 * result + green.hashCode() + result = 31 * result + blue.hashCode() + return result + } + + override fun toString(): String = + "ColorInterval(alpha=$alpha, red=$red, green=$green, blue=$blue)" + + public companion object { + /** Full 8-bit unsigned channel range `[0, 255]`. */ + public val BYTE_RANGE: IntInterval = IntInterval(0, 255) + + /** Conservative interval covering every possible 32-bit ARGB color. */ + public val UNKNOWN: ColorInterval = + ColorInterval(BYTE_RANGE, BYTE_RANGE, BYTE_RANGE, BYTE_RANGE) + + /** Returns an exact point [ColorInterval] for a packed 32-bit `0xAARRGGBB` color int. */ + @JvmStatic + public fun constant(argb: Int): ColorInterval = + ColorInterval( + alpha = IntInterval.point(RemoteColorMath.alpha(argb)), + red = IntInterval.point(RemoteColorMath.red(argb)), + green = IntInterval.point(RemoteColorMath.green(argb)), + blue = IntInterval.point(RemoteColorMath.blue(argb)), + ) + } +} + +/** + * Pure-Kotlin abstract transfer functions for RemoteCompose string and color operations. + * + * Uses [TextFromFloatFormatter] and [RemoteColorMath] directly so both document-level and + * expression-level interval analyzers share identical semantics without depending on `remote-core`. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public object StringAndColorIntervalOps { + private const val EXACT_INT_FLOAT_LIMIT = FloatInterval.MAX_EXACT_INT.toFloat() + + /** + * Computes a conservative [StringSummary] for a `TextFromFloat` formatting operation. + * + * @param valueInterval Conservative bounding range of the input float value. + * @param digitsBefore Maximum digits before the decimal point. + * @param digitsAfter Maximum digits after the decimal point. + * @param flags Wire formatting flags from `TextFromFloatFlags`. + * @return Exact constant summary for point intervals, or a conservative length/ASCII summary. + */ + @JvmStatic + public fun summarizeTextFromFloat( + valueInterval: FloatInterval, + digitsBefore: Int, + digitsAfter: Int, + flags: Int, + ): StringSummary { + if ( + valueInterval.isEmpty || + digitsBefore !in 0..TextFromFloatFormatter.MAX_DIGITS || + digitsAfter !in 0..TextFromFloatFormatter.MAX_DIGITS + ) { + return StringSummary.UNKNOWN + } + val spec = TextFromFloatFormatter.parseSpec(digitsBefore, digitsAfter, flags) + if (valueInterval.isPoint) { + return StringSummary.constant(TextFromFloatFormatter.format(valueInterval.min, spec)) + } + if (spec.isFullFormat) { + return StringSummary(length = IntInterval(3, 16), isAsciiOnly = true) + } + + val signWidth = if (!spec.isLegacyMode && spec.isNegativeParentheses) 2 else 1 + val signMin = if (valueInterval.max < 0f) signWidth else 0 + val signMax = if (valueInterval.min < 0f) signWidth else 0 + val mag = valueInterval.abs() + val effMagMin = if (mag.minInclusive || mag.min.isInfinite()) mag.min else mag.min.nextUp() + val effMagMax = + if (mag.maxInclusive || mag.max.isInfinite()) mag.max else mag.max.nextDown() + if (effMagMin > effMagMax) return StringSummary.UNKNOWN + val bodyLen = + if (spec.isLegacyMode) { + computeLegacyFloatLengthRange(effMagMin, effMagMax, spec) + } else { + computeStandardFloatLengthRange(effMagMin, effMagMax, spec) + } + return StringSummary( + length = + IntInterval.fromLongBounds( + signMin.toLong() + bodyLen.min.toLong(), + signMax.toLong() + bodyLen.max.toLong(), + ), + isAsciiOnly = true, + ) + } + + /** Computes a conservative [StringSummary] for string concatenation (`TextMerge`). */ + @JvmStatic + public fun summarizeTextMerge(s1: StringSummary, s2: StringSummary): StringSummary { + val constant = + if (s1.constantValue != null && s2.constantValue != null) { + s1.constantValue + s2.constantValue + } else { + null + } + return StringSummary( + length = (s1.length + s2.length).clampToRange(0, IntInterval.MAX_BOUND), + isAsciiOnly = s1.isAsciiOnly && s2.isAsciiOnly, + constantValue = constant, + ) + } + + /** Computes a conservative [StringSummary] for a `TextTransform` case or trim operation. */ + @JvmStatic + public fun summarizeTextTransform( + src: StringSummary, + start: FloatInterval, + len: FloatInterval, + operation: Int, + ): StringSummary { + val sub = summarizeSubstring(src = src, start = start, len = len) + return when (operation) { + TextTransformOperation.CAPITALIZE, + TextTransformOperation.UPPERCASE_FIRST_CHAR -> + StringSummary(length = sub.length, isAsciiOnly = sub.isAsciiOnly) + TextTransformOperation.TO_LOWERCASE, + TextTransformOperation.TO_UPPERCASE -> { + if (sub.isAsciiOnly) { + StringSummary(length = sub.length, isAsciiOnly = false) + } else { + val minLen = if (sub.length.min > 0) 1 else 0 + val maxLen = (sub.length * IntInterval.point(3)).max + StringSummary(length = IntInterval(minLen, maxLen), isAsciiOnly = false) + } + } + TextTransformOperation.TRIM -> { + val constant = sub.constantValue?.trim { it <= ' ' } + if (constant != null) { + StringSummary.constant(constant) + } else { + StringSummary( + length = IntInterval(0, sub.length.max), + isAsciiOnly = sub.isAsciiOnly, + ) + } + } + else -> StringSummary.UNKNOWN + } + } + + /** Computes a conservative [StringSummary] for a `TextSubtext` slice `(start, len)`. */ + @JvmStatic + public fun summarizeSubstring( + src: StringSummary, + start: FloatInterval, + len: FloatInterval, + ): StringSummary { + if (src.constantValue != null && start.isPoint && len.isPoint) { + val s = start.min.toInt() + val end = + if (len.min == -1f) src.constantValue.length else (start.min + len.min).toInt() + if (s in 0..src.constantValue.length && end in s..src.constantValue.length) { + return StringSummary.constant(src.constantValue.substring(s, end)) + } + } + + val srcLen = src.length + val maxOut = if (srcLen.hasFiniteMax) srcLen.max else IntInterval.MAX_BOUND + val startInt = SlotInterval.fromFloat(start).toIntInterval() + val clampedStart = startInt.clampToRange(0, maxOut) + val remainingLen = (srcLen - clampedStart).clampToRange(0, maxOut) + val remainderLen = if (-1f in len) remainingLen else null + val finiteLen = + summarizeFiniteSubstringLength(start, len, clampedStart, remainingLen, maxOut) + + val combinedLen = + when { + remainderLen != null && finiteLen != null -> remainderLen.union(finiteLen) + remainderLen != null -> remainderLen + finiteLen != null -> finiteLen + else -> IntInterval(0, maxOut) + } + return StringSummary(length = combinedLen, isAsciiOnly = src.isAsciiOnly) + } + + /** Computes a conservative [ColorInterval] for normalized `[0, 1]` ARGB float inputs. */ + @JvmStatic + public fun summarizeColorArgb( + alpha: FloatInterval, + red: FloatInterval, + green: FloatInterval, + blue: FloatInterval, + ): ColorInterval { + if (alpha.isPoint && red.isPoint && green.isPoint && blue.isPoint) { + return ColorInterval.constant( + RemoteColorMath.toArgb(alpha.min, red.min, green.min, blue.min) + ) + } + val qa = quantizeColorChannel(alpha) + val qr = quantizeColorChannel(red) + val qg = quantizeColorChannel(green) + val qb = quantizeColorChannel(blue) + + val bOk = qb.min >= 0 && qb.max <= 255 + val gOk = bOk && qg.min >= 0 && qg.max <= 255 + val rOk = gOk && qr.min >= 0 && qr.max <= 255 + val aOk = rOk && qa.min >= 0 && qa.max <= 255 + return ColorInterval( + alpha = if (aOk) qa else ColorInterval.BYTE_RANGE, + red = if (rOk) qr else ColorInterval.BYTE_RANGE, + green = if (gOk) qg else ColorInterval.BYTE_RANGE, + blue = if (bOk) qb else ColorInterval.BYTE_RANGE, + ) + } + + /** + * Computes a conservative [ColorInterval] for an HSV color expression with fixed alpha byte. + */ + @JvmStatic + public fun summarizeColorHsv( + alpha: Int, + hue: FloatInterval, + saturation: FloatInterval, + value: FloatInterval, + ): ColorInterval { + val alphaByte = alpha and 0xFF + val alphaInterval = IntInterval.point(alphaByte) + if (hue.isPoint && saturation.isPoint && value.isPoint) { + val rgb = RemoteColorMath.hsvToRgb(hue.min, saturation.min, value.min) + val argb = (alphaByte shl 24) or (rgb and 0x00FFFFFF) + return ColorInterval.constant(argb) + } + if ( + !hue.isEmpty && + !saturation.isEmpty && + !value.isEmpty && + hue.min >= 0f && + saturation.min >= 0f && + saturation.max <= 1f && + value.min >= 0f && + value.max <= 1f + ) { + val rgbMax = (0.5f + 255f * value.max).toInt().coerceIn(0, 255) + val hueAlwaysInUnit = + hue.min >= 0f && (hue.max < 1f || (hue.max == 1f && !hue.maxInclusive)) + val rgbMin = + if (hueAlwaysInUnit) { + (0.5f + 255f * value.min * (1f - saturation.max)).toInt().coerceIn(0, 255) + } else { + 0 + } + val ch = IntInterval(min(rgbMin, rgbMax), max(rgbMin, rgbMax)) + return ColorInterval(alpha = alphaInterval, red = ch, green = ch, blue = ch) + } + return ColorInterval( + alpha = alphaInterval, + red = ColorInterval.BYTE_RANGE, + green = ColorInterval.BYTE_RANGE, + blue = ColorInterval.BYTE_RANGE, + ) + } + + /** + * Computes a conservative [ColorInterval] for `RemoteColorMath.interpolateColor(c1, c2, t)`. + * + * Samples the exact adjacent floats `0f.nextUp()` and `1f.nextDown()` when `[t]` touches `0f` + * or `1f` to capture gamma-2.2 round-trip truncation dips inside `(0, 1)`. + * + * @param c1 Start color interval. + * @param c2 End color interval. + * @param t Interpolation fraction interval; values outside `[0, 1]` or empty widen to + * [ColorInterval.UNKNOWN]. + * @return Conservative bounding [ColorInterval]. + */ + @JvmStatic + public fun summarizeColorTween( + c1: ColorInterval, + c2: ColorInterval, + t: FloatInterval, + ): ColorInterval { + if ( + t.isEmpty || + t.min.isNaN() || + t.max.isNaN() || + t.min < 0f || + t.max > 1f || + c1.alpha.isEmpty || + c1.red.isEmpty || + c1.green.isEmpty || + c1.blue.isEmpty || + c2.alpha.isEmpty || + c2.red.isEmpty || + c2.green.isEmpty || + c2.blue.isEmpty + ) { + return ColorInterval.UNKNOWN + } + if (t.isPoint) { + if (t.min == 0f) return c1 + if (t.min == 1f) return c2 + } + val c1Min = RemoteColorMath.argb(c1.alpha.min, c1.red.min, c1.green.min, c1.blue.min) + val c1Max = RemoteColorMath.argb(c1.alpha.max, c1.red.max, c1.green.max, c1.blue.max) + val c2Min = RemoteColorMath.argb(c2.alpha.min, c2.red.min, c2.green.min, c2.blue.min) + val c2Max = RemoteColorMath.argb(c2.alpha.max, c2.red.max, c2.green.max, c2.blue.max) + + fun evalFourCorners(tau: Float): ColorInterval = + ColorInterval.constant(RemoteColorMath.interpolateColor(c1Min, c2Min, tau)) + .union(ColorInterval.constant(RemoteColorMath.interpolateColor(c1Min, c2Max, tau))) + .union(ColorInterval.constant(RemoteColorMath.interpolateColor(c1Max, c2Min, tau))) + .union(ColorInterval.constant(RemoteColorMath.interpolateColor(c1Max, c2Max, tau))) + + val result = + if (t.isPoint) { + evalFourCorners(t.min) + } else { + var acc = evalFourCorners(t.min).union(evalFourCorners(t.max)) + if (t.min == 0f && t.max > 0f) { + acc = acc.union(evalFourCorners(min(t.max, 0f.nextUp()))) + } + if (t.max == 1f && t.min < 1f) { + acc = acc.union(evalFourCorners(max(t.min, 1f.nextDown()))) + } + acc + } + + // For any channel where c1 or c2 is non-point, IEEE-754 float32 rounding in + // c1f + t * (c2f - c1f) is non-monotonic at 1-ULP boundaries (error <= 2^-23, well below + // the minimum 8-bit channel step), which can shift an interior channel output by at most 1. + fun widenIfNonPoint( + ch: IntInterval, + c1Ch: IntInterval, + c2Ch: IntInterval, + ): IntInterval = + if (c1Ch.isPoint && c2Ch.isPoint) { + ch + } else { + IntInterval(ch.min - 1, ch.max + 1).clampToRange(0, 255) + } + + return ColorInterval( + alpha = widenIfNonPoint(result.alpha, c1.alpha, c2.alpha), + red = widenIfNonPoint(result.red, c1.red, c2.red), + green = widenIfNonPoint(result.green, c1.green, c2.green), + blue = widenIfNonPoint(result.blue, c1.blue, c2.blue), + ) + } + + /** Computes a conservative [FloatInterval] for a [ColorAttributeType] extraction on [color]. */ + @JvmStatic + public fun summarizeColorAttribute(color: ColorInterval, attributeType: Int): FloatInterval { + val attrType = attributeType and 0xFF + color.toArgbOrNull()?.let { exactArgb -> + return summarizeExactColorAttribute(exactArgb, attrType) + } + return when (attrType) { + ColorAttributeType.RED -> FloatInterval(color.red.min / 255f, color.red.max / 255f) + ColorAttributeType.GREEN -> + FloatInterval(color.green.min / 255f, color.green.max / 255f) + ColorAttributeType.BLUE -> FloatInterval(color.blue.min / 255f, color.blue.max / 255f) + ColorAttributeType.ALPHA -> + FloatInterval(color.alpha.min / 255f, color.alpha.max / 255f) + ColorAttributeType.BRIGHTNESS -> + FloatInterval( + maxOf(color.red.min, color.green.min, color.blue.min) / 255f, + maxOf(color.red.max, color.green.max, color.blue.max) / 255f, + ) + ColorAttributeType.SATURATION -> summarizeSaturationInterval(color) + ColorAttributeType.HUE -> + FloatInterval(0f, 1f, minInclusive = true, maxInclusive = false) + else -> FloatInterval.UNBOUNDED + } + } + + /** Component-wise color multiplication over normalized `[0, 1]` channels. */ + @JvmStatic + public fun summarizeColorMultiply(c1: ColorInterval, c2: ColorInterval): ColorInterval = + summarizeColorArgb( + alpha = + FloatInterval(c1.alpha.min / 255f, c1.alpha.max / 255f) * + FloatInterval(c2.alpha.min / 255f, c2.alpha.max / 255f), + red = + FloatInterval(c1.red.min / 255f, c1.red.max / 255f) * + FloatInterval(c2.red.min / 255f, c2.red.max / 255f), + green = + FloatInterval(c1.green.min / 255f, c1.green.max / 255f) * + FloatInterval(c2.green.min / 255f, c2.green.max / 255f), + blue = + FloatInterval(c1.blue.min / 255f, c1.blue.max / 255f) * + FloatInterval(c2.blue.min / 255f, c2.blue.max / 255f), + ) + + private fun computeLegacyFloatLengthRange( + effMagMin: Float, + effMagMax: Float, + spec: FloatFormatSpec, + ): IntInterval { + val minRawDigits = decimalDigitCount(effMagMin.toInt().toLong()) + val maxRawDigits = + if (effMagMax.isInfinite() || effMagMax >= Int.MAX_VALUE.toFloat()) { + 10 + } else { + decimalDigitCount(effMagMax.toInt().toLong()) + } + val intMin = + if (spec.padBefore != TextFromFloatFormatter.PAD_NONE) { + spec.digitsBefore + } else { + min(minRawDigits, spec.digitsBefore) + } + val intMax = + if (spec.padBefore != TextFromFloatFormatter.PAD_NONE) { + spec.digitsBefore + } else { + min(maxRawDigits, spec.digitsBefore) + } + val fracMin = + when { + spec.digitsAfter == 0 -> 0 + spec.padAfter != TextFromFloatFormatter.PAD_NONE -> 1 + spec.digitsAfter + else -> 1 + } + val fracMax = if (spec.digitsAfter == 0) 0 else 1 + spec.digitsAfter + return IntInterval(intMin + fracMin, intMax + fracMax) + } + + private fun computeStandardFloatLengthRange( + effMagMin: Float, + effMagMax: Float, + spec: FloatFormatSpec, + ): IntInterval { + val roundingOffset = if (spec.isRounding) roundingFactor(spec.digitsAfter) else 0f + val minRounded = effMagMin + roundingOffset + val maxRounded = + if (effMagMax.isInfinite()) Float.POSITIVE_INFINITY else effMagMax + roundingOffset + + val minRawDigits = longMagnitudeDigitCount(minRounded) + val maxRawDigits = longMagnitudeDigitCount(maxRounded) + val iLenMin = groupedDigitLength(min(spec.digitsBefore, minRawDigits), spec.grouping) + val iLenMax = groupedDigitLength(min(spec.digitsBefore, maxRawDigits), spec.grouping) + + var minTotal = Int.MAX_VALUE + var maxTotal = 0 + for (iLen in iLenMin..iLenMax) { + val finalIntLen = + if (spec.padBefore != TextFromFloatFormatter.PAD_NONE) { + spec.digitsBefore + } else { + min(iLen, spec.digitsBefore) + } + val trimAfter = if (iLen + spec.digitsAfter > 9) max(1, 9 - iLen) else spec.digitsAfter + val effAfter = + if (spec.padAfter == TextFromFloatFormatter.PAD_NONE) { + trimAfter + } else { + spec.digitsAfter + } + val fracMin = + when { + effAfter == 0 -> 0 + spec.padAfter != TextFromFloatFormatter.PAD_NONE -> 1 + effAfter + else -> 2 + } + val fracMax = if (effAfter == 0) 0 else 1 + effAfter + minTotal = min(minTotal, finalIntLen + fracMin) + maxTotal = max(maxTotal, finalIntLen + fracMax) + } + return if (minTotal > maxTotal) IntInterval.NON_NEGATIVE + else IntInterval(minTotal, maxTotal) + } + + private fun longMagnitudeDigitCount(value: Float): Int = + if (value.isInfinite() || value >= Long.MAX_VALUE.toFloat()) { + 19 + } else { + decimalDigitCount(value.toLong()) + } + + private fun summarizeFiniteSubstringLength( + start: FloatInterval, + len: FloatInterval, + clampedStart: IntInterval, + remainingLen: IntInterval, + maxOut: Int, + ): IntInterval? { + if (len.isPoint && len.min == -1f) return null + val clampedEnd = SlotInterval.fromFloat(start + len).toIntInterval().clampToRange(0, maxOut) + val fromDiff = clampedEnd - clampedStart + val rawLen = + if ( + !start.isUnbounded && + !len.isUnbounded && + start.min >= 0f && + len.min >= 0f && + start.max.toDouble() + len.max.toDouble() + 1.0 <= + EXACT_INT_FLOAT_LIMIT.toDouble() + ) { + val fromLen = + IntInterval.fromLongBounds(floor(len.min).toLong(), ceil(len.max).toLong() + 1L) + val intersected = fromLen.intersect(fromDiff) + if (intersected.isEmpty) fromDiff else intersected + } else { + fromDiff + } + return rawLen.clampToRange(0, maxOut).min(remainingLen) + } + + private fun quantizeColorChannel(channel: FloatInterval): IntInterval { + val scaled = channel * FloatInterval.point(255f) + FloatInterval.point(0.5f) + return SlotInterval.fromFloat(scaled).toIntInterval() + } + + private fun summarizeExactColorAttribute(exactArgb: Int, attrType: Int): FloatInterval { + val exact = + when (attrType) { + ColorAttributeType.HUE -> RemoteColorMath.hue(exactArgb) + ColorAttributeType.SATURATION -> RemoteColorMath.saturation(exactArgb) + ColorAttributeType.BRIGHTNESS -> RemoteColorMath.brightness(exactArgb) + ColorAttributeType.RED -> RemoteColorMath.red(exactArgb) / 255f + ColorAttributeType.GREEN -> RemoteColorMath.green(exactArgb) / 255f + ColorAttributeType.BLUE -> RemoteColorMath.blue(exactArgb) / 255f + ColorAttributeType.ALPHA -> RemoteColorMath.alpha(exactArgb) / 255f + else -> return FloatInterval.UNBOUNDED + } + return FloatInterval.point(exact) + } + + private fun summarizeSaturationInterval(c: ColorInterval): FloatInterval { + val maxLo = maxOf(c.red.min, c.green.min, c.blue.min) + val maxHi = maxOf(c.red.max, c.green.max, c.blue.max) + val minLo = minOf(c.red.min, c.green.min, c.blue.min) + val minHi = minOf(c.red.max, c.green.max, c.blue.max) + val allCanBeEqual = !c.red.intersect(c.green).intersect(c.blue).isEmpty + val minSat = + if (allCanBeEqual || maxLo <= minHi || maxLo == 0) { + 0f + } else { + (((maxLo / 255f) - (minHi / 255f)) / (maxLo / 255f)).coerceIn(0f, 1f) + } + val maxSat = + if (maxHi == 0) { + 0f + } else { + (((maxHi / 255f) - (minLo / 255f)) / (maxHi / 255f)).coerceIn(0f, 1f) + } + return FloatInterval(min(minSat, maxSat), max(minSat, maxSat)) + } + + private fun decimalDigitCount(nonNegativeValue: Long): Int { + var v = nonNegativeValue + if (v <= 0L) return 1 + var digits = 0 + while (v > 0L) { + v /= 10L + digits++ + } + return digits + } + + private fun groupedDigitLength(rawDigits: Int, grouping: Int): Int { + if (rawDigits <= 0) return 0 + return when (grouping) { + TextFromFloatFormatter.GROUPING_BY3 -> rawDigits + (rawDigits - 1) / 3 + TextFromFloatFormatter.GROUPING_BY4 -> rawDigits + (rawDigits - 1) / 4 + TextFromFloatFormatter.GROUPING_BY32 -> + if (rawDigits <= 3) rawDigits else rawDigits + 1 + (rawDigits - 4) / 2 + else -> rawDigits + } + } + + private fun roundingFactor(afterDigits: Int): Float { + var factor = 0.5f + // Float32 subnormals underflow to 0f after 45 divisions by 10. + repeat(min(afterDigits.coerceAtLeast(0), 46)) { factor /= 10.0f } + return factor + } +}
diff --git a/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/TriState.kt b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/TriState.kt new file mode 100644 index 0000000..7b15dd4 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/main/java/androidx/compose/remote/document/intervals/TriState.kt
@@ -0,0 +1,336 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.annotation.RestrictTo +import androidx.compose.remote.document.ConditionType + +/** + * Result of statically evaluating a boolean predicate or relational comparison over intervals. + * + * [TRUE] and [FALSE] indicate that the predicate holds or fails across every reachable runtime + * assignment in the analyzed intervals; [UNKNOWN] indicates that both outcomes are possible or an + * input interval is empty. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public enum class TriState { + /** The predicate provably evaluates to `true` across all reachable runtime states. */ + TRUE, + + /** The predicate provably evaluates to `false` across all reachable runtime states. */ + FALSE, + + /** The predicate's runtime truth value cannot be statically proven constant. */ + UNKNOWN; + + /** Returns the boolean value if statically determined, or `null` for [UNKNOWN]. */ + public val booleanValueOrNull: Boolean? + get() = + when (this) { + TRUE -> true + FALSE -> false + UNKNOWN -> null + } + + /** Three-valued logical negation. */ + public operator fun not(): TriState = + when (this) { + TRUE -> FALSE + FALSE -> TRUE + UNKNOWN -> UNKNOWN + } + + /** + * Three-valued logical conjunction (Kleene strong logic). + * + * @param other The right-hand [TriState] operand. + * @return [FALSE] if either operand is [FALSE], [TRUE] if both are [TRUE], else [UNKNOWN]. + */ + public infix fun and(other: TriState): TriState = + when { + this == FALSE || other == FALSE -> FALSE + this == TRUE && other == TRUE -> TRUE + else -> UNKNOWN + } + + /** + * Three-valued logical disjunction (Kleene strong logic). + * + * @param other The right-hand [TriState] operand. + * @return [TRUE] if either operand is [TRUE], [FALSE] if both are [FALSE], else [UNKNOWN]. + */ + public infix fun or(other: TriState): TriState = + when { + this == TRUE || other == TRUE -> TRUE + this == FALSE && other == FALSE -> FALSE + else -> UNKNOWN + } + + /** Converts this [TriState] to an integer interval (`[1, 1]`, `[0, 0]`, or `[0, 1]`). */ + public fun toIntInterval(): IntInterval = + when (this) { + TRUE -> IntInterval.point(1) + FALSE -> IntInterval.ZERO + UNKNOWN -> IntInterval(0, 1) + } + + /** Converts this [TriState] to a float interval (`[1f, 1f]`, `[0f, 0f]`, or `[0f, 1f]`). */ + public fun toFloatInterval(): FloatInterval = + when (this) { + TRUE -> FloatInterval.point(1f) + FALSE -> FloatInterval.ZERO + UNKNOWN -> FloatInterval.UNIT + } + + public companion object { + /** + * Converts a known [Boolean] into [TRUE] or [FALSE]. + * + * @param value The concrete boolean value. + * @return [TRUE] if [value] is `true`, otherwise [FALSE]. + */ + @JvmStatic public fun of(value: Boolean): TriState = if (value) TRUE else FALSE + } +} + +/** + * Relational comparison operator aligned with [ConditionType] wire opcodes (`TYPE_EQ`..`TYPE_GTE`). + * + * Encapsulates logical negation, operand flipping, reflexive self-comparison, and sound interval + * narrowing for both [FloatInterval] and [IntInterval]. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public enum class IntervalComparison(public val wireCode: Int) { + /** Equality (`a == b`). */ + EQ(ConditionType.TYPE_EQ.toInt()), + + /** Inequality (`a != b`). */ + NEQ(ConditionType.TYPE_NEQ.toInt()), + + /** Strict less-than (`a < b`). */ + LT(ConditionType.TYPE_LT.toInt()), + + /** Less-than-or-equal (`a <= b`). */ + LTE(ConditionType.TYPE_LTE.toInt()), + + /** Strict greater-than (`a > b`). */ + GT(ConditionType.TYPE_GT.toInt()), + + /** Greater-than-or-equal (`a >= b`). */ + GTE(ConditionType.TYPE_GTE.toInt()); + + /** Returns the logical negation of this comparison (`!(a op b)`). */ + public fun negate(): IntervalComparison = + when (this) { + EQ -> NEQ + NEQ -> EQ + LT -> GTE + LTE -> GT + GT -> LTE + GTE -> LT + } + + /** Returns the comparison obtained by swapping operands (`a op b` <=> `b flipped a`). */ + public fun flip(): IntervalComparison = + when (this) { + EQ -> EQ + NEQ -> NEQ + LT -> GT + LTE -> GTE + GT -> LT + GTE -> LTE + } + + /** Returns the result of `x op x` for any finite, non-NaN deterministic value `x`. */ + public fun selfComparisonResult(): TriState = + when (this) { + EQ, + LTE, + GTE -> TriState.TRUE + NEQ, + LT, + GT -> TriState.FALSE + } + + /** Narrows a pair of [FloatInterval] operands `(a, b)` assuming `a <this> b` holds. */ + public fun narrowFloat(a: FloatInterval, b: FloatInterval): Pair<FloatInterval, FloatInterval> { + if (a.isEmpty || b.isEmpty) return Pair(FloatInterval.EMPTY, FloatInterval.EMPTY) + return when (this) { + EQ -> a.intersect(b).let { Pair(it, it) } + NEQ -> Pair(a, b) + LT -> + Pair( + upperBound(a, b.max, inclusive = false), + lowerBound(b, a.min, inclusive = false), + ) + LTE -> Pair(upperBound(a, b.max, b.maxInclusive), lowerBound(b, a.min, a.minInclusive)) + GT -> + Pair( + lowerBound(a, b.min, inclusive = false), + upperBound(b, a.max, inclusive = false), + ) + GTE -> Pair(lowerBound(a, b.min, b.minInclusive), upperBound(b, a.max, a.maxInclusive)) + } + } + + /** Narrows a pair of [IntInterval] operands `(a, b)` assuming `a <this> b` holds. */ + public fun narrowInt(a: IntInterval, b: IntInterval): Pair<IntInterval, IntInterval> { + if (a.isEmpty || b.isEmpty) return Pair(IntInterval.EMPTY, IntInterval.EMPTY) + val minL = Int.MIN_VALUE.toLong() + val maxL = Int.MAX_VALUE.toLong() + return when (this) { + EQ -> a.intersect(b).let { Pair(it, it) } + NEQ -> Pair(a, b) + LT -> + Pair( + if (b.hasFiniteMax) { + a.intersect(IntInterval.fromLongBounds(minL, b.max.toLong() - 1L)) + } else { + a + }, + if (a.hasFiniteMin) { + b.intersect(IntInterval.fromLongBounds(a.min.toLong() + 1L, maxL)) + } else { + b + }, + ) + LTE -> + Pair( + if (b.hasFiniteMax) { + a.intersect(IntInterval.fromLongBounds(minL, b.max.toLong())) + } else { + a + }, + if (a.hasFiniteMin) { + b.intersect(IntInterval.fromLongBounds(a.min.toLong(), maxL)) + } else { + b + }, + ) + GT -> + Pair( + if (b.hasFiniteMin) { + a.intersect(IntInterval.fromLongBounds(b.min.toLong() + 1L, maxL)) + } else { + a + }, + if (a.hasFiniteMax) { + b.intersect(IntInterval.fromLongBounds(minL, a.max.toLong() - 1L)) + } else { + b + }, + ) + GTE -> + Pair( + if (b.hasFiniteMin) { + a.intersect(IntInterval.fromLongBounds(b.min.toLong(), maxL)) + } else { + a + }, + if (a.hasFiniteMax) { + b.intersect(IntInterval.fromLongBounds(minL, a.max.toLong())) + } else { + b + }, + ) + } + } + + /** + * Evaluates `x <this> 0` across all `Long` values in `[lo, hi]`, returning [TriState.UNKNOWN] + * if `lo > hi`. + */ + public fun compareLongRangeAgainstZero(lo: Long, hi: Long): TriState { + if (lo > hi) return TriState.UNKNOWN + return when (this) { + EQ -> + when { + lo == 0L && hi == 0L -> TriState.TRUE + hi < 0L || lo > 0L -> TriState.FALSE + else -> TriState.UNKNOWN + } + NEQ -> + when { + hi < 0L || lo > 0L -> TriState.TRUE + lo == 0L && hi == 0L -> TriState.FALSE + else -> TriState.UNKNOWN + } + LT -> + when { + hi < 0L -> TriState.TRUE + lo >= 0L -> TriState.FALSE + else -> TriState.UNKNOWN + } + LTE -> + when { + hi <= 0L -> TriState.TRUE + lo > 0L -> TriState.FALSE + else -> TriState.UNKNOWN + } + GT -> + when { + lo > 0L -> TriState.TRUE + hi <= 0L -> TriState.FALSE + else -> TriState.UNKNOWN + } + GTE -> + when { + lo >= 0L -> TriState.TRUE + hi < 0L -> TriState.FALSE + else -> TriState.UNKNOWN + } + } + } + + public companion object { + /** + * Returns the [IntervalComparison] corresponding to [ConditionType] [wireCode], or `null` + * for non-relational types (such as [ConditionType.TYPE_CHANGED]). + */ + @JvmStatic + public fun fromWireCode(wireCode: Int): IntervalComparison? = + when (wireCode) { + ConditionType.TYPE_EQ.toInt() -> EQ + ConditionType.TYPE_NEQ.toInt() -> NEQ + ConditionType.TYPE_LT.toInt() -> LT + ConditionType.TYPE_LTE.toInt() -> LTE + ConditionType.TYPE_GT.toInt() -> GT + ConditionType.TYPE_GTE.toInt() -> GTE + else -> null + } + + private fun upperBound(x: FloatInterval, max: Float, inclusive: Boolean): FloatInterval = + x.intersect( + FloatInterval( + Float.NEGATIVE_INFINITY, + max, + minInclusive = true, + maxInclusive = inclusive, + ) + ) + + private fun lowerBound(x: FloatInterval, min: Float, inclusive: Boolean): FloatInterval = + x.intersect( + FloatInterval( + min, + Float.POSITIVE_INFINITY, + minInclusive = inclusive, + maxInclusive = true, + ) + ) + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/IntervalOptimizerTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/IntervalOptimizerTest.kt new file mode 100644 index 0000000..1eefd41 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/IntervalOptimizerTest.kt
@@ -0,0 +1,802 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.core.RemoteContext +import androidx.compose.remote.creation.compose.state.MutableRemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteColor +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteEnum +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteFloatArray +import androidx.compose.remote.creation.compose.state.RemoteFloatOperationKey +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteIntArray +import androidx.compose.remote.creation.compose.state.RemoteNamedCacheKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateIdKey +import androidx.compose.remote.creation.compose.state.RemoteString +import androidx.compose.remote.creation.compose.state.RemoteStringArray +import androidx.compose.remote.creation.compose.state.RemoteValue +import androidx.compose.remote.creation.compose.state.abs +import androidx.compose.remote.creation.compose.state.animatedRemoteFloat +import androidx.compose.remote.creation.compose.state.atan +import androidx.compose.remote.creation.compose.state.atan2 +import androidx.compose.remote.creation.compose.state.cacheKey +import androidx.compose.remote.creation.compose.state.ceil +import androidx.compose.remote.creation.compose.state.clamp +import androidx.compose.remote.creation.compose.state.cos +import androidx.compose.remote.creation.compose.state.exp +import androidx.compose.remote.creation.compose.state.floor +import androidx.compose.remote.creation.compose.state.lerp +import androidx.compose.remote.creation.compose.state.max +import androidx.compose.remote.creation.compose.state.min +import androidx.compose.remote.creation.compose.state.rand +import androidx.compose.remote.creation.compose.state.rb +import androidx.compose.remote.creation.compose.state.rf +import androidx.compose.remote.creation.compose.state.ri +import androidx.compose.remote.creation.compose.state.round +import androidx.compose.remote.creation.compose.state.rs +import androidx.compose.remote.creation.compose.state.selectIfGe +import androidx.compose.remote.creation.compose.state.selectIfGt +import androidx.compose.remote.creation.compose.state.selectIfLt +import androidx.compose.remote.creation.compose.state.sign +import androidx.compose.remote.creation.compose.state.sin +import androidx.compose.remote.document.AnimationEasing +import androidx.compose.remote.document.NanEncoding +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.packAnimationSpec +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class IntervalOptimizerTest { + + @Test + fun prunesDeadSelectsAndComparisonsAcrossAllTypes() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val n = RemoteInt.createNamedRemoteInt("n", 0) + val c1 = RemoteColor.createNamedRemoteColor("c1", 0xFFFF0000.toInt()) + val c2 = RemoteColor.createNamedRemoteColor("c2", 0xFF0000FF.toInt()) + val env = + MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(10f, 20f)) + .withNamedInt("n", IntInterval(5, 10)) + + // Boolean.select across Float, Int, String, Boolean, Color + assertThat(x.isGreaterThan(5f.rf).select(x + 1f.rf, 999f.rf).optimizeWithIntervals(env)) + .isEqualTo(x + 1f.rf) + assertThat(n.isLessThan(0.ri).select(1.ri, n + 2.ri).optimizeWithIntervals(env)) + .isEqualTo(n + 2.ri) + assertThat(n.isGreaterThan(4.ri).select("yes".rs, "no".rs).optimizeWithIntervals(env)) + .isEqualTo("yes".rs) + assertThat( + n.isGreaterThan(4.ri) + .select(RemoteBoolean(true), x.isLessThan(15f.rf)) + .optimizeWithIntervals(env) + ) + .isEqualTo(RemoteBoolean(true)) + assertThat(n.isGreaterThan(4.ri).select(c1, c2).optimizeWithIntervals(env)).isEqualTo(c1) + assertThat(n.isLessThan(0.ri).select(c1, c2).optimizeWithIntervals(env)).isEqualTo(c2) + + // selectIf* with affine self-differences + assertThat(selectIfLt(x, x + 1f.rf, x * 2f.rf, 0f.rf).optimizeWithIntervals(env)) + .isEqualTo(x * 2f.rf) + assertThat(selectIfGe(n + 2.ri, n, n + 1.ri, 0.ri).optimizeWithIntervals(env)) + .isEqualTo(n + 1.ri) + + // String selectIf* for both float and int comparisons + assertThat(selectIfLt(x, 100f.rf, "small".rs, "big".rs).optimizeWithIntervals(env)) + .isEqualTo("small".rs) + assertThat(selectIfGt(n, 100.ri, "huge".rs, "ok".rs).optimizeWithIntervals(env)) + .isEqualTo("ok".rs) + + // Provable comparison folding + assertThat(x.isGreaterThan(0f.rf).optimizeWithIntervals(env)).isEqualTo(RemoteBoolean(true)) + assertThat(n.isLessThan(0.ri).optimizeWithIntervals(env)).isEqualTo(RemoteBoolean(false)) + } + + @Test + fun pathSensitiveBranchRefinementIsolatesMemoAcrossBranchesAndRoot() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val n = RemoteInt.createNamedRemoteInt("n", 0) + val env = + MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(0f, 100f)) + .withNamedInt("n", IntInterval(0, 10)) + + // Nested ladder prunes dead inner arms in both branches + val ladder = + x.isLessThan(10f.rf) + .select( + ifTrue = x.isLessThan(20f.rf).select(1f.rf, 999f.rf), + ifFalse = x.isLessThan(5f.rf).select(888f.rf, 4f.rf), + ) + val optimizedLadder = ladder.optimizeWithIntervals(env) + assertThat(optimizedLadder).isEqualTo(x.isLessThan(10f.rf).select(1f.rf, 4f.rf)) + + // Equality branch folds n inside true branch without affecting false branch + val eqSelect = n.isEqualTo(5.ri).select(n + 10.ri, n + 20.ri) + assertThat(eqSelect.optimizeWithIntervals(env)) + .isEqualTo(n.isEqualTo(5.ri).select(15.ri, n + 20.ri)) + + // Shared DAG node must NOT leak true-branch refinement into sibling branch or outer root + val shared = x.isLessThan(20f.rf).select(1f.rf, 2f.rf) + val combined = x.isLessThan(10f.rf).select(shared + 10f.rf, shared + 20f.rf) + shared + val optimizedCombined = combined.optimizeWithIntervals(env) + assertThat(optimizedCombined) + .isEqualTo(x.isLessThan(10f.rf).select(11f.rf, shared + 20f.rf) + shared) + } + + @Test + fun purityAndIeee754AndNamedBooleanGuards() { + val unboundedX = RemoteFloat.createNamedRemoteFloat("u", 0f) + val boundedX = RemoteFloat.createNamedRemoteFloat("b", 0f) + val nonFoldableId = 42 + val nonFoldableZeroId = 43 + val env = + MapIntervalEnvironment.EMPTY.withNamedFloat("b", FloatInterval(0f, 10f)) + .withNamedFloat("five", FloatInterval.point(5f)) + .withNamedFloat("one", FloatInterval.point(1f)) + .withNamedFloat("zero", FloatInterval.point(0f)) + .withStateIdFloat(nonFoldableId, FloatInterval.point(7f)) + .withNonFoldableStateId(nonFoldableId) + .withStateIdFloat(nonFoldableZeroId, FloatInterval.point(0f)) + .withNonFoldableStateId(nonFoldableZeroId) + + // Unbounded IEEE-754 absorption must NOT constant-fold OR trigger comparison/select/math + // simplifications (e.g., NaN/Infinity absorbed by FloatInterval.clamp or + // FloatInterval.times) + val unboundedClamp = clamp(value = unboundedX, min = 5f.rf, max = 5f.rf) + assertThat(unboundedClamp.optimizeWithIntervals(env).hasConstantValue).isFalse() + val nonFoldableZero = RemoteFloat(NanEncoding.asNan(nonFoldableZeroId)) + val unboundedZeroProd = unboundedX * nonFoldableZero + assertThat(unboundedZeroProd.optimizeWithIntervals(env).hasConstantValue).isFalse() + assertThat(unboundedZeroProd.isEqualTo(0f.rf).optimizeWithIntervals(env).hasConstantValue) + .isFalse() + assertThat( + unboundedZeroProd + .isEqualTo(0f.rf) + .select(1f.rf, 2f.rf) + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + assertThat( + selectIfLt(unboundedZeroProd, 1f.rf, 1f.rf, 2f.rf) + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + assertThat(min(unboundedZeroProd, 10f.rf).optimizeWithIntervals(env)) + .isEqualTo(min(unboundedZeroProd, 10f.rf)) + assertThat(clamp(0f.rf, 10f.rf, unboundedZeroProd).optimizeWithIntervals(env)) + .isEqualTo(clamp(0f.rf, 10f.rf, unboundedZeroProd)) + val c1 = RemoteColor.createNamedRemoteColor("c1", 0xFFFF0000.toInt()) + val c2 = RemoteColor.createNamedRemoteColor("c2", 0xFF0000FF.toInt()) + assertThat(lerp(c1, c2, unboundedZeroProd).optimizeWithIntervals(env)) + .isEqualTo(lerp(c1, c2, unboundedZeroProd)) + assertThat(lerp(c1, c1, unboundedX).optimizeWithIntervals(env)) + .isEqualTo(lerp(c1, c1, unboundedX)) + // Trig, rem, div, sign, exp, and abs on unbounded inputs can return NaN at runtime and + // must NOT fold comparisons or enum lookups + assertThat(sin(unboundedX).isLessThan(2f.rf).optimizeWithIntervals(env).hasConstantValue) + .isFalse() + assertThat(cos(unboundedX).isLessThan(2f.rf).optimizeWithIntervals(env).hasConstantValue) + .isFalse() + assertThat( + (unboundedX % 5f.rf).isLessThan(10f.rf).optimizeWithIntervals(env).hasConstantValue + ) + .isFalse() + assertThat(atan(unboundedX).isLessThan(2f.rf).optimizeWithIntervals(env).hasConstantValue) + .isFalse() + assertThat( + atan2(unboundedX, 1f.rf) + .isLessThan(4f.rf) + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + assertThat( + sign(unboundedX) + .isLessThanOrEqualTo(1f.rf) + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + assertThat( + exp(-abs(unboundedX)) + .isLessThanOrEqualTo(1f.rf) + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + assertThat( + (2f.rf / max(unboundedX, 1f.rf)) + .isLessThanOrEqualTo(2f.rf) + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + assertThat( + abs(unboundedX) + .isGreaterThanOrEqualTo(0f.rf) + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + assertThat( + RemoteEnum(clamp(unboundedX, 1f.rf, 1f.rf).toRemoteInt(), TestEnum.entries) + .toRemoteString() + .optimizeWithIntervals(env) + .hasConstantValue + ) + .isFalse() + + // Bounded operands DO fold cleanly + assertThat(clamp(value = boundedX, min = 5f.rf, max = 5f.rf).optimizeWithIntervals(env)) + .isEqualTo(5f.rf) + + // Non-deterministic & stateful expressions must never fold + assertThat(rand().optimizeWithIntervals(env).hasConstantValue).isFalse() + assertThat((rand() - rand()).optimizeWithIntervals(env).hasConstantValue).isFalse() + + val spec = packAnimationSpec(duration = 0.5f, type = AnimationEasing.CUBIC_STANDARD) + assertThat(animatedRemoteFloat(5f.rf, spec).optimizeWithIntervals(env).hasConstantValue) + .isFalse() + + // forceRemote = true reference must not fold + val forced = (boundedX - boundedX).createReference(forceRemote = true) + assertThat(forced.optimizeWithIntervals(env).hasConstantValue).isFalse() + + // MutableRemoteFloat (RemoteStateInstanceKey) must not fold + val mutableFloat = MutableRemoteFloat(5f) + assertThat(mutableFloat.optimizeWithIntervals(env)).isSameInstanceAs(mutableFloat) + + // nonFoldableStateIds must not fold + val nonFoldableState = RemoteFloat(NanEncoding.asNan(nonFoldableId)) + assertThat(nonFoldableState.optimizeWithIntervals(env).hasConstantValue).isFalse() + + // Named RemoteBoolean probe: only fold exact 0f / 1f, never non-boolean float 5f + val namedFive = RemoteBoolean.createNamedRemoteBoolean("five", false) + assertThat(namedFive.optimizeWithIntervals(env).hasConstantValue).isFalse() + assertThat(RemoteBoolean.createNamedRemoteBoolean("one", false).optimizeWithIntervals(env)) + .isEqualTo(RemoteBoolean(true)) + assertThat(RemoteBoolean.createNamedRemoteBoolean("zero", true).optimizeWithIntervals(env)) + .isEqualTo(RemoteBoolean(false)) + } + + @Test + fun trappingOperandsInsideEagerBranchesUseUnrefinedEnvironment() { + val n = RemoteInt.createNamedRemoteInt("n", 0) + val x = RemoteInt.createNamedRemoteInt("x", 0) + val env = + MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(-5, 5)) + .withNamedInt("x", IntInterval(0, 100)) + + // Inside n > 0 branch, max(n, 1) is the divisor of x / max(n, 1). + // Because select evaluates both arms eagerly, max(n, 1) must NOT be simplified to n + // (which would divide by 0 when n == 0)! + val guardedDiv = n.isGreaterThan(0.ri).select(x / max(n, 1.ri), 0.ri) + val optimizedDiv = guardedDiv.optimizeWithIntervals(env) + assertThat(optimizedDiv).isEqualTo(guardedDiv) + + // Same for array index inside an eager branch: clamp(n, 0, 1) must NOT drop its lower + // clamp bound using the branch-only assumption n >= 0! + val arr = RemoteFloatArray(10f, 20f, 30f) + val guardedLookup = n.isGreaterThanOrEqualTo(0.ri).select(arr[clamp(0.ri, 1.ri, n)], 0f.rf) + val optimizedLookup = guardedLookup.optimizeWithIntervals(env) + assertThat(optimizedLookup).isEqualTo(guardedLookup) + + // Same for Substring indices inside an eager branch: max(n, 0) must NOT simplify to n! + val s = RemoteString.createNamedRemoteString("s", "abcdef") + val guardedSub = + n.isGreaterThanOrEqualTo(0.ri).select(s.substring(max(n, 0.ri), 2.ri), "".rs) + assertThat(guardedSub.optimizeWithIntervals(env)).isEqualTo(guardedSub) + } + + @Test + fun simplifiesRangeMathAndLiteralArrayOperations() { + val pos = RemoteFloat.createNamedRemoteFloat("pos", 0f) + val neg = RemoteFloat.createNamedRemoteFloat("neg", 0f) + val posInt = RemoteInt.createNamedRemoteInt("posInt", 0) + val negInt = RemoteInt.createNamedRemoteInt("negInt", 0) + val idx01 = RemoteInt.createNamedRemoteInt("idx01", 0) + val idxPoint = RemoteInt.createNamedRemoteInt("idxPoint", 0) + val floatIdx01 = RemoteFloat.createNamedRemoteFloat("fIdx01", 0f) + val env = + MapIntervalEnvironment.EMPTY.withNamedFloat("pos", FloatInterval(2f, 8f)) + .withNamedFloat("neg", FloatInterval(-8f, -2f)) + .withNamedInt("posInt", IntInterval(2, 8)) + .withNamedInt("negInt", IntInterval(-8, -2)) + .withNamedInt("idx01", IntInterval(0, 1)) + .withNamedInt("idxPoint", IntInterval.point(1)) + .withNamedFloat("fIdx01", FloatInterval(0f, 1.5f)) + + // Float abs, min, max, clamp, integer-valued rounding + assertThat(abs(pos).optimizeWithIntervals(env)).isEqualTo(pos) + assertThat(abs(neg).optimizeWithIntervals(env)).isEqualTo(-neg) + assertThat(min(pos, pos + 5f.rf).optimizeWithIntervals(env)).isEqualTo(pos) + assertThat(max(pos, 1f.rf).optimizeWithIntervals(env)).isEqualTo(pos) + assertThat(clamp(value = pos, min = 0f.rf, max = 10f.rf).optimizeWithIntervals(env)) + .isEqualTo(pos) + assertThat(clamp(value = pos, min = 10f.rf, max = 20f.rf).optimizeWithIntervals(env)) + .isEqualTo(10f.rf) + assertThat(clamp(value = pos, min = 0f.rf, max = 1f.rf).optimizeWithIntervals(env)) + .isEqualTo(1f.rf) + assertThat(clamp(value = pos, min = 0f.rf, max = 5f.rf).optimizeWithIntervals(env)) + .isEqualTo(min(pos, 5f.rf)) + assertThat(clamp(value = pos, min = 5f.rf, max = 10f.rf).optimizeWithIntervals(env)) + .isEqualTo(max(pos, 5f.rf)) + assertThat(floor(posInt.toRemoteFloat()).optimizeWithIntervals(env)) + .isEqualTo(posInt.toRemoteFloat()) + assertThat(ceil(posInt.toRemoteFloat()).optimizeWithIntervals(env)) + .isEqualTo(posInt.toRemoteFloat()) + assertThat(round(posInt.toRemoteFloat()).optimizeWithIntervals(env)) + .isEqualTo(posInt.toRemoteFloat()) + + // OP_ROUND clamps floats >= 2^31 to Int.MAX_VALUE: + // - For [3e9f, 4e9f], round(floor(huge)) must NOT strip to floor(huge); it folds to the + // clamped constant Int.MAX_VALUE.toFloat(). + // - For [0f, 4e9f] (non-constant after clamping), round(floor(straddle)) stays intact. + val hugeFloat = RemoteFloat.createNamedRemoteFloat("huge", 0f) + val straddleHuge = RemoteFloat.createNamedRemoteFloat("straddleHuge", 0f) + val hugeEnv = + MapIntervalEnvironment.EMPTY.withNamedFloat("huge", FloatInterval(3e9f, 4e9f)) + .withNamedFloat("straddleHuge", FloatInterval(0f, 4e9f)) + val floorHuge = floor(hugeFloat) + assertThat(round(floorHuge).optimizeWithIntervals(hugeEnv)) + .isEqualTo(Int.MAX_VALUE.toFloat().rf) + val floorStraddle = floor(straddleHuge) + assertThat(round(floorStraddle).optimizeWithIntervals(hugeEnv)) + .isEqualTo(round(floorStraddle)) + assertThat(floor(floorHuge).optimizeWithIntervals(hugeEnv)).isEqualTo(floorHuge) + assertThat(ceil(floorHuge).optimizeWithIntervals(hugeEnv)).isEqualTo(floorHuge) + + // Color Tween and TweenInt endpoint & identical-color simplification + val c1 = RemoteColor.createNamedRemoteColor("c1", 0xFFFF0000.toInt()) + val c2 = RemoteColor.createNamedRemoteColor("c2", 0xFF0000FF.toInt()) + val tZero = RemoteFloat.createNamedRemoteFloat("tZero", 0f) + val tOne = RemoteFloat.createNamedRemoteFloat("tOne", 1f) + val tMid = RemoteFloat.createNamedRemoteFloat("tMid", 0.5f) + val colorEnv = + MapIntervalEnvironment.EMPTY.withNamedFloat("tZero", FloatInterval.point(0f)) + .withNamedFloat("tOne", FloatInterval.point(1f)) + .withNamedFloat("tMid", FloatInterval(0f, 1f)) + assertThat(lerp(c1, c2, tZero).optimizeWithIntervals(colorEnv)).isEqualTo(c1) + assertThat(lerp(c1, c2, tOne).optimizeWithIntervals(colorEnv)).isEqualTo(c2) + assertThat(lerp(c1, c1, tMid).optimizeWithIntervals(colorEnv)).isEqualTo(c1) + assertThat( + lerp(0xFFFF0000.toInt(), 0xFF0000FF.toInt(), tZero).optimizeWithIntervals(colorEnv) + ) + .isEqualTo(RemoteColor(0xFFFF0000.toInt())) + assertThat( + lerp(0xFFFF0000.toInt(), 0xFF0000FF.toInt(), tOne).optimizeWithIntervals(colorEnv) + ) + .isEqualTo(RemoteColor(0xFF0000FF.toInt())) + + // Int abs, min, max, clamp + assertThat(posInt.absoluteValue.optimizeWithIntervals(env)).isEqualTo(posInt) + assertThat(negInt.absoluteValue.optimizeWithIntervals(env)).isEqualTo(-negInt) + assertThat(min(posInt, 100.ri).optimizeWithIntervals(env)).isEqualTo(posInt) + assertThat(max(posInt, 0.ri).optimizeWithIntervals(env)).isEqualTo(posInt) + assertThat(clamp(0.ri, 10.ri, posInt).optimizeWithIntervals(env)).isEqualTo(posInt) + assertThat(clamp(0.ri, 5.ri, posInt).optimizeWithIntervals(env)) + .isEqualTo(min(posInt, 5.ri)) + + // Literal array point-index folding (with dynamic elements optimized bottom-up) + val dynArr = RemoteFloatArray(listOf(pos, abs(pos))) + assertThat(dynArr[idxPoint].optimizeWithIntervals(env)).isEqualTo(pos) + + val intArr = RemoteIntArray(listOf(posInt, posInt + 1.ri)) + assertThat(intArr[idxPoint].optimizeWithIntervals(env)).isEqualTo(posInt + 1.ri) + + val strArr = RemoteStringArray(listOf("AM".rs, "PM".rs)) + assertThat(strArr[idxPoint].optimizeWithIntervals(env)).isEqualTo("PM".rs) + + // 2-element literal array lowering to select on [0, 1] + assertThat(dynArr[idx01].optimizeWithIntervals(env)) + .isEqualTo(pos) // identical after abs(pos) -> pos! + val distinctFloatArr = RemoteFloatArray(listOf(pos, neg)) + assertThat(distinctFloatArr[idx01].optimizeWithIntervals(env)) + .isEqualTo(RemoteBoolean.fromRemoteInt(idx01).select(neg, pos)) + assertThat(distinctFloatArr[floatIdx01].optimizeWithIntervals(env)) + .isEqualTo(selectIfLt(floatIdx01, 1f.rf, pos, neg)) + assertThat(intArr[idx01].optimizeWithIntervals(env)) + .isEqualTo(RemoteBoolean.fromRemoteInt(idx01).select(posInt + 1.ri, posInt)) + assertThat(intArr[floatIdx01].optimizeWithIntervals(env)) + .isEqualTo(floatIdx01.isLessThan(1f.rf).select(posInt, posInt + 1.ri)) + assertThat(strArr[idx01].optimizeWithIntervals(env)) + .isEqualTo(RemoteBoolean.fromRemoteInt(idx01).select("PM".rs, "AM".rs)) + + // Branch-narrowed RemoteInt index into RemoteFloatArray picks up intOverride + val nBranch = RemoteInt.createNamedRemoteInt("nBranch", 0) + val branchArrEnv = MapIntervalEnvironment.EMPTY.withNamedInt("nBranch", IntInterval(0, 1)) + val branchArrExpr = nBranch.isEqualTo(1.ri).select(distinctFloatArr[nBranch], 0f.rf) + assertThat(branchArrExpr.optimizeWithIntervals(branchArrEnv)) + .isEqualTo(nBranch.isEqualTo(1.ri).select(neg, 0f.rf)) + + // Config switches independently disable each optimization phase + val noLower = IntervalOptimizerConfig(lowerTwoElementArraysToSelect = false) + assertThat(strArr[idx01].optimizeWithIntervals(env, noLower)).isEqualTo(strArr[idx01]) + assertThat(strArr[idxPoint].optimizeWithIntervals(env, noLower)).isEqualTo("PM".rs) + + val noFoldArr = + IntervalOptimizerConfig( + foldArrayGets = false, + lowerTwoElementArraysToSelect = false, + foldPointConstants = false, + ) + assertThat(distinctFloatArr[idxPoint].optimizeWithIntervals(env, noFoldArr)) + .isEqualTo(distinctFloatArr[idxPoint]) + val onlyFoldArr = + IntervalOptimizerConfig( + foldArrayGets = true, + lowerTwoElementArraysToSelect = false, + foldPointConstants = false, + ) + assertThat(distinctFloatArr[idxPoint].optimizeWithIntervals(env, onlyFoldArr)) + .isEqualTo(neg) + + val noPrune = + IntervalOptimizerConfig( + pruneTernaries = false, + foldComparisons = false, + foldPointConstants = false, + ) + val deadSel = posInt.isGreaterThan(0.ri).select(posInt, negInt) + assertThat(deadSel.optimizeWithIntervals(env, noPrune)).isEqualTo(deadSel) + + val noRefine = IntervalOptimizerConfig(refineTernaryBranches = false) + val refSel = idx01.isEqualTo(1.ri).select(idx01 + 10.ri, 0.ri) + assertThat(refSel.optimizeWithIntervals(env, noRefine)).isEqualTo(refSel) + + val noFoldCmp = IntervalOptimizerConfig(foldComparisons = false, foldPointConstants = false) + assertThat(posInt.isGreaterThan(0.ri).optimizeWithIntervals(env, noFoldCmp)) + .isEqualTo(posInt.isGreaterThan(0.ri)) + + val noRangeMath = IntervalOptimizerConfig(simplifyRangeMath = false) + assertThat(abs(pos).optimizeWithIntervals(env, noRangeMath)).isEqualTo(abs(pos)) + + val noPointFold = IntervalOptimizerConfig(foldPointConstants = false) + assertThat((pos - pos).optimizeWithIntervals(env, noPointFold)).isEqualTo(pos - pos) + } + + @Test + fun namedBooleanRefinementAndCustomRuleHooks() { + // Path-sensitive refinement of a named RemoteBoolean folds inner uses via intOverride + val flag = RemoteBoolean.createNamedRemoteBoolean("flag", false) + val flagEnv = MapIntervalEnvironment.EMPTY.withNamedInt("flag", IntInterval(0, 1)) + val selfSelect = flag.select(flag, RemoteBoolean(false)) + assertThat(selfSelect.optimizeWithIntervals(flagEnv)) + .isEqualTo(flag.select(RemoteBoolean(true), RemoteBoolean(false))) + val nestedFlagSelect = flag.select(flag.select(10.ri, 20.ri), 30.ri) + assertThat(nestedFlagSelect.optimizeWithIntervals(flagEnv)) + .isEqualTo(flag.select(10.ri, 30.ri)) + + // First-class boolean connective & identity simplification + val n = RemoteInt.createNamedRemoteInt("n", 0) + val nEnv = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(0, 10)) + assertThat((n.isGreaterThan(5.ri) and n.isLessThan(3.ri)).optimizeWithIntervals(nEnv)) + .isEqualTo(RemoteBoolean(false)) + assertThat( + (n.isGreaterThan(5.ri) or n.isLessThanOrEqualTo(5.ri)).optimizeWithIntervals(nEnv) + ) + .isEqualTo(RemoteBoolean(true)) + assertThat((flag and true.rb).optimizeWithIntervals(flagEnv)).isEqualTo(flag) + assertThat((flag or false.rb).optimizeWithIntervals(flagEnv)).isEqualTo(flag) + assertThat((flag xor true.rb).optimizeWithIntervals(flagEnv)).isEqualTo(!flag) + + // Non-canonical RemoteBoolean(pos) must NOT fold to RemoteBoolean(true) (which would + // corrupt toRemoteInt()), while select still prunes dead false branch. + val pos = RemoteInt.createNamedRemoteInt("pos", 1) + val negPoint = RemoteInt.createNamedRemoteInt("negPoint", -1) + val twoPoint = RemoteInt.createNamedRemoteInt("twoPoint", 2) + val posEnv = + MapIntervalEnvironment.EMPTY.withNamedInt("pos", IntInterval(1, 5)) + .withNamedInt("negPoint", IntInterval.point(-1)) + .withNamedInt("twoPoint", IntInterval.point(2)) + val nonCanonical = RemoteBoolean.fromRemoteInt(pos) + assertThat(nonCanonical.toRemoteInt().optimizeWithIntervals(posEnv)).isEqualTo(pos) + assertThat(nonCanonical.select(10f.rf, 20f.rf).optimizeWithIntervals(posEnv)) + .isEqualTo(10f.rf) + // Point negative or > 1 RemoteInt wrapped in RemoteBoolean must NOT fold via reconstruct + // into RemoteBoolean(true) or prune negative conditions to the true branch! + val negBool = RemoteBoolean.fromRemoteInt(negPoint) + assertThat(negBool.optimizeWithIntervals(posEnv).hasConstantValue).isFalse() + assertThat(negBool.select(10f.rf, 20f.rf).optimizeWithIntervals(posEnv).hasConstantValue) + .isFalse() + assertThat(negBool.toRemoteInt().optimizeWithIntervals(posEnv)).isEqualTo((-1).ri) + val twoBool = RemoteBoolean.fromRemoteInt(twoPoint) + assertThat(twoBool.optimizeWithIntervals(posEnv).hasConstantValue).isFalse() + assertThat(twoBool.toRemoteInt().optimizeWithIntervals(posEnv)).isEqualTo(2.ri) + assertThat(twoBool.select(10f.rf, 20f.rf).optimizeWithIntervals(posEnv)).isEqualTo(10f.rf) + + // First-class RemoteEnum folding and ordinal/toRemoteString simplification + val idxPoint = RemoteInt.createNamedRemoteInt("idxPoint", 0) + val enumEnv = + MapIntervalEnvironment.EMPTY.withNamedInt("idxPoint", IntInterval.point(1)) + .withNamedInt("n", IntInterval(0, 2)) + assertThat(RemoteEnum(idxPoint, TestEnum.entries).optimizeWithIntervals(enumEnv)) + .isEqualTo(RemoteEnum(TestEnum.B)) + assertThat(RemoteEnum(n + 1.ri, TestEnum.entries).ordinal.optimizeWithIntervals(enumEnv)) + .isEqualTo(n + 1.ri) + assertThat( + RemoteEnum(idxPoint, TestEnum.entries) + .toRemoteString() + .optimizeWithIntervals(enumEnv) + ) + .isEqualTo("B".rs) + + // Custom rule triggers on named RemoteBoolean + val forceFlagTrue = + object : IntervalOptimizationRule { + override fun rewriteAfterChildren( + value: RemoteValue<*>, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = + if ( + value is RemoteBoolean && + (value.cacheKey as? RemoteNamedCacheKey)?.name == "flag" + ) { + RemoteBoolean(true) + } else { + null + } + } + assertThat(flag.optimizeWithIntervals(flagEnv, rules = listOf(forceFlagTrue))) + .isEqualTo(RemoteBoolean(true)) + + // rewriteBeforeChildren & optimizeUnrefined hooks + MutableRemoteFloat subtype preservation + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val env = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(-5f, 5f)) + var sawRefinedBranch = false + val beforeRule = + object : IntervalOptimizationRule { + override fun rewriteBeforeChildren( + value: RemoteValue<*>, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + if (context.isInRefinedBranch && value == abs(x)) { + sawRefinedBranch = true + return context.optimizeUnrefined(value) + } + return null + } + } + val branchWithAbs = x.isGreaterThan(0f.rf).select(abs(x), 0f.rf) + assertThat(branchWithAbs.optimizeWithIntervals(env, rules = listOf(beforeRule))) + .isEqualTo(branchWithAbs) + assertThat(sawRefinedBranch).isTrue() + + val mutable = MutableRemoteFloat(1f) + val badRuleReturningImmutable = + object : IntervalOptimizationRule { + override fun rewriteAfterChildren( + value: RemoteValue<*>, + context: IntervalOptimizationContext, + ): RemoteValue<*>? = if (value === mutable) 2f.rf else null + } + assertThat(mutable.optimizeWithIntervals(env, rules = listOf(badRuleReturningImmutable))) + .isSameInstanceAs(mutable) + } + + @Test + fun supportsCustomRulesAndCustomRemoteOperations() { + // 1. Custom IntervalOptimizationRule lowering continuous seconds to discrete seconds + val clockDowngradeRule = + object : IntervalOptimizationRule { + override fun rewriteAfterChildren( + value: RemoteValue<*>, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + val idKey = value.cacheKey as? RemoteStateIdKey ?: return null + if (idKey.id == RemoteContext.ID_CONTINUOUS_SEC && value is RemoteFloat) { + return RemoteFloat(RemoteContext.FLOAT_TIME_IN_SEC) + } + return null + } + } + + val continuous = RemoteFloat(RemoteContext.FLOAT_CONTINUOUS_SEC) + val expr = floor(continuous + 1f.rf) + val optimized = expr.optimizeWithIntervals(rules = listOf(clockDowngradeRule)) + // After lowering continuous -> FLOAT_TIME_IN_SEC (which is integer-valued and finite!), + // floor(time_in_sec + 1f) also simplifies away the redundant floor()! + assertThat(optimized).isEqualTo(RemoteFloat(RemoteContext.FLOAT_TIME_IN_SEC) + 1f.rf) + + // 2. Custom RemoteIntervalOperation plugs directly into evaluator & optimizer with zero + // changes + // to IntervalOptimizer + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val env = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(2f, 4f)) + val customExpr = + RemoteFloat( + constantValueOrNull = null, + cacheKey = RemoteOperationCacheKey.create(TestCustomOp.IdentityIfPositive, x), + arrayProvider = { FloatArray(0) }, + ) + assertThat(customExpr.optimizeWithIntervals(env)).isEqualTo(x) + + // When x can be negative, custom op stays intact + val mixedEnv = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(-4f, 4f)) + assertThat(customExpr.optimizeWithIntervals(mixedEnv)).isEqualTo(customExpr) + } + + @Test + fun hasBoundedFloatOperands_handlesDeepSubtreesAndMemoizesWithoutOverflow() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val u = RemoteFloat.createNamedRemoteFloat("u", 0f) + val env = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(1f, 2f)) + val evaluator = RemoteValueIntervalEvaluator(env) + + // Build a 30-level deep addition chain with no ops requiring bounded float operands. + var deepPositive: RemoteFloat = x + repeat(30) { deepPositive = deepPositive + 1f.rf } + assertThat(IntervalOptimizer.hasBoundedFloatOperands(deepPositive.cacheKey, evaluator)) + .isTrue() + // abs(deepPositive) simplifies away abs() cleanly. + assertThat(abs(deepPositive).optimizeWithIntervals(env)).isEqualTo(deepPositive) + + // Nested op requiring bounded float operands must still block folding on unbounded input. + val nestedUnboundedClamp = clamp(value = u, min = 5f.rf, max = 5f.rf) + 1f.rf + assertThat( + IntervalOptimizer.hasBoundedFloatOperands(nestedUnboundedClamp.cacheKey, evaluator) + ) + .isFalse() + assertThat(nestedUnboundedClamp.optimizeWithIntervals(env).hasConstantValue).isFalse() + + // Combining a shallow bounded op with a deep sibling succeeds cleanly. + val boundedOpWithDeepSibling = (x * 2f.rf) + deepPositive + assertThat( + IntervalOptimizer.hasBoundedFloatOperands( + boundedOpWithDeepSibling.cacheKey, + evaluator, + ) + ) + .isTrue() + + // Iterative traversal handles very deep chains (2000 levels) without stack overflow. + var veryDeepBounded: RemoteStateCacheKey = x.cacheKey + repeat(2000) { + veryDeepBounded = + RemoteOperationCacheKey( + RemoteFloatOperationKey.Plus, + listOf(veryDeepBounded, RemoteConstantCacheKey(1f)), + ) + } + assertThat(IntervalOptimizer.hasBoundedFloatOperands(veryDeepBounded, evaluator)).isTrue() + + var veryDeepUnbounded: RemoteStateCacheKey = (u * 2f.rf).cacheKey + repeat(2000) { + veryDeepUnbounded = + RemoteOperationCacheKey( + RemoteFloatOperationKey.Plus, + listOf(veryDeepUnbounded, RemoteConstantCacheKey(1f)), + ) + } + assertThat(IntervalOptimizer.hasBoundedFloatOperands(veryDeepUnbounded, evaluator)) + .isFalse() + } + + @Test + fun soundnessRegressions_nonCanonicalBooleanUnboundedBranchRefinementAndMemoIsolation() { + // 1. Non-canonical RemoteBoolean operations (Not/And/Or/Xor) must NOT fold to 1 (true), + // which would corrupt .toRemoteInt() (e.g. (!2) = 3, not 1) and isEqualTo(true.rb). + val two = RemoteInt.createNamedRemoteInt("two", 2) + val three = RemoteInt.createNamedRemoteInt("three", 3) + val nonCanonEnv = + MapIntervalEnvironment.EMPTY.withNamedInt("two", IntInterval.point(2)) + .withNamedInt("three", IntInterval.point(3)) + val twoBool = RemoteBoolean.fromRemoteInt(two) + val threeBool = RemoteBoolean.fromRemoteInt(three) + assertThat((!twoBool).optimizeWithIntervals(nonCanonEnv).hasConstantValue).isFalse() + assertThat((!twoBool).toRemoteInt().optimizeWithIntervals(nonCanonEnv)).isEqualTo(3.ri) + assertThat((threeBool and twoBool).optimizeWithIntervals(nonCanonEnv).hasConstantValue) + .isFalse() + assertThat((threeBool and twoBool).toRemoteInt().optimizeWithIntervals(nonCanonEnv)) + .isEqualTo(2.ri) + + // 2. Branch refinement must not narrow sibling x under sin(unboundedU) < x + val u = RemoteFloat.createNamedRemoteFloat("u", 0f) + val x = RemoteFloat.createNamedRemoteFloat("x", 5f) + val branchEnv = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(0f, 10f)) + val selectWithUnboundedSin = + selectIfLt( + sin(u), + x, + 1f.rf, + x.isLessThanOrEqualTo(1f.rf).select(1f.rf, 999f.rf), + ) + assertThat(selectWithUnboundedSin.optimizeWithIntervals(branchEnv).hasConstantValue) + .isFalse() + + // 3. Distinct RemoteEnum types wrapping the same RemoteInt do not collide in optimizeMemo + val idx = RemoteInt.createNamedRemoteInt("idx", 1) + val enumEnv = MapIntervalEnvironment.EMPTY.withNamedInt("idx", IntInterval.point(1)) + val opt = IntervalOptimizer(enumEnv) + val e1 = RemoteEnum(idx, TestEnum.entries) + val e2 = RemoteEnum(idx, OtherTestEnum.entries) + assertThat(opt.optimize(e1).constantValueOrNull).isEqualTo(TestEnum.B) + assertThat(opt.optimize(e2).constantValueOrNull).isEqualTo(OtherTestEnum.Y) + + // 4. Custom IntervalEnvironment implementing only intForNamed folds named RemoteBoolean + val flag = RemoteBoolean.createNamedRemoteBoolean("flag", false) + val customIntEnv = + object : IntervalEnvironment { + override fun intForNamed(key: RemoteNamedCacheKey): IntInterval = + if (key.name == "flag") IntInterval.point(1) else IntInterval.UNBOUNDED + } + assertThat(flag.optimizeWithIntervals(customIntEnv)).isEqualTo(RemoteBoolean(true)) + + // 5. Pruned ternary branch invokes rewriteAfterChildren at most once per node + var afterCount = 0 + val countRule = + object : IntervalOptimizationRule { + override fun rewriteAfterChildren( + value: RemoteValue<*>, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + if (value == x) afterCount++ + return null + } + } + val cond = RemoteBoolean.createNamedRemoteBoolean("cond", true) + val prunedSel = cond.select(x, x) + prunedSel.optimizeWithIntervals(branchEnv, rules = listOf(countRule)) + assertThat(afterCount).isEqualTo(1) + } + + private enum class TestEnum { + A, + B, + C, + } + + private enum class OtherTestEnum { + X, + Y, + } + + private enum class TestCustomOp : RemoteIntervalOperation { + IdentityIfPositive { + override fun toDebugString(args: List<RemoteStateCacheKey>): String = + "idIfPos(${args[0].toDebugString()})" + + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = evaluator.evalFloatKey(key.args[0]) + + override fun simplifyWithIntervals( + value: RemoteValue<*>, + key: RemoteOperationCacheKey, + context: IntervalOptimizationContext, + ): RemoteValue<*>? { + val r = context.evaluator.evalFloatKey(key.args[0]) + return if (!r.isEmpty && !r.isUnbounded && r.min > 0f) { + key.args[0].getOrCreateValueOrNull() + } else { + null + } + } + } + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteAffineAndRefinementTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteAffineAndRefinementTest.kt new file mode 100644 index 0000000..9d762aa --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteAffineAndRefinementTest.kt
@@ -0,0 +1,454 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteEnum +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteNamedCacheKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.abs +import androidx.compose.remote.creation.compose.state.cacheKey +import androidx.compose.remote.creation.compose.state.intValue +import androidx.compose.remote.creation.compose.state.lerp +import androidx.compose.remote.creation.compose.state.mad +import androidx.compose.remote.creation.compose.state.rand +import androidx.compose.remote.creation.compose.state.rb +import androidx.compose.remote.creation.compose.state.rf +import androidx.compose.remote.creation.compose.state.ri +import androidx.compose.remote.creation.compose.state.selectIfLt +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.IntervalComparison +import androidx.compose.remote.document.intervals.TriState +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class RemoteAffineAndRefinementTest { + + @Test + fun floatAffineCancellationAndComparisons() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val env = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(0f, 100f)) + val eval = RemoteValueIntervalEvaluator(env) + + // Exact self-cancellation: x - x == 0f + assertThat(eval.evalFloat(x - x)).isEqualTo(FloatInterval.ZERO) + + // Correlated affine comparisons + assertThat(eval.evalBoolean(x.isLessThan(x + 1f.rf))).isEqualTo(TriState.TRUE) + assertThat(eval.evalBoolean(x.isGreaterThan(x + 1f.rf))).isEqualTo(TriState.FALSE) + assertThat(eval.evalBoolean((x * 2f.rf).isGreaterThanOrEqualTo(x + x - 1f.rf))) + .isEqualTo(TriState.TRUE) + + // MAD cancellation: mad(x, 2f, -(x * 2f)) tightens near zero (within ULP error) + val madCancel = mad(x, 2f.rf, -(x * 2f.rf)) + val madRange = eval.evalFloat(madCancel) + assertThat(madRange.min).isWithin(1e-3f).of(0f) + assertThat(madRange.max).isWithin(1e-3f).of(0f) + + // Lerp cancellation: lerp(x, x + 10f, 0.5f) - x is tight around 5f (standard interval would + // be [-95f, 105f]) + val lerpDiff = lerp(x, x + 10f.rf, 0.5f.rf) - x + val lerpRange = eval.evalFloat(lerpDiff) + assertThat(lerpRange.min).isWithin(1e-3f).of(5f) + assertThat(lerpRange.max).isWithin(1e-3f).of(5f) + + // Nondeterministic rand() - rand() must NOT cancel + val randDiff = rand() - rand() + assertThat(eval.evalFloat(randDiff).isPoint).isFalse() + } + + @Test + fun intAffineCancellationAndOverflowSafety() { + val n = RemoteInt.createNamedRemoteInt("n", 0) + val env = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(0, 1000)) + val eval = RemoteValueIntervalEvaluator(env) + + assertThat(eval.evalInt(n - n)).isEqualTo(IntInterval.ZERO) + assertThat(eval.evalInt((n * 3.ri) - (n + n + n))).isEqualTo(IntInterval.ZERO) + assertThat(eval.evalBoolean((n + 2.ri).isGreaterThan(n))).isEqualTo(TriState.TRUE) + assertThat(eval.evalBoolean((n + 2.ri).isLessThan(n))).isEqualTo(TriState.FALSE) + + // Overflow near Int.MAX_VALUE must NOT prove n + 2 > n + val overflowEnv = + MapIntervalEnvironment.EMPTY.withNamedInt( + "n", + IntInterval(Int.MAX_VALUE - 1, Int.MAX_VALUE), + ) + val overflowEval = RemoteValueIntervalEvaluator(overflowEnv) + assertThat(overflowEval.evalBoolean((n + 2.ri).isGreaterThan(n))) + .isEqualTo(TriState.UNKNOWN) + } + + @Test + fun intToFloatAffineBridgeAndBackPropagation() { + val n = RemoteInt.createNamedRemoteInt("n", 0) + val env = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(0, 100)) + val eval = RemoteValueIntervalEvaluator(env) + + // Affine cancellation across Int -> Float conversion + val nf = n.toRemoteFloat() + assertThat(eval.evalFloat(nf - nf)).isEqualTo(FloatInterval.ZERO) + assertThat(eval.evalBoolean(nf.isLessThan((n + 1.ri).toRemoteFloat()))) + .isEqualTo(TriState.TRUE) + + // Back-propagation: nf < 5.5f narrows underlying int n to [0, 5] + val refinedTrue = env.refine(nf.isLessThan(5.5f.rf).cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedTrue).evalInt(n)) + .isEqualTo(IntInterval(0, 5)) + + // Negated branch: !(nf < 5.5f) => nf >= 5.5f narrows n to [6, 100] + val refinedFalse = env.refine(nf.isLessThan(5.5f.rf).cacheKey, false) + assertThat(RemoteValueIntervalEvaluator(refinedFalse).evalInt(n)) + .isEqualTo(IntInterval(6, 100)) + + // Unwrapping via .toRemoteInt() / .intValue also propagates refinement + val refinedViaIntValue = env.refine(nf.isLessThan(5.5f.rf).intValue.cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedViaIntValue).evalInt(n)) + .isEqualTo(IntInterval(0, 5)) + } + + @Test + fun pathSensitiveNestedBranchRefinement() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val env = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(0f, 100f)) + val eval = RemoteValueIntervalEvaluator(env) + + // Inside x < 10f: x < 20f is provably TRUE (selects 1f, prunes 999f). + // Inside !(x < 10f) (i.e. x >= 10f): x < 5f is provably FALSE (selects 4f, prunes 888f). + val ladder = + x.isLessThan(10f.rf) + .select( + ifTrue = x.isLessThan(20f.rf).select(1f.rf, 999f.rf), + ifFalse = x.isLessThan(5f.rf).select(888f.rf, 4f.rf), + ) + assertThat(eval.evalFloat(ladder)).isEqualTo(FloatInterval(1f, 4f)) + + // Same for selectIfLt on floats + val selectIfLadder = + selectIfLt( + x, + 10f.rf, + selectIfLt(x, 20f.rf, 1f.rf, 999f.rf), + selectIfLt(x, 5f.rf, 888f.rf, 4f.rf), + ) + assertThat(eval.evalFloat(selectIfLadder)).isEqualTo(FloatInterval(1f, 4f)) + + // Nested int selectIfLt + val n = RemoteInt.createNamedRemoteInt("n", 0) + val intEnv = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(0, 50)) + val intLadder = + selectIfLt( + n, + 10.ri, + selectIfLt(n, 20.ri, 1.ri, 500.ri), + selectIfLt(n, 5.ri, 600.ri, 4.ri), + ) + assertThat(RemoteValueIntervalEvaluator(intEnv).evalInt(intLadder)) + .isEqualTo(IntInterval(1, 4)) + } + + @Test + fun booleanConnectivesAndZeroComparisonUnwrapping() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val y = RemoteFloat.createNamedRemoteFloat("y", 0f) + val n = RemoteInt.createNamedRemoteInt("n", 0) + val m = RemoteInt.createNamedRemoteInt("m", 0) + val env = + MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(-50f, 50f)) + .withNamedFloat("y", FloatInterval(10f, 20f)) + .withNamedInt("n", IntInterval(-50, 50)) + .withNamedInt("m", IntInterval(10, 20)) + + // AND holds -> both sides refine + val andCond = x.isGreaterThanOrEqualTo(0f.rf) and x.isLessThanOrEqualTo(10f.rf) + val refinedAnd = env.refine(andCond.cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedAnd).evalFloat(x)) + .isEqualTo(FloatInterval(0f, 10f)) + + // OR does not hold -> both sides are false + val orCond = x.isLessThan(0f.rf) or x.isGreaterThan(10f.rf) + val refinedOrFalse = env.refine(orCond.cacheKey, false) + assertThat(RemoteValueIntervalEvaluator(refinedOrFalse).evalFloat(x)) + .isEqualTo(FloatInterval(0f, 10f)) + + // NOT -> flips holds + val notCond = !(x.isLessThan(5f.rf)) + val refinedNot = env.refine(notCond.cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedNot).evalFloat(x)) + .isEqualTo(FloatInterval(5f, 50f)) + + // Path-sensitive AND/OR contradiction and tautology detection + val baseEval = RemoteValueIntervalEvaluator(env) + assertThat(baseEval.evalBoolean(n.isGreaterThan(5.ri) and n.isLessThan(3.ri))) + .isEqualTo(TriState.FALSE) + assertThat(baseEval.evalBoolean(n.isGreaterThan(5.ri) or n.isLessThanOrEqualTo(5.ri))) + .isEqualTo(TriState.TRUE) + + // Boolean Equal/NotEqual against constant boolean refines underlying comparison + val eqFalse = x.isLessThan(5f.rf).isEqualTo(false.rb) + assertThat(RemoteValueIntervalEvaluator(env.refine(eqFalse.cacheKey, true)).evalFloat(x)) + .isEqualTo(FloatInterval(5f, 50f)) + + // Float zero-comparison unwrapping: (x - y) <= 0f -> x <= 20f + val diffLeZero = (x - y).isLessThanOrEqualTo(0f.rf) + val refinedDiff = env.refine(diffLeZero.cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedDiff).evalFloat(x)) + .isEqualTo(FloatInterval(-50f, 20f)) + + // Negated-plus zero-comparison unwrapping: (10f - x) <= 0f (i.e. (-x) + 10f <= 0f) -> x >= + // 10f + val constMinusX = (10f.rf - x).isLessThanOrEqualTo(0f.rf) + val refinedConstMinusX = env.refine(constMinusX.cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedConstMinusX).evalFloat(x)) + .isEqualTo(FloatInterval(10f, 50f)) + + // abs(x) <= 0f -> x == 0f + val absLeZero = abs(x).isLessThanOrEqualTo(0f.rf) + val refinedAbs = env.refine(absLeZero.cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedAbs).evalFloat(x)) + .isEqualTo(FloatInterval.ZERO) + + // Int zero-comparison unwrapping: (n - m) < 0 -> n <= 19 + val intDiffLtZero = (n - m).isLessThan(0.ri) + val refinedIntDiff = env.refine(intDiffLtZero.cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedIntDiff).evalInt(n)) + .isEqualTo(IntInterval(-50, 19)) + + // Enum ordinal affine cancellation and narrowing + val mode = RemoteEnum(n, TestMode.entries) + assertThat(baseEval.evalInt(mode.ordinal - n)).isEqualTo(IntInterval.ZERO) + val refinedEnum = env.refine(mode.ordinal.isLessThan(2.ri).cacheKey, true) + assertThat(RemoteValueIntervalEvaluator(refinedEnum).evalInt(n)) + .isEqualTo(IntInterval(-50, 1)) + } + + private enum class TestMode { + A, + B, + C, + } + + @Test + fun customIntervalEnvironmentPreservesNestedOverlays() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val y = RemoteFloat.createNamedRemoteFloat("y", 0f) + val customBase = + object : IntervalEnvironment { + override fun floatForNamed(key: RemoteNamedCacheKey): FloatInterval = + FloatInterval(0f, 100f) + } + + // Two consecutive default withFloatNarrowing calls must preserve BOTH overlays. + val cond = x.isLessThan(10f.rf) and y.isGreaterThan(80f.rf) + val refined = customBase.refine(cond.cacheKey, true) + val eval = RemoteValueIntervalEvaluator(refined) + + assertThat(eval.evalFloat(x).max).isEqualTo(10f) + assertThat(eval.evalFloat(x).maxInclusive).isFalse() + assertThat(eval.evalFloat(y).min).isEqualTo(80f) + assertThat(eval.evalFloat(y).minInclusive).isFalse() + } + + @Test + fun soundnessRegressions_xorNonBooleanUnboundedNanUlpAndOverflow() { + val n = RemoteInt.createNamedRemoteInt("n", 0) + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + + // 1. Xor with 1 on non-boolean [0, 5]: holds=true must NOT narrow n to 0 (2..5 also hold!) + val nonBoolEnv = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(0, 5)) + val xor1 = n xor 1.ri + val refinedXorTrue = nonBoolEnv.refine(xor1.cacheKey, holds = true) + assertThat(RemoteValueIntervalEvaluator(refinedXorTrue).evalInt(n)) + .isEqualTo(IntInterval(0, 5)) + // holds=false on non-negative n forces (n xor 1) == 0 -> n == 1 + val refinedXorFalse = nonBoolEnv.refine(xor1.cacheKey, holds = false) + assertThat(RemoteValueIntervalEvaluator(refinedXorFalse).evalInt(n)) + .isEqualTo(IntInterval.point(1)) + // holds=false on signed [-5, 5] must NOT force n == 1 because (-2 xor 1) == -1 <= 0 + val signedEnv = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(-5, 5)) + val refinedSignedXorFalse = signedEnv.refine(xor1.cacheKey, holds = false) + assertThat(RemoteValueIntervalEvaluator(refinedSignedXorFalse).evalInt(n)) + .isEqualTo(IntInterval(-5, 5)) + + // 2. Direct bool var refinement on signed [-5, 5] preserves negative ints under !holds + val refinedSignedFalse = signedEnv.refine(n.cacheKey, holds = false) + assertThat(RemoteValueIntervalEvaluator(refinedSignedFalse).evalInt(n)) + .isEqualTo(IntInterval(-5, 0)) + val boolEnv = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(0, 1)) + assertThat( + RemoteValueIntervalEvaluator(boolEnv.refine(n.cacheKey, holds = false)).evalInt(n) + ) + .isEqualTo(IntInterval.ZERO) + assertThat( + RemoteValueIntervalEvaluator(boolEnv.refine(n.cacheKey, holds = true)).evalInt(n) + ) + .isEqualTo(IntInterval.point(1)) + + // 3. UNBOUNDED float comparison must NOT narrow (guards against NaN entering negated arms) + val unboundedRefined = + MapIntervalEnvironment.EMPTY.refine(x.isLessThan(10f.rf).cacheKey, holds = false) + assertThat(RemoteValueIntervalEvaluator(unboundedRefined).evalFloat(x)) + .isEqualTo(FloatInterval.UNBOUNDED) + + // 4. 32-bit int mul overflow inside (MIN_BOUND, MAX_BOUND): 50_000 * 50_000 wraps! + val mulOverflowEnv = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(0, 50_000)) + val mulEval = RemoteValueIntervalEvaluator(mulOverflowEnv) + assertThat(mulEval.evalBoolean((n * 50_000.ri + 1.ri).isGreaterThan(n * 50_000.ri))) + .isEqualTo(TriState.UNKNOWN) + + // 5. Large-magnitude float ULP soundness: for x in [1e7f, 2e7f], ulp(2e7f) == 2f, so + // x + 1f == x is reachable and x + 1f > x must be UNKNOWN (not TRUE!) + val largeFloatEnv = + MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(1e7f, 2e7f)) + val largeEval = RemoteValueIntervalEvaluator(largeFloatEnv) + assertThat(largeEval.evalBoolean((x + 1f.rf).isGreaterThan(x))).isEqualTo(TriState.UNKNOWN) + + // 6. exactIntBoundsWithinFloatInterval boundary precision at +/- 2^24 + val exactLimit = 16_777_216 + assertThat( + exactIntBoundsWithinFloatInterval( + FloatInterval(-exactLimit.toFloat(), exactLimit.toFloat()) + ) + ) + .isEqualTo(IntInterval(-exactLimit - 1, exactLimit + 1)) + assertThat( + exactIntBoundsWithinFloatInterval( + FloatInterval( + -exactLimit.toFloat(), + exactLimit.toFloat(), + minInclusive = false, + maxInclusive = false, + ) + ) + ) + .isEqualTo(IntInterval(-exactLimit + 1, exactLimit - 1)) + + // 7. IntAffineForm.scale overflow on (-1L * Long.MIN_VALUE) returns null + assertThat(IntAffineForm(mapOf(n.cacheKey to -1L), 0L).scale(Long.MIN_VALUE)).isNull() + assertThat(IntAffineForm(emptyMap(), -1L).scale(Long.MIN_VALUE)).isNull() + assertThat(IntAffineForm(mapOf(n.cacheKey to Long.MIN_VALUE), 0L).scale(-1L)).isNull() + + // 8. Bitwise And/Or condition refinement requires non-negative operands (signed I_IFELSE) + val p = RemoteInt.createNamedRemoteInt("p", 0) + val two = RemoteInt.createNamedRemoteInt("two", 2) + val signedPairEnv = + MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(-5, 5)) + .withNamedInt("p", IntInterval(0, 1)) + .withNamedInt("two", IntInterval.point(2)) + val pBool = RemoteBoolean.fromRemoteInt(p) + val nBool = RemoteBoolean.fromRemoteInt(n) + // n = -2, p = 1 => (n | p) == -1 <= 0 (false under I_IFELSE), so p must NOT refine to 0! + assertThat( + RemoteValueIntervalEvaluator( + signedPairEnv.refine((nBool or pBool).cacheKey, holds = false) + ) + .evalInt(p) + ) + .isEqualTo(IntInterval(0, 1)) + assertThat( + RemoteValueIntervalEvaluator(signedPairEnv.refine((n or p).cacheKey, holds = false)) + .evalInt(p) + ) + .isEqualTo(IntInterval(0, 1)) + // n = -1, p = 1 => (n & p) == 1 > 0 (true under I_IFELSE), so n must NOT refine to > 0! + assertThat( + RemoteValueIntervalEvaluator( + signedPairEnv.refine((nBool and pBool).cacheKey, holds = true) + ) + .evalInt(n) + ) + .isEqualTo(IntInterval(-5, 5)) + assertThat( + RemoteValueIntervalEvaluator(signedPairEnv.refine((n and p).cacheKey, holds = true)) + .evalInt(n) + ) + .isEqualTo(IntInterval(-5, 5)) + + // 9. Boolean Equal/NotEqual refinement requires BOTH operands in [0, 1] + val nonCanonicalTwo = RemoteBoolean.fromRemoteInt(two) + assertThat( + RemoteValueIntervalEvaluator( + signedPairEnv.refine( + pBool.isNotEqualTo(nonCanonicalTwo).cacheKey, + holds = true, + ) + ) + .evalInt(p) + ) + .isEqualTo(IntInterval(0, 1)) + assertThat( + RemoteValueIntervalEvaluator( + signedPairEnv.refine( + nonCanonicalTwo.isNotEqualTo(pBool).cacheKey, + holds = true, + ) + ) + .evalInt(p) + ) + .isEqualTo(IntInterval(0, 1)) + + // 10. FloatAffineForm rejects NaN weights and negative errorBound + val boundedEnv = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(0f, 10f)) + val boundedEval = RemoteValueIntervalEvaluator(boundedEnv) + assertThat( + FloatAffineForm( + mapOf(AffineTerm(x.cacheKey, isInt = false) to Double.NaN), + constant = 1.0, + errorBound = 0.0, + ) + .evaluate(boundedEval) + ) + .isNull() + assertThat( + FloatAffineForm(emptyMap(), constant = 1.0, errorBound = -1.0).evaluate(boundedEval) + ) + .isNull() + + // 11. Custom bounded-range op over UNBOUNDED float must NOT narrow bounded sibling x + val unboundedU = RemoteFloat.createNamedRemoteFloat("unboundedU", 0f) + val customKey = RemoteOperationCacheKey.create(CustomBoundedOp.Bounded, unboundedU) + val refinedFromCustom = + boundedEnv.narrowComparison( + IntervalComparison.GTE, + customKey, + x.cacheKey, + asInt = false, + ) + assertThat(RemoteValueIntervalEvaluator(refinedFromCustom).evalFloat(x)) + .isEqualTo(FloatInterval(0f, 10f)) + } + + private enum class CustomBoundedOp : RemoteIntervalOperation { + Bounded; + + override val requiresBoundedFloatOperands: Boolean = true + + override fun toDebugString(args: List<RemoteStateCacheKey>): String = "bounded(u)" + + override fun evaluateFloatInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): FloatInterval = FloatInterval(-1f, 1f) + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteOperationMetadataTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteOperationMetadataTest.kt new file mode 100644 index 0000000..2db89ea --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteOperationMetadataTest.kt
@@ -0,0 +1,211 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteConstantCacheKey +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteFloatOperationKey +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteOperation +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateIdKey +import androidx.compose.remote.creation.compose.state.RemoteString +import androidx.compose.remote.creation.compose.state.RemoteValueKind +import androidx.compose.remote.creation.compose.state.StringOperationKey +import androidx.compose.remote.creation.compose.state.cacheKey +import androidx.compose.remote.creation.compose.state.rb +import androidx.compose.remote.creation.compose.state.rf +import androidx.compose.remote.creation.compose.state.ri +import androidx.compose.remote.creation.compose.state.rs +import androidx.compose.remote.creation.compose.state.selectIfGe +import androidx.compose.remote.creation.compose.state.selectIfLt +import androidx.compose.remote.document.intervals.IntervalComparison +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class RemoteOperationMetadataTest { + + private val x = RemoteFloat.createNamedRemoteFloat("x", 1f) + private val n = RemoteInt.createNamedRemoteInt("n", 1) + private val s = RemoteString.createNamedRemoteString("s", "abc") + private val b = RemoteBoolean.createNamedRemoteBoolean("b", true) + + @Test + fun boundedFloatOperandComparisonAndSelectMetadata() { + val mulOp = ((x * 2f.rf).cacheKey as RemoteOperationCacheKey).op + assertThat(mulOp).isNotInstanceOf(RemoteIntervalOperation::class.java) + val floatSem = intervalSemanticsFor(mulOp)!! + for (boundedOp in + listOf( + RemoteFloatOperationKey.Times, + RemoteFloatOperationKey.Div, + RemoteFloatOperationKey.Rem, + RemoteFloatOperationKey.Mad, + RemoteFloatOperationKey.Clamp, + RemoteFloatOperationKey.Lerp, + RemoteFloatOperationKey.Min, + RemoteFloatOperationKey.Max, + RemoteFloatOperationKey.Abs, + RemoteFloatOperationKey.Round, + RemoteFloatOperationKey.Sin, + RemoteFloatOperationKey.Cos, + RemoteFloatOperationKey.Atan, + RemoteFloatOperationKey.Atan2, + RemoteFloatOperationKey.Sign, + RemoteFloatOperationKey.CopySign, + RemoteFloatOperationKey.Exp, + RemoteFloatOperationKey.Cubic, + RemoteFloatOperationKey.RandInRange, + )) { + assertThat(floatSem.requiresBoundedFloatOperands(boundedOp)).isTrue() + } + val addOp = ((x + 2f.rf).cacheKey as RemoteOperationCacheKey).op + assertThat(floatSem.requiresBoundedFloatOperands(addOp)).isFalse() + + val floatCmpLtOp = (x.isLessThan(5f.rf).cacheKey as RemoteOperationCacheKey).op + assertThat(floatSem.comparisonCondition(floatCmpLtOp)).isEqualTo(IntervalComparison.LT) + assertThat((floatCmpLtOp as RemoteOperation).resultKind).isEqualTo(RemoteValueKind.BOOLEAN) + assertThat(floatSem.isBooleanSelect(floatCmpLtOp)).isFalse() + assertThat(floatSem.selectComparisonKind(addOp, emptyList())) + .isEqualTo(RemoteValueKind.OTHER) + + val intCmpGeOp = (n.isGreaterThanOrEqualTo(0.ri).cacheKey as RemoteOperationCacheKey).op + val intSem = intervalSemanticsFor(intCmpGeOp)!! + assertThat(intSem.comparisonCondition(intCmpGeOp)).isEqualTo(IntervalComparison.GTE) + assertThat((intCmpGeOp as RemoteOperation).resultKind).isEqualTo(RemoteValueKind.BOOLEAN) + assertThat(intSem.isBooleanSelect(intCmpGeOp)).isFalse() + + val selectIfIntKey = selectIfLt(n, 0.ri, 1.ri, 2.ri).cacheKey as RemoteOperationCacheKey + assertThat(intSem.selectCondition(selectIfIntKey.op)).isEqualTo(IntervalComparison.LT) + assertThat(intSem.selectComparisonKind(selectIfIntKey.op, selectIfIntKey.args)) + .isEqualTo(RemoteValueKind.INT) + assertThat(intSem.selectComparisonKind(intCmpGeOp, emptyList())) + .isEqualTo(RemoteValueKind.OTHER) + + val isEmptyOp = (s.isEmpty.cacheKey as RemoteOperationCacheKey).op + val strSem = intervalSemanticsFor(isEmptyOp)!! + assertThat((isEmptyOp as RemoteOperation).resultKind).isEqualTo(RemoteValueKind.BOOLEAN) + assertThat(strSem.comparisonCondition(isEmptyOp)).isNull() + assertThat(strSem.isBooleanSelect(isEmptyOp)).isFalse() + assertThat(strSem.selectComparisonKind(isEmptyOp, emptyList())) + .isEqualTo(RemoteValueKind.OTHER) + + val selectIfFloatKey = + selectIfGe(x, 0f.rf, 1f.rf, 2f.rf).cacheKey as RemoteOperationCacheKey + val selectIfFloatSem = intervalSemanticsFor(selectIfFloatKey.op)!! + assertThat(selectIfFloatSem.selectCondition(selectIfFloatKey.op)) + .isEqualTo(IntervalComparison.GTE) + assertThat( + selectIfFloatSem.selectComparisonKind(selectIfFloatKey.op, selectIfFloatKey.args) + ) + .isEqualTo(RemoteValueKind.FLOAT) + assertThat(selectIfFloatSem.isBooleanSelect(selectIfFloatKey.op)).isFalse() + + val selectIfStrIntKey = + selectIfLt(n, 0.ri, "a".rs, "b".rs).cacheKey as RemoteOperationCacheKey + val selectIfStrIntSem = intervalSemanticsFor(selectIfStrIntKey.op)!! + assertThat(selectIfStrIntSem.selectCondition(selectIfStrIntKey.op)) + .isEqualTo(IntervalComparison.LT) + assertThat( + selectIfStrIntSem.selectComparisonKind(selectIfStrIntKey.op, selectIfStrIntKey.args) + ) + .isEqualTo(RemoteValueKind.INT) + assertThat(selectIfStrIntSem.isBooleanSelect(selectIfStrIntKey.op)).isFalse() + + // Detached state IDs infer domain from the sibling operand, or OTHER when both are unknown. + assertThat( + strSem.selectComparisonKind( + StringOperationKey.SelectIfLT, + listOf( + RemoteStateIdKey(42), + RemoteConstantCacheKey(0), + RemoteConstantCacheKey("a"), + RemoteConstantCacheKey("b"), + ), + ) + ) + .isEqualTo(RemoteValueKind.INT) + assertThat( + strSem.selectComparisonKind( + StringOperationKey.SelectIfLT, + listOf( + RemoteStateIdKey(42), + RemoteConstantCacheKey(0f), + RemoteConstantCacheKey("a"), + RemoteConstantCacheKey("b"), + ), + ) + ) + .isEqualTo(RemoteValueKind.FLOAT) + assertThat( + strSem.selectComparisonKind( + StringOperationKey.SelectIfLT, + listOf( + RemoteStateIdKey(42), + RemoteStateIdKey(43), + RemoteConstantCacheKey("a"), + RemoteConstantCacheKey("b"), + ), + ) + ) + .isEqualTo(RemoteValueKind.OTHER) + + val selectIfStrFloatKey = + selectIfLt(x, 0f.rf, "a".rs, "b".rs).cacheKey as RemoteOperationCacheKey + val selectIfStrFloatSem = intervalSemanticsFor(selectIfStrFloatKey.op)!! + assertThat( + selectIfStrFloatSem.selectComparisonKind( + selectIfStrFloatKey.op, + selectIfStrFloatKey.args, + ) + ) + .isEqualTo(RemoteValueKind.FLOAT) + + val boolSelectFloatOp = (b.select(1f.rf, 2f.rf).cacheKey as RemoteOperationCacheKey).op + val boolSem = intervalSemanticsFor(boolSelectFloatOp)!! + assertThat(boolSem.isBooleanSelect(boolSelectFloatOp)).isTrue() + assertThat(boolSem.selectCondition(boolSelectFloatOp)).isNull() + + val b2 = RemoteBoolean.createNamedRemoteBoolean("b2", false) + val boolSelectBoolOp = (b.select(b2, false.rb).cacheKey as RemoteOperationCacheKey).op + assertThat(boolSem.isBooleanSelect(boolSelectBoolOp)).isTrue() + assertThat((boolSelectBoolOp as RemoteOperation).resultKind) + .isEqualTo(RemoteValueKind.BOOLEAN) + } + + @Test + fun customRemoteIntervalOperation_dispatchesThroughIntervalSemanticsAdapter() { + val customOp = + object : RemoteIntervalOperation { + override val requiresBoundedFloatOperands: Boolean = true + override val comparisonCondition: IntervalComparison = IntervalComparison.EQ + override val resultKind: RemoteValueKind = RemoteValueKind.BOOLEAN + + override fun toDebugString(args: List<RemoteStateCacheKey>): String = "custom" + } + val sem = intervalSemanticsFor(customOp)!! + assertThat(sem.requiresBoundedFloatOperands(customOp)).isTrue() + assertThat(sem.comparisonCondition(customOp)).isEqualTo(IntervalComparison.EQ) + assertThat(sem.selectComparisonKind(customOp, emptyList())).isEqualTo(RemoteValueKind.OTHER) + assertThat(sem.isBooleanSelect(customOp)).isFalse() + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteValueIntervalEvaluatorTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteValueIntervalEvaluatorTest.kt new file mode 100644 index 0000000..0aaeed3 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/intervals/RemoteValueIntervalEvaluatorTest.kt
@@ -0,0 +1,519 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.intervals + +import androidx.compose.remote.creation.compose.state.RemoteBoolean +import androidx.compose.remote.creation.compose.state.RemoteColor +import androidx.compose.remote.creation.compose.state.RemoteEnum +import androidx.compose.remote.creation.compose.state.RemoteFloat +import androidx.compose.remote.creation.compose.state.RemoteFloatArray +import androidx.compose.remote.creation.compose.state.RemoteInt +import androidx.compose.remote.creation.compose.state.RemoteIntArray +import androidx.compose.remote.creation.compose.state.RemoteIntOperationKey +import androidx.compose.remote.creation.compose.state.RemoteNamedCacheKey +import androidx.compose.remote.creation.compose.state.RemoteOperationCacheKey +import androidx.compose.remote.creation.compose.state.RemoteStateCacheKey +import androidx.compose.remote.creation.compose.state.RemoteString +import androidx.compose.remote.creation.compose.state.RemoteStringArray +import androidx.compose.remote.creation.compose.state.RemoteTimeVariables +import androidx.compose.remote.creation.compose.state.abs +import androidx.compose.remote.creation.compose.state.acos +import androidx.compose.remote.creation.compose.state.animatedRemoteFloat +import androidx.compose.remote.creation.compose.state.asin +import androidx.compose.remote.creation.compose.state.atan +import androidx.compose.remote.creation.compose.state.atan2 +import androidx.compose.remote.creation.compose.state.cacheKey +import androidx.compose.remote.creation.compose.state.cbrt +import androidx.compose.remote.creation.compose.state.ceil +import androidx.compose.remote.creation.compose.state.clamp +import androidx.compose.remote.creation.compose.state.copySign +import androidx.compose.remote.creation.compose.state.cos +import androidx.compose.remote.creation.compose.state.cubicEasing +import androidx.compose.remote.creation.compose.state.exp +import androidx.compose.remote.creation.compose.state.floor +import androidx.compose.remote.creation.compose.state.joinToDebugString +import androidx.compose.remote.creation.compose.state.lerp +import androidx.compose.remote.creation.compose.state.ln +import androidx.compose.remote.creation.compose.state.log +import androidx.compose.remote.creation.compose.state.mad +import androidx.compose.remote.creation.compose.state.max +import androidx.compose.remote.creation.compose.state.min +import androidx.compose.remote.creation.compose.state.pow +import androidx.compose.remote.creation.compose.state.rand +import androidx.compose.remote.creation.compose.state.randRange +import androidx.compose.remote.creation.compose.state.rb +import androidx.compose.remote.creation.compose.state.rf +import androidx.compose.remote.creation.compose.state.ri +import androidx.compose.remote.creation.compose.state.round +import androidx.compose.remote.creation.compose.state.rs +import androidx.compose.remote.creation.compose.state.selectIfLt +import androidx.compose.remote.creation.compose.state.sign +import androidx.compose.remote.creation.compose.state.sin +import androidx.compose.remote.creation.compose.state.sqrt +import androidx.compose.remote.document.AnimationEasing +import androidx.compose.remote.document.TextFromFloatFlags +import androidx.compose.remote.document.intervals.ColorInterval +import androidx.compose.remote.document.intervals.FloatInterval +import androidx.compose.remote.document.intervals.IntInterval +import androidx.compose.remote.document.intervals.StringSummary +import androidx.compose.remote.document.intervals.TriState +import androidx.compose.remote.document.packAnimationSpec +import com.google.common.truth.Truth.assertThat +import kotlin.math.PI +import kotlin.math.sqrt as mathSqrt +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class RemoteValueIntervalEvaluatorTest { + + @Test + fun floatOperationsAndSystemGlobals() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val env = MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(10f, 20f)) + val eval = RemoteValueIntervalEvaluator(env) + + assertThat(eval.evalFloat(x * 2f.rf + 5f.rf)).isEqualTo(FloatInterval(25f, 45f)) + assertThat(eval.evalFloat(clamp(value = x, min = 12f.rf, max = 18f.rf))) + .isEqualTo(FloatInterval(12f, 18f)) + assertThat(eval.evalFloat(lerp(0f.rf, 100f.rf, (x - 10f.rf) / 10f.rf))) + .isEqualTo(FloatInterval(0f, 100f)) + assertThat(eval.evalFloat(sin(x))).isEqualTo(FloatInterval(-1f, 1f)) + assertThat(eval.evalFloat(rand())) + .isEqualTo(FloatInterval(0f, 1f, minInclusive = true, maxInclusive = false)) + + // Animated float bounds & cubic easing + val spec = packAnimationSpec(duration = 0.5f, type = AnimationEasing.CUBIC_STANDARD) + assertThat(eval.evalFloat(animatedRemoteFloat(x, spec))).isEqualTo(FloatInterval(10f, 20f)) + + val eased = cubicEasing(0.4f.rf, 0f.rf, 0.2f.rf, 1f.rf, (x - 10f.rf) / 10f.rf) + assertThat(eval.evalFloat(eased)).isEqualTo(FloatInterval.UNIT) + + // Built-in system time global + assertThat(eval.evalInt(RemoteTimeVariables.hourOfDay)).isEqualTo(IntInterval(0, 23)) + } + + @Test + fun intBooleanAndSelectOperations() { + val n = RemoteInt.createNamedRemoteInt("n", 0) + val env = MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(5, 10)) + val eval = RemoteValueIntervalEvaluator(env) + + assertThat(eval.evalInt(n * 3.ri - 2.ri)).isEqualTo(IntInterval(13, 28)) + assertThat(eval.evalBoolean(n.isGreaterThan(4.ri))).isEqualTo(TriState.TRUE) + assertThat(eval.evalBoolean(n.isLessThan(0.ri))).isEqualTo(TriState.FALSE) + assertThat(eval.evalBoolean(n.isLessThan(8.ri))).isEqualTo(TriState.UNKNOWN) + assertThat(eval.evalBoolean(!n.isGreaterThan(4.ri))).isEqualTo(TriState.FALSE) + assertThat(eval.evalBoolean(n.isGreaterThan(4.ri) and n.isLessThan(20.ri))) + .isEqualTo(TriState.TRUE) + + // Select prunes statically dead arm during interval evaluation + assertThat(eval.evalFloat(n.isGreaterThan(4.ri).select(100f.rf, 999f.rf))) + .isEqualTo(FloatInterval.point(100f)) + assertThat(eval.evalInt(selectIfLt(n, 0.ri, 1.ri, 2.ri))).isEqualTo(IntInterval.point(2)) + } + + private enum class TestMode { + OFF, + LOW, + HIGH, + } + + @Test + fun firstClassBooleanAndEnumOperations() { + val n = RemoteInt.createNamedRemoteInt("n", 0) + val flag = RemoteBoolean.createNamedRemoteBoolean("flag", false) + val unboundFlag = RemoteBoolean.createNamedRemoteBoolean("unboundFlag", false) + val pos = RemoteInt.createNamedRemoteInt("pos", 1) + val gt1 = RemoteInt.createNamedRemoteInt("gt1", 2) + val env = + MapIntervalEnvironment.EMPTY.withNamedInt("n", IntInterval(5, 10)) + .withNamedInt("flag", IntInterval.point(1)) + .withNamedInt("pos", IntInterval(1, 5)) + .withNamedInt("gt1", IntInterval(2, 5)) + .withNamedInt("mode", IntInterval(0, 1)) + val eval = RemoteValueIntervalEvaluator(env) + + // First-class RemoteBoolean ops + val gt4 = n.isGreaterThan(4.ri) + val lt0 = n.isLessThan(0.ri) + assertThat(eval.evalBoolean(flag)).isEqualTo(TriState.TRUE) + assertThat(eval.evalBoolean(!flag)).isEqualTo(TriState.FALSE) + assertThat(eval.evalBoolean(gt4 or unboundFlag)).isEqualTo(TriState.TRUE) + assertThat(eval.evalBoolean(lt0 and unboundFlag)).isEqualTo(TriState.FALSE) + assertThat(eval.evalBoolean(gt4 xor lt0)).isEqualTo(TriState.TRUE) + assertThat(eval.evalBoolean(gt4.isEqualTo(flag))).isEqualTo(TriState.TRUE) + assertThat(eval.evalBoolean(gt4.isNotEqualTo(lt0))).isEqualTo(TriState.TRUE) + assertThat(eval.evalInt(gt4.toRemoteInt())).isEqualTo(IntInterval.point(1)) + assertThat(eval.evalInt(lt0.toRemoteInt())).isEqualTo(IntInterval.ZERO) + + // Non-canonical RemoteBoolean(int) preserves soundness + val nonCanonicalPos = RemoteBoolean.fromRemoteInt(pos) + val nonCanonicalGt1 = RemoteBoolean.fromRemoteInt(gt1) + assertThat(eval.evalBoolean(nonCanonicalPos)).isEqualTo(TriState.TRUE) + assertThat(eval.evalInt(nonCanonicalPos.toRemoteInt())).isEqualTo(IntInterval(1, 5)) + assertThat(eval.evalBoolean(!nonCanonicalPos)).isEqualTo(TriState.UNKNOWN) + assertThat(eval.evalBoolean(nonCanonicalGt1.isEqualTo(true.rb))).isEqualTo(TriState.FALSE) + + // First-class RemoteEnum ops + val namedMode = RemoteEnum.createNamedRemoteEnum("mode", TestMode.OFF) + assertThat(eval.evalInt(namedMode.ordinal)).isEqualTo(IntInterval(0, 1)) + assertThat(eval.evalString(namedMode.toRemoteString()).length).isEqualTo(IntInterval(3, 3)) + + val wrappedMode = RemoteEnum(RemoteInt.createNamedRemoteInt("mode", 0), TestMode.entries) + assertThat(eval.evalInt(wrappedMode.ordinal)).isEqualTo(IntInterval(0, 1)) + assertThat(eval.evalString(wrappedMode.toRemoteString { it.name.rs }).length) + .isEqualTo(IntInterval(3, 3)) + } + + @Test + fun stringAndColorOperationsIncludingFromArgbOrder() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val s = RemoteString.createNamedRemoteString("s", "hello") + val env = + MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(0f, 59f)) + .withNamedString("s", StringSummary(IntInterval(2, 5), isAsciiOnly = true)) + val eval = RemoteValueIntervalEvaluator(env) + + assertThat(eval.evalInt(s.length)).isEqualTo(IntInterval(2, 5)) + assertThat(eval.evalBoolean(s.isEmpty)).isEqualTo(TriState.FALSE) + assertThat(eval.evalBoolean(s.isNotEmpty)).isEqualTo(TriState.TRUE) + assertThat(eval.evalString(s + "!".rs).length).isEqualTo(IntInterval(3, 6)) + assertThat( + eval + .evalString( + x.toRemoteStringOptions( + 2, + 0, + TextFromFloatFlags.PAD_PRE_ZERO or TextFromFloatFlags.PAD_AFTER_NONE, + ) + ) + .length + ) + .isEqualTo(IntInterval(2, 2)) + + // Verify FromArgb uses (red, green, blue, alpha) order accurately! + val dynR = RemoteFloat.createNamedRemoteFloat("r", 0f) + val colorEnv = MapIntervalEnvironment.EMPTY.withNamedFloat("r", FloatInterval(0.5f, 1f)) + val colorEval = RemoteValueIntervalEvaluator(colorEnv) + val color = RemoteColor(red = dynR, green = 0f.rf, blue = 0f.rf, alpha = 0.25f.rf) + val colorInterval = colorEval.evalColor(color) + assertThat(colorInterval.alpha).isEqualTo(IntInterval.point(64)) + assertThat(colorInterval.red.min).isAtLeast(127) + assertThat(colorInterval.red.max).isEqualTo(255) + assertThat(colorInterval.green).isEqualTo(IntInterval.point(0)) + assertThat(colorInterval.blue).isEqualTo(IntInterval.point(0)) + assertThat(colorEval.evalFloat(color.alpha)).isEqualTo(FloatInterval.point(0.25f)) + + // Named color exercises ColorOperationKey.Component extraction. + val namedColor = RemoteColor.createNamedRemoteColor("c", 0) + val namedColorEval = + RemoteValueIntervalEvaluator( + MapIntervalEnvironment.EMPTY.withNamedColor( + "c", + ColorInterval.constant(0x40FF0000), + ) + ) + assertThat(namedColorEval.evalFloat(namedColor.alpha)) + .isEqualTo(FloatInterval.point(64f / 255f)) + assertThat(namedColorEval.evalFloat(namedColor.red)).isEqualTo(FloatInterval.point(1f)) + } + + @Test + fun literalArrayIndexingAndCustomOperationExtensibility() { + val idx = RemoteInt.createNamedRemoteInt("idx", 0) + val env = MapIntervalEnvironment.EMPTY.withNamedInt("idx", IntInterval(1, 2)) + val eval = RemoteValueIntervalEvaluator(env) + + val floats = RemoteFloatArray(listOf(10f.rf, 20f.rf, 30f.rf, 40f.rf)) + assertThat(eval.evalFloat(floats[idx])).isEqualTo(FloatInterval(20f, 30f)) + + val ints = RemoteIntArray(listOf(1.ri, 5.ri, 9.ri)) + assertThat(eval.evalInt(ints[idx])).isEqualTo(IntInterval(5, 9)) + + val strings = RemoteStringArray(listOf("a".rs, "bb".rs, "ccc".rs)) + assertThat(eval.evalString(strings[idx]).length).isEqualTo(IntInterval(2, 3)) + + // Custom RemoteOperation plugs directly into RemoteValueIntervalEvaluator without edits! + val customKey = RemoteOperationCacheKey.create(CustomDoubleOp.DoubleValue, idx) + assertThat(eval.evalIntKey(customKey)).isEqualTo(IntInterval(2, 4)) + + // Array indexing picks up opposite-type path-sensitive narrowing overrides + val nIdx = RemoteInt.createNamedRemoteInt("nIdx", 0) + val envWithIntOverride = + MapIntervalEnvironment.EMPTY.withNamedInt("nIdx", IntInterval(0, 3)) + .withIntNarrowing(nIdx.cacheKey, IntInterval.point(2)) + assertThat(RemoteValueIntervalEvaluator(envWithIntOverride).evalFloat(floats[nIdx])) + .isEqualTo(FloatInterval.point(30f)) + + val fIdx = RemoteFloat.createNamedRemoteFloat("fIdx", 0f) + val envWithFloatOverride = + MapIntervalEnvironment.EMPTY.withNamedFloat("fIdx", FloatInterval(0f, 2f)) + .withFloatNarrowing(fIdx.cacheKey, FloatInterval.point(1f)) + assertThat(RemoteValueIntervalEvaluator(envWithFloatOverride).evalInt(ints[fIdx])) + .isEqualTo(IntInterval.point(5)) + + // Out-of-bounds array indexing unions in 0 + val oobEnv = MapIntervalEnvironment.EMPTY.withNamedInt("idx", IntInterval(-1, 5)) + assertThat(RemoteValueIntervalEvaluator(oobEnv).evalFloat(floats[idx])) + .isEqualTo(FloatInterval(0f, 40f)) + assertThat(RemoteValueIntervalEvaluator(oobEnv).evalInt(ints[idx])) + .isEqualTo(IntInterval(0, 9)) + } + + @Test + fun soundnessRegressions_copySignSqrtCbrtLerpNarrowingAndBoolSign() { + // 1. RemoteInt CopySign returns a (b >= 0) or -a (b < 0), NOT |a| + val a = RemoteInt.createNamedRemoteInt("a", 0) + val bPos = RemoteInt.createNamedRemoteInt("bPos", 0) + val bNeg = RemoteInt.createNamedRemoteInt("bNeg", 0) + val bMix = RemoteInt.createNamedRemoteInt("bMix", 0) + val intEnv = + MapIntervalEnvironment.EMPTY.withNamedInt("a", IntInterval(-10, -2)) + .withNamedInt("bPos", IntInterval(0, 5)) + .withNamedInt("bNeg", IntInterval(-5, -1)) + .withNamedInt("bMix", IntInterval(-3, 3)) + val intEval = RemoteValueIntervalEvaluator(intEnv) + assertThat(intEval.evalInt(copySign(a, bPos))).isEqualTo(IntInterval(-10, -2)) + assertThat(intEval.evalInt(copySign(a, bNeg))).isEqualTo(IntInterval(2, 10)) + assertThat(intEval.evalInt(copySign(a, bMix))).isEqualTo(IntInterval(-10, 10)) + + // 2. Sqrt and Cbrt widen to UNBOUNDED when negative inputs are reachable (NaN at runtime) + val negStraddle = RemoteFloat.createNamedRemoteFloat("negStraddle", 0f) + val nonNeg = RemoteFloat.createNamedRemoteFloat("nonNeg", 0f) + val floatEnv = + MapIntervalEnvironment.EMPTY.withNamedFloat("negStraddle", FloatInterval(-4f, 9f)) + .withNamedFloat("nonNeg", FloatInterval(0f, 8f)) + val floatEval = RemoteValueIntervalEvaluator(floatEnv) + assertThat(floatEval.evalFloat(sqrt(negStraddle))).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(floatEval.evalFloat(cbrt(negStraddle))).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(floatEval.evalFloat(sqrt(nonNeg))).isEqualTo(FloatInterval(0f, mathSqrt(8f))) + assertThat(floatEval.evalFloat(cbrt(nonNeg))).isEqualTo(FloatInterval(0f, 2f)) + + // 3. Lerp and RandInRange soundly capture float32 overflow & cancellation + val huge = RemoteFloat.createNamedRemoteFloat("huge", 0f) + val tUnit = RemoteFloat.createNamedRemoteFloat("tUnit", 0f) + val lerpEnv = + MapIntervalEnvironment.EMPTY.withNamedFloat("huge", FloatInterval(-3e38f, 3e38f)) + .withNamedFloat("tUnit", FloatInterval.UNIT) + val lerpEval = RemoteValueIntervalEvaluator(lerpEnv) + assertThat(lerpEval.evalFloat(lerp(huge, huge, tUnit))).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(lerpEval.evalFloat(randRange(huge, huge))).isEqualTo(FloatInterval.UNBOUNDED) + val cancelRange = lerpEval.evalFloat(lerp(1e8f.rf, 1f.rf, tUnit)) + assertThat(0f in cancelRange).isTrue() + assertThat(1e8f in cancelRange).isTrue() + + // 4. withFloatNarrowing / withIntNarrowing intersect with base bindings (never widen!) + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val n = RemoteInt.createNamedRemoteInt("n", 0) + val baseEnv = + MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(0f, 10f)) + .withNamedInt("n", IntInterval(0, 10)) + val narrowedMap = + baseEnv + .withFloatNarrowing(x.cacheKey, FloatInterval(-5f, 5f)) + .withIntNarrowing(n.cacheKey, IntInterval(-5, 5)) + assertThat(RemoteValueIntervalEvaluator(narrowedMap).evalFloat(x)) + .isEqualTo(FloatInterval(0f, 5f)) + assertThat(RemoteValueIntervalEvaluator(narrowedMap).evalInt(n)) + .isEqualTo(IntInterval(0, 5)) + + // 5. Chained OverlaidIntervalEnvironment on a custom IntervalEnvironment preserves ALL + // layers + val customBase = + object : IntervalEnvironment { + override fun floatForNamed(key: RemoteNamedCacheKey): FloatInterval = + if (key.name == "x") FloatInterval(0f, 10f) else FloatInterval.UNBOUNDED + + override fun intForNamed(key: RemoteNamedCacheKey): IntInterval = + if (key.name == "n") IntInterval(0, 10) else IntInterval.UNBOUNDED + } + val chained = + customBase + .withFloatNarrowing(x.cacheKey, FloatInterval(-5f, 6f)) + .withIntNarrowing(n.cacheKey, IntInterval(2, 8)) + val chainedEval = RemoteValueIntervalEvaluator(chained) + assertThat(chainedEval.evalFloat(x)).isEqualTo(FloatInterval(0f, 6f)) + assertThat(chainedEval.evalInt(n)).isEqualTo(IntInterval(2, 8)) + + // 6. Negative RemoteInt evaluates to UNKNOWN (not TRUE!) as boolean for I_IFELSE parity + assertThat(intEval.evalBoolKey(bNeg.cacheKey)).isEqualTo(TriState.UNKNOWN) + assertThat(intEval.evalBoolKey(bPos.cacheKey)).isEqualTo(TriState.UNKNOWN) + val strictlyPos = RemoteInt.createNamedRemoteInt("pos", 1) + val posMixEval = + RemoteValueIntervalEvaluator( + MapIntervalEnvironment.EMPTY.withNamedInt("pos", IntInterval(1, 5)) + .withNamedInt("bPos", IntInterval(0, 5)) + .withNamedInt("bMix", IntInterval(-3, 3)) + ) + assertThat(posMixEval.evalBoolKey(strictlyPos.cacheKey)).isEqualTo(TriState.TRUE) + // Bitwise OR with a possibly-negative RemoteInt must NOT evaluate to TRUE (I_IFELSE <= 0) + assertThat(posMixEval.evalBoolKey((strictlyPos or bMix).cacheKey)) + .isEqualTo(TriState.UNKNOWN) + assertThat(posMixEval.evalBoolKey((strictlyPos or bPos).cacheKey)).isEqualTo(TriState.TRUE) + + // 7. Derived unbounded non-canonical RemoteBoolean (!RemoteBoolean.fromRemoteInt(u)) + // must NOT be whitelisted as non-negative in OR + val unboundedInt = RemoteInt.createNamedRemoteInt("unboundedInt", -2) + val derivedNegatable = !RemoteBoolean.fromRemoteInt(unboundedInt) + assertThat(posMixEval.evalBoolean(strictlyPos.isGreaterThan(0.ri) or derivedNegatable)) + .isEqualTo(TriState.UNKNOWN) + + // 8. RemoteColor.hsv with constant alpha != 1f uses FromAHSV with accurate alpha bounds + val dynH = RemoteFloat.createNamedRemoteFloat("h", 0f) + val hsvHalfAlpha = RemoteColor.hsv(dynH, 1f.rf, 1f.rf, alpha = 0.5f.rf) + val hsvOpaque = RemoteColor.hsv(dynH, 1f.rf, 1f.rf, alpha = 1f.rf) + assertThat(hsvHalfAlpha.cacheKey).isNotEqualTo(hsvOpaque.cacheKey) + assertThat(RemoteValueIntervalEvaluator().evalColor(hsvHalfAlpha).alpha) + .isEqualTo(IntInterval.point(128)) + assertThat(RemoteValueIntervalEvaluator().evalColor(hsvOpaque).alpha) + .isEqualTo(IntInterval.point(255)) + + // 9. RemoteInt.toRemoteString() includes GROUPING_BY3 ("1,000" -> length 5) + val thousand = RemoteInt.createNamedRemoteInt("thousand", 1000) + val thousandEval = + RemoteValueIntervalEvaluator( + MapIntervalEnvironment.EMPTY.withNamedInt("thousand", IntInterval.point(1000)) + ) + assertThat(thousandEval.evalString(thousand.toRemoteString()).length) + .isEqualTo(IntInterval.point(5)) + assertThat( + thousandEval + .evalStringKey( + RemoteOperationCacheKey.create( + RemoteIntOperationKey.ToRemoteString, + thousand, + ) + ) + .length + ) + .isEqualTo(IntInterval.point(5)) + + // 10. Float32 interior rounding in lerp must be soundly contained (tie-to-even u - f) + val wideFrom = RemoteFloat.createNamedRemoteFloat("wideFrom", 67108872f) + val lerpRoundEnv = + MapIntervalEnvironment.EMPTY.withNamedFloat( + "wideFrom", + FloatInterval(67108864f, 67108880f), + ) + val lerpRoundEval = RemoteValueIntervalEvaluator(lerpRoundEnv) + val lerpRes = lerpRoundEval.evalFloat(lerp(wideFrom, 4f.rf, 1f.rf)) + val interiorRuntime = 67108872f + (4f - 67108872f) * 1f + assertThat(lerpRes.contains(interiorRuntime)).isTrue() + + // 11. UNBOUNDED (reachable NaN) is never swallowed by bounded-range float ops + val unboundedU = RemoteFloat.createNamedRemoteFloat("unboundedU", 0f) + val emptyEval = RemoteValueIntervalEvaluator() + assertThat(emptyEval.evalFloat(exp(unboundedU))).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(emptyEval.evalFloat(sin(unboundedU))).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(emptyEval.evalFloat(clamp(value = unboundedU, min = 0f.rf, max = 1f.rf))) + .isEqualTo(FloatInterval.UNBOUNDED) + assertThat(emptyEval.evalBoolean(exp(unboundedU).isGreaterThan((-1f).rf))) + .isEqualTo(TriState.UNKNOWN) + assertThat(emptyEval.evalBoolean(sin(unboundedU).isLessThan(2f.rf))) + .isEqualTo(TriState.UNKNOWN) + + // 12. FromArgb models ColorExpression 10-bit constant alpha quantization (0.1f -> 25) + val dynR2 = RemoteFloat.createNamedRemoteFloat("r2", 0f) + val argbQuantEval = + RemoteValueIntervalEvaluator( + MapIntervalEnvironment.EMPTY.withNamedFloat("r2", FloatInterval(0f, 1f)) + ) + val argbQuant = RemoteColor(red = dynR2, green = 0f.rf, blue = 0f.rf, alpha = 0.1f.rf) + assertThat(argbQuantEval.evalColor(argbQuant).alpha).isEqualTo(IntInterval.point(25)) + + // 13. Empty-interval propagation in evalIsEmpty, int And, compareIntKeys, array union + val emptyEnv = + MapIntervalEnvironment.EMPTY.withNamedString( + "es", + StringSummary(IntInterval.EMPTY, isAsciiOnly = true), + ) + .withNamedInt("ei", IntInterval.EMPTY) + .withNamedInt("pos5", IntInterval(0, 5)) + val emptyIntEval = RemoteValueIntervalEvaluator(emptyEnv) + val es = RemoteString.createNamedRemoteString("es", "") + val ei = RemoteInt.createNamedRemoteInt("ei", 0) + val pos5 = RemoteInt.createNamedRemoteInt("pos5", 1) + assertThat(emptyIntEval.evalBoolean(es.isEmpty)).isEqualTo(TriState.UNKNOWN) + assertThat(emptyIntEval.evalInt(ei and pos5)).isEqualTo(IntInterval.EMPTY) + assertThat(emptyIntEval.evalBoolean(ei.isEqualTo(ei))).isEqualTo(TriState.UNKNOWN) + val arr = RemoteFloatArray(listOf(1f.rf, 2f.rf)) + assertThat(emptyIntEval.evalFloat(arr[ei])).isEqualTo(FloatInterval.EMPTY) + } + + @Test + fun broadFloatAndIntOperationCoverage() { + val x = RemoteFloat.createNamedRemoteFloat("x", 0f) + val y = RemoteFloat.createNamedRemoteFloat("y", 0f) + val u = RemoteFloat.createNamedRemoteFloat("u", 0f) + val n = RemoteInt.createNamedRemoteInt("n", 0) + val m = RemoteInt.createNamedRemoteInt("m", 0) + val env = + MapIntervalEnvironment.EMPTY.withNamedFloat("x", FloatInterval(1f, 4f)) + .withNamedFloat("y", FloatInterval(-2f, 2f)) + .withNamedFloat("u", FloatInterval(-0.5f, 0.5f)) + .withNamedInt("n", IntInterval(2, 6)) + .withNamedInt("m", IntInterval(1, 3)) + val eval = RemoteValueIntervalEvaluator(env) + + assertThat(eval.evalFloat(x / 2f.rf)).isEqualTo(FloatInterval(0.5f, 2f)) + assertThat(eval.evalFloat(x % 2f.rf)) + .isEqualTo(FloatInterval(0f, 2f, minInclusive = true, maxInclusive = false)) + assertThat(eval.evalFloat(min(x, y))).isEqualTo(FloatInterval(-2f, 2f)) + assertThat(eval.evalFloat(max(x, y))).isEqualTo(FloatInterval(1f, 4f)) + assertThat(eval.evalFloat(abs(y))).isEqualTo(FloatInterval(0f, 2f)) + assertThat(eval.evalFloat(mad(x, 2f.rf, 1f.rf))).isEqualTo(FloatInterval(3f, 9f)) + assertThat(eval.evalFloat(floor(x))).isEqualTo(FloatInterval(1f, 4f)) + assertThat(eval.evalFloat(ceil(x))).isEqualTo(FloatInterval(1f, 4f)) + assertThat(eval.evalFloat(round(x))).isEqualTo(FloatInterval(1f, 4f)) + assertThat(eval.evalFloat(exp(x)).min).isGreaterThan(2.5f) + assertThat(eval.evalFloat(ln(x)).min).isEqualTo(0f) + assertThat(eval.evalFloat(log(x)).min).isEqualTo(0f) + assertThat(eval.evalFloat(pow(x, 2f.rf))).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(eval.evalFloat(cos(x)).min).isAtLeast(-1f) + assertThat(eval.evalFloat(asin(u)).max).isAtMost((PI / 2.0).toFloat()) + assertThat(eval.evalFloat(acos(u)).min).isAtLeast(0f) + assertThat(eval.evalFloat(atan(y)).max).isAtMost((PI / 2.0).toFloat()) + assertThat(eval.evalFloat(atan2(y, x)).min).isAtLeast(-PI.toFloat()) + assertThat(eval.evalFloat(sign(x))).isEqualTo(FloatInterval.point(1f)) + assertThat(eval.evalFloat(sign(y))).isEqualTo(FloatInterval(-1f, 1f)) + assertThat(eval.evalFloat(copySign(y, x))).isEqualTo(FloatInterval(0f, 2f)) + + // Integer bitwise, div, rem, min, max, abs + assertThat(eval.evalInt(n / m)).isEqualTo(IntInterval(0, 6)) + assertThat(eval.evalInt(n % m)).isEqualTo(IntInterval(0, 2)) + assertThat(eval.evalInt(n and m)).isEqualTo(IntInterval(0, 3)) + assertThat(eval.evalInt(n or m)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(eval.evalInt(n xor m)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(eval.evalInt(n shl m)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(eval.evalInt(n shr m)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(eval.evalInt(n.inv())).isEqualTo(IntInterval.UNBOUNDED) + } + + private enum class CustomDoubleOp : RemoteIntervalOperation { + DoubleValue; + + override fun toDebugString(args: List<RemoteStateCacheKey>): String = + "double(${args.joinToDebugString()})" + + override fun evaluateIntInterval( + key: RemoteOperationCacheKey, + evaluator: RemoteValueIntervalEvaluator, + ): IntInterval = evaluator.evalIntKey(key.args[0]) * IntInterval.point(2) + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/state/RemoteColorTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/state/RemoteColorTest.kt index e8f6541..05c41df 100644 --- a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/state/RemoteColorTest.kt +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/state/RemoteColorTest.kt
@@ -557,6 +557,23 @@ assertThat(tweened.constantValueOrNull).isEqualTo(COLOR_RED) } + @Test + fun hsv_constantNonOpaqueAlpha_preservesAlphaAndDistinctCacheKey() { + val dynH = createNamedRemoteFloat("h", 0f) + val halfAlpha = + RemoteColor.hsv(hue = dynH, saturation = 1f.rf, value = 1f.rf, alpha = 0.5f.rf) + val opaque = RemoteColor.hsv(hue = dynH, saturation = 1f.rf, value = 1f.rf, alpha = 1f.rf) + + assertThat(halfAlpha.cacheKey).isNotEqualTo(opaque.cacheKey) + assertThat(halfAlpha).isNotEqualTo(opaque) + val halfId = creationState.getId(halfAlpha) + val opaqueId = creationState.getId(opaque) + assertThat(halfId).isNotEqualTo(opaqueId) + makeAndPaintCoreDocument() + assertThat((context.getColor(halfId) ushr 24) and 0xFF).isEqualTo(128) + assertThat((context.getColor(opaqueId) ushr 24) and 0xFF).isEqualTo(255) + } + private fun makeAndPaintCoreDocument() = CoreDocument().apply { val buffer = creationState.document.buffer
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/state/RemoteImageBitmapTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/state/RemoteImageBitmapTest.kt new file mode 100644 index 0000000..bcfda5f --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/creation/compose/state/RemoteImageBitmapTest.kt
@@ -0,0 +1,168 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.creation.compose.state + +import androidx.compose.remote.creation.compose.capture.RemoteComposeCreationState +import androidx.compose.remote.document.RemoteDocumentWriter +import com.google.common.truth.Truth.assertThat +import java.lang.reflect.Proxy +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class RemoteImageBitmapTest { + + @Test + fun urlFactory_defaultAndExplicitDimensions() { + val url = "https://example.com/banner.png" + val defaultBitmap = RemoteImageBitmap(url) + val explicitOneByOne = RemoteImageBitmap(url, 1, 1) + val sizedBitmap = RemoteImageBitmap(url, 320, 180) + val intrinsicSizeBitmap = RemoteImageBitmap(url, 0, 0) + + assertThat(defaultBitmap.urlOrNull).isEqualTo(url) + assertThat(defaultBitmap.declaredWidth).isEqualTo(1) + assertThat(defaultBitmap.declaredHeight).isEqualTo(1) + assertThat(defaultBitmap.hasIntrinsicDimensions).isFalse() + assertThat(defaultBitmap.cacheKey).isEqualTo(RemoteConstantCacheKey(url)) + assertThat(explicitOneByOne).isEqualTo(defaultBitmap) + + assertThat(sizedBitmap.urlOrNull).isEqualTo(url) + assertThat(sizedBitmap.declaredWidth).isEqualTo(320) + assertThat(sizedBitmap.declaredHeight).isEqualTo(180) + assertThat(sizedBitmap.hasIntrinsicDimensions).isFalse() + assertThat(sizedBitmap).isNotEqualTo(defaultBitmap) + assertThat(sizedBitmap).isEqualTo(RemoteImageBitmap(url, 320, 180)) + + assertThat(intrinsicSizeBitmap.urlOrNull).isEqualTo(url) + assertThat(intrinsicSizeBitmap.declaredWidth).isNull() + assertThat(intrinsicSizeBitmap.declaredHeight).isNull() + assertThat(intrinsicSizeBitmap.hasIntrinsicDimensions).isTrue() + assertThat(intrinsicSizeBitmap).isNotEqualTo(defaultBitmap) + assertThat(intrinsicSizeBitmap).isNotEqualTo(sizedBitmap) + assertThat(sizedBitmap.cacheKey.getValueKind()).isEqualTo(RemoteValueKind.IMAGE_BITMAP) + assertThat(sizedBitmap.cacheKey.isResultWholeNumber).isFalse() + } + + @Test + fun urlFactory_writesExplicitDimensionsToDocumentWithoutColliding() { + data class RecordedUrlBitmap(val url: String, val width: Int, val height: Int) + + val recorded = LinkedHashMap<Int, RecordedUrlBitmap>() + var nextId = 42 + val writer = + Proxy.newProxyInstance( + RemoteDocumentWriter::class.java.classLoader, + arrayOf(RemoteDocumentWriter::class.java), + ) { _, method, args -> + if (method.name.startsWith("addBitmapUrl")) { + val id = nextId++ + recorded[id] = + RecordedUrlBitmap( + url = args[0] as String, + width = args[1] as Int, + height = args[2] as Int, + ) + id + } else { + throw UnsupportedOperationException(method.name) + } + } as RemoteDocumentWriter + val creationState = RemoteComposeCreationState().apply { document = writer } + val url = "https://example.com/photo.png" + val defaultBitmap = RemoteImageBitmap(url) + val sizedBitmap = RemoteImageBitmap(url, 640, 480) + val intrinsicBitmap = RemoteImageBitmap(url, 0, 0) + + val defaultId = creationState.getId(defaultBitmap) + val sizedId = creationState.getId(sizedBitmap) + val intrinsicId = creationState.getId(intrinsicBitmap) + assertThat(sizedId).isNotEqualTo(defaultId) + assertThat(intrinsicId).isNotEqualTo(defaultId) + assertThat(intrinsicId).isNotEqualTo(sizedId) + + assertThat(recorded[defaultId]).isEqualTo(RecordedUrlBitmap(url, 1, 1)) + assertThat(recorded[sizedId]).isEqualTo(RecordedUrlBitmap(url, 640, 480)) + assertThat(recorded[intrinsicId]).isEqualTo(RecordedUrlBitmap(url, 0, 0)) + } + + @Test + fun namedUrlBitmap_exposesUrlAndDeclaredDimensions() { + val url = "https://example.com/avatar.png" + val namedDefault = RemoteImageBitmap.createNamedRemoteImageBitmap("avatar_default", url) + val namedSized = + RemoteImageBitmap.createNamedRemoteImageBitmap( + name = "avatar_sized", + url = url, + width = 256, + height = 128, + domain = RemoteValue.Domain.System, + ) + + val namedIntrinsic = + RemoteImageBitmap.createNamedRemoteImageBitmap( + name = "avatar_intrinsic", + url = url, + width = 0, + height = 0, + ) + + assertThat(namedDefault.urlOrNull).isEqualTo(url) + assertThat(namedDefault.declaredWidth).isEqualTo(1) + assertThat(namedDefault.declaredHeight).isEqualTo(1) + assertThat(namedDefault.hasIntrinsicDimensions).isFalse() + assertThat(namedDefault.cacheKey) + .isEqualTo(RemoteNamedCacheKey(RemoteValue.Domain.User, "avatar_default")) + + assertThat(namedSized.urlOrNull).isEqualTo(url) + assertThat(namedSized.declaredWidth).isEqualTo(256) + assertThat(namedSized.declaredHeight).isEqualTo(128) + assertThat(namedSized.hasIntrinsicDimensions).isFalse() + assertThat(namedSized.cacheKey) + .isEqualTo(RemoteNamedCacheKey(RemoteValue.Domain.System, "avatar_sized")) + + assertThat(namedIntrinsic.urlOrNull).isEqualTo(url) + assertThat(namedIntrinsic.declaredWidth).isNull() + assertThat(namedIntrinsic.declaredHeight).isNull() + assertThat(namedIntrinsic.hasIntrinsicDimensions).isTrue() + } + + @Test + fun nonUrlBitmaps_returnNullUrlAndExpectedDimensions() { + val offscreen = RemoteImageBitmap.createOffscreenRemoteBitmap(200, 100) + assertThat(offscreen.urlOrNull).isNull() + assertThat(offscreen.declaredWidth).isEqualTo(200) + assertThat(offscreen.declaredHeight).isEqualTo(100) + assertThat(offscreen.hasIntrinsicDimensions).isFalse() + + val byId = RemoteImageBitmap.createForId(42) + assertThat(byId.urlOrNull).isNull() + assertThat(byId.declaredWidth).isNull() + assertThat(byId.declaredHeight).isNull() + assertThat(byId.hasIntrinsicDimensions).isFalse() + } + + @Test + fun sizedUrlBitmap_widthHeightPropertiesStillWork() { + val sized = RemoteImageBitmap("https://example.com/icon.png", 48, 32) + assertThat(sized.width.cacheKey.getValueKind()).isEqualTo(RemoteValueKind.FLOAT) + assertThat(sized.height.cacheKey.getValueKind()).isEqualTo(RemoteValueKind.FLOAT) + assertThat(sized.width.cacheKey.isResultWholeNumber).isTrue() + assertThat(sized.height.cacheKey.isResultWholeNumber).isTrue() + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/RemoteProtocolParityTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/RemoteProtocolParityTest.kt index 5507b9b..52642ef 100644 --- a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/RemoteProtocolParityTest.kt +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/RemoteProtocolParityTest.kt
@@ -17,6 +17,7 @@ package androidx.compose.remote.document import androidx.compose.remote.core.Operations +import androidx.compose.remote.core.PaintOperation import androidx.compose.remote.core.RcProfiles as CoreRcProfiles import androidx.compose.remote.core.RemoteComposeBuffer import androidx.compose.remote.core.RemoteComposeState @@ -43,6 +44,7 @@ import androidx.compose.remote.core.operations.utilities.ImageScaling import androidx.compose.remote.core.operations.utilities.IntegerExpressionEvaluator import androidx.compose.remote.core.operations.utilities.NanMap +import androidx.compose.remote.core.operations.utilities.StringUtils import androidx.compose.remote.core.operations.utilities.easing.CubicEasing import androidx.compose.remote.core.operations.utilities.easing.Easing import androidx.compose.remote.core.operations.utilities.easing.FloatAnimation @@ -262,6 +264,7 @@ val arrayId = RemoteArrayId(NanEncoding.START_ARRAY_ID) assertTrue(NanEncoding.isArrayNan(arrayId.toNanFloat())) + assertTrue(arrayId.toMaybeVariableFloat().isArrayVariable) val intId = RemoteIntId(55) val encodedLong = intId.toLongEncodedId() @@ -330,9 +333,35 @@ HostNamedActionType.FLOAT_ARRAY_TYPE, ) + assertEquals(TextFromFloat.PAD_AFTER_SPACE, TextFromFloatFlags.PAD_AFTER_SPACE) + assertEquals(TextFromFloat.PAD_AFTER_NONE, TextFromFloatFlags.PAD_AFTER_NONE) assertEquals(TextFromFloat.PAD_AFTER_ZERO, TextFromFloatFlags.PAD_AFTER_ZERO) + assertEquals(TextFromFloat.PAD_PRE_SPACE, TextFromFloatFlags.PAD_PRE_SPACE) assertEquals(TextFromFloat.PAD_PRE_NONE, TextFromFloatFlags.PAD_PRE_NONE) + assertEquals(TextFromFloat.PAD_PRE_ZERO, TextFromFloatFlags.PAD_PRE_ZERO) assertEquals(TextFromFloat.GROUPING_BY3, TextFromFloatFlags.GROUPING_BY3) + assertEquals(TextFromFloat.GROUPING_BY4, TextFromFloatFlags.GROUPING_BY4) + assertEquals(TextFromFloat.GROUPING_BY32, TextFromFloatFlags.GROUPING_BY32) + assertEquals( + TextFromFloat.SEPARATOR_PERIOD_COMMA, + TextFromFloatFlags.SEPARATOR_PERIOD_COMMA, + ) + assertEquals( + TextFromFloat.SEPARATOR_COMMA_PERIOD, + TextFromFloatFlags.SEPARATOR_COMMA_PERIOD, + ) + assertEquals(TextFromFloat.SEPARATOR_SPACE_COMMA, TextFromFloatFlags.SEPARATOR_SPACE_COMMA) + assertEquals( + TextFromFloat.SEPARATOR_UNDER_PERIOD, + TextFromFloatFlags.SEPARATOR_UNDER_PERIOD, + ) + assertEquals(TextFromFloat.OPTIONS_ROUNDING, TextFromFloatFlags.OPTIONS_ROUNDING) + assertEquals( + TextFromFloat.OPTIONS_NEGATIVE_PARENTHESES, + TextFromFloatFlags.OPTIONS_NEGATIVE_PARENTHESES, + ) + assertEquals(TextFromFloat.LEGACY_MODE, TextFromFloatFlags.LEGACY_MODE) + assertEquals(TextFromFloat.FULL_FORMAT, TextFromFloatFlags.FULL_FORMAT) assertEquals(DrawTextAnchored.ANCHOR_TEXT_RTL, DrawTextAnchoredFlags.ANCHOR_TEXT_RTL) assertEquals(DrawTextAnchored.BASELINE_RELATIVE, DrawTextAnchoredFlags.BASELINE_RELATIVE) assertEquals(TextLayout.TEXT_ALIGN_CENTER, TextLayoutFlags.TEXT_ALIGN_CENTER) @@ -490,6 +519,113 @@ } @Test + fun testNanEncodingIgnoresSignBit() { + assertEquals(0x7F800000, NanEncoding.NAN_EXPONENT) + assertEquals(-1, NanEncoding.NO_ID) + assertTrue(NanEncoding.isNan(NanEncoding.asNan(42))) + assertEquals(42, NanEncoding.idFromNan(NanEncoding.asNan(42))) + assertTrue(NanEncoding.isNan(Float.fromBits(0x7F800005))) + assertEquals(5, NanEncoding.idFromNan(Float.fromBits(0x7F800005))) + assertTrue(NanEncoding.isNan(Float.fromBits(0x7FC00001))) + assertEquals(1, NanEncoding.idFromNan(Float.fromBits(0x7FC00001))) + assertFalse(NanEncoding.isNan(Float.NaN)) + assertEquals(NanEncoding.NO_ID, NanEncoding.idFromNan(Float.NaN)) + assertFalse(NanEncoding.isNan(Float.fromBits(0xFFC00000.toInt()))) + assertEquals(NanEncoding.NO_ID, NanEncoding.idFromNan(Float.fromBits(0xFFC00000.toInt()))) + assertFalse(NanEncoding.isNan(Float.POSITIVE_INFINITY)) + assertFalse(NanEncoding.isNan(Float.NEGATIVE_INFINITY)) + + val posAddToken = + Float.fromBits((FloatRpn.OFFSET + FloatRpn.ID_ADD) or NanEncoding.NAN_EXPONENT) + assertTrue(FloatRpn.isOperator(posAddToken)) + assertEquals(FloatRpn.ID_ADD, FloatRpn.operatorId(posAddToken)) + assertFalse(FloatRpn.isOperator(Float.NaN)) + assertEquals(NanEncoding.NO_ID, FloatRpn.operatorId(Float.NaN)) + } + + @Test + fun testMaybeDereferencedIdAndNanEncodingHelpers() { + assertEquals(PaintOperation.PTR_DEREFERENCE, MaybeDereferencedId.PTR_DEREFERENCE) + assertEquals(PaintOperation.VALUE_MASK, MaybeDereferencedId.VALUE_MASK) + + val direct = MaybeDereferencedId.direct(42) + assertFalse(direct.isDereferenced) + assertEquals(42, direct.directId) + assertNull(direct.pointerId) + assertEquals(42, direct.unmaskedId) + + val indirect = MaybeDereferencedId.dereferenced(42) + assertTrue(indirect.isDereferenced) + assertNull(indirect.directId) + assertEquals(42, indirect.pointerId) + assertEquals(42, indirect.unmaskedId) + + // High bits above 16-bit VALUE_MASK (including sign bit 31 and bits 16..29) are masked out + val highBitsRaw = MaybeDereferencedId.fromRawInt(0x8003_002A.toInt()) + assertFalse(highBitsRaw.isDereferenced) + assertEquals(42, highBitsRaw.unmaskedId) + assertEquals(42, highBitsRaw.directId) + assertNull(highBitsRaw.pointerId) + val highBitsPtr = MaybeDereferencedId.fromRawInt(0xC003_002A.toInt()) + assertTrue(highBitsPtr.isDereferenced) + assertEquals(42, highBitsPtr.unmaskedId) + assertNull(highBitsPtr.directId) + assertEquals(42, highBitsPtr.pointerId) + assertEquals(42, MaybeDereferencedId.direct(0x1234_002A).raw) + assertEquals( + 42 or PaintOperation.PTR_DEREFERENCE, + MaybeDereferencedId.dereferenced(0x1234_002A).raw, + ) + + for (id in -5..60) { + assertEquals(Utils.isSystemGlobal(id), NanEncoding.isSystemGlobalId(id)) + } + for (id in intArrayOf(0x3FFF, 0x4000, 0x4FFF, 0x5000)) { + assertEquals(Utils.isMacroLocal(id), NanEncoding.isMacroLocalId(id)) + } + + assertEquals(-1, NanEncoding.idRegion(-1)) + assertEquals(-1, NanEncoding.idRegion(Int.MIN_VALUE)) + assertEquals(NanEncoding.REGION_SYSTEM, NanEncoding.idRegion(42)) + assertEquals( + NanEncoding.REGION_VARIABLE, + NanEncoding.idRegion(NanEncoding.REGION_VARIABLE + 1), + ) + assertEquals(NanEncoding.REGION_ARRAY, NanEncoding.idRegion(NanEncoding.START_ARRAY_ID)) + assertEquals( + NanEncoding.REGION_OPERATION, + NanEncoding.idRegion(NanEncoding.REGION_OPERATION + 5), + ) + + assertTrue(NanEncoding.isNonIdFloatNan(Float.NaN)) + assertFalse(NanEncoding.isNonIdFloatNan(Float.fromBits(0x7F800005))) + assertFalse(NanEncoding.isNonIdFloatNan(Float.fromBits(0x7FC00001))) + assertTrue(NanEncoding.isNonIdFloatNan(Float.fromBits(0xFFC00000.toInt()))) + assertFalse(NanEncoding.isNonIdFloatNan(NanEncoding.asNan(42))) + assertFalse(NanEncoding.isNonIdFloatNan(Float.POSITIVE_INFINITY)) + assertFalse(NanEncoding.isNonIdFloatNan(Float.NEGATIVE_INFINITY)) + assertFalse(NanEncoding.isNonIdFloatNan(1.5f)) + + assertEquals(42, NanEncoding.decodeIdOrNull(NanEncoding.asNan(42))) + assertNull(NanEncoding.decodeIdOrNull(Float.NaN)) + assertNull(NanEncoding.decodeIdOrNull(1.5f)) + + assertEquals(0, NanEncoding.decodeLongIdOrNull(NanEncoding.LONG_ID_OFFSET)) + assertEquals(42, NanEncoding.decodeLongIdOrNull(NanEncoding.encodeLongId(42))) + assertEquals( + Int.MAX_VALUE, + NanEncoding.decodeLongIdOrNull(NanEncoding.LONG_ID_OFFSET + Int.MAX_VALUE), + ) + assertNull(NanEncoding.decodeLongIdOrNull(NanEncoding.LONG_ID_OFFSET - 1L)) + assertNull(NanEncoding.decodeLongIdOrNull(NanEncoding.LONG_ID_OFFSET + Int.MAX_VALUE + 1L)) + assertNull(NanEncoding.decodeLongIdOrNull(42L)) + + assertTrue(MaybeVariableFloat.variable(NanEncoding.START_ARRAY_ID).isArrayVariable) + assertFalse(MaybeVariableFloat.variable(42).isArrayVariable) + assertFalse(1.5f.mvf.isArrayVariable) + } + + @Test fun testUnpackAnimationSpecAndCubicControlPointsParity() { val packed = packAnimationSpec( @@ -682,4 +818,213 @@ RemoteColorMath.toArgb(0.5f, 0.25f, 0.75f, 1.0f), ) } + + @Test + fun testTextFromFloatFormatterBitForBitParityWithStringUtils() { + val values = + floatArrayOf( + 0f, + -0f, + 1e-4f, + 12.345f, + -987654.3f, + 0.999f, + 1234567.8f, + -0.05f, + 42f, + Float.NaN, + Float.POSITIVE_INFINITY, + Float.NEGATIVE_INFINITY, + ) + val flagCombos = + intArrayOf( + TextFromFloatFlags.PAD_PRE_NONE or TextFromFloatFlags.PAD_AFTER_ZERO, + TextFromFloatFlags.PAD_PRE_ZERO or TextFromFloatFlags.PAD_AFTER_ZERO, + TextFromFloatFlags.PAD_PRE_SPACE or TextFromFloatFlags.PAD_AFTER_SPACE, + TextFromFloatFlags.PAD_PRE_NONE or + TextFromFloatFlags.PAD_AFTER_NONE or + TextFromFloatFlags.GROUPING_BY3 or + TextFromFloatFlags.SEPARATOR_COMMA_PERIOD, + TextFromFloatFlags.PAD_PRE_NONE or + TextFromFloatFlags.PAD_AFTER_ZERO or + TextFromFloatFlags.GROUPING_BY4 or + TextFromFloatFlags.SEPARATOR_PERIOD_COMMA or + TextFromFloatFlags.OPTIONS_NEGATIVE_PARENTHESES, + TextFromFloatFlags.PAD_PRE_NONE or + TextFromFloatFlags.PAD_AFTER_ZERO or + TextFromFloatFlags.GROUPING_BY32 or + TextFromFloatFlags.SEPARATOR_SPACE_COMMA or + TextFromFloatFlags.OPTIONS_ROUNDING, + TextFromFloatFlags.PAD_PRE_ZERO or + TextFromFloatFlags.PAD_AFTER_ZERO or + TextFromFloatFlags.GROUPING_BY3 or + TextFromFloatFlags.SEPARATOR_UNDER_PERIOD or + TextFromFloatFlags.OPTIONS_ROUNDING or + TextFromFloatFlags.OPTIONS_NEGATIVE_PARENTHESES, + TextFromFloatFlags.PAD_PRE_ZERO or + TextFromFloatFlags.PAD_AFTER_ZERO or + TextFromFloatFlags.LEGACY_MODE, + TextFromFloatFlags.PAD_PRE_NONE or + TextFromFloatFlags.PAD_AFTER_NONE or + TextFromFloatFlags.LEGACY_MODE, + TextFromFloatFlags.PAD_PRE_SPACE or + TextFromFloatFlags.PAD_AFTER_SPACE or + TextFromFloatFlags.LEGACY_MODE, + TextFromFloatFlags.FULL_FORMAT, + ) + val digitPairs = listOf(8 to 2, 8 to 0, 0 to 2, 8 to 4) + + for ((before, after) in digitPairs) { + for (flags in flagCombos) { + // Decode flags independently using remote-core's TextFromFloat constants so the + // oracle does not depend on TextFromFloatFormatter.parseSpec. + val oraclePadAfter = + when (flags and 3) { + TextFromFloat.PAD_AFTER_SPACE -> ' ' + TextFromFloat.PAD_AFTER_NONE -> '\u0000' + TextFromFloat.PAD_AFTER_ZERO -> '0' + else -> ' ' + } + val oraclePadBefore = + when (flags and (3 shl 2)) { + TextFromFloat.PAD_PRE_SPACE -> ' ' + TextFromFloat.PAD_PRE_NONE -> '\u0000' + TextFromFloat.PAD_PRE_ZERO -> '0' + else -> ' ' + } + val oracleGrouping = + when (flags and (3 shl 4)) { + TextFromFloat.GROUPING_BY3 -> StringUtils.GROUPING_BY3 + TextFromFloat.GROUPING_BY4 -> StringUtils.GROUPING_BY4 + TextFromFloat.GROUPING_BY32 -> StringUtils.GROUPING_BY32 + else -> StringUtils.GROUPING_NONE + } + val oracleSeparator = + when (flags and (3 shl 6)) { + TextFromFloat.SEPARATOR_PERIOD_COMMA -> StringUtils.SEPARATOR_PERIOD_COMMA + TextFromFloat.SEPARATOR_COMMA_PERIOD -> StringUtils.SEPARATOR_COMMA_PERIOD + TextFromFloat.SEPARATOR_SPACE_COMMA -> StringUtils.SEPARATOR_SPACE_COMMA + else -> StringUtils.SEPARATOR_UNDER_PERIOD + } + for (v in values) { + val isFull = (flags and TextFromFloat.FULL_FORMAT) != 0 + val expected = + when { + isFull -> v.toString() + (flags and TextFromFloat.LEGACY_MODE) != 0 -> + StringUtils.floatToString( + v, + before, + after, + oraclePadBefore, + oraclePadAfter, + ) + else -> { + var opts = 0 + if ((flags and TextFromFloat.OPTIONS_ROUNDING) != 0) { + opts = opts or StringUtils.ROUNDING + } + if ((flags and TextFromFloat.OPTIONS_NEGATIVE_PARENTHESES) != 0) { + opts = opts or StringUtils.NEGATIVE_PARENTHESES + } + StringUtils.floatToString( + v, + before, + after, + oraclePadBefore, + oraclePadAfter, + oracleSeparator, + oracleGrouping, + opts, + ) + } + } + assertEquals( + expected, + TextFromFloatFormatter.format( + value = v, + digitsBefore = before, + digitsAfter = after, + flags = flags, + ), + "Formatting mismatch for v=$v before=$before after=$after flags=0x${flags.toString(16)}", + ) + } + } + } + + // Bounds validation rejects negative and excessively large digit counts + assertFailsWith<IllegalArgumentException> { + TextFromFloatFormatter.parseSpec(-1, 2, TextFromFloatFlags.PAD_PRE_NONE) + } + assertFailsWith<IllegalArgumentException> { + TextFromFloatFormatter.parseSpec(2, -1, TextFromFloatFlags.PAD_PRE_NONE) + } + assertFailsWith<IllegalArgumentException> { + TextFromFloatFormatter.parseSpec( + TextFromFloatFormatter.MAX_DIGITS + 1, + 2, + TextFromFloatFlags.PAD_PRE_NONE, + ) + } + assertFailsWith<IllegalArgumentException> { + TextFromFloatFormatter.format( + 1.5f, + 2, + TextFromFloatFormatter.MAX_DIGITS + 1, + TextFromFloatFlags.PAD_PRE_NONE, + ) + } + } + + @Test + fun testProfileOperationRegistry() { + val registry = ProfileOperationRegistry() + val otherRegistry = ProfileOperationRegistry() + val maskA = 1 shl 28 + val maskB = 1 shl 29 + val maskBoth = maskA or maskB + val opcodeA = 254 + val opcodeB = 255 + val opcodeOverride = 253 + + // register(0) rejected; unregister on absent mask is a no-op + assertFailsWith<IllegalArgumentException> { registry.register(0) { emptySet() } } + registry.unregister(maskA) + + // Built-in RcProfiles delegation (HEADER opcode 0 is supported in API 6) + assertTrue(registry.isOpcodeSupported(0, apiLevel = 6, profileFlags = 0)) + + assertFalse(registry.isOpcodeSupported(opcodeA, 7, maskA)) + registry.register(maskA) { setOf(opcodeA) } + assertEquals(setOf(opcodeA), registry.resolveOperationIds(maskA)) + assertTrue(registry.isOpcodeSupported(opcodeA, 7, maskA)) + assertFalse(registry.isOpcodeSupported(opcodeA, 7, 0)) + + // Separate instances remain isolated from each other + assertFalse(otherRegistry.isOpcodeSupported(opcodeA, 7, maskA)) + assertTrue(otherRegistry.resolveOperationIds(maskA).isEmpty()) + + // apiLevel <= 6 ignores custom profile providers + assertFalse(registry.isOpcodeSupported(opcodeA, 6, maskA)) + + // Multi-provider additive union & partial-bit non-match + registry.register(maskBoth) { setOf(opcodeB) } + assertEquals(setOf(opcodeA), registry.resolveOperationIds(maskA)) + assertFalse(registry.isOpcodeSupported(opcodeB, 7, maskA)) + assertFalse(registry.isOpcodeSupported(opcodeB, 7, maskB)) + assertEquals(setOf(opcodeA, opcodeB), registry.resolveOperationIds(maskBoth)) + assertTrue(registry.isOpcodeSupported(opcodeA, 7, maskBoth)) + assertTrue(registry.isOpcodeSupported(opcodeB, 7, maskBoth)) + + // Re-registering same mask overwrites previous provider + registry.register(maskA) { setOf(opcodeOverride) } + assertEquals(setOf(opcodeOverride), registry.resolveOperationIds(maskA)) + assertFalse(registry.isOpcodeSupported(opcodeA, 7, maskA)) + assertTrue(registry.isOpcodeSupported(opcodeOverride, 7, maskA)) + + registry.unregister(maskA) + registry.unregister(maskBoth) + assertTrue(registry.resolveOperationIds(maskBoth).isEmpty()) + } }
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/FloatAnimationBoundsTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/FloatAnimationBoundsTest.kt new file mode 100644 index 0000000..b91fea0 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/FloatAnimationBoundsTest.kt
@@ -0,0 +1,331 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.compose.remote.core.operations.utilities.easing.CubicEasing +import androidx.compose.remote.document.AnimationEasing +import androidx.compose.remote.document.packAnimationSpec +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import kotlin.math.nextDown +import kotlin.test.Test + +class FloatAnimationBoundsTest { + + @Test + fun evaluateCubicEasing_bitForBitParityWithRemoteCore() { + val presets = + intArrayOf( + AnimationEasing.CUBIC_STANDARD, + AnimationEasing.CUBIC_ACCELERATE, + AnimationEasing.CUBIC_DECELERATE, + AnimationEasing.CUBIC_LINEAR, + AnimationEasing.CUBIC_ANTICIPATE, + AnimationEasing.CUBIC_OVERSHOOT, + ) + val xs = floatArrayOf(-0.2f, 0f, 0.1f, 0.25f, 0.5f, 0.73f, 0.99f, 1f, 1.5f) + for (preset in presets) { + val pts = AnimationEasing.cubicControlPoints(preset)!! + val core = CubicEasing().apply { config(preset) } + for (x in xs) { + assertWithMessage("Mismatch for preset=$preset x=$x") + .that( + FloatAnimationBounds.evaluateCubicEasing(pts[0], pts[1], pts[2], pts[3], x) + ) + .isEqualTo(core.get(x)) + } + } + } + + @Test + fun boundAnimatedFloat_handlesStandardOvershootInitialValueAndTaint() { + val standardSpec = packAnimationSpec(duration = 0.5f, type = AnimationEasing.CUBIC_STANDARD) + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(standardSpec)).isFalse() + assertThat(FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval(10f, 20f))) + .isEqualTo(FloatInterval(10f, 20f)) + + val withInit = + packAnimationSpec( + duration = 0.5f, + type = AnimationEasing.CUBIC_STANDARD, + initialValue = 0f, + ) + val withInitBound = + FloatAnimationBounds.boundAnimatedFloat(withInit, FloatInterval(10f, 20f)) + assertThat(withInitBound.min).isEqualTo(0f) + assertThat(withInitBound.max).isAtLeast(20f) + assertThat(withInitBound.max).isLessThan(20.001f) + + val overshootSpec = + packAnimationSpec(duration = 0.5f, type = AnimationEasing.CUBIC_OVERSHOOT) + val overshootBound = + FloatAnimationBounds.boundAnimatedFloat(overshootSpec, FloatInterval(0f, 100f)) + assertThat(overshootBound.min).isLessThan(0f) + assertThat(overshootBound.max).isGreaterThan(100f) + + val wrapSpec = + packAnimationSpec(duration = 0.5f, type = AnimationEasing.CUBIC_STANDARD, wrap = 360f) + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(wrapSpec)).isTrue() + assertThat(FloatAnimationBounds.boundAnimatedFloat(wrapSpec, FloatInterval(0f, 100f))) + .isEqualTo(FloatInterval.UNBOUNDED) + + val springSpec = floatArrayOf(0f, 1f, 2f, 3f, 4f) + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(springSpec)).isTrue() + + // Soundness regressions for [0, 1] easing under float32 overflow, cancellation, and + // non-monotonic ULP boundary rounding in p * (t - s) + s + assertThat( + FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval(-3e38f, 3e38f)) + ) + .isEqualTo(FloatInterval.UNBOUNDED) + val largeSpan = + FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval(1f, 1e8f)) + assertWithMessage("Float32 cancellation (1*(1-1e8)+1e8 == 0f) must be included") + .that(0f in largeSpan) + .isTrue() + assertThat(1e8f in largeSpan).isTrue() + + val posUlpSpan = + FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval(3f, 33554432f)) + val posInterior = 1f * (3f - 33554430f) + 33554430f // evaluates to 2f < 3f + assertThat(posInterior).isEqualTo(2f) + assertWithMessage("Interior binary32 rounding result 2f must be in $posUlpSpan") + .that(posInterior in posUlpSpan) + .isTrue() + + val negUlpSpan = + FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval(-33554432f, -3f)) + val negInterior = 1f * (-3f - -33554430f) + -33554430f // evaluates to -2f > -3f + assertThat(negInterior).isEqualTo(-2f) + assertWithMessage("Interior binary32 rounding result -2f must be in $negUlpSpan") + .that(negInterior in negUlpSpan) + .isTrue() + + val oddUpper = 20f.nextDown() + val oddUpperSpan = + FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval(0f, oddUpper)) + val oddInterior = 1f * (oddUpper - 9.23872e-7f) + 9.23872e-7f + assertWithMessage("Interior upward rounding $oddInterior must be in $oddUpperSpan") + .that(oddInterior in oddUpperSpan) + .isTrue() + + // Constant target stays exact + assertThat(FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval.ZERO)) + .isEqualTo(FloatInterval.ZERO) + + // CUBIC_ANTICIPATE, EASE_OUT_BOUNCE, CUBIC_CUSTOM, EASE_OUT_ELASTIC, SPLINE_CUSTOM, + // malformed + val anticipateSpec = + packAnimationSpec(duration = 0.5f, type = AnimationEasing.CUBIC_ANTICIPATE) + val anticipateBound = + FloatAnimationBounds.boundAnimatedFloat(anticipateSpec, FloatInterval(0f, 100f)) + assertThat(anticipateBound.min).isLessThan(0f) + assertThat(anticipateBound.max).isGreaterThan(100f) + + val bounceSpec = packAnimationSpec(duration = 0.5f, type = AnimationEasing.EASE_OUT_BOUNCE) + assertThat(FloatAnimationBounds.boundAnimatedFloat(bounceSpec, FloatInterval(10f, 20f))) + .isEqualTo(FloatInterval(10f, 20f)) + + val customSpec = + packAnimationSpec( + duration = 0.5f, + type = AnimationEasing.CUBIC_CUSTOM, + spec = floatArrayOf(0.2f, -0.5f, 0.8f, 1.5f), + ) + val customBound = + FloatAnimationBounds.boundAnimatedFloat(customSpec, FloatInterval(0f, 100f)) + assertThat(customBound.min).isLessThan(0f) + assertThat(customBound.max).isGreaterThan(100f) + + val badCustomX = + packAnimationSpec( + duration = 0.5f, + type = AnimationEasing.CUBIC_CUSTOM, + spec = floatArrayOf(-0.2f, 0f, 0.8f, 1f), + ) + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(badCustomX)).isTrue() + + val elasticSpec = + packAnimationSpec(duration = 0.5f, type = AnimationEasing.EASE_OUT_ELASTIC) + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(elasticSpec)).isTrue() + + val splineSpec = + packAnimationSpec( + duration = 0.5f, + type = AnimationEasing.SPLINE_CUSTOM, + spec = floatArrayOf(0f, 0.5f, 1f), + ) + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(splineSpec)).isTrue() + + // Empty / 1-element / non-positive duration / truncated / infinite initialValue specs + assertThat(FloatAnimationBounds.parseAnimationSpec(floatArrayOf())) + .isEqualTo(ParsedAnimationSpec(FloatInterval.UNIT, null)) + assertThat(FloatAnimationBounds.parseAnimationSpec(floatArrayOf(0.5f))) + .isEqualTo(ParsedAnimationSpec(FloatInterval.UNIT, null)) + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(floatArrayOf(0f))).isTrue() + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(floatArrayOf(-1f))) + .isTrue() + assertThat(FloatAnimationBounds.isConservativelyTaintedAnimation(floatArrayOf(Float.NaN))) + .isTrue() + assertThat( + FloatAnimationBounds.isConservativelyTaintedAnimation( + floatArrayOf(1f, Float.fromBits((4 shl 16) or AnimationEasing.CUBIC_CUSTOM)) + ) + ) + .isTrue() + assertThat( + FloatAnimationBounds.isConservativelyTaintedAnimation( + packAnimationSpec(duration = 1f, initialValue = Float.POSITIVE_INFINITY) + ) + ) + .isTrue() + assertThat(FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval.EMPTY)) + .isEqualTo(FloatInterval.EMPTY) + assertThat(FloatAnimationBounds.boundAnimatedFloat(standardSpec, FloatInterval.UNBOUNDED)) + .isEqualTo(FloatInterval.UNBOUNDED) + } + + @Test + fun evalCubicEasingInterval_boundsMonotoneAndOvershootingCurves() { + val mono = + FloatAnimationBounds.evalCubicEasingInterval( + x1 = FloatInterval.point(0.4f), + y1 = FloatInterval.point(0f), + x2 = FloatInterval.point(0.2f), + y2 = FloatInterval.point(1f), + pos = FloatInterval(0.25f, 0.75f), + ) + assertThat(mono.min).isGreaterThan(0f) + assertThat(mono.max).isLessThan(1f) + + val overshooting = + FloatAnimationBounds.evalCubicEasingInterval( + x1 = FloatInterval.point(0.34f), + y1 = FloatInterval.point(1.56f), + x2 = FloatInterval.point(0.64f), + y2 = FloatInterval.point(1f), + pos = FloatInterval.UNIT, + ) + assertThat(overshooting.max).isGreaterThan(1.0f) + assertThat(overshooting.min).isEqualTo(0f) + + // Exact point evaluation even when y1/y2 overshoot [0, 1] + val overshootAtHalf = + FloatAnimationBounds.evalCubicEasingInterval( + x1 = FloatInterval.point(0.34f), + y1 = FloatInterval.point(1.56f), + x2 = FloatInterval.point(0.64f), + y2 = FloatInterval.point(1f), + pos = FloatInterval.point(0.5f), + ) + assertThat(overshootAtHalf.isPoint).isTrue() + assertThat(overshootAtHalf.min) + .isEqualTo(FloatAnimationBounds.evaluateCubicEasing(0.34f, 1.56f, 0.64f, 1f, 0.5f)) + + // Clamped endpoints, non-point control points, invalid x, empty/unbounded + assertThat( + FloatAnimationBounds.evalCubicEasingInterval( + FloatInterval.point(0.4f), + FloatInterval.point(0f), + FloatInterval.point(0.2f), + FloatInterval.point(1f), + FloatInterval(-2f, 0f), + ) + ) + .isEqualTo(FloatInterval.ZERO) + assertThat( + FloatAnimationBounds.evalCubicEasingInterval( + FloatInterval.point(0.4f), + FloatInterval.point(0f), + FloatInterval.point(0.2f), + FloatInterval.point(1f), + FloatInterval(1f, 3f), + ) + ) + .isEqualTo(FloatInterval.point(1f)) + val rangedCtrl = + FloatAnimationBounds.evalCubicEasingInterval( + FloatInterval(0.2f, 0.5f), + FloatInterval(-0.5f, 1.5f), + FloatInterval(0.5f, 0.8f), + FloatInterval(0f, 1.5f), + FloatInterval(0.2f, 0.8f), + ) + assertThat(rangedCtrl.min).isLessThan(0f) + assertThat(rangedCtrl.max).isGreaterThan(1f) + assertThat( + FloatAnimationBounds.evalCubicEasingInterval( + FloatInterval(-0.1f, 0.5f), + FloatInterval.ZERO, + FloatInterval.point(0.5f), + FloatInterval.point(1f), + FloatInterval.UNIT, + ) + ) + .isEqualTo(FloatInterval.UNBOUNDED) + assertThat( + FloatAnimationBounds.evalCubicEasingInterval( + FloatInterval.point(0.4f), + FloatInterval.point(0f), + FloatInterval.point(0.2f), + FloatInterval.point(1f), + FloatInterval.EMPTY, + ) + ) + .isEqualTo(FloatInterval.EMPTY) + + // Citardauq quadratic root stability regression for large equal y1 == y2 + val hugePeak = FloatAnimationBounds.cubicBezierYBounds(1e16f, 1e16f) + assertWithMessage( + "Expected peak 7.5e15f in cubicBezierYBounds(1e16f, 1e16f), got $hugePeak" + ) + .that(7.5e15f in hugePeak) + .isTrue() + val hugeNeg = FloatAnimationBounds.cubicBezierYBounds(-1e6f, -1e6f) + assertThat(-7.5e5f in hugeNeg).isTrue() + assertThat(hugeNeg.max).isGreaterThan(1f) + + // Unbounded control points widen soundly to UNBOUNDED + assertThat( + FloatAnimationBounds.evalCubicEasingInterval( + x1 = FloatInterval.point(0.4f), + y1 = FloatInterval.UNBOUNDED, + x2 = FloatInterval.point(0.2f), + y2 = FloatInterval.point(1f), + pos = FloatInterval.point(0.5f), + ) + ) + .isEqualTo(FloatInterval.UNBOUNDED) + } + + @Test + fun parsedAnimationSpec_canonicalizesZeroAndNanInEqualsAndHashCode() { + val posZero = ParsedAnimationSpec(FloatInterval.UNIT, 0.0f) + val negZero = ParsedAnimationSpec(FloatInterval.UNIT, -0.0f) + assertThat(posZero).isEqualTo(negZero) + assertThat(posZero.hashCode()).isEqualTo(negZero.hashCode()) + + val nanA = ParsedAnimationSpec(FloatInterval.UNIT, Float.NaN) + val nanB = ParsedAnimationSpec(FloatInterval.UNIT, Float.fromBits(0x7FC01234)) + assertThat(nanA).isEqualTo(nanA) + assertThat(nanA).isEqualTo(nanB) + assertThat(nanA.hashCode()).isEqualTo(nanB.hashCode()) + + val nullInit = ParsedAnimationSpec(FloatInterval.UNIT, null) + assertThat(nullInit).isNotEqualTo(posZero) + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/NumericIntervalTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/NumericIntervalTest.kt new file mode 100644 index 0000000..d1c6c50 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/NumericIntervalTest.kt
@@ -0,0 +1,412 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.compose.remote.core.operations.ConditionalOperations +import androidx.compose.remote.document.RemoteContextIds +import com.google.common.truth.Truth.assertThat +import kotlin.math.PI +import kotlin.math.nextDown +import kotlin.math.sqrt +import kotlin.test.Test +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull + +class NumericIntervalTest { + + @Test + fun triState_booleanAlgebraAndConversions() { + assertThat(TriState.of(true)).isEqualTo(TriState.TRUE) + assertThat(TriState.of(false)).isEqualTo(TriState.FALSE) + assertThat(TriState.TRUE.booleanValueOrNull).isTrue() + assertThat(TriState.FALSE.booleanValueOrNull).isFalse() + assertThat(TriState.UNKNOWN.booleanValueOrNull).isNull() + + assertThat(!TriState.TRUE).isEqualTo(TriState.FALSE) + assertThat(!TriState.FALSE).isEqualTo(TriState.TRUE) + assertThat(!TriState.UNKNOWN).isEqualTo(TriState.UNKNOWN) + + assertThat(TriState.FALSE and TriState.UNKNOWN).isEqualTo(TriState.FALSE) + assertThat(TriState.TRUE and TriState.UNKNOWN).isEqualTo(TriState.UNKNOWN) + assertThat(TriState.TRUE and TriState.TRUE).isEqualTo(TriState.TRUE) + + assertThat(TriState.TRUE or TriState.UNKNOWN).isEqualTo(TriState.TRUE) + assertThat(TriState.FALSE or TriState.UNKNOWN).isEqualTo(TriState.UNKNOWN) + assertThat(TriState.FALSE or TriState.FALSE).isEqualTo(TriState.FALSE) + + assertThat(TriState.TRUE.toIntInterval()).isEqualTo(IntInterval.point(1)) + assertThat(TriState.FALSE.toIntInterval()).isEqualTo(IntInterval.ZERO) + assertThat(TriState.UNKNOWN.toIntInterval()).isEqualTo(IntInterval(0, 1)) + + assertThat(TriState.TRUE.toFloatInterval()).isEqualTo(FloatInterval.point(1f)) + assertThat(TriState.FALSE.toFloatInterval()).isEqualTo(FloatInterval.ZERO) + assertThat(TriState.UNKNOWN.toFloatInterval()).isEqualTo(FloatInterval.UNIT) + + assertThat(FloatInterval.MAX_EXACT_INT).isEqualTo(16_777_216) + } + + @Test + fun intervalComparison_wireCodeParityNegateFlipAndNarrow() { + assertThat(IntervalComparison.fromWireCode(ConditionalOperations.TYPE_EQ.toInt())) + .isEqualTo(IntervalComparison.EQ) + assertThat(IntervalComparison.fromWireCode(ConditionalOperations.TYPE_NEQ.toInt())) + .isEqualTo(IntervalComparison.NEQ) + assertThat(IntervalComparison.fromWireCode(ConditionalOperations.TYPE_LT.toInt())) + .isEqualTo(IntervalComparison.LT) + assertThat(IntervalComparison.fromWireCode(ConditionalOperations.TYPE_LTE.toInt())) + .isEqualTo(IntervalComparison.LTE) + assertThat(IntervalComparison.fromWireCode(ConditionalOperations.TYPE_GT.toInt())) + .isEqualTo(IntervalComparison.GT) + assertThat(IntervalComparison.fromWireCode(ConditionalOperations.TYPE_GTE.toInt())) + .isEqualTo(IntervalComparison.GTE) + assertThat(IntervalComparison.fromWireCode(ConditionalOperations.TYPE_CHANGED.toInt())) + .isNull() + + for (cmp in IntervalComparison.entries) { + assertThat(cmp.negate().negate()).isEqualTo(cmp) + assertThat(cmp.flip().flip()).isEqualTo(cmp) + } + + assertThat(IntervalComparison.EQ.selfComparisonResult()).isEqualTo(TriState.TRUE) + assertThat(IntervalComparison.LTE.selfComparisonResult()).isEqualTo(TriState.TRUE) + assertThat(IntervalComparison.GTE.selfComparisonResult()).isEqualTo(TriState.TRUE) + assertThat(IntervalComparison.NEQ.selfComparisonResult()).isEqualTo(TriState.FALSE) + assertThat(IntervalComparison.LT.selfComparisonResult()).isEqualTo(TriState.FALSE) + assertThat(IntervalComparison.GT.selfComparisonResult()).isEqualTo(TriState.FALSE) + + val (fA, fB) = + IntervalComparison.LT.narrowFloat(FloatInterval(0f, 20f), FloatInterval(5f, 10f)) + assertThat(fA).isEqualTo(FloatInterval(0f, 10f, minInclusive = true, maxInclusive = false)) + assertThat(fB).isEqualTo(FloatInterval(5f, 10f)) + + val (iA, iB) = IntervalComparison.LT.narrowInt(IntInterval(0, 20), IntInterval(5, 10)) + assertThat(iA).isEqualTo(IntInterval(0, 9)) + assertThat(iB).isEqualTo(IntInterval(5, 10)) + + assertThat(IntervalComparison.LT.compareLongRangeAgainstZero(-5L, -1L)) + .isEqualTo(TriState.TRUE) + assertThat(IntervalComparison.LT.compareLongRangeAgainstZero(0L, 5L)) + .isEqualTo(TriState.FALSE) + assertThat(IntervalComparison.LT.compareLongRangeAgainstZero(-1L, 1L)) + .isEqualTo(TriState.UNKNOWN) + // Empty Long range (lo > hi) returns UNKNOWN across all comparison ops + for (cmp in IntervalComparison.entries) { + assertThat(cmp.compareLongRangeAgainstZero(5L, -5L)).isEqualTo(TriState.UNKNOWN) + } + + // Empty narrowing short-circuits BOTH operands to EMPTY + for (cmp in IntervalComparison.entries) { + assertThat(cmp.narrowFloat(FloatInterval.EMPTY, FloatInterval(0f, 10f))) + .isEqualTo(Pair(FloatInterval.EMPTY, FloatInterval.EMPTY)) + assertThat(cmp.narrowFloat(FloatInterval(0f, 10f), FloatInterval.EMPTY)) + .isEqualTo(Pair(FloatInterval.EMPTY, FloatInterval.EMPTY)) + assertThat(cmp.narrowInt(IntInterval.EMPTY, IntInterval(0, 10))) + .isEqualTo(Pair(IntInterval.EMPTY, IntInterval.EMPTY)) + assertThat(cmp.narrowInt(IntInterval(0, 10), IntInterval.EMPTY)) + .isEqualTo(Pair(IntInterval.EMPTY, IntInterval.EMPTY)) + } + + // All comparison ops on narrowFloat and narrowInt (including upper sentinel range) + assertThat( + IntervalComparison.EQ.narrowFloat(FloatInterval(0f, 10f), FloatInterval(5f, 20f)) + ) + .isEqualTo(Pair(FloatInterval(5f, 10f), FloatInterval(5f, 10f))) + assertThat( + IntervalComparison.NEQ.narrowFloat(FloatInterval(0f, 20f), FloatInterval(5f, 10f)) + ) + .isEqualTo(Pair(FloatInterval(0f, 20f), FloatInterval(5f, 10f))) + assertThat( + IntervalComparison.LTE.narrowFloat(FloatInterval(0f, 20f), FloatInterval(5f, 10f)) + ) + .isEqualTo(Pair(FloatInterval(0f, 10f), FloatInterval(5f, 10f))) + assertThat( + IntervalComparison.GT.narrowFloat(FloatInterval(0f, 20f), FloatInterval(5f, 10f)) + ) + .isEqualTo( + Pair( + FloatInterval(5f, 20f, minInclusive = false, maxInclusive = true), + FloatInterval(5f, 10f), + ) + ) + assertThat( + IntervalComparison.GTE.narrowFloat(FloatInterval(0f, 20f), FloatInterval(5f, 10f)) + ) + .isEqualTo(Pair(FloatInterval(5f, 20f), FloatInterval(5f, 10f))) + assertThat(IntervalComparison.NEQ.narrowInt(IntInterval(0, 20), IntInterval(5, 10))) + .isEqualTo(Pair(IntInterval(0, 20), IntInterval(5, 10))) + assertThat(IntervalComparison.GT.narrowInt(IntInterval(0, 20), IntInterval(5, 10))) + .isEqualTo(Pair(IntInterval(6, 20), IntInterval(5, 10))) + assertThat(IntervalComparison.GTE.narrowInt(IntInterval(0, 20), IntInterval(5, 10))) + .isEqualTo(Pair(IntInterval(5, 20), IntInterval(5, 10))) + assertThat(IntervalComparison.LTE.narrowInt(IntInterval(0, 20), IntInterval(5, 10))) + .isEqualTo(Pair(IntInterval(0, 10), IntInterval(5, 10))) + val highSentinel = IntInterval(IntInterval.MAX_BOUND, IntInterval.MAX_BOUND) + val (narrowHiA, narrowHiB) = IntervalComparison.LT.narrowInt(highSentinel, highSentinel) + assertThat(narrowHiA.isEmpty).isFalse() + assertThat(narrowHiB.isEmpty).isFalse() + } + + @Test + fun floatInterval_arithmeticOpenClosedTrigRemAndComparisons() { + val halfOpen = FloatInterval(0f, 10f, minInclusive = true, maxInclusive = false) + assertThat(0f in halfOpen).isTrue() + assertThat(10f in halfOpen).isFalse() + assertThat(halfOpen.isAlwaysLessThan(FloatInterval.point(10f))).isTrue() + assertThat(halfOpen.compareEqualTo(FloatInterval.point(10f))).isEqualTo(TriState.FALSE) + + // Empty interval normalization in equals/hashCode, NaN, and -0.0f handling + val reversedEmpty = FloatInterval(5f, 2f) + val openSingletonEmpty = FloatInterval(5f, 5f, minInclusive = false, maxInclusive = true) + val nanEmpty = FloatInterval(Float.NaN, 1f) + assertThat(reversedEmpty.isEmpty).isTrue() + assertThat(openSingletonEmpty.isEmpty).isTrue() + assertThat(nanEmpty.isEmpty).isTrue() + assertThat(reversedEmpty).isEqualTo(FloatInterval.EMPTY) + assertThat(openSingletonEmpty).isEqualTo(FloatInterval.EMPTY) + assertThat(nanEmpty).isEqualTo(FloatInterval.EMPTY) + assertThat(reversedEmpty.hashCode()).isEqualTo(FloatInterval.EMPTY.hashCode()) + assertThat(openSingletonEmpty.hashCode()).isEqualTo(FloatInterval.EMPTY.hashCode()) + assertThat(nanEmpty.hashCode()).isEqualTo(FloatInterval.EMPTY.hashCode()) + + assertThat(FloatInterval.point(Float.NaN)).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(Float.NaN in FloatInterval.UNBOUNDED).isFalse() + val negZero = FloatInterval(-0.0f, -0.0f) + assertThat(negZero).isEqualTo(FloatInterval.ZERO) + assertThat(negZero.hashCode()).isEqualTo(FloatInterval.ZERO.hashCode()) + assertThat(-0.0f in FloatInterval.ZERO).isTrue() + + // Arithmetic & ZERO absorption + assertThat(FloatInterval(1f, 3f) + FloatInterval(2f, 4f)).isEqualTo(FloatInterval(3f, 7f)) + assertThat(FloatInterval(1f, 3f) - FloatInterval(2f, 4f)).isEqualTo(FloatInterval(-3f, 1f)) + assertThat(-FloatInterval(1f, 3f)).isEqualTo(FloatInterval(-3f, -1f)) + assertThat(FloatInterval.UNBOUNDED * FloatInterval.ZERO).isEqualTo(FloatInterval.ZERO) + assertThat(FloatInterval(1f, 2f) / FloatInterval(-1f, 1f)) + .isEqualTo(FloatInterval.UNBOUNDED) + assertThat(FloatInterval(-5f, 3f).abs()).isEqualTo(FloatInterval(0f, 5f)) + assertThat(FloatInterval(1f, 5f).min(FloatInterval(2f, 3f))) + .isEqualTo(FloatInterval(1f, 3f)) + assertThat(FloatInterval(1f, 5f).max(FloatInterval(2f, 3f))) + .isEqualTo(FloatInterval(2f, 5f)) + assertThat(FloatInterval(1f, 4f).union(FloatInterval(6f, 10f))) + .isEqualTo(FloatInterval(1f, 10f)) + assertThat(FloatInterval(1f, 6f).intersect(FloatInterval(4f, 10f))) + .isEqualTo(FloatInterval(4f, 6f)) + assertThat(FloatInterval(-1f, 10f).clamp(FloatInterval.point(2f), FloatInterval.point(4f))) + .isEqualTo(FloatInterval(2f, 4f)) + + // IEEE-754 rounding soundness: computed finite bounds on +, -, *, /, sqrt are closed + val openUnit = FloatInterval(0f, 1f, minInclusive = true, maxInclusive = false) + val bigShift = FloatInterval.point(8388608f) // 2^23 + val shifted = openUnit + bigShift + assertThat(0.75f + 8388608f in shifted).isTrue() // 8388609f must be contained! + assertThat(shifted.maxInclusive).isTrue() + val sqrtOpen = FloatInterval(0f, 2f, minInclusive = true, maxInclusive = false).sqrt() + assertThat(sqrt(2f.nextDown()) in sqrtOpen).isTrue() + assertThat(sqrtOpen.maxInclusive).isTrue() + assertThat(FloatInterval(0f, 4f).sqrt()).isEqualTo(FloatInterval(0f, 2f)) + assertThat(FloatInterval(-0.0f, 4f).sqrt()).isEqualTo(FloatInterval(0f, 2f)) + assertThat(FloatInterval(-4f, 9f).sqrt()).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(FloatInterval(-4f, -1f).sqrt()).isEqualTo(FloatInterval.UNBOUNDED) + assertThat(FloatInterval.EMPTY.sqrt()).isEqualTo(FloatInterval.EMPTY) + + // Rounding: floor/ceil return closed intervals; round matches (float) Math.round(x) + assertThat(halfOpen.floor()).isEqualTo(FloatInterval(0f, 9f)) + assertThat(halfOpen.ceil()).isEqualTo(FloatInterval(0f, 10f)) + assertThat(FloatInterval.point(0.5f).round()).isEqualTo(FloatInterval.point(1f)) + assertThat(FloatInterval.point(-0.5f).round()).isEqualTo(FloatInterval.point(0f)) + assertThat(FloatInterval.point(-1.5f).round()).isEqualTo(FloatInterval.point(-1f)) + assertThat(FloatInterval(1e12f, 2e12f).round()) + .isEqualTo(FloatInterval.point(Int.MAX_VALUE.toFloat())) + assertThat(FloatInterval.UNBOUNDED.round()) + .isEqualTo(FloatInterval(Int.MIN_VALUE.toFloat(), Int.MAX_VALUE.toFloat())) + + // Periodic trig & rem (including infinite divisor keeping infinite endpoints closed) + assertThat(FloatInterval(0f, (2.0 * PI).toFloat()).sin()).isEqualTo(FloatInterval(-1f, 1f)) + assertThat(FloatInterval(0f, PI.toFloat()).cos()).isEqualTo(FloatInterval(-1f, 1f)) + val cosHalfPi = FloatInterval(0f, (PI / 2.0).toFloat()).cos() + assertThat(cosHalfPi.max).isEqualTo(1f) + assertThat(cosHalfPi.min in -1e-6f..0f).isTrue() + val remHalfOpen = + FloatInterval(0f, 3600f, minInclusive = true, maxInclusive = false) % + FloatInterval.point(60f) + assertThat(remHalfOpen) + .isEqualTo(FloatInterval(0f, 60f, minInclusive = true, maxInclusive = false)) + + val remSameBucket = FloatInterval(65f, 70f) % FloatInterval.point(60f) + assertThat(remSameBucket).isEqualTo(FloatInterval(5f, 10f)) + + val remInfDiv = FloatInterval(0f, 10f) % FloatInterval(1f, Float.POSITIVE_INFINITY) + assertThat(remInfDiv).isEqualTo(FloatInterval(0f, Float.POSITIVE_INFINITY)) + assertThat(remInfDiv.maxInclusive).isTrue() + + // All FloatInterval comparison operators + val lo = FloatInterval(0f, 5f) + val hi = FloatInterval(6f, 10f) + assertThat(lo.compare(IntervalComparison.LT, hi)).isEqualTo(TriState.TRUE) + assertThat(lo.compare(IntervalComparison.LTE, hi)).isEqualTo(TriState.TRUE) + assertThat(lo.compare(IntervalComparison.GT, hi)).isEqualTo(TriState.FALSE) + assertThat(lo.compare(IntervalComparison.GTE, hi)).isEqualTo(TriState.FALSE) + assertThat(lo.compare(IntervalComparison.EQ, hi)).isEqualTo(TriState.FALSE) + assertThat(lo.compare(IntervalComparison.NEQ, hi)).isEqualTo(TriState.TRUE) + } + + @Test + fun intInterval_arithmeticOverflowSentinelsRemAndComparisons() { + assertThat(IntInterval(1, 3) + IntInterval(2, 4)).isEqualTo(IntInterval(3, 7)) + assertThat(IntInterval(1, 3) - IntInterval(2, 4)).isEqualTo(IntInterval(-3, 1)) + assertThat(-IntInterval(1, 3)).isEqualTo(IntInterval(-3, -1)) + assertThat(IntInterval.UNBOUNDED * IntInterval.ZERO).isEqualTo(IntInterval.ZERO) + assertThat(IntInterval(1, 10) / IntInterval(-1, 1)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(IntInterval(-5, 3).abs()).isEqualTo(IntInterval(0, 5)) + assertThat(IntInterval(1, 5).min(IntInterval(2, 3))).isEqualTo(IntInterval(1, 3)) + assertThat(IntInterval(1, 5).max(IntInterval(2, 3))).isEqualTo(IntInterval(2, 5)) + assertThat(IntInterval(1, 4).union(IntInterval(6, 10))).isEqualTo(IntInterval(1, 10)) + assertThat(IntInterval(1, 6).intersect(IntInterval(4, 10))).isEqualTo(IntInterval(4, 6)) + assertThat(IntInterval(-1, 10).clamp(IntInterval.point(2), IntInterval.point(4))) + .isEqualTo(IntInterval(2, 4)) + assertThat(IntInterval(-5, 20).clampToRange(0, 10)).isEqualTo(IntInterval(0, 10)) + assertThat(IntInterval.UNBOUNDED.clampToRange(0, 255)).isEqualTo(IntInterval(0, 255)) + assertThat(IntInterval.EMPTY.clampToRange(0, 10)).isEqualTo(IntInterval.EMPTY) + assertFailsWith<IllegalArgumentException> { IntInterval(0, 10).clampToRange(10, 0) } + assertThat(IntInterval(0, 3599) % IntInterval.point(60)).isEqualTo(IntInterval(0, 59)) + assertThat(IntInterval(65, 70) % IntInterval.point(60)).isEqualTo(IntInterval(5, 10)) + + // Constructor normalizes out-of-sentinel and empty bounds + assertThat(IntInterval(Int.MIN_VALUE, Int.MAX_VALUE)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(IntInterval(5, 2)).isEqualTo(IntInterval.EMPTY) + + // Non-wrapping sentinel saturation + val huge = IntInterval.point(IntInterval.MAX_BOUND - 1) + IntInterval.point(10) + assertThat(huge.isUnbounded).isTrue() + assertThat(huge.isEmpty).isFalse() + assertThat((IntInterval.MAX_BOUND + 9) in huge).isTrue() + + // 32-bit wrap-around soundness regressions + assertThat(IntInterval.point(Int.MAX_VALUE) + IntInterval.point(1)) + .isEqualTo(IntInterval.UNBOUNDED) + assertThat(IntInterval.NON_NEGATIVE + IntInterval.point(1)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(IntInterval.point(Int.MIN_VALUE) - IntInterval.point(1)) + .isEqualTo(IntInterval.UNBOUNDED) + assertThat(IntInterval.point(50_000) * IntInterval.point(50_000)) + .isEqualTo(IntInterval.UNBOUNDED) + assertThat(IntInterval.UNBOUNDED.abs()).isEqualTo(IntInterval.UNBOUNDED) + assertThat(Int.MIN_VALUE in IntInterval.UNBOUNDED.abs()).isTrue() + assertThat(-IntInterval.UNBOUNDED).isEqualTo(IntInterval.UNBOUNDED) + assertThat(-IntInterval.point(Int.MIN_VALUE)).isEqualTo(IntInterval.UNBOUNDED) + assertThat(IntInterval.point(Int.MIN_VALUE) / IntInterval.point(-1)) + .isEqualTo(IntInterval.UNBOUNDED) + // Non-wrapping unbounded ops retain tight bounds + assertThat(IntInterval.NON_NEGATIVE + IntInterval(-5, -1)) + .isEqualTo(IntInterval(-5, IntInterval.MAX_BOUND)) + assertThat(-IntInterval.NON_NEGATIVE).isEqualTo(IntInterval(IntInterval.MIN_BOUND, 0)) + + assertThat(IntInterval(0, 5).compare(IntervalComparison.LT, IntInterval(6, 10))) + .isEqualTo(TriState.TRUE) + assertThat(IntInterval(0, 5).compare(IntervalComparison.LTE, IntInterval(5, 10))) + .isEqualTo(TriState.TRUE) + assertThat(IntInterval(6, 10).compare(IntervalComparison.LT, IntInterval(0, 5))) + .isEqualTo(TriState.FALSE) + assertThat(IntInterval(6, 10).compare(IntervalComparison.GT, IntInterval(0, 5))) + .isEqualTo(TriState.TRUE) + assertThat(IntInterval(5, 10).compare(IntervalComparison.GTE, IntInterval(0, 5))) + .isEqualTo(TriState.TRUE) + assertThat(IntInterval.point(7).compare(IntervalComparison.EQ, IntInterval.point(7))) + .isEqualTo(TriState.TRUE) + assertThat(IntInterval(0, 5).compare(IntervalComparison.NEQ, IntInterval(6, 10))) + .isEqualTo(TriState.TRUE) + assertThat(IntInterval(0, 6).compareLessThan(IntInterval(5, 10))) + .isEqualTo(TriState.UNKNOWN) + } + + @Test + fun slotInterval_coupledFloatIntNormalizationUnionAndSystemGlobals() { + // Normalization, equals/hashCode, and union idempotence + val unnormalizedEmpty = SlotInterval(0f, 1f, 5, 2) + val canonicalEmpty = SlotInterval(0f, 1f, 1, 0) + assertThat(unnormalizedEmpty).isEqualTo(canonicalEmpty) + assertThat(unnormalizedEmpty.hashCode()).isEqualTo(canonicalEmpty.hashCode()) + assertThat(unnormalizedEmpty.union(unnormalizedEmpty)).isEqualTo(unnormalizedEmpty) + + val unnormalizedSentinel = SlotInterval(0f, 1f, Int.MIN_VALUE, Int.MAX_VALUE) + val canonicalSentinel = SlotInterval(0f, 1f, IntInterval.MIN_BOUND, IntInterval.MAX_BOUND) + assertThat(unnormalizedSentinel).isEqualTo(canonicalSentinel) + assertThat(unnormalizedSentinel.hashCode()).isEqualTo(canonicalSentinel.hashCode()) + assertThat(unnormalizedSentinel.union(unnormalizedSentinel)).isEqualTo(unnormalizedSentinel) + + val joined = SlotInterval.fromFloatPoint(1.5f).union(SlotInterval.fromIntPoint(5)) + assertThat(joined.toFloatInterval()).isEqualTo(FloatInterval(1.5f, 5f)) + assertThat(joined.toIntInterval()).isEqualTo(IntInterval(1, 5)) + + val secSlot = SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_CONTINUOUS_SEC) + assertNotNull(secSlot) + assertThat(secSlot.toFloatInterval()) + .isEqualTo(FloatInterval(0f, 3600f, minInclusive = true, maxInclusive = false)) + assertThat(secSlot.toIntInterval()).isEqualTo(IntInterval(0, 3599)) + + assertThat( + SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_TIME_IN_SEC)?.toIntInterval() + ) + .isEqualTo(IntInterval(0, 3599)) + assertThat( + SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_TIME_IN_MIN)?.toIntInterval() + ) + .isEqualTo(IntInterval(0, 1439)) + assertThat(SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_TIME_IN_HR)?.toIntInterval()) + .isEqualTo(IntInterval(0, 23)) + assertThat( + SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_CALENDAR_MONTH)?.toIntInterval() + ) + .isEqualTo(IntInterval(1, 12)) + assertThat(SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_WEEK_DAY)?.toIntInterval()) + .isEqualTo(IntInterval(1, 7)) + assertThat( + SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_DAY_OF_MONTH)?.toIntInterval() + ) + .isEqualTo(IntInterval(1, 31)) + assertThat( + SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_DAY_OF_YEAR)?.toIntInterval() + ) + .isEqualTo(IntInterval(1, 366)) + + val winW = + SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_WINDOW_WIDTH, canvasWidth = 450f) + assertNotNull(winW) + assertThat(winW.toFloatInterval()).isEqualTo(FloatInterval.point(450f)) + assertThat(winW.toIntInterval()).isEqualTo(IntInterval.point(450)) + assertThat(SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_WINDOW_WIDTH)).isNull() + + val winH = + SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_WINDOW_HEIGHT, canvasHeight = 800f) + assertThat(winH?.toFloatInterval()).isEqualTo(FloatInterval.point(800f)) + assertThat(SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_WINDOW_HEIGHT)).isNull() + + for (id in + intArrayOf( + RemoteContextIds.ID_COMPONENT_WIDTH, + RemoteContextIds.ID_COMPONENT_HEIGHT, + RemoteContextIds.ID_ANIMATION_TIME, + )) { + assertThat(SlotInterval.systemGlobalOrNull(id)?.toFloatInterval()) + .isEqualTo(FloatInterval(0f, Float.POSITIVE_INFINITY)) + } + assertThat(SlotInterval.systemGlobalOrNull(RemoteContextIds.ID_ANIMATION_DELTA_TIME)) + .isEqualTo(SlotInterval.UNBOUNDED) + assertThat(SlotInterval.systemGlobalOrNull(9999)).isNull() + assertThat(SlotInterval.fromFloat(FloatInterval.EMPTY)).isEqualTo(SlotInterval.UNBOUNDED) + assertThat(SlotInterval.fromInt(IntInterval.EMPTY)).isEqualTo(SlotInterval.UNBOUNDED) + } +}
diff --git a/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/StringAndColorIntervalTest.kt b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/StringAndColorIntervalTest.kt new file mode 100644 index 0000000..b30c07a1 --- /dev/null +++ b/compose/remote/remote-creation-expression/src/test/java/androidx/compose/remote/document/intervals/StringAndColorIntervalTest.kt
@@ -0,0 +1,504 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.document.intervals + +import androidx.compose.remote.core.operations.ColorAttribute +import androidx.compose.remote.core.operations.TextTransform +import androidx.compose.remote.document.ColorAttributeType +import androidx.compose.remote.document.RemoteColorMath +import androidx.compose.remote.document.TextFromFloatFlags +import androidx.compose.remote.document.TextFromFloatFormatter +import androidx.compose.remote.document.TextTransformOperation +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage +import kotlin.math.nextDown +import kotlin.math.nextUp +import kotlin.test.Test + +class StringAndColorIntervalTest { + + @Test + fun protocolConstantParityWithRemoteCore() { + assertThat(ColorAttributeType.HUE).isEqualTo(ColorAttribute.COLOR_HUE.toInt()) + assertThat(ColorAttributeType.SATURATION).isEqualTo(ColorAttribute.COLOR_SATURATION.toInt()) + assertThat(ColorAttributeType.BRIGHTNESS).isEqualTo(ColorAttribute.COLOR_BRIGHTNESS.toInt()) + assertThat(ColorAttributeType.RED).isEqualTo(ColorAttribute.COLOR_RED.toInt()) + assertThat(ColorAttributeType.GREEN).isEqualTo(ColorAttribute.COLOR_GREEN.toInt()) + assertThat(ColorAttributeType.BLUE).isEqualTo(ColorAttribute.COLOR_BLUE.toInt()) + assertThat(ColorAttributeType.ALPHA).isEqualTo(ColorAttribute.COLOR_ALPHA.toInt()) + + assertThat(TextTransformOperation.TO_LOWERCASE).isEqualTo(TextTransform.TEXT_TO_LOWERCASE) + assertThat(TextTransformOperation.TO_UPPERCASE).isEqualTo(TextTransform.TEXT_TO_UPPERCASE) + assertThat(TextTransformOperation.TRIM).isEqualTo(TextTransform.TEXT_TRIM) + assertThat(TextTransformOperation.CAPITALIZE).isEqualTo(TextTransform.TEXT_CAPITALIZE) + assertThat(TextTransformOperation.UPPERCASE_FIRST_CHAR) + .isEqualTo(TextTransform.TEXT_UPPERCASE_FIRST_CHAR) + } + + @Test + fun stringSummary_textFromFloatMergeSubstringAndTransform() { + val exact = + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval.point(7f), + digitsBefore = 2, + digitsAfter = 0, + flags = TextFromFloatFlags.PAD_PRE_ZERO or TextFromFloatFlags.PAD_AFTER_NONE, + ) + assertThat(exact.constantValue).isEqualTo("07") + assertThat(exact.length).isEqualTo(IntInterval.point(2)) + + val ranged = + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval(0f, 59f), + digitsBefore = 2, + digitsAfter = 0, + flags = TextFromFloatFlags.PAD_PRE_ZERO or TextFromFloatFlags.PAD_AFTER_NONE, + ) + assertThat(ranged.constantValue).isNull() + assertThat(ranged.length).isEqualTo(IntInterval.point(2)) + assertThat(ranged.isAsciiOnly).isTrue() + + // Negative or excessively large digitsBefore/digitsAfter return UNKNOWN instead of throwing + for ((before, after) in + listOf( + -1 to 2, + 2 to -1, + TextFromFloatFormatter.MAX_DIGITS + 1 to 0, + 0 to TextFromFloatFormatter.MAX_DIGITS + 1, + )) { + assertThat( + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval.point(7f), + digitsBefore = before, + digitsAfter = after, + flags = 0, + ) + ) + .isEqualTo(StringSummary.UNKNOWN) + assertThat( + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval(0f, 59f), + digitsBefore = before, + digitsAfter = after, + flags = 0, + ) + ) + .isEqualTo(StringSummary.UNKNOWN) + } + + val merged = + StringAndColorIntervalOps.summarizeTextMerge( + StringSummary.constant("07"), + StringSummary.constant(":30"), + ) + assertThat(merged.constantValue).isEqualTo("07:30") + assertThat(merged.length).isEqualTo(IntInterval.point(5)) + + val sub = + StringAndColorIntervalOps.summarizeSubstring( + src = StringSummary.constant("HelloWorld"), + start = FloatInterval.point(5f), + len = FloatInterval.point(-1f), + ) + assertThat(sub.constantValue).isEqualTo("World") + + val trimmed = + StringAndColorIntervalOps.summarizeTextTransform( + src = StringSummary.constant(" abc "), + start = FloatInterval.ZERO, + len = FloatInterval.point(-1f), + operation = TextTransformOperation.TRIM, + ) + assertThat(trimmed.constantValue).isEqualTo("abc") + + val upper = + StringAndColorIntervalOps.summarizeTextTransform( + src = StringSummary.constant("abc"), + start = FloatInterval.ZERO, + len = FloatInterval.point(-1f), + operation = TextTransformOperation.TO_UPPERCASE, + ) + assertThat(upper.length).isEqualTo(IntInterval.point(3)) + assertThat(upper.isAsciiOnly).isFalse() + + // Open adjacent-float interval regression (no Int.MAX_VALUE / Int.MIN_VALUE overflow) + val openAdjacentPos = + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval(10f.nextDown(), 10f, minInclusive = false, maxInclusive = false), + digitsBefore = 4, + digitsAfter = 2, + flags = TextFromFloatFlags.PAD_PRE_NONE or TextFromFloatFlags.PAD_AFTER_NONE, + ) + assertThat(openAdjacentPos).isEqualTo(StringSummary.UNKNOWN) + val openAdjacentNeg = + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval(-10f, (-10f).nextUp(), minInclusive = false, maxInclusive = false), + digitsBefore = 4, + digitsAfter = 2, + flags = TextFromFloatFlags.PAD_PRE_NONE or TextFromFloatFlags.PAD_AFTER_NONE, + ) + assertThat(openAdjacentNeg).isEqualTo(StringSummary.UNKNOWN) + assertThat( + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval.EMPTY, + digitsBefore = 2, + digitsAfter = 0, + flags = 0, + ) + ) + .isEqualTo(StringSummary.UNKNOWN) + + // TextFromFloat negative parentheses, grouping, rounding, legacy, and FULL_FORMAT + val negParens = + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval(-9999f, -1000f), + digitsBefore = 6, + digitsAfter = 2, + flags = + TextFromFloatFlags.PAD_PRE_NONE or + TextFromFloatFlags.PAD_AFTER_ZERO or + TextFromFloatFlags.GROUPING_BY3 or + TextFromFloatFlags.OPTIONS_ROUNDING or + TextFromFloatFlags.OPTIONS_NEGATIVE_PARENTHESES, + ) + assertThat(negParens.length.min).isAtLeast(10) + assertThat(negParens.isAsciiOnly).isTrue() + + val legacyRange = + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval(0f, 999f), + digitsBefore = 3, + digitsAfter = 2, + flags = + TextFromFloatFlags.PAD_PRE_NONE or + TextFromFloatFlags.PAD_AFTER_NONE or + TextFromFloatFlags.LEGACY_MODE, + ) + assertThat(legacyRange.length).isEqualTo(IntInterval(2, 6)) + + val fullFmt = + StringAndColorIntervalOps.summarizeTextFromFloat( + FloatInterval(0f, 10f), + digitsBefore = 2, + digitsAfter = 2, + flags = TextFromFloatFlags.FULL_FORMAT, + ) + assertThat(fullFmt.length).isEqualTo(IntInterval(3, 16)) + + // Non-point summarizeSubstring exercising summarizeFiniteSubstringLength + val finiteSub = + StringAndColorIntervalOps.summarizeSubstring( + src = StringSummary(IntInterval(10, 12), isAsciiOnly = true), + start = FloatInterval(2f, 4f), + len = FloatInterval(3f, 5f), + ) + assertThat(3 in finiteSub.length && 5 in finiteSub.length).isTrue() + assertThat(finiteSub.length.min).isAtLeast(3) + assertThat(finiteSub.length.max).isAtMost(6) + + val mixedSub = + StringAndColorIntervalOps.summarizeSubstring( + src = StringSummary(IntInterval(10, 10), isAsciiOnly = true), + start = FloatInterval.point(2f), + len = FloatInterval(-1f, 3f), + ) + assertThat(8 in mixedSub.length && 0 in mixedSub.length).isTrue() + + // Additional TextTransform operations & StringSummary union/equals + val cap = + StringAndColorIntervalOps.summarizeTextTransform( + src = StringSummary(IntInterval(2, 5), isAsciiOnly = true), + start = FloatInterval.ZERO, + len = FloatInterval.point(-1f), + operation = TextTransformOperation.CAPITALIZE, + ) + assertThat(cap.length).isEqualTo(IntInterval(2, 5)) + val nonAsciiLower = + StringAndColorIntervalOps.summarizeTextTransform( + src = StringSummary(IntInterval(2, 5), isAsciiOnly = false), + start = FloatInterval.ZERO, + len = FloatInterval.point(-1f), + operation = TextTransformOperation.TO_LOWERCASE, + ) + assertThat(nonAsciiLower.length).isEqualTo(IntInterval(1, 15)) + val dynTrim = + StringAndColorIntervalOps.summarizeTextTransform( + src = StringSummary(IntInterval(2, 5), isAsciiOnly = true), + start = FloatInterval.ZERO, + len = FloatInterval.point(-1f), + operation = TextTransformOperation.TRIM, + ) + assertThat(dynTrim.length).isEqualTo(IntInterval(0, 5)) + assertThat( + StringAndColorIntervalOps.summarizeTextTransform( + src = StringSummary.constant("abc"), + start = FloatInterval.ZERO, + len = FloatInterval.point(-1f), + operation = 99, + ) + ) + .isEqualTo(StringSummary.UNKNOWN) + val sUnion = StringSummary.constant("ab").union(StringSummary.constant("cde")) + assertThat(sUnion.constantValue).isNull() + assertThat(sUnion.length).isEqualTo(IntInterval(2, 3)) + assertThat(StringSummary.constant("ab").union(StringSummary.constant("ab"))) + .isEqualTo(StringSummary.constant("ab")) + assertThat(sUnion.hashCode()) + .isEqualTo(StringSummary(IntInterval(2, 3), isAsciiOnly = true).hashCode()) + } + + @Test + fun colorInterval_argbHsvTweenMultiplyAndAttribute() { + val red = ColorInterval.constant(0xFFFF0000.toInt()) + val blue = ColorInterval.constant(0xFF0000FF.toInt()) + + assertThat(red.toArgbOrNull()).isEqualTo(0xFFFF0000.toInt()) + assertThat(StringAndColorIntervalOps.summarizeColorAttribute(red, ColorAttributeType.RED)) + .isEqualTo(FloatInterval.point(1f)) + assertThat(StringAndColorIntervalOps.summarizeColorAttribute(red, ColorAttributeType.BLUE)) + .isEqualTo(FloatInterval.point(0f)) + + val tween = StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval(0f, 1f)) + assertThat(tween.alpha).isEqualTo(IntInterval.point(255)) + assertThat(tween.red).isEqualTo(IntInterval(0, 255)) + assertThat(tween.green).isEqualTo(IntInterval.point(0)) + assertThat(tween.blue).isEqualTo(IntInterval(0, 255)) + + // Point t inside [0, 1] and outside [0, 1] + assertThat( + StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval.point(0f)) + ) + .isEqualTo(red) + assertThat( + StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval.point(1f)) + ) + .isEqualTo(blue) + val midPoint = + StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval.point(0.5f)) + assertThat(midPoint.toArgbOrNull()) + .isEqualTo( + RemoteColorMath.interpolateColor(0xFFFF0000.toInt(), 0xFF0000FF.toInt(), 0.5f) + ) + assertThat( + StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval.point(-0.1f)) + ) + .isEqualTo(ColorInterval.UNKNOWN) + assertThat( + StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval.point(1.5f)) + ) + .isEqualTo(ColorInterval.UNKNOWN) + + // Non-point ColorInterval soundness near t = 1f.nextDown() (both point and ranged t) + val c1Range = + ColorInterval( + alpha = IntInterval(1, 3), + red = IntInterval(2, 10), + green = IntInterval.point(0), + blue = IntInterval.point(0), + ) + val c2Range = + ColorInterval( + alpha = IntInterval(4, 10), + red = IntInterval(6, 20), + green = IntInterval.point(0), + blue = IntInterval.point(0), + ) + val nearOnePoint = FloatInterval.point(1f.nextDown()) + val nearOneRange = FloatInterval(1f.nextDown(), 1f) + val interiorSample = + RemoteColorMath.interpolateColor( + RemoteColorMath.argb(2, 3, 0, 0), + RemoteColorMath.argb(4, 6, 0, 0), + 1f.nextDown(), + ) + for (tInterval in listOf(nearOnePoint, nearOneRange)) { + val bound = StringAndColorIntervalOps.summarizeColorTween(c1Range, c2Range, tInterval) + assertWithMessage("t=$tInterval alpha=${bound.alpha}") + .that(RemoteColorMath.alpha(interiorSample) in bound.alpha) + .isTrue() + assertWithMessage("t=$tInterval red=${bound.red}") + .that(RemoteColorMath.red(interiorSample) in bound.red) + .isTrue() + // Exact constant channels remain un-widened + assertThat(bound.green).isEqualTo(IntInterval.point(0)) + assertThat(bound.blue).isEqualTo(IntInterval.point(0)) + } + // Exhaustively verify soundness for all interior pairs in c1Range x c2Range at + // 1f.nextDown() + val rangedBound = + StringAndColorIntervalOps.summarizeColorTween(c1Range, c2Range, nearOneRange) + for (a1 in 1..3) { + for (a2 in 4..10) { + for (r1 in 2..10) { + for (r2 in 6..20) { + val sample = + RemoteColorMath.interpolateColor( + RemoteColorMath.argb(a1, r1, 0, 0), + RemoteColorMath.argb(a2, r2, 0, 0), + 1f.nextDown(), + ) + assertThat(RemoteColorMath.alpha(sample) in rangedBound.alpha).isTrue() + assertThat(RemoteColorMath.red(sample) in rangedBound.red).isTrue() + } + } + } + } + + // Gamma round-trip dip regression across ALL 0..255 channel values at 0f.nextUp() and + // 1f.nextDown() + val samples = floatArrayOf(0f, 0f.nextUp(), 0.5f, 1f.nextDown(), 1f) + for (r in 0..255) { + val c = RemoteColorMath.argb(255, r, r, r) + val cInt = ColorInterval.constant(c) + val selfTween = + StringAndColorIntervalOps.summarizeColorTween(cInt, cInt, FloatInterval(0f, 1f)) + val toWhiteTween = + StringAndColorIntervalOps.summarizeColorTween( + cInt, + ColorInterval.constant(0xFFFFFFFF.toInt()), + FloatInterval(0f, 1f), + ) + for (tau in samples) { + val selfSample = RemoteColorMath.interpolateColor(c, c, tau) + assertWithMessage( + "r=$r tau=$tau selfTween=${selfTween.red} missed ${RemoteColorMath.red(selfSample)}" + ) + .that(RemoteColorMath.red(selfSample) in selfTween.red) + .isTrue() + val whiteSample = RemoteColorMath.interpolateColor(c, 0xFFFFFFFF.toInt(), tau) + assertWithMessage( + "r=$r tau=$tau toWhiteTween=${toWhiteTween.red} missed ${RemoteColorMath.red(whiteSample)}" + ) + .that(RemoteColorMath.red(whiteSample) in toWhiteTween.red) + .isTrue() + } + } + assertThat(StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval.EMPTY)) + .isEqualTo(ColorInterval.UNKNOWN) + assertThat( + StringAndColorIntervalOps.summarizeColorTween(red, blue, FloatInterval(-0.5f, 1.5f)) + ) + .isEqualTo(ColorInterval.UNKNOWN) + + // summarizeColorArgb: exact, ranged, open-endpoint rounding, and out-of-range spillover + val exactArgb = + StringAndColorIntervalOps.summarizeColorArgb( + FloatInterval.point(1f), + FloatInterval.point(0.5f), + FloatInterval.point(0f), + FloatInterval.point(1f), + ) + assertThat(exactArgb.toArgbOrNull()).isEqualTo(RemoteColorMath.toArgb(1f, 0.5f, 0f, 1f)) + val rangedArgb = + StringAndColorIntervalOps.summarizeColorArgb( + FloatInterval(0.5f, 1f), + FloatInterval(0f, 1f, minInclusive = true, maxInclusive = false), + FloatInterval.point(0.25f), + FloatInterval.point(0.75f), + ) + assertThat(rangedArgb.alpha).isEqualTo(IntInterval(128, 255)) + assertThat(255 in rangedArgb.red).isTrue() // (1f.nextDown() * 255f + 0.5f).toInt() == 255! + val overflowArgb = + StringAndColorIntervalOps.summarizeColorArgb( + FloatInterval.point(1f), + FloatInterval.point(0.5f), + FloatInterval.point(0.5f), + FloatInterval(0f, 2f), // overflows blue byte into green/red/alpha + ) + assertThat(overflowArgb).isEqualTo(ColorInterval.UNKNOWN) + + val hsv = + StringAndColorIntervalOps.summarizeColorHsv( + alpha = 0x80, + hue = FloatInterval(0f, 1f, minInclusive = true, maxInclusive = false), + saturation = FloatInterval.point(0.5f), + value = FloatInterval.point(1f), + ) + assertThat(hsv.alpha).isEqualTo(IntInterval.point(0x80)) + assertThat(hsv.red.min).isAtLeast(127) + assertThat(hsv.red.max).isEqualTo(255) + val hsvIncludingOne = + StringAndColorIntervalOps.summarizeColorHsv( + alpha = 0xFF, + hue = FloatInterval(0f, 1f), + saturation = FloatInterval.point(0.5f), + value = FloatInterval.point(1f), + ) + assertThat(hsvIncludingOne.red.min).isEqualTo(0) + val hsvOutOfRange = + StringAndColorIntervalOps.summarizeColorHsv( + alpha = 0xFF, + hue = FloatInterval(-1f, 2f), + saturation = FloatInterval.point(0.5f), + value = FloatInterval.point(1f), + ) + assertThat(hsvOutOfRange.red).isEqualTo(ColorInterval.BYTE_RANGE) + + val multiplied = StringAndColorIntervalOps.summarizeColorMultiply(red, blue) + assertThat(multiplied.toArgbOrNull()).isEqualTo(0xFF000000.toInt()) + val rangedColor = + ColorInterval( + alpha = IntInterval(128, 255), + red = IntInterval(200, 255), + green = IntInterval(0, 50), + blue = IntInterval(0, 50), + ) + assertThat(rangedColor.toArgbOrNull()).isNull() + val nonPointMul = StringAndColorIntervalOps.summarizeColorMultiply(rangedColor, red) + assertThat(nonPointMul.blue).isEqualTo(IntInterval.point(0)) + assertThat(nonPointMul.red.min).isAtLeast(200) + + // Non-point summarizeColorAttribute across all attributes + assertThat( + StringAndColorIntervalOps.summarizeColorAttribute( + rangedColor, + ColorAttributeType.ALPHA, + ) + ) + .isEqualTo(FloatInterval(128 / 255f, 1f)) + assertThat( + StringAndColorIntervalOps.summarizeColorAttribute( + rangedColor, + ColorAttributeType.BRIGHTNESS, + ) + ) + .isEqualTo(FloatInterval(200 / 255f, 1f)) + val sat = + StringAndColorIntervalOps.summarizeColorAttribute( + rangedColor, + ColorAttributeType.SATURATION, + ) + assertThat(sat.min).isGreaterThan(0.7f) + assertThat(sat.max).isEqualTo(1f) + assertThat( + StringAndColorIntervalOps.summarizeColorAttribute( + rangedColor, + ColorAttributeType.HUE, + ) + ) + .isEqualTo(FloatInterval(0f, 1f, minInclusive = true, maxInclusive = false)) + assertThat(StringAndColorIntervalOps.summarizeColorAttribute(rangedColor, 99)) + .isEqualTo(FloatInterval.UNBOUNDED) + + // ColorInterval union/equals/hashCode + val cUnion = red.union(blue) + assertThat(cUnion.red).isEqualTo(IntInterval(0, 255)) + assertThat(cUnion.blue).isEqualTo(IntInterval(0, 255)) + assertThat(cUnion).isEqualTo(blue.union(red)) + assertThat(cUnion.hashCode()).isEqualTo(blue.union(red).hashCode()) + } +}
diff --git a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/JsonSchemaParser.kt b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/JsonSchemaParser.kt index a248a92..db58f92 100644 --- a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/JsonSchemaParser.kt +++ b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/JsonSchemaParser.kt
@@ -181,6 +181,14 @@ } } + val visibilityConstants = linkedMapOf<String, Int>() + if (root.has("visibilityConstants")) { + val vcObj = root.getJSONObject("visibilityConstants") + for (constKey in vcObj.keys()) { + visibilityConstants[constKey] = vcObj.getInt(constKey) + } + } + val idEncoding = if (root.has("idEncoding")) { val obj = root.getJSONObject("idEncoding") @@ -199,6 +207,8 @@ valueMask = obj.getInt("valueMask"), macroLocalStartId = obj.getInt("macroLocalStartId"), macroLocalEndId = obj.getInt("macroLocalEndId"), + nanExponent = obj.optInt("nanExponent", 0x7F800000), + noId = obj.optInt("noId", -1), ) } else null @@ -327,6 +337,8 @@ val opCodeName = if (opObj.has("opCodeName")) opObj.getString("opCodeName") else null + val javaClassName = + if (opObj.has("javaClass")) opObj.getString("javaClass") else null val restrictToLibraryGroup = opObj.optBoolean("restrictToLibraryGroup", true) val encoding = if (opObj.has("encoding")) opObj.getString("encoding") else null @@ -406,6 +418,29 @@ sparseParameters = sparseParameters, allowedChildren = allowedChildren, conditionalSkip = conditionalSkip, + javaClassName = javaClassName, + ) + ) + } + } + + val reservedOpcodes = mutableListOf<SchemaReservedOpcode>() + if (root.has("reservedOpcodes")) { + val resArray = root.getJSONArray("reservedOpcodes") + for (i in 0 until resArray.length()) { + val rObj = resArray.getJSONObject(i) + val rProfiles = + if (rObj.has("profiles")) { + val pArr = rObj.getJSONArray("profiles") + (0 until pArr.length()).map { pArr.getString(it) } + } else emptyList() + reservedOpcodes.add( + SchemaReservedOpcode( + id = rObj.getInt("id"), + name = rObj.getString("name"), + opCodeName = rObj.getString("opCodeName"), + profiles = rProfiles, + description = rObj.optString("description", ""), ) ) } @@ -424,9 +459,11 @@ pathCommands = pathCommands, systemVariables = systemVariables, headerConstants = headerConstants, + visibilityConstants = visibilityConstants, idEncoding = idEncoding, animationSpec = animationSpec, pathEffects = pathEffects, + reservedOpcodes = reservedOpcodes, ) } @@ -476,12 +513,18 @@ val structObj = structsObj.getJSONObject(structName) if (structObj.has("fields")) { val sfArray = structObj.getJSONArray("fields") + val fieldIndexByName = + (0 until sfArray.length()).associate { + sfArray.getJSONObject(it).getString("name") to it + } for (j in 0 until sfArray.length()) { validateField( owner = "Struct $structName", f = sfArray.getJSONObject(j), declaredTypes = declaredTypes, errors = errors, + fieldIndex = j, + fieldIndexByName = fieldIndexByName, ) } } @@ -492,12 +535,28 @@ val opsArray = root.getJSONArray("operations") val seenIds = mutableSetOf<Int>() val seenNames = mutableSetOf<String>() + val seenOpCodeNames = mutableSetOf<String>() var prevId = -1 for (i in 0 until opsArray.length()) { val op = opsArray.getJSONObject(i) val id = op.getInt("id") val name = op.getString("name") + val opCodeName = + if (op.has("opCodeName")) { + val explicit = op.opt("opCodeName") as? String + if (explicit.isNullOrBlank()) { + errors.add("Operation $name has blank or non-string opCodeName") + null + } else { + explicit + } + } else { + SchemaOperation.toScreamingSnakeCase(name) + } + if (opCodeName != null && !seenOpCodeNames.add(opCodeName)) { + errors.add("Duplicate operation opCodeName: $opCodeName ($name)") + } if (id !in 0..255) { errors.add("Operation $name has invalid ID $id (must be 0..255)") @@ -513,15 +572,27 @@ if (!seenNames.add(name)) { errors.add("Duplicate operation name: $name") } + if (op.has("javaClass")) { + val jc = op.opt("javaClass") as? String + if (jc.isNullOrBlank()) { + errors.add("Operation $name has blank or non-string javaClass") + } + } if (op.has("fields")) { val fArray = op.getJSONArray("fields") + val fieldIndexByName = + (0 until fArray.length()).associate { + fArray.getJSONObject(it).getString("name") to it + } for (j in 0 until fArray.length()) { validateField( owner = "Operation $name", f = fArray.getJSONObject(j), declaredTypes = declaredTypes, errors = errors, + fieldIndex = j, + fieldIndexByName = fieldIndexByName, ) } } @@ -733,10 +804,88 @@ } } + // 10. Reserved opcodes validation + if (root.has("reservedOpcodes")) { + val resArr = root.getJSONArray("reservedOpcodes") + val resIds = mutableSetOf<Int>() + val resNames = mutableSetOf<String>() + val resOpCodeNames = mutableSetOf<String>() + var prevResId = -1 + for (i in 0 until resArr.length()) { + val rObj = resArr.getJSONObject(i) + val rawId = rObj.opt("id") + val rId: Int? = + when (rawId) { + is Int -> rawId + is Long -> + if (rawId in Int.MIN_VALUE..Int.MAX_VALUE) rawId.toInt() else null + else -> null + } + val rName = rObj.opt("name") as? String + if (rId == null) { + errors.add("Reserved opcode at index $i must specify an integer id") + continue + } + if (rName.isNullOrBlank()) { + errors.add("Reserved opcode ($rId) at index $i must specify a non-blank name") + continue + } + if (rId !in 0..255) { + errors.add("Reserved opcode $rName has invalid ID $rId (must be 0..255)") + } else { + if (rId <= prevResId) { + errors.add( + "reservedOpcodes not sorted: $rName ($rId) <= previous ID $prevResId at index $i" + ) + } + prevResId = rId + } + if (!resIds.add(rId)) { + errors.add("Duplicate reserved opcode ID: $rId ($rName)") + } + if (rId in seenIds) { + errors.add("Reserved opcode $rName ($rId) overlaps declared operation ID $rId") + } + if (!resNames.add(rName) || rName in seenNames) { + errors.add("Duplicate reserved opcode name: $rName") + } + val rOpCodeName = rObj.opt("opCodeName") as? String + if (rOpCodeName.isNullOrBlank()) { + errors.add("Reserved opcode $rName ($rId) must specify a non-blank opCodeName") + } else { + if (!resOpCodeNames.add(rOpCodeName)) { + errors.add("Duplicate reserved opcode opCodeName: $rOpCodeName") + } + if (rOpCodeName in seenOpCodeNames) { + errors.add( + "Reserved opcode $rName opCodeName '$rOpCodeName' collides with declared operation" + ) + } + } + if (rObj.has("profiles")) { + val pArr = rObj.optJSONArray("profiles") + if (pArr == null) { + errors.add("Reserved opcode $rName ($rId) profiles must be an array") + } else { + for (pIdx in 0 until pArr.length()) { + val profile = pArr.opt(pIdx) as? String + if (profile == null || profile !in VALID_PROFILES) { + errors.add( + "Reserved opcode $rName ($rId) has unknown profile '$profile'" + ) + } + } + } + } + } + } + return errors } private val VALID_LENGTH_TYPES = setOf("ubyte", "byte", "ushort", "short", "int") + private val VALID_PROFILES = + setOf("baseline", "androidx", "widgets", "oem", "experimental", "deprecated", "reserved") private fun isDeclaredSchemaType(type: String, declaredTypes: Set<String>): Boolean { val elemType = type.removeSuffix("[]") @@ -757,6 +906,8 @@ f: JSONObject, declaredTypes: Set<String>, errors: MutableList<String>, + fieldIndex: Int = -1, + fieldIndexByName: Map<String, Int> = emptyMap(), ) { val fName = f.getString("name") val fType = f.getString("type") @@ -818,6 +969,23 @@ errors.add("$owner field $fName sets payloadKind on non-bytes type '$fType'") } } + if (f.has("resolvedAfter")) { + val targetField = f.opt("resolvedAfter") as? String + if (targetField.isNullOrBlank()) { + errors.add("$owner field $fName has blank or non-string resolvedAfter") + } else { + val targetIdx = fieldIndexByName[targetField] + if (targetIdx == null) { + errors.add( + "$owner field $fName resolvedAfter references missing field '$targetField'" + ) + } else if (fieldIndex >= 0 && targetIdx <= fieldIndex) { + errors.add( + "$owner field $fName resolvedAfter '$targetField' must reference a later field" + ) + } + } + } if (f.has("conditionalTypes")) { val ctArr = f.getJSONArray("conditionalTypes") if (ctArr.length() == 0) { @@ -975,6 +1143,9 @@ } } else emptyList() + val resolvedAfter = + if (fieldObj.has("resolvedAfter")) fieldObj.getString("resolvedAfter") else null + return SchemaField( name = fieldName, type = fieldType, @@ -1003,6 +1174,7 @@ mustBeZeroBits = mustBeZeroBits, conditionalTypes = conditionalTypes, conditionalRoles = conditionalRoles, + resolvedAfter = resolvedAfter, ) } }
diff --git a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/OperationSchema.kt b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/OperationSchema.kt index 531798a..9b1131a 100644 --- a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/OperationSchema.kt +++ b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/OperationSchema.kt
@@ -34,9 +34,11 @@ public val pathCommands: Map<Int, SchemaPathCommand> = emptyMap(), public val systemVariables: List<SchemaSystemVariable> = emptyList(), public val headerConstants: Map<String, Map<String, Int>> = emptyMap(), + public val visibilityConstants: Map<String, Int> = emptyMap(), public val idEncoding: SchemaIdEncoding? = null, public val animationSpec: SchemaAnimationSpec? = null, public val pathEffects: SchemaPathEffects? = null, + public val reservedOpcodes: List<SchemaReservedOpcode> = emptyList(), ) { public val operationsById: Map<Int, SchemaOperation> = operations.associateBy { it.id } public val operationsByName: Map<String, SchemaOperation> = operations.associateBy { it.name } @@ -77,6 +79,15 @@ ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public class SchemaReservedOpcode( + public val id: Int, + public val name: String, + public val opCodeName: String, + public val profiles: List<String> = emptyList(), + public val description: String = "", +) + +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class SchemaIdEncoding( public val nanPrefix: Int, public val payloadMask: Int, @@ -92,6 +103,8 @@ public val valueMask: Int, public val macroLocalStartId: Int, public val macroLocalEndId: Int, + public val nanExponent: Int = 0x7F800000, + public val noId: Int = -1, ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @@ -190,10 +203,14 @@ public val sparseParameters: List<SchemaSparseParam>? = null, public val allowedChildren: List<String>? = null, public val conditionalSkip: SchemaConditionalSkip? = null, + public val javaClassName: String? = null, ) { public val resolvedOpCodeName: String get() = opCodeName ?: ID_TO_OPCODE_NAME[id] ?: toScreamingSnakeCase(name) + public val resolvedJavaClassName: String + get() = javaClassName ?: name + public val astProperties: List<AstProperty> get() = buildAstProperties(fields, sparseParameters) @@ -257,6 +274,7 @@ public val mustBeZeroBits: String? = null, public val conditionalTypes: List<SchemaConditionalType> = emptyList(), public val conditionalRoles: List<SchemaConditionalRole> = emptyList(), + public val resolvedAfter: String? = null, ) { public val effectiveLengthType: String get() = lengthType ?: "short"
diff --git a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinProtocolAndSinkGenerator.kt b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinProtocolAndSinkGenerator.kt index fd7d592..99f30a2 100644 --- a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinProtocolAndSinkGenerator.kt +++ b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinProtocolAndSinkGenerator.kt
@@ -241,6 +241,19 @@ .build() ) .addProperty( + PropertySpec.builder("NAN_EXPONENT", INT, KModifier.PRIVATE, KModifier.CONST) + .initializer( + "%L", + "0x${(schema.idEncoding?.nanExponent ?: 0x7F800000).toUInt().toString(16).uppercase()}", + ) + .build() + ) + .addProperty( + PropertySpec.builder("NO_ID", INT, KModifier.PRIVATE, KModifier.CONST) + .initializer("%L", schema.idEncoding?.noId ?: -1) + .build() + ) + .addProperty( PropertySpec.builder("PAYLOAD_MASK", INT, KModifier.PRIVATE, KModifier.CONST) .initializer("%L", "0x3FFFFF") .build() @@ -267,13 +280,6 @@ .build() ) } - if ("STORE_RO" in rpn.operatorsByName && "STORE_R0" !in rpn.operatorsByName) { - builder.addProperty( - PropertySpec.builder("ID_STORE_R0", INT, KModifier.PUBLIC, KModifier.CONST) - .initializer("ID_STORE_RO") - .build() - ) - } for (op in rpn.operators) { builder.addProperty( @@ -296,13 +302,6 @@ .build() ) } - if ("STORE_RO" in rpn.operatorsByName && "STORE_R0" !in rpn.operatorsByName) { - builder.addProperty( - PropertySpec.builder("STORE_R0", FLOAT, KModifier.PUBLIC) - .initializer("STORE_RO") - .build() - ) - } builder.addFunction( FunSpec.builder("tokenFromId") @@ -330,7 +329,7 @@ .addParameter("token", FLOAT) .returns(BOOLEAN) .addStatement("val bits = token.toRawBits()") - .addStatement("if ((bits and NAN_PREFIX) != NAN_PREFIX) return false") + .addStatement("if ((bits and NAN_EXPONENT) != NAN_EXPONENT) return false") .addStatement("val id = (bits and PAYLOAD_MASK) - OFFSET") .addStatement("return id in 1..MAX_ID && id != 68 && id != 69") .build() @@ -345,7 +344,7 @@ .addModifiers(KModifier.PUBLIC) .addParameter("token", FLOAT) .returns(INT) - .addStatement("if (!isOperator(token)) return -1") + .addStatement("if (!isOperator(token)) return NO_ID") .addStatement("return (token.toRawBits() and PAYLOAD_MASK) - OFFSET") .build() ) @@ -361,7 +360,7 @@ .addParameter("apiLevel", INT) .returns(BOOLEAN) .addStatement("val id = operatorId(token)") - .addStatement("if (id == -1) return true") + .addStatement("if (id == NO_ID) return true") .addStatement( "return if (apiLevel <= 6) id <= API_LEVEL_6_MAX_ID else id <= MAX_ID" )
diff --git a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinWireCodecsGenerator.kt b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinWireCodecsGenerator.kt index 4df1da6..aaf84c0 100644 --- a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinWireCodecsGenerator.kt +++ b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/KotlinWireCodecsGenerator.kt
@@ -210,7 +210,9 @@ val intConsts = listOf( "NAN_PREFIX" to enc.nanPrefix, + "NAN_EXPONENT" to enc.nanExponent, "PAYLOAD_MASK" to enc.payloadMask, + "NO_ID" to enc.noId, "START_ID" to enc.startId, "REGION_MASK" to enc.regionMask, "REGION_SUB_ID_MASK" to enc.regionSubIdMask,
diff --git a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/MultiLangProtocolGenerator.kt b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/MultiLangProtocolGenerator.kt index 2912965..f0a4bc0 100644 --- a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/MultiLangProtocolGenerator.kt +++ b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/MultiLangProtocolGenerator.kt
@@ -128,7 +128,9 @@ schema.idEncoding?.let { enc -> w.block("namespace IdEncoding", close = "} // namespace IdEncoding") { line("inline constexpr int32_t NAN_PREFIX = ${enc.nanPrefix};") + line("inline constexpr int32_t NAN_EXPONENT = ${enc.nanExponent};") line("inline constexpr int32_t PAYLOAD_MASK = ${enc.payloadMask};") + line("inline constexpr int32_t NO_ID = ${enc.noId};") line("inline constexpr int32_t START_ID = ${enc.startId};") line("inline constexpr int32_t REGION_MASK = ${enc.regionMask};") line("inline constexpr int32_t REGION_SUB_ID_MASK = ${enc.regionSubIdMask};") @@ -143,10 +145,10 @@ line("inline constexpr int32_t MACRO_LOCAL_START_ID = ${enc.macroLocalStartId};") line("inline constexpr int32_t MACRO_LOCAL_END_ID = ${enc.macroLocalEndId};") line( - "inline bool isNanBits(int32_t bits) { return (bits & NAN_PREFIX) == NAN_PREFIX && (bits & PAYLOAD_MASK) != 0; }" + "inline bool isNanBits(int32_t bits) { return (bits & NAN_EXPONENT) == NAN_EXPONENT && (bits & PAYLOAD_MASK) != 0; }" ) line( - "inline int32_t idFromNanBits(int32_t bits) { return isNanBits(bits) ? (bits & PAYLOAD_MASK) : -1; }" + "inline int32_t idFromNanBits(int32_t bits) { return isNanBits(bits) ? (bits & PAYLOAD_MASK) : NO_ID; }" ) line( "inline int32_t asNanBits(int32_t id) { return (id & PAYLOAD_MASK) | NAN_PREFIX; }" @@ -590,7 +592,9 @@ schema.idEncoding?.let { enc -> w.block("pub mod id_encoding") { line("pub const NAN_PREFIX: i32 = ${enc.nanPrefix};") + line("pub const NAN_EXPONENT: i32 = ${enc.nanExponent};") line("pub const PAYLOAD_MASK: i32 = ${enc.payloadMask};") + line("pub const NO_ID: i32 = ${enc.noId};") line("pub const START_ID: i32 = ${enc.startId};") line("pub const REGION_MASK: i32 = ${enc.regionMask};") line("pub const REGION_SUB_ID_MASK: i32 = ${enc.regionSubIdMask};") @@ -605,10 +609,10 @@ line("pub const MACRO_LOCAL_START_ID: i32 = ${enc.macroLocalStartId};") line("pub const MACRO_LOCAL_END_ID: i32 = ${enc.macroLocalEndId};") line( - "pub fn is_nan_bits(bits: i32) -> bool { (bits & NAN_PREFIX) == NAN_PREFIX && (bits & PAYLOAD_MASK) != 0 }" + "pub fn is_nan_bits(bits: i32) -> bool { (bits & NAN_EXPONENT) == NAN_EXPONENT && (bits & PAYLOAD_MASK) != 0 }" ) line( - "pub fn id_from_nan_bits(bits: i32) -> i32 { if is_nan_bits(bits) { bits & PAYLOAD_MASK } else { -1 } }" + "pub fn id_from_nan_bits(bits: i32) -> i32 { if is_nan_bits(bits) { bits & PAYLOAD_MASK } else { NO_ID } }" ) line("pub fn as_nan_bits(id: i32) -> i32 { (id & PAYLOAD_MASK) | NAN_PREFIX }") line("pub fn is_dereferenced(raw: i32) -> bool { (raw & PTR_DEREFERENCE) != 0 }") @@ -972,7 +976,9 @@ w.line("class IdEncoding:") w.indent { w.line("NAN_PREFIX = ${enc.nanPrefix}") + w.line("NAN_EXPONENT = ${enc.nanExponent}") w.line("PAYLOAD_MASK = ${enc.payloadMask}") + w.line("NO_ID = ${enc.noId}") w.line("START_ID = ${enc.startId}") w.line("REGION_MASK = ${enc.regionMask}") w.line("REGION_SUB_ID_MASK = ${enc.regionSubIdMask}") @@ -990,14 +996,14 @@ w.line("def is_nan_bits(bits: int) -> bool:") w.indent { w.line( - "return ((bits & 0xFFFFFFFF) & (IdEncoding.NAN_PREFIX & 0xFFFFFFFF)) == (IdEncoding.NAN_PREFIX & 0xFFFFFFFF) and (bits & IdEncoding.PAYLOAD_MASK) != 0" + "return ((bits & 0xFFFFFFFF) & IdEncoding.NAN_EXPONENT) == IdEncoding.NAN_EXPONENT and (bits & IdEncoding.PAYLOAD_MASK) != 0" ) } w.line("@staticmethod") w.line("def id_from_nan_bits(bits: int) -> int:") w.indent { w.line( - "return (bits & IdEncoding.PAYLOAD_MASK) if IdEncoding.is_nan_bits(bits) else -1" + "return (bits & IdEncoding.PAYLOAD_MASK) if IdEncoding.is_nan_bits(bits) else IdEncoding.NO_ID" ) } w.line("@staticmethod") @@ -1482,49 +1488,70 @@ // Swift // ========================================================================================= + private fun toSwiftLowerCamel(name: String): String { + val raw = + if ('_' in name || name.all { !it.isLowerCase() }) { + val parts = name.split('_').filter { it.isNotEmpty() } + if (parts.isEmpty()) { + name.lowercase() + } else { + parts[0].lowercase() + + parts.drop(1).joinToString("") { p -> + p[0].uppercaseChar() + p.substring(1).lowercase() + } + } + } else { + name.replaceFirstChar { it.lowercaseChar() } + } + val safe = if (raw.isNotEmpty() && raw[0].isDigit()) "_$raw" else raw + return if (safe in SWIFT_KEYWORDS) "`$safe`" else safe + } + fun emitSwiftOpEnumConstants(w: CodeWriter, fields: List<SchemaField>) { val consts = collectEnumConstants(fields) if (consts.isEmpty()) return for ((k, v) in consts) { - w.line("public static let $k: Int32 = $v") + w.line("public static let ${toSwiftLowerCamel(k)}: Int32 = $v") } } fun emitSwiftProtocol(w: CodeWriter) { schema.idEncoding?.let { enc -> w.block("public enum IdEncoding") { - line("public static let NAN_PREFIX: Int32 = ${enc.nanPrefix}") - line("public static let PAYLOAD_MASK: Int32 = ${enc.payloadMask}") - line("public static let START_ID: Int32 = ${enc.startId}") - line("public static let REGION_MASK: Int32 = ${enc.regionMask}") - line("public static let REGION_SUB_ID_MASK: Int32 = ${enc.regionSubIdMask}") - line("public static let REGION_SYSTEM: Int32 = ${enc.regionSystem}") - line("public static let REGION_VARIABLE: Int32 = ${enc.regionVariable}") - line("public static let REGION_ARRAY: Int32 = ${enc.regionArray}") - line("public static let REGION_OPERATION: Int32 = ${enc.regionOperation}") - line("public static let START_ARRAY_ID: Int32 = ${enc.regionArray + enc.startId}") - line("public static let LONG_ID_OFFSET: Int64 = ${enc.longIdOffset}") - line("public static let PTR_DEREFERENCE: Int32 = ${enc.ptrDereference}") - line("public static let VALUE_MASK: Int32 = ${enc.valueMask}") - line("public static let MACRO_LOCAL_START_ID: Int32 = ${enc.macroLocalStartId}") - line("public static let MACRO_LOCAL_END_ID: Int32 = ${enc.macroLocalEndId}") + line("public static let nanPrefix: Int32 = ${enc.nanPrefix}") + line("public static let nanExponent: Int32 = ${enc.nanExponent}") + line("public static let payloadMask: Int32 = ${enc.payloadMask}") + line("public static let noId: Int32 = ${enc.noId}") + line("public static let startId: Int32 = ${enc.startId}") + line("public static let regionMask: Int32 = ${enc.regionMask}") + line("public static let regionSubIdMask: Int32 = ${enc.regionSubIdMask}") + line("public static let regionSystem: Int32 = ${enc.regionSystem}") + line("public static let regionVariable: Int32 = ${enc.regionVariable}") + line("public static let regionArray: Int32 = ${enc.regionArray}") + line("public static let regionOperation: Int32 = ${enc.regionOperation}") + line("public static let startArrayId: Int32 = ${enc.regionArray + enc.startId}") + line("public static let longIdOffset: Int64 = ${enc.longIdOffset}") + line("public static let ptrDereference: Int32 = ${enc.ptrDereference}") + line("public static let valueMask: Int32 = ${enc.valueMask}") + line("public static let macroLocalStartId: Int32 = ${enc.macroLocalStartId}") + line("public static let macroLocalEndId: Int32 = ${enc.macroLocalEndId}") line( - "public static func isNanBits(_ bits: Int32) -> Bool { (bits & NAN_PREFIX) == NAN_PREFIX && (bits & PAYLOAD_MASK) != 0 }" + "public static func isNanBits(_ bits: Int32) -> Bool { (bits & nanExponent) == nanExponent && (bits & payloadMask) != 0 }" ) line( - "public static func idFromNanBits(_ bits: Int32) -> Int32 { isNanBits(bits) ? (bits & PAYLOAD_MASK) : -1 }" + "public static func idFromNanBits(_ bits: Int32) -> Int32 { isNanBits(bits) ? (bits & payloadMask) : noId }" ) line( - "public static func asNanBits(_ id: Int32) -> Int32 { (id & PAYLOAD_MASK) | NAN_PREFIX }" + "public static func asNanBits(_ id: Int32) -> Int32 { (id & payloadMask) | nanPrefix }" ) line( - "public static func isDereferenced(_ raw: Int32) -> Bool { (raw & PTR_DEREFERENCE) != 0 }" + "public static func isDereferenced(_ raw: Int32) -> Bool { (raw & ptrDereference) != 0 }" ) line( - "public static func directId(_ raw: Int32) -> Int32? { isDereferenced(raw) ? nil : (raw & VALUE_MASK) }" + "public static func directId(_ raw: Int32) -> Int32? { isDereferenced(raw) ? nil : (raw & valueMask) }" ) line( - "public static func pointerId(_ raw: Int32) -> Int32? { isDereferenced(raw) ? (raw & VALUE_MASK) : nil }" + "public static func pointerId(_ raw: Int32) -> Int32? { isDereferenced(raw) ? (raw & valueMask) : nil }" ) } w.line() @@ -1534,25 +1561,122 @@ w.block("public enum HeaderConstants") { for ((_, group) in schema.headerConstants) { for ((k, v) in group.entries.sortedBy { it.value }) { - line("public static let $k: Int32 = $v") + line("public static let ${toSwiftLowerCamel(k)}: Int32 = $v") } } } w.line() } + if (schema.visibilityConstants.isNotEmpty()) { + w.block("public enum ComponentVisibility") { + for ((k, v) in schema.visibilityConstants.entries.sortedBy { it.value }) { + line("public static let ${toSwiftLowerCamel(k)}: Int32 = $v") + } + } + w.line() + } + if (schema.paintCommands.isNotEmpty()) { w.block("public enum PaintCommandTags") { + line("public static let tagMask: Int32 = 0xFFFF") + line("public static let inlineValueShift: Int32 = 16") for ((id, cmd) in schema.paintCommands.entries.sortedBy { it.key }) { line( - "public static let ${SchemaOperation.toScreamingSnakeCase(cmd.name)}: Int32 = $id" + "public static let ${toSwiftLowerCamel(SchemaOperation.toScreamingSnakeCase(cmd.name))}: Int32 = $id" ) } + line( + "public static func packInline(tag: Int32, value: Int32) -> Int32 { (tag & tagMask) | (value << inlineValueShift) }" + ) } w.line() w.block("public enum PaintConstants") { for ((k, v) in collectPaintConstants()) { - line("public static let $k: Int32 = $v") + line("public static let ${toSwiftLowerCamel(k)}: Int32 = $v") + } + } + w.line() + } + + if (schema.rpnOperators != null && schema.idEncoding != null) { + val rpn = schema.rpnOperators + val maxV6 = rpn.operators.filter { it.addedVersion <= 6 }.maxOfOrNull { it.id } ?: 38 + val maxId = rpn.operators.maxOfOrNull { it.id } ?: 79 + val validIds = rpn.operators.map { it.id }.toSet() + val gapChecks = + (1..maxId).filter { it !in validIds }.joinToString("") { " && id != $it" } + val rpnOffsetLiteral = + if (rpn.offset >= 0) "0x${rpn.offset.toString(16).uppercase()}" else "${rpn.offset}" + w.block("public enum FloatExpressionOperator") { + line("public static let offset: Int32 = $rpnOffsetLiteral") + line("public static let apiLevel6MaxId: Int32 = $maxV6") + line("public static let maxId: Int32 = $maxId") + for (op in rpn.operators) { + line( + "public static let ${toSwiftLowerCamel("ID_${op.name}")}: Int32 = ${op.id}" + ) + } + if ("DEG_TO_RAD" in rpn.operatorsByName && "DEG" !in rpn.operatorsByName) { + line("public static let idDeg: Int32 = idDegToRad") + } + if ("RAD_TO_DEG" in rpn.operatorsByName && "RAD" !in rpn.operatorsByName) { + line("public static let idRad: Int32 = idRadToDeg") + } + for (op in rpn.operators) { + line( + "public static let ${toSwiftLowerCamel(op.name)}: Float = Float(bitPattern: UInt32(bitPattern: IdEncoding.asNanBits(offset + ${op.id})))" + ) + } + if ("DEG_TO_RAD" in rpn.operatorsByName && "DEG" !in rpn.operatorsByName) { + line("public static let deg: Float = degToRad") + } + if ("RAD_TO_DEG" in rpn.operatorsByName && "RAD" !in rpn.operatorsByName) { + line("public static let rad: Float = radToDeg") + } + block("public static func token(fromId id: Int32) -> Float?") { + line("guard id >= 1 && id <= maxId$gapChecks else { return nil }") + line( + "return Float(bitPattern: UInt32(bitPattern: IdEncoding.asNanBits(offset + id)))" + ) + } + block("public static func isOperator(_ token: Float) -> Bool") { + line("let bits = Int32(bitPattern: token.bitPattern)") + line("guard IdEncoding.isNanBits(bits) else { return false }") + line("let id = (bits & IdEncoding.payloadMask) - offset") + line("return id >= 1 && id <= maxId$gapChecks") + } + block("public static func operatorId(_ token: Float) -> Int32") { + line("guard isOperator(token) else { return IdEncoding.noId }") + line( + "return (Int32(bitPattern: token.bitPattern) & IdEncoding.payloadMask) - offset" + ) + } + } + w.line() + } + + schema.intRpnOperators?.let { intRpn -> + val maxId = intRpn.operators.maxOfOrNull { it.id } ?: 25 + val validIds = intRpn.operators.map { it.id }.toSet() + val gapChecks = + (1..maxId).filter { it !in validIds }.joinToString("") { " && id != $it" } + val offsetLiteral = + if (intRpn.offset >= 0) "0x${intRpn.offset.toString(16).uppercase()}" + else "${intRpn.offset}" + w.block("public enum IntegerExpressionOperator") { + line("public static let offset: Int32 = $offsetLiteral") + line("public static let maxId: Int32 = $maxId") + line("public static let maxTokens: Int = 32") + for (op in intRpn.operators) { + line( + "public static let ${toSwiftLowerCamel(op.name)}: Int32 = offset + ${op.id}" + ) + } + block("public static func isOperatorCode(_ value: Int32) -> Bool") { + line("let (id, overflow) = value.subtractingReportingOverflow(offset)") + line("guard !overflow else { return false }") + line("return id >= 1 && id <= maxId$gapChecks") } } w.line() @@ -1562,7 +1686,7 @@ w.block("public enum PathCommandTags") { for ((id, cmd) in schema.pathCommands.entries.sortedBy { it.key }) { line( - "public static let ${SchemaOperation.toScreamingSnakeCase(cmd.name)}: Int32 = $id" + "public static let ${toSwiftLowerCamel(SchemaOperation.toScreamingSnakeCase(cmd.name))}: Int32 = $id" ) } } @@ -1573,7 +1697,9 @@ val timeIds = schema.systemVariables.filter { it.isTime }.map { it.id }.sorted() w.block("public enum RemoteContextIds") { for (sv in schema.systemVariables) { - line("public static let ID_${sv.name}: Int32 = ${sv.id}") + line( + "public static let ${toSwiftLowerCamel("ID_${sv.name}")}: Int32 = ${sv.id}" + ) } val expr = if (timeIds.isEmpty()) "false" @@ -1588,9 +1714,9 @@ schema.animationSpec?.let { anim -> w.block("public enum AnimationEasing") { for (e in anim.easings.sortedBy { it.id }) { - line("public static let ${e.name}: Int32 = ${e.id}") + line("public static let ${toSwiftLowerCamel(e.name)}: Int32 = ${e.id}") for (a in e.aliases) { - line("public static let $a: Int32 = ${e.id}") + line("public static let ${toSwiftLowerCamel(a)}: Int32 = ${e.id}") } } block("public static func cubicControlPoints(_ type: Int32) -> [Float]?") { @@ -1598,7 +1724,7 @@ for (e in anim.easings.sortedBy { it.id }) { val pts = e.cubicControlPoints ?: continue line( - "case ${e.name}: return [${pts[0]}, ${pts[1]}, ${pts[2]}, ${pts[3]}]" + "case ${toSwiftLowerCamel(e.name)}: return [${pts[0]}, ${pts[1]}, ${pts[2]}, ${pts[3]}]" ) } line("default: return nil") @@ -1606,7 +1732,7 @@ } } w.line() - w.block("public struct FloatAnimationSpec: Equatable") { + w.block("public struct FloatAnimationSpec: Equatable, Hashable, Sendable") { line("public var duration: Float") line("public var type: Int32") line("public var params: [Float]") @@ -1615,7 +1741,7 @@ line("public var directionalSnap: Int32") line("public var isPropagate: Bool") block( - "public init(duration: Float = 1.0, type: Int32 = AnimationEasing.CUBIC_STANDARD, params: [Float] = [], initialValue: Float = .nan, wrap: Float = .nan, directionalSnap: Int32 = 0, isPropagate: Bool = false)" + "public init(duration: Float = 1.0, type: Int32 = AnimationEasing.cubicStandard, params: [Float] = [], initialValue: Float = .nan, wrap: Float = .nan, directionalSnap: Int32 = 0, isPropagate: Bool = false)" ) { line("self.duration = duration") line("self.type = type") @@ -1640,12 +1766,27 @@ line(" && lhs.directionalSnap == rhs.directionalSnap") line(" && lhs.isPropagate == rhs.isPropagate") } + block("public func hash(into hasher: inout Hasher)") { + line( + "let norm: (Float) -> UInt32 = { \$0.isNaN ? 0x7FC0_0000 : (\$0 == 0 ? 0 : \$0.bitPattern) }" + ) + line("hasher.combine(norm(duration))") + line("hasher.combine(type)") + line("hasher.combine(params.count)") + line("for p in params { hasher.combine(norm(p)) }") + line("hasher.combine(norm(initialValue))") + line("hasher.combine(norm(wrap))") + line("hasher.combine(directionalSnap)") + line("hasher.combine(isPropagate)") + } line( "public static func isSpring(_ data: [Float]) -> Bool { data.count > 4 && data[0] == 0.0 }" ) - block("public static func unpack(_ data: [Float]) throws -> FloatAnimationSpec") { + block( + "public static func unpack(_ data: [Float]) throws(WireError) -> FloatAnimationSpec" + ) { line( - "if isSpring(data) { throw NSError(domain: \"FloatAnimationSpec\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Spring animation specs cannot be unpacked with unpackAnimationSpec\"]) }" + "if isSpring(data) { throw WireError.invalidAnimationSpec(\"Spring animation specs cannot be unpacked with unpackAnimationSpec\") }" ) line("var out = FloatAnimationSpec()") line("if data.isEmpty { return out }") @@ -1659,20 +1800,20 @@ line("out.isPropagate = ((bits >> 12) & 1) != 0") line("let paramLen = Int((bits >> 16) & 0xFFFF)") line( - "if 2 + paramLen > data.count { throw NSError(domain: \"FloatAnimationSpec\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Truncated animation spec params\"]) }" + "if 2 + paramLen > data.count { throw WireError.invalidAnimationSpec(\"Truncated animation spec params\") }" ) line("out.params = Array(data[2..<(2 + paramLen)])") line("var off = 2 + paramLen") line( - "if hasInit { if off >= data.count { throw NSError(domain: \"FloatAnimationSpec\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Truncated animation spec initialValue\"]) }; out.initialValue = data[off]; off += 1 }" + "if hasInit { if off >= data.count { throw WireError.invalidAnimationSpec(\"Truncated animation spec initialValue\") }; out.initialValue = data[off]; off += 1 }" ) line( - "if hasWrap { if off >= data.count { throw NSError(domain: \"FloatAnimationSpec\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Truncated animation spec wrap\"]) }; out.wrap = data[off] }" + "if hasWrap { if off >= data.count { throw WireError.invalidAnimationSpec(\"Truncated animation spec wrap\") }; out.wrap = data[off] }" ) line("return out") } block( - "public static func pack(duration: Float = 1.0, type: Int32 = AnimationEasing.CUBIC_STANDARD, spec: [Float]? = nil, initialValue: Float = .nan, wrap: Float = .nan) -> [Float]" + "public static func pack(duration: Float = 1.0, type: Int32 = AnimationEasing.cubicStandard, spec: [Float]? = nil, initialValue: Float = .nan, wrap: Float = .nan) -> [Float]" ) { line("var count = 0") line("let hasInit = !initialValue.isNaN") @@ -1680,7 +1821,7 @@ line("if hasInit { count += 1 }") line("if spec != nil { count += 1 }") line( - "if spec != nil || type != AnimationEasing.CUBIC_STANDARD { count += 1 + (spec?.count ?? 0) }" + "if spec != nil || type != AnimationEasing.cubicStandard { count += 1 + (spec?.count ?? 0) }" ) line("if hasInit { count += 1 }") line("if hasWrap { count += 1 }") @@ -1711,42 +1852,42 @@ "public func isSpringAnimationSpec(_ data: [Float]) -> Bool { FloatAnimationSpec.isSpring(data) }" ) w.line( - "public func unpackAnimationSpec(_ data: [Float]) throws -> FloatAnimationSpec { try FloatAnimationSpec.unpack(data) }" + "public func unpackAnimationSpec(_ data: [Float]) throws(WireError) -> FloatAnimationSpec { try FloatAnimationSpec.unpack(data) }" ) w.line( - "public func packAnimationSpec(duration: Float = 1.0, type: Int32 = AnimationEasing.CUBIC_STANDARD, spec: [Float]? = nil, initialValue: Float = .nan, wrap: Float = .nan) -> [Float] { FloatAnimationSpec.pack(duration: duration, type: type, spec: spec, initialValue: initialValue, wrap: wrap) }" + "public func packAnimationSpec(duration: Float = 1.0, type: Int32 = AnimationEasing.cubicStandard, spec: [Float]? = nil, initialValue: Float = .nan, wrap: Float = .nan) -> [Float] { FloatAnimationSpec.pack(duration: duration, type: type, spec: spec, initialValue: initialValue, wrap: wrap) }" ) w.line() } schema.pathEffects?.let { pe -> - w.block("public indirect enum PathEffect: Equatable") { + w.block("public indirect enum PathEffect: Equatable, Hashable, Sendable") { line("case dash(phase: Float, intervals: [Float])") line("case discrete(segmentLength: Float, deviation: Float)") line("case pathDash(shapeId: Int32, advance: Float, phase: Float, style: Int32)") line("case sum(PathEffect, PathEffect)") line("case compose(PathEffect, PathEffect)") for (t in pe.types.sortedBy { it.id }) { - line("public static let ${t.constName}: Int32 = ${t.id}") + line("public static let ${toSwiftLowerCamel(t.constName)}: Int32 = ${t.id}") } - line("public static let MAX_DASH_INTERVALS: Int = ${pe.maxDashIntervals}") - line("public static let MAX_NESTING_DEPTH: Int = ${pe.maxNestingDepth}") - block("public func encode() throws -> [Float]") { + line("public static let maxDashIntervals: Int = ${pe.maxDashIntervals}") + line("public static let maxNestingDepth: Int = ${pe.maxNestingDepth}") + block("public func encode() throws(WireError) -> [Float]") { block("switch self") { line( - "case let .dash(phase, intervals): if intervals.count > Self.MAX_DASH_INTERVALS { throw NSError(domain: \"PathEffect\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Dash interval count (\\(intervals.count)) exceeds MAX_DASH_INTERVALS (\\(Self.MAX_DASH_INTERVALS))\"]) }; return [Float(bitPattern: UInt32(bitPattern: Self.TYPE_DASH)), phase, Float(bitPattern: UInt32(intervals.count))] + intervals" + "case let .dash(phase, intervals): if intervals.count > Self.maxDashIntervals { throw WireError.invalidPathEffect(\"Dash interval count (\\(intervals.count)) exceeds maxDashIntervals (\\(Self.maxDashIntervals))\") }; return [Float(bitPattern: UInt32(bitPattern: Self.typeDash)), phase, Float(bitPattern: UInt32(intervals.count))] + intervals" ) line( - "case let .discrete(segmentLength, deviation): return [Float(bitPattern: UInt32(bitPattern: Self.TYPE_DISCRETE)), segmentLength, deviation]" + "case let .discrete(segmentLength, deviation): return [Float(bitPattern: UInt32(bitPattern: Self.typeDiscrete)), segmentLength, deviation]" ) line( - "case let .pathDash(shapeId, advance, phase, style): return [Float(bitPattern: UInt32(bitPattern: Self.TYPE_PATH_DASH)), Float(bitPattern: UInt32(bitPattern: shapeId)), advance, phase, Float(bitPattern: UInt32(bitPattern: style))]" + "case let .pathDash(shapeId, advance, phase, style): return [Float(bitPattern: UInt32(bitPattern: Self.typePathDash)), Float(bitPattern: UInt32(bitPattern: shapeId)), advance, phase, Float(bitPattern: UInt32(bitPattern: style))]" ) line( - "case let .sum(a, b): return [Float(bitPattern: UInt32(bitPattern: Self.TYPE_SUM))] + (try a.encode()) + (try b.encode())" + "case let .sum(a, b): return [Float(bitPattern: UInt32(bitPattern: Self.typeSum))] + (try a.encode()) + (try b.encode())" ) line( - "case let .compose(a, b): return [Float(bitPattern: UInt32(bitPattern: Self.TYPE_COMPOSE))] + (try a.encode()) + (try b.encode())" + "case let .compose(a, b): return [Float(bitPattern: UInt32(bitPattern: Self.typeCompose))] + (try a.encode()) + (try b.encode())" ) } } @@ -1761,35 +1902,92 @@ block( "private static func parseOne(_ data: [Float], _ cursor: inout Int, _ depth: Int) -> PathEffect?" ) { - line("if depth > MAX_NESTING_DEPTH || cursor >= data.count { return nil }") + line("if depth > maxNestingDepth || cursor >= data.count { return nil }") line("let idx = cursor") line("let tag = Int32(bitPattern: data[idx].bitPattern)") block("switch tag") { line( - "case TYPE_DASH: if idx + 3 > data.count { return nil }; let count = Int(Int32(bitPattern: data[idx + 2].bitPattern)); if count < 0 || count > MAX_DASH_INTERVALS || count > data.count - (idx + 3) { return nil }; cursor = idx + 3 + count; return .dash(phase: data[idx + 1], intervals: Array(data[(idx + 3)..<(idx + 3 + count)]))" + "case typeDash: if idx + 3 > data.count { return nil }; let count = Int(Int32(bitPattern: data[idx + 2].bitPattern)); if count < 0 || count > maxDashIntervals || count > data.count - (idx + 3) { return nil }; cursor = idx + 3 + count; return .dash(phase: data[idx + 1], intervals: Array(data[(idx + 3)..<(idx + 3 + count)]))" ) line( - "case TYPE_DISCRETE: if idx + 3 > data.count { return nil }; cursor = idx + 3; return .discrete(segmentLength: data[idx + 1], deviation: data[idx + 2])" + "case typeDiscrete: if idx + 3 > data.count { return nil }; cursor = idx + 3; return .discrete(segmentLength: data[idx + 1], deviation: data[idx + 2])" ) line( - "case TYPE_PATH_DASH: if idx + 5 > data.count { return nil }; cursor = idx + 5; return .pathDash(shapeId: Int32(bitPattern: data[idx + 1].bitPattern), advance: data[idx + 2], phase: data[idx + 3], style: Int32(bitPattern: data[idx + 4].bitPattern))" + "case typePathDash: if idx + 5 > data.count { return nil }; cursor = idx + 5; return .pathDash(shapeId: Int32(bitPattern: data[idx + 1].bitPattern), advance: data[idx + 2], phase: data[idx + 3], style: Int32(bitPattern: data[idx + 4].bitPattern))" ) line( - "case TYPE_SUM: cursor = idx + 1; guard let a = parseOne(data, &cursor, depth + 1), let b = parseOne(data, &cursor, depth + 1) else { return nil }; return .sum(a, b)" + "case typeSum: cursor = idx + 1; guard let a = parseOne(data, &cursor, depth + 1), let b = parseOne(data, &cursor, depth + 1) else { return nil }; return .sum(a, b)" ) line( - "case TYPE_COMPOSE: cursor = idx + 1; guard let a = parseOne(data, &cursor, depth + 1), let b = parseOne(data, &cursor, depth + 1) else { return nil }; return .compose(a, b)" + "case typeCompose: cursor = idx + 1; guard let a = parseOne(data, &cursor, depth + 1), let b = parseOne(data, &cursor, depth + 1) else { return nil }; return .compose(a, b)" ) line("default: return nil") } } + block("public static func == (lhs: PathEffect, rhs: PathEffect) -> Bool") { + block("switch (lhs, rhs)") { + line( + "case (.dash(let lp, let li), .dash(let rp, let ri)): return wireFloatEquals(lp, rp) && wireFloatEquals(li, ri)" + ) + line( + "case (.discrete(let ls, let ld), .discrete(let rs, let rd)): return wireFloatEquals(ls, rs) && wireFloatEquals(ld, rd)" + ) + line( + "case (.pathDash(let lShape, let lAdv, let lPhase, let lStyle), .pathDash(let rShape, let rAdv, let rPhase, let rStyle)): return lShape == rShape && wireFloatEquals(lAdv, rAdv) && wireFloatEquals(lPhase, rPhase) && lStyle == rStyle" + ) + line( + "case (.sum(let la, let lb), .sum(let ra, let rb)): return la == ra && lb == rb" + ) + line( + "case (.compose(let la, let lb), .compose(let ra, let rb)): return la == ra && lb == rb" + ) + line("default: return false") + } + } + block("public func hash(into hasher: inout Hasher)") { + block("switch self") { + line("case .dash(let phase, let intervals):") + indent { + line("hasher.combine(0)") + line("wireFloatHash(phase, into: &hasher)") + line("wireFloatHash(intervals, into: &hasher)") + } + line("case .discrete(let segmentLength, let deviation):") + indent { + line("hasher.combine(1)") + line("wireFloatHash(segmentLength, into: &hasher)") + line("wireFloatHash(deviation, into: &hasher)") + } + line("case .pathDash(let shapeId, let advance, let phase, let style):") + indent { + line("hasher.combine(2)") + line("hasher.combine(shapeId)") + line("wireFloatHash(advance, into: &hasher)") + line("wireFloatHash(phase, into: &hasher)") + line("hasher.combine(style)") + } + line("case .sum(let a, let b):") + indent { + line("hasher.combine(3)") + line("hasher.combine(a)") + line("hasher.combine(b)") + } + line("case .compose(let a, let b):") + indent { + line("hasher.combine(4)") + line("hasher.combine(a)") + line("hasher.combine(b)") + } + } + } } w.line() } if (schema.pathCommands.isNotEmpty() && schema.idEncoding != null) { - w.block("public enum PathCommand: Equatable") { - for ((_, cmd) in schema.pathCommands.entries.sortedBy { it.key }) { + val sortedPathCommands = schema.pathCommands.entries.sortedBy { it.key } + w.block("public enum PathCommand: Equatable, Hashable, Sendable") { + for ((_, cmd) in sortedPathCommands) { val vName = pathCmdVariantName(cmd).replaceFirstChar { it.lowercaseChar() } if (cmd.fields.isEmpty()) { line("case $vName") @@ -1799,6 +1997,55 @@ } } line("case unknown(verb: Int32)") + block("public static func == (lhs: PathCommand, rhs: PathCommand) -> Bool") { + block("switch (lhs, rhs)") { + for ((_, cmd) in sortedPathCommands) { + val vName = + pathCmdVariantName(cmd).replaceFirstChar { it.lowercaseChar() } + if (cmd.fields.isEmpty()) { + line("case (.$vName, .$vName): return true") + } else { + val lhsBinds = cmd.fields.indices.joinToString(", ") { "let l$it" } + val rhsBinds = cmd.fields.indices.joinToString(", ") { "let r$it" } + val checks = + cmd.fields.indices.joinToString(" && ") { + "wireFloatEquals(l$it, r$it)" + } + line( + "case (.$vName($lhsBinds), .$vName($rhsBinds)): return $checks" + ) + } + } + line("case (.unknown(let l), .unknown(let r)): return l == r") + line("default: return false") + } + } + block("public func hash(into hasher: inout Hasher)") { + block("switch self") { + for ((idx, entry) in sortedPathCommands.withIndex()) { + val cmd = entry.value + val vName = + pathCmdVariantName(cmd).replaceFirstChar { it.lowercaseChar() } + if (cmd.fields.isEmpty()) { + line("case .$vName: hasher.combine($idx)") + } else { + val binds = cmd.fields.indices.joinToString(", ") { "let v$it" } + line("case .$vName($binds):") + indent { + line("hasher.combine($idx)") + for (fIdx in cmd.fields.indices) { + line("wireFloatHash(v$fIdx, into: &hasher)") + } + } + } + } + line("case .unknown(let verb):") + indent { + line("hasher.combine(${sortedPathCommands.size})") + line("hasher.combine(verb)") + } + } + } block("public static func decode(_ pathData: [Float]) -> [PathCommand]") { line("var result: [PathCommand] = []") line("var i = 0") @@ -1808,8 +2055,11 @@ "let tag = IdEncoding.idFromNanBits(Int32(bitPattern: pathData[i].bitPattern))" ) block("switch tag") { - for ((_, cmd) in schema.pathCommands.entries.sortedBy { it.key }) { - val tagConst = SchemaOperation.toScreamingSnakeCase(cmd.name) + for ((_, cmd) in sortedPathCommands) { + val tagConst = + toSwiftLowerCamel( + SchemaOperation.toScreamingSnakeCase(cmd.name) + ) val vName = pathCmdVariantName(cmd).replaceFirstChar { it.lowercaseChar() } val total = 1 + cmd.leadingPaddingFloats + cmd.fields.size @@ -1848,12 +2098,12 @@ "public var isSpringAnimation: Bool { FloatAnimationSpec.isSpring(animationSpec) }" ) w.line( - "public func unpackAnimationSpec() throws -> FloatAnimationSpec { try FloatAnimationSpec.unpack(animationSpec) }" + "public func unpackAnimationSpec() throws(WireError) -> FloatAnimationSpec { try FloatAnimationSpec.unpack(animationSpec) }" ) } if (isBitmapDataReady(op)) { w.line( - "public var uncompressedByteSize: Int64 { let w = Int64(width); let h = Int64(height); if w <= 0 || h <= 0 { return 0 }; let bpp: Int64 = imageType == BitmapData.TYPE_PNG_ALPHA_8 ? 1 : 4; let (wh, o1) = w.multipliedReportingOverflow(by: h); if o1 { return Int64.max }; let (total, o2) = wh.multipliedReportingOverflow(by: bpp); return o2 ? Int64.max : total }" + "public var uncompressedByteSize: Int64 { let w = Int64(width); let h = Int64(height); if w <= 0 || h <= 0 { return 0 }; let bpp: Int64 = imageType == BitmapData.typePngAlpha8 ? 1 : 4; let (wh, o1) = w.multipliedReportingOverflow(by: h); if o1 { return Int64.max }; let (total, o2) = wh.multipliedReportingOverflow(by: bpp); return o2 ? Int64.max : total }" ) } if ( @@ -1907,7 +2157,9 @@ schema.idEncoding?.let { enc -> w.block("export const IdEncoding =", close = "} as const;") { line("NAN_PREFIX: ${enc.nanPrefix},") + line("NAN_EXPONENT: ${enc.nanExponent},") line("PAYLOAD_MASK: ${enc.payloadMask},") + line("NO_ID: ${enc.noId},") line("START_ID: ${enc.startId},") line("REGION_MASK: ${enc.regionMask},") line("REGION_SUB_ID_MASK: ${enc.regionSubIdMask},") @@ -1922,10 +2174,10 @@ line("MACRO_LOCAL_START_ID: ${enc.macroLocalStartId},") line("MACRO_LOCAL_END_ID: ${enc.macroLocalEndId},") line( - "isNanBits(bits: number): boolean { return ((bits & ${enc.nanPrefix}) | 0) === ${enc.nanPrefix} && (bits & ${enc.payloadMask}) !== 0; }," + "isNanBits(bits: number): boolean { return ((bits & ${enc.nanExponent}) | 0) === ${enc.nanExponent} && (bits & ${enc.payloadMask}) !== 0; }," ) line( - "idFromNanBits(bits: number): number { return IdEncoding.isNanBits(bits) ? (bits & ${enc.payloadMask}) : -1; }," + "idFromNanBits(bits: number): number { return IdEncoding.isNanBits(bits) ? (bits & ${enc.payloadMask}) : ${enc.noId}; }," ) line( "asNanBits(id: number): number { return ((id & ${enc.payloadMask}) | ${enc.nanPrefix}) | 0; }," @@ -2263,4 +2515,65 @@ w.line("getAlphaPayload(): number { return (this.flagsAndMode >>> 16) & 0xFF; }") } } + + private companion object { + val SWIFT_KEYWORDS = + setOf( + "associatedtype", + "class", + "deinit", + "enum", + "extension", + "fileprivate", + "func", + "import", + "init", + "inout", + "internal", + "let", + "open", + "operator", + "private", + "precedencegroup", + "protocol", + "public", + "rethrows", + "static", + "struct", + "subscript", + "typealias", + "var", + "break", + "case", + "catch", + "continue", + "default", + "defer", + "do", + "else", + "fallthrough", + "for", + "guard", + "if", + "in", + "repeat", + "return", + "throw", + "switch", + "where", + "while", + "as", + "false", + "is", + "nil", + "self", + "Self", + "super", + "throws", + "true", + "try", + "Any", + "Type", + ) + } }
diff --git a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/SwiftGenerator.kt b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/SwiftGenerator.kt index eb3203c..a52d007 100644 --- a/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/SwiftGenerator.kt +++ b/compose/remote/remote-generator/src/main/java/androidx/compose/remote/generator/codegen/SwiftGenerator.kt
@@ -27,11 +27,13 @@ import androidx.compose.remote.generator.SchemaStruct /** - * Generator that transforms an [OperationSchema] into idiomatic Swift bindings: - * - OpCode enum with UInt8 raw values - * - RemoteOperation protocol - * - Auxiliary structs and typed structs for each operation with WireBuffer read/write methods - * - RemoteDocument container and WireBuffer implementation + * Generator that transforms an [OperationSchema] into zero-Foundation, Swift 6-ready wire bindings: + * - `OpCode` enum with `UInt8` raw values (`Equatable, Hashable, Sendable`) + * - Typed `WireError` enum (`Error, Equatable, Hashable, Sendable`) + * - Pure-Swift `[UInt8]`-backed `WireBuffer` with typed `throws(WireError)` + * - Auxiliary structs and operation structs (`Equatable, Hashable, Sendable`) + * - Closed `WireOperation` enum with one case per schema operation + * - `WireDocument` container with lossless legacy and modern v1.1+ header round-tripping */ internal class SwiftGenerator(private val schema: OperationSchema) { @@ -39,10 +41,9 @@ fun generate(): String = buildCode { line("// Generated by RemoteCompose Schema Codegen. DO NOT EDIT.") - line("import Foundation") line() line("/// Operation wire identifiers for RemoteCompose.") - block("public enum OpCode: UInt8, CaseIterable") { + block("public enum OpCode: UInt8, CaseIterable, Equatable, Hashable, Sendable") { for (op in schema.operations) { val swiftCase = toCamelCase(op.name) val desc = op.description.replace("\n", " ").trim() @@ -52,15 +53,29 @@ line("case $swiftCase = ${op.id}") } } - line() - line("/// Protocol adopted by all RemoteCompose operation types.") - block("public protocol RemoteOperation") { - line("var opCode: OpCode { get }") - line("func write(to buffer: inout WireBuffer) throws") + if (schema.reservedOpcodes.isNotEmpty()) { + line() + line("/// Reserved and experimental operation wire identifiers without wire codecs.") + block( + "public enum ReservedOpCode: UInt8, CaseIterable, Equatable, Hashable, Sendable" + ) { + for (rop in schema.reservedOpcodes) { + val swiftCase = toCamelCase(rop.name) + val desc = rop.description.replace("\n", " ").trim() + if (desc.isNotEmpty()) { + line("/// $desc") + } + line("case $swiftCase = ${rop.id}") + } + } } line() + emitWireError(this) + line() emitWireBuffer(this) line() + emitFloatBitEqualityHelpers(this) + line() multiLang.emitSwiftProtocol(this) for ((_, structDef) in schema.structs) { emitAuxStruct(this, structDef) @@ -70,53 +85,77 @@ emitStruct(this, op) line() } - emitRemoteDocument(this) + emitWireOperationEnum(this) + line() + emitWireDocument(this) + } + + private fun emitWireError(w: CodeWriter) { + w.line("/// Typed error thrown while decoding or encoding RemoteCompose wire streams.") + w.block("public enum WireError: Error, Equatable, Hashable, Sendable") { + line("case underflow(needed: Int, remaining: Int)") + line("case indexOutOfBounds(index: Int, count: Int)") + line("case invalidLength(field: String, length: Int)") + line("case lengthOutOfRange(field: String, length: Int, min: Int?, max: Int?)") + line("case invalidUTF8(field: String)") + line("case unknownOpCode(UInt8)") + line("case expectedHeaderOpCode(actual: UInt8)") + line("case unexpectedHeaderInBody") + line("case invalidHeaderMagic(Int32)") + line("case compressedDocumentUnsupported") + line("case operationCountExceeded(limit: Int)") + line("case invalidFieldValue(owner: String, field: String, detail: String)") + line("case missingRequiredField(owner: String, field: String)") + line("case unknownSparseParameter(owner: String, id: Int)") + line("case invalidAnimationSpec(String)") + line("case invalidPathEffect(String)") + } } private fun emitWireBuffer(w: CodeWriter) { - w.block("public struct WireBuffer") { - line("public private(set) var data: Data") + w.line("/// Big-endian binary reader and writer backed by a Swift byte array.") + w.block("public struct WireBuffer: Equatable, Hashable, Sendable") { + line("public private(set) var data: [UInt8]") line("public private(set) var index: Int = 0") line() - block("public init(data: Data = Data())") { - line("self.data = data.startIndex == 0 ? data : Data(data)") + block("public init(data: [UInt8] = [])") { + line("self.data = data") line("self.index = 0") } line() - block("public var remaining: Int") { line("return max(0, data.count - index)") } + block("public var remaining: Int") { line("return Swift.max(0, data.count - index)") } line() block("public var available: Bool") { line("return index < data.count") } line() - block("public mutating func setIndex(_ newIndex: Int) throws") { + block("public mutating func setIndex(_ newIndex: Int) throws(WireError)") { block("guard newIndex >= 0 && newIndex <= data.count else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Index out of bounds: \\(newIndex)\"])" - ) + line("throw WireError.indexOutOfBounds(index: newIndex, count: data.count)") } line("index = newIndex") } line() - block("public mutating func skipBytes(_ count: Int) throws") { + block("public mutating func skipBytes(_ count: Int) throws(WireError)") { block("guard count >= 0 else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative skip length\"])" - ) + line("throw WireError.invalidLength(field: \"skip\", length: count)") } block("guard count <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: count, remaining: remaining)") } line("index += count") } line() + block("public mutating func truncate(to count: Int)") { + block("if count >= 0 && count < data.count") { + line("data.removeLast(data.count - count)") + block("if index > count") { line("index = count") } + } + } + line() block("public mutating func writeByte(_ value: UInt8)") { line("data.append(value)") } line() - block("public mutating func readByte() throws -> UInt8") { + block("public mutating func readByte() throws(WireError) -> UInt8") { block("guard 1 <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: 1, remaining: remaining)") } line("let byte = data[index]") line("index += 1") @@ -124,15 +163,14 @@ } line() block("public mutating func writeShort(_ value: Int16)") { - line("var val = value.bigEndian") - line("withUnsafeBytes(of: &val) { data.append(contentsOf: \$0) }") + line("let bits = UInt16(bitPattern: value)") + line("data.append(UInt8(truncatingIfNeeded: bits >> 8))") + line("data.append(UInt8(truncatingIfNeeded: bits))") } line() - block("public mutating func readShort() throws -> Int16") { + block("public mutating func readShort() throws(WireError) -> Int16") { block("guard 2 <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: 2, remaining: remaining)") } line("let bits = (UInt16(data[index]) << 8) | UInt16(data[index + 1])") line("index += 2") @@ -140,15 +178,16 @@ } line() block("public mutating func writeInt(_ value: Int32)") { - line("var val = value.bigEndian") - line("withUnsafeBytes(of: &val) { data.append(contentsOf: \$0) }") + line("let bits = UInt32(bitPattern: value)") + line("data.append(UInt8(truncatingIfNeeded: bits >> 24))") + line("data.append(UInt8(truncatingIfNeeded: bits >> 16))") + line("data.append(UInt8(truncatingIfNeeded: bits >> 8))") + line("data.append(UInt8(truncatingIfNeeded: bits))") } line() - block("public mutating func readInt() throws -> Int32") { + block("public mutating func readInt() throws(WireError) -> Int32") { block("guard 4 <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: 4, remaining: remaining)") } line("let bits = (UInt32(data[index]) << 24)") indent { @@ -161,15 +200,15 @@ } line() block("public mutating func writeLong(_ value: Int64)") { - line("var val = value.bigEndian") - line("withUnsafeBytes(of: &val) { data.append(contentsOf: \$0) }") + line("let bits = UInt64(bitPattern: value)") + block("for shift in stride(from: 56, through: 0, by: -8)") { + line("data.append(UInt8(truncatingIfNeeded: bits >> shift))") + } } line() - block("public mutating func readLong() throws -> Int64") { + block("public mutating func readLong() throws(WireError) -> Int64") { block("guard 8 <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: 8, remaining: remaining)") } line("var bits: UInt64 = 0") block("for i in 0..<8") { line("bits = (bits << 8) | UInt64(data[index + i])") } @@ -178,11 +217,10 @@ } line() block("public mutating func writeFloat(_ value: Float)") { - line("var bitVal = value.bitPattern.bigEndian") - line("withUnsafeBytes(of: &bitVal) { data.append(contentsOf: \$0) }") + line("writeInt(Int32(bitPattern: value.bitPattern))") } line() - block("public mutating func readFloat() throws -> Float") { + block("public mutating func readFloat() throws(WireError) -> Float") { line("let bitVal = UInt32(bitPattern: try readInt())") line("return Float(bitPattern: bitVal)") } @@ -191,109 +229,373 @@ line("writeByte(value ? 1 : 0)") } line() - block("public mutating func readBoolean() throws -> Bool") { + block("public mutating func readBoolean() throws(WireError) -> Bool") { line("return (try readByte()) != 0") } line() - block("public mutating func writeUTF8(_ value: String)") { - line("let utf8Data = Data(value.utf8)") - line("writeInt(Int32(utf8Data.count))") - line("data.append(utf8Data)") + block( + "public mutating func writeUTF8(_ value: String, maxLength: Int? = nil) throws(WireError)" + ) { + line("let utf8Count = value.utf8.count") + line( + "let limit = maxLength.map { Swift.min(\$0, Int(Int32.max)) } ?? Int(Int32.max)" + ) + block("guard utf8Count <= limit else") { + line( + "throw WireError.lengthOutOfRange(field: \"utf8\", length: utf8Count, min: nil, max: limit)" + ) + } + line("writeInt(Int32(utf8Count))") + line("data.append(contentsOf: value.utf8)") } line() - block("public mutating func readUTF8(maxLength: Int? = nil) throws -> String") { + block( + "public mutating func readUTF8(maxLength: Int? = nil) throws(WireError) -> String" + ) { line("let len = Int(try readInt())") block("guard len >= 0 else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative UTF-8 length\"])" - ) + line("throw WireError.invalidLength(field: \"utf8\", length: len)") } block("if let maxLen = maxLength, len > maxLen") { line( - "throw NSError(domain: \"WireBuffer\", code: 5, userInfo: [NSLocalizedDescriptionKey: \"UTF-8 length exceeds maximum\"])" + "throw WireError.lengthOutOfRange(field: \"utf8\", length: len, min: nil, max: maxLen)" ) } block("guard len <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: len, remaining: remaining)") } - line("let strData = data.subdata(in: index..<(index + len))") - block("guard let str = String(data: strData, encoding: .utf8) else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 4, userInfo: [NSLocalizedDescriptionKey: \"Invalid UTF-8 byte sequence\"])" - ) + line("var scalars = String.UnicodeScalarView()") + line("scalars.reserveCapacity(len)") + line("var decoder = UTF8()") + line("var iterator = data[index..<(index + len)].makeIterator()") + block("while true") { + swiftSwitch("decoder.decode(&iterator)") { + swiftCase("case .scalarValue(let scalar)") { + line("scalars.append(scalar)") + } + swiftCase("case .emptyInput") { + line("index += len") + line("return String(scalars)") + } + swiftCase("case .error") { + line("throw WireError.invalidUTF8(field: \"utf8\")") + } + } } - line("index += len") - line("return str") } line() - block("public mutating func writeBuffer(_ value: Data)") { + block( + "public mutating func writeBuffer(_ value: [UInt8], maxLength: Int? = nil) throws(WireError)" + ) { + line( + "let limit = maxLength.map { Swift.min(\$0, Int(Int32.max)) } ?? Int(Int32.max)" + ) + block("guard value.count <= limit else") { + line( + "throw WireError.lengthOutOfRange(field: \"buffer\", length: value.count, min: nil, max: limit)" + ) + } line("writeInt(Int32(value.count))") - line("data.append(value)") + line("data.append(contentsOf: value)") } line() - block("public mutating func writeBytes(_ value: Data)") { line("data.append(value)") } + block("public mutating func writeBytes(_ value: [UInt8])") { + line("data.append(contentsOf: value)") + } line() - block("public mutating func readBytes(count: Int) throws -> Data") { + block("public mutating func readBytes(count: Int) throws(WireError) -> [UInt8]") { block("guard count >= 0 else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative byte count\"])" - ) + line("throw WireError.invalidLength(field: \"bytes\", length: count)") } block("guard count <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: count, remaining: remaining)") } - line("let bufData = data.subdata(in: index..<(index + count))") + line("let bufData = Array(data[index..<(index + count)])") line("index += count") line("return bufData") } line() - block("public mutating func readBuffer(maxLength: Int? = nil) throws -> Data") { + block( + "public mutating func readBuffer(maxLength: Int? = nil) throws(WireError) -> [UInt8]" + ) { line("let len = Int(try readInt())") block("guard len >= 0 else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative buffer length\"])" - ) + line("throw WireError.invalidLength(field: \"buffer\", length: len)") } block("if let maxLen = maxLength, len > maxLen") { line( - "throw NSError(domain: \"WireBuffer\", code: 5, userInfo: [NSLocalizedDescriptionKey: \"Buffer length exceeds maximum\"])" + "throw WireError.lengthOutOfRange(field: \"buffer\", length: len, min: nil, max: maxLen)" ) } block("guard len <= remaining else") { - line( - "throw NSError(domain: \"WireBuffer\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Underflow\"])" - ) + line("throw WireError.underflow(needed: len, remaining: remaining)") } - line("let bufData = data.subdata(in: index..<(index + len))") + line("let bufData = Array(data[index..<(index + len)])") line("index += len") line("return bufData") } } } - private fun emitRemoteDocument(w: CodeWriter) { - w.line("/// In-memory representation of a RemoteCompose document.") - w.block("public struct RemoteDocument") { - line("public static let MAX_HEADER_PROPERTIES: Int = 1000") - line("public static let MAX_OPERATION_COUNT: Int = 100_000") + private fun emitFloatBitEqualityHelpers(w: CodeWriter) { + w.line("@inline(__always)") + w.block("private func wireFloatEquals(_ lhs: Float, _ rhs: Float) -> Bool") { + line("lhs.bitPattern == rhs.bitPattern") + } + w.line() + w.line("@inline(__always)") + w.block("private func wireFloatEquals(_ lhs: Float?, _ rhs: Float?) -> Bool") { + line("lhs?.bitPattern == rhs?.bitPattern") + } + w.line() + w.line("@inline(__always)") + w.block("private func wireFloatEquals(_ lhs: [Float], _ rhs: [Float]) -> Bool") { + line("guard lhs.count == rhs.count else { return false }") + block("for i in lhs.indices") { + line("if lhs[i].bitPattern != rhs[i].bitPattern { return false }") + } + line("return true") + } + w.line() + w.line("@inline(__always)") + w.block("private func wireFloatEquals(_ lhs: [Float]?, _ rhs: [Float]?) -> Bool") { + swiftSwitch("(lhs, rhs)") { + swiftCase("case (nil, nil)") { line("return true") } + swiftCase("case (let a?, let b?)") { line("return wireFloatEquals(a, b)") } + swiftCase("default") { line("return false") } + } + } + w.line() + w.line("@inline(__always)") + w.block("private func wireFloatHash(_ value: Float, into hasher: inout Hasher)") { + line("hasher.combine(value.bitPattern)") + } + w.line() + w.line("@inline(__always)") + w.block("private func wireFloatHash(_ value: Float?, into hasher: inout Hasher)") { + line("hasher.combine(value?.bitPattern)") + } + w.line() + w.line("@inline(__always)") + w.block("private func wireFloatHash(_ value: [Float], into hasher: inout Hasher)") { + line("hasher.combine(value.count)") + block("for element in value") { line("hasher.combine(element.bitPattern)") } + } + w.line() + w.line("@inline(__always)") + w.block("private func wireFloatHash(_ value: [Float]?, into hasher: inout Hasher)") { + block("if let array = value", close = null) { + line("hasher.combine(true)") + line("wireFloatHash(array, into: &hasher)") + } + block("} else") { line("hasher.combine(false)") } + } + } + + private fun isFloatProperty(prop: AstProperty): Boolean = + prop.type == "float" || + prop.type == "float_or_id" || + prop.type == "float[]" || + prop.type == "float_or_id[]" + + private fun emitStructBitExactEquality( + w: CodeWriter, + structName: String, + props: List<AstProperty>, + ) { + if (props.none { isFloatProperty(it) }) return + w.line() + w.block("public static func == (lhs: $structName, rhs: $structName) -> Bool") { + if (props.size == 1) { + val p = props[0] + val cmp = + if (isFloatProperty(p)) "wireFloatEquals(lhs.${p.name}, rhs.${p.name})" + else "lhs.${p.name} == rhs.${p.name}" + line("return $cmp") + } else { + for ((idx, p) in props.withIndex()) { + val cmp = + if (isFloatProperty(p)) "wireFloatEquals(lhs.${p.name}, rhs.${p.name})" + else "lhs.${p.name} == rhs.${p.name}" + if (idx == 0) { + line("return $cmp") + } else { + indent { line("&& $cmp") } + } + } + } + } + w.line() + w.block("public func hash(into hasher: inout Hasher)") { + for (p in props) { + if (isFloatProperty(p)) { + line("wireFloatHash(self.${p.name}, into: &hasher)") + } else { + line("hasher.combine(self.${p.name})") + } + } + } + } + + private fun emitWireOperationEnum(w: CodeWriter) { + w.line("/// Closed union of all RemoteCompose wire operations.") + w.block("public enum WireOperation: Equatable, Hashable, Sendable") { + for (op in schema.operations) { + val swiftCase = toCamelCase(op.name) + line("case $swiftCase(${op.name})") + } line() - line("public var majorVersion: Int32 = 1") - line("public var minorVersion: Int32 = 1") - line("public var patchVersion: Int32 = 0") - line("public var width: Int32 = 0") - line("public var height: Int32 = 0") - line("public var capabilities: Int64 = 0") - line("public var operations: [RemoteOperation] = []") + block("public var opCode: OpCode") { + swiftSwitch("self") { + for (op in schema.operations) { + val swiftCase = toCamelCase(op.name) + line("case .$swiftCase: return .$swiftCase") + } + } + } line() - line("public init() {}") + block("public func write(to buffer: inout WireBuffer) throws(WireError)") { + swiftSwitch("self") { + for (op in schema.operations) { + val swiftCase = toCamelCase(op.name) + line("case .$swiftCase(let op): try op.write(to: &buffer)") + } + } + } + } + } + + private fun emitWireDocument(w: CodeWriter) { + w.line("/// Typed value stored in a modern (v1.1+) RemoteCompose header property.") + w.block("public enum HeaderPropertyValue: Equatable, Hashable, Sendable") { + line("case int(Int32)") + line("case float(Float)") + line("case long(Int64)") + line("case string(String)") + line("case unknown(dataType: Int32, payload: [UInt8])") line() - line("/// Deserializes a RemoteDocument from raw binary data.") block( - "public static func load(from data: Data, maxOperations: Int = MAX_OPERATION_COUNT) throws -> RemoteDocument" + "public static func == (lhs: HeaderPropertyValue, rhs: HeaderPropertyValue) -> Bool" + ) { + swiftSwitch("(lhs, rhs)") { + swiftCase("case (.int(let a), .int(let b))") { line("return a == b") } + swiftCase("case (.float(let a), .float(let b))") { + line("return wireFloatEquals(a, b)") + } + swiftCase("case (.long(let a), .long(let b))") { line("return a == b") } + swiftCase("case (.string(let a), .string(let b))") { line("return a == b") } + swiftCase( + "case (.unknown(let aDt, let aPayload), .unknown(let bDt, let bPayload))" + ) { + line("return aDt == bDt && aPayload == bPayload") + } + swiftCase("default") { line("return false") } + } + } + line() + block("public func hash(into hasher: inout Hasher)") { + swiftSwitch("self") { + swiftCase("case .int(let val)") { + line("hasher.combine(0)") + line("hasher.combine(val)") + } + swiftCase("case .float(let val)") { + line("hasher.combine(1)") + line("wireFloatHash(val, into: &hasher)") + } + swiftCase("case .long(let val)") { + line("hasher.combine(2)") + line("hasher.combine(val)") + } + swiftCase("case .string(let val)") { + line("hasher.combine(3)") + line("hasher.combine(val)") + } + swiftCase("case .unknown(let dt, let payload)") { + line("hasher.combine(4)") + line("hasher.combine(dt)") + line("hasher.combine(payload)") + } + } + } + } + w.line() + w.line("/// Ordered header property entry in a modern (v1.1+) RemoteCompose document.") + w.block("public struct WireHeaderProperty: Equatable, Hashable, Sendable") { + line("public var key: Int32") + line("public var value: HeaderPropertyValue") + line() + block("public init(key: Int32, value: HeaderPropertyValue)") { + line("self.key = key") + line("self.value = value") + } + } + w.line() + w.line("/// Wire-level representation of a RemoteCompose binary document.") + w.block("public struct WireDocument: Equatable, Hashable, Sendable") { + line("public static let maxHeaderProperties: Int = 1000") + line("public static let maxOperationCount: Int = 100_000") + line("public static let defaultDimension: Int32 = 256") + line("public static let magicNumber: Int32 = 0x048C_0000") + line("public static let maxHeaderStringLength: Int = 4000") + line() + line("public var majorVersion: Int32") + line("public var minorVersion: Int32") + line("public var patchVersion: Int32") + line("public var width: Int32") + line("public var height: Int32") + line("public var capabilities: Int64") + line("public var isModernHeader: Bool") + line("public var properties: [WireHeaderProperty]") + line("public var operations: [WireOperation]") + line() + block( + "public init(", + openSuffix = "", + close = null, + ) { + line("majorVersion: Int32 = 1,") + line("minorVersion: Int32 = 1,") + line("patchVersion: Int32 = 0,") + line("width: Int32? = nil,") + line("height: Int32? = nil,") + line("capabilities: Int64? = nil,") + line("isModernHeader: Bool = false,") + line("properties: [WireHeaderProperty] = [],") + line("operations: [WireOperation] = []") + } + block(")") { + line("let modern = isModernHeader || !properties.isEmpty") + line("var resolvedWidth: Int32 = modern ? Self.defaultDimension : 0") + line("var resolvedHeight: Int32 = modern ? Self.defaultDimension : 0") + line("var resolvedCapabilities: Int64 = 0") + block("for prop in properties") { + swiftSwitch("(prop.key, prop.value)") { + swiftCase("case (5, .int(let val))") { line("resolvedWidth = val") } + swiftCase("case (6, .int(let val))") { line("resolvedHeight = val") } + swiftCase("case (14, .int(let val))") { + line("resolvedCapabilities = Int64(UInt32(bitPattern: val))") + } + swiftCase("case (14, .long(let val))") { + line("resolvedCapabilities = val") + } + swiftCase("default") { line("break") } + } + } + line("self.majorVersion = majorVersion") + line("self.minorVersion = minorVersion") + line("self.patchVersion = patchVersion") + line("self.width = width ?? resolvedWidth") + line("self.height = height ?? resolvedHeight") + line("self.capabilities = capabilities ?? resolvedCapabilities") + line("self.isModernHeader = modern") + line("self.properties = properties") + line("self.operations = operations") + } + line() + line("/// Deserializes a WireDocument from raw binary bytes.") + block( + "public static func load(from data: [UInt8], maxOperations: Int = maxOperationCount) throws(WireError) -> WireDocument" ) { line( "return try loadImpl(from: data, maxOperations: maxOperations, evaluateSkip: false, playerApiLevel: 0, playerProfiles: 0)" @@ -301,19 +603,19 @@ } line() line( - "/// Deserializes a RemoteDocument evaluating conditional skip operations against the target player." + "/// Deserializes a WireDocument evaluating conditional skip operations against the target player." ) block( "public static func loadForPlayer(", openSuffix = "", close = null, ) { - line("from data: Data,") + line("from data: [UInt8],") line("playerApiLevel: Int32,") line("playerProfiles: Int32 = 0,") - line("maxOperations: Int = MAX_OPERATION_COUNT") + line("maxOperations: Int = maxOperationCount") } - block(") throws -> RemoteDocument") { + block(") throws(WireError) -> WireDocument") { block("return try loadImpl(", openSuffix = "", close = ")") { line("from: data,") line("maxOperations: maxOperations,") @@ -328,124 +630,134 @@ openSuffix = "", close = null, ) { - line("from data: Data,") + line("from data: [UInt8],") line("maxOperations: Int,") line("evaluateSkip: Bool,") line("playerApiLevel: Int32,") line("playerProfiles: Int32") } - block(") throws -> RemoteDocument") { + block(") throws(WireError) -> WireDocument") { line("var buffer = WireBuffer(data: data)") - line("var doc = RemoteDocument()") + line("var doc = WireDocument()") line("guard buffer.available else { return doc }") line() line("let headerOp = try buffer.readByte()") block("guard headerOp == OpCode.header.rawValue else") { - line( - "throw NSError(domain: \"RemoteDocument\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Expected header opcode\"])" - ) + line("throw WireError.expectedHeaderOpCode(actual: headerOp)") } line("let rawMajor = try buffer.readInt()") line("doc.minorVersion = try buffer.readInt()") line("doc.patchVersion = try buffer.readInt()") block( - "if (UInt32(bitPattern: rawMajor) & 0xFFFF0000) == 0x048C0000", + "if (UInt32(bitPattern: rawMajor) & 0xFFFF_0000) == UInt32(bitPattern: magicNumber)", close = null, ) { + line("doc.isModernHeader = true") line("doc.majorVersion = rawMajor & 0xFFFF") - line("doc.width = 256") - line("doc.height = 256") + line("doc.width = defaultDimension") + line("doc.height = defaultDimension") line("let numProps = Int(try buffer.readInt())") - block("guard numProps >= 0 && numProps <= MAX_HEADER_PROPERTIES else") { + block("guard numProps >= 0 && numProps <= maxHeaderProperties else") { line( - "throw NSError(domain: \"RemoteDocument\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Invalid header property count: \\(numProps)\"])" + "throw WireError.lengthOutOfRange(field: \"headerProperties\", length: numProps, min: 0, max: maxHeaderProperties)" ) } block("guard numProps <= buffer.remaining / 4 else") { line( - "throw NSError(domain: \"RemoteDocument\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Header property count exceeds remaining buffer\"])" + "throw WireError.underflow(needed: numProps * 4, remaining: buffer.remaining)" ) } + line("doc.properties.reserveCapacity(numProps)") block("for _ in 0..<numProps") { - line("let tag = Int32(try buffer.readShort())") - line("_ = try buffer.readShort() // itemLen (read and ignored)") - line("let dataType = tag >> 10") - line("let key = tag & 0x3F") + line("let rawTag = try buffer.readShort()") + line("let itemLen = Int(UInt16(bitPattern: try buffer.readShort()))") + line("let dataType = Int32(rawTag) >> 10") + line("let key = Int32(rawTag) & 0x3F") swiftSwitch("dataType") { swiftCase("case 0") { line("let val = try buffer.readInt()") + line( + "doc.properties.append(WireHeaderProperty(key: key, value: .int(val)))" + ) line("if key == 5 { doc.width = val }") line("else if key == 6 { doc.height = val }") line( "else if key == 14 { doc.capabilities = Int64(UInt32(bitPattern: val)) }" ) block("else if key == 31 && val != 0") { - line( - "throw NSError(domain: \"RemoteDocument\", code: 6, userInfo: [NSLocalizedDescriptionKey: \"Compressed RemoteCompose documents are not supported\"])" - ) + line("throw WireError.compressedDocumentUnsupported") } } - swiftCase("case 1") { line("_ = try buffer.readFloat()") } + swiftCase("case 1") { + line("let val = try buffer.readFloat()") + line( + "doc.properties.append(WireHeaderProperty(key: key, value: .float(val)))" + ) + } swiftCase("case 2") { line("let val = try buffer.readLong()") + line( + "doc.properties.append(WireHeaderProperty(key: key, value: .long(val)))" + ) line("if key == 14 { doc.capabilities = val }") block("else if key == 31 && val != 0") { - line( - "throw NSError(domain: \"RemoteDocument\", code: 6, userInfo: [NSLocalizedDescriptionKey: \"Compressed RemoteCompose documents are not supported\"])" - ) + line("throw WireError.compressedDocumentUnsupported") } } - swiftCase("case 3") { line("_ = try buffer.readUTF8(maxLength: 4000)") } - swiftCase("default") { line("break") } + swiftCase("case 3") { + line( + "let val = try buffer.readUTF8(maxLength: maxHeaderStringLength)" + ) + line( + "doc.properties.append(WireHeaderProperty(key: key, value: .string(val)))" + ) + } + swiftCase("default") { + line("let payload = try buffer.readBytes(count: itemLen)") + line( + "doc.properties.append(WireHeaderProperty(key: key, value: .unknown(dataType: dataType, payload: payload)))" + ) + } } } } block("} else if rawMajor >= 0 && rawMajor < 0x10000", close = null) { + line("doc.isModernHeader = false") line("doc.majorVersion = rawMajor") line("doc.width = try buffer.readInt()") line("doc.height = try buffer.readInt()") line("doc.capabilities = try buffer.readLong()") } - block("} else") { - line( - "throw NSError(domain: \"RemoteDocument\", code: 7, userInfo: [NSLocalizedDescriptionKey: \"Invalid header magic number: \\(rawMajor)\"])" - ) - } + block("} else") { line("throw WireError.invalidHeaderMagic(rawMajor)") } line() block("while buffer.available") { block("guard doc.operations.count < maxOperations else") { - line( - "throw NSError(domain: \"RemoteDocument\", code: 8, userInfo: [NSLocalizedDescriptionKey: \"Operation count exceeds limit \\(maxOperations)\"])" - ) + line("throw WireError.operationCountExceeded(limit: maxOperations)") } line("let opByte = try buffer.readByte()") block("guard let opCode = OpCode(rawValue: opByte) else") { - line( - "throw NSError(domain: \"RemoteDocument\", code: 5, userInfo: [NSLocalizedDescriptionKey: \"Unknown opcode: \\(opByte)\"])" - ) + line("throw WireError.unknownOpCode(opByte)") } swiftSwitch("opCode") { for (op in schema.operations) { val swiftCase = toCamelCase(op.name) swiftCase("case .$swiftCase") { if (op.id == 0) { - line( - "throw NSError(domain: \"RemoteDocument\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Unexpected Header opcode inside document body\"])" - ) + line("throw WireError.unexpectedHeaderInBody") } else if (op.conditionalSkip != null) { block("if evaluateSkip", close = null) { line( - "doc.operations.append(try ${op.name}.readForPlayer(from: &buffer, playerApiLevel: playerApiLevel, playerProfiles: playerProfiles))" + "doc.operations.append(.$swiftCase(try ${op.name}.readForPlayer(from: &buffer, playerApiLevel: playerApiLevel, playerProfiles: playerProfiles)))" ) } block("} else") { line( - "doc.operations.append(try ${op.name}.read(from: &buffer))" + "doc.operations.append(.$swiftCase(try ${op.name}.read(from: &buffer)))" ) } } else { line( - "doc.operations.append(try ${op.name}.read(from: &buffer))" + "doc.operations.append(.$swiftCase(try ${op.name}.read(from: &buffer)))" ) } } @@ -455,16 +767,144 @@ line("return doc") } line() - line("/// Serializes this document to raw binary data.") - block("public func save() throws -> Data") { + line("/// Serializes this document to raw binary bytes, preserving modern headers.") + block("public func save() throws(WireError) -> [UInt8]") { + block("guard majorVersion >= 0 && majorVersion <= 0xFFFF else") { + line( + "throw WireError.invalidFieldValue(owner: \"WireDocument\", field: \"majorVersion\", detail: \"majorVersion \\(majorVersion) out of range (0..65535)\")" + ) + } line("var buffer = WireBuffer()") line("buffer.writeByte(OpCode.header.rawValue)") - line("buffer.writeInt(majorVersion)") - line("buffer.writeInt(minorVersion)") - line("buffer.writeInt(patchVersion)") - line("buffer.writeInt(width)") - line("buffer.writeInt(height)") - line("buffer.writeLong(capabilities)") + block("if isModernHeader || !properties.isEmpty", close = null) { + line("var outProps = properties") + block( + "if let idx = outProps.lastIndex(where: { if \$0.key != 5 { return false }; if case .int(_) = \$0.value { return true }; return false })", + close = null, + ) { + line("outProps[idx].value = .int(width)") + } + block("} else if width != Self.defaultDimension") { + line("outProps.append(WireHeaderProperty(key: 5, value: .int(width)))") + } + block( + "if let idx = outProps.lastIndex(where: { if \$0.key != 6 { return false }; if case .int(_) = \$0.value { return true }; return false })", + close = null, + ) { + line("outProps[idx].value = .int(height)") + } + block("} else if height != Self.defaultDimension") { + line("outProps.append(WireHeaderProperty(key: 6, value: .int(height)))") + } + line("let capValue: HeaderPropertyValue") + block( + "if capabilities >= 0 && capabilities <= Int64(UInt32.max)", + close = null, + ) { + line("capValue = .int(Int32(truncatingIfNeeded: capabilities))") + } + block("} else") { line("capValue = .long(capabilities)") } + block( + "if let idx = outProps.lastIndex(where: { if \$0.key != 14 { return false }; switch \$0.value { case .int(_), .long(_): return true; default: return false } })", + close = null, + ) { + line("let matchesExisting: Bool") + swiftSwitch("outProps[idx].value") { + swiftCase("case .int(let existing)") { + line( + "matchesExisting = Int64(UInt32(bitPattern: existing)) == capabilities" + ) + } + swiftCase("case .long(let existing)") { + line("matchesExisting = existing == capabilities") + } + swiftCase("default") { line("matchesExisting = false") } + } + block("if !matchesExisting") { line("outProps[idx].value = capValue") } + } + block("} else if capabilities != 0") { + line("outProps.append(WireHeaderProperty(key: 14, value: capValue))") + } + block("guard outProps.count <= Self.maxHeaderProperties else") { + line( + "throw WireError.lengthOutOfRange(field: \"headerProperties\", length: outProps.count, min: 0, max: Self.maxHeaderProperties)" + ) + } + line("buffer.writeInt(Self.magicNumber | (majorVersion & 0xFFFF))") + line("buffer.writeInt(minorVersion)") + line("buffer.writeInt(patchVersion)") + line("buffer.writeInt(Int32(outProps.count))") + block("for prop in outProps") { + block("guard prop.key >= 0 && prop.key <= 0x3F else") { + line( + "throw WireError.invalidFieldValue(owner: \"WireDocument\", field: \"headerPropertyKey\", detail: \"Property key \\(prop.key) out of range (0..63)\")" + ) + } + swiftSwitch("prop.value") { + swiftCase("case .int(let val)") { + line( + "buffer.writeShort(Int16(truncatingIfNeeded: prop.key & 0x3F))" + ) + line("buffer.writeShort(4)") + line("buffer.writeInt(val)") + } + swiftCase("case .float(let val)") { + line( + "buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | (1 << 10)))" + ) + line("buffer.writeShort(4)") + line("buffer.writeFloat(val)") + } + swiftCase("case .long(let val)") { + line( + "buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | (2 << 10)))" + ) + line("buffer.writeShort(8)") + line("buffer.writeLong(val)") + } + swiftCase("case .string(let val)") { + line("let utf8Count = val.utf8.count") + block("guard utf8Count <= Self.maxHeaderStringLength else") { + line( + "throw WireError.lengthOutOfRange(field: \"headerStringProperty\", length: utf8Count, min: nil, max: Self.maxHeaderStringLength)" + ) + } + line( + "buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | (3 << 10)))" + ) + line("buffer.writeShort(Int16(truncatingIfNeeded: utf8Count + 4))") + line( + "try buffer.writeUTF8(val, maxLength: Self.maxHeaderStringLength)" + ) + } + swiftCase("case .unknown(let dt, let payload)") { + block("guard dt >= -32 && dt <= 31 && (dt < 0 || dt > 3) else") { + line( + "throw WireError.invalidFieldValue(owner: \"WireDocument\", field: \"headerPropertyDataType\", detail: \"Unknown dataType \\(dt) out of range\")" + ) + } + block("guard payload.count <= Int(UInt16.max) else") { + line( + "throw WireError.lengthOutOfRange(field: \"headerUnknownProperty\", length: payload.count, min: nil, max: Int(UInt16.max))" + ) + } + line( + "buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | ((dt & 0x3F) << 10)))" + ) + line("buffer.writeShort(Int16(truncatingIfNeeded: payload.count))") + line("buffer.writeBytes(payload)") + } + } + } + } + block("} else") { + line("buffer.writeInt(majorVersion)") + line("buffer.writeInt(minorVersion)") + line("buffer.writeInt(patchVersion)") + line("buffer.writeInt(width)") + line("buffer.writeInt(height)") + line("buffer.writeLong(capabilities)") + } line() block("for op in operations") { line("try op.write(to: &buffer)") } line("return buffer.data") @@ -478,7 +918,7 @@ if (desc.isNotEmpty()) { w.line("/// $desc") } - w.block("public struct ${structDef.name}: Equatable") { + w.block("public struct ${structDef.name}: Equatable, Hashable, Sendable") { multiLang.emitSwiftOpEnumConstants(this, structDef.fields) for (prop in props) { val swiftType = mapToSwiftType(prop.type, prop.isNullable) @@ -526,15 +966,18 @@ line() block( - "public static func read(from buffer: inout WireBuffer) throws -> ${structDef.name}" + "public static func read(from buffer: inout WireBuffer) throws(WireError) -> ${structDef.name}" ) { emitSwiftReadBody(this, structDef.name, structDef.fields, null, props) } line() - block("public func write(to buffer: inout WireBuffer) throws") { - emitSwiftWriteBody(this, structDef.name, structDef.fields, null, props) + block("public func write(to buffer: inout WireBuffer) throws(WireError)") { + emitSwiftAtomicWriteBody(this) { + emitSwiftWriteBody(this, structDef.name, structDef.fields, null, props) + } } + emitStructBitExactEquality(this, structDef.name, props) } } @@ -545,8 +988,9 @@ w.line("/// $desc") } val swiftCase = toCamelCase(op.name) - w.block("public struct ${op.name}: RemoteOperation, Equatable") { - line("public let opCode: OpCode = .$swiftCase") + w.block("public struct ${op.name}: Equatable, Hashable, Sendable") { + line("public static let opCode: OpCode = .$swiftCase") + line("public var opCode: OpCode { Self.opCode }") multiLang.emitSwiftOpEnumConstants(this, op.fields) line() @@ -601,7 +1045,9 @@ line() line("/// Reads and decodes a [${op.name}] from the wire buffer.") - block("public static func read(from buffer: inout WireBuffer) throws -> ${op.name}") { + block( + "public static func read(from buffer: inout WireBuffer) throws(WireError) -> ${op.name}" + ) { if (op.conditionalSkip != null) { line("let skipTaken = true") } @@ -641,7 +1087,7 @@ } line() block( - "public static func readForPlayer(from buffer: inout WireBuffer, playerApiLevel: Int32, playerProfiles: Int32 = 0) throws -> ${op.name}" + "public static func readForPlayer(from buffer: inout WireBuffer, playerApiLevel: Int32, playerProfiles: Int32 = 0) throws(WireError) -> ${op.name}" ) { emitSwiftReadBody( this, @@ -658,19 +1104,24 @@ } line("/// Serializes this operation to the wire buffer.") - block("public func write(to buffer: inout WireBuffer) throws") { - line("buffer.writeByte(opCode.rawValue)") - emitSwiftWriteBody( + block("public func write(to buffer: inout WireBuffer) throws(WireError)") { + emitSwiftAtomicWriteBody( this, - op.name, - op.fields, - op.sparseParameters, - props, - op.sparseCountType, - op.sparseKeyType, - op.conditionalSkip, - ) + prefixLine = "buffer.writeByte(Self.opCode.rawValue)", + ) { + emitSwiftWriteBody( + this, + op.name, + op.fields, + op.sparseParameters, + props, + op.sparseCountType, + op.sparseKeyType, + op.conditionalSkip, + ) + } } + emitStructBitExactEquality(this, op.name, props) } } @@ -694,7 +1145,7 @@ if (f.minValue != null) { w.block("guard $intExpr >= ${f.minValue} else") { line( - "throw NSError(domain: \"$ownerName\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Invalid ${f.name} below minimum (${f.minValue})\"])" + "throw WireError.invalidFieldValue(owner: \"$ownerName\", field: \"${f.name}\", detail: \"below minimum (${f.minValue})\")" ) } } @@ -707,7 +1158,7 @@ ) w.block("if $badBits") { line( - "throw NSError(domain: \"$ownerName\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Non-zero reserved bits in ${f.name}\"])" + "throw WireError.invalidFieldValue(owner: \"$ownerName\", field: \"${f.name}\", detail: \"non-zero reserved bits\")" ) } } @@ -761,7 +1212,7 @@ ) w.block("if $badBits") { line( - "throw NSError(domain: \"$ownerName\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Non-zero reserved bits in ${f.name}\"])" + "throw WireError.invalidFieldValue(owner: \"$ownerName\", field: \"${f.name}\", detail: \"non-zero reserved bits\")" ) } } @@ -797,10 +1248,12 @@ emitSwiftArrayRead(this, ownerName, f, "${f.name}Tmp") line("${f.name} = ${f.name}Tmp") } else if (hasSwiftScalarValidations(f)) { + emitSwiftCountedBytesGuards(this, f) line("let parsed = try ${mapToSwiftFieldReadExpr(f)}") emitSwiftScalarValidations(this, ownerName, f, "parsed") line("${f.name} = parsed") } else { + emitSwiftCountedBytesGuards(this, f) line("${f.name} = try ${mapToSwiftFieldReadExpr(f)}") } } @@ -810,6 +1263,7 @@ } else if (f.type.endsWith("[]")) { emitSwiftArrayRead(w, ownerName, f, f.name) } else { + emitSwiftCountedBytesGuards(w, f) w.line("let ${f.name} = try ${mapToSwiftFieldReadExpr(f)}") emitSwiftScalarValidations(w, ownerName, f, f.name) } @@ -826,7 +1280,7 @@ w.line("let sparseCount = Int(try buffer.readInt())") w.block("guard sparseCount >= 0 else") { line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative sparse parameter count\"])" + "throw WireError.invalidLength(field: \"sparseCount\", length: sparseCount)" ) } } @@ -834,7 +1288,7 @@ w.line("let sparseCount = Int(try buffer.readShort())") w.block("guard sparseCount >= 0 else") { line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative sparse parameter count\"])" + "throw WireError.invalidLength(field: \"sparseCount\", length: sparseCount)" ) } } @@ -842,7 +1296,7 @@ w.line("let sparseCount = Int(Int8(bitPattern: try buffer.readByte()))") w.block("guard sparseCount >= 0 else") { line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative sparse parameter count\"])" + "throw WireError.invalidLength(field: \"sparseCount\", length: sparseCount)" ) } } @@ -858,7 +1312,10 @@ } w.block("guard sparseCount <= buffer.remaining / $minEntryBytes else") { line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Sparse parameter count exceeds remaining buffer\"])" + "let (needed, overflow) = sparseCount.multipliedReportingOverflow(by: $minEntryBytes)" + ) + line( + "throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining)" ) } w.block("for _ in 0..<sparseCount") { @@ -891,7 +1348,7 @@ } swiftCase("default") { line( - "throw NSError(domain: \"$ownerName\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Unknown sparse parameter\"])" + "throw WireError.unknownSparseParameter(owner: \"$ownerName\", id: paramId)" ) } } @@ -916,7 +1373,7 @@ swiftCase("case $allowed") { line("break") } swiftCase("default") { line( - "throw NSError(domain: \"$ownerName\", code: 2, userInfo: [NSLocalizedDescriptionKey: \"Invalid enum value for $fieldName\"])" + "throw WireError.invalidFieldValue(owner: \"$ownerName\", field: \"$fieldName\", detail: \"invalid enum value \\($varExpr)\")" ) } } @@ -944,37 +1401,100 @@ val elemType = f.type.removeSuffix("[]") val elemMinBytes = CodegenExprUtils.minWireElementBytes(elemType, schema) w.block("guard $lenVar >= 0 else") { - line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Invalid negative array length\"])" - ) + line("throw WireError.invalidLength(field: \"${f.name}\", length: $lenVar)") } if (f.minLength != null && f.minLength > 0) { w.block("guard $lenVar >= ${f.minLength} else") { line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Array length below minimum (${f.minLength})\"])" + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $lenVar, min: ${f.minLength}, max: ${f.maxLength?.toString() ?: "nil"})" ) } } if (f.maxLength != null) { w.block("guard $lenVar <= ${f.maxLength} else") { line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Array length exceeds maximum (${f.maxLength})\"])" + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $lenVar, min: ${f.minLength?.toString() ?: "nil"}, max: ${f.maxLength})" ) } } w.block("guard $lenVar <= buffer.remaining / $elemMinBytes else") { - line( - "throw NSError(domain: \"$ownerName\", code: 1, userInfo: [NSLocalizedDescriptionKey: \"Array length exceeds remaining buffer\"])" - ) + if (elemMinBytes == 1) { + line("throw WireError.underflow(needed: $lenVar, remaining: buffer.remaining)") + } else { + line( + "let (needed, overflow) = $lenVar.multipliedReportingOverflow(by: $elemMinBytes)" + ) + line( + "throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining)" + ) + } } val swiftElemType = mapToSwiftType(elemType, false) w.line("var $targetVar = [$swiftElemType]()") - w.line("$targetVar.reserveCapacity(min($lenVar, 4096))") + w.line("$targetVar.reserveCapacity(Swift.min($lenVar, 4096))") w.block("for _ in 0..<$lenVar") { line("$targetVar.append(try ${mapToSwiftReadExpr(elemType)})") } } + private fun swiftLengthTypeMax(lengthType: String): Int = + when (lengthType) { + "byte" -> 127 + "ubyte" -> 255 + "short" -> 32767 + "ushort" -> 65535 + else -> Int.MAX_VALUE + } + + private fun emitSwiftAtomicWriteBody( + w: CodeWriter, + prefixLine: String? = null, + emitBody: CodeWriter.() -> Unit, + ) { + val body = buildCode { + if (prefixLine != null) { + line(prefixLine) + } + emitBody() + } + val bodyLines = body.trimEnd('\n').split('\n').filter { it.isNotEmpty() } + val canThrow = body.contains("throw ") || body.contains("try ") + if (canThrow) { + w.line("let _startCount = buffer.data.count") + w.line("var _committed = false") + w.block("defer") { + block("if !_committed") { line("buffer.truncate(to: _startCount)") } + } + for (l in bodyLines) { + w.line(l) + } + w.line("_committed = true") + } else { + for (l in bodyLines) { + w.line(l) + } + } + } + + private fun emitSwiftCountedBytesGuards(w: CodeWriter, f: SchemaField) { + if (f.type != "bytes" || f.countFrom == null) return + val countExpr = "Int(${f.countFrom})" + if (f.minLength != null && f.minLength > 0) { + w.block("guard $countExpr >= ${f.minLength} else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $countExpr, min: ${f.minLength}, max: ${f.maxLength?.toString() ?: "nil"})" + ) + } + } + if (f.maxLength != null) { + w.block("guard $countExpr <= ${f.maxLength} else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $countExpr, min: ${f.minLength?.toString() ?: "nil"}, max: ${f.maxLength})" + ) + } + } + } + private fun emitSwiftWriteBody( w: CodeWriter, ownerName: String, @@ -994,7 +1514,20 @@ val terms = mutableListOf<Pair<String, SchemaBitField>>() for (b in bits) { if (b.derivedFrom != null) { - val expr = derivedExprToSwift(DerivedExpr.parse(b.derivedFrom)) + val parsed = DerivedExpr.parse(b.derivedFrom) + if (parsed is DerivedExpr.LengthOf) { + val rawMax = + if (b.signed) (1L shl (b.bitWidth - 1)) - 1L + else (1L shl b.bitWidth) - 1L + val bitMax = rawMax.coerceAtMost(Int.MAX_VALUE.toLong()).toInt() + val target = parsed.targetName + w.block("guard $target.count <= $bitMax else") { + line( + "throw WireError.lengthOutOfRange(field: \"$target\", length: $target.count, min: nil, max: $bitMax)" + ) + } + } + val expr = derivedExprToSwift(parsed) w.line("let ${b.name}: Int32 = $expr") localVars.add(b.name) terms.add(b.name to b) @@ -1008,12 +1541,33 @@ } if (f.derivedFrom != null) { - val expr = derivedExprToSwift(DerivedExpr.parse(f.derivedFrom)) + val parsed = DerivedExpr.parse(f.derivedFrom) + val expr = derivedExprToSwift(parsed) + val maxLimit = + if (parsed is DerivedExpr.LengthOf) swiftLengthTypeMax(f.type) else null if (f.presentIf != null) { val cond = CodegenExprUtils.translateCondition(f.presentIf, ExprLang.SWIFT) { it } - w.block("if $cond") { line(mapToSwiftDerivedWrite(f.type, expr)) } + w.block("if $cond") { + if (maxLimit != null) { + val target = parsed.targetName + block("guard $target.count <= $maxLimit else") { + line( + "throw WireError.lengthOutOfRange(field: \"$target\", length: $target.count, min: nil, max: $maxLimit)" + ) + } + } + line(mapToSwiftDerivedWrite(f.type, expr)) + } } else { + if (maxLimit != null) { + val target = parsed.targetName + w.block("guard $target.count <= $maxLimit else") { + line( + "throw WireError.lengthOutOfRange(field: \"$target\", length: $target.count, min: nil, max: $maxLimit)" + ) + } + } w.line("let ${f.name}: Int32 = $expr") localVars.add(f.name) w.line(mapToSwiftDerivedWrite(f.type, f.name)) @@ -1023,13 +1577,35 @@ val isNullable = propByName[f.name]?.isNullable == true if (conditionalSkip != null && f.name == conditionalSkip.lengthField) { - w.line( - "buffer.writeInt(${conditionalSkip.payloadField} != nil ? Int32(${conditionalSkip.payloadField}!.count) : ${f.name})" - ) + w.block("if let _payload = ${conditionalSkip.payloadField}", close = null) { + block("guard _payload.count <= Int(Int32.max) else") { + line( + "throw WireError.lengthOutOfRange(field: \"${conditionalSkip.payloadField}\", length: _payload.count, min: nil, max: Int(Int32.max))" + ) + } + line("buffer.writeInt(Int32(_payload.count))") + } + w.block("} else") { line("buffer.writeInt(${f.name})") } continue } if (conditionalSkip != null && f.name == conditionalSkip.payloadField) { - w.block("if let val = ${f.name}") { line("buffer.writeBytes(val)") } + w.block("if let val = ${f.name}") { + if (f.minLength != null && f.minLength > 0) { + block("guard val.count >= ${f.minLength} else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: val.count, min: ${f.minLength}, max: ${f.maxLength?.toString() ?: "nil"})" + ) + } + } + if (f.maxLength != null) { + block("guard val.count <= ${f.maxLength} else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: val.count, min: ${f.minLength?.toString() ?: "nil"}, max: ${f.maxLength})" + ) + } + } + line("buffer.writeBytes(val)") + } continue } if (f.presentIf != null) { @@ -1038,7 +1614,7 @@ if (isNullable) { block("guard let val = ${f.name} else") { line( - "throw NSError(domain: \"$ownerName\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Missing required field ${f.name}\"])" + "throw WireError.missingRequiredField(owner: \"$ownerName\", field: \"${f.name}\")" ) } emitSwiftFieldWrite(this, f, "val") @@ -1087,6 +1663,27 @@ private fun emitSwiftFieldWrite(w: CodeWriter, f: SchemaField, varExpr: String) { if (f.type.endsWith("[]")) { + val effectiveMax = + if (f.countFrom == null) { + val prefixMax = swiftLengthTypeMax(f.effectiveLengthType) + if (f.maxLength != null) minOf(f.maxLength, prefixMax) else prefixMax + } else { + f.maxLength + } + if (f.minLength != null && f.minLength > 0) { + w.block("guard $varExpr.count >= ${f.minLength} else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $varExpr.count, min: ${f.minLength}, max: ${effectiveMax?.toString() ?: "nil"})" + ) + } + } + if (effectiveMax != null) { + w.block("guard $varExpr.count <= $effectiveMax else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $varExpr.count, min: ${f.minLength?.toString() ?: "nil"}, max: $effectiveMax)" + ) + } + } if (f.countFrom == null) { when (f.effectiveLengthType) { "int" -> w.line("buffer.writeInt(Int32($varExpr.count))") @@ -1098,9 +1695,23 @@ val elemType = f.type.removeSuffix("[]") w.block("for item in $varExpr") { line(mapToSwiftWriteExpr(elemType, "item")) } } else if (f.type == "bytes" && f.countFrom != null) { + if (f.minLength != null && f.minLength > 0) { + w.block("guard $varExpr.count >= ${f.minLength} else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $varExpr.count, min: ${f.minLength}, max: ${f.maxLength?.toString() ?: "nil"})" + ) + } + } + if (f.maxLength != null) { + w.block("guard $varExpr.count <= ${f.maxLength} else") { + line( + "throw WireError.lengthOutOfRange(field: \"${f.name}\", length: $varExpr.count, min: ${f.minLength?.toString() ?: "nil"}, max: ${f.maxLength})" + ) + } + } w.line("buffer.writeBytes($varExpr)") } else { - w.line(mapToSwiftWriteExpr(f.type, varExpr)) + w.line(mapToSwiftWriteExpr(f.type, varExpr, f.maxLength)) } } @@ -1154,7 +1765,7 @@ "float_or_id" -> "Float" "boolean" -> "Bool" "string" -> "String" - "bytes" -> "Data" + "bytes" -> "[UInt8]" else -> if (schema.structs.containsKey(type)) type else "Int32" } } @@ -1187,7 +1798,7 @@ "float_or_id" -> "0.0" "boolean" -> "false" "string" -> "\"\"" - "bytes" -> "Data()" + "bytes" -> "[]" else -> if (schema.structs.containsKey(type)) "$type()" else "0" } } @@ -1214,7 +1825,11 @@ else "buffer.readInt()" } - private fun mapToSwiftWriteExpr(type: String, varName: String): String = + private fun mapToSwiftWriteExpr( + type: String, + varName: String, + maxLength: Int? = null, + ): String = when (type) { "int", "int_id", @@ -1225,8 +1840,12 @@ "float", "float_or_id" -> "buffer.writeFloat($varName)" "boolean" -> "buffer.writeBoolean($varName)" - "string" -> "buffer.writeUTF8($varName)" - "bytes" -> "buffer.writeBuffer($varName)" + "string" -> + if (maxLength != null) "try buffer.writeUTF8($varName, maxLength: $maxLength)" + else "try buffer.writeUTF8($varName)" + "bytes" -> + if (maxLength != null) "try buffer.writeBuffer($varName, maxLength: $maxLength)" + else "try buffer.writeBuffer($varName)" else -> if (schema.structs.containsKey(type)) "try $varName.write(to: &buffer)" else "buffer.writeInt($varName)"
diff --git a/compose/remote/remote-generator/src/main/resources/schema/operations.json b/compose/remote/remote-generator/src/main/resources/schema/operations.json index f02b100..01d2fa4 100644 --- a/compose/remote/remote-generator/src/main/resources/schema/operations.json +++ b/compose/remote/remote-generator/src/main/resources/schema/operations.json
@@ -472,6 +472,7 @@ { "id": 16, "name": "WidthModifierOperation", + "opCodeName": "MODIFIER_WIDTH", "category": "Modifier Operations", "description": "Fixed width modifier", "addedVersion": 6, @@ -583,6 +584,7 @@ { "id": 40, "name": "PaintData", + "opCodeName": "PAINT_VALUES", "category": "Paint & Styles Operations", "description": "Encode a Paint object with various properties", "addedVersion": 6, @@ -680,6 +682,7 @@ { "id": 43, "name": "DrawText", + "opCodeName": "DRAW_TEXT_RUN", "category": "Text Operations", "description": "Draw a run of text, all in a single direction", "addedVersion": 6, @@ -776,6 +779,7 @@ { "id": 45, "name": "ShaderData", + "opCodeName": "DATA_SHADER", "category": "Paint & Styles Operations", "description": "Defines a runtime shader program with uniforms and texture bindings for paint effects", "addedVersion": 6, @@ -904,6 +908,7 @@ { "id": 48, "name": "DrawBitmapFontText", + "opCodeName": "DRAW_BITMAP_FONT_TEXT_RUN", "category": "Text Operations", "description": "Draw text using a bitmap font", "addedVersion": 6, @@ -969,6 +974,7 @@ { "id": 49, "name": "DrawBitmapFontTextOnPath", + "opCodeName": "DRAW_BITMAP_FONT_TEXT_RUN_ON_PATH", "category": "Text Operations", "description": "Draw text using a bitmap font along a path", "addedVersion": 7, @@ -1160,6 +1166,7 @@ { "id": 54, "name": "RoundedClipRectModifierOperation", + "opCodeName": "MODIFIER_ROUNDED_CLIP_RECT", "category": "Modifier Operations", "description": "Clip the component's content to its rounded rectangular bounds", "addedVersion": 6, @@ -1193,6 +1200,7 @@ { "id": 55, "name": "BackgroundModifierOperation", + "opCodeName": "MODIFIER_BACKGROUND", "category": "Modifier Operations", "description": "Background color modifier", "addedVersion": 6, @@ -1200,7 +1208,10 @@ { "name": "flags", "type": "int", - "description": "Modifier flags (bit 1 = COLOR_REF)" + "description": "Modifier flags (bit 1 = COLOR_REF)", + "enum": { + "COLOR_REF": 2 + } }, { "name": "colorId", @@ -1352,6 +1363,7 @@ { "id": 58, "name": "PaddingModifierOperation", + "opCodeName": "MODIFIER_PADDING", "category": "Modifier Operations", "description": "Applies padding offsets around a layout component", "addedVersion": 6, @@ -1385,6 +1397,7 @@ { "id": 59, "name": "ClickModifier", + "opCodeName": "MODIFIER_CLICK", "category": "Modifier Operations", "description": "Click modifier. This operation contains a list of action operations executed on click", "addedVersion": 6, @@ -1401,7 +1414,8 @@ "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "ClickModifierOperation" }, { "id": 60, @@ -1704,6 +1718,7 @@ { "id": 67, "name": "HeightModifierOperation", + "opCodeName": "MODIFIER_HEIGHT", "category": "Modifier Operations", "description": "Fixed height modifier", "addedVersion": 6, @@ -1739,6 +1754,7 @@ { "id": 80, "name": "FloatConstant", + "opCodeName": "DATA_FLOAT", "category": "Data Operations", "description": "Define a constant float variable", "addedVersion": 6, @@ -1764,6 +1780,7 @@ { "id": 81, "name": "FloatExpression", + "opCodeName": "ANIMATED_FLOAT", "category": "Logic & Expressions Operations", "description": "Defines a float variable computed via Reverse Polish Notation (RPN) expression evaluation", "addedVersion": 6, @@ -1818,6 +1835,7 @@ { "id": 83, "name": "MultiClickModifier", + "opCodeName": "MODIFIER_MULTI_CLICK", "category": "Modifier Operations", "description": "MultiClick modifier. This operation contains a list of action operations executed on click", "addedVersion": 7, @@ -1840,6 +1858,7 @@ { "id": 93, "name": "Custom", + "opCodeName": "LAYOUT_CUSTOM", "category": "Layout Managers", "description": "Hosts and configures platform-specific native custom components", "addedVersion": 7, @@ -1947,6 +1966,7 @@ { "id": 101, "name": "BitmapData", + "opCodeName": "DATA_BITMAP", "category": "Data Operations", "description": "Embed or reference bitmap image data", "addedVersion": 6, @@ -2024,6 +2044,7 @@ { "id": 102, "name": "TextData", + "opCodeName": "DATA_TEXT", "category": "Text Operations", "description": "Define a static string and associate it with an ID", "addedVersion": 6, @@ -2067,6 +2088,7 @@ { "id": 104, "name": "AddMesh2D", + "opCodeName": "ADD_MESH_2D", "category": "Canvas Operations", "description": "Defines a 2D vertex mesh for canvas deformation, independent of the 3D subsystem", "addedVersion": 7, @@ -2350,6 +2372,7 @@ { "id": 105, "name": "DrawMesh2D", + "opCodeName": "DRAW_MESH_2D", "category": "Canvas Operations", "description": "Draw a 2D vertex mesh defined by AddMesh2D", "addedVersion": 7, @@ -2384,6 +2407,7 @@ { "id": 106, "name": "MatrixFromMesh2D", + "opCodeName": "MATRIX_FROM_MESH_2D", "category": "Matrix Operations", "description": "Multiply the local frame of a 2D mesh at (u, v) into the current canvas matrix, so ordinary drawing can be placed onto a deformed surface", "addedVersion": 7, @@ -2425,6 +2449,7 @@ { "id": 107, "name": "BorderModifierOperation", + "opCodeName": "MODIFIER_BORDER", "category": "Modifier Operations", "description": "Define a border for a component", "addedVersion": 6, @@ -2432,7 +2457,10 @@ { "name": "flags", "type": "int", - "description": "Behavior flags" + "description": "Behavior flags", + "enum": { + "COLOR_REF": 2 + } }, { "name": "colorId", @@ -2442,7 +2470,11 @@ { "name": "reserve1", "type": "int", - "description": "0 for legacy behavior, 1 to support dynamic radius" + "description": "0 for legacy behavior, 1 to support dynamic radius", + "enum": { + "LEGACY": 0, + "VERSION_1": 1 + } }, { "name": "reserve2", @@ -2482,7 +2514,12 @@ { "name": "shapeType", "type": "int", - "description": "The shape type (0=RECTANGLE, 1=CIRCLE)" + "description": "The shape type (0=RECTANGLE, 1=CIRCLE, 2=ROUNDED_RECTANGLE)", + "enum": { + "RECTANGLE": 0, + "CIRCLE": 1, + "ROUNDED_RECTANGLE": 2 + } } ], "profiles": [ @@ -2493,6 +2530,7 @@ { "id": 108, "name": "ClipRectModifierOperation", + "opCodeName": "MODIFIER_CLIP_RECT", "category": "Modifier Operations", "description": "Clip the component's content to its rectangular bounds", "addedVersion": 6, @@ -2605,6 +2643,7 @@ { "id": 123, "name": "PathData", + "opCodeName": "DATA_PATH", "category": "Canvas Operations", "description": "Defines a complete static path data buffer with commands and coordinates", "addedVersion": 6, @@ -2840,6 +2879,7 @@ { "id": 133, "name": "DrawTextAnchored", + "opCodeName": "DRAW_TEXT_ANCHOR", "category": "Text Operations", "description": "Draw text centered about an anchor point", "addedVersion": 6, @@ -2889,6 +2929,7 @@ { "id": 134, "name": "ColorExpression", + "opCodeName": "COLOR_EXPRESSIONS", "category": "Paint & Styles Operations", "description": "Defines a color via dynamic expression (interpolation, HSV, or ARGB)", "addedVersion": 6, @@ -3205,6 +3246,7 @@ { "id": 140, "name": "IntegerConstant", + "opCodeName": "DATA_INT", "category": "Data Operations", "description": "Define a constant integer variable", "addedVersion": 6, @@ -3270,6 +3312,7 @@ { "id": 143, "name": "BooleanConstant", + "opCodeName": "DATA_BOOLEAN", "category": "Data Operations", "description": "Define a constant boolean variable", "addedVersion": 6, @@ -3328,6 +3371,7 @@ { "id": 145, "name": "DataMapIds", + "opCodeName": "ID_MAP", "category": "Data Operations", "description": "Encode a collection of named variable IDs", "addedVersion": 6, @@ -3356,6 +3400,7 @@ { "id": 146, "name": "IdListData", + "opCodeName": "ID_LIST", "category": "Data Operations", "description": "Defines an indexed list of integer resource or variable identifiers", "addedVersion": 6, @@ -3379,11 +3424,13 @@ "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "DataListIds" }, { "id": 147, "name": "FloatListData", + "opCodeName": "FLOAT_LIST", "category": "Data Operations", "description": "Defines an indexed list of float values for variables or geometry", "addedVersion": 6, @@ -3407,11 +3454,13 @@ "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "DataListFloat" }, { "id": 148, "name": "LongConstant", + "opCodeName": "DATA_LONG", "category": "Data Operations", "description": "A long and its associated id", "addedVersion": 6, @@ -3953,6 +4002,7 @@ { "id": 160, "name": "PathAppend", + "opCodeName": "PATH_ADD", "category": "Canvas Operations", "description": "Append segments to an existing dynamic path", "addedVersion": 6, @@ -3982,6 +4032,7 @@ { "id": 161, "name": "ParticlesCreate", + "opCodeName": "PARTICLE_DEFINE", "category": "Animation & Particles Operations", "description": "Creates a particle system with count, particle state variables, and emitter configuration", "addedVersion": 6, @@ -4015,6 +4066,7 @@ { "id": 163, "name": "ParticlesLoop", + "opCodeName": "PARTICLE_LOOP", "category": "Animation & Particles Operations", "description": "Evolves and updates particle positions and velocities across iterations", "addedVersion": 6, @@ -4054,6 +4106,7 @@ { "id": 164, "name": "ImpulseOperation", + "opCodeName": "IMPULSE_START", "category": "Animation & Particles Operations", "description": "Execute a list of actions once, and a process block for a fixed duration", "addedVersion": 6, @@ -4092,6 +4145,7 @@ { "id": 166, "name": "FloatFunctionCall", + "opCodeName": "FUNCTION_CALL", "category": "Data Operations", "description": "Invokes a defined float function with evaluated float argument expressions", "addedVersion": 6, @@ -4120,6 +4174,7 @@ { "id": 167, "name": "BitmapFontData", + "opCodeName": "DATA_BITMAP_FONT", "category": "Text Operations", "description": "Embeds font glyph layout, character metrics, and glyph page mappings for bitmap font rendering", "addedVersion": 6, @@ -4171,6 +4226,7 @@ { "id": 168, "name": "FloatFunctionDefine", + "opCodeName": "FUNCTION_DEFINE", "category": "Data Operations", "description": "Defines a parameterized float function expression", "addedVersion": 6, @@ -4201,6 +4257,7 @@ { "id": 169, "name": "SoundData", + "opCodeName": "DATA_SOUND", "category": "Data Operations", "description": "Embeds inline raw PCM sound data in SC format", "addedVersion": 7, @@ -4228,6 +4285,7 @@ { "id": 170, "name": "TextAttribute", + "opCodeName": "ATTRIBUTE_TEXT", "category": "Text Operations", "description": "Extract text-related properties (width, length, etc.)", "addedVersion": 6, @@ -4293,6 +4351,7 @@ { "id": 171, "name": "ImageAttribute", + "opCodeName": "ATTRIBUTE_IMAGE", "category": "Logic & Expressions Operations", "description": "Extract image-related properties (width, height)", "addedVersion": 6, @@ -4327,6 +4386,7 @@ { "id": 172, "name": "TimeAttribute", + "opCodeName": "ATTRIBUTE_TIME", "category": "Logic & Expressions Operations", "description": "Extract time-related information (seconds, hours, etc.)", "addedVersion": 6, @@ -4376,6 +4436,7 @@ { "id": 174, "name": "DrawContentOperation", + "opCodeName": "MODIFIER_DRAW_CONTENT", "category": "Modifier Operations", "description": "A modifier that triggers drawing of the component's content", "addedVersion": 6, @@ -4427,6 +4488,7 @@ { "id": 176, "name": "FitBoxLayout", + "opCodeName": "LAYOUT_FIT_BOX", "category": "Layout Managers", "description": "FitBox layout implementation. Only displays the first child component that fits in the available space.", "addedVersion": 6, @@ -4557,6 +4619,7 @@ { "id": 180, "name": "ColorAttribute", + "opCodeName": "ATTRIBUTE_COLOR", "category": "Paint & Styles Operations", "description": "Extract components (Hue, RGB, Alpha) from a color", "addedVersion": 6, @@ -4930,6 +4993,7 @@ { "id": 189, "name": "FontData", + "opCodeName": "DATA_FONT", "category": "Data Operations", "description": "Embed raw font data in the document", "addedVersion": 7, @@ -5098,6 +5162,7 @@ { "id": 194, "name": "ParticlesCompare", + "opCodeName": "PARTICLE_COMPARE", "category": "Animation & Particles Operations", "description": "Compares particle variables to evaluate conditional state transitions or recycling", "addedVersion": 7, @@ -5204,6 +5269,7 @@ { "id": 197, "name": "DataDynamicListFloat", + "opCodeName": "DYNAMIC_FLOAT_LIST", "category": "Data Operations", "description": "A dynamic list of floats", "addedVersion": 7, @@ -5307,6 +5373,7 @@ { "id": 200, "name": "RootLayout", + "opCodeName": "LAYOUT_ROOT", "category": "Layout Operations", "description": "Root element for a document. Other components / layout managers are children in the component tree starting from this Root component.", "addedVersion": 6, @@ -5322,7 +5389,8 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "RootLayoutComponent" }, { "id": 201, @@ -5342,11 +5410,13 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "LayoutComponentContent" }, { "id": 202, "name": "BoxLayout", + "opCodeName": "LAYOUT_BOX", "category": "Layout Operations", "description": "Box container layout component", "addedVersion": 6, @@ -5397,6 +5467,7 @@ { "id": 203, "name": "RowLayout", + "opCodeName": "LAYOUT_ROW", "category": "Layout Operations", "description": "Row container layout component", "addedVersion": 6, @@ -5455,6 +5526,7 @@ { "id": 204, "name": "ColumnLayout", + "opCodeName": "LAYOUT_COLUMN", "category": "Layout Operations", "description": "Column container layout component", "addedVersion": 6, @@ -5513,6 +5585,7 @@ { "id": 205, "name": "CanvasLayout", + "opCodeName": "LAYOUT_CANVAS", "category": "Layout Managers", "description": "Canvas implementation. Encapsulates drawing operations.", "addedVersion": 6, @@ -5581,6 +5654,7 @@ { "id": 207, "name": "CanvasContent", + "opCodeName": "LAYOUT_CANVAS_CONTENT", "category": "Layout Operations", "description": "Container for canvas drawing commands inside a CanvasLayout component", "addedVersion": 6, @@ -5606,6 +5680,7 @@ { "id": 208, "name": "TextLayout", + "opCodeName": "LAYOUT_TEXT", "category": "Text Operations", "description": "Text layout implementation", "addedVersion": 6, @@ -5645,7 +5720,8 @@ "role": "idRef", "idKind": "color" } - ] + ], + "resolvedAfter": "textAlign" }, { "name": "fontSize", @@ -5655,7 +5731,11 @@ { "name": "fontStyle", "type": "int", - "description": "The font style (0=normal, 1=italic)" + "description": "The font style (0=normal, 1=italic)", + "enum": { + "FONT_STYLE_NORMAL": 0, + "FONT_STYLE_ITALIC": 1 + } }, { "name": "fontWeight", @@ -5741,7 +5821,8 @@ "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "HostActionOperation" }, { "id": 210, @@ -5778,11 +5859,13 @@ "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "HostNamedActionOperation" }, { "id": 211, "name": "ComponentVisibilityOperation", + "opCodeName": "MODIFIER_VISIBILITY", "category": "Modifier Operations", "description": "Set component visibility from a provided integer variable", "addedVersion": 6, @@ -5801,6 +5884,7 @@ { "id": 212, "name": "ValueIntegerChangeActionOperation", + "opCodeName": "VALUE_INTEGER_CHANGE_ACTION", "category": "Actions & Events Operations", "description": "Action that sets a new value for an integer variable", "addedVersion": 6, @@ -5824,6 +5908,7 @@ { "id": 213, "name": "ValueStringChangeActionOperation", + "opCodeName": "VALUE_STRING_CHANGE_ACTION", "category": "Actions & Events Operations", "description": "Action that sets a new value for a string variable", "addedVersion": 6, @@ -5859,6 +5944,7 @@ { "id": 215, "name": "Loop", + "opCodeName": "LOOP_START", "category": "Logic & Expressions Operations", "description": "Execute a list of operations in a loop", "addedVersion": 6, @@ -5889,11 +5975,13 @@ "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "LoopOperation" }, { "id": 216, "name": "HostActionMetadata", + "opCodeName": "HOST_METADATA_ACTION", "category": "Layout Operations", "description": "Host action + metadata. This operation represents a host action that can also provides some metadata", "addedVersion": 6, @@ -5912,11 +6000,13 @@ "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "HostActionMetadataOperation" }, { "id": 217, "name": "StateLayout", + "opCodeName": "LAYOUT_STATE", "category": "Layout Operations", "description": "A layout that switches between child layouts based on an index", "addedVersion": 6, @@ -5957,6 +6047,7 @@ { "id": 218, "name": "ValueIntegerExpressionChangeActionOperation", + "opCodeName": "VALUE_INTEGER_EXPRESSION_CHANGE_ACTION", "category": "Actions & Events Operations", "description": "Action that updates an integer variable via a dynamic expression", "addedVersion": 6, @@ -5990,6 +6081,7 @@ { "id": 219, "name": "TouchModifier", + "opCodeName": "MODIFIER_TOUCH_DOWN", "category": "Modifier Operations", "description": "Touch down modifier. This operation contains a list of action operations executed on touch down", "addedVersion": 6, @@ -5998,11 +6090,13 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "TouchDownModifierOperation" }, { "id": 220, "name": "TouchUpModifier", + "opCodeName": "MODIFIER_TOUCH_UP", "category": "Modifier Operations", "description": "Touch up modifier. This operation contains a list of action operations executed on touch up", "addedVersion": 6, @@ -6011,11 +6105,13 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "TouchUpModifierOperation" }, { "id": 221, "name": "OffsetModifierOperation", + "opCodeName": "MODIFIER_OFFSET", "category": "Modifier Operations", "description": "Shift the component's position", "addedVersion": 6, @@ -6039,6 +6135,7 @@ { "id": 222, "name": "ValueFloatChangeActionOperation", + "opCodeName": "VALUE_FLOAT_CHANGE_ACTION", "category": "Actions & Events Operations", "description": "Action that sets a new value for a float variable", "addedVersion": 6, @@ -6062,6 +6159,7 @@ { "id": 223, "name": "ZIndexModifierOperation", + "opCodeName": "MODIFIER_ZINDEX", "category": "Modifier Operations", "description": "Define the Z-Index of a component", "addedVersion": 6, @@ -6080,6 +6178,7 @@ { "id": 224, "name": "GraphicsLayerModifierOperation", + "opCodeName": "MODIFIER_GRAPHICS_LAYER", "category": "Modifier Operations", "description": "Define transformations (scale, rotation, alpha) for a component", "addedVersion": 6, @@ -6100,6 +6199,7 @@ { "id": 225, "name": "TouchCancelModifier", + "opCodeName": "MODIFIER_TOUCH_CANCEL", "category": "Modifier Operations", "description": "Touch cancel modifier. This operation contains a list of action operations executed on touch cancel", "addedVersion": 6, @@ -6108,11 +6208,13 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "TouchCancelModifierOperation" }, { "id": 226, "name": "ScrollModifierOperation", + "opCodeName": "MODIFIER_SCROLL", "category": "Modifier Operations", "description": "Define a scrolling behavior for a component", "addedVersion": 6, @@ -6148,6 +6250,7 @@ { "id": 227, "name": "ValueFloatExpressionChangeActionOperation", + "opCodeName": "VALUE_FLOAT_EXPRESSION_CHANGE_ACTION", "category": "Actions & Events Operations", "description": "Action that updates a float variable via a dynamic expression", "addedVersion": 6, @@ -6171,6 +6274,7 @@ { "id": 228, "name": "MarqueeModifierOperation", + "opCodeName": "MODIFIER_MARQUEE", "category": "Modifier Operations", "description": "Define a scrolling marquee effect for a component", "addedVersion": 6, @@ -6214,17 +6318,20 @@ { "id": 229, "name": "RippleModifier", + "opCodeName": "MODIFIER_RIPPLE", "category": "Modifier Operations", "description": "Ripple modifier. This modifier will do a ripple animation on touch down", "addedVersion": 6, "profiles": [ "baseline" ], - "restrictToLibraryGroup": true + "restrictToLibraryGroup": true, + "javaClass": "RippleModifierOperation" }, { "id": 230, "name": "CollapsibleRow", + "opCodeName": "LAYOUT_COLLAPSIBLE_ROW", "category": "Layout Managers", "description": "A row layout that can hide children if space is insufficient", "addedVersion": 6, @@ -6273,11 +6380,13 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "CollapsibleRowLayout" }, { "id": 231, "name": "WidthInModifierOperation", + "opCodeName": "MODIFIER_WIDTH_IN", "category": "Modifier Operations", "description": "Add additional constraints to the width", "addedVersion": 6, @@ -6301,6 +6410,7 @@ { "id": 232, "name": "HeightInModifierOperation", + "opCodeName": "MODIFIER_HEIGHT_IN", "category": "Modifier Operations", "description": "Add additional constraints to the height", "addedVersion": 6, @@ -6324,6 +6434,7 @@ { "id": 233, "name": "CollapsibleColumn", + "opCodeName": "LAYOUT_COLLAPSIBLE_COLUMN", "category": "Layout Managers", "description": "A column layout that can hide children if space is insufficient", "addedVersion": 6, @@ -6372,11 +6483,13 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "CollapsibleColumnLayout" }, { "id": 234, "name": "ImageLayout", + "opCodeName": "LAYOUT_IMAGE", "category": "Layout Managers", "description": "Image layout implementation", "addedVersion": 6, @@ -6445,6 +6558,7 @@ { "id": 235, "name": "CollapsiblePriorityModifierOperation", + "opCodeName": "MODIFIER_COLLAPSIBLE_PRIORITY", "category": "Modifier Operations", "description": "Add additional priority to children of collapsible layouts", "addedVersion": 6, @@ -6476,11 +6590,13 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "RunActionOperation" }, { "id": 237, "name": "AlignByModifierOperation", + "opCodeName": "MODIFIER_ALIGN_BY", "category": "Modifier Operations", "description": "Align a component based on a specific baseline or anchor", "addedVersion": 7, @@ -6532,7 +6648,8 @@ ], "restrictToLibraryGroup": true, "isContainer": true, - "closedBy": "ContainerEnd" + "closedBy": "ContainerEnd", + "javaClass": "LayoutComputeOperation" }, { "id": 239, @@ -6721,6 +6838,7 @@ { "id": 240, "name": "FlowLayout", + "opCodeName": "LAYOUT_FLOW", "category": "Layout Managers", "description": "Flow layout implementation. Positions components one after the other horizontally and wraps to the next line if space is exhausted.", "addedVersion": 7, @@ -7072,6 +7190,7 @@ { "id": 243, "name": "DimensionConstraintsModifierOperation", + "opCodeName": "MODIFIER_DIMENSION_CONSTRAINTS", "category": "Modifier Operations", "description": "Add additional constraints to the dimensions", "addedVersion": 7, @@ -7108,6 +7227,7 @@ { "id": 244, "name": "PatternForEach", + "opCodeName": "MACRO_FOR_EACH", "category": "Layout Operations", "description": "Iterates over a collection parameter and expands child templates for each item", "addedVersion": 7, @@ -7155,6 +7275,7 @@ { "id": 246, "name": "PatternDefine", + "opCodeName": "MACRO_DEFINE", "category": "Layout Operations", "description": "Defines a reusable template pattern with parameter IDs", "addedVersion": 7, @@ -7191,6 +7312,7 @@ { "id": 247, "name": "PatternInflation", + "opCodeName": "MACRO_CALL", "category": "Layout Operations", "description": "Inflates and materializes a pattern template by ID with argument IDs", "addedVersion": 7, @@ -7224,6 +7346,7 @@ { "id": 248, "name": "PatternArgument", + "opCodeName": "MACRO_ARGUMENT", "category": "Layout Operations", "description": "Placeholder for an operation block argument in a pattern definition", "addedVersion": 7, @@ -7244,6 +7367,7 @@ { "id": 249, "name": "PatternBlock", + "opCodeName": "MACRO_BLOCK", "category": "Layout Operations", "description": "Encapsulates an operation block argument for pattern inflation", "addedVersion": 7, @@ -7266,6 +7390,7 @@ { "id": 250, "name": "CoreSemantics", + "opCodeName": "ACCESSIBILITY_SEMANTICS", "category": "Accessibility Operations", "description": "Define accessibility semantics for a component", "addedVersion": 6, @@ -7701,7 +7826,13 @@ "name": "dataType", "range": "10..15", "signed": true, - "description": "0=int, 1=float, 2=long, 3=string; any other value reads 0 bytes" + "description": "0=int, 1=float, 2=long, 3=string; any other value reads 0 bytes", + "enum": { + "DATA_TYPE_INT": 0, + "DATA_TYPE_FLOAT": 1, + "DATA_TYPE_LONG": 2, + "DATA_TYPE_STRING": 3 + } } ], "unpackBits": false @@ -8534,7 +8665,7 @@ }, { "id": 56, - "name": "STORE_RO", + "name": "STORE_R0", "symbol": "store_r0", "arity": 1, "addedVersion": 7, @@ -9303,6 +9434,20 @@ "compression": { "COMPRESSION_NONE": 0, "COMPRESSION_DEFLATE": 1 + }, + "dataTypes": { + "DATA_TYPE_INT": 0, + "DATA_TYPE_FLOAT": 1, + "DATA_TYPE_LONG": 2, + "DATA_TYPE_STRING": 3 + }, + "version": { + "MAGIC_NUMBER": 76283904, + "DEFAULT_MAJOR_VERSION": 1, + "DEFAULT_MINOR_VERSION": 1, + "DEFAULT_PATCH_VERSION": 0, + "DEFAULT_DIMENSION": 256, + "COMPRESSED_STREAM_MARKER": 119 } }, "idEncoding": { @@ -9319,7 +9464,9 @@ "ptrDereference": 1073741824, "valueMask": 65535, "macroLocalStartId": 16384, - "macroLocalEndId": 20479 + "macroLocalEndId": 20479, + "nanExponent": 2139095040, + "noId": -1 }, "animationSpec": { "easings": [ @@ -9527,5 +9674,200 @@ ] } ] - } + }, + "visibilityConstants": { + "GONE": 0, + "VISIBLE": 1, + "INVISIBLE": 2, + "OVERRIDE_GONE": 16, + "OVERRIDE_VISIBLE": 32, + "OVERRIDE_INVISIBLE": 64, + "CLEAR_OVERRIDE": 128 + }, + "reservedOpcodes": [ + { + "id": 95, + "name": "PropertyBundleModifierOperation", + "opCodeName": "MODIFIER_PROPERTY_BUNDLE", + "profiles": [ + "androidx", + "experimental" + ], + "description": "Property bundle modifier (experimental AndroidX profile)" + }, + { + "id": 96, + "name": "PropertyBundleLookupOperation", + "opCodeName": "PROPERTY_BUNDLE_LOOKUP", + "profiles": [ + "androidx", + "experimental" + ], + "description": "Property bundle lookup operation (experimental AndroidX profile)" + }, + { + "id": 110, + "name": "DefineMesh3D", + "opCodeName": "DEFINE_MESH_3D", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D mesh definition (experimental 3D profile)" + }, + { + "id": 111, + "name": "SetCamera3D", + "opCodeName": "SET_CAMERA_3D", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D camera state (experimental 3D profile)" + }, + { + "id": 112, + "name": "Matrix3DOp", + "opCodeName": "MATRIX_3D_OP", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D matrix transform operation (experimental 3D profile)" + }, + { + "id": 113, + "name": "DrawMesh3D", + "opCodeName": "DRAW_MESH_3D", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "Draw 3D mesh (experimental 3D profile)" + }, + { + "id": 114, + "name": "Paint3DState", + "opCodeName": "PAINT_3D_STATE", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D paint state (clear-depth / material / depth-bias)" + }, + { + "id": 115, + "name": "SetLights3D", + "opCodeName": "SET_LIGHTS_3D", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D light set configuration (experimental 3D profile)" + }, + { + "id": 116, + "name": "VectorExpression", + "opCodeName": "VECTOR_EXPRESSION", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "vec2/3/4-valued expression scattering to IDs" + }, + { + "id": 117, + "name": "MeshExpression3D", + "opCodeName": "MESH_EXPRESSION_3D", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D mesh expression (experimental 3D profile)" + }, + { + "id": 118, + "name": "SetTexture3D", + "opCodeName": "SET_TEXTURE_3D", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D texture binding (experimental 3D profile)" + }, + { + "id": 119, + "name": "CompressedStreamMarker", + "opCodeName": "COMPRESSED_STREAM_MARKER", + "profiles": [ + "reserved" + ], + "description": "Reserved marker byte (0x77) starting a compressed document's operations (Header.COMPRESSED_STREAM_MARKER)" + }, + { + "id": 120, + "name": "MeshPrimitive3D", + "opCodeName": "MESH_PRIMITIVE_3D", + "profiles": [ + "androidx", + "widgets", + "experimental" + ], + "description": "3D mesh primitive (experimental 3D profile)" + }, + { + "id": 251, + "name": "ExtensionRangeReserved4", + "opCodeName": "EXTENSION_RANGE_RESERVED_4", + "profiles": [ + "reserved" + ], + "description": "Reserved for extended opcode range" + }, + { + "id": 252, + "name": "ExtensionRangeReserved3", + "opCodeName": "EXTENSION_RANGE_RESERVED_3", + "profiles": [ + "reserved" + ], + "description": "Reserved for extended opcode range" + }, + { + "id": 253, + "name": "ExtensionRangeReserved2", + "opCodeName": "EXTENSION_RANGE_RESERVED_2", + "profiles": [ + "reserved" + ], + "description": "Reserved for extended opcode range" + }, + { + "id": 254, + "name": "ExtensionRangeReserved1", + "opCodeName": "EXTENSION_RANGE_RESERVED_1", + "profiles": [ + "reserved" + ], + "description": "Reserved for extended opcode range" + }, + { + "id": 255, + "name": "ExtendedOpcode", + "opCodeName": "EXTENDED_OPCODE", + "profiles": [ + "reserved" + ], + "description": "Escape opcode for extended opcodes" + } + ] }
diff --git a/compose/remote/remote-generator/src/main/resources/schema/schema.json b/compose/remote/remote-generator/src/main/resources/schema/schema.json index b4c37cc..bd9b7a3 100644 --- a/compose/remote/remote-generator/src/main/resources/schema/schema.json +++ b/compose/remote/remote-generator/src/main/resources/schema/schema.json
@@ -153,6 +153,24 @@ "additionalProperties": { "type": "integer" } } }, + "visibilityConstants": { + "type": "object", + "additionalProperties": { "type": "integer" } + }, + "reservedOpcodes": { + "type": "array", + "items": { + "type": "object", + "required": ["id", "name", "opCodeName"], + "properties": { + "id": { "type": "integer", "minimum": 0, "maximum": 255 }, + "name": { "type": "string" }, + "opCodeName": { "type": "string" }, + "profiles": { "type": "array", "items": { "type": "string" } }, + "description": { "type": "string" } + } + } + }, "idEncoding": { "type": "object", "required": [ @@ -173,7 +191,9 @@ ], "properties": { "nanPrefix": { "type": "integer" }, + "nanExponent": { "type": "integer" }, "payloadMask": { "type": "integer" }, + "noId": { "type": "integer" }, "startId": { "type": "integer" }, "regionMask": { "type": "integer" }, "regionSubIdMask": { "type": "integer" }, @@ -315,6 +335,7 @@ "items": { "type": "string" } }, "opCodeName": { "type": "string" }, + "javaClass": { "type": "string" }, "restrictToLibraryGroup": { "type": "boolean" }, "encoding": { "type": "string" }, "conditionalSkip": { @@ -430,6 +451,7 @@ "omitIf": {}, "role": { "type": "string" }, "idKind": { "type": "string" }, + "resolvedAfter": { "type": "string" }, "conditionalTypes": { "type": "array", "items": {
diff --git a/compose/remote/remote-generator/src/test/java/androidx/compose/remote/generator/RemoteComposeGeneratorTest.kt b/compose/remote/remote-generator/src/test/java/androidx/compose/remote/generator/RemoteComposeGeneratorTest.kt index b590e7a..11340c2 100644 --- a/compose/remote/remote-generator/src/test/java/androidx/compose/remote/generator/RemoteComposeGeneratorTest.kt +++ b/compose/remote/remote-generator/src/test/java/androidx/compose/remote/generator/RemoteComposeGeneratorTest.kt
@@ -834,20 +834,25 @@ val generator = SwiftGenerator(schema) val code = generator.generate() - assertTrue(code.contains("public enum OpCode: UInt8, CaseIterable {")) + assertTrue( + code.contains( + "public enum OpCode: UInt8, CaseIterable, Equatable, Hashable, Sendable {" + ) + ) assertTrue(code.contains("case drawCircle = 46")) assertTrue(code.contains("case boxLayout = 202")) - assertTrue(code.contains("public struct DrawCircle: RemoteOperation, Equatable {")) - assertTrue(code.contains("public struct WireBuffer {")) - assertTrue(code.contains("public struct RemoteDocument {")) + assertTrue(code.contains("public struct DrawCircle: Equatable, Hashable, Sendable {")) + assertTrue(code.contains("public enum WireOperation: Equatable, Hashable, Sendable {")) + assertTrue(code.contains("public struct WireBuffer: Equatable, Hashable, Sendable {")) + assertTrue(code.contains("public struct WireDocument: Equatable, Hashable, Sendable {")) assertTrue(code.contains("buffer.writeFloat(radius)")) assertTrue(code.contains("try buffer.readFloat()")) - assertTrue(code.contains("guard numProps >= 0 && numProps <= MAX_HEADER_PROPERTIES else {")) - assertTrue(code.contains("let key = tag & 0x3F")) + assertTrue(code.contains("guard numProps >= 0 && numProps <= maxHeaderProperties else {")) + assertTrue(code.contains("let key = Int32(rawTag) & 0x3F")) assertTrue(code.contains("guard _argsCount >= 0 else {")) - assertTrue(code.contains("public mutating func readShort() throws -> Int16")) + assertTrue(code.contains("public mutating func readShort() throws(WireError) -> Int16")) assertTrue(code.contains("public mutating func writeShort(_ value: Int16)")) - assertTrue(code.contains("Unknown opcode:")) + assertTrue(code.contains("throw WireError.unknownOpCode(opByte)")) } @Test @@ -2695,17 +2700,31 @@ "Swift must not use overflowing index + len <= data.count", swiftCode.contains("index + len <= data.count"), ) - assertTrue(swiftCode.contains("data.startIndex == 0 ? data : Data(data)")) + assertFalse("Swift must not import Foundation", swiftCode.contains("import Foundation")) + assertFalse("Swift must not throw NSError", swiftCode.contains("NSError")) + assertFalse( + "Swift must not emit unqualified min() or max() that fields can shadow", + Regex("""(?<!Swift\.)\b(?:min|max)\(""").containsMatchIn(swiftCode), + ) + assertTrue(swiftCode.contains("public private(set) var data: [UInt8]")) assertTrue(swiftCode.contains("public private(set) var index: Int = 0")) - assertTrue(swiftCode.contains("MAX_HEADER_PROPERTIES")) - assertTrue(swiftCode.contains("MAX_OPERATION_COUNT")) - assertTrue(swiftCode.contains("Unexpected Header opcode inside document body")) - assertTrue(swiftCode.contains("Compressed RemoteCompose documents are not supported")) - assertTrue(swiftCode.contains("Invalid header magic number")) + assertTrue(swiftCode.contains("maxHeaderProperties")) + assertTrue(swiftCode.contains("maxOperationCount")) + assertTrue(swiftCode.contains("throw WireError.unexpectedHeaderInBody")) + assertTrue(swiftCode.contains("throw WireError.compressedDocumentUnsupported")) + assertTrue(swiftCode.contains("throw WireError.invalidHeaderMagic(rawMajor)")) assertTrue(swiftCode.contains("guard _glyphsCount <= buffer.remaining / 20 else")) assertTrue(swiftCode.contains("guard sparseCount <= buffer.remaining / 2 else")) - assertTrue(swiftCode.contains("Invalid enum value for mode")) - assertTrue(swiftCode.contains("Invalid enum value for attributeType")) + assertTrue( + swiftCode.contains( + "throw WireError.invalidFieldValue(owner: \"ColorExpression\", field: \"mode\"" + ) + ) + assertTrue( + swiftCode.contains( + "throw WireError.invalidFieldValue(owner: \"GraphicsLayerAttribute\", field: \"attributeType\"" + ) + ) assertTrue(swiftCode.contains("buffer.readUTF8(maxLength: 4000)")) assertTrue(swiftCode.contains("buffer.readBuffer(maxLength: 800000)")) assertTrue(swiftCode.contains("(raw_versionAndNumGlyphs >> 16)")) @@ -3618,18 +3637,18 @@ // Verify SwiftGenerator val swiftCode = SwiftGenerator(synSchema).generate() assertTrue( - "Swift protocol write must throw", - swiftCode.contains("func write(to buffer: inout WireBuffer) throws"), + "Swift WireOperation write must use typed throws(WireError)", + swiftCode.contains("public func write(to buffer: inout WireBuffer) throws(WireError)"), ) assertTrue( - "Swift save must throw and forward try op.write", - swiftCode.contains("public func save() throws -> Data") && + "Swift WireDocument.save must return [UInt8] with typed throws and forward try op.write", + swiftCode.contains("public func save() throws(WireError) -> [UInt8]") && swiftCode.contains("try op.write(to: &buffer)"), ) assertTrue( - "Swift must throw NSError instead of preconditionFailure on missing required field", + "Swift must throw WireError.missingRequiredField instead of preconditionFailure", swiftCode.contains( - "throw NSError(domain: \"SyntheticTestOp\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Missing required field optPacked\"])" + "throw WireError.missingRequiredField(owner: \"SyntheticTestOp\", field: \"optPacked\")" ) && !swiftCode.contains("preconditionFailure"), ) assertTrue( @@ -4006,12 +4025,14 @@ val swiftSrc = SwiftGenerator(schema).generate() assertTrue( swiftSrc.contains( - "throw NSError(domain: \"HeaderProperty\", code: 3, userInfo: [NSLocalizedDescriptionKey: \"Missing required field intValue\"])" + "throw WireError.missingRequiredField(owner: \"HeaderProperty\", field: \"intValue\")" ) ) assertTrue( "Swift modern Header must default omitted width/height to 256", - swiftSrc.contains("doc.width = 256") && swiftSrc.contains("doc.height = 256"), + swiftSrc.contains("public static let defaultDimension: Int32 = 256") && + swiftSrc.contains("doc.width = defaultDimension") && + swiftSrc.contains("doc.height = defaultDimension"), ) val pySrc = PythonGenerator(schema).generate() assertTrue(pySrc.contains("raise ValueError(\"Missing required field intValue\")")) @@ -4531,7 +4552,7 @@ swiftCode .substringAfter("public struct ImageAttribute:") .substringBefore("public struct TimeAttribute:") - assertFalse(swiftImageSection.contains("<= 32")) + assertFalse(swiftImageSection.contains("<= 32 else")) // Skip conditional framing & player load in Kotlin, TS, Swift assertTrue(ktAst.contains("internal fun shouldSkip(")) @@ -5029,31 +5050,65 @@ val swiftCode = SwiftGenerator(schema).generate() for (marker in listOf( + "public enum OpCode: UInt8, CaseIterable, Equatable, Hashable, Sendable", + "public enum WireError: Error, Equatable, Hashable, Sendable", + "public struct WireBuffer: Equatable, Hashable, Sendable", + "public enum WireOperation: Equatable, Hashable, Sendable", + "public struct WireDocument: Equatable, Hashable, Sendable", + "public enum HeaderPropertyValue: Equatable, Hashable, Sendable", + "public struct WireHeaderProperty: Equatable, Hashable, Sendable", + "private func wireFloatEquals(_ lhs: Float, _ rhs: Float) -> Bool", + "public static func == (lhs: HeaderPropertyValue, rhs: HeaderPropertyValue) -> Bool", + "public static func == (lhs: FloatExpression, rhs: FloatExpression) -> Bool", + "let itemLen = Int(UInt16(bitPattern: try buffer.readShort()))", + "let dataType = Int32(rawTag) >> 10", + "case unknown(dataType: Int32, payload: [UInt8])", + "let payload = try buffer.readBytes(count: itemLen)", + "buffer.writeBytes(payload)", + "outProps.lastIndex(where:", + "guard majorVersion >= 0 && majorVersion <= 0xFFFF else", + "if capabilities >= 0 && capabilities <= Int64(UInt32.max)", "public enum IdEncoding", + "public static let nanExponent: Int32 = 2139095040", + "public static let noId: Int32 = -1", "public enum HeaderConstants", "public enum PaintCommandTags", "public enum PaintConstants", "public enum PathCommandTags", "public enum RemoteContextIds", "public enum AnimationEasing", - "public struct FloatAnimationSpec: Equatable", + "public struct FloatAnimationSpec: Equatable, Hashable, Sendable", "public static func == (lhs: FloatAnimationSpec, rhs: FloatAnimationSpec) -> Bool", - "public indirect enum PathEffect: Equatable", - "public enum PathCommand: Equatable", + "public func hash(into hasher: inout Hasher)", + "public indirect enum PathEffect: Equatable, Hashable, Sendable", + "public static func == (lhs: PathEffect, rhs: PathEffect) -> Bool", + "public enum PathCommand: Equatable, Hashable, Sendable", + "public static func == (lhs: PathCommand, rhs: PathCommand) -> Bool", "public var isSpringAnimation: Bool", - "public func unpackAnimationSpec() throws -> FloatAnimationSpec", - "public func encode() throws -> [Float]", + "public func unpackAnimationSpec() throws(WireError) -> FloatAnimationSpec", + "public func encode() throws(WireError) -> [Float]", "public var uncompressedByteSize: Int64", "multipliedReportingOverflow", "public func decodePathCommands() -> [PathCommand]", "public var alphaPayload: Int32", + "reserveCapacity(Swift.min(", + "public static let roundedRectangle: Int32 = 2", )) { assertTrue("Swift output missing: $marker", swiftCode.contains(marker)) } assertFalse( - "Swift output must not reference undefined WireError", - swiftCode.contains("WireError"), + "Swift output must not define RemoteOperation protocol", + swiftCode.contains("protocol RemoteOperation"), ) + assertFalse( + "Swift output must not define RemoteDocument", + swiftCode.contains("struct RemoteDocument"), + ) + assertFalse( + "Swift output must not import Foundation", + swiftCode.contains("import Foundation"), + ) + assertFalse("Swift output must not throw NSError", swiftCode.contains("NSError")) // Standalone Rust generateStruct output must not reference module-level protocol helpers val standaloneFloatExpr = @@ -5132,10 +5187,15 @@ int32_t nanBits = IdEncoding::asNanBits(42); assert(IdEncoding::isNanBits(nanBits)); assert(IdEncoding::idFromNanBits(nanBits) == 42); + assert(IdEncoding::isNanBits(0x7F800005)); + assert(IdEncoding::idFromNanBits(0x7F800005) == 5); + assert(!IdEncoding::isNanBits(0x7F800000)); + assert(!IdEncoding::isNanBits(0x7FC00000)); + assert(IdEncoding::idFromNanBits(0x7FC00000) == IdEncoding::NO_ID); assert(!IdEncoding::isNanBits(static_cast<int32_t>(0xFF800000u))); - assert(IdEncoding::idFromNanBits(static_cast<int32_t>(0xFF800000u)) == -1); + assert(IdEncoding::idFromNanBits(static_cast<int32_t>(0xFF800000u)) == IdEncoding::NO_ID); assert(!IdEncoding::isNanBits(static_cast<int32_t>(0xFFC00000u))); - assert(IdEncoding::idFromNanBits(static_cast<int32_t>(0xFFC00000u)) == -1); + assert(IdEncoding::idFromNanBits(static_cast<int32_t>(0xFFC00000u)) == IdEncoding::NO_ID); assert(!IdEncoding::isDereferenced(42)); assert(IdEncoding::directId(42) == 42); assert(IdEncoding::pointerId(IdEncoding::PTR_DEREFERENCE | 7) == 7); @@ -5260,10 +5320,15 @@ let nan_bits = id_encoding::as_nan_bits(42); assert!(id_encoding::is_nan_bits(nan_bits)); assert_eq!(id_encoding::id_from_nan_bits(nan_bits), 42); + assert!(id_encoding::is_nan_bits(0x7F800005)); + assert_eq!(id_encoding::id_from_nan_bits(0x7F800005), 5); + assert!(!id_encoding::is_nan_bits(0x7F800000)); + assert!(!id_encoding::is_nan_bits(0x7FC00000)); + assert_eq!(id_encoding::id_from_nan_bits(0x7FC00000), id_encoding::NO_ID); assert!(!id_encoding::is_nan_bits(0xFF800000u32 as i32)); - assert_eq!(id_encoding::id_from_nan_bits(0xFF800000u32 as i32), -1); + assert_eq!(id_encoding::id_from_nan_bits(0xFF800000u32 as i32), id_encoding::NO_ID); assert!(!id_encoding::is_nan_bits(0xFFC00000u32 as i32)); - assert_eq!(id_encoding::id_from_nan_bits(0xFFC00000u32 as i32), -1); + assert_eq!(id_encoding::id_from_nan_bits(0xFFC00000u32 as i32), id_encoding::NO_ID); assert_eq!(id_encoding::direct_id(42), Some(42)); assert_eq!(id_encoding::pointer_id(id_encoding::PTR_DEREFERENCE | 7), Some(7)); assert!(remote_context_ids::is_time(remote_context_ids::ID_CONTINUOUS_SEC)); @@ -5374,10 +5439,15 @@ nan_bits = IdEncoding.as_nan_bits(42) assert IdEncoding.is_nan_bits(nan_bits) assert IdEncoding.id_from_nan_bits(nan_bits) == 42 + assert IdEncoding.is_nan_bits(0x7F800005) + assert IdEncoding.id_from_nan_bits(0x7F800005) == 5 + assert not IdEncoding.is_nan_bits(0x7F800000) + assert not IdEncoding.is_nan_bits(0x7FC00000) + assert IdEncoding.id_from_nan_bits(0x7FC00000) == IdEncoding.NO_ID assert not IdEncoding.is_nan_bits(-0x800000) - assert IdEncoding.id_from_nan_bits(-0x800000) == -1 + assert IdEncoding.id_from_nan_bits(-0x800000) == IdEncoding.NO_ID assert not IdEncoding.is_nan_bits(-0x400000) - assert IdEncoding.id_from_nan_bits(-0x400000) == -1 + assert IdEncoding.id_from_nan_bits(-0x400000) == IdEncoding.NO_ID assert IdEncoding.direct_id(42) == 42 assert IdEncoding.pointer_id(IdEncoding.PTR_DEREFERENCE | 7) == 7 assert RemoteContextIds.is_time(RemoteContextIds.ID_CONTINUOUS_SEC) @@ -5483,10 +5553,15 @@ const nanBits = IdEncoding.asNanBits(42); assert.equal(IdEncoding.isNanBits(nanBits), true); assert.equal(IdEncoding.idFromNanBits(nanBits), 42); + assert.equal(IdEncoding.isNanBits(0x7F800005), true); + assert.equal(IdEncoding.idFromNanBits(0x7F800005), 5); + assert.equal(IdEncoding.isNanBits(0x7F800000), false); + assert.equal(IdEncoding.isNanBits(0x7FC00000), false); + assert.equal(IdEncoding.idFromNanBits(0x7FC00000), IdEncoding.NO_ID); assert.equal(IdEncoding.isNanBits(0xFF800000 | 0), false); - assert.equal(IdEncoding.idFromNanBits(0xFF800000 | 0), -1); + assert.equal(IdEncoding.idFromNanBits(0xFF800000 | 0), IdEncoding.NO_ID); assert.equal(IdEncoding.isNanBits(0xFFC00000 | 0), false); - assert.equal(IdEncoding.idFromNanBits(0xFFC00000 | 0), -1); + assert.equal(IdEncoding.idFromNanBits(0xFFC00000 | 0), IdEncoding.NO_ID); assert.equal(IdEncoding.directId(42), 42); assert.equal(IdEncoding.pointerId(IdEncoding.PTR_DEREFERENCE | 7), 7); assert.equal(RemoteContextIds.isTime(RemoteContextIds.ID_CONTINUOUS_SEC), true); @@ -5574,6 +5649,495 @@ } } + @Test + fun testSchemaEnrichmentsAndMetadataValidation() { + val schema = loadSchema() + + // 1. STORE_R0 renamed cleanly from STORE_RO + val rpnOps = checkNotNull(schema.rpnOperators) + assertEquals("STORE_R0", rpnOps.operatorsById[56]?.name) + assertNull(rpnOps.operatorsByName["STORE_RO"]) + + // 2. idEncoding includes nanExponent and noId + val enc = checkNotNull(schema.idEncoding) + assertEquals(0x7F800000, enc.nanExponent) + assertEquals(-1, enc.noId) + + // 3. headerConstants includes dataTypes and version groups + assertEquals(0, schema.headerConstants["dataTypes"]?.get("DATA_TYPE_INT")) + assertEquals(1, schema.headerConstants["dataTypes"]?.get("DATA_TYPE_FLOAT")) + assertEquals(2, schema.headerConstants["dataTypes"]?.get("DATA_TYPE_LONG")) + assertEquals(3, schema.headerConstants["dataTypes"]?.get("DATA_TYPE_STRING")) + assertEquals(0x048C0000, schema.headerConstants["version"]?.get("MAGIC_NUMBER")) + assertEquals(256, schema.headerConstants["version"]?.get("DEFAULT_DIMENSION")) + assertEquals(0x77, schema.headerConstants["version"]?.get("COMPRESSED_STREAM_MARKER")) + + // 4. HeaderProperty.tag.bits[dataType] enum + val hpTag = schema.structs["HeaderProperty"]!!.fields.first { it.name == "tag" } + val dtBit = hpTag.bits!!.first { it.name == "dataType" } + assertEquals( + mapOf( + "DATA_TYPE_INT" to 0, + "DATA_TYPE_FLOAT" to 1, + "DATA_TYPE_LONG" to 2, + "DATA_TYPE_STRING" to 3, + ), + dtBit.enumValues, + ) + + // 5. visibilityConstants match Component.Visibility + assertEquals( + mapOf( + "GONE" to 0, + "VISIBLE" to 1, + "INVISIBLE" to 2, + "OVERRIDE_GONE" to 16, + "OVERRIDE_VISIBLE" to 32, + "OVERRIDE_INVISIBLE" to 64, + "CLEAR_OVERRIDE" to 128, + ), + schema.visibilityConstants, + ) + + // 6. Border/Background/TextLayout enums and TextLayout.color.resolvedAfter + val border = schema.operationsByName.getValue("BorderModifierOperation") + assertEquals( + mapOf("RECTANGLE" to 0, "CIRCLE" to 1, "ROUNDED_RECTANGLE" to 2), + border.fields.first { it.name == "shapeType" }.enumValues, + ) + assertEquals( + mapOf("COLOR_REF" to 2), + border.fields.first { it.name == "flags" }.enumValues, + ) + assertEquals( + mapOf("LEGACY" to 0, "VERSION_1" to 1), + border.fields.first { it.name == "reserve1" }.enumValues, + ) + val bg = schema.operationsByName.getValue("BackgroundModifierOperation") + assertEquals(mapOf("COLOR_REF" to 2), bg.fields.first { it.name == "flags" }.enumValues) + + val textLayout = schema.operationsByName.getValue("TextLayout") + assertEquals("textAlign", textLayout.fields.first { it.name == "color" }.resolvedAfter) + assertEquals( + mapOf("FONT_STYLE_NORMAL" to 0, "FONT_STYLE_ITALIC" to 1), + textLayout.fields.first { it.name == "fontStyle" }.enumValues, + ) + + // 7. javaClass overrides on the 17 ops whose schema name differs from remote-core + val customJavaClasses = schema.operations.filter { it.javaClassName != null } + assertEquals(17, customJavaClasses.size) + assertEquals( + "TouchDownModifierOperation", + schema.operationsByName.getValue("TouchModifier").resolvedJavaClassName, + ) + assertEquals( + "ClickModifierOperation", + schema.operationsByName.getValue("ClickModifier").resolvedJavaClassName, + ) + assertEquals( + "TouchUpModifierOperation", + schema.operationsByName.getValue("TouchUpModifier").resolvedJavaClassName, + ) + assertEquals( + "RippleModifierOperation", + schema.operationsByName.getValue("RippleModifier").resolvedJavaClassName, + ) + assertEquals( + "LoopOperation", + schema.operationsByName.getValue("Loop").resolvedJavaClassName, + ) + assertEquals( + "DrawRect", + schema.operationsByName.getValue("DrawRect").resolvedJavaClassName, + ) + + // 8. reservedOpcodes cover experimental PropertyBundle (95, 96), 3D (110..118, 120), + // compressed stream marker (119), and extension range (251..255) + val reservedById = schema.reservedOpcodes.associateBy { it.id } + for (id in listOf(95, 96)) { + assertTrue("Missing experimental PropertyBundle opcode $id", id in reservedById) + assertEquals(listOf("androidx", "experimental"), reservedById.getValue(id).profiles) + } + for (id in listOf(110, 111, 112, 113, 114, 115, 116, 117, 118, 120)) { + assertTrue("Missing 3D opcode $id", id in reservedById) + assertEquals( + listOf("androidx", "widgets", "experimental"), + reservedById.getValue(id).profiles, + ) + } + assertTrue("Missing compressed stream marker opcode 119", 119 in reservedById) + assertEquals("COMPRESSED_STREAM_MARKER", reservedById.getValue(119).opCodeName) + assertEquals(listOf("reserved"), reservedById.getValue(119).profiles) + for (id in 251..255) { + assertTrue("Missing reserved opcode $id", id in reservedById) + assertEquals(listOf("reserved"), reservedById.getValue(id).profiles) + } + + // 8b. Every operation's schema-only opCodeName (without Operations.java reflection) + // matches Operations.java so validate() and generators never diverge by classpath + for (op in schema.operations) { + val expectedJavaOp = SchemaOperation.ID_TO_OPCODE_NAME[op.id] + if (expectedJavaOp != null) { + val schemaOnlyOpCodeName = + op.opCodeName ?: SchemaOperation.toScreamingSnakeCase(op.name) + assertEquals( + "Operation ${op.name} (${op.id}) must match Operations.$expectedJavaOp without reflection", + expectedJavaOp, + schemaOnlyOpCodeName, + ) + } + } + + // 9. JsonSchemaParser.validate rejects bad resolvedAfter, blank javaClass, duplicate + // opCodeName, & invalid reservedOpcodes + val badJson = + JSONObject( + """ + { + "schemaVersion": "1.0.0", + "targetApiLevel": 8, + "types": { "int": { "wire": "INT32", "description": "int" } }, + "categories": [{ "name": "Test", "description": "Test" }], + "operations": [ + { + "id": 1, + "name": "Sample", + "opCodeName": "SAMPLE_OP", + "javaClass": " ", + "category": "Test", + "description": "Sample", + "fields": [ + { "name": "a", "type": "int", "resolvedAfter": null }, + { "name": "b", "type": "int", "resolvedAfter": "a" }, + { "name": "c", "type": "int", "resolvedAfter": 123 } + ] + }, + { + "id": 2, + "name": "SampleDupOpCode", + "opCodeName": "SAMPLE_OP", + "category": "Test", + "description": "Dup opCodeName", + "fields": [] + } + ], + "reservedOpcodes": [ + { "id": 1, "name": "Overlap", "opCodeName": "OVERLAP", "profiles": ["reserved"] }, + { "id": 3, "name": "MissingOpCode", "profiles": ["reserved"] }, + { "id": 4, "name": "DupOpCode", "opCodeName": "OVERLAP", "profiles": ["reserved"] }, + { "id": 5, "name": "CollideOpCode", "opCodeName": "SAMPLE_OP", "profiles": ["bogus_profile"] }, + { "id": 95.5, "name": "FractionalId", "opCodeName": "FRAC_ID", "profiles": ["reserved"] }, + { "id": 300, "name": "OutOfRangeId", "opCodeName": "OOR_ID", "profiles": ["reserved"] }, + { "id": 251, "name": "ValidAfterOor", "opCodeName": "VALID_AFTER_OOR", "profiles": ["reserved"] }, + { "name": "MissingId", "opCodeName": "MISSING_ID" } + ] + } + """ + .trimIndent() + ) + val errors = JsonSchemaParser.validate(badJson) + assertTrue( + "Expected blank javaClass error, got: $errors", + errors.any { it.contains("blank or non-string javaClass") }, + ) + assertTrue( + "Expected duplicate operation opCodeName error, got: $errors", + errors.any { it.contains("Duplicate operation opCodeName: SAMPLE_OP") }, + ) + assertTrue( + "Expected blank/non-string resolvedAfter error, got: $errors", + errors.any { it.contains("field a has blank or non-string resolvedAfter") }, + ) + assertTrue( + "Expected non-string resolvedAfter error, got: $errors", + errors.any { it.contains("field c has blank or non-string resolvedAfter") }, + ) + assertTrue( + "Expected resolvedAfter ordering error, got: $errors", + errors.any { it.contains("resolvedAfter 'a' must reference a later field") }, + ) + assertTrue( + "Expected reservedOpcodes overlap error, got: $errors", + errors.any { it.contains("overlaps declared operation ID") }, + ) + assertTrue( + "Expected missing opCodeName error, got: $errors", + errors.any { it.contains("must specify a non-blank opCodeName") }, + ) + assertTrue( + "Expected duplicate reserved opCodeName error, got: $errors", + errors.any { it.contains("Duplicate reserved opcode opCodeName: OVERLAP") }, + ) + assertTrue( + "Expected colliding reserved opCodeName error, got: $errors", + errors.any { it.contains("opCodeName 'SAMPLE_OP' collides with declared operation") }, + ) + assertTrue( + "Expected unknown profile error, got: $errors", + errors.any { it.contains("unknown profile 'bogus_profile'") }, + ) + assertTrue( + "Expected fractional id error, got: $errors", + errors.any { it.contains("index 4 must specify an integer id") }, + ) + assertTrue( + "Expected out-of-range id error, got: $errors", + errors.any { it.contains("OutOfRangeId has invalid ID 300") }, + ) + assertFalse( + "Out-of-range ID 300 must not cause spurious sort error on ValidAfterOor (251), got: $errors", + errors.any { it.contains("ValidAfterOor") && it.contains("not sorted") }, + ) + assertTrue( + "Expected missing id error, got: $errors", + errors.any { it.contains("index 7 must specify an integer id") }, + ) + } + + @Test + fun testSwiftWriterTablesMaxLengthAndHygieneInvariants() { + val schema = loadSchema() + val swiftCode = SwiftGenerator(schema).generate() + + // 1. Writer tables & constants + for (marker in + listOf( + "public enum ReservedOpCode: UInt8, CaseIterable, Equatable, Hashable, Sendable", + "case propertyBundleModifierOperation = 95", + "case defineMesh3D = 110", + "case compressedStreamMarker = 119", + "case extendedOpcode = 255", + "public enum ComponentVisibility", + "public static let gone: Int32 = 0", + "public static let visible: Int32 = 1", + "public static let invisible: Int32 = 2", + "public static let overrideGone: Int32 = 16", + "public static let overrideVisible: Int32 = 32", + "public static let overrideInvisible: Int32 = 64", + "public static let clearOverride: Int32 = 128", + "public static let tagMask: Int32 = 0xFFFF", + "public static let inlineValueShift: Int32 = 16", + "public static func packInline(tag: Int32, value: Int32) -> Int32", + "public enum FloatExpressionOperator", + "public static let idStoreR0: Int32 = 56", + "public static let storeR0: Float =", + "public static func token(fromId id: Int32) -> Float?", + "public static func isOperator(_ token: Float) -> Bool", + "public static func operatorId(_ token: Float) -> Int32", + "public enum IntegerExpressionOperator", + "public static let iAdd: Int32 = offset + 1", + "public static func isOperatorCode(_ value: Int32) -> Bool", + "public static let magicNumber: Int32 = 76283904", + "public static let dataTypeInt: Int32 = 0", + "public static let colorRef: Int32 = 2", + "public static let fontStyleItalic: Int32 = 1", + )) { + assertTrue("Swift output missing writer marker: $marker", swiftCode.contains(marker)) + } + + // 2. Symmetric maxLength checks, implicit prefix/bitfield bounds, and atomic write rollback + for (marker in + listOf( + "public mutating func truncate(to count: Int)", + "buffer.truncate(to: _startCount)", + "public mutating func writeUTF8(_ value: String, maxLength: Int? = nil) throws(WireError)", + "public mutating func writeBuffer(_ value: [UInt8], maxLength: Int? = nil) throws(WireError)", + "try buffer.writeUTF8(text, maxLength: 4000)", + "try buffer.writeBuffer(data, maxLength: 100000)", + "try buffer.writeBuffer(fontData, maxLength: 800000)", + "guard words.count <= 1024 else", + "guard expression.count <= 32 else", + "guard args.count <= 32767 else", + "guard kerningTable.count <= 65535 else", + "guard floatUniforms.count <= 255 else", + "guard animationSpec.count <= 65535 else", + "try buffer.writeUTF8(val, maxLength: Self.maxHeaderStringLength)", + )) { + assertTrue( + "Swift output missing maxLength write guard: $marker", + swiftCode.contains(marker), + ) + } + + // 3. Static Swift hygiene invariants across the full generated file + assertFalse("Swift must not import Foundation", swiftCode.contains("import Foundation")) + assertFalse("Swift must not reference NSError", swiftCode.contains("NSError")) + assertFalse( + "Swift must not emit SCREAMING_SNAKE static let constants", + Regex("""public static let [A-Z][A-Z0-9_]+\s*:""").containsMatchIn(swiftCode), + ) + assertFalse( + "Swift must not call throwing writeUTF8 without try", + Regex("""(?<!try )(?<!func )buffer\.writeUTF8\(""").containsMatchIn(swiftCode), + ) + assertFalse( + "Swift must not call throwing writeBuffer without try", + Regex("""(?<!try )(?<!func )buffer\.writeBuffer\(""").containsMatchIn(swiftCode), + ) + assertFalse( + "Swift must not emit unqualified min() or max()", + Regex("""(?<!Swift\.)\b(?:min|max)\(""").containsMatchIn(swiftCode), + ) + assertEquals( + "Swift braces must be balanced", + swiftCode.count { it == '{' }, + swiftCode.count { it == '}' }, + ) + assertTrue( + "Swift IntegerExpressionOperator.isOperatorCode must use overflow-safe subtraction", + swiftCode.contains("value.subtractingReportingOverflow(offset)"), + ) + + // 4. Optional swiftc compile + runtime round-trip check when Swift 6 toolchain is present + val swiftc = + (listOfNotNull(findExecutableOnPath("swiftc")) + + listOf("/usr/bin/swiftc", "/usr/local/bin/swiftc", "/opt/homebrew/bin/swiftc") + .map { File(it) }) + .firstOrNull { it.exists() && it.canExecute() && canCompileSwift6(it) } + if (swiftc != null) { + val tmpDir = Files.createTempDirectory("rc_swift_test").toFile() + try { + File(tmpDir, "RemoteComposeWire.swift").writeText(swiftCode) + File(tmpDir, "main.swift") + .writeText( + """ + // Verify TouchExpression/PathExpression/ParticlesCompare compile, + // modern header round-trip, NaN ID equality & decoding, atomic rollback, + // and write maxLength/prefix-bound enforcement. + assert(IdEncoding.isNanBits(0x7F80_0005)) + assert(IdEncoding.idFromNanBits(0x7F80_0005) == 5) + assert(!IdEncoding.isNanBits(0x7FC0_0000)) + assert(IdEncoding.idFromNanBits(0x7FC0_0000) == IdEncoding.noId) + assert(FloatExpressionOperator.isOperator(FloatExpressionOperator.storeR0)) + assert(FloatExpressionOperator.operatorId(FloatExpressionOperator.storeR0) == FloatExpressionOperator.idStoreR0) + assert(IntegerExpressionOperator.isOperatorCode(IntegerExpressionOperator.iAdd)) + assert(!IntegerExpressionOperator.isOperatorCode(Int32.min)) + assert(PaintCommandTags.packInline(tag: PaintCommandTags.style, value: PaintConstants.styleStroke) == (PaintCommandTags.style | (PaintConstants.styleStroke << PaintCommandTags.inlineValueShift))) + + let nanVar = Float(bitPattern: UInt32(bitPattern: IdEncoding.asNanBits(42))) + let doc = WireDocument( + majorVersion: 1, + minorVersion: 1, + patchVersion: 0, + width: 400, + height: 300, + isModernHeader: true, + properties: [ + WireHeaderProperty(key: HeaderProperty.docWidth, value: .int(400)), + WireHeaderProperty(key: HeaderProperty.docHeight, value: .int(300)), + WireHeaderProperty(key: HeaderProperty.docDensityAtGeneration, value: .float(2.0)), + WireHeaderProperty(key: HeaderProperty.docContentDescription, value: .string("test")), + ], + operations: [ + .textData(TextData(textId: 42, text: "hello")), + .borderModifierOperation(BorderModifierOperation(shapeType: BorderModifierOperation.roundedRectangle)), + .floatExpression(FloatExpression(id: 7, expression: [nanVar, 2.0, FloatExpressionOperator.add])), + ] + ) + let bytes = try doc.save() + let decoded = try WireDocument.load(from: bytes) + assert(decoded == doc) + assert(try decoded.save() == bytes) + + // Verify PathEffect/PathCommand bit-exact equality & hashing with NaN IDs + let pe1 = PathEffect.dash(phase: nanVar, intervals: [4.0, nanVar]) + let pe2 = PathEffect.dash(phase: nanVar, intervals: [4.0, nanVar]) + assert(pe1 == pe2) + assert(Set([pe1]).contains(pe2)) + let pc1 = PathCommand.moveTo(x: nanVar, y: 1.0) + let pc2 = PathCommand.moveTo(x: nanVar, y: 1.0) + assert(pc1 == pc2) + assert(Set([pc1]).contains(pc2)) + + // Verify unknown header payload round-trip & dimension/capabilities reconciliation + var mutDoc = decoded + mutDoc.width = 800 + mutDoc.capabilities = 0x1_0000_0001 + mutDoc.properties.append( + WireHeaderProperty(key: 60, value: .unknown(dataType: 7, payload: [1, 2, 3, 4])) + ) + let mutBytes = try mutDoc.save() + let mutDecoded = try WireDocument.load(from: mutBytes) + assert(mutDecoded.width == 800) + assert(mutDecoded.height == 300) + assert(mutDecoded.capabilities == 0x1_0000_0001) + assert(mutDecoded.properties.contains(WireHeaderProperty(key: 60, value: .unknown(dataType: 7, payload: [1, 2, 3, 4])))) + assert(mutDecoded.operations == doc.operations) + let mixedInitDoc = WireDocument( + width: 640, + height: 480, + properties: [WireHeaderProperty(key: HeaderProperty.docDensityAtGeneration, value: .float(3.0))] + ) + let mixedDecoded = try WireDocument.load(from: try mixedInitDoc.save()) + assert(mixedDecoded.width == 640) + assert(mixedDecoded.height == 480) + + // Verify atomic WireBuffer rollback on throwing write + var partialBuf = WireBuffer(data: [0xDE, 0xAD]) + var threwOnTooLong = false + do { + let bigOp = TextData(textId: 1, text: String(repeating: "a", count: 4001)) + try bigOp.write(to: &partialBuf) + } catch WireError.lengthOutOfRange { + threwOnTooLong = true + } + assert(threwOnTooLong) + assert(partialBuf.data == [0xDE, 0xAD]) + print("Swift codecs OK") + """ + .trimIndent() + ) + val outBin = File(tmpDir, "rc_swift_test") + runCheckedProcess( + "Swift compile", + listOf( + swiftc.absolutePath, + "-swift-version", + "6", + File(tmpDir, "RemoteComposeWire.swift").absolutePath, + File(tmpDir, "main.swift").absolutePath, + "-o", + outBin.absolutePath, + ), + tmpDir, + ) + runCheckedProcess("Swift run", listOf(outBin.absolutePath), tmpDir) + } finally { + tmpDir.deleteRecursively() + } + } + } + + private fun canCompileSwift6(swiftc: File): Boolean { + val tmpDir = Files.createTempDirectory("rc_swift6_probe").toFile() + return try { + val probe = File(tmpDir, "probe.swift") + probe.writeText("enum E: Error, Sendable { case a }\nfunc f() throws(E) {}\n") + val proc = + ProcessBuilder( + swiftc.absolutePath, + "-swift-version", + "6", + "-typecheck", + probe.absolutePath, + ) + .redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .start() + val finished = proc.waitFor(15, TimeUnit.SECONDS) + if (!finished) { + proc.destroyForcibly() + false + } else { + proc.exitValue() == 0 + } + } catch (_: Exception) { + false + } finally { + tmpDir.deleteRecursively() + } + } + private fun runCheckedProcess( label: String, command: List<String>,
diff --git a/compose/remote/remote-generator/src/test/resources/golden/subset_expected_output.txt b/compose/remote/remote-generator/src/test/resources/golden/subset_expected_output.txt index 354536b..f5c277c 100644 --- a/compose/remote/remote-generator/src/test/resources/golden/subset_expected_output.txt +++ b/compose/remote/remote-generator/src/test/resources/golden/subset_expected_output.txt
@@ -5773,10 +5773,9 @@ === SWIFT (RemoteCompose.swift) === // Generated by RemoteCompose Schema Codegen. DO NOT EDIT. -import Foundation /// Operation wire identifiers for RemoteCompose. -public enum OpCode: UInt8, CaseIterable { +public enum OpCode: UInt8, CaseIterable, Equatable, Hashable, Sendable { /// Document metadata containing version, dimensions, density behavior, and capabilities case header = 0 /// Draws a circle with center (centerX, centerY) and radius @@ -5801,53 +5800,77 @@ case textStyle = 242 } -/// Protocol adopted by all RemoteCompose operation types. -public protocol RemoteOperation { - var opCode: OpCode { get } - func write(to buffer: inout WireBuffer) throws +/// Typed error thrown while decoding or encoding RemoteCompose wire streams. +public enum WireError: Error, Equatable, Hashable, Sendable { + case underflow(needed: Int, remaining: Int) + case indexOutOfBounds(index: Int, count: Int) + case invalidLength(field: String, length: Int) + case lengthOutOfRange(field: String, length: Int, min: Int?, max: Int?) + case invalidUTF8(field: String) + case unknownOpCode(UInt8) + case expectedHeaderOpCode(actual: UInt8) + case unexpectedHeaderInBody + case invalidHeaderMagic(Int32) + case compressedDocumentUnsupported + case operationCountExceeded(limit: Int) + case invalidFieldValue(owner: String, field: String, detail: String) + case missingRequiredField(owner: String, field: String) + case unknownSparseParameter(owner: String, id: Int) + case invalidAnimationSpec(String) + case invalidPathEffect(String) } -public struct WireBuffer { - public private(set) var data: Data +/// Big-endian binary reader and writer backed by a Swift byte array. +public struct WireBuffer: Equatable, Hashable, Sendable { + public private(set) var data: [UInt8] public private(set) var index: Int = 0 - public init(data: Data = Data()) { - self.data = data.startIndex == 0 ? data : Data(data) + public init(data: [UInt8] = []) { + self.data = data self.index = 0 } public var remaining: Int { - return max(0, data.count - index) + return Swift.max(0, data.count - index) } public var available: Bool { return index < data.count } - public mutating func setIndex(_ newIndex: Int) throws { + public mutating func setIndex(_ newIndex: Int) throws(WireError) { guard newIndex >= 0 && newIndex <= data.count else { - throw NSError(domain: "WireBuffer", code: 2, userInfo: [NSLocalizedDescriptionKey: "Index out of bounds: \(newIndex)"]) + throw WireError.indexOutOfBounds(index: newIndex, count: data.count) } index = newIndex } - public mutating func skipBytes(_ count: Int) throws { + public mutating func skipBytes(_ count: Int) throws(WireError) { guard count >= 0 else { - throw NSError(domain: "WireBuffer", code: 3, userInfo: [NSLocalizedDescriptionKey: "Invalid negative skip length"]) + throw WireError.invalidLength(field: "skip", length: count) } guard count <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: count, remaining: remaining) } index += count } + public mutating func truncate(to count: Int) { + if count >= 0 && count < data.count { + data.removeLast(data.count - count) + if index > count { + index = count + } + } + } + public mutating func writeByte(_ value: UInt8) { data.append(value) } - public mutating func readByte() throws -> UInt8 { + public mutating func readByte() throws(WireError) -> UInt8 { guard 1 <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: 1, remaining: remaining) } let byte = data[index] index += 1 @@ -5855,13 +5878,14 @@ } public mutating func writeShort(_ value: Int16) { - var val = value.bigEndian - withUnsafeBytes(of: &val) { data.append(contentsOf: $0) } + let bits = UInt16(bitPattern: value) + data.append(UInt8(truncatingIfNeeded: bits >> 8)) + data.append(UInt8(truncatingIfNeeded: bits)) } - public mutating func readShort() throws -> Int16 { + public mutating func readShort() throws(WireError) -> Int16 { guard 2 <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: 2, remaining: remaining) } let bits = (UInt16(data[index]) << 8) | UInt16(data[index + 1]) index += 2 @@ -5869,13 +5893,16 @@ } public mutating func writeInt(_ value: Int32) { - var val = value.bigEndian - withUnsafeBytes(of: &val) { data.append(contentsOf: $0) } + let bits = UInt32(bitPattern: value) + data.append(UInt8(truncatingIfNeeded: bits >> 24)) + data.append(UInt8(truncatingIfNeeded: bits >> 16)) + data.append(UInt8(truncatingIfNeeded: bits >> 8)) + data.append(UInt8(truncatingIfNeeded: bits)) } - public mutating func readInt() throws -> Int32 { + public mutating func readInt() throws(WireError) -> Int32 { guard 4 <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: 4, remaining: remaining) } let bits = (UInt32(data[index]) << 24) | (UInt32(data[index + 1]) << 16) @@ -5886,13 +5913,15 @@ } public mutating func writeLong(_ value: Int64) { - var val = value.bigEndian - withUnsafeBytes(of: &val) { data.append(contentsOf: $0) } + let bits = UInt64(bitPattern: value) + for shift in stride(from: 56, through: 0, by: -8) { + data.append(UInt8(truncatingIfNeeded: bits >> shift)) + } } - public mutating func readLong() throws -> Int64 { + public mutating func readLong() throws(WireError) -> Int64 { guard 8 <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: 8, remaining: remaining) } var bits: UInt64 = 0 for i in 0..<8 { @@ -5903,11 +5932,10 @@ } public mutating func writeFloat(_ value: Float) { - var bitVal = value.bitPattern.bigEndian - withUnsafeBytes(of: &bitVal) { data.append(contentsOf: $0) } + writeInt(Int32(bitPattern: value.bitPattern)) } - public mutating func readFloat() throws -> Float { + public mutating func readFloat() throws(WireError) -> Float { let bitVal = UInt32(bitPattern: try readInt()) return Float(bitPattern: bitVal) } @@ -5916,75 +5944,151 @@ writeByte(value ? 1 : 0) } - public mutating func readBoolean() throws -> Bool { + public mutating func readBoolean() throws(WireError) -> Bool { return (try readByte()) != 0 } - public mutating func writeUTF8(_ value: String) { - let utf8Data = Data(value.utf8) - writeInt(Int32(utf8Data.count)) - data.append(utf8Data) + public mutating func writeUTF8(_ value: String, maxLength: Int? = nil) throws(WireError) { + let utf8Count = value.utf8.count + let limit = maxLength.map { Swift.min($0, Int(Int32.max)) } ?? Int(Int32.max) + guard utf8Count <= limit else { + throw WireError.lengthOutOfRange(field: "utf8", length: utf8Count, min: nil, max: limit) + } + writeInt(Int32(utf8Count)) + data.append(contentsOf: value.utf8) } - public mutating func readUTF8(maxLength: Int? = nil) throws -> String { + public mutating func readUTF8(maxLength: Int? = nil) throws(WireError) -> String { let len = Int(try readInt()) guard len >= 0 else { - throw NSError(domain: "WireBuffer", code: 3, userInfo: [NSLocalizedDescriptionKey: "Invalid negative UTF-8 length"]) + throw WireError.invalidLength(field: "utf8", length: len) } if let maxLen = maxLength, len > maxLen { - throw NSError(domain: "WireBuffer", code: 5, userInfo: [NSLocalizedDescriptionKey: "UTF-8 length exceeds maximum"]) + throw WireError.lengthOutOfRange(field: "utf8", length: len, min: nil, max: maxLen) } guard len <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: len, remaining: remaining) } - let strData = data.subdata(in: index..<(index + len)) - guard let str = String(data: strData, encoding: .utf8) else { - throw NSError(domain: "WireBuffer", code: 4, userInfo: [NSLocalizedDescriptionKey: "Invalid UTF-8 byte sequence"]) + var scalars = String.UnicodeScalarView() + scalars.reserveCapacity(len) + var decoder = UTF8() + var iterator = data[index..<(index + len)].makeIterator() + while true { + switch decoder.decode(&iterator) { + case .scalarValue(let scalar): + scalars.append(scalar) + case .emptyInput: + index += len + return String(scalars) + case .error: + throw WireError.invalidUTF8(field: "utf8") + } } - index += len - return str } - public mutating func writeBuffer(_ value: Data) { + public mutating func writeBuffer(_ value: [UInt8], maxLength: Int? = nil) throws(WireError) { + let limit = maxLength.map { Swift.min($0, Int(Int32.max)) } ?? Int(Int32.max) + guard value.count <= limit else { + throw WireError.lengthOutOfRange(field: "buffer", length: value.count, min: nil, max: limit) + } writeInt(Int32(value.count)) - data.append(value) + data.append(contentsOf: value) } - public mutating func writeBytes(_ value: Data) { - data.append(value) + public mutating func writeBytes(_ value: [UInt8]) { + data.append(contentsOf: value) } - public mutating func readBytes(count: Int) throws -> Data { + public mutating func readBytes(count: Int) throws(WireError) -> [UInt8] { guard count >= 0 else { - throw NSError(domain: "WireBuffer", code: 3, userInfo: [NSLocalizedDescriptionKey: "Invalid negative byte count"]) + throw WireError.invalidLength(field: "bytes", length: count) } guard count <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: count, remaining: remaining) } - let bufData = data.subdata(in: index..<(index + count)) + let bufData = Array(data[index..<(index + count)]) index += count return bufData } - public mutating func readBuffer(maxLength: Int? = nil) throws -> Data { + public mutating func readBuffer(maxLength: Int? = nil) throws(WireError) -> [UInt8] { let len = Int(try readInt()) guard len >= 0 else { - throw NSError(domain: "WireBuffer", code: 3, userInfo: [NSLocalizedDescriptionKey: "Invalid negative buffer length"]) + throw WireError.invalidLength(field: "buffer", length: len) } if let maxLen = maxLength, len > maxLen { - throw NSError(domain: "WireBuffer", code: 5, userInfo: [NSLocalizedDescriptionKey: "Buffer length exceeds maximum"]) + throw WireError.lengthOutOfRange(field: "buffer", length: len, min: nil, max: maxLen) } guard len <= remaining else { - throw NSError(domain: "WireBuffer", code: 1, userInfo: [NSLocalizedDescriptionKey: "Underflow"]) + throw WireError.underflow(needed: len, remaining: remaining) } - let bufData = data.subdata(in: index..<(index + len)) + let bufData = Array(data[index..<(index + len)]) index += len return bufData } } +@inline(__always) +private func wireFloatEquals(_ lhs: Float, _ rhs: Float) -> Bool { + lhs.bitPattern == rhs.bitPattern +} + +@inline(__always) +private func wireFloatEquals(_ lhs: Float?, _ rhs: Float?) -> Bool { + lhs?.bitPattern == rhs?.bitPattern +} + +@inline(__always) +private func wireFloatEquals(_ lhs: [Float], _ rhs: [Float]) -> Bool { + guard lhs.count == rhs.count else { return false } + for i in lhs.indices { + if lhs[i].bitPattern != rhs[i].bitPattern { return false } + } + return true +} + +@inline(__always) +private func wireFloatEquals(_ lhs: [Float]?, _ rhs: [Float]?) -> Bool { + switch (lhs, rhs) { + case (nil, nil): + return true + case (let a?, let b?): + return wireFloatEquals(a, b) + default: + return false + } +} + +@inline(__always) +private func wireFloatHash(_ value: Float, into hasher: inout Hasher) { + hasher.combine(value.bitPattern) +} + +@inline(__always) +private func wireFloatHash(_ value: Float?, into hasher: inout Hasher) { + hasher.combine(value?.bitPattern) +} + +@inline(__always) +private func wireFloatHash(_ value: [Float], into hasher: inout Hasher) { + hasher.combine(value.count) + for element in value { + hasher.combine(element.bitPattern) + } +} + +@inline(__always) +private func wireFloatHash(_ value: [Float]?, into hasher: inout Hasher) { + if let array = value { + hasher.combine(true) + wireFloatHash(array, into: &hasher) + } else { + hasher.combine(false) + } +} + /// Bitmap font glyph metrics and bitmap reference -public struct Glyph: Equatable { +public struct Glyph: Equatable, Hashable, Sendable { /// Character or ligature string public var character: String /// Bitmap asset ID @@ -6013,7 +6117,7 @@ self.height = height } - public static func read(from buffer: inout WireBuffer) throws -> Glyph { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> Glyph { let character = try buffer.readUTF8() let bitmapId = try buffer.readInt() let marginLeft = try buffer.readShort() @@ -6025,8 +6129,15 @@ return Glyph(character: character, bitmapId: bitmapId, marginLeft: marginLeft, marginTop: marginTop, marginRight: marginRight, marginBottom: marginBottom, width: width, height: height) } - public func write(to buffer: inout WireBuffer) throws { - buffer.writeUTF8(character) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + try buffer.writeUTF8(character) buffer.writeInt(bitmapId) buffer.writeShort(marginLeft) buffer.writeShort(marginTop) @@ -6034,11 +6145,12 @@ buffer.writeShort(marginBottom) buffer.writeShort(width) buffer.writeShort(height) + _committed = true } } /// Kerning adjustment for a pair of glyphs -public struct KerningPair: Equatable { +public struct KerningPair: Equatable, Hashable, Sendable { /// Two-character sequence public var glyphPair: String /// Horizontal kerning adjustment in pixels @@ -6049,21 +6161,30 @@ self.adjustment = adjustment } - public static func read(from buffer: inout WireBuffer) throws -> KerningPair { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> KerningPair { let glyphPair = try buffer.readUTF8() let adjustment = try buffer.readShort() return KerningPair(glyphPair: glyphPair, adjustment: adjustment) } - public func write(to buffer: inout WireBuffer) throws { - buffer.writeUTF8(glyphPair) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + try buffer.writeUTF8(glyphPair) buffer.writeShort(adjustment) + _committed = true } } /// Document metadata containing version, dimensions, density behavior, and capabilities -public struct Header: RemoteOperation, Equatable { - public let opCode: OpCode = .header +public struct Header: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .header + public var opCode: OpCode { Self.opCode } /// Major version public var majorVersion: Int32 @@ -6096,7 +6217,7 @@ } /// Reads and decodes a [Header] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> Header { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> Header { let majorVersion = try buffer.readInt() let minorVersion = try buffer.readInt() let patchVersion = try buffer.readInt() @@ -6107,8 +6228,8 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + buffer.writeByte(Self.opCode.rawValue) buffer.writeInt(majorVersion) buffer.writeInt(minorVersion) buffer.writeInt(patchVersion) @@ -6119,8 +6240,9 @@ } /// Draws a circle with center (centerX, centerY) and radius -public struct DrawCircle: RemoteOperation, Equatable { - public let opCode: OpCode = .drawCircle +public struct DrawCircle: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .drawCircle + public var opCode: OpCode { Self.opCode } /// Center X coordinate public var centerX: Float @@ -6141,7 +6263,7 @@ } /// Reads and decodes a [DrawCircle] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> DrawCircle { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> DrawCircle { let centerX = try buffer.readFloat() let centerY = try buffer.readFloat() let radius = try buffer.readFloat() @@ -6149,17 +6271,30 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + buffer.writeByte(Self.opCode.rawValue) buffer.writeFloat(centerX) buffer.writeFloat(centerY) buffer.writeFloat(radius) } + + public static func == (lhs: DrawCircle, rhs: DrawCircle) -> Bool { + return wireFloatEquals(lhs.centerX, rhs.centerX) + && wireFloatEquals(lhs.centerY, rhs.centerY) + && wireFloatEquals(lhs.radius, rhs.radius) + } + + public func hash(into hasher: inout Hasher) { + wireFloatHash(self.centerX, into: &hasher) + wireFloatHash(self.centerY, into: &hasher) + wireFloatHash(self.radius, into: &hasher) + } } /// Defines a float variable computed via Reverse Polish Notation (RPN) expression evaluation -public struct FloatExpression: RemoteOperation, Equatable { - public let opCode: OpCode = .floatExpression +public struct FloatExpression: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .floatExpression + public var opCode: OpCode { Self.opCode } /// The ID of the expression variable public var id: Int32 @@ -6180,35 +6315,37 @@ } /// Reads and decodes a [FloatExpression] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> FloatExpression { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> FloatExpression { let id = try buffer.readInt() let raw_packedLengths = try buffer.readInt() let expressionLength = Int32(UInt32(bitPattern: raw_packedLengths) & 0xFFFF) let animationLength = Int32((UInt32(bitPattern: raw_packedLengths) >> 16) & 0xFFFF) let _expressionCount = Int(expressionLength) guard _expressionCount >= 0 else { - throw NSError(domain: "FloatExpression", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid negative array length"]) + throw WireError.invalidLength(field: "expression", length: _expressionCount) } guard _expressionCount <= 32 else { - throw NSError(domain: "FloatExpression", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds maximum (32)"]) + throw WireError.lengthOutOfRange(field: "expression", length: _expressionCount, min: nil, max: 32) } guard _expressionCount <= buffer.remaining / 4 else { - throw NSError(domain: "FloatExpression", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds remaining buffer"]) + let (needed, overflow) = _expressionCount.multipliedReportingOverflow(by: 4) + throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining) } var expression = [Float]() - expression.reserveCapacity(min(_expressionCount, 4096)) + expression.reserveCapacity(Swift.min(_expressionCount, 4096)) for _ in 0..<_expressionCount { expression.append(try buffer.readFloat()) } let _animationSpecCount = Int(animationLength) guard _animationSpecCount >= 0 else { - throw NSError(domain: "FloatExpression", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid negative array length"]) + throw WireError.invalidLength(field: "animationSpec", length: _animationSpecCount) } guard _animationSpecCount <= buffer.remaining / 4 else { - throw NSError(domain: "FloatExpression", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds remaining buffer"]) + let (needed, overflow) = _animationSpecCount.multipliedReportingOverflow(by: 4) + throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining) } var animationSpec = [Float]() - animationSpec.reserveCapacity(min(_animationSpecCount, 4096)) + animationSpec.reserveCapacity(Swift.min(_animationSpecCount, 4096)) for _ in 0..<_animationSpecCount { animationSpec.append(try buffer.readFloat()) } @@ -6216,24 +6353,54 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + buffer.writeByte(Self.opCode.rawValue) buffer.writeInt(id) + guard expression.count <= 65535 else { + throw WireError.lengthOutOfRange(field: "expression", length: expression.count, min: nil, max: 65535) + } let expressionLength: Int32 = Int32(expression.count) + guard animationSpec.count <= 65535 else { + throw WireError.lengthOutOfRange(field: "animationSpec", length: animationSpec.count, min: nil, max: 65535) + } let animationLength: Int32 = Int32(animationSpec.count) buffer.writeInt(Int32(bitPattern: (UInt32(bitPattern: Int32(expressionLength)) & 0xFFFF) | ((UInt32(bitPattern: Int32(animationLength)) & 0xFFFF) << 16))) + guard expression.count <= 32 else { + throw WireError.lengthOutOfRange(field: "expression", length: expression.count, min: nil, max: 32) + } for item in expression { buffer.writeFloat(item) } for item in animationSpec { buffer.writeFloat(item) } + _committed = true + } + + public static func == (lhs: FloatExpression, rhs: FloatExpression) -> Bool { + return lhs.id == rhs.id + && wireFloatEquals(lhs.expression, rhs.expression) + && wireFloatEquals(lhs.animationSpec, rhs.animationSpec) + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(self.id) + wireFloatHash(self.expression, into: &hasher) + wireFloatHash(self.animationSpec, into: &hasher) } } /// Embed or reference bitmap image data -public struct BitmapData: RemoteOperation, Equatable { - public let opCode: OpCode = .bitmapData +public struct BitmapData: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .bitmapData + public var opCode: OpCode { Self.opCode } /// The ID of the bitmap public var imageId: Int32 @@ -6242,7 +6409,7 @@ /// Encoded height (bits 0..15) and data encoding (bits 16..31) public var heightAndEncoding: Int32 /// The raw or encoded bitmap data - public var bitmap: Data + public var bitmap: [UInt8] public var width: Int32 { return Int32(UInt32(bitPattern: widthAndType) & 0xFFFF) } @@ -6262,7 +6429,7 @@ /// - widthAndType: Encoded width (bits 0..15) and image type (bits 16..31) /// - heightAndEncoding: Encoded height (bits 0..15) and data encoding (bits 16..31) /// - bitmap: The raw or encoded bitmap data - public init(imageId: Int32 = 0, widthAndType: Int32 = 0, heightAndEncoding: Int32 = 0, bitmap: Data = Data()) { + public init(imageId: Int32 = 0, widthAndType: Int32 = 0, heightAndEncoding: Int32 = 0, bitmap: [UInt8] = []) { self.imageId = imageId self.widthAndType = widthAndType self.heightAndEncoding = heightAndEncoding @@ -6270,7 +6437,7 @@ } /// Reads and decodes a [BitmapData] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> BitmapData { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> BitmapData { let imageId = try buffer.readInt() let widthAndType = try buffer.readInt() let heightAndEncoding = try buffer.readInt() @@ -6279,18 +6446,27 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + buffer.writeByte(Self.opCode.rawValue) buffer.writeInt(imageId) buffer.writeInt(widthAndType) buffer.writeInt(heightAndEncoding) - buffer.writeBuffer(bitmap) + try buffer.writeBuffer(bitmap) + _committed = true } } /// Define a static string and associate it with an ID -public struct TextData: RemoteOperation, Equatable { - public let opCode: OpCode = .textData +public struct TextData: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .textData + public var opCode: OpCode { Self.opCode } /// The ID of the text public var textId: Int32 @@ -6307,23 +6483,32 @@ } /// Reads and decodes a [TextData] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> TextData { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> TextData { let textId = try buffer.readInt() let text = try buffer.readUTF8(maxLength: 4000) return TextData(textId: textId, text: text) } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + buffer.writeByte(Self.opCode.rawValue) buffer.writeInt(textId) - buffer.writeUTF8(text) + try buffer.writeUTF8(text, maxLength: 4000) + _committed = true } } /// Embeds font glyph layout, character metrics, and glyph page mappings for bitmap font rendering -public struct BitmapFontData: RemoteOperation, Equatable { - public let opCode: OpCode = .bitmapFontData +public struct BitmapFontData: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .bitmapFontData + public var opCode: OpCode { Self.opCode } /// Bitmap font ID public var id: Int32 @@ -6344,20 +6529,21 @@ } /// Reads and decodes a [BitmapFontData] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> BitmapFontData { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> BitmapFontData { let id = try buffer.readInt() let raw_versionAndNumGlyphs = try buffer.readInt() let numGlyphs = Int32(UInt32(bitPattern: raw_versionAndNumGlyphs) & 0xFFFF) let version = (raw_versionAndNumGlyphs >> 16) let _glyphsCount = Int(numGlyphs) guard _glyphsCount >= 0 else { - throw NSError(domain: "BitmapFontData", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid negative array length"]) + throw WireError.invalidLength(field: "glyphs", length: _glyphsCount) } guard _glyphsCount <= buffer.remaining / 20 else { - throw NSError(domain: "BitmapFontData", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds remaining buffer"]) + let (needed, overflow) = _glyphsCount.multipliedReportingOverflow(by: 20) + throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining) } var glyphs = [Glyph]() - glyphs.reserveCapacity(min(_glyphsCount, 4096)) + glyphs.reserveCapacity(Swift.min(_glyphsCount, 4096)) for _ in 0..<_glyphsCount { glyphs.append(try Glyph.read(from: &buffer)) } @@ -6365,13 +6551,14 @@ if version >= 1 { let _kerningTableCount = Int(UInt16(bitPattern: try buffer.readShort())) guard _kerningTableCount >= 0 else { - throw NSError(domain: "BitmapFontData", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid negative array length"]) + throw WireError.invalidLength(field: "kerningTable", length: _kerningTableCount) } guard _kerningTableCount <= buffer.remaining / 6 else { - throw NSError(domain: "BitmapFontData", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds remaining buffer"]) + let (needed, overflow) = _kerningTableCount.multipliedReportingOverflow(by: 6) + throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining) } var kerningTableTmp = [KerningPair]() - kerningTableTmp.reserveCapacity(min(_kerningTableCount, 4096)) + kerningTableTmp.reserveCapacity(Swift.min(_kerningTableCount, 4096)) for _ in 0..<_kerningTableCount { kerningTableTmp.append(try KerningPair.read(from: &buffer)) } @@ -6383,9 +6570,19 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + buffer.writeByte(Self.opCode.rawValue) buffer.writeInt(id) + guard glyphs.count <= 65535 else { + throw WireError.lengthOutOfRange(field: "glyphs", length: glyphs.count, min: nil, max: 65535) + } let numGlyphs: Int32 = Int32(glyphs.count) let version: Int32 = (!kerningTable.isEmpty ? 1 : 0) buffer.writeInt(Int32(bitPattern: (UInt32(bitPattern: Int32(numGlyphs)) & 0xFFFF) | ((UInt32(bitPattern: Int32(version)) & 0xFFFF) << 16))) @@ -6393,17 +6590,22 @@ try item.write(to: &buffer) } if version >= 1 { + guard kerningTable.count <= 65535 else { + throw WireError.lengthOutOfRange(field: "kerningTable", length: kerningTable.count, min: nil, max: 65535) + } buffer.writeShort(Int16(truncatingIfNeeded: kerningTable.count)) for item in kerningTable { try item.write(to: &buffer) } } + _committed = true } } /// Extract time-related information (seconds, hours, etc.) -public struct TimeAttribute: RemoteOperation, Equatable { - public let opCode: OpCode = .timeAttribute +public struct TimeAttribute: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .timeAttribute + public var opCode: OpCode { Self.opCode } /// The ID of the float variable to store the result public var id: Int32 @@ -6428,22 +6630,23 @@ } /// Reads and decodes a [TimeAttribute] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> TimeAttribute { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> TimeAttribute { let id = try buffer.readInt() let timeId = try buffer.readInt() let type = try buffer.readShort() let _argsCount = Int(try buffer.readShort()) guard _argsCount >= 0 else { - throw NSError(domain: "TimeAttribute", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid negative array length"]) + throw WireError.invalidLength(field: "args", length: _argsCount) } guard _argsCount <= 32 else { - throw NSError(domain: "TimeAttribute", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds maximum (32)"]) + throw WireError.lengthOutOfRange(field: "args", length: _argsCount, min: nil, max: 32) } guard _argsCount <= buffer.remaining / 4 else { - throw NSError(domain: "TimeAttribute", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds remaining buffer"]) + let (needed, overflow) = _argsCount.multipliedReportingOverflow(by: 4) + throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining) } var args = [Int32]() - args.reserveCapacity(min(_argsCount, 4096)) + args.reserveCapacity(Swift.min(_argsCount, 4096)) for _ in 0..<_argsCount { args.append(try buffer.readInt()) } @@ -6451,28 +6654,40 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + buffer.writeByte(Self.opCode.rawValue) buffer.writeInt(id) buffer.writeInt(timeId) buffer.writeShort(type) + guard args.count <= 32 else { + throw WireError.lengthOutOfRange(field: "args", length: args.count, min: nil, max: 32) + } buffer.writeShort(Int16(truncatingIfNeeded: args.count)) for item in args { buffer.writeInt(item) } + _committed = true } } /// Execute a list of operations if a condition is met -public struct ConditionalOperations: RemoteOperation, Equatable { - public let opCode: OpCode = .conditionalOperations - public static let TYPE_EQ: Int32 = 0 - public static let TYPE_NEQ: Int32 = 1 - public static let TYPE_LT: Int32 = 2 - public static let TYPE_LTE: Int32 = 3 - public static let TYPE_GT: Int32 = 4 - public static let TYPE_GTE: Int32 = 5 - public static let TYPE_CHANGED: Int32 = 6 +public struct ConditionalOperations: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .conditionalOperations + public var opCode: OpCode { Self.opCode } + public static let typeEq: Int32 = 0 + public static let typeNeq: Int32 = 1 + public static let typeLt: Int32 = 2 + public static let typeLte: Int32 = 3 + public static let typeGt: Int32 = 4 + public static let typeGte: Int32 = 5 + public static let typeChanged: Int32 = 6 /// The type of comparison (EQ, NEQ, LT, etc.) public var type: UInt8 @@ -6493,13 +6708,13 @@ } /// Reads and decodes a [ConditionalOperations] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> ConditionalOperations { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> ConditionalOperations { let type = try buffer.readByte() switch type { case 0, 1, 2, 3, 4, 5, 6: break default: - throw NSError(domain: "ConditionalOperations", code: 2, userInfo: [NSLocalizedDescriptionKey: "Invalid enum value for type"]) + throw WireError.invalidFieldValue(owner: "ConditionalOperations", field: "type", detail: "invalid enum value \(type)") } let varA = try buffer.readFloat() let varB = try buffer.readFloat() @@ -6507,17 +6722,30 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + buffer.writeByte(Self.opCode.rawValue) buffer.writeByte(type) buffer.writeFloat(varA) buffer.writeFloat(varB) } + + public static func == (lhs: ConditionalOperations, rhs: ConditionalOperations) -> Bool { + return lhs.type == rhs.type + && wireFloatEquals(lhs.varA, rhs.varA) + && wireFloatEquals(lhs.varB, rhs.varB) + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(self.type) + wireFloatHash(self.varA, into: &hasher) + wireFloatHash(self.varB, into: &hasher) + } } /// Measure text dimensions specifically for bitmap fonts -public struct BitmapTextMeasure: RemoteOperation, Equatable { - public let opCode: OpCode = .bitmapTextMeasure +public struct BitmapTextMeasure: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .bitmapTextMeasure + public var opCode: OpCode { Self.opCode } /// Output float ID in bits 0..30 and glyphSpacing presence flag in bit 31 public var id: Int32 @@ -6546,7 +6774,7 @@ } /// Reads and decodes a [BitmapTextMeasure] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> BitmapTextMeasure { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> BitmapTextMeasure { let raw_id = try buffer.readInt() let id = Int32(UInt32(bitPattern: raw_id) & 0x7FFFFFFF) let hasGlyphSpacing = Int32((UInt32(bitPattern: raw_id) >> 31) & 0x1) @@ -6563,25 +6791,50 @@ } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + buffer.writeByte(Self.opCode.rawValue) let hasGlyphSpacing: Int32 = (glyphSpacing != nil ? 1 : 0) buffer.writeInt(Int32(bitPattern: (UInt32(bitPattern: Int32(id)) & 0x7FFFFFFF) | ((UInt32(bitPattern: Int32(hasGlyphSpacing)) & 0x1) << 31))) if hasGlyphSpacing != 0 { guard let val = glyphSpacing else { - throw NSError(domain: "BitmapTextMeasure", code: 3, userInfo: [NSLocalizedDescriptionKey: "Missing required field glyphSpacing"]) + throw WireError.missingRequiredField(owner: "BitmapTextMeasure", field: "glyphSpacing") } buffer.writeFloat(val) } buffer.writeInt(textId) buffer.writeInt(bitmapFontId) buffer.writeInt(type) + _committed = true + } + + public static func == (lhs: BitmapTextMeasure, rhs: BitmapTextMeasure) -> Bool { + return lhs.id == rhs.id + && wireFloatEquals(lhs.glyphSpacing, rhs.glyphSpacing) + && lhs.textId == rhs.textId + && lhs.bitmapFontId == rhs.bitmapFontId + && lhs.type == rhs.type + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(self.id) + wireFloatHash(self.glyphSpacing, into: &hasher) + hasher.combine(self.textId) + hasher.combine(self.bitmapFontId) + hasher.combine(self.type) } } /// Closes the current container or layout component -public struct ContainerEnd: RemoteOperation, Equatable { - public let opCode: OpCode = .containerEnd +public struct ContainerEnd: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .containerEnd + public var opCode: OpCode { Self.opCode } /// Creates a new [ContainerEnd] operation. @@ -6589,19 +6842,20 @@ } /// Reads and decodes a [ContainerEnd] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> ContainerEnd { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> ContainerEnd { return ContainerEnd() } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + buffer.writeByte(Self.opCode.rawValue) } } /// Text style implementation -public struct TextStyle: RemoteOperation, Equatable { - public let opCode: OpCode = .textStyle +public struct TextStyle: Equatable, Hashable, Sendable { + public static let opCode: OpCode = .textStyle + public var opCode: OpCode { Self.opCode } public var id: Int32? public var fontSize: Float? @@ -6619,13 +6873,14 @@ } /// Reads and decodes a [TextStyle] from the wire buffer. - public static func read(from buffer: inout WireBuffer) throws -> TextStyle { + public static func read(from buffer: inout WireBuffer) throws(WireError) -> TextStyle { var id: Int32? = nil var fontSize: Float? = nil var fontAxis: [Int32]? = nil let sparseCount = Int(UInt16(bitPattern: try buffer.readShort())) guard sparseCount <= buffer.remaining / 2 else { - throw NSError(domain: "TextStyle", code: 1, userInfo: [NSLocalizedDescriptionKey: "Sparse parameter count exceeds remaining buffer"]) + let (needed, overflow) = sparseCount.multipliedReportingOverflow(by: 2) + throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining) } for _ in 0..<sparseCount { let paramId = Int(try buffer.readByte()) @@ -6637,27 +6892,35 @@ case 20: let _fontAxisCount = Int(UInt16(bitPattern: try buffer.readShort())) guard _fontAxisCount >= 0 else { - throw NSError(domain: "TextStyle", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid negative array length"]) + throw WireError.invalidLength(field: "fontAxis", length: _fontAxisCount) } guard _fontAxisCount <= buffer.remaining / 4 else { - throw NSError(domain: "TextStyle", code: 1, userInfo: [NSLocalizedDescriptionKey: "Array length exceeds remaining buffer"]) + let (needed, overflow) = _fontAxisCount.multipliedReportingOverflow(by: 4) + throw WireError.underflow(needed: overflow ? Int.max : needed, remaining: buffer.remaining) } var fontAxisTmp = [Int32]() - fontAxisTmp.reserveCapacity(min(_fontAxisCount, 4096)) + fontAxisTmp.reserveCapacity(Swift.min(_fontAxisCount, 4096)) for _ in 0..<_fontAxisCount { fontAxisTmp.append(try buffer.readInt()) } fontAxis = fontAxisTmp default: - throw NSError(domain: "TextStyle", code: 2, userInfo: [NSLocalizedDescriptionKey: "Unknown sparse parameter"]) + throw WireError.unknownSparseParameter(owner: "TextStyle", id: paramId) } } return TextStyle(id: id, fontSize: fontSize, fontAxis: fontAxis) } /// Serializes this operation to the wire buffer. - public func write(to buffer: inout WireBuffer) throws { - buffer.writeByte(opCode.rawValue) + public func write(to buffer: inout WireBuffer) throws(WireError) { + let _startCount = buffer.data.count + var _committed = false + defer { + if !_committed { + buffer.truncate(to: _startCount) + } + } + buffer.writeByte(Self.opCode.rawValue) var sparseCount: Int32 = 0 if id != nil { sparseCount += 1 } if fontSize != nil { sparseCount += 1 } @@ -6673,41 +6936,205 @@ } if let val = fontAxis { buffer.writeByte(UInt8(truncatingIfNeeded: 20)) + guard val.count <= 65535 else { + throw WireError.lengthOutOfRange(field: "fontAxis", length: val.count, min: nil, max: 65535) + } buffer.writeShort(Int16(truncatingIfNeeded: val.count)) for item in val { buffer.writeInt(item) } } + _committed = true + } + + public static func == (lhs: TextStyle, rhs: TextStyle) -> Bool { + return lhs.id == rhs.id + && wireFloatEquals(lhs.fontSize, rhs.fontSize) + && lhs.fontAxis == rhs.fontAxis + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(self.id) + wireFloatHash(self.fontSize, into: &hasher) + hasher.combine(self.fontAxis) } } -/// In-memory representation of a RemoteCompose document. -public struct RemoteDocument { - public static let MAX_HEADER_PROPERTIES: Int = 1000 - public static let MAX_OPERATION_COUNT: Int = 100_000 +/// Closed union of all RemoteCompose wire operations. +public enum WireOperation: Equatable, Hashable, Sendable { + case header(Header) + case drawCircle(DrawCircle) + case floatExpression(FloatExpression) + case bitmapData(BitmapData) + case textData(TextData) + case bitmapFontData(BitmapFontData) + case timeAttribute(TimeAttribute) + case conditionalOperations(ConditionalOperations) + case bitmapTextMeasure(BitmapTextMeasure) + case containerEnd(ContainerEnd) + case textStyle(TextStyle) - public var majorVersion: Int32 = 1 - public var minorVersion: Int32 = 1 - public var patchVersion: Int32 = 0 - public var width: Int32 = 0 - public var height: Int32 = 0 - public var capabilities: Int64 = 0 - public var operations: [RemoteOperation] = [] + public var opCode: OpCode { + switch self { + case .header: return .header + case .drawCircle: return .drawCircle + case .floatExpression: return .floatExpression + case .bitmapData: return .bitmapData + case .textData: return .textData + case .bitmapFontData: return .bitmapFontData + case .timeAttribute: return .timeAttribute + case .conditionalOperations: return .conditionalOperations + case .bitmapTextMeasure: return .bitmapTextMeasure + case .containerEnd: return .containerEnd + case .textStyle: return .textStyle + } + } - public init() {} + public func write(to buffer: inout WireBuffer) throws(WireError) { + switch self { + case .header(let op): try op.write(to: &buffer) + case .drawCircle(let op): try op.write(to: &buffer) + case .floatExpression(let op): try op.write(to: &buffer) + case .bitmapData(let op): try op.write(to: &buffer) + case .textData(let op): try op.write(to: &buffer) + case .bitmapFontData(let op): try op.write(to: &buffer) + case .timeAttribute(let op): try op.write(to: &buffer) + case .conditionalOperations(let op): try op.write(to: &buffer) + case .bitmapTextMeasure(let op): try op.write(to: &buffer) + case .containerEnd(let op): try op.write(to: &buffer) + case .textStyle(let op): try op.write(to: &buffer) + } + } +} - /// Deserializes a RemoteDocument from raw binary data. - public static func load(from data: Data, maxOperations: Int = MAX_OPERATION_COUNT) throws -> RemoteDocument { +/// Typed value stored in a modern (v1.1+) RemoteCompose header property. +public enum HeaderPropertyValue: Equatable, Hashable, Sendable { + case int(Int32) + case float(Float) + case long(Int64) + case string(String) + case unknown(dataType: Int32, payload: [UInt8]) + + public static func == (lhs: HeaderPropertyValue, rhs: HeaderPropertyValue) -> Bool { + switch (lhs, rhs) { + case (.int(let a), .int(let b)): + return a == b + case (.float(let a), .float(let b)): + return wireFloatEquals(a, b) + case (.long(let a), .long(let b)): + return a == b + case (.string(let a), .string(let b)): + return a == b + case (.unknown(let aDt, let aPayload), .unknown(let bDt, let bPayload)): + return aDt == bDt && aPayload == bPayload + default: + return false + } + } + + public func hash(into hasher: inout Hasher) { + switch self { + case .int(let val): + hasher.combine(0) + hasher.combine(val) + case .float(let val): + hasher.combine(1) + wireFloatHash(val, into: &hasher) + case .long(let val): + hasher.combine(2) + hasher.combine(val) + case .string(let val): + hasher.combine(3) + hasher.combine(val) + case .unknown(let dt, let payload): + hasher.combine(4) + hasher.combine(dt) + hasher.combine(payload) + } + } +} + +/// Ordered header property entry in a modern (v1.1+) RemoteCompose document. +public struct WireHeaderProperty: Equatable, Hashable, Sendable { + public var key: Int32 + public var value: HeaderPropertyValue + + public init(key: Int32, value: HeaderPropertyValue) { + self.key = key + self.value = value + } +} + +/// Wire-level representation of a RemoteCompose binary document. +public struct WireDocument: Equatable, Hashable, Sendable { + public static let maxHeaderProperties: Int = 1000 + public static let maxOperationCount: Int = 100_000 + public static let defaultDimension: Int32 = 256 + public static let magicNumber: Int32 = 0x048C_0000 + public static let maxHeaderStringLength: Int = 4000 + + public var majorVersion: Int32 + public var minorVersion: Int32 + public var patchVersion: Int32 + public var width: Int32 + public var height: Int32 + public var capabilities: Int64 + public var isModernHeader: Bool + public var properties: [WireHeaderProperty] + public var operations: [WireOperation] + + public init( + majorVersion: Int32 = 1, + minorVersion: Int32 = 1, + patchVersion: Int32 = 0, + width: Int32? = nil, + height: Int32? = nil, + capabilities: Int64? = nil, + isModernHeader: Bool = false, + properties: [WireHeaderProperty] = [], + operations: [WireOperation] = [] + ) { + let modern = isModernHeader || !properties.isEmpty + var resolvedWidth: Int32 = modern ? Self.defaultDimension : 0 + var resolvedHeight: Int32 = modern ? Self.defaultDimension : 0 + var resolvedCapabilities: Int64 = 0 + for prop in properties { + switch (prop.key, prop.value) { + case (5, .int(let val)): + resolvedWidth = val + case (6, .int(let val)): + resolvedHeight = val + case (14, .int(let val)): + resolvedCapabilities = Int64(UInt32(bitPattern: val)) + case (14, .long(let val)): + resolvedCapabilities = val + default: + break + } + } + self.majorVersion = majorVersion + self.minorVersion = minorVersion + self.patchVersion = patchVersion + self.width = width ?? resolvedWidth + self.height = height ?? resolvedHeight + self.capabilities = capabilities ?? resolvedCapabilities + self.isModernHeader = modern + self.properties = properties + self.operations = operations + } + + /// Deserializes a WireDocument from raw binary bytes. + public static func load(from data: [UInt8], maxOperations: Int = maxOperationCount) throws(WireError) -> WireDocument { return try loadImpl(from: data, maxOperations: maxOperations, evaluateSkip: false, playerApiLevel: 0, playerProfiles: 0) } - /// Deserializes a RemoteDocument evaluating conditional skip operations against the target player. + /// Deserializes a WireDocument evaluating conditional skip operations against the target player. public static func loadForPlayer( - from data: Data, + from data: [UInt8], playerApiLevel: Int32, playerProfiles: Int32 = 0, - maxOperations: Int = MAX_OPERATION_COUNT - ) throws -> RemoteDocument { + maxOperations: Int = maxOperationCount + ) throws(WireError) -> WireDocument { return try loadImpl( from: data, maxOperations: maxOperations, @@ -6718,117 +7145,208 @@ } private static func loadImpl( - from data: Data, + from data: [UInt8], maxOperations: Int, evaluateSkip: Bool, playerApiLevel: Int32, playerProfiles: Int32 - ) throws -> RemoteDocument { + ) throws(WireError) -> WireDocument { var buffer = WireBuffer(data: data) - var doc = RemoteDocument() + var doc = WireDocument() guard buffer.available else { return doc } let headerOp = try buffer.readByte() guard headerOp == OpCode.header.rawValue else { - throw NSError(domain: "RemoteDocument", code: 2, userInfo: [NSLocalizedDescriptionKey: "Expected header opcode"]) + throw WireError.expectedHeaderOpCode(actual: headerOp) } let rawMajor = try buffer.readInt() doc.minorVersion = try buffer.readInt() doc.patchVersion = try buffer.readInt() - if (UInt32(bitPattern: rawMajor) & 0xFFFF0000) == 0x048C0000 { + if (UInt32(bitPattern: rawMajor) & 0xFFFF_0000) == UInt32(bitPattern: magicNumber) { + doc.isModernHeader = true doc.majorVersion = rawMajor & 0xFFFF - doc.width = 256 - doc.height = 256 + doc.width = defaultDimension + doc.height = defaultDimension let numProps = Int(try buffer.readInt()) - guard numProps >= 0 && numProps <= MAX_HEADER_PROPERTIES else { - throw NSError(domain: "RemoteDocument", code: 3, userInfo: [NSLocalizedDescriptionKey: "Invalid header property count: \(numProps)"]) + guard numProps >= 0 && numProps <= maxHeaderProperties else { + throw WireError.lengthOutOfRange(field: "headerProperties", length: numProps, min: 0, max: maxHeaderProperties) } guard numProps <= buffer.remaining / 4 else { - throw NSError(domain: "RemoteDocument", code: 3, userInfo: [NSLocalizedDescriptionKey: "Header property count exceeds remaining buffer"]) + throw WireError.underflow(needed: numProps * 4, remaining: buffer.remaining) } + doc.properties.reserveCapacity(numProps) for _ in 0..<numProps { - let tag = Int32(try buffer.readShort()) - _ = try buffer.readShort() // itemLen (read and ignored) - let dataType = tag >> 10 - let key = tag & 0x3F + let rawTag = try buffer.readShort() + let itemLen = Int(UInt16(bitPattern: try buffer.readShort())) + let dataType = Int32(rawTag) >> 10 + let key = Int32(rawTag) & 0x3F switch dataType { case 0: let val = try buffer.readInt() + doc.properties.append(WireHeaderProperty(key: key, value: .int(val))) if key == 5 { doc.width = val } else if key == 6 { doc.height = val } else if key == 14 { doc.capabilities = Int64(UInt32(bitPattern: val)) } else if key == 31 && val != 0 { - throw NSError(domain: "RemoteDocument", code: 6, userInfo: [NSLocalizedDescriptionKey: "Compressed RemoteCompose documents are not supported"]) + throw WireError.compressedDocumentUnsupported } case 1: - _ = try buffer.readFloat() + let val = try buffer.readFloat() + doc.properties.append(WireHeaderProperty(key: key, value: .float(val))) case 2: let val = try buffer.readLong() + doc.properties.append(WireHeaderProperty(key: key, value: .long(val))) if key == 14 { doc.capabilities = val } else if key == 31 && val != 0 { - throw NSError(domain: "RemoteDocument", code: 6, userInfo: [NSLocalizedDescriptionKey: "Compressed RemoteCompose documents are not supported"]) + throw WireError.compressedDocumentUnsupported } case 3: - _ = try buffer.readUTF8(maxLength: 4000) + let val = try buffer.readUTF8(maxLength: maxHeaderStringLength) + doc.properties.append(WireHeaderProperty(key: key, value: .string(val))) default: - break + let payload = try buffer.readBytes(count: itemLen) + doc.properties.append(WireHeaderProperty(key: key, value: .unknown(dataType: dataType, payload: payload))) } } } else if rawMajor >= 0 && rawMajor < 0x10000 { + doc.isModernHeader = false doc.majorVersion = rawMajor doc.width = try buffer.readInt() doc.height = try buffer.readInt() doc.capabilities = try buffer.readLong() } else { - throw NSError(domain: "RemoteDocument", code: 7, userInfo: [NSLocalizedDescriptionKey: "Invalid header magic number: \(rawMajor)"]) + throw WireError.invalidHeaderMagic(rawMajor) } while buffer.available { guard doc.operations.count < maxOperations else { - throw NSError(domain: "RemoteDocument", code: 8, userInfo: [NSLocalizedDescriptionKey: "Operation count exceeds limit \(maxOperations)"]) + throw WireError.operationCountExceeded(limit: maxOperations) } let opByte = try buffer.readByte() guard let opCode = OpCode(rawValue: opByte) else { - throw NSError(domain: "RemoteDocument", code: 5, userInfo: [NSLocalizedDescriptionKey: "Unknown opcode: \(opByte)"]) + throw WireError.unknownOpCode(opByte) } switch opCode { case .header: - throw NSError(domain: "RemoteDocument", code: 2, userInfo: [NSLocalizedDescriptionKey: "Unexpected Header opcode inside document body"]) + throw WireError.unexpectedHeaderInBody case .drawCircle: - doc.operations.append(try DrawCircle.read(from: &buffer)) + doc.operations.append(.drawCircle(try DrawCircle.read(from: &buffer))) case .floatExpression: - doc.operations.append(try FloatExpression.read(from: &buffer)) + doc.operations.append(.floatExpression(try FloatExpression.read(from: &buffer))) case .bitmapData: - doc.operations.append(try BitmapData.read(from: &buffer)) + doc.operations.append(.bitmapData(try BitmapData.read(from: &buffer))) case .textData: - doc.operations.append(try TextData.read(from: &buffer)) + doc.operations.append(.textData(try TextData.read(from: &buffer))) case .bitmapFontData: - doc.operations.append(try BitmapFontData.read(from: &buffer)) + doc.operations.append(.bitmapFontData(try BitmapFontData.read(from: &buffer))) case .timeAttribute: - doc.operations.append(try TimeAttribute.read(from: &buffer)) + doc.operations.append(.timeAttribute(try TimeAttribute.read(from: &buffer))) case .conditionalOperations: - doc.operations.append(try ConditionalOperations.read(from: &buffer)) + doc.operations.append(.conditionalOperations(try ConditionalOperations.read(from: &buffer))) case .bitmapTextMeasure: - doc.operations.append(try BitmapTextMeasure.read(from: &buffer)) + doc.operations.append(.bitmapTextMeasure(try BitmapTextMeasure.read(from: &buffer))) case .containerEnd: - doc.operations.append(try ContainerEnd.read(from: &buffer)) + doc.operations.append(.containerEnd(try ContainerEnd.read(from: &buffer))) case .textStyle: - doc.operations.append(try TextStyle.read(from: &buffer)) + doc.operations.append(.textStyle(try TextStyle.read(from: &buffer))) } } return doc } - /// Serializes this document to raw binary data. - public func save() throws -> Data { + /// Serializes this document to raw binary bytes, preserving modern headers. + public func save() throws(WireError) -> [UInt8] { + guard majorVersion >= 0 && majorVersion <= 0xFFFF else { + throw WireError.invalidFieldValue(owner: "WireDocument", field: "majorVersion", detail: "majorVersion \(majorVersion) out of range (0..65535)") + } var buffer = WireBuffer() buffer.writeByte(OpCode.header.rawValue) - buffer.writeInt(majorVersion) - buffer.writeInt(minorVersion) - buffer.writeInt(patchVersion) - buffer.writeInt(width) - buffer.writeInt(height) - buffer.writeLong(capabilities) + if isModernHeader || !properties.isEmpty { + var outProps = properties + if let idx = outProps.lastIndex(where: { if $0.key != 5 { return false }; if case .int(_) = $0.value { return true }; return false }) { + outProps[idx].value = .int(width) + } else if width != Self.defaultDimension { + outProps.append(WireHeaderProperty(key: 5, value: .int(width))) + } + if let idx = outProps.lastIndex(where: { if $0.key != 6 { return false }; if case .int(_) = $0.value { return true }; return false }) { + outProps[idx].value = .int(height) + } else if height != Self.defaultDimension { + outProps.append(WireHeaderProperty(key: 6, value: .int(height))) + } + let capValue: HeaderPropertyValue + if capabilities >= 0 && capabilities <= Int64(UInt32.max) { + capValue = .int(Int32(truncatingIfNeeded: capabilities)) + } else { + capValue = .long(capabilities) + } + if let idx = outProps.lastIndex(where: { if $0.key != 14 { return false }; switch $0.value { case .int(_), .long(_): return true; default: return false } }) { + let matchesExisting: Bool + switch outProps[idx].value { + case .int(let existing): + matchesExisting = Int64(UInt32(bitPattern: existing)) == capabilities + case .long(let existing): + matchesExisting = existing == capabilities + default: + matchesExisting = false + } + if !matchesExisting { + outProps[idx].value = capValue + } + } else if capabilities != 0 { + outProps.append(WireHeaderProperty(key: 14, value: capValue)) + } + guard outProps.count <= Self.maxHeaderProperties else { + throw WireError.lengthOutOfRange(field: "headerProperties", length: outProps.count, min: 0, max: Self.maxHeaderProperties) + } + buffer.writeInt(Self.magicNumber | (majorVersion & 0xFFFF)) + buffer.writeInt(minorVersion) + buffer.writeInt(patchVersion) + buffer.writeInt(Int32(outProps.count)) + for prop in outProps { + guard prop.key >= 0 && prop.key <= 0x3F else { + throw WireError.invalidFieldValue(owner: "WireDocument", field: "headerPropertyKey", detail: "Property key \(prop.key) out of range (0..63)") + } + switch prop.value { + case .int(let val): + buffer.writeShort(Int16(truncatingIfNeeded: prop.key & 0x3F)) + buffer.writeShort(4) + buffer.writeInt(val) + case .float(let val): + buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | (1 << 10))) + buffer.writeShort(4) + buffer.writeFloat(val) + case .long(let val): + buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | (2 << 10))) + buffer.writeShort(8) + buffer.writeLong(val) + case .string(let val): + let utf8Count = val.utf8.count + guard utf8Count <= Self.maxHeaderStringLength else { + throw WireError.lengthOutOfRange(field: "headerStringProperty", length: utf8Count, min: nil, max: Self.maxHeaderStringLength) + } + buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | (3 << 10))) + buffer.writeShort(Int16(truncatingIfNeeded: utf8Count + 4)) + try buffer.writeUTF8(val, maxLength: Self.maxHeaderStringLength) + case .unknown(let dt, let payload): + guard dt >= -32 && dt <= 31 && (dt < 0 || dt > 3) else { + throw WireError.invalidFieldValue(owner: "WireDocument", field: "headerPropertyDataType", detail: "Unknown dataType \(dt) out of range") + } + guard payload.count <= Int(UInt16.max) else { + throw WireError.lengthOutOfRange(field: "headerUnknownProperty", length: payload.count, min: nil, max: Int(UInt16.max)) + } + buffer.writeShort(Int16(truncatingIfNeeded: (prop.key & 0x3F) | ((dt & 0x3F) << 10))) + buffer.writeShort(Int16(truncatingIfNeeded: payload.count)) + buffer.writeBytes(payload) + } + } + } else { + buffer.writeInt(majorVersion) + buffer.writeInt(minorVersion) + buffer.writeInt(patchVersion) + buffer.writeInt(width) + buffer.writeInt(height) + buffer.writeLong(capabilities) + } for op in operations { try op.write(to: &buffer)
diff --git a/compose/remote/remote-player-compose/src/androidTest/java/androidx/compose/remote/player/compose/embedded/RcPlayerRcDocScreenshotTest.kt b/compose/remote/remote-player-compose/src/androidTest/java/androidx/compose/remote/player/compose/embedded/RcPlayerRcDocScreenshotTest.kt new file mode 100644 index 0000000..1641529c4 --- /dev/null +++ b/compose/remote/remote-player-compose/src/androidTest/java/androidx/compose/remote/player/compose/embedded/RcPlayerRcDocScreenshotTest.kt
@@ -0,0 +1,202 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:Suppress("RestrictedApiAndroidX") +@file:OptIn(ExperimentalRemotePlayerApi::class) + +package androidx.compose.remote.player.compose.embedded + +import android.graphics.Color as AndroidColor +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.RcProfiles +import androidx.compose.remote.core.RemoteComposeBuffer +import androidx.compose.remote.core.operations.layout.managers.BoxLayout +import androidx.compose.remote.core.operations.layout.managers.ColumnLayout +import androidx.compose.remote.core.operations.layout.managers.CoreText +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.RemoteComposeWriterAndroid +import androidx.compose.remote.creation.modifiers.RecordingModifier +import androidx.compose.remote.creation.modifiers.RoundedRectShape +import androidx.compose.remote.creation.platform.AndroidxRcPlatformServices +import androidx.compose.remote.player.compose.ExperimentalRemotePlayerApi +import androidx.compose.testutils.assertAgainstGolden +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.unit.dp +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.MediumTest +import androidx.test.filters.SdkSuppress +import androidx.test.screenshot.AndroidXScreenshotTestRule +import java.io.ByteArrayInputStream +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** Screenshot tests for embedded [RcDocLayout] documents rendered in [RcPlayer]. */ +@MediumTest +@SdkSuppress(minSdkVersion = 35, maxSdkVersion = 35) +@RunWith(AndroidJUnit4::class) +class RcPlayerRcDocScreenshotTest { + + @get:Rule val rule = RcPlayerTestRule() + + @get:Rule val screenshotRule = AndroidXScreenshotTestRule(SCREENSHOT_GOLDEN_DIRECTORY) + + private fun buildBytes( + width: Int, + height: Int, + block: RemoteComposeWriter.() -> Unit, + ): ByteArray { + val writer = + RemoteComposeWriterAndroid( + width, + height, + "EmbeddedScreenshotDoc", + CoreDocument.DOCUMENT_API_LEVEL, + RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL, + AndroidxRcPlatformServices(), + ) + writer.block() + return writer.encodeToByteArray() + } + + private fun RemoteComposeWriter.addLabel( + textId: Int, + color: Int = AndroidColor.WHITE, + fontSize: Float = 24f, + ) { + textComponent( + RecordingModifier(), + textId, + color, + fontSize, + 0, + 600f, + null, + CoreText.TEXT_ALIGN_LEFT, + CoreText.OVERFLOW_CLIP, + 1, + ) {} + } + + @Test + fun embeddedDocuments_resolvedAndInlineWithVariableMapping() { + val resolvedChildBytes = + buildBytes(width = 360, height = 120) { + val titleId = addNamedString("title", "Default") + root { + box( + RecordingModifier() + .fillMaxSize() + .clip(RoundedRectShape(16f, 16f, 16f, 16f)) + .background(0xFF1D4ED8.toInt()) + .padding(16), + BoxLayout.START, + BoxLayout.CENTER, + ) { + addLabel(titleId, color = AndroidColor.WHITE, fontSize = 26f) + } + } + } + + val inlineChildBytes = + buildBytes(width = 360, height = 120) { + val badgeId = addNamedString("badge", "Inline") + root { + box( + RecordingModifier() + .fillMaxSize() + .clip(RoundedRectShape(16f, 16f, 16f, 16f)) + .background(0xFF047857.toInt()) + .padding(16), + BoxLayout.START, + BoxLayout.CENTER, + ) { + addLabel(badgeId, color = AndroidColor.WHITE, fontSize = 26f) + } + } + } + + val hostBytes = + buildBytes(width = 400, height = 340) { + val headerId = addText("Parent Document") + val resolvedTitle = addNamedString("resolvedTitle", "Resolved Child (Mapped)") + val inlineBadge = addNamedString("inlineBadge", "Inline BinaryData Child") + val inlineDocId = addEmbeddedDocument(inlineChildBytes) + + root { + column( + RecordingModifier() + .fillMaxSize() + .background(0xFF0F172A.toInt()) + .padding(20), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + addLabel(headerId, color = AndroidColor.WHITE, fontSize = 28f) + box(RecordingModifier().size(1, 16)) + val resolvedId = + rcDoc("screenshot://resolved", RecordingModifier().size(360, 110)) + mapRcDocVariables( + resolvedId, + RemoteComposeWriter.MAP_FORWARD, + resolvedTitle, + "title", + ) + box(RecordingModifier().size(1, 16)) + val embeddedId = rcDoc(inlineDocId, RecordingModifier().size(360, 110)) + mapRcDocVariables( + embeddedId, + RemoteComposeWriter.MAP_FORWARD, + inlineBadge, + "badge", + ) + } + } + } + + val hostDoc = + CoreDocument().apply { + ByteArrayInputStream(hostBytes).use { + initFromBuffer(RemoteComposeBuffer.fromInputStream(it)) + } + } + + rule.setContent { + Box(modifier = Modifier.size(200.dp, 170.dp)) { + RcPlayer( + document = hostDoc, + documentResolver = + RcDocumentResolver { url -> + if (url == "screenshot://resolved") resolvedChildBytes else null + }, + ) + } + } + + rule.waitForIdle() + rule + .onRoot() + .captureToImage() + .assertAgainstGolden( + screenshotRule, + "RcPlayerRcDocScreenshotTest_embeddedDocuments", + ) + } +}
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/ExperimentalRemoteDocumentPlayer.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/ExperimentalRemoteDocumentPlayer.kt index fca9dd7..59e693c 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/ExperimentalRemoteDocumentPlayer.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/ExperimentalRemoteDocumentPlayer.kt
@@ -45,6 +45,7 @@ onNamedAction: (name: String, value: Any?, stateUpdater: StateUpdater) -> Unit = { _, _, _ -> }, theme: Int = Theme.SYSTEM, customPlugins: CustomPluginRegistry? = null, + documentResolver: RcDocumentResolver? = LocalRcDocumentResolver.current, ) { RcPlayer( document = document.document, @@ -55,5 +56,6 @@ onNamedAction = onNamedAction, theme = theme, customPlugins = customPlugins, + documentResolver = documentResolver, ) }
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcDocumentResolver.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcDocumentResolver.kt new file mode 100644 index 0000000..a6cb195 --- /dev/null +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcDocumentResolver.kt
@@ -0,0 +1,53 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.player.compose.embedded + +import androidx.annotation.RestrictTo +import androidx.compose.runtime.ProvidableCompositionLocal +import androidx.compose.runtime.Stable +import androidx.compose.runtime.compositionLocalOf + +/** + * Pluggable resolver for embedded RemoteCompose documents referenced by URL in `RcDocLayout`. + * + * Resolving a URL to serialized RemoteCompose document bytes is the responsibility of the host + * application (for example reading raw resources, app assets, local disk caches, or fetching from + * the network). Returning `null` indicates that the URL cannot be resolved or is not permitted by + * the host. + * + * [resolve] is a `suspend` function so hosts can perform off-main-thread I/O without blocking + * composition. + */ +@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +@Stable +public fun interface RcDocumentResolver { + /** + * Resolves the given [url] or document identifier into serialized RemoteCompose document bytes, + * or `null` if unavailable. + */ + public suspend fun resolve(url: String): ByteArray? +} + +/** + * The active [RcDocumentResolver] for resolving embedded RemoteCompose documents in [RcPlayer]. + * Inherited automatically by nested [RcPlayer] instances. + */ +@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public val LocalRcDocumentResolver: ProvidableCompositionLocal<RcDocumentResolver?> = + compositionLocalOf { + null + }
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayer.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayer.kt index b614a03..48b7411 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayer.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayer.kt
@@ -116,12 +116,14 @@ pendingIntents: IntObjectMap<PendingIntent> = emptyIntObjectMap(), typefaceResolver: RcTypefaceResolver? = LocalRcTypefaceResolver.current, theme: Int = Theme.SYSTEM, + documentResolver: RcDocumentResolver? = LocalRcDocumentResolver.current, ) { val features = remember(state.document) { RcPlayerFeatures.forProfiles(state.document.profileMask) } RcPlayerImpl( state = state, features = features, + featureResolver = RcPlayerFeatures::forProfiles, modifier = modifier, imageLoader = imageLoader, trustedContent = trustedContent, @@ -132,6 +134,7 @@ pendingIntents = pendingIntents, typefaceResolver = typefaceResolver, theme = theme, + documentResolver = documentResolver, ) } @@ -161,6 +164,7 @@ pendingIntents: IntObjectMap<PendingIntent> = emptyIntObjectMap(), typefaceResolver: RcTypefaceResolver? = LocalRcTypefaceResolver.current, theme: Int = Theme.SYSTEM, + documentResolver: RcDocumentResolver? = LocalRcDocumentResolver.current, ) { RcPlayerImpl( state = state, @@ -175,6 +179,7 @@ pendingIntents = pendingIntents, typefaceResolver = typefaceResolver, theme = theme, + documentResolver = documentResolver, ) } @@ -194,6 +199,8 @@ pendingIntents: IntObjectMap<PendingIntent> = emptyIntObjectMap(), typefaceResolver: RcTypefaceResolver? = LocalRcTypefaceResolver.current, theme: Int = Theme.SYSTEM, + documentResolver: RcDocumentResolver? = LocalRcDocumentResolver.current, + featureResolver: ((Int) -> RcPlayerFeatureSet)? = null, ) { check(RemoteComposePlayerFlags.isEmbeddedPlayerEnabled) { "Embedded player is disabled. Set RemoteComposePlayerFlags.isEmbeddedPlayerEnabled = true to enable." @@ -540,8 +547,15 @@ onNamedAction(name, value, stateUpdater) } }, + LocalHostRemoteActionHandler provides onAction, + LocalHostRemoteNamedActionHandler provides onNamedAction, LocalRcCustomPlugins provides customPlugins, LocalRcTypefaceResolver provides typefaceResolver, + LocalRcDocumentResolver provides documentResolver, + LocalRcDocMappingsMap provides preprocessed.rcDocMappingsMap, + LocalRcPlayerFeatures provides features, + LocalRcPlayerFeatureResolver provides featureResolver, + LocalRcPlayerTheme provides theme, ) { val animatedExpressionIds = remember(document) { @@ -604,6 +618,7 @@ pendingIntents: IntObjectMap<PendingIntent> = emptyIntObjectMap(), typefaceResolver: RcTypefaceResolver? = LocalRcTypefaceResolver.current, theme: Int = Theme.SYSTEM, + documentResolver: RcDocumentResolver? = LocalRcDocumentResolver.current, ) { val state = rememberRcPlayerState(document) RcPlayer( @@ -618,6 +633,7 @@ pendingIntents = pendingIntents, typefaceResolver = typefaceResolver, theme = theme, + documentResolver = documentResolver, ) } @@ -642,6 +658,7 @@ pendingIntents: IntObjectMap<PendingIntent> = emptyIntObjectMap(), typefaceResolver: RcTypefaceResolver? = LocalRcTypefaceResolver.current, theme: Int = Theme.SYSTEM, + documentResolver: RcDocumentResolver? = LocalRcDocumentResolver.current, ) { val state = rememberRcPlayerState(document) RcPlayerImpl( @@ -657,6 +674,7 @@ pendingIntents = pendingIntents, typefaceResolver = typefaceResolver, theme = theme, + documentResolver = documentResolver, ) } @@ -680,6 +698,7 @@ customPlugins: CustomPluginRegistry? = null, typefaceResolver: RcTypefaceResolver? = LocalRcTypefaceResolver.current, theme: Int = Theme.SYSTEM, + documentResolver: RcDocumentResolver? = LocalRcDocumentResolver.current, ) { val state = rememberRcPlayerState(capturedDocument) RcPlayer( @@ -694,5 +713,6 @@ pendingIntents = capturedDocument.pendingIntents, typefaceResolver = typefaceResolver, theme = theme, + documentResolver = documentResolver, ) }
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerCompositionLocals.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerCompositionLocals.kt index 31c4a6b0..f02c215 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerCompositionLocals.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerCompositionLocals.kt
@@ -25,8 +25,12 @@ import androidx.compose.remote.core.CoreDocument import androidx.compose.remote.core.RemoteContext import androidx.compose.remote.core.operations.ComponentValue +import androidx.compose.remote.core.operations.MapRcDocVariables +import androidx.compose.remote.core.operations.Theme import androidx.compose.remote.core.operations.TouchExpression +import androidx.compose.remote.player.compose.ExperimentalRemotePlayerApi import androidx.compose.remote.player.compose.embedded.doc.GraphContext +import androidx.compose.remote.player.core.state.StateUpdater import androidx.compose.runtime.MutableState import androidx.compose.runtime.ProvidableCompositionLocal import androidx.compose.runtime.State @@ -108,6 +112,26 @@ } /** + * Raw host `onAction` callback without parent `PendingIntentAction` interception, used by embedded + * child documents so untrusted child action IDs cannot invoke parent `PendingIntent`s. + */ +internal val LocalHostRemoteActionHandler: ProvidableCompositionLocal<(Int, String?) -> Unit> = + compositionLocalOf { + { _, _ -> } + } + +/** + * Raw host `onNamedAction` callback without parent `LambdaAction` / `PendingIntentAction` + * interception, used by embedded child documents so untrusted child actions cannot invoke parent + * closures or `PendingIntent`s. + */ +internal val LocalHostRemoteNamedActionHandler: + ProvidableCompositionLocal<(String, Any?, StateUpdater) -> Unit> = + compositionLocalOf { + { _, _, _ -> } + } + +/** * [RcTypefaceResolver] for resolving typefaces in the embedded player. Null when using the default * built-in resolver. */ @@ -130,7 +154,6 @@ compositionLocalOf { null } - /** * True when composing unplaced `FitBoxSlot.Probe` measurement candidates so probe subtrees do not * allocate interaction/ripple nodes or register duplicate Compose focus targets. @@ -138,3 +161,42 @@ internal val LocalRcIsMeasureProbe: ProvidableCompositionLocal<Boolean> = compositionLocalOf { false } + +internal const val DEFAULT_MAX_RC_DOC_NESTING_DEPTH: Int = 1 + +/** + * Maximum nesting depth for embedded `RcDocLayout` documents in [RcPlayer]. Defaults to `1` (host + * -> child only). Set to `0` to disable embedded documents, or a higher value (e.g. `2` for + * grandchildren) to permit deeper nesting. + */ +@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) +public val LocalRcDocMaxNestingDepth: ProvidableCompositionLocal<Int> = compositionLocalOf { + DEFAULT_MAX_RC_DOC_NESTING_DEPTH +} + +internal val LocalRcDocMappingsMap: ProvidableCompositionLocal<Map<Int, List<MapRcDocVariables>>> = + compositionLocalOf { + emptyMap() + } + +@OptIn(ExperimentalRemotePlayerApi::class) +internal val LocalRcPlayerFeatures: ProvidableCompositionLocal<RcPlayerFeatureSet> = + compositionLocalOf { + RcPlayerFeatureSet.Empty + } + +/** + * Resolves an [RcPlayerFeatureSet] for an embedded child's `profileMask` when the host `RcPlayer` + * did not pin an explicit [RcPlayerFeatureSet]. Null for pinned players so R8 can strip unused + * features. + */ +@OptIn(ExperimentalRemotePlayerApi::class) +internal val LocalRcPlayerFeatureResolver: + ProvidableCompositionLocal<((Int) -> RcPlayerFeatureSet)?> = + compositionLocalOf { + null + } + +internal val LocalRcPlayerTheme: ProvidableCompositionLocal<Int> = compositionLocalOf { + Theme.SYSTEM +}
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerFeatureSet.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerFeatureSet.kt index 3ad43c3..f895701 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerFeatureSet.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/RcPlayerFeatureSet.kt
@@ -123,8 +123,12 @@ Operations.LAYOUT_FLOW, Operations.LAYOUT_CUSTOM, Operations.LAYOUT_TEXT_INPUT, + Operations.LAYOUT_RC_DOC, + Operations.MAP_RC_DOC_VARIABLES, + Operations.BINARY_DATA, Operations.MODIFIER_MULTI_CLICK, Operations.MODIFIER_DIMENSION_CONSTRAINTS, + Operations.MODIFIER_EVENT_HANDLER, ) /**
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/components/RcPlayerComponents.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/components/RcPlayerComponents.kt index ee78292..267f927 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/components/RcPlayerComponents.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/components/RcPlayerComponents.kt
@@ -22,6 +22,8 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.operations.BinaryData +import androidx.compose.remote.core.operations.MapRcDocVariables import androidx.compose.remote.core.operations.RootContentBehavior import androidx.compose.remote.core.operations.layout.Component import androidx.compose.remote.core.operations.layout.LayoutComponent @@ -35,6 +37,7 @@ import androidx.compose.remote.core.operations.layout.managers.FitBoxLayout import androidx.compose.remote.core.operations.layout.managers.FlowLayout import androidx.compose.remote.core.operations.layout.managers.ImageLayout +import androidx.compose.remote.core.operations.layout.managers.RcDocLayout import androidx.compose.remote.core.operations.layout.managers.RowLayout import androidx.compose.remote.core.operations.layout.managers.StateLayout import androidx.compose.remote.core.operations.layout.managers.TextInputLayout @@ -58,10 +61,13 @@ import androidx.compose.remote.player.compose.embedded.layout.RcPlayerFitBoxLayout import androidx.compose.remote.player.compose.embedded.layout.RcPlayerFlowRow import androidx.compose.remote.player.compose.embedded.layout.RcPlayerImageLayout +import androidx.compose.remote.player.compose.embedded.layout.RcPlayerRcDoc import androidx.compose.remote.player.compose.embedded.layout.RcPlayerRow import androidx.compose.remote.player.compose.embedded.layout.RcPlayerStateLayout import androidx.compose.remote.player.compose.embedded.layout.RcPlayerTextInputLayout import androidx.compose.remote.player.compose.embedded.modifier.ClickActionHandlers +import androidx.compose.remote.player.compose.embedded.modifier.keyEventActions +import androidx.compose.remote.player.compose.embedded.modifier.pointerEventActions import androidx.compose.remote.player.compose.embedded.modifier.toModifier import androidx.compose.remote.player.compose.embedded.state.rememberRemoteFloatAsState import androidx.compose.runtime.Composable @@ -160,7 +166,12 @@ val remoteContext = LocalRemoteContext.current val graph = LocalGraphContext.current - val drawOps = remember(root) { root.list.fastFilter { it !is Component } } + val drawOps = + remember(root) { + root.list.fastFilter { + it !is Component && it !is MapRcDocVariables && it !is BinaryData + } + } if (drawOps.isNotEmpty()) { val textMeasurer = rememberTextMeasurer() Canvas(modifier = Modifier.fillMaxSize()) { @@ -231,6 +242,13 @@ // modifiers and outside the component's own modifiers. val contentModifier = Modifier.rcComponentOuterInspector(component) + // Outside the component's modifiers, so key events from a focus target they add + // (e.g. a clickable) bubble up to the handlers. + .keyEventActions(component) + // Outside the component's modifiers (incl. PaddingModifierOperation), so hit + // testing covers the component's outer bounds and local coordinates match + // PointerInputRouter's component-local origin. + .pointerEventActions(component) .then( component.componentModifiers.toModifier( component.drawContentOperations?.list, @@ -409,6 +427,7 @@ is StateLayout -> RcPlayerStateLayout(component, modifier) is TextInputLayout -> RcPlayerTextInputLayout(component, modifier) is ImageLayout -> RcPlayerImageLayout(component, modifier) + is RcDocLayout -> RcPlayerRcDoc(component, modifier) is Custom -> RcPlayerCustom(component, modifier, customClickHandlers) // Last as others are often BoxLayout subclasses is BoxLayout -> RcPlayerBox(component, modifier)
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/CoreDataAccessors.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/CoreDataAccessors.kt index 4ff5a8a..c24005e 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/CoreDataAccessors.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/CoreDataAccessors.kt
@@ -28,6 +28,7 @@ import androidx.compose.remote.core.operations.ComponentData import androidx.compose.remote.core.operations.FloatFunctionDefine import androidx.compose.remote.core.operations.FontData +import androidx.compose.remote.core.operations.MapRcDocVariables import androidx.compose.remote.core.operations.PathData import androidx.compose.remote.core.operations.SoundData import androidx.compose.remote.core.operations.SoundExpression @@ -37,6 +38,7 @@ import androidx.compose.remote.core.operations.layout.ImpulseOperation import androidx.compose.remote.core.operations.layout.LayoutComponent import androidx.compose.remote.core.operations.layout.LoopOperation +import androidx.compose.remote.core.operations.layout.managers.RcDocLayout import androidx.compose.remote.player.core.platform.AndroidRemoteContext import java.util.ArrayList @@ -96,6 +98,21 @@ registerImpulseResources(context, op) continue } + if (op is RcDocLayout) { + // RcPlayerRcDoc loads and manages the child document itself via a nested RcPlayer; + // calling RcDocLayout.updateVariables here would eagerly parse a second copy. + op.markNotDirty() + context.incrementOpCount() + applyOperationsWithoutBitmaps(context, op.list) + continue + } + if (op is MapRcDocVariables) { + // RcPlayerRcDoc collects mappings via preprocessing; applying them here would populate + // RcDocLayout.mMappings and allow core updateVariables passes to overwrite host state. + op.markNotDirty() + context.incrementOpCount() + continue + } if (op is VariableSupport) { op.updateVariables(context) } @@ -257,6 +274,32 @@ } } +internal fun CoreDocument.updateVariablesWithoutRcDoc( + context: RemoteContext, + operations: List<Operation>, +) { + for (i in operations.indices) { + val op = operations[i] + if (op is RcDocLayout) { + op.markNotDirty() + updateVariablesWithoutRcDoc(context, op.list) + continue + } + if (op is MapRcDocVariables) { + op.markNotDirty() + continue + } + if (op.isDirty && op is VariableSupport) { + op.markNotDirty() + op.updateVariables(context) + op.apply(context) + } + if (op is Container) { + updateVariablesWithoutRcDoc(context, op.list) + } + } +} + internal fun PathData.applyTrackingPathChange(context: RemoteContext) { val outputPath = getOutputPath() if (context.getPathData(getId()) !== outputPath) {
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/RcPlayerPreprocess.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/RcPlayerPreprocess.kt index 7306d4d..616470e 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/RcPlayerPreprocess.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/RcPlayerPreprocess.kt
@@ -36,6 +36,7 @@ import androidx.compose.remote.core.RemoteContext import androidx.compose.remote.core.VariableProvider import androidx.compose.remote.core.VariableSupport +import androidx.compose.remote.core.operations.BinaryData import androidx.compose.remote.core.operations.BitmapTextMeasure import androidx.compose.remote.core.operations.ColorConstant import androidx.compose.remote.core.operations.ColorTheme @@ -48,6 +49,7 @@ import androidx.compose.remote.core.operations.IdLookup import androidx.compose.remote.core.operations.ImageAttribute import androidx.compose.remote.core.operations.IntegerExpression +import androidx.compose.remote.core.operations.MapRcDocVariables import androidx.compose.remote.core.operations.NamedVariable import androidx.compose.remote.core.operations.PaintData import androidx.compose.remote.core.operations.ParticlesCompare @@ -78,6 +80,7 @@ import androidx.compose.remote.core.operations.layout.managers.StateLayout import androidx.compose.remote.core.operations.layout.modifiers.ComponentModifiers import androidx.compose.remote.core.operations.layout.modifiers.ComponentVisibilityOperation +import androidx.compose.remote.core.operations.layout.modifiers.EventHandlerModifierOperation import androidx.compose.remote.core.operations.layout.modifiers.ScrollModifierOperation import androidx.compose.remote.core.operations.matrix.MatrixConstant import androidx.compose.remote.core.operations.matrix.MatrixExpression @@ -87,6 +90,7 @@ import androidx.compose.remote.core.types.LongConstant import androidx.compose.remote.player.compose.embedded.components.rootTouchExpressions import androidx.compose.remote.player.compose.embedded.draw.TextMeasurePaintSpec +import androidx.compose.remote.player.compose.embedded.modifier.parseEventHandler import androidx.compose.remote.player.compose.embedded.state.MaybeVariableFloat import androidx.compose.remote.player.compose.embedded.state.anyScalarReference import androidx.compose.remote.player.compose.embedded.state.forEachScalarReference @@ -129,6 +133,8 @@ * it from inputs that have since moved on. */ val streamFloatIds: IntSet = emptyIntSet(), + /** [MapRcDocVariables] mappings grouped by their target `RcDocLayout` component ID. */ + val rcDocMappingsMap: Map<Int, List<MapRcDocVariables>> = emptyMap(), ) /** @@ -151,6 +157,7 @@ } else if ( op is VariableSupport && op is VariableProvider && + op !is BinaryData && op !is MatrixExpression && op !is MatrixConstant ) { @@ -198,6 +205,7 @@ var currentTextPaintSpec = TextMeasurePaintSpec.Empty val touchExpressionIds = mutableIntSetOf() val rawComponentValues = ArrayList<ComponentValue>() + val rcDocMappingsMap = HashMap<Int, MutableList<MapRcDocVariables>>() val componentsById = mutableIntObjectMapOf<Component>() var hasParticles = false var hasWakeIn = false @@ -214,6 +222,17 @@ // The first expression assigned to each float id; the same operation can be visited twice. val firstAssignments = mutableIntObjectMapOf<Operation>() + fun recordListenedVariableId(id: Int) { + if (isTouchPositionVariable(id)) { + readsTouchPosition = true + } else if (isContinuousTimeVariable(id)) { + hasContinuousTime = true + } else if (isDiscreteTimeVariable(id)) { + hasDiscreteTime = true + discreteTimeMask = discreteTimeMask or (1 shl discreteTimeIndex(id)) + } + } + fun collectFunctionWrites(ops: List<Operation>) { ops.fastForEach { op -> // Register names declared in the body at setup, so a host can set them before the @@ -278,26 +297,26 @@ // Collect direct references to continuous or discrete time variables from expressions // and variable-reading operations so we know which clock loop (if any) needs to run. - if (op is StateLayout) { - // StateLayout does not implement VariableSupport, so inspect its indexId directly. - val id = op.indexId - if (isContinuousTimeVariable(id)) { - hasContinuousTime = true - } else if (isDiscreteTimeVariable(id)) { - hasDiscreteTime = true - discreteTimeMask = discreteTimeMask or (1 shl discreteTimeIndex(id)) - } - } else { - forEachListenedVariableId(op) { id -> - if (isTouchPositionVariable(id)) { - readsTouchPosition = true - } else if (isContinuousTimeVariable(id)) { + when (op) { + is StateLayout -> { + // StateLayout does not implement VariableSupport, so inspect its indexId + // directly. + val id = op.indexId + if (isContinuousTimeVariable(id)) { hasContinuousTime = true } else if (isDiscreteTimeVariable(id)) { hasDiscreteTime = true discreteTimeMask = discreteTimeMask or (1 shl discreteTimeIndex(id)) } } + is EventHandlerModifierOperation -> { + // EventHandlerModifierOperation does not implement VariableSupport, so inspect + // its condition expression directly for time or touch-position variables. + op.parseEventHandler() + .condition + ?.forEachScalarReference(::recordListenedVariableId) + } + else -> forEachListenedVariableId(op, ::recordListenedVariableId) } if (op is TimeAttribute) { @@ -386,6 +405,7 @@ } else if ( op is VariableSupport && op is VariableProvider && + op !is BinaryData && op !is PathData && op !is PathCreate && op !is PathCombine && @@ -449,6 +469,13 @@ rawComponentValues.add(op) } + if (op is MapRcDocVariables) { + val list = rcDocMappingsMap.getOrPut(op.docId) { ArrayList() } + if (!list.contains(op)) { + list.add(op) + } + } + if (op is Component) { if (op.componentId !in componentsById) { componentsById[op.componentId] = op @@ -562,6 +589,7 @@ discreteTimeMask = discreteTimeMask, readsTouchPosition = readsTouchPosition, streamFloatIds = streamFloatIds, + rcDocMappingsMap = rcDocMappingsMap, ) }
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/SnapshotRemoteComposeState.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/SnapshotRemoteComposeState.kt index b94eee5..5dec575 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/SnapshotRemoteComposeState.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/doc/SnapshotRemoteComposeState.kt
@@ -22,7 +22,10 @@ import androidx.collection.IntSet import androidx.collection.emptyIntSet import androidx.compose.remote.core.RemoteComposeState +import androidx.compose.remote.core.VariableSupport import androidx.compose.remote.core.operations.BitmapData +import androidx.compose.remote.core.operations.MapRcDocVariables +import androidx.compose.remote.core.operations.layout.managers.RcDocLayout import androidx.compose.remote.core.operations.utilities.ArrayAccess import androidx.compose.remote.player.compose.embedded.resources.setDimensions import androidx.compose.runtime.getValue @@ -70,6 +73,16 @@ */ internal var streamFloatIds: IntSet = emptyIntSet() + override fun listenToVar(id: Int, variableSupport: VariableSupport) { + // RcPlayerRcDoc manages child documents and variable mappings reactively in Compose; + // skipping core listener registration prevents CoreDocument.updateVariables from parsing a + // phantom child copy or overwriting mapped variables with stale defaults. + if (variableSupport is RcDocLayout || variableSupport is MapRcDocVariables) { + return + } + super.listenToVar(id, variableSupport) + } + // --- Float --- override fun getFloat(id: Int): Float { if (streamFloatIds.contains(id)) return super.getFloat(id)
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/layout/RcPlayerRcDoc.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/layout/RcPlayerRcDoc.kt new file mode 100644 index 0000000..7692ff0 --- /dev/null +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/layout/RcPlayerRcDoc.kt
@@ -0,0 +1,669 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:Suppress("PrimitiveInCollection") +@file:OptIn(ExperimentalRemotePlayerApi::class) + +package androidx.compose.remote.player.compose.embedded.layout + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.RemoteComposeBuffer +import androidx.compose.remote.core.RemoteContext +import androidx.compose.remote.core.operations.BinaryData +import androidx.compose.remote.core.operations.Header +import androidx.compose.remote.core.operations.MapRcDocVariables +import androidx.compose.remote.core.operations.NamedVariable +import androidx.compose.remote.core.operations.layout.managers.RcDocLayout +import androidx.compose.remote.player.compose.ExperimentalRemotePlayerApi +import androidx.compose.remote.player.compose.embedded.LocalCoreDocument +import androidx.compose.remote.player.compose.embedded.LocalGraphContext +import androidx.compose.remote.player.compose.embedded.LocalHostRemoteActionHandler +import androidx.compose.remote.player.compose.embedded.LocalHostRemoteNamedActionHandler +import androidx.compose.remote.player.compose.embedded.LocalRcCustomPlugins +import androidx.compose.remote.player.compose.embedded.LocalRcDocMappingsMap +import androidx.compose.remote.player.compose.embedded.LocalRcDocMaxNestingDepth +import androidx.compose.remote.player.compose.embedded.LocalRcDocumentResolver +import androidx.compose.remote.player.compose.embedded.LocalRcIsMeasureProbe +import androidx.compose.remote.player.compose.embedded.LocalRcPlayerFeatureResolver +import androidx.compose.remote.player.compose.embedded.LocalRcPlayerFeatures +import androidx.compose.remote.player.compose.embedded.LocalRcPlayerTheme +import androidx.compose.remote.player.compose.embedded.LocalRcTypefaceResolver +import androidx.compose.remote.player.compose.embedded.LocalRemoteContext +import androidx.compose.remote.player.compose.embedded.RcDocumentResolver +import androidx.compose.remote.player.compose.embedded.RcPlayerImpl +import androidx.compose.remote.player.compose.embedded.RcPlayerState +import androidx.compose.remote.player.compose.embedded.doc.SnapshotRemoteComposeState +import androidx.compose.remote.player.compose.embedded.doc.rawDimensionDp +import androidx.compose.remote.player.compose.embedded.state.rememberRemoteStringAsState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.snapshotFlow +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.util.fastAny +import androidx.compose.ui.util.fastFirstOrNull +import androidx.compose.ui.util.fastForEach +import java.io.ByteArrayInputStream +import kotlinx.coroutines.CancellationException + +private val LocalRcDocNestingDepth = compositionLocalOf { 0 } + +private data class ChildHeaderDimensions( + val width: Int, + val height: Int, + val densityBehavior: Int, +) + +private class ParsedChildDocument( + val state: RcPlayerState, + val headerDimensions: ChildHeaderDimensions, +) + +private fun extractHeaderDimensions(doc: CoreDocument): ChildHeaderDimensions { + val header = doc.operations.fastFirstOrNull { it is Header } as? Header + val width = + (doc.getProperty(Header.DOC_WIDTH) as? Int)?.takeIf { it > 0 } + ?: header?.getInt(Header.DOC_WIDTH.toInt(), 0)?.takeIf { it > 0 } + ?: doc.width.takeIf { it > 0 } + ?: 0 + val height = + (doc.getProperty(Header.DOC_HEIGHT) as? Int)?.takeIf { it > 0 } + ?: header?.getInt(Header.DOC_HEIGHT.toInt(), 0)?.takeIf { it > 0 } + ?: doc.height.takeIf { it > 0 } + ?: 0 + return ChildHeaderDimensions( + width = width, + height = height, + densityBehavior = doc.densityBehavior, + ) +} + +/** + * Embedded Compose player implementation of [RcDocLayout]: resolves the embedded document bytes + * (from an inline [BinaryData] blob or the host [RcDocumentResolver]), instantiates a nested + * [RcPlayerImpl] with isolated state, and synchronizes [MapRcDocVariables] bindings and + * `HostAction` interceptions across the parent/child boundary. + */ +@Composable +internal fun RcPlayerRcDoc(layout: RcDocLayout, modifier: Modifier) { + val depth = LocalRcDocNestingDepth.current + val maxDepth = LocalRcDocMaxNestingDepth.current + if (depth >= maxDepth) { + return + } + + val isMeasureProbe = LocalRcIsMeasureProbe.current + val parentDoc = LocalCoreDocument.current + val hostRemoteContext = LocalRemoteContext.current + val hostReadContext: RemoteContext = LocalGraphContext.current ?: hostRemoteContext + val documentResolver = LocalRcDocumentResolver.current + val mappings = LocalRcDocMappingsMap.current[layout.componentId].orEmpty() + + // 1. Check whether urlId points directly to a TYPE_RC_DOC BinaryData blob. + val directBlob = + (hostRemoteContext.getObject(layout.urlId) as? BinaryData)?.takeIf { + it.type == BinaryData.TYPE_RC_DOC + } + + // 2. Otherwise read the URL string reactively, checking rc:embedded/<id> before resolving + // asynchronously via RcDocumentResolver. + val resolvedBytes: ByteArray? + val isInlineBlob: Boolean + if (directBlob != null) { + resolvedBytes = directBlob.data + isInlineBlob = true + } else { + val url by rememberRemoteStringAsState(layout.urlId) + val embeddedBlob = + if (url.startsWith(RcDocLayout.EMBEDDED_URL_PREFIX)) { + val blobId = url.removePrefix(RcDocLayout.EMBEDDED_URL_PREFIX).trim().toIntOrNull() + blobId?.let { id -> + (hostRemoteContext.getObject(id) as? BinaryData)?.takeIf { + it.type == BinaryData.TYPE_RC_DOC + } + } + } else { + null + } + if (embeddedBlob != null) { + resolvedBytes = embeddedBlob.data + isInlineBlob = true + } else if (!isMeasureProbe && url.isNotEmpty() && documentResolver != null) { + // Key the state holder on (url, documentResolver) so switching URLs immediately clears + // the previous child document and a cancelling in-flight fetch cannot clobber a newer + // resolution. + val externalBytesState = + remember(url, documentResolver) { mutableStateOf<ByteArray?>(null) } + LaunchedEffect(url, documentResolver) { + externalBytesState.value = + try { + documentResolver.resolve(url) + } catch (e: CancellationException) { + throw e + } catch (_: Throwable) { + null + } + } + resolvedBytes = externalBytesState.value + isInlineBlob = false + } else { + resolvedBytes = null + isInlineBlob = false + } + } + + val density = LocalDensity.current.density + + // FitBox measure probes subcompose all candidate branches alongside the chosen branch. + // Measure using only the child header's intrinsic size without running variable sync, + // LaunchedEffects, or mounting a duplicate RcPlayerImpl (sound/sensor/clock loops). + if (isMeasureProbe) { + val probeHeaderDimensions = + remember(resolvedBytes, parentDoc.clock) { + if (resolvedBytes == null || resolvedBytes.isEmpty()) { + null + } else { + runCatching { + val buffer = + RemoteComposeBuffer.fromInputStream(ByteArrayInputStream(resolvedBytes)) + val doc = CoreDocument(parentDoc.clock).apply { initFromBuffer(buffer) } + extractHeaderDimensions(doc) + } + .getOrNull() + } + } + val probeIntrinsicModifier = + if ( + probeHeaderDimensions != null && + probeHeaderDimensions.width > 0 && + probeHeaderDimensions.height > 0 + ) { + val w = + rawDimensionDp( + probeHeaderDimensions.width.toFloat(), + probeHeaderDimensions.densityBehavior, + density, + ) + val h = + rawDimensionDp( + probeHeaderDimensions.height.toFloat(), + probeHeaderDimensions.densityBehavior, + density, + ) + Modifier.size(w, h) + } else { + Modifier + } + Box(modifier = modifier.then(probeIntrinsicModifier).clipToBounds()) + return + } + + // 3. Parse the resolved bytes into an isolated CoreDocument + RcPlayerState, capturing the + // initial header dimensions before placement can mutate CoreDocument.width/height. + val parsedChild = + remember(resolvedBytes, parentDoc.clock) { + if (resolvedBytes == null || resolvedBytes.isEmpty()) { + null + } else { + runCatching { + val buffer = + RemoteComposeBuffer.fromInputStream(ByteArrayInputStream(resolvedBytes)) + val doc = CoreDocument(parentDoc.clock).apply { initFromBuffer(buffer) } + // Construct RcPlayerState first so Header.apply populates doc properties and + // densityBehavior, while still capturing dimensions before placement can + // mutate CoreDocument.width/height. + val state = RcPlayerState(doc, defaultPrefix = null) + val headerDimensions = extractHeaderDimensions(doc) + ParsedChildDocument(state = state, headerDimensions = headerDimensions) + } + .getOrNull() + } + } + val childState = parsedChild?.state + + // 4. Index child named variables and run synchronous initial sync so frame 0 sees mapped + // values. + val childVarsByName = remember(childState) { buildChildNamedVariablesMap(childState) } + val syncState = + remember(childState, mappings, hostReadContext, hostRemoteContext) { + RcDocSyncState().also { state -> + if (childState != null && mappings.isNotEmpty()) { + Snapshot.withoutReadObservation { + syncInitialVariables( + mappings = mappings, + hostReadContext = hostReadContext, + hostRemoteContext = hostRemoteContext, + childState = childState, + childVarsByName = childVarsByName, + syncState = state, + ) + } + } + } + } + + // 5. Reactively keep forward, reverse, and bidirectional variable mappings in sync. + if (childState != null && mappings.isNotEmpty()) { + val hasVariableMappings = + remember(mappings) { mappings.fastAny { it.mode != MapRcDocVariables.MAP_HOST_ACTION } } + if (hasVariableMappings) { + LaunchedEffect(childState, mappings, hostReadContext, hostRemoteContext, syncState) { + snapshotFlow { + captureMappingSnapshots( + mappings = mappings, + hostReadContext = hostReadContext, + childReadContext = childState.graphContext, + childVarsByName = childVarsByName, + ) + } + .collect { snapshots -> + applyMappingSnapshots( + snapshots = snapshots, + hostReadContext = hostReadContext, + hostRemoteContext = hostRemoteContext, + childRemoteContext = childState.remoteContext, + syncState = syncState, + ) + } + } + } + } + + // 6. Intercept MAP_HOST_ACTION actions from the child; forward unmapped actions directly to the + // raw host callbacks (never through the parent's PendingIntent/Lambda interceptors). + val hostActionHandler = LocalHostRemoteActionHandler.current + val hostNamedActionHandler = LocalHostRemoteNamedActionHandler.current + val childOnAction: (Int, String?) -> Unit = + remember(mappings, hostRemoteContext, hostActionHandler) { + { actionId, value -> + var mapped = false + val metadata = value ?: "" + mappings.fastForEach { mapping -> + if ( + mapping.mode == MapRcDocVariables.MAP_HOST_ACTION && + mapping.remoteTarget == actionId + ) { + hostRemoteContext.mRemoteComposeState.overrideData( + mapping.localId, + metadata, + ) + mapped = true + } + } + if (!mapped) { + hostActionHandler(actionId, value) + } + } + } + + // 7. Size and clip: adopt the child's remembered header dimensions (using the child's own + // densityBehavior) when no explicit size modifier constrains this component; outer size + // modifiers take precedence over the inner intrinsic size. + val headerDimensions = parsedChild?.headerDimensions + val intrinsicModifier = + if (headerDimensions != null && headerDimensions.width > 0 && headerDimensions.height > 0) { + val w = + rawDimensionDp( + headerDimensions.width.toFloat(), + headerDimensions.densityBehavior, + density, + ) + val h = + rawDimensionDp( + headerDimensions.height.toFloat(), + headerDimensions.densityBehavior, + density, + ) + Modifier.size(w, h) + } else { + Modifier + } + + val parentFeatures = LocalRcPlayerFeatures.current + val featureResolver = LocalRcPlayerFeatureResolver.current + val childFeatures = + remember(childState, parentFeatures, featureResolver) { + if (childState != null && featureResolver != null) { + featureResolver(childState.document.profileMask) + } else { + parentFeatures + } + } + val parentTheme = LocalRcPlayerTheme.current + val customPlugins = LocalRcCustomPlugins.current + val typefaceResolver = LocalRcTypefaceResolver.current + // Only propagate trustedContent for inline BinaryData blobs authored inside the trusted host + // document; externally resolved bytes are treated as untrusted. + val parentTrustedContent = + (hostRemoteContext.mRemoteComposeState as? SnapshotRemoteComposeState)?.trustedContent == + true + val childTrustedContent = parentTrustedContent && isInlineBlob + + Box(modifier = modifier.then(intrinsicModifier).clipToBounds()) { + if (childState != null) { + CompositionLocalProvider(LocalRcDocNestingDepth provides depth + 1) { + RcPlayerImpl( + state = childState, + features = childFeatures, + modifier = Modifier.fillMaxSize(), + imageLoader = null, + trustedContent = childTrustedContent, + onAction = childOnAction, + onNamedAction = hostNamedActionHandler, + customPlugins = customPlugins, + typefaceResolver = typefaceResolver, + theme = parentTheme, + documentResolver = documentResolver, + featureResolver = featureResolver, + ) + } + } + } +} + +private class RcDocSyncState { + val lastSyncedFloat = HashMap<MapRcDocVariables, Float>() + val lastSyncedInt = HashMap<MapRcDocVariables, Int>() + val lastSyncedColor = HashMap<MapRcDocVariables, Int>() + val lastSyncedText = HashMap<MapRcDocVariables, String?>() +} + +private data class MappingSnapshot( + val mapping: MapRcDocVariables, + val entries: List<NamedVariable>, + val varType: Int, + val hostValue: Any?, + val childValue: Any?, +) + +private fun buildChildNamedVariablesMap( + childState: RcPlayerState? +): Map<String, List<NamedVariable>> { + if (childState == null) return emptyMap() + val map = HashMap<String, MutableList<NamedVariable>>() + childState.preprocessed.constantOps.fastForEach { op -> + if (op is NamedVariable) { + val list = map.getOrPut(op.mVarName) { ArrayList(1) } + if (!list.fastAny { it.mVarId == op.mVarId && it.mVarType == op.mVarType }) { + list.add(op) + } + } + } + return map +} + +private fun readValue(context: RemoteContext, id: Int, varType: Int): Any? = + when (varType) { + NamedVariable.FLOAT_TYPE -> context.getFloat(id) + NamedVariable.INT_TYPE -> context.getInteger(id) + NamedVariable.COLOR_TYPE -> context.getColor(id) + NamedVariable.STRING_TYPE -> context.getText(id) + else -> null + } + +private fun writeToChild( + childRemoteContext: RemoteContext, + entries: List<NamedVariable>, + varType: Int, + value: Any?, +) { + when (varType) { + NamedVariable.FLOAT_TYPE -> { + val f = value as? Float ?: return + entries.fastForEach { entry -> childRemoteContext.overrideFloat(entry.mVarId, f) } + } + NamedVariable.INT_TYPE -> { + val i = value as? Int ?: return + entries.fastForEach { entry -> childRemoteContext.overrideInteger(entry.mVarId, i) } + } + NamedVariable.COLOR_TYPE -> { + val c = value as? Int ?: return + entries.fastForEach { entry -> + childRemoteContext.mRemoteComposeState.overrideColor(entry.mVarId, c) + } + } + NamedVariable.STRING_TYPE -> { + val s = value as? String ?: return + entries.fastForEach { entry -> + childRemoteContext.mRemoteComposeState.overrideData(entry.mVarId, s) + } + } + } +} + +private fun writeToHost( + hostReadContext: RemoteContext, + hostRemoteContext: RemoteContext, + localId: Int, + varType: Int, + value: Any?, +) { + val hostState = hostRemoteContext.mRemoteComposeState as? SnapshotRemoteComposeState + when (varType) { + NamedVariable.FLOAT_TYPE -> { + val f = value as? Float ?: return + if ( + hostReadContext.getFloat(localId).compareTo(f) != 0 || + hostState?.isFloatOverridden(localId) != true + ) { + hostRemoteContext.overrideFloat(localId, f) + } + } + NamedVariable.INT_TYPE -> { + val i = value as? Int ?: return + if ( + hostReadContext.getInteger(localId) != i || + hostState?.isIntegerOverridden(localId) != true + ) { + hostRemoteContext.overrideInteger(localId, i) + } + } + NamedVariable.COLOR_TYPE -> { + val c = value as? Int ?: return + if ( + hostReadContext.getColor(localId) != c || + hostState?.isColorOverridden(localId) != true + ) { + hostRemoteContext.mRemoteComposeState.overrideColor(localId, c) + } + } + NamedVariable.STRING_TYPE -> { + val s = value as? String ?: return + if ( + hostReadContext.getText(localId) != s || + hostState?.isDataOverridden(localId) != true + ) { + hostRemoteContext.mRemoteComposeState.overrideData(localId, s) + } + } + } +} + +private fun syncInitialVariables( + mappings: List<MapRcDocVariables>, + hostReadContext: RemoteContext, + hostRemoteContext: RemoteContext, + childState: RcPlayerState, + childVarsByName: Map<String, List<NamedVariable>>, + syncState: RcDocSyncState, +) { + val childReadContext = childState.graphContext + val childRemoteContext = childState.remoteContext + + // Forward pass first (MAP_FORWARD + MAP_BIDIRECTIONAL: parent wins initial value). + mappings.fastForEach { mapping -> + val mode = mapping.mode + if (mode != MapRcDocVariables.MAP_FORWARD && mode != MapRcDocVariables.MAP_BIDIRECTIONAL) { + return@fastForEach + } + val remoteName = hostReadContext.getText(mapping.remoteTarget) ?: return@fastForEach + val entries = childVarsByName[remoteName] ?: return@fastForEach + if (entries.isEmpty()) return@fastForEach + val varType = entries[0].mVarType + val hostVal = readValue(hostReadContext, mapping.localId, varType) + writeToChild(childRemoteContext, entries, varType, hostVal) + recordLastSynced(syncState, mapping, varType, hostVal) + } + + // Reverse pass second (MAP_REVERSE only; MAP_BIDIRECTIONAL already synced from parent). + mappings.fastForEach { mapping -> + if (mapping.mode != MapRcDocVariables.MAP_REVERSE) return@fastForEach + val remoteName = hostReadContext.getText(mapping.remoteTarget) ?: return@fastForEach + val entries = childVarsByName[remoteName] ?: return@fastForEach + if (entries.isEmpty()) return@fastForEach + val varType = entries[0].mVarType + val childVal = readValue(childReadContext, entries[0].mVarId, varType) + writeToHost(hostReadContext, hostRemoteContext, mapping.localId, varType, childVal) + recordLastSynced(syncState, mapping, varType, childVal) + } +} + +private fun captureMappingSnapshots( + mappings: List<MapRcDocVariables>, + hostReadContext: RemoteContext, + childReadContext: RemoteContext, + childVarsByName: Map<String, List<NamedVariable>>, +): List<MappingSnapshot> { + val result = ArrayList<MappingSnapshot>(mappings.size) + mappings.fastForEach { mapping -> + val mode = mapping.mode + if (mode == MapRcDocVariables.MAP_HOST_ACTION) return@fastForEach + val remoteName = hostReadContext.getText(mapping.remoteTarget) ?: return@fastForEach + val entries = childVarsByName[remoteName] ?: return@fastForEach + if (entries.isEmpty()) return@fastForEach + val varType = entries[0].mVarType + val hostVal = + if ( + mode == MapRcDocVariables.MAP_FORWARD || mode == MapRcDocVariables.MAP_BIDIRECTIONAL + ) { + readValue(hostReadContext, mapping.localId, varType) + } else { + null + } + val childVal = + if ( + mode == MapRcDocVariables.MAP_REVERSE || mode == MapRcDocVariables.MAP_BIDIRECTIONAL + ) { + readValue(childReadContext, entries[0].mVarId, varType) + } else { + null + } + result.add(MappingSnapshot(mapping, entries, varType, hostVal, childVal)) + } + return result +} + +private fun applyMappingSnapshots( + snapshots: List<MappingSnapshot>, + hostReadContext: RemoteContext, + hostRemoteContext: RemoteContext, + childRemoteContext: RemoteContext, + syncState: RcDocSyncState, +) { + snapshots.fastForEach { snap -> + val mapping = snap.mapping + when (mapping.mode) { + MapRcDocVariables.MAP_FORWARD -> { + if (valueDiffers(syncState, mapping, snap.varType, snap.hostValue)) { + writeToChild(childRemoteContext, snap.entries, snap.varType, snap.hostValue) + recordLastSynced(syncState, mapping, snap.varType, snap.hostValue) + } + } + MapRcDocVariables.MAP_REVERSE -> { + if (valueDiffers(syncState, mapping, snap.varType, snap.childValue)) { + writeToHost( + hostReadContext, + hostRemoteContext, + mapping.localId, + snap.varType, + snap.childValue, + ) + recordLastSynced(syncState, mapping, snap.varType, snap.childValue) + } + } + MapRcDocVariables.MAP_BIDIRECTIONAL -> { + val hostChanged = valueDiffers(syncState, mapping, snap.varType, snap.hostValue) + val childChanged = valueDiffers(syncState, mapping, snap.varType, snap.childValue) + if (hostChanged) { + writeToChild(childRemoteContext, snap.entries, snap.varType, snap.hostValue) + recordLastSynced(syncState, mapping, snap.varType, snap.hostValue) + } else if (childChanged) { + writeToHost( + hostReadContext, + hostRemoteContext, + mapping.localId, + snap.varType, + snap.childValue, + ) + recordLastSynced(syncState, mapping, snap.varType, snap.childValue) + } + } + } + } +} + +private fun valueDiffers( + syncState: RcDocSyncState, + mapping: MapRcDocVariables, + varType: Int, + value: Any?, +): Boolean = + when (varType) { + NamedVariable.FLOAT_TYPE -> { + val f = value as? Float ?: return false + val last = syncState.lastSyncedFloat[mapping] + last == null || last.compareTo(f) != 0 + } + NamedVariable.INT_TYPE -> { + val i = value as? Int ?: return false + syncState.lastSyncedInt[mapping] != i + } + NamedVariable.COLOR_TYPE -> { + val c = value as? Int ?: return false + syncState.lastSyncedColor[mapping] != c + } + NamedVariable.STRING_TYPE -> { + val s = value as? String ?: return false + syncState.lastSyncedText[mapping] != s + } + else -> false + } + +private fun recordLastSynced( + syncState: RcDocSyncState, + mapping: MapRcDocVariables, + varType: Int, + value: Any?, +) { + when (varType) { + NamedVariable.FLOAT_TYPE -> + (value as? Float)?.let { syncState.lastSyncedFloat[mapping] = it } + NamedVariable.INT_TYPE -> (value as? Int)?.let { syncState.lastSyncedInt[mapping] = it } + NamedVariable.COLOR_TYPE -> (value as? Int)?.let { syncState.lastSyncedColor[mapping] = it } + NamedVariable.STRING_TYPE -> + (value as? String)?.let { syncState.lastSyncedText[mapping] = it } + } +}
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ClickModifier.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ClickModifier.kt index 6f7a03c..d3c6f4c 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ClickModifier.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ClickModifier.kt
@@ -24,7 +24,6 @@ import androidx.compose.remote.core.CoreDocument import androidx.compose.remote.core.Operation import androidx.compose.remote.core.RemoteContext -import androidx.compose.remote.core.operations.Theme import androidx.compose.remote.core.operations.layout.ClickModifierOperation import androidx.compose.remote.core.operations.layout.MultiClickModifier import androidx.compose.remote.core.operations.layout.TouchCancelModifierOperation @@ -46,6 +45,7 @@ import androidx.compose.remote.player.compose.embedded.LocalRemoteNamedActionHandler import androidx.compose.remote.player.compose.embedded.doc.GraphContext import androidx.compose.remote.player.compose.embedded.doc.getOperationsList +import androidx.compose.remote.player.compose.embedded.doc.updateVariablesWithoutRcDoc import androidx.compose.remote.player.compose.embedded.state.rememberRemoteStringAsState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue @@ -111,9 +111,8 @@ onNamedAction = onNamedAction, ) } - coreDocument.updateVariables( + coreDocument.updateVariablesWithoutRcDoc( remoteContext, - Theme.SYSTEM, coreDocument.getOperationsList(), ) } @@ -177,9 +176,8 @@ ) } } - coreDocument.updateVariables( + coreDocument.updateVariablesWithoutRcDoc( remoteContext, - Theme.SYSTEM, coreDocument.getOperationsList(), ) } @@ -249,9 +247,8 @@ ) } } - coreDocument.updateVariables( + coreDocument.updateVariablesWithoutRcDoc( remoteContext, - Theme.SYSTEM, coreDocument.getOperationsList(), ) } @@ -304,7 +301,7 @@ } } -private fun applyClickAction( +internal fun applyClickAction( action: Operation, coreDocument: CoreDocument, remoteContext: RemoteContext,
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/EventModifier.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/EventModifier.kt new file mode 100644 index 0000000..6394979 --- /dev/null +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/EventModifier.kt
@@ -0,0 +1,973 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:Suppress("RestrictedApiAndroidX") + +package androidx.compose.remote.player.compose.embedded.modifier + +import androidx.collection.IntSet +import androidx.collection.MutableIntSet +import androidx.collection.MutableLongIntMap +import androidx.collection.MutableLongList +import androidx.collection.MutableLongObjectMap +import androidx.collection.MutableLongSet +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.Operations +import androidx.compose.remote.core.RemoteContext +import androidx.compose.remote.core.WireBuffer +import androidx.compose.remote.core.events.Event +import androidx.compose.remote.core.events.EventManager +import androidx.compose.remote.core.input.MetadataUtil +import androidx.compose.remote.core.input.PointerInputEvent +import androidx.compose.remote.core.input.PointerInputRouter +import androidx.compose.remote.core.operations.FloatExpression +import androidx.compose.remote.core.operations.Theme +import androidx.compose.remote.core.operations.layout.LayoutComponent +import androidx.compose.remote.core.operations.layout.modifiers.EventHandlerModifierOperation +import androidx.compose.remote.player.compose.embedded.LocalCoreDocument +import androidx.compose.remote.player.compose.embedded.LocalGraphContext +import androidx.compose.remote.player.compose.embedded.LocalRcIsMeasureProbe +import androidx.compose.remote.player.compose.embedded.LocalRemoteActionHandler +import androidx.compose.remote.player.compose.embedded.LocalRemoteContext +import androidx.compose.remote.player.compose.embedded.LocalRemoteNamedActionHandler +import androidx.compose.remote.player.compose.embedded.doc.GraphContext +import androidx.compose.remote.player.compose.embedded.doc.getOperationsList +import androidx.compose.runtime.Composable +import androidx.compose.runtime.State +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.key.KeyEvent +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.nativeKeyCode +import androidx.compose.ui.input.key.onKeyEvent +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.pointer.PointerEvent +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.changedToDownIgnoreConsumed +import androidx.compose.ui.input.pointer.changedToUpIgnoreConsumed +import androidx.compose.ui.input.pointer.positionChangeIgnoreConsumed +import androidx.compose.ui.input.pointer.util.VelocityTracker +import androidx.compose.ui.input.pointer.util.addPointerInputChange +import androidx.compose.ui.node.ModifierNodeElement +import androidx.compose.ui.node.PointerInputModifierNode +import androidx.compose.ui.platform.InspectorInfo +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.util.fastAny +import androidx.compose.ui.util.fastForEach + +internal class RcEvent( + private val type: Int, + private val metadata: Int, + private val data: FloatArray?, +) : Event { + override fun getType(): Int = type + + override fun getMetadata(): Int = metadata + + override fun getData(): FloatArray? = data +} + +/** + * The key input event constants the embedded player dispatches to [EventHandlerModifierOperation]s, + * and how Compose key input maps onto them. + * + * `remote-core` defines pointer input types in [PointerInputRouter], [PointerInputEvent], and + * [MetadataUtil], but has no key event types or router yet. The embedded player attaches each + * component's handlers as Compose input modifiers rather than routing through core's + * `EventManager`, because Compose already handles key delivery to the focused node and pointer hit + * testing / per-pointer streams. + * + * These key constants are provisional until they move into `remote-core` alongside a key router for + * the View player. + */ +internal object RcPlayerEvents { + /** Key events, as proposed in go/rc-eventhandler. */ + const val EVENT_TYPE_KEY: Int = 2 + + /** + * The tunneling pass, from the root down to the target (`onPreviewKeyEvent` for keys). Pass and + * subtype values follow the event data layout in go/rc-eventhandler. + */ + const val PASS_TUNNELING: Int = 1 + + /** The bubbling pass, from the target up to the root (`onKeyEvent` for keys). */ + const val PASS_BUBBLING: Int = 2 + + /** A key was pressed, including key repeats. */ + const val KEY_SUBTYPE_DOWN: Int = 1 + + /** A key was released. */ + const val KEY_SUBTYPE_UP: Int = 2 + + /** Handler flag: consume a key event and stop propagation. */ + const val STATUS_CONSUMED: Int = 1 + + /** Packs a key pass and subtype into an event metadata (and handler filter) value. */ + fun metadata(pass: Int, subtype: Int): Int = (pass shl 8) or subtype + + /** Returns the pass packed into a key event metadata (or handler filter) value. */ + fun passOf(metadata: Int): Int = metadata shr 8 +} + +// Match EventHandlerModifierOperation.CommonFlagsUtil until aosp/4337994 lands. +private const val EVENT_HANDLER_FLAG_UNCONDITIONAL = 1 +private const val EVENT_HANDLER_FLAG_NO_DATA = 1 shl 1 + +/** + * Decoded wire fields of an [EventHandlerModifierOperation] alongside the [op] whose nested actions + * run. + * + * TODO: Replace wire re-parsing with generated `EventHandlerModifierOperationNode` once + * aosp/4337994 lands. + */ +internal class ParsedEventHandler( + val op: EventHandlerModifierOperation, + val type: Int, + val filter: Int, + val flags: Int, + val dataIds: IntArray?, + val condition: FloatArray?, +) { + /** + * Reusable [FloatExpression] for evaluating [condition] without allocating per event; + * `FloatExpression.updateVariables` resolves variables into `mPreCalcValue` without mutating + * `mSrcValue`. + */ + val conditionExpression: FloatExpression? = condition?.let { FloatExpression(-1, it, null) } +} + +/** + * Extracts [EventHandlerModifierOperation]'s wire fields by re-parsing `op.write(WireBuffer())`. + * + * TODO: Replace wire re-parsing with generated `EventHandlerModifierOperationNode` once + * aosp/4337994 lands. + */ +internal fun EventHandlerModifierOperation.parseEventHandler(): ParsedEventHandler { + val buffer = WireBuffer(256) + write(buffer) + buffer.setIndex(0) + val opcode = buffer.readOperationType() + require(opcode == Operations.MODIFIER_EVENT_HANDLER) { + "Unexpected opcode for EventHandlerModifierOperation: $opcode" + } + val version = buffer.readInt() + require(version == 0) { "Unsupported EventHandlerModifierOperation version: $version" } + val type = buffer.readInt() + val filter = buffer.readInt() + val commonFlags = buffer.readShort() + val flags = buffer.readShort() + val dataIds = + if ((commonFlags and EVENT_HANDLER_FLAG_NO_DATA) == 0) { + val dataLen = buffer.readInt() + IntArray(dataLen) { buffer.readInt() } + } else { + null + } + val condition = + if ((commonFlags and EVENT_HANDLER_FLAG_UNCONDITIONAL) == 0) { + val len = buffer.readInt() + FloatArray(len) { buffer.readNanId() } + } else { + null + } + return ParsedEventHandler( + op = this, + type = type, + filter = filter, + flags = flags, + dataIds = dataIds, + condition = condition, + ) +} + +/** + * Runs [handlers] that match [event], outer-to-inner for tunneling/final passes and inner-to-outer + * for bubbling (`POINTER_PASS_MAIN` / `PASS_BUBBLING`) passes, the same way + * `PointerInputRouter.dispatchToModifiers` and `EventHandlerModifierOperation.onEvent` do: the + * handler's filter must equal the event metadata, the event data is written to the handler's data + * ids, and the nested actions run if the handler's condition holds. The nested actions run through + * the player's action dispatch, so host actions reach the `RcPlayer` callbacks. + * + * For pointer events, consumption marks the event consumed so later handlers in the pass observe + * `consumed = 1`. For key events, consumption stops dispatching to subsequent handlers on this + * component in the same pass. + * + * @return the bitwise OR of the flags of every handler whose actions ran, or + * [EventManager.STATUS_UNHANDLED] if none did. + */ +internal fun dispatchEventActions( + handlers: List<ParsedEventHandler>, + event: Event, + coreDocument: CoreDocument, + remoteContext: RemoteContext, + onAction: (Int, String?) -> Unit, + onNamedAction: (String, Any?) -> Unit, + graphContext: GraphContext? = null, +): Int { + val isBubbling = + when (event.type) { + PointerInputRouter.EVENT_TYPE_POINTER -> + MetadataUtil.unpackPass(event.metadata) == PointerInputRouter.POINTER_PASS_MAIN + RcPlayerEvents.EVENT_TYPE_KEY -> + RcPlayerEvents.passOf(event.metadata) == RcPlayerEvents.PASS_BUBBLING + else -> false + } + val evalContext = graphContext ?: remoteContext + var status = EventManager.STATUS_UNHANDLED + var wroteData = false + var ranActions = false + for (i in handlers.indices) { + val handler = handlers[if (isBubbling) handlers.lastIndex - i else i] + if (handler.type != event.type || handler.filter != event.metadata) continue + val dataIds = handler.dataIds + val data = event.data + var wroteHandlerData = false + if (dataIds != null && data != null) { + for (j in 0 until minOf(dataIds.size, data.size)) { + // An id of 0 means the creator doesn't want this field. + if (dataIds[j] != 0) { + remoteContext.overrideFloat(dataIds[j], data[j]) + wroteHandlerData = true + wroteData = true + } + } + } + val conditionExpr = handler.conditionExpression + if (conditionExpr != null) { + if (wroteHandlerData && graphContext == null) { + coreDocument.updateVariables( + remoteContext, + Theme.SYSTEM, + coreDocument.getOperationsList(), + ) + } + if (conditionExpr.evaluate(evalContext) == 0f) { + continue + } + } + handler.op.list.fastForEach { action -> + applyClickAction( + action = action, + coreDocument = coreDocument, + remoteContext = remoteContext, + graphContext = graphContext, + onAction = onAction, + onNamedAction = onNamedAction, + ) + } + ranActions = true + status = status or handler.flags + if ( + event is PointerInputEvent && + (handler.flags and PointerInputRouter.POINTER_STATUS_CONSUMED) != 0 + ) { + event.markConsumed() + } + if ( + event.type == RcPlayerEvents.EVENT_TYPE_KEY && + (handler.flags and RcPlayerEvents.STATUS_CONSUMED) != 0 + ) { + break + } + } + if (ranActions || wroteData) { + coreDocument.updateVariables( + remoteContext, + Theme.SYSTEM, + coreDocument.getOperationsList(), + ) + } + return status +} + +/** + * Attaches [component]'s key [EventHandlerModifierOperation]s as Compose key input modifiers. + * + * Compose delivers key events to the focused node, so the handlers run when focus is on, or within, + * this component: tunneling-pass handlers from `onPreviewKeyEvent` (root to focused node) and + * bubbling-pass handlers from `onKeyEvent` (focused node to root). Place this outside the + * component's other modifiers so it is an ancestor of any focus target they add (e.g. a clickable). + * + * Key downs (including repeats) and key ups are dispatched with the pass and subtype as the + * metadata, and `[keyCode, metaState, repeatCount]` as the data, where the key code is the Android + * key code. A handler matches a specific key with a condition on the key code it receives through + * its data ids. A handler returning [RcPlayerEvents.STATUS_CONSUMED] consumes the key event. + * + * TODO: `RemoteComposeView` only dispatches key downs, in a single pass with the key code as the + * metadata. It should dispatch both passes and key ups in this layout so documents behave the + * same in both players. + */ +@Composable +internal fun Modifier.keyEventActions(component: LayoutComponent): Modifier { + if (LocalRcIsMeasureProbe.current) return this + val handlers = rememberEventActions(component, RcPlayerEvents.EVENT_TYPE_KEY) + if (handlers.isEmpty()) return this + val dispatch by rememberEventDispatcher(handlers) + var modifier = this + if (handlers.fastAny { RcPlayerEvents.passOf(it.filter) == RcPlayerEvents.PASS_TUNNELING }) { + modifier = modifier.onPreviewKeyEvent { + dispatchKeyEvent(it, RcPlayerEvents.PASS_TUNNELING, dispatch) + } + } + if (handlers.fastAny { RcPlayerEvents.passOf(it.filter) == RcPlayerEvents.PASS_BUBBLING }) { + modifier = modifier.onKeyEvent { + dispatchKeyEvent(it, RcPlayerEvents.PASS_BUBBLING, dispatch) + } + } + return modifier +} + +private fun dispatchKeyEvent(keyEvent: KeyEvent, pass: Int, dispatch: (Event) -> Int): Boolean { + val subtype = + when (keyEvent.type) { + KeyEventType.KeyDown -> RcPlayerEvents.KEY_SUBTYPE_DOWN + KeyEventType.KeyUp -> RcPlayerEvents.KEY_SUBTYPE_UP + else -> return false + } + val nativeEvent = keyEvent.nativeKeyEvent + val status = + dispatch( + RcEvent( + RcPlayerEvents.EVENT_TYPE_KEY, + RcPlayerEvents.metadata(pass, subtype), + floatArrayOf( + keyEvent.key.nativeKeyCode.toFloat(), + nativeEvent.metaState.toFloat(), + nativeEvent.repeatCount.toFloat(), + ), + ) + ) + return status and RcPlayerEvents.STATUS_CONSUMED != 0 +} + +/** + * Attaches [component]'s pointer [EventHandlerModifierOperation]s as a Compose + * [PointerInputModifierNode] matching [PointerInputRouter]'s wire contract + * ([PointerInputRouter.EVENT_TYPE_POINTER], [MetadataUtil]-packed metadata, and `[pointerId, x, y, + * velocityX, velocityY]` data with `pointerId` mapped into `0..31` active slots). + * + * Compose hit tests pointer downs and keeps delivering each pointer's stream to the components it + * went down in, so the handlers see the pointers that went down within this component. Placed + * outside the component's own modifiers so hit testing covers its outer bounds and `(x, y)` is + * relative to those outer bounds (matching `PointerInputRouter.convertToLocalCoordinates`). + * + * Each change is dispatched in the [PointerInputRouter.POINTER_PASS_INITIAL] + * ([PointerEventPass.Initial]), [PointerInputRouter.POINTER_PASS_MAIN] ([PointerEventPass.Main]), + * and [PointerInputRouter.POINTER_PASS_FINAL] ([PointerEventPass.Final]) passes. Only the passes + * that have handlers are dispatched. A handler returning + * [PointerInputRouter.POINTER_STATUS_CONSUMED] consumes the change (except in `FINAL`) and marks + * later handlers in the pass as seeing it consumed. A `MAIN`-pass cancel is dispatched when a + * descendant or ancestor consumes a tracked pointer (even without movement) or when a tracked + * pointer disappears from the event stream; `MotionEvent.ACTION_CANCEL` and node detach cancel + * tracked pointers through [PointerInputModifierNode.onCancelPointerInput] without synthesizing a + * release (`UP`) event. + */ +@Composable +internal fun Modifier.pointerEventActions(component: LayoutComponent): Modifier { + if (LocalRcIsMeasureProbe.current) return this + val handlers = rememberEventActions(component, PointerInputRouter.EVENT_TYPE_POINTER) + if (handlers.isEmpty()) return this + val dispatchState = rememberEventDispatcher(handlers) + val passes = + remember(handlers) { + MutableIntSet().apply { + handlers.fastForEach { add(MetadataUtil.unpackPass(it.filter)) } + } + } + return this then PointerEventActionsElement(component, passes, dispatchState) +} + +private class PointerEventActionsElement( + private val component: LayoutComponent, + private val passes: IntSet, + private val dispatchState: State<(Event) -> Int>, +) : ModifierNodeElement<PointerEventActionsNode>() { + override fun create(): PointerEventActionsNode = + PointerEventActionsNode(component, passes, dispatchState) + + override fun update(node: PointerEventActionsNode) { + if (node.component !== component) { + node.cancelAllTrackedPointers() + node.component = component + } + node.passes = passes + node.dispatchState = dispatchState + } + + override fun InspectorInfo.inspectableProperties() { + name = "pointerEventActions" + properties["componentId"] = component.getId() + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is PointerEventActionsElement) return false + return component === other.component && + passes == other.passes && + dispatchState == other.dispatchState + } + + override fun hashCode(): Int { + var result = System.identityHashCode(component) + result = 31 * result + passes.hashCode() + result = 31 * result + dispatchState.hashCode() + return result + } +} + +private class PointerEventActionsNode( + var component: LayoutComponent, + var passes: IntSet, + var dispatchState: State<(Event) -> Int>, +) : Modifier.Node(), PointerInputModifierNode { + // Pointers this component saw go down unconsumed externally and hasn't released/cancelled. + private val trackedPointers = MutableLongObjectMap<TrackedPointerState>() + + // Per-pointer velocity trackers updated across the stream and read on UP. + private val velocityEntries = MutableLongObjectMap<PointerVelocityEntry>() + + // Active Compose pointer IDs mapped to reusable 0..31 slot IDs (matching PointerInputRouter). + private val pointerSlots = MutableLongIntMap() + private var usedSlotMask = 0 + + // Per-event transient sets cleared at the start of Initial. + private val consumedBySelfInInitial = MutableLongSet() + private val consumedBySelfInMain = MutableLongSet() + private val downInCurrentEvent = MutableLongSet() + private val upInCurrentEvent = MutableLongSet() + private val seenInMain = MutableLongSet() + + override fun onPointerEvent( + pointerEvent: PointerEvent, + pass: PointerEventPass, + bounds: IntSize, + ) { + val dispatch = dispatchState.value + when (pass) { + PointerEventPass.Initial -> handleInitialPass(pointerEvent, dispatch) + PointerEventPass.Main -> handleMainPass(pointerEvent, dispatch) + PointerEventPass.Final -> handleFinalPass(pointerEvent, dispatch) + } + } + + override fun onCancelPointerInput() { + cancelAllTrackedPointers() + } + + override fun onDetach() { + cancelAllTrackedPointers() + } + + private fun slotFor(pointerId: Long): Int { + val existing = pointerSlots.getOrDefault(pointerId, -1) + if (existing >= 0) return existing + val freeBits = usedSlotMask.inv() + val slot = + if (freeBits != 0) { + Integer.numberOfTrailingZeros(freeBits) + } else { + (pointerId and 31L).toInt() + } + usedSlotMask = usedSlotMask or (1 shl slot) + pointerSlots[pointerId] = slot + return slot + } + + private fun releasePointerResources(pointerId: Long) { + velocityEntries.remove(pointerId) + val slot = pointerSlots.getOrDefault(pointerId, -1) + if (slot >= 0) { + pointerSlots.remove(pointerId) + usedSlotMask = usedSlotMask and (1 shl slot).inv() + } + } + + private fun handleInitialPass(pointerEvent: PointerEvent, dispatch: (Event) -> Int) { + consumedBySelfInInitial.clear() + consumedBySelfInMain.clear() + downInCurrentEvent.clear() + upInCurrentEvent.clear() + + pointerEvent.changes.fastForEach { change -> + val pointerId = change.id.value + val isDown = change.changedToDownIgnoreConsumed() + val isUp = change.changedToUpIgnoreConsumed() + if (isDown) { + downInCurrentEvent.add(pointerId) + val slot = slotFor(pointerId) + val entry = velocityEntries.getOrPut(pointerId) { PointerVelocityEntry() } + entry.tracker.resetTracking() + entry.releaseVelocityX = 0f + entry.releaseVelocityY = 0f + entry.tracker.addPointerInputChange(change) + + if (PointerInputRouter.POINTER_PASS_INITIAL in passes) { + val wasConsumedBefore = change.isConsumed + val status = + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_INITIAL, + subtype = PointerInputRouter.POINTER_SUBTYPE_DOWN, + consumed = wasConsumedBefore, + pointerSlot = slot, + x = change.position.x, + y = change.position.y, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + if (status and PointerInputRouter.POINTER_STATUS_CONSUMED != 0) { + change.consume() + if (!wasConsumedBefore) { + consumedBySelfInInitial.add(pointerId) + } + } + } + return@fastForEach + } + + val state = trackedPointers[pointerId] ?: return@fastForEach + if (isUp) { + val entry = velocityEntries[pointerId] + if (entry != null) { + entry.tracker.addPointerInputChange(change) + val velocity = entry.tracker.calculateVelocity() + entry.releaseVelocityX = velocity.x + entry.releaseVelocityY = velocity.y + } + } else if (change.pressed) { + velocityEntries[pointerId]?.tracker?.addPointerInputChange(change) + } + + if (PointerInputRouter.POINTER_PASS_INITIAL !in passes) return@fastForEach + val subtype = + when { + isUp -> PointerInputRouter.POINTER_SUBTYPE_UP + change.pressed && change.positionChangeIgnoreConsumed() != Offset.Zero -> + PointerInputRouter.POINTER_SUBTYPE_MOVE + else -> return@fastForEach + } + val vx: Float + val vy: Float + if (subtype == PointerInputRouter.POINTER_SUBTYPE_UP) { + val entry = velocityEntries[pointerId] + vx = entry?.releaseVelocityX ?: 0f + vy = entry?.releaseVelocityY ?: 0f + } else { + vx = 0f + vy = 0f + } + val wasConsumedBefore = change.isConsumed + val status = + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_INITIAL, + subtype = subtype, + consumed = wasConsumedBefore, + pointerSlot = state.slot, + x = change.position.x, + y = change.position.y, + velocityX = vx, + velocityY = vy, + dispatch = dispatch, + ) + if (status and PointerInputRouter.POINTER_STATUS_CONSUMED != 0) { + change.consume() + if (!wasConsumedBefore) { + consumedBySelfInInitial.add(pointerId) + } + } + } + } + + private fun handleMainPass(pointerEvent: PointerEvent, dispatch: (Event) -> Int) { + seenInMain.clear() + val hasMainHandlers = PointerInputRouter.POINTER_PASS_MAIN in passes + pointerEvent.changes.fastForEach { change -> + val pointerId = change.id.value + seenInMain.add(pointerId) + val wasConsumedBefore = change.isConsumed + val consumedExternally = wasConsumedBefore && pointerId !in consumedBySelfInInitial + val isDown = change.changedToDownIgnoreConsumed() + if (isDown) { + val slot = slotFor(pointerId) + val status = + if (hasMainHandlers) { + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_MAIN, + subtype = PointerInputRouter.POINTER_SUBTYPE_DOWN, + consumed = wasConsumedBefore, + pointerSlot = slot, + x = change.position.x, + y = change.position.y, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + } else { + EventManager.STATUS_UNHANDLED + } + if (!consumedExternally) { + trackedPointers[pointerId] = + TrackedPointerState(slot, change.position.x, change.position.y) + } + if (status and PointerInputRouter.POINTER_STATUS_CONSUMED != 0) { + change.consume() + if (!wasConsumedBefore) { + consumedBySelfInMain.add(pointerId) + } + } + return@fastForEach + } + + val state = trackedPointers[pointerId] ?: return@fastForEach + if (consumedExternally) { + // A descendant (in Main) or ancestor (in Initial) claimed this stream: cancel + // immediately, even when this change had no position delta. + trackedPointers.remove(pointerId) + releasePointerResources(pointerId) + if (hasMainHandlers) { + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_MAIN, + subtype = PointerInputRouter.POINTER_SUBTYPE_CANCEL, + consumed = false, + pointerSlot = state.slot, + x = change.position.x, + y = change.position.y, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + } + return@fastForEach + } + + val subtype = + when { + change.changedToUpIgnoreConsumed() -> PointerInputRouter.POINTER_SUBTYPE_UP + change.pressed && change.positionChangeIgnoreConsumed() != Offset.Zero -> + PointerInputRouter.POINTER_SUBTYPE_MOVE + else -> return@fastForEach + } + val vx: Float + val vy: Float + if (subtype == PointerInputRouter.POINTER_SUBTYPE_UP) { + // Keep trackedPointers and velocityEntries until after Final so Final still sees UP + // with its slot and computed velocity. + upInCurrentEvent.add(pointerId) + val entry = velocityEntries[pointerId] + vx = entry?.releaseVelocityX ?: 0f + vy = entry?.releaseVelocityY ?: 0f + } else { + state.lastX = change.position.x + state.lastY = change.position.y + vx = 0f + vy = 0f + } + val status = + if (hasMainHandlers) { + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_MAIN, + subtype = subtype, + consumed = wasConsumedBefore, + pointerSlot = state.slot, + x = change.position.x, + y = change.position.y, + velocityX = vx, + velocityY = vy, + dispatch = dispatch, + ) + } else { + EventManager.STATUS_UNHANDLED + } + if (status and PointerInputRouter.POINTER_STATUS_CONSUMED != 0) { + change.consume() + if (!wasConsumedBefore) { + consumedBySelfInMain.add(pointerId) + } + } + } + + if (trackedPointers.isNotEmpty()) { + var disappeared: MutableLongList? = null + trackedPointers.forEachKey { id -> + if (id !in seenInMain) { + if (disappeared == null) disappeared = MutableLongList(1) + disappeared.add(id) + } + } + disappeared?.forEach { id -> + val state = trackedPointers.remove(id) + releasePointerResources(id) + if (state != null && hasMainHandlers) { + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_MAIN, + subtype = PointerInputRouter.POINTER_SUBTYPE_CANCEL, + consumed = false, + pointerSlot = state.slot, + x = state.lastX, + y = state.lastY, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + } + } + } + } + + private fun handleFinalPass(pointerEvent: PointerEvent, dispatch: (Event) -> Int) { + val hasFinalHandlers = PointerInputRouter.POINTER_PASS_FINAL in passes + val hasMainHandlers = PointerInputRouter.POINTER_PASS_MAIN in passes + pointerEvent.changes.fastForEach { change -> + val pointerId = change.id.value + val isDown = pointerId in downInCurrentEvent + val isUp = pointerId in upInCurrentEvent + val state = trackedPointers[pointerId] + if (state == null && !isDown) { + return@fastForEach + } + + val slot = state?.slot ?: slotFor(pointerId) + if (hasFinalHandlers) { + val subtype = + when { + isDown -> PointerInputRouter.POINTER_SUBTYPE_DOWN + isUp -> PointerInputRouter.POINTER_SUBTYPE_UP + change.pressed && change.positionChangeIgnoreConsumed() != Offset.Zero -> + PointerInputRouter.POINTER_SUBTYPE_MOVE + else -> null + } + if (subtype != null) { + val vx: Float + val vy: Float + if (subtype == PointerInputRouter.POINTER_SUBTYPE_UP) { + val entry = velocityEntries[pointerId] + vx = entry?.releaseVelocityX ?: 0f + vy = entry?.releaseVelocityY ?: 0f + } else { + vx = 0f + vy = 0f + } + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_FINAL, + subtype = subtype, + consumed = change.isConsumed, + pointerSlot = slot, + x = change.position.x, + y = change.position.y, + velocityX = vx, + velocityY = vy, + dispatch = dispatch, + ) + } + } + + if (state != null && !isDown && !isUp && change.pressed) { + val consumedBySelf = + pointerId in consumedBySelfInInitial || pointerId in consumedBySelfInMain + if (change.isConsumed && !consumedBySelf) { + // An ancestor (e.g. a scrollable container) consumed this pointer on Main + // after our Main pass ran: stop tracking and cancel the stream. + trackedPointers.remove(pointerId) + releasePointerResources(pointerId) + if (hasMainHandlers) { + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_MAIN, + subtype = PointerInputRouter.POINTER_SUBTYPE_CANCEL, + consumed = false, + pointerSlot = state.slot, + x = change.position.x, + y = change.position.y, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + } + return@fastForEach + } + } + + if (isUp) { + trackedPointers.remove(pointerId) + releasePointerResources(pointerId) + } else if (isDown && state == null) { + // Externally-consumed DOWN was not tracked; free its slot/velocity after Final. + releasePointerResources(pointerId) + } + } + } + + fun cancelAllTrackedPointers() { + if (trackedPointers.isEmpty()) { + velocityEntries.clear() + pointerSlots.clear() + usedSlotMask = 0 + consumedBySelfInInitial.clear() + consumedBySelfInMain.clear() + downInCurrentEvent.clear() + upInCurrentEvent.clear() + seenInMain.clear() + return + } + // Snapshot and clear before dispatching so a CANCEL action that detaches this node cannot + // re-enter and double-dispatch CANCEL. + val toCancel = ArrayList<TrackedPointerState>(trackedPointers.size) + trackedPointers.forEachValue { toCancel.add(it) } + trackedPointers.clear() + velocityEntries.clear() + pointerSlots.clear() + usedSlotMask = 0 + consumedBySelfInInitial.clear() + consumedBySelfInMain.clear() + downInCurrentEvent.clear() + upInCurrentEvent.clear() + seenInMain.clear() + + val dispatch = dispatchState.value + toCancel.fastForEach { state -> + var consumed = false + if (PointerInputRouter.POINTER_PASS_INITIAL in passes) { + val status = + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_INITIAL, + subtype = PointerInputRouter.POINTER_SUBTYPE_CANCEL, + consumed = false, + pointerSlot = state.slot, + x = state.lastX, + y = state.lastY, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + if (status and PointerInputRouter.POINTER_STATUS_CONSUMED != 0) { + consumed = true + } + } + if (PointerInputRouter.POINTER_PASS_MAIN in passes) { + val status = + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_MAIN, + subtype = PointerInputRouter.POINTER_SUBTYPE_CANCEL, + consumed = consumed, + pointerSlot = state.slot, + x = state.lastX, + y = state.lastY, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + if (status and PointerInputRouter.POINTER_STATUS_CONSUMED != 0) { + consumed = true + } + } + if (PointerInputRouter.POINTER_PASS_FINAL in passes) { + dispatchPointerChange( + pass = PointerInputRouter.POINTER_PASS_FINAL, + subtype = PointerInputRouter.POINTER_SUBTYPE_CANCEL, + consumed = consumed, + pointerSlot = state.slot, + x = state.lastX, + y = state.lastY, + velocityX = 0f, + velocityY = 0f, + dispatch = dispatch, + ) + } + } + } +} + +private class TrackedPointerState(val slot: Int, var lastX: Float, var lastY: Float) + +private class PointerVelocityEntry { + val tracker = VelocityTracker() + var releaseVelocityX = 0f + var releaseVelocityY = 0f +} + +/** + * Returns [component]'s [EventHandlerModifierOperation]s of the given event [type], parsed and in + * document order. + */ +@Composable +private fun rememberEventActions( + component: LayoutComponent, + type: Int, +): List<ParsedEventHandler> = + remember(component, type) { + buildList { + component.componentModifiers.list.fastForEach { + if (it is EventHandlerModifierOperation) { + val parsed = it.parseEventHandler() + if (parsed.type == type) add(parsed) + } + } + } + } + +/** + * Returns a dispatcher for [handlers] that reads the latest document, context and host callbacks, + * as the input handlers using it outlive recompositions. + */ +@Composable +private fun rememberEventDispatcher(handlers: List<ParsedEventHandler>): State<(Event) -> Int> { + val coreDocument = LocalCoreDocument.current + val remoteContext = LocalRemoteContext.current + val graphContext = LocalGraphContext.current + val onAction = LocalRemoteActionHandler.current + val onNamedAction = LocalRemoteNamedActionHandler.current + return rememberUpdatedState { event: Event -> + dispatchEventActions( + handlers = handlers, + event = event, + coreDocument = coreDocument, + remoteContext = remoteContext, + onAction = onAction, + onNamedAction = onNamedAction, + graphContext = graphContext, + ) + } +} + +private fun dispatchPointerChange( + pass: Int, + subtype: Int, + consumed: Boolean, + pointerSlot: Int, + x: Float, + y: Float, + velocityX: Float, + velocityY: Float, + dispatch: (Event) -> Int, +): Int { + val event = PointerInputEvent.obtain() + event.setPass(pass) + event.setSubtype(subtype) + if (consumed) { + event.markConsumed() + } + val data = event.data + data[0] = pointerSlot.toFloat() + data[1] = x + data[2] = y + data[3] = velocityX + data[4] = velocityY + return dispatch(event) +}
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/RcPlayerModifiers.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/RcPlayerModifiers.kt index 12bb6c5..861f302 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/RcPlayerModifiers.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/RcPlayerModifiers.kt
@@ -33,6 +33,7 @@ import androidx.compose.remote.core.operations.layout.modifiers.ComponentVisibilityOperation import androidx.compose.remote.core.operations.layout.modifiers.DimensionConstraintsModifierOperation import androidx.compose.remote.core.operations.layout.modifiers.DrawContentOperation +import androidx.compose.remote.core.operations.layout.modifiers.EventHandlerModifierOperation import androidx.compose.remote.core.operations.layout.modifiers.GraphicsLayerModifierOperation import androidx.compose.remote.core.operations.layout.modifiers.HeightInModifierOperation import androidx.compose.remote.core.operations.layout.modifiers.HeightModifierOperation @@ -247,6 +248,9 @@ is CollapsiblePriorityModifierOperation -> modifier is LayoutComputeOperation -> modifier is AnimationSpec -> modifier + // EventHandlerModifierOperation handlers for key and pointer events are attached + // in RcPlayerComponents via keyEventActions / pointerEventActions. + is EventHandlerModifierOperation -> modifier else -> { println("Warning: Unsupported modifier $op") modifier
diff --git a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ScrollModifier.kt b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ScrollModifier.kt index 88cfb18..fa0fdc9 100644 --- a/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ScrollModifier.kt +++ b/compose/remote/remote-player-compose/src/main/java/androidx/compose/remote/player/compose/embedded/modifier/ScrollModifier.kt
@@ -53,6 +53,9 @@ import kotlin.math.floor import kotlin.math.roundToInt import kotlin.math.sign +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive /** * The even-notch count of a scroll, or 0 for free scrolling. The scroll's `TouchExpression` (a @@ -120,9 +123,46 @@ if (raw.isReference) raw.id else -1 } if (positionId > 0) { - LaunchedEffect(scrollState, positionId) { + val lastPublishedPx = + remember(scrollState, positionId, remoteContext) { intArrayOf(scrollState.value) } + LaunchedEffect(scrollState, positionId, remoteContext) { snapshotFlow { scrollState.value } - .collect { px -> remoteContext.overrideFloat(positionId, px.toFloat()) } + .collect { px -> + lastPublishedPx[0] = px + remoteContext.overrideFloat(positionId, px.toFloat()) + } + } + // Apply programmatic scroll overrides (ValueFloatChange, ValueFloatExpressionChange, + // host float overrides, or rcDoc variable mappings) to Compose's ScrollState. + LaunchedEffect(scrollState, positionId, remoteContext) { + snapshotFlow { remoteContext.getFloat(positionId) } + .collect { raw -> + if (!raw.isFinite()) return@collect + val clampedPx = raw.roundToInt().coerceIn(0, scrollState.maxValue) + val isEcho = + raw == lastPublishedPx[0].toFloat() && + lastPublishedPx[0] == scrollState.value + if (isEcho) return@collect + + var interruptedByHigherPriority = false + if (clampedPx != scrollState.value) { + try { + scrollState.scrollTo(clampedPx) + } catch (e: CancellationException) { + // Rethrow if this LaunchedEffect was cancelled; swallow only + // MutatorMutex priority cancellations (e.g. an active user drag/fling). + currentCoroutineContext().ensureActive() + interruptedByHigherPriority = true + } + } + if (!interruptedByHigherPriority) { + val actualPx = scrollState.value + lastPublishedPx[0] = actualPx + if (raw != actualPx.toFloat()) { + remoteContext.overrideFloat(positionId, actualPx.toFloat()) + } + } + } } }
diff --git a/compose/remote/remote-player-compose/src/sharedTest/java/androidx/compose/remote/player/compose/embedded/RcPlayerTestRule.kt b/compose/remote/remote-player-compose/src/sharedTest/java/androidx/compose/remote/player/compose/embedded/RcPlayerTestRule.kt index 6e73db3..6770d31 100644 --- a/compose/remote/remote-player-compose/src/sharedTest/java/androidx/compose/remote/player/compose/embedded/RcPlayerTestRule.kt +++ b/compose/remote/remote-player-compose/src/sharedTest/java/androidx/compose/remote/player/compose/embedded/RcPlayerTestRule.kt
@@ -85,6 +85,7 @@ fun setRemoteContent( customPlugins: CustomPluginRegistry? = null, typefaceResolver: RcTypefaceResolver? = null, + documentResolver: RcDocumentResolver? = null, profile: Profile = RcPlatformProfiles.ANDROIDX, onNamedAction: (name: String, value: Any?, stateUpdater: StateUpdater) -> Unit = { _, _, _ -> @@ -139,6 +140,7 @@ ?: RcPlayerFeatures.forProfiles(coreDocument.profileMask), customPlugins = customPlugins, typefaceResolver = typefaceResolver, + documentResolver = documentResolver, onNamedAction = onNamedAction, onAction = onAction, )
diff --git a/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RcPlayerEventActionTest.kt b/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RcPlayerEventActionTest.kt new file mode 100644 index 0000000..677021b --- /dev/null +++ b/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RcPlayerEventActionTest.kt
@@ -0,0 +1,1082 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.player.compose.embedded + +import android.view.KeyEvent.KEYCODE_A +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.RcProfiles +import androidx.compose.remote.core.RemoteClock +import androidx.compose.remote.core.RemoteComposeBuffer +import androidx.compose.remote.core.RemoteContext +import androidx.compose.remote.core.input.MetadataUtil +import androidx.compose.remote.core.input.PointerInputRouter.EVENT_TYPE_POINTER +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_PASS_FINAL +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_PASS_INITIAL +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_PASS_MAIN +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_STATUS_CONSUMED +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_STATUS_NOT_CONSUMED +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_SUBTYPE_CANCEL +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_SUBTYPE_DOWN +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_SUBTYPE_MOVE +import androidx.compose.remote.core.input.PointerInputRouter.POINTER_SUBTYPE_UP +import androidx.compose.remote.core.operations.Header +import androidx.compose.remote.core.operations.Utils +import androidx.compose.remote.core.operations.layout.LayoutComponent +import androidx.compose.remote.core.operations.layout.managers.BoxLayout +import androidx.compose.remote.core.operations.layout.modifiers.HostNamedActionOperation +import androidx.compose.remote.core.operations.utilities.AnimatedFloatExpression +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.RemoteComposeWriterAndroid +import androidx.compose.remote.creation.actions.HostAction +import androidx.compose.remote.creation.modifiers.RecordingModifier +import androidx.compose.remote.creation.platform.AndroidxRcPlatformServices +import androidx.compose.remote.creation.profile.Profile +import androidx.compose.remote.player.compose.embedded.doc.preprocessDocument +import androidx.compose.remote.player.compose.embedded.modifier.RcPlayerEvents +import androidx.compose.remote.player.compose.embedded.modifier.pointerEventActions +import androidx.compose.remote.player.core.platform.AndroidRemoteContext +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.unit.dp +import androidx.compose.ui.util.fastForEach +import com.google.common.truth.Truth.assertThat +import java.io.ByteArrayInputStream +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.ParameterizedRobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * Key and pointer input dispatched to `EventHandlerModifierOperation`s, run against both players. + * + * Interactions are observed through the host named actions the handlers run. + */ +@RunWith(ParameterizedRobolectricTestRunner::class) +@Config(sdk = [35]) +class RcPlayerEventActionTest(player: PlayerUnderTest) { + + companion object { + @JvmStatic + @ParameterizedRobolectricTestRunner.Parameters(name = "{0}") + fun parameters() = PlayerUnderTest.parameters() + } + + @get:Rule val rule = RemotePlayerTestRule(player) + + @Test + fun pointerEvents_dispatchTunnelingBubblingAndFinal_withLocalPosition() { + val document = pointerBoxDocument { writer -> + val pointerIdVar = Utils.idFromNan(writer.addFloatConstant(-1f)) + val xId = Utils.idFromNan(writer.addFloatConstant(0f)) + val yId = Utils.idFromNan(writer.addFloatConstant(0f)) + RecordingModifier() + .onPointer(POINTER_PASS_INITIAL, POINTER_SUBTYPE_DOWN) { + HostAction("tunnelingDown") + } + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + flags = POINTER_STATUS_CONSUMED, + dataIds = intArrayOf(pointerIdVar, xId, yId), + ) { + HostAction("bubblingDown", HostNamedActionOperation.FLOAT_TYPE, xId) + } + .onPointer( + POINTER_PASS_FINAL, + POINTER_SUBTYPE_DOWN, + consumed = POINTER_STATUS_CONSUMED, + ) { + HostAction("finalDownConsumed") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { + HostAction("bubblingUp", HostNamedActionOperation.FLOAT_TYPE, yId) + } + .onPointer(POINTER_PASS_FINAL, POINTER_SUBTYPE_UP) { + HostAction("finalUp", HostNamedActionOperation.FLOAT_TYPE, pointerIdVar) + } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 20f)) + up() + } + + // The y and pointerId data are written on the down/up, and read as host action values. + assertThat(rule.takeNamedActions()) + .containsExactly( + "tunnelingDown" to null, + "bubblingDown" to 10f, + "finalDownConsumed" to null, + "bubblingUp" to 20f, + "finalUp" to 0f, + ) + .inOrder() + } + + @Test + fun pointerMove_dispatchesThePosition() { + val document = pointerBoxDocument { writer -> + val xId = Utils.idFromNan(writer.addFloatConstant(0f)) + RecordingModifier().onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_MOVE, + dataIds = intArrayOf(0, xId), + ) { + HostAction("move", HostNamedActionOperation.FLOAT_TYPE, xId) + } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + moveTo(Offset(30f, 10f)) + moveTo(Offset(50f, 10f)) + up() + } + + assertThat(rule.takeNamedActions()).containsExactly("move" to 30f, "move" to 50f).inOrder() + } + + @Test + fun pointerUp_dispatchesVelocity() { + val document = pointerBoxDocument { writer -> + val vxId = Utils.idFromNan(writer.addFloatConstant(0f)) + RecordingModifier().onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_UP, + dataIds = intArrayOf(0, 0, 0, vxId), + ) { + HostAction("up", HostNamedActionOperation.FLOAT_TYPE, vxId) + } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + advanceEventTime(16L) + moveTo(Offset(40f, 10f)) + advanceEventTime(16L) + moveTo(Offset(80f, 10f)) + advanceEventTime(16L) + up() + } + + val actions = rule.takeNamedActions() + assertThat(actions).hasSize(1) + assertThat(actions.single().first).isEqualTo("up") + assertThat(actions.single().second as Float).isGreaterThan(0f) + } + + @Test + fun pointerEvents_withPadding_hitPaddingAndUseOuterOrigin() { + val document = + pointerDocument(100, 100) { writer -> + val xId = Utils.idFromNan(writer.addFloatConstant(0f)) + val yId = Utils.idFromNan(writer.addFloatConstant(0f)) + writer.box( + RecordingModifier() + .size(100, 100) + .padding(20) + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + dataIds = intArrayOf(0, xId, yId), + ) { + HostAction("downX", HostNamedActionOperation.FLOAT_TYPE, xId) + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { + HostAction("upY", HostNamedActionOperation.FLOAT_TYPE, yId) + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + rule.play(document, 100, 100) + + // Tap inside the 20px padding: should hit the component and report outer-bounds + // coordinates. + rule.tap(10f, 15f) + + assertThat(rule.takeNamedActions()).containsExactly("downX" to 10f, "upY" to 15f).inOrder() + } + + @Test + fun pointerConsumedByAChild_cancelsTheParentsStream() { + // PointerInputRouter forwards the consumed MOVE rather than synthesizing CANCEL; Compose + // synthesizes CANCEL for the bubbling stream when a descendant consumes a tracked pointer. + assumeTrue( + "View player delivers consumed MOVE rather than synthetic CANCEL", + rule.player != PlayerUnderTest.View, + ) + val document = + pointerDocument(100, 100) { writer -> + writer.box( + RecordingModifier() + .size(100, 100) + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_DOWN) { + HostAction("parentDown") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_CANCEL) { + HostAction("parentCancel") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { + HostAction("parentUp") + }, + BoxLayout.START, + BoxLayout.TOP, + ) { + writer.box( + RecordingModifier() + .size(50, 50) + // The child takes the stream once the pointer moves. + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_MOVE, + flags = POINTER_STATUS_CONSUMED, + ) { + HostAction("childMove") + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + moveTo(Offset(20f, 10f)) + up() + } + + assertThat(rule.takeNamedActions()) + .containsExactly("parentDown" to null, "childMove" to null, "parentCancel" to null) + .inOrder() + } + + @Test + fun pointerDownConsumedByChild_doesNotTrackOrFireUnconsumedParent() { + assumeTrue( + "Embedded player skips tracking consumed DOWN on ancestors", + rule.player != PlayerUnderTest.View, + ) + val document = + pointerDocument(100, 100) { writer -> + writer.box( + RecordingModifier() + .size(100, 100) + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_DOWN) { + HostAction("parentDown") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_MOVE) { + HostAction("parentMove") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_CANCEL) { + HostAction("parentCancel") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { + HostAction("parentUp") + }, + BoxLayout.START, + BoxLayout.TOP, + ) { + writer.box( + RecordingModifier().size(50, 50).onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + flags = POINTER_STATUS_CONSUMED, + ) { + HostAction("childDown") + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + moveTo(Offset(20f, 10f)) + up() + } + + assertThat(rule.takeNamedActions()).containsExactly("childDown" to null) + } + + @Test + fun pointerConsumedWithoutMovement_cancelsTrackedPointerImmediately() { + assumeTrue( + "Embedded pointer modifier test", + rule.player == PlayerUnderTest.Embedded, + ) + val document = + pointerDocument(100, 100) { writer -> + writer.box( + RecordingModifier() + .size(100, 100) + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_DOWN) { + HostAction("parentDown") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_CANCEL) { + HostAction("parentCancel") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { + HostAction("parentUp") + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + val boxComponent = + document.rootLayoutComponent!!.list.first { it is LayoutComponent } as LayoutComponent + val namedActions = mutableListOf<Pair<String, Any?>>() + var consumeNextStationaryChange = false + val remoteContext = AndroidRemoteContext().apply { document.initializeContext(this) } + rule.composeRule.setContent { + CompositionLocalProvider( + LocalCoreDocument provides document, + LocalRemoteContext provides remoteContext, + LocalRemoteActionHandler provides { _, _ -> }, + LocalRemoteNamedActionHandler provides + { name, value -> + namedActions += name to value + }, + ) { + Box(Modifier.size(100.dp).pointerEventActions(boxComponent)) { + Box( + Modifier.fillMaxSize().pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Main) + if (consumeNextStationaryChange) { + consumeNextStationaryChange = false + event.changes.fastForEach { it.consume() } + } + } + } + } + ) + } + } + } + + rule.composeRule.onRoot().performTouchInput { + down(0, Offset(10f, 10f)) + } + assertThat(namedActions).containsExactly("parentDown" to null) + + // Trigger a stationary pointer event for pointer 0 (only pointer 1 moves) that a child + // consumes: pointerEventActions must cancel pointer 0 without waiting for movement/up. + consumeNextStationaryChange = true + rule.composeRule.onRoot().performTouchInput { + down(1, Offset(80f, 80f)) + } + assertThat(namedActions) + .containsExactly("parentDown" to null, "parentCancel" to null) + .inOrder() + + rule.composeRule.onRoot().performTouchInput { + up(1) + up(0) + } + assertThat(namedActions) + .containsExactly("parentDown" to null, "parentCancel" to null) + .inOrder() + } + + @Test + fun pointerOutsideTheComponent_isNotDispatched() { + val document = + pointerDocument(100, 100) { writer -> + writer.box(RecordingModifier().size(100, 100), BoxLayout.START, BoxLayout.TOP) { + writer.box( + RecordingModifier().size(50, 50).onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + ) { + HostAction("childDown") + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + } + rule.play(document, 100, 100) + + rule.tap(75f, 75f) + + assertThat(rule.takeNamedActions()).isEmpty() + } + + @Test + fun keyEvents_dispatchBothPassesAndKeyUps_toFocusedComponent() { + assumeKeyEventsSupported() + val document = focusableBoxDocument { writer -> + val keyCodeId = Utils.idFromNan(writer.addFloatConstant(0f)) + RecordingModifier() + .onKey( + RcPlayerEvents.PASS_TUNNELING, + RcPlayerEvents.KEY_SUBTYPE_DOWN, + dataIds = intArrayOf(keyCodeId), + ) { + HostAction("tunnelingDown", HostNamedActionOperation.FLOAT_TYPE, keyCodeId) + } + .onKey(RcPlayerEvents.PASS_BUBBLING, RcPlayerEvents.KEY_SUBTYPE_DOWN) { + HostAction("bubblingDown") + } + .onKey(RcPlayerEvents.PASS_BUBBLING, RcPlayerEvents.KEY_SUBTYPE_UP) { + HostAction("bubblingUp") + } + } + rule.play(document, 100, 100) + rule.focusHost() + + rule.pressKey(KEYCODE_A) + + assertThat(rule.takeNamedActions()) + .containsExactly( + "tunnelingDown" to KEYCODE_A.toFloat(), + "bubblingDown" to null, + "bubblingUp" to null, + ) + .inOrder() + } + + @Test + fun keyConsumedInTheTunnelingPass_isNotBubbled() { + assumeKeyEventsSupported() + val document = focusableBoxDocument { _ -> + RecordingModifier() + .onKey( + RcPlayerEvents.PASS_TUNNELING, + RcPlayerEvents.KEY_SUBTYPE_DOWN, + flags = RcPlayerEvents.STATUS_CONSUMED, + ) { + HostAction("tunnelingDown") + } + .onKey(RcPlayerEvents.PASS_BUBBLING, RcPlayerEvents.KEY_SUBTYPE_DOWN) { + HostAction("bubblingDown") + } + } + rule.play(document, 100, 100) + rule.focusHost() + + assertThat(rule.pressKey(KEYCODE_A)).isTrue() + assertThat(rule.takeNamedActions()).containsExactly("tunnelingDown" to null) + } + + @Test + fun keyNotConsumed_isNotHandled() { + assumeKeyEventsSupported() + val document = focusableBoxDocument { _ -> + RecordingModifier().onKey( + RcPlayerEvents.PASS_BUBBLING, + RcPlayerEvents.KEY_SUBTYPE_DOWN, + ) { + HostAction("observed") + } + } + rule.play(document, 100, 100) + rule.focusHost() + + assertThat(rule.pressKey(KEYCODE_A)).isFalse() + assertThat(rule.takeNamedActions()).containsExactly("observed" to null) + } + + @Test + fun handlerCondition_gatesTheActions() { + assumeKeyEventsSupported() + val document = focusableBoxDocument { _ -> + RecordingModifier() + .onKey( + RcPlayerEvents.PASS_BUBBLING, + RcPlayerEvents.KEY_SUBTYPE_DOWN, + condition = floatArrayOf(0f), + ) { + HostAction("never") + } + .onKey( + RcPlayerEvents.PASS_BUBBLING, + RcPlayerEvents.KEY_SUBTYPE_DOWN, + condition = floatArrayOf(1f), + ) { + HostAction("always") + } + } + rule.play(document, 100, 100) + rule.focusHost() + + rule.pressKey(KEYCODE_A) + + assertThat(rule.takeNamedActions()).containsExactly("always" to null) + } + + @Test + fun pointerAndClickCoexistence_outerConsumingOnEventDoesNotSwallowClick() { + // FEATURE_UNIFIED_POINTER_INPUT swaps ClickModifierOperation for ClickModifierOperation2, + // which only the View player handles (see POINTER_INPUT.md); the embedded player uses + // ClickModifierOperation without the header flag. + val buildBox: (RemoteComposeWriter) -> Unit = { writer -> + writer.box( + RecordingModifier() + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + flags = POINTER_STATUS_CONSUMED, + ) { + HostAction("eventDown") + } + .onClick(HostAction("click")) + .size(100, 100), + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + val document = + if (rule.player == PlayerUnderTest.View) { + pointerDocument(100, 100, buildBox) + } else { + experimentalDocument(100, 100, buildBox) + } + rule.play(document, 100, 100) + + rule.tap(50f, 50f) + + assertThat(rule.takeNamedActions()).containsExactly("click" to null) + } + + @Test + fun pointerIds_reuseSlotIdsAcrossGestures() { + val document = pointerBoxDocument { writer -> + val pointerIdVar = Utils.idFromNan(writer.addFloatConstant(-1f)) + RecordingModifier().onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + dataIds = intArrayOf(pointerIdVar), + ) { + HostAction("down", HostNamedActionOperation.FLOAT_TYPE, pointerIdVar) + } + } + rule.play(document, 100, 100) + + rule.tap(10f, 10f) + rule.tap(20f, 20f) + + assertThat(rule.takeNamedActions()).containsExactly("down" to 0f, "down" to 0f).inOrder() + } + + @Test + fun pointerMainPass_sameComponentRunsInnerToOuter() { + val document = pointerBoxDocument { _ -> + RecordingModifier() + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_DOWN) { + HostAction("outerUnconsumed") + } + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + consumed = POINTER_STATUS_CONSUMED, + ) { + HostAction("outerConsumed") + } + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + flags = POINTER_STATUS_CONSUMED, + ) { + HostAction("innerDown") + } + } + rule.play(document, 100, 100) + + rule.tap(10f, 10f) + + assertThat(rule.takeNamedActions()) + .containsExactly("innerDown" to null, "outerConsumed" to null) + .inOrder() + } + + @Test + fun keyBubblingPass_sameComponentRunsInnerToOuterAndStopsOnConsume() { + assumeKeyEventsSupported() + val document = focusableBoxDocument { _ -> + RecordingModifier() + .onKey(RcPlayerEvents.PASS_BUBBLING, RcPlayerEvents.KEY_SUBTYPE_DOWN) { + HostAction("outer") + } + .onKey( + RcPlayerEvents.PASS_BUBBLING, + RcPlayerEvents.KEY_SUBTYPE_DOWN, + flags = RcPlayerEvents.STATUS_CONSUMED, + ) { + HostAction("inner") + } + } + rule.play(document, 100, 100) + rule.focusHost() + + assertThat(rule.pressKey(KEYCODE_A)).isTrue() + assertThat(rule.takeNamedActions()).containsExactly("inner" to null) + } + + @Test + fun keyTunnelingPass_sameComponentRunsOuterToInnerAndStopsOnConsume() { + assumeKeyEventsSupported() + val document = focusableBoxDocument { _ -> + RecordingModifier() + .onKey( + RcPlayerEvents.PASS_TUNNELING, + RcPlayerEvents.KEY_SUBTYPE_DOWN, + flags = RcPlayerEvents.STATUS_CONSUMED, + ) { + HostAction("outer") + } + .onKey(RcPlayerEvents.PASS_TUNNELING, RcPlayerEvents.KEY_SUBTYPE_DOWN) { + HostAction("inner") + } + } + rule.play(document, 100, 100) + rule.focusHost() + + assertThat(rule.pressKey(KEYCODE_A)).isTrue() + assertThat(rule.takeNamedActions()).containsExactly("outer" to null) + } + + @Test + fun handlerCondition_evaluatesComputedExpressionFromDataIds() { + assumeTrue( + "Embedded player evaluates computed condition expressions live via GraphContext", + rule.player == PlayerUnderTest.Embedded, + ) + val document = pointerBoxDocument { writer -> + val xNan = writer.addFloatConstant(0f) + val xId = Utils.idFromNan(xNan) + val isRightHalf = + writer.floatExpression( + xNan, + 50f, + AnimatedFloatExpression.SUB, + 0f, + AnimatedFloatExpression.MAX, + ) + RecordingModifier().onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + dataIds = intArrayOf(0, xId), + condition = floatArrayOf(isRightHalf), + ) { + HostAction("rightHalf", HostNamedActionOperation.FLOAT_TYPE, xId) + } + } + rule.play(document, 100, 100) + + rule.tap(20f, 10f) + rule.tap(80f, 10f) + + assertThat(rule.takeNamedActions()).containsExactly("rightHalf" to 80f) + } + + @Test + fun preprocessDocument_scansEventHandlerConditionForTimeAndTouchVariables() { + assumeTrue( + "Embedded player preprocessing test", + rule.player == PlayerUnderTest.Embedded, + ) + val timeDoc = pointerBoxDocument { _ -> + RecordingModifier().onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + condition = floatArrayOf(RemoteContext.FLOAT_ANIMATION_TIME), + ) { + HostAction("tick") + } + } + val touchDoc = pointerBoxDocument { _ -> + RecordingModifier().onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_DOWN, + condition = floatArrayOf(RemoteContext.FLOAT_TOUCH_POS_X), + ) { + HostAction("touch") + } + } + + val timePreprocessed = preprocessDocument(timeDoc) + val touchPreprocessed = preprocessDocument(touchDoc) + + assertThat(timePreprocessed.hasContinuousTime).isTrue() + assertThat(touchPreprocessed.readsTouchPosition).isTrue() + } + + @Test + fun pointerConsumedByAncestorInMain_cancelsChildStream() { + assumeTrue( + "Embedded player synthesizes CANCEL when an ancestor consumes MOVE in Main", + rule.player == PlayerUnderTest.Embedded, + ) + val document = + pointerDocument(100, 100) { writer -> + writer.box( + RecordingModifier().size(100, 100).onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_MOVE, + flags = POINTER_STATUS_CONSUMED, + ) { + HostAction("parentMove") + }, + BoxLayout.START, + BoxLayout.TOP, + ) { + writer.box( + RecordingModifier() + .size(100, 100) + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_DOWN) { + HostAction("childDown") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_MOVE) { + HostAction("childMove") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_CANCEL) { + HostAction("childCancel") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { + HostAction("childUp") + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + moveTo(Offset(30f, 10f)) + moveTo(Offset(50f, 10f)) + up() + } + + assertThat(rule.takeNamedActions()) + .containsExactly( + "childDown" to null, + "childMove" to null, + "parentMove" to null, + "childCancel" to null, + "parentMove" to null, + ) + .inOrder() + } + + @Test + fun pointerCancelledByChild_stopsInitialAndFinalForPointer() { + assumeTrue( + "Embedded player stops Initial and Final passes after cancelling a pointer", + rule.player == PlayerUnderTest.Embedded, + ) + val document = + pointerDocument(100, 100) { writer -> + writer.box( + RecordingModifier() + .size(100, 100) + .onPointer(POINTER_PASS_INITIAL, POINTER_SUBTYPE_MOVE) { + HostAction("parentInitialMove") + } + .onPointer(POINTER_PASS_INITIAL, POINTER_SUBTYPE_UP) { + HostAction("parentInitialUp") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_DOWN) { + HostAction("parentDown") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_CANCEL) { + HostAction("parentCancel") + } + .onPointer( + POINTER_PASS_FINAL, + POINTER_SUBTYPE_MOVE, + consumed = POINTER_STATUS_CONSUMED, + ) { + HostAction("parentFinalMove") + } + .onPointer(POINTER_PASS_FINAL, POINTER_SUBTYPE_UP) { + HostAction("parentFinalUp") + }, + BoxLayout.START, + BoxLayout.TOP, + ) { + writer.box( + RecordingModifier().size(50, 50).onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_MOVE, + flags = POINTER_STATUS_CONSUMED, + ) { + HostAction("childMove") + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + moveTo(Offset(20f, 10f)) + moveTo(Offset(30f, 10f)) + up() + } + + assertThat(rule.takeNamedActions()) + .containsExactly( + "parentDown" to null, + "parentInitialMove" to null, + "childMove" to null, + "parentCancel" to null, + "childMove" to null, + ) + .inOrder() + } + + @Test + fun pointerActionCancel_dispatchesCancelWithoutFakeUp() { + val document = pointerBoxDocument { _ -> + RecordingModifier() + .onPointer(POINTER_PASS_INITIAL, POINTER_SUBTYPE_UP) { HostAction("initialUp") } + .onPointer( + POINTER_PASS_INITIAL, + POINTER_SUBTYPE_UP, + consumed = POINTER_STATUS_CONSUMED, + ) { + HostAction("initialUpConsumed") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { HostAction("mainUp") } + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_UP, + consumed = POINTER_STATUS_CONSUMED, + ) { + HostAction("mainUpConsumed") + } + .onPointer(POINTER_PASS_FINAL, POINTER_SUBTYPE_UP) { HostAction("finalUp") } + .onPointer( + POINTER_PASS_FINAL, + POINTER_SUBTYPE_UP, + consumed = POINTER_STATUS_CONSUMED, + ) { + HostAction("finalUpConsumed") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_CANCEL) { HostAction("cancel") } + } + rule.play(document, 100, 100) + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + cancel() + } + + assertThat(rule.takeNamedActions()).containsExactly("cancel" to null) + } + + @Test + fun pointerUpConsumedByOuterInitial_cancelsChildInsteadOfDispatchingUp() { + assumeTrue( + "Embedded pointer modifier test", + rule.player == PlayerUnderTest.Embedded, + ) + val document = + pointerDocument(100, 100) { writer -> + writer.box( + RecordingModifier() + .size(100, 100) + .onPointer( + POINTER_PASS_INITIAL, + POINTER_SUBTYPE_UP, + consumed = POINTER_STATUS_CONSUMED, + flags = POINTER_STATUS_CONSUMED, + ) { + HostAction("childInitialUpConsumed") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_UP) { + HostAction("childMainUp") + } + .onPointer( + POINTER_PASS_MAIN, + POINTER_SUBTYPE_UP, + consumed = POINTER_STATUS_CONSUMED, + ) { + HostAction("childMainUpConsumed") + } + .onPointer(POINTER_PASS_MAIN, POINTER_SUBTYPE_CANCEL) { + HostAction("childCancel") + }, + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + val boxComponent = + document.rootLayoutComponent!!.list.first { it is LayoutComponent } as LayoutComponent + val namedActions = mutableListOf<Pair<String, Any?>>() + val remoteContext = AndroidRemoteContext().apply { document.initializeContext(this) } + rule.composeRule.setContent { + CompositionLocalProvider( + LocalCoreDocument provides document, + LocalRemoteContext provides remoteContext, + LocalRemoteActionHandler provides { _, _ -> }, + LocalRemoteNamedActionHandler provides + { name, value -> + namedActions += name to value + }, + ) { + Box( + Modifier.size(100.dp).pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + event.changes.fastForEach { change -> + if (!change.pressed && change.previousPressed) { + change.consume() + } + } + } + } + } + ) { + Box(Modifier.fillMaxSize().pointerEventActions(boxComponent)) + } + } + } + + rule.composeRule.onRoot().performTouchInput { + down(Offset(10f, 10f)) + up() + } + + assertThat(namedActions) + .containsExactly("childInitialUpConsumed" to null, "childCancel" to null) + .inOrder() + } + + // TODO: RemoteComposeView dispatches key downs to EventManager with no key router yet. + // Remove this once it routes key events in the layout the embedded player uses. + private fun assumeKeyEventsSupported() { + assumeTrue( + "The View player doesn't route key events", + rule.player != PlayerUnderTest.View, + ) + } + + private fun pointerDocument( + width: Int, + height: Int, + content: (RemoteComposeWriter) -> Unit, + ): CoreDocument { + val profile = + Profile( + CoreDocument.DOCUMENT_API_LEVEL, + RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL, + AndroidxRcPlatformServices(), + ) { creationDisplayInfo, p, callback -> + RemoteComposeWriterAndroid(creationDisplayInfo, null, p, callback) + } + val writer = + RemoteComposeWriterAndroid( + profile, + RemoteComposeWriter.hTag(Header.DOC_WIDTH, width), + RemoteComposeWriter.hTag(Header.DOC_HEIGHT, height), + RemoteComposeWriter.hTag(Header.FEATURE_UNIFIED_POINTER_INPUT, 1), + ) + writer.root { content(writer) } + return CoreDocument(RemoteClock.SYSTEM).apply { + ByteArrayInputStream(writer.buffer(), 0, writer.bufferSize()).use { + initFromBuffer(RemoteComposeBuffer.fromInputStream(it)) + } + } + } + + /** A 100x100 box carrying the modifiers [buildModifiers] adds. */ + private fun pointerBoxDocument( + buildModifiers: (RemoteComposeWriter) -> RecordingModifier + ): CoreDocument = + pointerDocument(100, 100) { writer -> + writer.box( + buildModifiers(writer).size(100, 100), + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + + /** + * A 100x100 clickable box, which takes focus so that key events reach it, carrying the + * modifiers [buildModifiers] adds. + */ + private fun focusableBoxDocument( + buildModifiers: (RemoteComposeWriter) -> RecordingModifier + ): CoreDocument = + experimentalDocument(100, 100) { writer -> + writer.box( + buildModifiers(writer).size(100, 100).onClick(HostAction("click")), + BoxLayout.START, + BoxLayout.TOP, + ) {} + } + + private fun RecordingModifier.onPointer( + pass: Int, + subtype: Int, + consumed: Int = POINTER_STATUS_NOT_CONSUMED, + flags: Int = POINTER_STATUS_NOT_CONSUMED, + dataIds: IntArray? = null, + condition: FloatArray? = null, + action: () -> HostAction, + ): RecordingModifier = + onEvent( + EVENT_TYPE_POINTER, + MetadataUtil.pack(pass, subtype, consumed), + flags, + dataIds, + condition, + action(), + ) + + private fun RecordingModifier.onKey( + pass: Int, + subtype: Int, + flags: Int = 0, + dataIds: IntArray? = null, + condition: FloatArray? = null, + action: () -> HostAction, + ): RecordingModifier = + onEvent( + RcPlayerEvents.EVENT_TYPE_KEY, + RcPlayerEvents.metadata(pass, subtype), + flags, + dataIds, + condition, + action(), + ) +}
diff --git a/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RcPlayerRcDocTest.kt b/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RcPlayerRcDocTest.kt new file mode 100644 index 0000000..16ed4f5 --- /dev/null +++ b/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RcPlayerRcDocTest.kt
@@ -0,0 +1,1176 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:Suppress("RestrictedApiAndroidX") +@file:OptIn(ExperimentalRemotePlayerApi::class) + +package androidx.compose.remote.player.compose.embedded + +import android.graphics.Color as AndroidColor +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.Operations +import androidx.compose.remote.core.RcProfiles +import androidx.compose.remote.core.operations.MapRcDocVariables +import androidx.compose.remote.core.operations.TextFromFloat +import androidx.compose.remote.core.operations.Utils +import androidx.compose.remote.core.operations.layout.managers.BoxLayout +import androidx.compose.remote.core.operations.layout.managers.ColumnLayout +import androidx.compose.remote.core.operations.layout.managers.CoreText +import androidx.compose.remote.core.operations.layout.managers.RcDocLayout +import androidx.compose.remote.core.operations.layout.managers.RowLayout +import androidx.compose.remote.core.operations.utilities.AnimatedFloatExpression +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.RemoteComposeWriterAndroid +import androidx.compose.remote.creation.actions.HostAction +import androidx.compose.remote.creation.actions.ValueFloatChange +import androidx.compose.remote.creation.actions.ValueFloatExpressionChange +import androidx.compose.remote.creation.actions.ValueIntegerChange +import androidx.compose.remote.creation.actions.ValueStringChange +import androidx.compose.remote.creation.modifiers.RecordingModifier +import androidx.compose.remote.creation.platform.AndroidxRcPlatformServices +import androidx.compose.remote.player.compose.ExperimentalRemotePlayerApi +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.height +import androidx.compose.ui.unit.width +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.awaitCancellation +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35], qualifiers = "w400dp-h400dp-mdpi") +class RcPlayerRcDocTest { + + @get:Rule val enableEmbeddedPlayer = EnableEmbeddedPlayerRule() + + @get:Rule val rule = createComposeRule() + + private fun buildBytes( + width: Int = 200, + height: Int = 100, + block: RemoteComposeWriter.() -> Unit, + ): ByteArray { + val writer = + RemoteComposeWriterAndroid( + width, + height, + "EmbeddedChild", + CoreDocument.DOCUMENT_API_LEVEL, + RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL, + AndroidxRcPlatformServices(), + ) + writer.block() + return writer.encodeToByteArray() + } + + private fun RemoteComposeWriter.addCoreText( + textId: Int, + modifier: RecordingModifier = RecordingModifier(), + color: Int = AndroidColor.BLACK, + fontSize: Float = 16f, + ) { + textComponent( + modifier, + textId, + color, + fontSize, + 0, + 400f, + null, + CoreText.TEXT_ALIGN_LEFT, + CoreText.OVERFLOW_CLIP, + 1, + ) {} + } + + private fun RemoteComposeWriter.addCoreText( + text: String, + modifier: RecordingModifier = RecordingModifier(), + color: Int = AndroidColor.BLACK, + fontSize: Float = 16f, + ) { + addCoreText(addText(text), modifier, color, fontSize) + } + + @Test + fun rcDoc_viaRcResolver_rendersChildAndAdoptsIntrinsicSize() { + val childBytes = + buildBytes(width = 160, height = 80) { + root { + box( + RecordingModifier().fillMaxSize().background(AndroidColor.GREEN), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("ChildHello") + } + } + } + + val hostDoc = + buildWriterDocument(width = 400, height = 400) { + root { + box( + RecordingModifier().padding(30, 50, 0, 0), + BoxLayout.START, + BoxLayout.TOP, + ) { + rcDoc("widget://card") + } + } + } + + rule.setContent { + Box(modifier = Modifier.size(400.dp)) { + RcPlayer( + document = hostDoc, + documentResolver = + RcDocumentResolver { url -> + if (url == "widget://card") childBytes else null + }, + ) + } + } + + rule.onNodeWithText("ChildHello").assertIsDisplayed() + // At mdpi (density = 1), 160x80 px == 160x80 dp, placed inside the (30, 50) padding. + val bitmap = rule.captureRootBitmap() + // Inside the embedded green child (30..190, 50..130): + assertThat(bitmap.getPixel(35, 55)).isEqualTo(AndroidColor.GREEN) + assertThat(bitmap.getPixel(185, 125)).isEqualTo(AndroidColor.GREEN) + // Outside the embedded child: + assertThat(bitmap.getPixel(20, 55)).isNotEqualTo(AndroidColor.GREEN) + assertThat(bitmap.getPixel(200, 125)).isNotEqualTo(AndroidColor.GREEN) + } + + @Test + fun rcDoc_unresolvedAndLateRegisteredRcResolver() { + val childBytes = + buildBytes(width = 120, height = 60) { + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText("ResolvedLate") + } + } + } + + val hostDoc = + buildWriterDocument(width = 300, height = 300) { + root { rcDoc("host://late", RecordingModifier().size(120, 60)) } + } + + var resolver by mutableStateOf<RcDocumentResolver?>(null) + var nullResolveCalls = 0 + + rule.setContent { + Box(modifier = Modifier.size(300.dp)) { + RcPlayer(document = hostDoc, documentResolver = resolver) + } + } + + // 1. Without a resolver, renders cleanly with no child text. + rule.onNodeWithText("ResolvedLate").assertDoesNotExist() + + // 2. Registering a null-returning resolver resolves once and does not spam. + resolver = RcDocumentResolver { _ -> + nullResolveCalls++ + null + } + rule.waitForIdle() + assertThat(nullResolveCalls).isEqualTo(1) + rule.onNodeWithText("ResolvedLate").assertDoesNotExist() + + // 3. Swapping in a resolver that returns valid bytes loads and renders the child. + resolver = RcDocumentResolver { url -> if (url == "host://late") childBytes else null } + rule.waitForIdle() + rule.onNodeWithText("ResolvedLate").assertIsDisplayed() + } + + @Test + fun rcDoc_suspendingDocumentResolver_loadsAsynchronously() { + val childBytes = + buildBytes(width = 140, height = 60) { + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText("LoadedAsync") + } + } + } + val hostDoc = + buildWriterDocument(width = 300, height = 300) { + root { rcDoc("async://card", RecordingModifier().size(140, 60)) } + } + val deferred = CompletableDeferred<ByteArray?>() + + rule.setContent { + Box(modifier = Modifier.size(300.dp)) { + RcPlayer( + document = hostDoc, + documentResolver = + RcDocumentResolver { url -> + if (url == "async://card") deferred.await() else null + }, + ) + } + } + + rule.onNodeWithText("LoadedAsync").assertDoesNotExist() + deferred.complete(childBytes) + rule.waitForIdle() + rule.onNodeWithText("LoadedAsync").assertIsDisplayed() + } + + @Test + fun rcDoc_embeddedBinaryDataById_loadsWithoutResolver() { + val childBytes = + buildBytes(width = 160, height = 60) { + val titleId = addNamedString("title", "default") + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText(titleId) + } + } + } + + val hostDoc = + buildWriterDocument(width = 300, height = 300) { + val hostTitle = addNamedString("hostTitle", "InlineTitle") + val embeddedId = addEmbeddedDocument(childBytes) + root { + val docId = rcDoc(embeddedId, RecordingModifier().size(160, 60)) + mapRcDocVariables(docId, RemoteComposeWriter.MAP_FORWARD, hostTitle, "title") + } + } + + // No RcResolver provided at all. + rule.setContent { Box(modifier = Modifier.size(300.dp)) { RcPlayer(document = hostDoc) } } + + rule.onNodeWithText("InlineTitle").assertIsDisplayed() + } + + @Test + fun rcDoc_embeddedUrlScheme_switchesBetweenEmbeddedAndResolved() { + fun childWithLabel(label: String): ByteArray = + buildBytes(width = 120, height = 50) { + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText(label) + } + } + } + + val childA = childWithLabel("EmbeddedA") + val childB = childWithLabel("EmbeddedB") + val childC = childWithLabel("ResolvedC") + + var embeddedBId = -1 + val hostDoc = + buildWriterDocument(width = 300, height = 300) { + val embeddedA = addEmbeddedDocument(childA) + embeddedBId = addEmbeddedDocument(childB) + val urlVar = addNamedString("docUrl", RcDocLayout.EMBEDDED_URL_PREFIX + embeddedA) + root { rcDoc(urlVar, RecordingModifier().size(120, 50)) } + } + + val resolvedUrls = mutableListOf<String>() + val playerState = RcPlayerState(hostDoc, defaultPrefix = null) + var docUrl by playerState.stringState("docUrl") + + rule.setContent { + Box(modifier = Modifier.size(300.dp)) { + RcPlayer( + state = playerState, + documentResolver = + RcDocumentResolver { url -> + resolvedUrls.add(url) + if (url == "host://c") childC else null + }, + ) + } + } + + rule.onNodeWithText("EmbeddedA").assertIsDisplayed() + assertThat(resolvedUrls).isEmpty() + + // Switch to second embedded blob: resolver is still not consulted. + docUrl = RcDocLayout.EMBEDDED_URL_PREFIX + embeddedBId + rule.waitForIdle() + rule.onNodeWithText("EmbeddedB").assertIsDisplayed() + assertThat(resolvedUrls).isEmpty() + + // Switch to external URL: resolver is consulted. + docUrl = "host://c" + rule.waitForIdle() + rule.onNodeWithText("ResolvedC").assertIsDisplayed() + assertThat(resolvedUrls).containsExactly("host://c") + + // Switch to missing embedded blob id: falls through cleanly and renders nothing. + docUrl = RcDocLayout.EMBEDDED_URL_PREFIX + "9999" + rule.waitForIdle() + rule.onNodeWithText("ResolvedC").assertDoesNotExist() + } + + @Test + fun rcDoc_dynamicUrlVariableReloadsDocumentOnClick() { + val childA = + buildBytes(width = 120, height = 50) { + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText("DocA") + } + } + } + val childB = + buildBytes(width = 120, height = 50) { + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText("DocB") + } + } + } + + val hostDoc = + buildWriterDocument(width = 200, height = 150) { + val urlVarId = addNamedString("docUrl", "widget://a") + root { + column( + RecordingModifier().size(120, 100), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + box( + RecordingModifier() + .size(120, 50) + .onClick(ValueStringChange(urlVarId, "widget://b")), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("Switch") + } + rcDoc(urlVarId, RecordingModifier().size(120, 50)) + } + } + } + + rule.setContent { + Box(modifier = Modifier.size(200.dp)) { + RcPlayer( + document = hostDoc, + documentResolver = + RcDocumentResolver { url -> + when (url) { + "widget://a" -> childA + "widget://b" -> childB + else -> null + } + }, + ) + } + } + + rule.onNodeWithText("DocA").assertIsDisplayed() + rule.onNodeWithText("Switch").performClick() + rule.waitForIdle() + rule.onNodeWithText("DocB").assertIsDisplayed() + } + + @Test + fun rcDoc_defaultNestingDepthIsOne_andConfigurableViaLocal() { + val leafBytes = + buildBytes(width = 100, height = 40) { + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText("LeafDoc") + } + } + } + val middleBytes = + buildBytes(width = 150, height = 80) { + val leafId = addEmbeddedDocument(leafBytes) + root { + column( + RecordingModifier().size(150, 80), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + addCoreText("MiddleDoc") + rcDoc(leafId, RecordingModifier().size(100, 40)) + } + } + } + val hostDoc = + buildWriterDocument(width = 300, height = 300) { + val middleId = addEmbeddedDocument(middleBytes) + root { rcDoc(middleId, RecordingModifier().size(150, 80)) } + } + + var maxDepth by mutableStateOf(DEFAULT_MAX_RC_DOC_NESTING_DEPTH) + + rule.setContent { + CompositionLocalProvider(LocalRcDocMaxNestingDepth provides maxDepth) { + Box(modifier = Modifier.size(300.dp)) { RcPlayer(document = hostDoc) } + } + } + + // Default depth (1): direct child renders, grandchild is skipped. + rule.onNodeWithText("MiddleDoc").assertIsDisplayed() + rule.onNodeWithText("LeafDoc").assertDoesNotExist() + + // Increasing maxDepth to 2 enables grandchildren. + maxDepth = 2 + rule.waitForIdle() + rule.onNodeWithText("MiddleDoc").assertIsDisplayed() + rule.onNodeWithText("LeafDoc").assertIsDisplayed() + + // Setting maxDepth to 0 disables embedded documents altogether. + maxDepth = 0 + rule.waitForIdle() + rule.onNodeWithText("MiddleDoc").assertDoesNotExist() + rule.onNodeWithText("LeafDoc").assertDoesNotExist() + } + + @Test + fun rcDoc_cyclicResolver_stopsAtNestingCapWithoutCrashing() { + val cyclicBytes = + buildBytes(width = 100, height = 50) { + root { rcDoc("loop://self", RecordingModifier().size(100, 50)) } + } + val hostDoc = + buildWriterDocument(width = 200, height = 200) { + root { + column( + RecordingModifier().size(200, 200), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + addCoreText("HostStillAlive") + rcDoc("loop://self", RecordingModifier().size(100, 50)) + } + } + } + + rule.setContent { + Box(modifier = Modifier.size(200.dp)) { + RcPlayer( + document = hostDoc, + documentResolver = + RcDocumentResolver { url -> + if (url == "loop://self") cyclicBytes else null + }, + ) + } + } + + rule.onNodeWithText("HostStillAlive").assertIsDisplayed() + } + + @Test + fun mapRcDocVariables_forwardReverseAndBidirectional() { + val childBytes = + buildBytes(width = 200, height = 100) { + val inTitle = addNamedString("inTitle", "defaultTitle") + val inCount = addNamedInt("inCount", 0).toInt() + val outStatus = addNamedString("outStatus", "childReady") + val biCounter = addNamedFloat("biCounter", 10f) + val biCounterText = createTextFromFloat(biCounter, 3, 0, TextFromFloat.PAD_PRE_NONE) + val inCountFloat = floatExpression(Utils.asNan(inCount)) + val inCountText = + createTextFromFloat(inCountFloat, 3, 0, TextFromFloat.PAD_PRE_NONE) + + root { + column( + RecordingModifier() + .size(200, 100) + .onClick( + ValueFloatChange(Utils.idFromNan(biCounter), 42f), + ValueStringChange(outStatus, "childClicked"), + ), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + addCoreText(inTitle) + addCoreText(biCounterText) + addCoreText(inCountText) + } + } + } + + val hostDoc = + buildWriterDocument(width = 300, height = 200) { + val hostTitle = addNamedString("hostTitle", "ParentTitle") + val hostCount = addNamedInt("hostCount", 5).toInt() + val hostStatus = addNamedString("hostStatus", "initial") + val hostCounter = addNamedFloat("hostCounter", 7f) + + root { + column( + RecordingModifier().size(200, 200), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + addCoreText(hostStatus) + val docId = rcDoc("widget://vars", RecordingModifier().size(200, 100)) + mapRcDocVariables( + docId, + RemoteComposeWriter.MAP_FORWARD, + hostTitle, + "inTitle", + ) + mapRcDocVariables( + docId, + RemoteComposeWriter.MAP_FORWARD, + hostCount, + "inCount", + ) + mapRcDocVariables( + docId, + RemoteComposeWriter.MAP_REVERSE, + hostStatus, + "outStatus", + ) + mapRcDocVariables( + docId, + RemoteComposeWriter.MAP_BIDIRECTIONAL, + hostCounter, + "biCounter", + ) + } + } + } + + val playerState = RcPlayerState(hostDoc, defaultPrefix = null) + var hostTitle by playerState.stringState("hostTitle") + var hostCount by playerState.intState("hostCount") + val hostStatus by playerState.stringState("hostStatus") + var hostCounter by playerState.floatState("hostCounter") + + rule.setContent { + Box(modifier = Modifier.size(300.dp)) { + RcPlayer( + state = playerState, + documentResolver = + RcDocumentResolver { url -> + if (url == "widget://vars") childBytes else null + }, + ) + } + } + + // 1. Initial sync: forward pushed "ParentTitle" & 5, reverse pulled "childReady", + // bidirectional pushed initial host value 7. + rule.onNodeWithText("ParentTitle").assertIsDisplayed() + rule.onNodeWithText("7").assertIsDisplayed() + rule.onNodeWithText("5").assertIsDisplayed() + rule.onNodeWithText("childReady").assertIsDisplayed() + assertThat(hostStatus).isEqualTo("childReady") + + // 2. Host updates propagate forward and bidirectionally into the child. + hostTitle = "UpdatedFromHost" + hostCount = 9 + hostCounter = 15f + rule.waitForIdle() + rule.onNodeWithText("UpdatedFromHost").assertIsDisplayed() + rule.onNodeWithText("9").assertIsDisplayed() + rule.onNodeWithText("15").assertIsDisplayed() + + // 3. Clicking inside the child updates biCounter -> 42 and outStatus -> "childClicked", + // which sync back to the host. + rule.onNodeWithText("UpdatedFromHost").performClick() + rule.waitForIdle() + assertThat(hostCounter).isEqualTo(42f) + assertThat(hostStatus).isEqualTo("childClicked") + rule.onNodeWithText("42").assertIsDisplayed() + rule.onNodeWithText("childClicked").assertIsDisplayed() + } + + @Test + fun mapRcDocVariables_hostActionMapsKnownIdAndForwardsUnknownId() { + val mappedActionId = 1001 + val unmappedActionId = 2002 + + val childBytes = + buildBytes(width = 200, height = 100) { + val mappedMetaId = addText("mapped_payload") + val unmappedMetaId = addText("unmapped_payload") + root { + column( + RecordingModifier().size(200, 100), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + box( + RecordingModifier() + .size(200, 50) + .onClick(HostAction(mappedActionId, mappedMetaId)), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("MappedBtn") + } + box( + RecordingModifier() + .size(200, 50) + .onClick(HostAction(unmappedActionId, unmappedMetaId)), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("UnmappedBtn") + } + } + } + } + + val hostDoc = + buildWriterDocument(width = 300, height = 200) { + val actionResultVar = addNamedString("actionResult", "none") + root { + column( + RecordingModifier().size(200, 160), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + addCoreText(actionResultVar) + val docId = rcDoc("widget://actions", RecordingModifier().size(200, 100)) + mapRcDocVariables( + docId, + MapRcDocVariables.MAP_HOST_ACTION, + actionResultVar, + mappedActionId, + ) + } + } + } + + val hostReceivedActions = mutableListOf<Pair<Int, String?>>() + + rule.setContent { + Box(modifier = Modifier.size(300.dp)) { + RcPlayer( + document = hostDoc, + documentResolver = + RcDocumentResolver { url -> + if (url == "widget://actions") childBytes else null + }, + onAction = { id, value -> hostReceivedActions.add(id to value) }, + ) + } + } + + rule.onNodeWithText("none").assertIsDisplayed() + + // 1. Mapped action writes metadata to host string variable and is NOT forwarded to host. + rule.onNodeWithText("MappedBtn").performClick() + rule.waitForIdle() + rule.onNodeWithText("mapped_payload").assertIsDisplayed() + assertThat(hostReceivedActions).isEmpty() + + // 2. Unmapped action IS forwarded to host onAction callback. + rule.onNodeWithText("UnmappedBtn").performClick() + rule.waitForIdle() + assertThat(hostReceivedActions).containsExactly(unmappedActionId to "unmapped_payload") + } + + @Test + fun rcDoc_twoChildrenInteractViaParentBusAndGrandchildExpression() { + val childABytes = + buildBytes(width = 160, height = 50) { + val outVal = addNamedInt("outVal", 10).toInt() + root { + box( + RecordingModifier().size(160, 50).onClick(ValueIntegerChange(outVal, 30)), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("BumpA") + } + } + } + + val grandchildBytes = + buildBytes(width = 160, height = 50) { + val level = addNamedFloat("level", 0f) + val levelText = createTextFromFloat(level, 3, 0, TextFromFloat.PAD_PRE_NONE) + root { + box(RecordingModifier().fillMaxSize(), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText(levelText) + } + } + } + + val middleBytes = + buildBytes(width = 160, height = 50) { + val inLevel = addNamedFloat("inLevel", 0f) + val complement = floatExpression(100f, inLevel, AnimatedFloatExpression.SUB) + root { + val gcId = rcDoc("child://grandchild", RecordingModifier().size(160, 50)) + mapRcDocVariables(gcId, RemoteComposeWriter.MAP_FORWARD, complement, "level") + } + } + + val hostDoc = + buildWriterDocument(width = 200, height = 200) { + val sharedInt = addNamedInt("shared", 10).toInt() + val sharedFloat = floatExpression(Utils.asNan(sharedInt)) + root { + column( + RecordingModifier().size(160, 120), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + val aId = rcDoc("child://a", RecordingModifier().size(160, 50)) + mapRcDocVariables(aId, RemoteComposeWriter.MAP_REVERSE, sharedInt, "outVal") + + val midId = rcDoc("child://middle", RecordingModifier().size(160, 50)) + mapRcDocVariables( + midId, + RemoteComposeWriter.MAP_FORWARD, + sharedFloat, + "inLevel", + ) + } + } + } + + rule.setContent { + CompositionLocalProvider(LocalRcDocMaxNestingDepth provides 2) { + Box(modifier = Modifier.size(200.dp)) { + RcPlayer( + document = hostDoc, + documentResolver = + RcDocumentResolver { url -> + when (url) { + "child://a" -> childABytes + "child://middle" -> middleBytes + "child://grandchild" -> grandchildBytes + else -> null + } + }, + ) + } + } + } + + // Initial: Child A outVal = 10 -> host shared = 10 -> middle complement = 90 -> grandchild + // 90 + rule.onNodeWithText("90").assertIsDisplayed() + + // Click Child A -> outVal = 30 -> host shared = 30 -> middle complement = 70 -> grandchild + // 70 + rule.onNodeWithText("BumpA").performClick() + rule.waitForIdle() + rule.onNodeWithText("70").assertIsDisplayed() + } + + @Test + fun scrollOverride_verticalActionUpdatesComposeScrollPosition() { + val doc = + buildWriterDocument(width = 200, height = 300) { + val pos = addNamedFloat("pos", 0f) + val step = floatExpression(pos, 100f, AnimatedFloatExpression.ADD) + root { + column( + RecordingModifier().size(200, 300), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + column( + RecordingModifier().size(200, 100).verticalScroll(pos), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + for (i in 0 until 5) { + box( + RecordingModifier().size(200, 100), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("Item$i") + } + } + } + box( + RecordingModifier() + .size(200, 100) + .onClick( + ValueFloatExpressionChange( + Utils.idFromNan(pos), + Utils.idFromNan(step), + ) + ), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("ScrollNext") + } + } + } + } + + val state = RcPlayerState(doc, defaultPrefix = null) + val pos by state.floatState("pos") + + rule.setContent { + Box(modifier = Modifier.size(200.dp, 300.dp).testTag("root")) { + RcPlayer(state = state) + } + } + + assertThat(pos).isEqualTo(0f) + val initialItem0Top = rule.onNodeWithText("Item0").getUnclippedBoundsInRoot().top + + rule.onNodeWithText("ScrollNext").performClick() + rule.waitForIdle() + assertThat(pos).isEqualTo(100f) + val afterFirstClickTop = rule.onNodeWithText("Item0").getUnclippedBoundsInRoot().top + assertThat(initialItem0Top.value - afterFirstClickTop.value).isWithin(2f).of(100f) + + rule.onNodeWithText("ScrollNext").performClick() + rule.waitForIdle() + assertThat(pos).isEqualTo(200f) + val afterSecondClickTop = rule.onNodeWithText("Item0").getUnclippedBoundsInRoot().top + assertThat(initialItem0Top.value - afterSecondClickTop.value).isWithin(2f).of(200f) + } + + @Test + fun scrollOverride_horizontalActionUpdatesComposeScrollPosition() { + val doc = + buildWriterDocument(width = 200, height = 200) { + val pos = addNamedFloat("pos", 0f) + val step = floatExpression(pos, 100f, AnimatedFloatExpression.ADD) + root { + column( + RecordingModifier().size(200, 200), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + row( + RecordingModifier().size(200, 100).horizontalScroll(pos), + RowLayout.START, + RowLayout.TOP, + ) { + for (i in 0 until 5) { + box( + RecordingModifier().size(100, 100), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("HItem$i") + } + } + } + box( + RecordingModifier() + .size(200, 100) + .onClick( + ValueFloatExpressionChange( + Utils.idFromNan(pos), + Utils.idFromNan(step), + ) + ), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("ScrollRight") + } + } + } + } + + val state = RcPlayerState(doc, defaultPrefix = null) + val pos by state.floatState("pos") + + rule.setContent { + Box(modifier = Modifier.size(200.dp)) { RcPlayer(state = state) } + } + + assertThat(pos).isEqualTo(0f) + val initialLeft = rule.onNodeWithText("HItem0").getUnclippedBoundsInRoot().left + + rule.onNodeWithText("ScrollRight").performClick() + rule.waitForIdle() + assertThat(pos).isEqualTo(100f) + val afterClickLeft = rule.onNodeWithText("HItem0").getUnclippedBoundsInRoot().left + assertThat(initialLeft.value - afterClickLeft.value).isWithin(2f).of(100f) + } + + @Test + fun featureSet_marksEmbeddedDocOpcodesAsBuiltIn() { + val experimental = RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL + val unsupported = RcPlayerFeatureSet.Empty.unsupportedOpcodes(experimental) + + assertThat(Operations.LAYOUT_RC_DOC in unsupported).isFalse() + assertThat(Operations.MAP_RC_DOC_VARIABLES in unsupported).isFalse() + assertThat(Operations.BINARY_DATA in unsupported).isFalse() + } + + @Test + fun hostClick_doesNotRevertReverseMappedInlineVariable() { + val childBytes = + buildBytes(width = 160, height = 80) { + val childScore = addNamedFloat("score", 10f) + root { + box( + RecordingModifier() + .size(160, 80) + .onClick(ValueFloatChange(Utils.idFromNan(childScore), 99f)), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("BumpChild") + } + } + } + + val hostDoc = + buildWriterDocument(width = 200, height = 200) { + val hostScore = addNamedFloat("hostScore", 0f) + val hostOther = addNamedFloat("hostOther", 0f) + val blobId = addEmbeddedDocument(childBytes) + root { + column( + RecordingModifier().size(200, 200), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + val docId = rcDoc(blobId, RecordingModifier().size(160, 80)) + mapRcDocVariables( + docId, + MapRcDocVariables.MAP_REVERSE, + Utils.idFromNan(hostScore), + "score", + ) + box( + RecordingModifier() + .size(160, 80) + .onClick(ValueFloatChange(Utils.idFromNan(hostOther), 1f)), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("HostClick") + } + } + } + } + + val state = RcPlayerState(hostDoc, defaultPrefix = null) + val hostScore by state.floatState("hostScore") + + rule.setContent { Box(modifier = Modifier.size(200.dp)) { RcPlayer(state = state) } } + rule.waitForIdle() + assertThat(hostScore).isEqualTo(10f) + + rule.onNodeWithText("BumpChild").performClick() + rule.waitForIdle() + assertThat(hostScore).isEqualTo(99f) + + // Clicking an unrelated host control invokes updateVariablesWithoutRcDoc; it must not + // parse a phantom child document or overwrite hostScore back to 10f. + rule.onNodeWithText("HostClick").performClick() + rule.waitForIdle() + assertThat(hostScore).isEqualTo(99f) + } + + @Test + fun measureProbe_skipsVariableSyncAndDoesNotOverwriteHost() { + val childBytes = + buildBytes(width = 120, height = 60) { + addNamedFloat("score", 77f) + root { + box(RecordingModifier().size(120, 60), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText("ProbeChild") + } + } + } + + val hostDoc = + buildWriterDocument(width = 200, height = 100) { + val hostScore = addNamedFloat("hostScore", 5f) + val blobId = addEmbeddedDocument(childBytes) + root { + val docId = rcDoc(blobId, RecordingModifier().size(120, 60)) + mapRcDocVariables( + docId, + MapRcDocVariables.MAP_REVERSE, + Utils.idFromNan(hostScore), + "score", + ) + } + } + + val state = RcPlayerState(hostDoc, defaultPrefix = null) + val hostScore by state.floatState("hostScore") + + rule.setContent { + CompositionLocalProvider(LocalRcIsMeasureProbe provides true) { + Box(modifier = Modifier.size(200.dp, 100.dp)) { RcPlayer(state = state) } + } + } + rule.waitForIdle() + assertThat(hostScore).isEqualTo(5f) + } + + @Test + fun urlSwitch_cancellingSlowFetchDoesNotClobberFastResolution() { + val childBBytes = + buildBytes(width = 160, height = 80) { + root { + box(RecordingModifier().size(160, 80), BoxLayout.CENTER, BoxLayout.CENTER) { + addCoreText("FastChildB") + } + } + } + + val hostDoc = + buildWriterDocument(width = 200, height = 100) { + val urlId = addNamedString("docUrl", "rc://slow-a") + root { rcDoc(urlId, RecordingModifier().size(160, 80)) } + } + + val state = RcPlayerState(hostDoc, defaultPrefix = null) + var docUrl by state.stringState("docUrl") + + val resolver = RcDocumentResolver { url -> + when (url) { + "rc://slow-a" -> awaitCancellation() + "rc://fast-b" -> childBBytes + else -> null + } + } + + rule.setContent { + Box(modifier = Modifier.size(200.dp, 100.dp)) { + RcPlayer(state = state, documentResolver = resolver) + } + } + rule.waitForIdle() + + // Switch URL while "rc://slow-a" is still suspended; cancelling it must not clobber B. + docUrl = "rc://fast-b" + rule.waitForIdle() + rule.onNodeWithText("FastChildB").assertIsDisplayed() + } + + @Test + fun scrollOverride_outOfBoundsClampsPositionVariable() { + val doc = + buildWriterDocument(width = 200, height = 200) { + val pos = addNamedFloat("pos", 0f) + root { + column( + RecordingModifier().size(200, 100).verticalScroll(pos), + ColumnLayout.START, + ColumnLayout.TOP, + ) { + for (i in 0 until 5) { + box( + RecordingModifier().size(200, 100), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("ClampItem$i") + } + } + } + } + } + + val state = RcPlayerState(doc, defaultPrefix = null) + var pos by state.floatState("pos") + + rule.setContent { Box(modifier = Modifier.size(200.dp)) { RcPlayer(state = state) } } + rule.waitForIdle() + assertThat(pos).isEqualTo(0f) + + // Negative override should clamp back to 0f. + pos = -100f + rule.waitForIdle() + assertThat(pos).isEqualTo(0f) + + // Past-end override should clamp back to maxValue (400f for 5x100 in 100 viewport). + pos = 999f + rule.waitForIdle() + assertThat(pos).isEqualTo(400f) + } + + @Test + fun reverseColorMapping_continuesUpdatingAfterHostColorOverride() { + val childBytes = + buildBytes(width = 160, height = 80) { + val progress = addNamedFloat("progress", 0f) + val childColor = + addColorExpression(AndroidColor.BLUE, AndroidColor.GREEN, progress).toInt() + setColorName(childColor, "accent") + root { + box( + RecordingModifier() + .size(160, 80) + .onClick(ValueFloatChange(Utils.idFromNan(progress), 1f)), + BoxLayout.CENTER, + BoxLayout.CENTER, + ) { + addCoreText("TurnGreen") + } + } + } + + val hostDoc = + buildWriterDocument(width = 200, height = 100) { + val hostColor = addNamedColor("hostAccent", AndroidColor.RED) + val blobId = addEmbeddedDocument(childBytes) + root { + val docId = rcDoc(blobId, RecordingModifier().size(160, 80)) + mapRcDocVariables(docId, MapRcDocVariables.MAP_REVERSE, hostColor, "accent") + } + } + + val state = RcPlayerState(hostDoc, defaultPrefix = null) + var hostAccent by state.colorState("hostAccent") + + rule.setContent { + Box(modifier = Modifier.size(200.dp, 100.dp)) { RcPlayer(state = state) } + } + rule.waitForIdle() + assertThat(hostAccent).isEqualTo(Color(AndroidColor.BLUE)) + + // Host writes an override (setting mColorOverride on hostAccent). + hostAccent = Color(AndroidColor.MAGENTA) + rule.waitForIdle() + assertThat(hostAccent).isEqualTo(Color(AndroidColor.MAGENTA)) + + // Child updates the mapped color; reverse sync must still propagate through overrideColor. + rule.onNodeWithText("TurnGreen").performClick() + rule.waitForIdle() + assertThat(hostAccent).isEqualTo(Color(AndroidColor.GREEN)) + } +}
diff --git a/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RemotePlayerTestRule.kt b/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RemotePlayerTestRule.kt new file mode 100644 index 0000000..8916a2e --- /dev/null +++ b/compose/remote/remote-player-compose/src/test/java/androidx/compose/remote/player/compose/embedded/RemotePlayerTestRule.kt
@@ -0,0 +1,208 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.compose.remote.player.compose.embedded + +import android.view.KeyEvent +import android.view.View +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.RcProfiles +import androidx.compose.remote.core.RemoteClock +import androidx.compose.remote.core.RemoteComposeBuffer +import androidx.compose.remote.creation.CreationDisplayInfo +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.RemoteComposeWriterAndroid +import androidx.compose.remote.creation.platform.AndroidxRcPlatformServices +import androidx.compose.remote.creation.profile.Profile +import androidx.compose.remote.player.compose.ExperimentalRemotePlayerApi +import androidx.compose.remote.player.compose.RemoteComposePlayerFlags +import androidx.compose.remote.player.compose.RemoteDocumentPlayer +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.input.InputModeManager +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.click +import androidx.compose.ui.test.junit4.ComposeContentTestRule +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.unit.dp +import androidx.test.platform.app.InstrumentationRegistry +import java.io.ByteArrayInputStream +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement + +/** The Remote Compose players, for tests that run against each of them. */ +enum class PlayerUnderTest { + /** The embedded player, `RcPlayer`, which plays documents with Compose. */ + Embedded, + + /** The View player, `RemoteComposePlayer`, hosted in Compose by `RemoteDocumentPlayer`. */ + View; + + companion object { + /** The players, as parameters for `ParameterizedRobolectricTestRunner`. */ + @JvmStatic fun parameters(): List<Array<Any>> = entries.map { arrayOf(it) } + } +} + +/** + * Plays documents with [player] in a Compose host, and drives them with input dispatched through + * the host window, so the same test runs against both players. Interactions are observed through + * the host named actions the document runs ([takeNamedActions]). + */ +@OptIn(ExperimentalRemotePlayerApi::class, ExperimentalComposeUiApi::class) +class RemotePlayerTestRule(val player: PlayerUnderTest) : TestRule { + + val composeRule: ComposeContentTestRule = createComposeRule() + + private val namedActions = mutableListOf<Pair<String, Any?>>() + private lateinit var hostView: View + private lateinit var inputModeManager: InputModeManager + + override fun apply(base: Statement, description: Description): Statement = + composeRule.apply( + object : Statement() { + override fun evaluate() { + val previous = RemoteComposePlayerFlags.isEmbeddedPlayerEnabled + try { + RemoteComposePlayerFlags.isEmbeddedPlayerEnabled = + player == PlayerUnderTest.Embedded + base.evaluate() + } finally { + RemoteComposePlayerFlags.isEmbeddedPlayerEnabled = previous + } + } + }, + description, + ) + + /** Plays [document], sized [width] x [height] dp (pixels, at the test density of 1). */ + fun play(document: CoreDocument, width: Int, height: Int) { + composeRule.setContent { + hostView = LocalView.current + inputModeManager = LocalInputModeManager.current + Box(Modifier.size(width.dp, height.dp)) { + when (player) { + PlayerUnderTest.Embedded -> + RcPlayer( + document = document, + onNamedAction = { name, value, _ -> namedActions += name to value }, + ) + PlayerUnderTest.View -> + RemoteDocumentPlayer( + document = document, + documentWidth = width, + documentHeight = height, + onNamedAction = { name, value, _ -> namedActions += name to value }, + ) + } + } + } + // Start in non-touch mode, as when navigating with a hardware keyboard, where Compose + // clickables are focusable. + setTouchMode(false) + if (player == PlayerUnderTest.View) { + // Trigger a draw pass so the View-backed player lays out its RemoteCompose components. + composeRule.onRoot().captureToImage() + } + } + + /** Switches the window, and Compose's input mode, in or out of touch mode. */ + private fun setTouchMode(inTouchMode: Boolean) { + InstrumentationRegistry.getInstrumentation().setInTouchMode(inTouchMode) + composeRule.runOnIdle { + inputModeManager.requestInputMode( + if (inTouchMode) InputMode.Touch else InputMode.Keyboard + ) + } + composeRule.waitForIdle() + } + + /** + * Gives the host view focus, as the window does when focus moves into it. Both players then + * focus their first focus target. + */ + fun focusHost() { + composeRule.runOnIdle { hostView.requestFocus() } + composeRule.waitForIdle() + } + + /** + * Presses and releases [keyCode] through the host window. + * + * @return whether the key down was handled. + */ + fun pressKey(keyCode: Int, metaState: Int = 0): Boolean { + // A hardware key press puts the window in non-touch mode. + setTouchMode(false) + val handled = composeRule.runOnIdle { + val root = hostView.rootView + val handled = + root.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, keyCode, 0, metaState)) + root.dispatchKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_UP, keyCode, 0, metaState)) + handled + } + composeRule.waitForIdle() + return handled + } + + /** Taps at ([x], [y]) in the host. */ + fun tap(x: Float, y: Float) { + // A touch puts the window in touch mode. + setTouchMode(true) + composeRule.onRoot().performTouchInput { click(Offset(x, y)) } + composeRule.waitForIdle() + } + + /** Returns the named actions run since the last call, as (name, value) pairs. */ + fun takeNamedActions(): List<Pair<String, Any?>> = composeRule.runOnIdle { + namedActions.toList().also { namedActions.clear() } + } +} + +/** + * Writes a [width] x [height] document with [content] using the experimental AndroidX profile, + * which has the event and focus operations, and inflates it. + */ +fun experimentalDocument( + width: Int, + height: Int, + content: (RemoteComposeWriter) -> Unit, +): CoreDocument { + val profile = + Profile( + CoreDocument.DOCUMENT_API_LEVEL, + RcProfiles.PROFILE_ANDROIDX or RcProfiles.PROFILE_EXPERIMENTAL, + AndroidxRcPlatformServices(), + ) { creationDisplayInfo, profile, callback -> + RemoteComposeWriterAndroid(creationDisplayInfo, null, profile, callback) + } + val writer = profile.create(CreationDisplayInfo(width, height, 160), "test") + writer.root { content(writer) } + return CoreDocument(RemoteClock.SYSTEM).apply { + ByteArrayInputStream(writer.buffer(), 0, writer.bufferSize()).use { + initFromBuffer(RemoteComposeBuffer.fromInputStream(it)) + } + } +}
diff --git a/compose/test-utils/build.gradle b/compose/test-utils/build.gradle index a6edf3e..50b5bd9 100644 --- a/compose/test-utils/build.gradle +++ b/compose/test-utils/build.gradle
@@ -62,6 +62,7 @@ } androidDeviceTest.dependencies { + implementation(project(":compose:ui:ui")) implementation(libs.truth) implementation("androidx.compose.material:material:1.12.0") }
diff --git a/compose/test-utils/src/androidMain/kotlin/androidx/compose/testutils/AndroidComposeTestCaseRunner.android.kt b/compose/test-utils/src/androidMain/kotlin/androidx/compose/testutils/AndroidComposeTestCaseRunner.android.kt index ee2113a..3c0bd66 100644 --- a/compose/test-utils/src/androidMain/kotlin/androidx/compose/testutils/AndroidComposeTestCaseRunner.android.kt +++ b/compose/test-utils/src/androidMain/kotlin/androidx/compose/testutils/AndroidComposeTestCaseRunner.android.kt
@@ -464,4 +464,4 @@ } } -private val InternallyLaunchedCoroutines = 4 +private val InternallyLaunchedCoroutines = 0
diff --git a/compose/ui/ui/benchmark/src/androidTest/java/androidx/compose/ui/benchmark/focus/ParameterizedFocusBenchmark.kt b/compose/ui/ui/benchmark/src/androidTest/java/androidx/compose/ui/benchmark/focus/ParameterizedFocusBenchmark.kt index 9217753..8000166 100644 --- a/compose/ui/ui/benchmark/src/androidTest/java/androidx/compose/ui/benchmark/focus/ParameterizedFocusBenchmark.kt +++ b/compose/ui/ui/benchmark/src/androidTest/java/androidx/compose/ui/benchmark/focus/ParameterizedFocusBenchmark.kt
@@ -59,51 +59,6 @@ @get:Rule val composeBenchmarkRule = ComposeBenchmarkRule() @Test - fun modifyActiveHierarchy_addRemoveSubtree() { - composeBenchmarkRule.toggleAlternatingStateBenchmarkRecompose({ - object : LayeredComposeTestCase(), ToggleableAlternatingTestCase { - - private val focusRequester = FocusRequester() - private var shouldAddNodes by mutableStateOf(false) - private var rootFocusState: FocusState? = null - - @Composable - override fun MeasuredContent() { - if (shouldAddNodes) { - Box(focusTargetModifiers()) { - repeat(count) { - Box(Modifier.focusTarget()) { - repeat(count) { Box(Modifier.focusTarget()) } - } - } - } - } - } - - @Composable - override fun ContentWrappers(content: @Composable () -> Unit) { - Box( - Modifier.fillMaxSize() - .onFocusEvent { rootFocusState = it } - .then(focusTargetModifiers()) - ) { - Column { - Box(Modifier.focusRequester(focusRequester).focusTarget()) - LaunchedEffect(Unit) { focusRequester.requestFocus() } - content() - } - } - } - - override fun toggleState(isStateChangeMeasured: Boolean) { - assertThat(rootFocusState?.hasFocus).isTrue() - shouldAddNodes = isStateChangeMeasured - } - } - }) - } - - @Test fun modifyActiveHierarchy_addRemoveModifiersWithExistingSubtree() { composeBenchmarkRule.toggleAlternatingStateBenchmarkRecompose({ object : LayeredComposeTestCase(), ToggleableAlternatingTestCase {
diff --git a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidAccessibilityTest.kt b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidAccessibilityTest.kt index f4ec729..3471f08 100644 --- a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidAccessibilityTest.kt +++ b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidAccessibilityTest.kt
@@ -318,6 +318,7 @@ ViewCompat.getAccessibilityDelegate(androidComposeView) as AndroidComposeViewAccessibilityDelegateCompat delegate.accessibilityForceEnabledForTesting = true + delegate.SendRecurringAccessibilityEventsIntervalMillis = 0L provider = delegate.getAccessibilityNodeProvider(androidComposeView) } }
diff --git a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidComposeViewAccessibilityDelegateCompatTest.kt b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidComposeViewAccessibilityDelegateCompatTest.kt index 5153b56..c8066efc 100644 --- a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidComposeViewAccessibilityDelegateCompatTest.kt +++ b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/AndroidComposeViewAccessibilityDelegateCompatTest.kt
@@ -3220,6 +3220,7 @@ androidComposeView = LocalView.current as AndroidComposeView with(androidComposeView.composeAccessibilityDelegate) { accessibilityForceEnabledForTesting = true + SendRecurringAccessibilityEventsIntervalMillis = 0L onSendAccessibilityEvent = { dispatchedAccessibilityEvents += it false
diff --git a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/ScrollingTest.kt b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/ScrollingTest.kt index a8155a6..92dcec9 100644 --- a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/ScrollingTest.kt +++ b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/ScrollingTest.kt
@@ -20,6 +20,7 @@ import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.P import android.os.Build.VERSION_CODES.R +import android.os.SystemClock import android.view.View import android.view.accessibility.AccessibilityEvent import android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE @@ -84,6 +85,8 @@ import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Correspondence import com.google.common.truth.Truth.assertThat +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicLong import kotlin.math.abs import org.junit.After import org.junit.Rule @@ -97,8 +100,7 @@ private val tag = "tag" private lateinit var androidComposeView: AndroidComposeView - private val dispatchedAccessibilityEvents = mutableListOf<AccessibilityEvent>() - private val accessibilityEventLoopIntervalMs = 100L + private val dispatchedAccessibilityEvents = CopyOnWriteArrayList<AccessibilityEvent>() @After fun teardown() { @@ -130,7 +132,6 @@ Text("bar", Modifier.size(10.toDp()).testTag(tag)) } } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) val virtualViewId = rule.onNodeWithTag(tag).semanticsId() rule.runOnIdle { dispatchedAccessibilityEvents.clear() } @@ -150,7 +151,8 @@ } finally { androidComposeView.snapshotObserver.stopObserving() } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -195,16 +197,9 @@ ) } - // TODO(b/272068594): We receive an extra TYPE_WINDOW_CONTENT_CHANGED event 100ms after - // setup. So we wait an extra 100ms here so that this test is not affected by that extra - // event. - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) - dispatchedAccessibilityEvents.clear() - // Act. try { androidComposeView.snapshotObserver.startObserving() - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) rule.runOnIdle { Snapshot.notifyObjectsInitialized() scrollValue = 2f @@ -213,7 +208,8 @@ } finally { androidComposeView.snapshotObserver.stopObserving() } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -254,14 +250,11 @@ ) } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) - dispatchedAccessibilityEvents.clear() val scrollerId = rule.onNodeWithTag(tag).semanticsId() // Act: Trigger a semantics pass and simultaneous 2D scroll state change. try { androidComposeView.snapshotObserver.startObserving() - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) rule.runOnIdle { Snapshot.notifyObjectsInitialized() scrollXValue = 4f @@ -271,7 +264,8 @@ } finally { androidComposeView.snapshotObserver.stopObserving() } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert: Single coalesced 2D scroll event with both axes AND exactly one scope registered. rule.runOnIdle { @@ -311,6 +305,67 @@ } } + @Test + fun sendScrollEvent_respectsBatchIntervalDelay() { + // Arrange. + var scrollValue by mutableStateOf(0f, structuralEqualityPolicy()) + val scrollMaxValue = 100f + rule.setContentWithAccessibilityEnabled { + Box( + Modifier.size(10.dp).semantics(mergeDescendants = false) { + verticalScrollAxisRange = ScrollAxisRange({ scrollValue }, { scrollMaxValue }) + } + ) + } + + val batchIntervalMs = 200L + val lastScrollEventTime = AtomicLong(0L) + rule.runOnIdle { + with(androidComposeView.composeAccessibilityDelegate) { + SendRecurringAccessibilityEventsIntervalMillis = batchIntervalMs + onSendAccessibilityEvent = { event -> + if (event.eventType == TYPE_VIEW_SCROLLED) { + lastScrollEventTime.set(SystemClock.uptimeMillis()) + } + dispatchedAccessibilityEvents += event + false + } + } + } + + // Act & Assert. + try { + androidComposeView.snapshotObserver.startObserving() + rule.runOnIdle { + Snapshot.notifyObjectsInitialized() + scrollValue = 1f + Snapshot.sendApplyNotifications() + } + rule.waitUntil(timeoutMillis = 2_000) { dispatchedScrollEvents().isNotEmpty() } + val firstEventTime = lastScrollEventTime.get() + + rule.runOnIdle { + dispatchedAccessibilityEvents.clear() + scrollValue = 2f + Snapshot.sendApplyNotifications() + } + rule.waitForIdle() + assertThat(dispatchedScrollEvents()).isEmpty() + + rule.waitUntil(timeoutMillis = 2_000) { dispatchedScrollEvents().isNotEmpty() } + val secondEventTime = lastScrollEventTime.get() + + rule.runOnIdle { + val scrollEvents = dispatchedScrollEvents() + assertThat(scrollEvents).hasSize(1) + assertThat(scrollEvents.single().scrollY).isEqualTo(2) + assertThat(secondEventTime - firstEventTime).isAtLeast(100L) + } + } finally { + androidComposeView.snapshotObserver.stopObserving() + } + } + @SdkSuppress(minSdkVersion = P) @Test fun scrollEvent_lazyRowWideItem_reportsConsumedPixelScrollDeltaX() { @@ -440,7 +495,8 @@ // Act: remove the focused node from the composition. rule.runOnIdle { showBox = false } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. assertAccessibilityFocusCleared() @@ -462,7 +518,8 @@ // Act: deactivate the focused node in place without moving sibling bounds. rule.runOnIdle { active = false } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. assertAccessibilityFocusCleared() @@ -482,7 +539,8 @@ // Act: reuse the LayoutNode under a new key and semanticsId. rule.runOnIdle { key = 1 } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. assertAccessibilityFocusCleared() @@ -507,7 +565,8 @@ // Act: drop the fake Role node while keeping its parent LayoutNode attached. rule.runOnIdle { hasRole = false } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. assertAccessibilityFocusCleared() @@ -533,7 +592,8 @@ // Act: prune the focused child via clearAndSetSemantics without detaching it. rule.runOnIdle { clearDescendants = true } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. assertAccessibilityFocusCleared() @@ -555,7 +615,8 @@ // Act: hide the focused node from accessibility while keeping it attached. rule.runOnIdle { hidden = true } - rule.mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. assertAccessibilityFocusCleared() @@ -1039,6 +1100,7 @@ androidComposeView = LocalView.current as AndroidComposeView with(androidComposeView.composeAccessibilityDelegate) { accessibilityForceEnabledForTesting = true + SendRecurringAccessibilityEventsIntervalMillis = 0L onSendAccessibilityEvent = { dispatchedAccessibilityEvents += it false @@ -1047,9 +1109,10 @@ content() } - // Advance the clock past the first accessibility event loop, and clear the initial - // events as we are want the assertions to check the events that were generated later. - runOnIdle { mainClock.advanceTimeBy(accessibilityEventLoopIntervalMs) } + // Drain the initial accessibility event loop and clear initial events so assertions only + // see events generated later. + mainClock.advanceTimeByFrame() + waitForIdle() runOnIdle { dispatchedAccessibilityEvents.clear() } }
diff --git a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/WindowContentChangeTest.kt b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/WindowContentChangeTest.kt index bae34bb..c8ae8c4 100644 --- a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/WindowContentChangeTest.kt +++ b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/accessibility/WindowContentChangeTest.kt
@@ -283,6 +283,7 @@ androidComposeView = LocalView.current as AndroidComposeView with(androidComposeView.composeAccessibilityDelegate) { accessibilityForceEnabledForTesting = true + SendRecurringAccessibilityEventsIntervalMillis = 0L onSendAccessibilityEvent = { dispatchedAccessibilityEvents += it false
diff --git a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/contentcapture/ContentCaptureTest.kt b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/contentcapture/ContentCaptureTest.kt index 9821cec..c6b48dde 100644 --- a/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/contentcapture/ContentCaptureTest.kt +++ b/compose/ui/ui/src/androidDeviceTest/kotlin/androidx/compose/ui/contentcapture/ContentCaptureTest.kt
@@ -18,6 +18,7 @@ import android.os.Build import android.os.Bundle +import android.os.SystemClock import android.util.LongSparseArray import android.view.ViewStructure import android.view.translation.TranslationRequestValue @@ -65,6 +66,9 @@ import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth.assertThat +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong import java.util.function.Consumer import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -101,7 +105,6 @@ private lateinit var androidComposeView: AndroidComposeView private lateinit var contentCaptureSessionWrapper: ContentCaptureSessionWrapper private lateinit var viewStructure: ViewStructure - private val contentCaptureEventLoopIntervalMs = 100L @Test @SdkSuppress(minSdkVersion = 29) @@ -170,12 +173,8 @@ // Act. rule.runOnIdle { appeared = true } - // TODO(b/272068594): After refactoring this code, ensure that we don't need to wait for two - // invocations of boundsUpdatesEventLoop. - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -214,13 +213,8 @@ // Act. rule.runOnIdle { disappeared = true } - - // TODO(b/272068594): After refactoring this code, ensure that we don't need to wait for two - // invocations of boundsUpdatesEventLoop. - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -254,15 +248,12 @@ // The mocks also limit us to write this test since we can't mock AutofillIDs since // AutofillId is a final class, and these tests just use the autofill id of the parent // view. - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() rule.runOnIdle { appeared = false } - // TODO(b/272068594): After refactoring this code, ensure that we don't need to wait for - // two invocations of boundsUpdatesEventLoop. - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -287,13 +278,8 @@ } rule.runOnIdle { appeared = true } - - // TODO(b/272068594): After refactoring this code, ensure that we don't need to wait for two - // invocations of boundsUpdatesEventLoop. - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() rule.runOnIdle { verify(contentCaptureSessionWrapper, times(1)).newAutofillId(any()) @@ -306,13 +292,8 @@ // Act. rule.runOnIdle { appeared = false } - - // TODO(b/272068594): After refactoring this code, ensure that we don't need to wait for two - // invocations of boundsUpdatesEventLoop. - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -331,11 +312,8 @@ } // Act. + rule.mainClock.advanceTimeByFrame() rule.waitForIdle() - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } // Assert rule.runOnIdle { @@ -371,10 +349,8 @@ // Perform scroll down action: text_4 appeared, text_0 disappeared scope?.launch { listState?.scrollToItem(index = 1) } } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -409,11 +385,8 @@ // text_[4,5] appeared, text_[0,1] disappeared scope?.launch { listState?.scrollToItem(index = 2) } } - - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert rule.runOnIdle { @@ -450,10 +423,8 @@ // Perform scroll down action: text_2 appeared, text_6 disappeared scope?.launch { listState?.scrollToItem(index = 2) } } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { @@ -488,11 +459,8 @@ // text_[1,2] appeared, text_[5,6] disappeared scope?.launch { listState?.scrollToItem(index = 1) } } - - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert rule.runOnIdle { @@ -536,7 +504,8 @@ // Act. rule.runOnIdle { appeared = true } - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { assertThat(result).isFalse() } @@ -570,7 +539,8 @@ // Act. rule.runOnIdle { appeared = true } - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() // Assert. rule.runOnIdle { assertThat(result).isTrue() } @@ -798,6 +768,8 @@ // `LocalContentCaptureManager.current` setContent { androidComposeView = LocalView.current as AndroidComposeView + androidComposeView.contentCaptureManager + .SendRecurringContentCaptureEventsIntervalMillis = 0L androidComposeView.contentCaptureManager.onContentCaptureSession = { contentCaptureSessionWrapper } @@ -811,7 +783,8 @@ // Advance the clock past the first accessibility event loop, and clear the initial // as we are want the assertions to check the events that were generated later. - runOnIdle { mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) } + mainClock.advanceTimeByFrame() + waitForIdle() runOnIdle { if (!retainInteractionsDuringInitialization) { @@ -877,22 +850,14 @@ // Trigger semantics change which posts the checker manager.onSemanticsChange() - // Retrieve the private contentCaptureChangeChecker runnable via reflection - val checkerField = - AndroidContentCaptureManager::class - .java - .getDeclaredField("contentCaptureChangeChecker") - checkerField.isAccessible = true - val contentCaptureChangeChecker = checkerField.get(manager) as Runnable - // Simulate detachment by stubbing isAttachedToWindow to false doReturn(false).whenever(view).isAttachedToWindow // Reset spy view invocations clearInvocations(view) - // Run the checker (simulating looper execution) - contentCaptureChangeChecker.run() + // Run the manager runnable (simulating looper execution) + manager.run() // Verify that view.measureAndLayout() was never called (exited early) verify(view, never()).measureAndLayout() @@ -900,15 +865,8 @@ } @RequiresApi(Build.VERSION_CODES.Q) - private fun AndroidContentCaptureManager.hasPendingChangeChecker(): Boolean { - val checker = - AndroidContentCaptureManager::class - .java - .getDeclaredField("contentCaptureChangeChecker") - .apply { isAccessible = true } - .get(this) as Runnable - return checkNotNull(handler).hasCallbacks(checker) - } + private fun AndroidContentCaptureManager.hasPendingChangeChecker(): Boolean = + checkNotNull(handler).hasCallbacks(this) @Test @SdkSuppress(minSdkVersion = 29) @@ -918,18 +876,14 @@ rule.setContentWithContentCaptureEnabled { Box(Modifier.size(20.dp).semantics { text = AnnotatedString(textValue) }) } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } val manager = androidComposeView.contentCaptureManager rule.runOnUiThread { manager.onSemanticsChange() - rule.mainClock.advanceTimeByFrame() assertThat(manager.hasPendingChangeChecker()).isTrue() manager.onStop(mock()) } + rule.mainClock.advanceTimeByFrame() rule.waitForIdle() rule.runOnIdle { @@ -937,10 +891,8 @@ clearInvocations(contentCaptureSessionWrapper) textValue = "updated" } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() rule.runOnIdle { verify(contentCaptureSessionWrapper).notifyViewTextChanged(any(), eq("updated")) @@ -955,18 +907,14 @@ rule.setContentWithContentCaptureEnabled { Box(Modifier.size(20.dp).semantics { text = AnnotatedString(textValue) }) } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } val manager = androidComposeView.contentCaptureManager rule.runOnUiThread { manager.onSemanticsChange() - rule.mainClock.advanceTimeByFrame() assertThat(manager.hasPendingChangeChecker()).isTrue() manager.onViewDetachedFromWindow(androidComposeView) } + rule.mainClock.advanceTimeByFrame() rule.waitForIdle() rule.runOnIdle { @@ -975,10 +923,8 @@ clearInvocations(contentCaptureSessionWrapper) textValue = "updated" } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() rule.runOnIdle { verify(contentCaptureSessionWrapper).notifyViewTextChanged(any(), eq("updated")) @@ -993,19 +939,28 @@ rule.setContentWithContentCaptureEnabled { Box(Modifier.size(20.dp).semantics { text = AnnotatedString(textValue) }) } - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - rule.runOnIdle { clearInvocations(contentCaptureSessionWrapper, viewStructure) } - for (i in 1..4) { + val dispatchedTexts = CopyOnWriteArrayList<String>() + whenever(contentCaptureSessionWrapper.notifyViewTextChanged(any(), any())).thenAnswer { + dispatchedTexts.add(it.getArgument<CharSequence>(1).toString()) + Unit + } + + rule.runOnUiThread { textValue = "t1" } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() + + rule.runOnIdle { + androidComposeView.contentCaptureManager + .SendRecurringContentCaptureEventsIntervalMillis = 500L + } + + for (i in 2..4) { rule.runOnUiThread { textValue = "t$i" } rule.mainClock.advanceTimeByFrame() rule.waitForIdle() } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.waitUntil(timeoutMillis = 2_000) { "t4" in dispatchedTexts } rule.runOnIdle { verify(contentCaptureSessionWrapper).notifyViewTextChanged(any(), eq("t1")) @@ -1027,9 +982,11 @@ rule.setContentWithContentCaptureEnabled { Box(Modifier.size(20.dp).semantics { text = AnnotatedString(textValue) }) } - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - rule.runOnIdle { clearInvocations(contentCaptureSessionWrapper, viewStructure) } + rule.runOnIdle { + androidComposeView.contentCaptureManager + .SendRecurringContentCaptureEventsIntervalMillis = 500L + clearInvocations(contentCaptureSessionWrapper, viewStructure) + } for (i in 1..4) { rule.runOnUiThread { textValue = "t$i" } @@ -1062,11 +1019,25 @@ whenever(viewStructure.extras).thenAnswer { Bundle() } rule.runOnIdle { scope?.launch { listState?.scrollToItem(index = 1) } } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() + + rule.runOnIdle { + androidComposeView.contentCaptureManager + .SendRecurringContentCaptureEventsIntervalMillis = 300L + clearInvocations(contentCaptureSessionWrapper, viewStructure) } - rule.runOnIdle { clearInvocations(contentCaptureSessionWrapper, viewStructure) } + + val appearedCount = AtomicInteger(0) + val disappearedCount = AtomicInteger(0) + whenever(contentCaptureSessionWrapper.notifyViewAppeared(any())).thenAnswer { + appearedCount.incrementAndGet() + Unit + } + whenever(contentCaptureSessionWrapper.notifyViewDisappeared(any())).thenAnswer { + disappearedCount.incrementAndGet() + Unit + } rule.runOnIdle { scope?.launch { listState?.scrollToItem(index = 2) } } rule.mainClock.advanceTimeBy(32) @@ -1076,9 +1047,8 @@ verify(contentCaptureSessionWrapper, never()).newVirtualViewStructure(any(), any()) } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() + rule.waitUntil(timeoutMillis = 3_000) { + appearedCount.get() >= 1 && disappearedCount.get() >= 1 } rule.runOnIdle { @@ -1095,9 +1065,6 @@ rule.setContentWithContentCaptureEnabled { Box(Modifier.size(20.dp).semantics { text = AnnotatedString(textValue) }) } - // Advance past the initial startup cooldown and start a fresh 100ms batch window. - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() val manager = androidComposeView.contentCaptureManager rule.runOnIdle { manager.onLayoutChange() } @@ -1105,7 +1072,7 @@ rule.runOnUiThread { manager.onLayoutChange() manager.onStop(mock()) - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) + manager.onLayoutChange() assertThat(manager.hasPendingChangeChecker()).isFalse() } rule.waitForIdle() @@ -1115,13 +1082,66 @@ clearInvocations(contentCaptureSessionWrapper) textValue = "afterRestart" } - repeat(2) { - rule.mainClock.advanceTimeBy(contentCaptureEventLoopIntervalMs) - rule.waitForIdle() - } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() rule.runOnIdle { verify(contentCaptureSessionWrapper).notifyViewTextChanged(any(), eq("afterRestart")) } } + + @Test + @SdkSuppress(minSdkVersion = 29) + fun testSendContentCaptureEvents_respectsBatchIntervalDelay() { + // Arrange. + var appeared by mutableStateOf(false) + rule.mainClock.autoAdvance = false + rule.setContentWithContentCaptureEnabled { + Box(Modifier.size(10.dp).semantics {}) { + if (appeared) { + Box(Modifier.size(10.dp).semantics { text = AnnotatedString("foo") }) + } + } + } + + val batchIntervalMs = 200L + rule.runOnIdle { + androidComposeView.contentCaptureManager + .SendRecurringContentCaptureEventsIntervalMillis = batchIntervalMs + } + + val appearedCount = AtomicInteger(0) + val disappearedCount = AtomicInteger(0) + val appearedTime = AtomicLong(0L) + val disappearedTime = AtomicLong(0L) + whenever(contentCaptureSessionWrapper.notifyViewAppeared(any())).thenAnswer { + appearedCount.incrementAndGet() + appearedTime.set(SystemClock.uptimeMillis()) + Unit + } + whenever(contentCaptureSessionWrapper.notifyViewDisappeared(any())).thenAnswer { + disappearedCount.incrementAndGet() + disappearedTime.set(SystemClock.uptimeMillis()) + Unit + } + + // Act - trigger appearance and wait for it to be dispatched. + rule.runOnIdle { appeared = true } + rule.mainClock.advanceTimeByFrame() + rule.waitUntil(timeoutMillis = 2_000) { appearedCount.get() > 0 } + + // Trigger disappearance immediately after appearance is dispatched. + rule.runOnIdle { appeared = false } + rule.mainClock.advanceTimeByFrame() + rule.waitForIdle() + + // Assert - follow-up ContentCapture pass was deferred by postDelayed, not dispatched + // immediately. + assertThat(disappearedCount.get()).isEqualTo(0) + + // Wait for the delayed pass to dispatch the disappearance. + rule.waitUntil(timeoutMillis = 2_000) { disappearedCount.get() > 0 } + assertThat(disappearedCount.get()).isEqualTo(1) + assertThat(disappearedTime.get() - appearedTime.get()).isAtLeast(100L) + } }
diff --git a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/contentcapture/AndroidContentCaptureManager.android.kt b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/contentcapture/AndroidContentCaptureManager.android.kt index d1bdbc87..175a079 100644 --- a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/contentcapture/AndroidContentCaptureManager.android.kt +++ b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/contentcapture/AndroidContentCaptureManager.android.kt
@@ -19,6 +19,7 @@ import android.os.Build import android.os.Handler import android.os.Looper +import android.os.SystemClock import android.util.LongSparseArray import android.view.View import android.view.ViewStructure @@ -31,6 +32,7 @@ import androidx.collection.MutableIntObjectMap import androidx.collection.intObjectMapOf import androidx.collection.mutableIntObjectMapOf +import androidx.collection.mutableObjectListOf import androidx.compose.ui.AndroidComposeUiFlags import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.internal.checkPreconditionNotNull @@ -55,8 +57,6 @@ import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import java.util.function.Consumer -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.delay // TODO(b/272068594): Fix the primitive usage after completing the semantics refactor. // TODO(b/318748747): Add an interface for ContentCaptureManager to the common module, and then this @@ -69,19 +69,19 @@ internal class AndroidContentCaptureManager( val view: AndroidComposeView, var onContentCaptureSession: () -> ContentCaptureSessionWrapper?, -) : DefaultLifecycleObserver, View.OnAttachStateChangeListener { +) : DefaultLifecycleObserver, View.OnAttachStateChangeListener, Runnable { @VisibleForTesting internal var contentCaptureSession: ContentCaptureSessionWrapper? = null /** An ordered list of buffered content capture events. */ - private val bufferedEvents = mutableListOf<ContentCaptureEvent>() + private val bufferedEvents = mutableObjectListOf<ContentCaptureEvent>() /** * Delay before dispatching a recurring accessibility event in milliseconds. This delay * guarantees that a recurring event will be send at most once during the * [SendRecurringContentCaptureEventsIntervalMillis] time frame. */ - private var SendRecurringContentCaptureEventsIntervalMillis = 100L + @VisibleForTesting internal var SendRecurringContentCaptureEventsIntervalMillis = 100L /** * Indicates whether the translated information is show or hide in the [AndroidComposeView]. @@ -98,7 +98,7 @@ private var translateStatus = TranslateStatus.SHOW_ORIGINAL private var currentSemanticsNodesInvalidated = true - private val boundsUpdateChannel = Channel<Unit>(1) + private var lastUpdateTime = 0L // TODO remove with b/486998514 private val legacyMainHandler = Handler(Looper.getMainLooper()) @@ -119,7 +119,7 @@ } /** - * Up to date semantics nodes in pruned semantics tree. It always reflects the current semantics + * Up-to-date semantics nodes in pruned semantics tree. It always reflects the current semantics * tree. They key is the virtual view id(the root node has a key of * AccessibilityNodeProviderCompat.HOST_VIEW_ID and other node has a key of its id). */ @@ -150,42 +150,12 @@ SemanticsNodeCopy(view.semanticsOwner.unmergedRootSemanticsNode, intObjectMapOf()) private var checkingForSemanticsChanges = false - private val contentCaptureChangeChecker = Runnable { - if (!isEnabled || !view.isAttachedToWindow) { - checkingForSemanticsChanges = false - return@Runnable - } - - trace("ContentCapture:changeChecker") { - // TODO(mnuzen): there might be a case where `view.measureAndLayout()` is called twice - // -- - // once by the CC checker and once by the a11y checker. - view.measureAndLayout() - - // Semantics structural change - // Always send disappear event first. - sendContentCaptureDisappearEvents() - trace("ContentCapture:sendAppearEvents") { - sendContentCaptureAppearEvents( - view.semanticsOwner.unmergedRootSemanticsNode, - previousSemanticsRoot, - ) - } - - // Property change - checkForContentCapturePropertyChanges(currentSemanticsNodes) - updateSemanticsCopy() - - checkingForSemanticsChanges = false - } - } - override fun onViewAttachedToWindow(v: View) {} override fun onViewDetachedFromWindow(v: View) { // TODO: b/498432814 - Handler shouldn't be null on detach; investigate re-entrant // detachment to see if handler? can be removed. - handler?.removeCallbacks(contentCaptureChangeChecker) + handler?.removeCallbacks(this) checkingForSemanticsChanges = false contentCaptureSession = null } @@ -204,25 +174,36 @@ updateBuffersOnDisappeared(view.semanticsOwner.unmergedRootSemanticsNode) notifyContentCaptureChanges() contentCaptureSession = null + handler?.removeCallbacks(this) + checkingForSemanticsChanges = false } - /** - * This suspend function loops for the entire lifetime of the Compose instance: it consumes - * recent layout changes and sends events to the accessibility and content capture framework in - * batches separated by a 100ms delay. - */ - internal suspend fun boundsUpdatesEventLoop() { - for (notification in boundsUpdateChannel) { - if (isEnabled) { - notifyContentCaptureChanges() - val localHandler = handler - if (!checkingForSemanticsChanges && localHandler != null) { - checkingForSemanticsChanges = true - localHandler.post(contentCaptureChangeChecker) - } - } + /** This is debounced so that it is executed at least 100ms after the previous call. */ + override fun run() { + lastUpdateTime = SystemClock.uptimeMillis() + checkingForSemanticsChanges = false - delay(SendRecurringContentCaptureEventsIntervalMillis) + if (isEnabled && view.isAttachedToWindow) { + notifyContentCaptureChanges() + trace("ContentCapture:changeChecker") { + // TODO(mnuzen): there might be a case where `view.measureAndLayout()` is called + // twice -- once by the CC checker and once by the a11y checker. + view.measureAndLayout() + + // Semantics structural change + // Always send disappear event first. + sendContentCaptureDisappearEvents() + trace("ContentCapture:sendAppearEvents") { + sendContentCaptureAppearEvents( + view.semanticsOwner.unmergedRootSemanticsNode, + previousSemanticsRoot, + ) + } + + // Property change + checkForContentCapturePropertyChanges(currentSemanticsNodes) + updateSemanticsCopy() + } } } @@ -240,7 +221,7 @@ val localHandler = handler if (!checkingForSemanticsChanges && localHandler != null) { checkingForSemanticsChanges = true - localHandler.post(contentCaptureChangeChecker) + localHandler.post(this) } } } @@ -253,7 +234,7 @@ // The layout change of a LayoutNode will also affect its children, so even if it doesn't // have semantics attached, we should process it. - if (isEnabled) notifySubtreeStateChangeIfNeeded() + notifySubtreeStateChangeIfNeeded() } private fun sendContentCaptureDisappearEvents() { @@ -346,7 +327,17 @@ } private fun notifySubtreeStateChangeIfNeeded() { - boundsUpdateChannel.trySend(Unit) + val handler = handler ?: return + if (isEnabled && !checkingForSemanticsChanges) { + checkingForSemanticsChanges = true + val nextRunTime = lastUpdateTime + SendRecurringContentCaptureEventsIntervalMillis + val delay = nextRunTime - SystemClock.uptimeMillis() + if (delay <= 0) { + handler.post(this) + } else { + handler.postDelayed(this, delay) + } + } } private fun SemanticsNode.toViewStructure(index: Int): ViewStructure? { @@ -470,7 +461,7 @@ } if (bufferedEvents.isNotEmpty()) { - bufferedEvents.fastForEach { event -> + bufferedEvents.forEach { event -> when (event.type) { ContentCaptureEventType.VIEW_APPEAR -> { event.structureCompat?.let { node -> session.notifyViewAppeared(node) }
diff --git a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeView.android.kt b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeView.android.kt index a27edf6..8107d0f 100644 --- a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeView.android.kt +++ b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeView.android.kt
@@ -805,7 +805,7 @@ internal val isTouchExplorationEnabled: Boolean get() = composeAccessibilityDelegate.isTouchExplorationEnabled - internal var contentCaptureManager = + internal val contentCaptureManager = AndroidContentCaptureManager( view = this, onContentCaptureSession = ::getContentCaptureSessionCompat, @@ -2598,14 +2598,6 @@ } } - suspend fun boundsUpdatesAccessibilityEventLoop() { - composeAccessibilityDelegate.boundsUpdatesEventLoop() - } - - suspend fun boundsUpdatesContentCaptureEventLoop() { - contentCaptureManager.boundsUpdatesEventLoop() - } - /** Walks the entire LayoutNode sub-hierarchy and marks all nodes as needing measurement. */ private fun invalidateLayoutNodeMeasurement(node: LayoutNode) { measureAndLayoutDelegate.requestRemeasure(node)
diff --git a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeViewAccessibilityDelegateCompat.android.kt b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeViewAccessibilityDelegateCompat.android.kt index 9537ad7..dcb555d 100644 --- a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeViewAccessibilityDelegateCompat.android.kt +++ b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/AndroidComposeViewAccessibilityDelegateCompat.android.kt
@@ -146,8 +146,6 @@ import kotlin.math.min import kotlin.math.roundToInt import kotlin.math.sign -import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.delay private fun LayoutNode.findClosestParentNode(selector: (LayoutNode) -> Boolean): LayoutNode? { var currentParent = this.parent @@ -168,7 +166,7 @@ ExperimentalComposeUiHostApi::class, ) internal class AndroidComposeViewAccessibilityDelegateCompat(val view: AndroidComposeView) : - AccessibilityDelegateCompat(), OnAttachStateChangeListener { + AccessibilityDelegateCompat(), OnAttachStateChangeListener, Runnable { @Suppress("ConstPropertyName") companion object { /** Virtual node identifier value for invalid nodes. */ @@ -349,7 +347,13 @@ // traversal with granularity switches to the next node private var previousTraversedNode: Int? = null private val subtreeChangedLayoutNodes = ArraySet<LayoutNode>() - private val boundsUpdateChannel = Channel<Unit>(1) + // When false, the bounds update notification can be scheduled. When true, it has already been + // scheduled. + private var boundsUpdateNotified = false + // The time (SystemClock.uptimeMillis()) that the bounds was last updated for accessibility. + // Used to regulate when the next one should be targeted as it should arrive no less than 100ms + // after the last one. + private var lastBoundsUpdateNotification = 0L private var currentSemanticsNodesInvalidated = true private class PendingTextTraversedEvent( @@ -412,6 +416,10 @@ // parent) of the corresponding layout nodes. @VisibleForTesting internal val drawingOrder = MutableIntIntMap(0) + // Used in Runnable and cached in the class instance so it doesn't have to be allocated on + // every call. + private val subtreeChangedSemanticsNodesIds = MutableIntSet() + init { // Remove callbacks that rely on view being attached to a window when we become // detached. @@ -423,11 +431,19 @@ override fun onViewDetachedFromWindow(view: View) { // TODO: b/498432814 - Handler shouldn't be null on detach; investigate re-entrant // detachment to see if handler? can be removed. + view.removeCallbacks(this) + handler?.removeCallbacks(this) handler?.removeCallbacks(semanticsChangeChecker) + boundsUpdateNotified = false + checkingForSemanticsChanges = false isHoveringInteropView = false actionIdToLabel.clear() labelToActionId.clear() drawingOrder.clear() + subtreeChangedLayoutNodes.clear() + pendingHorizontalScrollEvents.clear() + pendingVerticalScrollEvents.clear() + scrollObservationScopes.fastForEach { it.pixelScrollDelta = Offset.Zero } } /** @@ -2480,62 +2496,58 @@ // later, we can refresh currentSemanticsNodes if currentSemanticsNodes is stale. currentSemanticsNodesInvalidated = true - val localHandler = handler - if (isEnabled && !checkingForSemanticsChanges && localHandler != null) { + val handler = handler ?: return + if (isEnabled && !checkingForSemanticsChanges) { checkingForSemanticsChanges = true - localHandler.post(semanticsChangeChecker) + handler.post(semanticsChangeChecker) } } /** - * This suspend function loops for the entire lifetime of the Compose instance: it consumes - * recent layout changes and sends events to the accessibility and content capture framework in - * batches separated by a 100ms delay. + * This runnable is scheduled whenever the bounds has changed and the accessibility tree must be + * updated. It consumes recent layout changes and sends events to the accessibility and content + * capture framework in batches separated by a 100ms delay. */ - internal suspend fun boundsUpdatesEventLoop() { - try { - val subtreeChangedSemanticsNodesIds = MutableIntSet() - for (notification in boundsUpdateChannel) { - if (isEnabled) { - trace("Compose:semantics:boundUpdates") { - updateBounds(subtreeChangedSemanticsNodesIds) - subtreeChangedSemanticsNodesIds.clear() - } - // When the bounds of layout nodes change, we will not always get semantics - // change notifications because bounds is not part of semantics. And bounds - // change from a layout node without semantics will affect the global bounds - // of it children which has semantics. Bounds change will affect which nodes - // are covered and which nodes are not, so the currentSemanticsNodes is not - // up to date anymore. - // After the subtree events are sent, accessibility services will get the - // current visible/invisible state. We also try to do semantics tree diffing - // to send out the proper accessibility events and update our copy here so - // that - // our incremental changes (represented by accessibility events) are - // consistent - // with accessibility services. That is: change - notify - new change - - // notify, if we don't do the tree diffing and update our copy here, we will - // combine old change and new change, which is missing finer-grained - // notification. - val localHandler = handler - if (!checkingForSemanticsChanges && localHandler != null) { - checkingForSemanticsChanges = true - localHandler.post(semanticsChangeChecker) - } - } else { - // The pending scroll events are dropped below, so drop their deltas too. - scrollObservationScopes.fastForEach { it.pixelScrollDelta = Offset.Zero } + override fun run() { + boundsUpdateNotified = false + lastBoundsUpdateNotification = SystemClock.uptimeMillis() + if (isEnabled) { + try { + trace("Compose:semantics:boundUpdates") { + updateBounds(subtreeChangedSemanticsNodesIds) + subtreeChangedSemanticsNodesIds.clear() } + } finally { subtreeChangedLayoutNodes.clear() pendingHorizontalScrollEvents.clear() pendingVerticalScrollEvents.clear() - delay(SendRecurringAccessibilityEventsIntervalMillis) } - } finally { + // When the bounds of layout nodes change, we will not always get semantics + // change notifications because bounds is not part of semantics. And bounds + // change from a layout node without semantics will affect the global bounds + // of it children which has semantics. Bounds change will affect which nodes + // are covered and which nodes are not, so the currentSemanticsNodes is not + // up to date anymore. + // After the subtree events are sent, accessibility services will get the + // current visible/invisible state. We also try to do semantics tree diffing + // to send out the proper accessibility events and update our copy here so + // that + // our incremental changes (represented by accessibility events) are + // consistent + // with accessibility services. That is: change - notify - new change - + // notify, if we don't do the tree diffing and update our copy here, we will + // combine old change and new change, which is missing finer-grained + // notification. + if (!checkingForSemanticsChanges) { + checkingForSemanticsChanges = true + semanticsChangeChecker.run() + } + } else { + // The pending scroll events are dropped below, so drop their deltas too. + scrollObservationScopes.fastForEach { it.pixelScrollDelta = Offset.Zero } subtreeChangedLayoutNodes.clear() pendingHorizontalScrollEvents.clear() pendingVerticalScrollEvents.clear() - scrollObservationScopes.fastForEach { it.pixelScrollDelta = Offset.Zero } } } @@ -2569,7 +2581,17 @@ private fun notifySubtreeAccessibilityStateChangedIfNeeded(layoutNode: LayoutNode) { if (subtreeChangedLayoutNodes.add(layoutNode)) { - boundsUpdateChannel.trySend(Unit) + if (isEnabled && !boundsUpdateNotified) { + boundsUpdateNotified = true + val nextShouldLandAt = + lastBoundsUpdateNotification + SendRecurringAccessibilityEventsIntervalMillis + val delay = nextShouldLandAt - SystemClock.uptimeMillis() + if (delay <= 0) { + view.post(this) + } else { + view.postDelayed(this, delay) + } + } } }
diff --git a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/Wrapper.android.kt b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/Wrapper.android.kt index 775939b..35a426d 100644 --- a/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/Wrapper.android.kt +++ b/compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/platform/Wrapper.android.kt
@@ -23,7 +23,6 @@ import androidx.compose.runtime.Composition import androidx.compose.runtime.CompositionServiceKey import androidx.compose.runtime.CompositionServices -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.tooling.CompositionData import androidx.compose.ui.R import androidx.compose.ui.node.LayoutNode @@ -120,8 +119,6 @@ } } else if (lifecycle.currentState.isAtLeast(Lifecycle.State.CREATED)) { original.setContent { - LaunchedEffect(owner) { owner.boundsUpdatesAccessibilityEventLoop() } - LaunchedEffect(owner) { owner.boundsUpdatesContentCaptureEventLoop() } composeViewContext.ProvideCompositionLocals(owner, content) } }
diff --git a/glance/adaptive/adaptive-appwidget/src/main/AndroidManifest.xml b/glance/adaptive/adaptive-appwidget/src/main/AndroidManifest.xml index ca8c77c..38bd879 100644 --- a/glance/adaptive/adaptive-appwidget/src/main/AndroidManifest.xml +++ b/glance/adaptive/adaptive-appwidget/src/main/AndroidManifest.xml
@@ -38,5 +38,27 @@ android:name=".RequestPinCallbackReceiver" android:exported="false" android:enabled="true" /> + + <!-- Backs scrollable ListView widgets on API 24-31. --> + <service + android:name=".components.list.AdaptiveListRemoteViewsService" + android:exported="true" + android:permission="android.permission.BIND_REMOTEVIEWS" /> + + <!-- Dispatches ListView item clicks for activity-launching or mixed lists. --> + <activity + android:name=".components.list.AdaptiveListClickActivity" + android:exported="false" + android:enabled="true" + android:excludeFromRecents="true" + android:noHistory="true" + android:taskAffinity="" + android:theme="@android:style/Theme.NoDisplay" /> + + <!-- Dispatches ListView item clicks for callback-only lists without starting an activity. --> + <receiver + android:name=".components.list.AdaptiveListClickReceiver" + android:exported="false" + android:enabled="true" /> </application> </manifest>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistry.kt b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistry.kt index b329a39..bd1f3ee 100644 --- a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistry.kt +++ b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistry.kt
@@ -109,22 +109,24 @@ ): AppWidgetRenderOutput = registry.render(data, surface, widgetName) /** - * Returns `true` if the built-in template omits a non-blank optional slot of [data] on - * [surface], or `false` if no built-in selector exists for [data]. When a custom renderer - * override is active for [widgetName], `false` means dropped slots are not reported. + * Returns `true` if a custom renderer override is registered for [widgetName], [templateClass], + * and [surface]. */ - fun hasDroppedSlots( - data: GlanceAdaptiveTemplate, + fun hasOverride( + widgetName: String, + templateClass: Class<out GlanceAdaptiveTemplate>, surface: AppWidgetSurface, - widgetName: String? = null, - ): Boolean { - if (widgetName != null && registry.hasOverride(widgetName, data.javaClass, surface)) { - return false - } - return try { + ): Boolean = registry.hasOverride(widgetName, templateClass, surface) + + /** + * Returns `true` if the built-in template omits a non-blank optional slot of [data] on + * [surface], or `false` if no built-in selector exists for [data]. It ignores custom renderer + * overrides; check [hasOverride] first, as their dropped slots are not reported. + */ + fun hasDroppedSlots(data: GlanceAdaptiveTemplate, surface: AppWidgetSurface): Boolean = + try { selectorRegistry.render(data, surface).hasDroppedSlots } catch (_: IllegalStateException) { false } - } }
diff --git a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManager.kt b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManager.kt index fdf7615..6508d3f 100644 --- a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManager.kt +++ b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManager.kt
@@ -189,31 +189,21 @@ } /** - * Draws templates of type [T] for [widgetName] on [surface] with [renderer] instead of the library - * default. + * Registers [renderer] to render [T] templates for [widgetName] on [surface], overriding the + * default renderer. * - * - Applies to the whole process, not only to this manager. Call it from - * [android.app.Application.onCreate], which runs before any widget renders, even when the process - * starts for a widget broadcast. - * - The last registration for a widget, template and surface wins, including over the library - * default. Placed widgets switch to it on their next update. + * Registration is process-wide. Registering from [android.app.Application.onCreate] is recommended + * so it is in place before any widget renders. Calling this again for the same [widgetName], [T], + * and [surface] replaces the previous renderer, and placed widgets use it on their next update. + * Does not check whether [widgetName] matches a declared receiver in the manifest. * - * Renderers produce AppWidget-specific output, so this operation is provided by this artifact as an - * extension rather than by [GlanceAdaptiveWidgetManager] itself. - * - * @param T The concrete template type implementing [GlanceAdaptiveTemplate], inferred from - * [renderer]. Templates are matched by their exact runtime class. - * @param widgetName Developer widget definition String identifier matching - * [GlanceAdaptiveWidgetReceiver.widgetName]. - * @param surface The [AppWidgetSurface] to draw [T] on. - * @param renderer Draws [T] as [AppWidgetRenderOutput]. The - * [androidx.glance.adaptive.core.selection.GlanceSurface.dimensions] of the surface it receives - * may be `(0, 0)` when the host has not reported a positive size or during widget picker preview - * rendering, so it must handle zero dimensions. - * @throws IllegalStateException if this manager is not backed by an AppWidget delegate, for example - * if it was created for another surface. - * @throws IllegalArgumentException if [T] is an interface or an abstract class, as no template - * instance can have it as its runtime class. + * @param T concrete [GlanceAdaptiveTemplate] type matched by exact runtime class + * @param widgetName non-blank widget identifier matching [GlanceAdaptiveWidgetReceiver.widgetName] + * @param surface target [AppWidgetSurface] + * @param renderer renders [T] into [AppWidgetRenderOutput]; must handle `Dimensions(0, 0)` + * @throws IllegalStateException if this manager was not created for AppWidget hosts + * @throws IllegalArgumentException if [widgetName] is blank or [T] is an interface or abstract + * class */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public inline fun <reified T : GlanceAdaptiveTemplate> GlanceAdaptiveWidgetManager.registerRenderer(
diff --git a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandler.kt b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandler.kt index b3099f81..0a598a4 100644 --- a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandler.kt +++ b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandler.kt
@@ -26,7 +26,7 @@ * Writes xFF telemetry extras into the [AppWidgetManager] options bundle of placed widgets. The * platform (`AppWidgetServiceImpl`) reads allowlisted keys during StatsD pulls * (`AppWidgetStatusPulled`) to attribute each placement to a template type, library version code, - * and responsive compaction state. + * responsive compaction state, and whether a custom renderer draws it. * * Each write is one blocking `updateAppWidgetOptions` Binder call to `system_server`, after which * the system broadcasts `ACTION_APPWIDGET_OPTIONS_CHANGED` back to the provider. Writes are skipped @@ -44,8 +44,8 @@ * @param targetToInstances appWidgetIds as grouped by * [GlanceRemoteViewsComposer.groupInstancesByRenderTarget]. * @param data Template payload being pushed. - * @param widgetName Optional widget identifier; skips built-in dropped-slot telemetry when a - * custom override is active. + * @param widgetName Optional widget identifier, used to detect a custom renderer override. When + * one is active, dropped slots are not reported. */ fun ensureTelemetryOptions( targetToInstances: Map<RenderTarget, List<Int>>, @@ -54,11 +54,22 @@ ) { val templateId = data.templateId for ((target, appWidgetIds) in targetToInstances) { - val hasDroppedSlots = hasDroppedSlots(data, target, widgetName) + val surface = target.surface.withDimensions(target.dimensions) + val usesCustomRenderer = + widgetName != null && + AppWidgetTemplateRegistry.hasOverride(widgetName, data.javaClass, surface) + // The built-in layout's dropped slots don't apply when a custom renderer draws it. + val hasDroppedSlots = + !usesCustomRenderer && AppWidgetTemplateRegistry.hasDroppedSlots(data, surface) for (i in appWidgetIds.indices) { val appWidgetId = appWidgetIds[i] try { - ensureTelemetryOptionsForWidget(appWidgetId, templateId, hasDroppedSlots) + ensureTelemetryOptionsForWidget( + appWidgetId, + templateId, + hasDroppedSlots, + usesCustomRenderer, + ) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -75,9 +86,10 @@ appWidgetId: Int, templateId: Int, hasDroppedSlots: Boolean, + usesCustomRenderer: Boolean, ) { val options = appWidgetManager.getAppWidgetOptions(appWidgetId) ?: return - if (!needsTelemetryUpdate(options, templateId, hasDroppedSlots)) return + if (!needsTelemetryUpdate(options, templateId, hasDroppedSlots, usesCustomRenderer)) return // Pre-populate the receiver's options cache before calling updateAppWidgetOptions so that // the system's resulting ACTION_APPWIDGET_OPTIONS_CHANGED broadcast does not mistake a @@ -99,6 +111,7 @@ putInt(OPTION_ADAPTIVE_WIDGET_TEMPLATE_TYPE, templateId) putInt(OPTION_ADAPTIVE_WIDGET_SDK_VERSION_CODE, XFF_SDK_VERSION_CODE) putBoolean(OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, hasDroppedSlots) + putBoolean(OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER, usesCustomRenderer) } try { appWidgetManager.updateAppWidgetOptions(appWidgetId, telemetryOptions) @@ -122,6 +135,7 @@ options: Bundle, templateId: Int, hasDroppedSlots: Boolean, + usesCustomRenderer: Boolean, ): Boolean = !options.getBoolean(OPTION_ADAPTIVE_WIDGET_ENABLED, false) || !options.containsKey(OPTION_ADAPTIVE_WIDGET_TEMPLATE_TYPE) || @@ -132,22 +146,10 @@ !options.containsKey(OPTION_ADAPTIVE_WIDGET_SDK_VERSION_CODE) || options.getInt(OPTION_ADAPTIVE_WIDGET_SDK_VERSION_CODE, 0) != XFF_SDK_VERSION_CODE || !options.containsKey(OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS) || - options.getBoolean(OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, false) != hasDroppedSlots - - /** - * Returns `true` when [target]'s container size causes at least one non-blank optional slot in - * [data] to be omitted from the rendered layout. - */ - private fun hasDroppedSlots( - data: GlanceAdaptiveTemplate, - target: RenderTarget, - widgetName: String?, - ): Boolean = - AppWidgetTemplateRegistry.hasDroppedSlots( - data, - target.surface.withDimensions(target.dimensions), - widgetName, - ) + options.getBoolean(OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, false) != + hasDroppedSlots || + !options.containsKey(OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER) || + options.getBoolean(OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER, false) != usesCustomRenderer companion object { private const val TAG = "WidgetTelemetryHandler" @@ -175,12 +177,20 @@ /** * Bundle option boolean flag indicating if secondary optional template slots were omitted - * due to responsive compaction. + * due to responsive compaction. Always `false` when + * [OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER] is `true`, meaning not reported. */ const val OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS: String = "android.appwidget.option.ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS" /** + * Bundle option boolean flag indicating that an app-registered custom renderer draws this + * widget on its surface instead of the built-in template layout. + */ + const val OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER: String = + "android.appwidget.option.ADAPTIVE_WIDGET_CUSTOM_RENDERER" + + /** * Default fallback SDK version code (`1.0.0` -> `10000`) used in host JVM unit tests where * AAR `META-INF` resources are not packaged. */
diff --git a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/components/list/AdaptiveListRemoteViewsService.kt b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/components/list/AdaptiveListRemoteViewsService.kt new file mode 100644 index 0000000..251c371 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/components/list/AdaptiveListRemoteViewsService.kt
@@ -0,0 +1,259 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.glance.adaptive.appwidget.components.list + +import android.app.Activity +import android.app.ActivityOptions +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.BadParcelableException +import android.os.Build +import android.os.Bundle +import android.os.Parcelable +import android.util.LruCache +import android.widget.RemoteViews +import android.widget.RemoteViewsService +import androidx.annotation.RequiresApi +import androidx.glance.adaptive.appwidget.R + +/** + * Distinct item layout count across scrollable `ListView` items: divider, compact (inert/tappable), + * focused (inert/tappable), checkbox (inert/tappable), and detail-card (inert/tappable). + */ +internal const val LIST_VIEW_TYPE_COUNT: Int = 9 + +internal const val ACTION_LIST_ITEM_CLICK: String = + "androidx.glance.adaptive.appwidget.action.LIST_ITEM_CLICK" +internal const val EXTRA_LIST_PENDING_INTENT: String = + "androidx.glance.adaptive.appwidget.extra.LIST_PENDING_INTENT" + +/** + * Upper bound on cached pre-API 32 list snapshots retained in memory across placed widgets, + * multi-size mappings, and theme/configuration changes; older keys are evicted via LRU. + */ +private const val MAX_STORED_LISTS = 64 + +/** + * [RemoteViewsService] supplying list item [RemoteViews] for scrollable `ItemList` widgets on API + * 24–31 (before [RemoteViews.RemoteCollectionItems] Parcelable support stabilized in API 32). + * + * Declared in `AndroidManifest.xml` with `android:exported="true"` and guarded by + * `android:permission="android.permission.BIND_REMOTEVIEWS"` (required by the platform widget + * host); kept `internal` (compiling to JVM `public` for platform instantiation) so it does not + * widen the `LIBRARY_GROUP` API surface. + */ +internal class AdaptiveListRemoteViewsService : RemoteViewsService() { + + override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { + val listKey = intent.getStringExtra(EXTRA_LIST_KEY) ?: "" + return ListFactory(applicationContext ?: this, listKey) + } + + private class ListFactory( + private val context: Context, + private val listKey: String, + ) : RemoteViewsFactory { + @Volatile private var items: List<RemoteViews> = emptyList() + + override fun onCreate() { + getItems(listKey)?.let { items = it } + } + + override fun onDataSetChanged() { + // Retain the last populated snapshot if this key was evicted from the LRU cache. + getItems(listKey)?.let { items = it } + } + + override fun onDestroy() {} + + override fun getCount(): Int = items.size + + override fun getViewAt(position: Int): RemoteViews = + items.getOrNull(position) + ?: RemoteViews( + context.packageName, + R.layout.glance_adaptive_appwidget_remoteviews_list_item, + ) + + override fun getLoadingView(): RemoteViews? = null + + override fun getViewTypeCount(): Int = LIST_VIEW_TYPE_COUNT + + override fun getItemId(position: Int): Long = position.toLong() + + // Positional indices are not stable across insertions or removals above existing rows. + override fun hasStableIds(): Boolean = false + } + + internal companion object { + private const val EXTRA_LIST_KEY = "androidx.glance.adaptive.appwidget.extra.LIST_KEY" + private const val URI_SCHEME = "glance-adaptive-list" + private const val URI_AUTHORITY = "list" + // TODO(b/580007927): In-memory storage blanks pre-API 32 scrollable lists after process + // death until appWidgetId is plumbed into renderers to back items on disk. + private val listStore = LruCache<String, List<RemoteViews>>(MAX_STORED_LISTS) + + internal fun getItems(key: String): List<RemoteViews>? = + synchronized(listStore) { listStore.get(key) } + + fun putItems(key: String, items: List<RemoteViews>) { + val copy = List(items.size) { i -> items[i] } + synchronized(listStore) { listStore.put(key, copy) } + } + + internal fun clearForTesting() { + synchronized(listStore) { listStore.evictAll() } + } + + fun serviceIntent(context: Context, key: String): Intent = + Intent(context, AdaptiveListRemoteViewsService::class.java).apply { + // Keep a distinct, properly encoded URI so Intent.filterEquals differentiates + // separate list keys (including widgetName, night mode, density, and fontScale). + data = + Uri.Builder() + .scheme(URI_SCHEME) + .authority(URI_AUTHORITY) + .appendPath(key) + .build() + putExtra(EXTRA_LIST_KEY, key) + } + } +} + +/** + * Trampoline [Activity] that dispatches `ListView` item fill-in intents for lists containing + * activity-launching actions (`LaunchAction` / `DeeplinkAction`). + * + * Launching the template as an [Activity] grants foreground activity-launch privileges on Android + * 14+ (avoiding Background Activity Launch blocks that reject activity starts from a + * [BroadcastReceiver]) and lets the widget host run native widget-to-app launch transitions. + * Passing [ActivityOptions] on API 34+ delegates this foreground activity's launch privileges to + * the embedded [PendingIntent] after verifying [PendingIntent.getCreatorPackage]. + */ +internal class AdaptiveListClickActivity : Activity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + try { + val pendingIntent = extractOwnListClickPendingIntent(this, intent) ?: return + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + AdaptiveListClickApi34Impl.sendWithBalOptions(this, pendingIntent) + } else { + pendingIntent.send() + } + } catch (_: PendingIntent.CanceledException) { + // Ignore clicks whose target PendingIntent was canceled before delivery. + } + } finally { + finish() + } + } + + internal companion object { + fun pendingIntentTemplate(context: Context): PendingIntent { + val intent = + Intent(context, AdaptiveListClickActivity::class.java).apply { + action = ACTION_LIST_ITEM_CLICK + } + return PendingIntent.getActivity(context, 0, intent, templatePendingIntentFlags()) + } + } +} + +/** + * Dispatches `ListView` item fill-in intents for callback-only lists (no activity-launching items) + * without starting a trampoline [Activity]. + * + * Android's `RemoteViews` rejects direct `setOnClickPendingIntent` / `fromPendingIntent` bindings + * on collection adapter items across all API levels; callback-only lists bind + * `setPendingIntentTemplate` to this receiver so background callbacks (such as checklist toggles) + * run silently with no activity flicker. + */ +internal class AdaptiveListClickReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + val pendingIntent = extractOwnListClickPendingIntent(context, intent) ?: return + try { + pendingIntent.send() + } catch (_: PendingIntent.CanceledException) { + // Ignore clicks whose target PendingIntent was canceled before delivery. + } + } + + internal companion object { + fun pendingIntentTemplate(context: Context): PendingIntent { + val intent = + Intent(context, AdaptiveListClickReceiver::class.java).apply { + action = ACTION_LIST_ITEM_CLICK + } + return PendingIntent.getBroadcast(context, 0, intent, templatePendingIntentFlags()) + } + } +} + +internal fun extractOwnListClickPendingIntent(context: Context, intent: Intent): PendingIntent? { + if (intent.action != ACTION_LIST_ITEM_CLICK) return null + val pendingIntent = + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + intent.getParcelableExtra(EXTRA_LIST_PENDING_INTENT, PendingIntent::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra<Parcelable>(EXTRA_LIST_PENDING_INTENT) as? PendingIntent + } + } catch (_: BadParcelableException) { + return null + } ?: return null + // pendingIntentTemplate is FLAG_MUTABLE so hosts can merge fill-in extras; verify the + // embedded PendingIntent was created by this app before forwarding it. + return pendingIntent.takeIf { it.creatorPackage == context.packageName } +} + +private fun templatePendingIntentFlags(): Int = + PendingIntent.FLAG_UPDATE_CURRENT or + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + PendingIntent.FLAG_MUTABLE + } else { + 0 + } + +@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) +private object AdaptiveListClickApi34Impl { + fun sendWithBalOptions(context: Context, pendingIntent: PendingIntent) { + val options = ActivityOptions.makeBasic() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) { + AdaptiveListClickApi36Impl.allowBackgroundStart(options) + } else { + @Suppress("DEPRECATION") + options.pendingIntentBackgroundActivityStartMode = + ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED + } + pendingIntent.send(context, 0, null, null, null, null, options.toBundle()) + } +} + +@RequiresApi(Build.VERSION_CODES.BAKLAVA) +private object AdaptiveListClickApi36Impl { + fun allowBackgroundStart(options: ActivityOptions) { + options.pendingIntentBackgroundActivityStartMode = + ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS + } +}
diff --git a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/renderer/AppWidgetRenderOutput.kt b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/renderer/AppWidgetRenderOutput.kt index 9e12810..b10328b 100644 --- a/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/renderer/AppWidgetRenderOutput.kt +++ b/glance/adaptive/adaptive-appwidget/src/main/kotlin/androidx/glance/adaptive/appwidget/renderer/AppWidgetRenderOutput.kt
@@ -22,20 +22,18 @@ import androidx.glance.adaptive.core.renderer.TemplateRenderer import androidx.glance.adaptive.core.selection.Dimensions -/** - * Output produced by a [TemplateRenderer] targeting platform AppWidget surfaces. - * - * Encapsulates the UI representations that can be translated into platform [RemoteViews]. - */ +/** Output produced by a [TemplateRenderer] for AppWidget surfaces. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun interface AppWidgetRenderOutput { /** - * Translates this render output into a platform [RemoteViews] for the given application - * [context] and target container [dimensions]. + * Builds [RemoteViews] for [context] and [dimensions]. * - * @param context The application [Context] used to construct or compose the [RemoteViews]. - * @param dimensions The target container [Dimensions] in dp. - * @return The [RemoteViews] to deliver to the host. + * May run concurrently on background threads and multiple times per update for different + * placement sizes. Must handle `Dimensions(0, 0)` when no positive size is available. + * + * @param context application [Context] used to build the [RemoteViews] + * @param dimensions target container [Dimensions] in dp + * @return [RemoteViews] to deliver to the host */ public suspend fun toRemoteViews( context: Context,
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_ic_checkbox_checked.xml b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_ic_checkbox_checked.xml new file mode 100644 index 0000000..4c7b373 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_ic_checkbox_checked.xml
@@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="#000000" + android:pathData="M19,3H5c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.11,0 2,-0.9 2,-2V5c0,-1.1 -0.89,-2 -2,-2zM10,17l-5,-5 1.41,-1.41L10,14.17l7.59,-7.59L19,8l-9,9z" /> +</vector>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_ic_checkbox_unchecked.xml b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_ic_checkbox_unchecked.xml new file mode 100644 index 0000000..87e0b9c --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_ic_checkbox_unchecked.xml
@@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<vector xmlns:android="http://schemas.android.com/apk/res/android" + android:width="24dp" + android:height="24dp" + android:viewportWidth="24" + android:viewportHeight="24"> + <path + android:fillColor="#000000" + android:pathData="M19,5v14H5V5h14m0,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2V5c0,-1.1 -0.9,-2 -2,-2z" /> +</vector>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_background.xml b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_background.xml new file mode 100644 index 0000000..99cdba8 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_background.xml
@@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <corners android:radius="14dp" /> + <solid android:color="@color/glance_adaptive_appwidget_remoteviews_secondary_container" /> +</shape>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_focused_background.xml b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_focused_background.xml new file mode 100644 index 0000000..c565456 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_focused_background.xml
@@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <corners android:radius="16dp" /> + <solid android:color="@color/glance_adaptive_appwidget_remoteviews_primary_container" /> +</shape>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_icon_circle.xml b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_icon_circle.xml new file mode 100644 index 0000000..be85ba6 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_icon_circle.xml
@@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<!-- + Fill of a contained trailing icon inside a list item card: uses widget_background so the circle + contrasts cleanly against primaryContainer and secondaryContainer rows in both Light and Dark + themes. +--> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="oval"> + <solid android:color="@color/glance_adaptive_appwidget_remoteviews_widget_background" /> +</shape>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_muted_background.xml b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_muted_background.xml new file mode 100644 index 0000000..c0dff03 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_muted_background.xml
@@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <corners android:radius="14dp" /> + <solid android:color="@color/glance_adaptive_appwidget_remoteviews_surface_container_highest" /> +</shape>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_outlined_background.xml b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_outlined_background.xml new file mode 100644 index 0000000..8533bf3 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/drawable/glance_adaptive_appwidget_remoteviews_list_item_outlined_background.xml
@@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<shape xmlns:android="http://schemas.android.com/apk/res/android" + android:shape="rectangle"> + <corners android:radius="11dp" /> + <solid android:color="@android:color/transparent" /> + <stroke + android:width="1dp" + android:color="@color/glance_adaptive_appwidget_remoteviews_secondary_container" /> +</shape>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list.xml new file mode 100644 index 0000000..8499f15 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list.xml
@@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:orientation="vertical" />
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_checkbox.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_checkbox.xml new file mode 100644 index 0000000..4605fdc --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_checkbox.xml
@@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="center_vertical" + android:orientation="horizontal" + android:paddingStart="4dp" + android:paddingTop="4dp" + android:paddingEnd="4dp" + android:paddingBottom="4dp"> + + <ImageView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_checkbox_icon" + android:layout_width="16dp" + android:layout_height="16dp" + android:layout_marginEnd="8dp" + android:adjustViewBounds="true" + android:importantForAccessibility="no" + android:scaleType="fitCenter" + android:src="@drawable/glance_adaptive_appwidget_ic_checkbox_unchecked" + android:tint="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + tools:ignore="UseAppTint" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_title" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.Medium" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card.xml new file mode 100644 index 0000000..5103b92 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card.xml
@@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="@drawable/glance_adaptive_appwidget_remoteviews_list_item_background" + android:gravity="top" + android:orientation="vertical" + android:paddingStart="12dp" + android:paddingTop="10dp" + android:paddingEnd="12dp" + android:paddingBottom="10dp"> + + <include layout="@layout/glance_adaptive_appwidget_remoteviews_list_detail_card_content" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card_content.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card_content.xml new file mode 100644 index 0000000..f3a07cc --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card_content.xml
@@ -0,0 +1,177 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<merge xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools"> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_title" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.SemiBold" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_detail_card_body" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:alpha="0.8" + android:gravity="start" + android:maxLines="2" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + android:visibility="gone" /> + + <!-- Static inline check slots avoid nested RemoteViews / duplicate IDs inside ListView. --> + <LinearLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_detail_card_checklist" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:orientation="vertical" + android:visibility="gone"> + + <LinearLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_row_0" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="center_vertical" + android:orientation="horizontal" + android:visibility="gone"> + + <ImageView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_icon_0" + android:layout_width="13dp" + android:layout_height="13dp" + android:layout_marginEnd="6dp" + android:adjustViewBounds="true" + android:importantForAccessibility="no" + android:scaleType="fitCenter" + android:src="@drawable/glance_adaptive_appwidget_ic_checkbox_unchecked" + android:tint="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + tools:ignore="UseAppTint" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_title_0" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:alpha="0.8" + android:gravity="start" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> + </LinearLayout> + + <LinearLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_row_1" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="2dp" + android:gravity="center_vertical" + android:orientation="horizontal" + android:visibility="gone"> + + <ImageView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_icon_1" + android:layout_width="13dp" + android:layout_height="13dp" + android:layout_marginEnd="6dp" + android:adjustViewBounds="true" + android:importantForAccessibility="no" + android:scaleType="fitCenter" + android:src="@drawable/glance_adaptive_appwidget_ic_checkbox_unchecked" + android:tint="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + tools:ignore="UseAppTint" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_title_1" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:alpha="0.8" + android:gravity="start" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> + </LinearLayout> + + <LinearLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_row_2" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="2dp" + android:gravity="center_vertical" + android:orientation="horizontal" + android:visibility="gone"> + + <ImageView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_icon_2" + android:layout_width="13dp" + android:layout_height="13dp" + android:layout_marginEnd="6dp" + android:adjustViewBounds="true" + android:importantForAccessibility="no" + android:scaleType="fitCenter" + android:src="@drawable/glance_adaptive_appwidget_ic_checkbox_unchecked" + android:tint="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + tools:ignore="UseAppTint" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_title_2" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:alpha="0.8" + android:gravity="start" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> + </LinearLayout> + + <LinearLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_row_3" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="2dp" + android:gravity="center_vertical" + android:orientation="horizontal" + android:visibility="gone"> + + <ImageView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_icon_3" + android:layout_width="13dp" + android:layout_height="13dp" + android:layout_marginEnd="6dp" + android:adjustViewBounds="true" + android:importantForAccessibility="no" + android:scaleType="fitCenter" + android:src="@drawable/glance_adaptive_appwidget_ic_checkbox_unchecked" + android:tint="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + tools:ignore="UseAppTint" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_check_title_3" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:alpha="0.8" + android:gravity="start" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> + </LinearLayout> + </LinearLayout> +</merge>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card_expanded.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card_expanded.xml new file mode 100644 index 0000000..dcce109 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_detail_card_expanded.xml
@@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:background="@drawable/glance_adaptive_appwidget_remoteviews_list_item_background" + android:gravity="top" + android:orientation="vertical" + android:paddingStart="12dp" + android:paddingTop="10dp" + android:paddingEnd="12dp" + android:paddingBottom="10dp"> + + <include layout="@layout/glance_adaptive_appwidget_remoteviews_list_detail_card_content" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_divider.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_divider.xml new file mode 100644 index 0000000..4581175 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_divider.xml
@@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="@drawable/glance_adaptive_appwidget_remoteviews_list_item_outlined_background" + android:gravity="center_vertical" + android:orientation="horizontal" + android:paddingStart="12dp" + android:paddingTop="3dp" + android:paddingEnd="12dp" + android:paddingBottom="3dp"> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_title" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:alpha="0.7" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.SemiBold" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item.xml new file mode 100644 index 0000000..6d0a01e --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item.xml
@@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="@drawable/glance_adaptive_appwidget_remoteviews_list_item_background" + android:gravity="center_vertical" + android:orientation="horizontal" + android:paddingStart="12dp" + android:paddingTop="5dp" + android:paddingEnd="12dp" + android:paddingBottom="5dp"> + + <include layout="@layout/glance_adaptive_appwidget_remoteviews_list_item_content" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_content.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_content.xml new file mode 100644 index 0000000..4cbeb53 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_content.xml
@@ -0,0 +1,103 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<merge xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools"> + + <FrameLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_leading" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginEnd="8dp" + android:visibility="gone" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="center_vertical" + android:orientation="horizontal"> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_subtitle" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginEnd="8dp" + android:alpha="0.7" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.Medium" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + android:visibility="gone" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_title" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.SemiBold" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> + </LinearLayout> + + <LinearLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_tertiary_row" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="2dp" + android:gravity="center_vertical" + android:orientation="horizontal" + android:visibility="gone"> + + <ImageView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_tertiary_icon" + android:layout_width="13dp" + android:layout_height="13dp" + android:layout_marginEnd="4dp" + android:adjustViewBounds="true" + android:alpha="0.7" + android:importantForAccessibility="no" + android:scaleType="fitCenter" + android:tint="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" + android:visibility="gone" + tools:ignore="UseAppTint" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_tertiary" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:alpha="0.7" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.Medium" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_secondary_container" /> + </LinearLayout> + </LinearLayout> + + <FrameLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_trailing" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginStart="8dp" + android:visibility="gone" /> +</merge>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_expanded.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_expanded.xml new file mode 100644 index 0000000..5f7e950 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_expanded.xml
@@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:background="@drawable/glance_adaptive_appwidget_remoteviews_list_item_background" + android:gravity="center_vertical" + android:orientation="horizontal" + android:paddingStart="12dp" + android:paddingTop="5dp" + android:paddingEnd="12dp" + android:paddingBottom="5dp"> + + <include layout="@layout/glance_adaptive_appwidget_remoteviews_list_item_content" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused.xml new file mode 100644 index 0000000..fc65f3a --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused.xml
@@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:background="@drawable/glance_adaptive_appwidget_remoteviews_list_item_focused_background" + android:gravity="center_vertical" + android:orientation="horizontal" + android:paddingStart="12dp" + android:paddingTop="8dp" + android:paddingEnd="12dp" + android:paddingBottom="8dp"> + + <include layout="@layout/glance_adaptive_appwidget_remoteviews_list_item_focused_content" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused_content.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused_content.xml new file mode 100644 index 0000000..810a8d3 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused_content.xml
@@ -0,0 +1,95 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<merge xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools"> + + <FrameLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_leading" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginEnd="8dp" + android:visibility="gone" /> + + <LinearLayout + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:orientation="vertical"> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_subtitle" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="2dp" + android:alpha="0.7" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.Medium" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_primary_container" + android:visibility="gone" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_title" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.SemiBold" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_primary_container" /> + + <LinearLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_tertiary_row" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="2dp" + android:gravity="center_vertical" + android:orientation="horizontal" + android:visibility="gone"> + + <ImageView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_tertiary_icon" + android:layout_width="13dp" + android:layout_height="13dp" + android:layout_marginEnd="4dp" + android:adjustViewBounds="true" + android:alpha="0.7" + android:importantForAccessibility="no" + android:scaleType="fitCenter" + android:tint="@color/glance_adaptive_appwidget_remoteviews_on_primary_container" + android:visibility="gone" + tools:ignore="UseAppTint" /> + + <TextView + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_tertiary" + style="@style/GlanceAdaptiveAppwidgetRemoteviews.ListText" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:alpha="0.7" + android:gravity="start" + android:textAppearance="@style/GlanceAdaptiveAppwidgetRemoteviews.TextAppearance.Medium" + android:textColor="@color/glance_adaptive_appwidget_remoteviews_on_primary_container" /> + </LinearLayout> + </LinearLayout> + + <FrameLayout + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item_trailing" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginStart="8dp" + android:visibility="gone" /> +</merge>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused_expanded.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused_expanded.xml new file mode 100644 index 0000000..df533bb --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_item_focused_expanded.xml
@@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:id="@+id/glance_adaptive_appwidget_remoteviews_list_item" + android:layout_width="match_parent" + android:layout_height="0dp" + android:layout_weight="1" + android:background="@drawable/glance_adaptive_appwidget_remoteviews_list_item_focused_background" + android:gravity="center_vertical" + android:orientation="horizontal" + android:paddingStart="12dp" + android:paddingTop="8dp" + android:paddingEnd="12dp" + android:paddingBottom="8dp"> + + <include layout="@layout/glance_adaptive_appwidget_remoteviews_list_item_focused_content" /> +</LinearLayout>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_spacer.xml b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_spacer.xml new file mode 100644 index 0000000..92b871a --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/layout/glance_adaptive_appwidget_remoteviews_list_spacer.xml
@@ -0,0 +1,19 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="4dp" />
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/values/remoteviews_layouts.xml b/glance/adaptive/adaptive-appwidget/src/main/res/values/remoteviews_layouts.xml new file mode 100644 index 0000000..a4791c1 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/main/res/values/remoteviews_layouts.xml
@@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- + Copyright 2026 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> +<resources> + <!-- Distinct layout IDs keep tappable and inert ListView rows in separate recycling pools. --> + <item name="glance_adaptive_appwidget_remoteviews_list_item_tappable" type="layout">@layout/glance_adaptive_appwidget_remoteviews_list_item</item> + <item name="glance_adaptive_appwidget_remoteviews_list_item_focused_tappable" type="layout">@layout/glance_adaptive_appwidget_remoteviews_list_item_focused</item> + <item name="glance_adaptive_appwidget_remoteviews_list_checkbox_tappable" type="layout">@layout/glance_adaptive_appwidget_remoteviews_list_checkbox</item> + <item name="glance_adaptive_appwidget_remoteviews_list_detail_card_tappable" type="layout">@layout/glance_adaptive_appwidget_remoteviews_list_detail_card</item> +</resources>
diff --git a/glance/adaptive/adaptive-appwidget/src/main/res/values/remoteviews_styles.xml b/glance/adaptive/adaptive-appwidget/src/main/res/values/remoteviews_styles.xml index c081c90..6d0fa10 100644 --- a/glance/adaptive/adaptive-appwidget/src/main/res/values/remoteviews_styles.xml +++ b/glance/adaptive/adaptive-appwidget/src/main/res/values/remoteviews_styles.xml
@@ -42,6 +42,11 @@ <item name="android:textDirection">locale</item> </style> + <!-- List item text disables extra font padding to match RemoteCompose vertical metrics. --> + <style name="GlanceAdaptiveAppwidgetRemoteviews.ListText" parent="GlanceAdaptiveAppwidgetRemoteviews.Text"> + <item name="android:includeFontPadding">false</item> + </style> + <!-- Glance applies FontWeight through a TextAppearanceSpan of these styles. Below API 29 there is no font weight attribute, so Glance falls back to bold for both.
diff --git a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistryTest.kt b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistryTest.kt index ebbbf92..1286bfa73 100644 --- a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistryTest.kt +++ b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/AppWidgetTemplateRegistryTest.kt
@@ -405,16 +405,7 @@ } @Test - fun hasDroppedSlots_returnsFalseWhenCustomRendererOverrideIsActive() { - val track = - TrackTemplate( - leading = Ring(0.55f), - primary = TemplateText("7,922"), - secondary = TemplateText("steps"), - supporting = listOf(TemplateText("Goal: 10,000")), - ) - val compactLock = AppWidgetSurface.MOBILE_LOCK_SCREEN.withDimensions(Dimensions(168, 28)) - val compactHome = AppWidgetSurface.MOBILE_HOME_SCREEN.withDimensions(Dimensions(88, 88)) + fun hasOverride_matchesWidgetTemplateAndSurface() { AppWidgetTemplateRegistry.register( widgetName = "custom_widget", templateClass = TrackTemplate::class.java, @@ -424,21 +415,31 @@ }, surface = AppWidgetSurface.MOBILE_LOCK_SCREEN, ) + val placedLock = AppWidgetSurface.MOBILE_LOCK_SCREEN.withDimensions(Dimensions(168, 28)) - assertThat(AppWidgetTemplateRegistry.hasDroppedSlots(track, compactLock, "custom_widget")) + assertThat( + AppWidgetTemplateRegistry.hasOverride( + "custom_widget", + TrackTemplate::class.java, + placedLock, + ) + ) + .isTrue() + assertThat( + AppWidgetTemplateRegistry.hasOverride( + "other_widget", + TrackTemplate::class.java, + placedLock, + ) + ) .isFalse() - assertThat(AppWidgetTemplateRegistry.hasDroppedSlots(track, compactLock, "other_widget")) - .isTrue() - assertThat(AppWidgetTemplateRegistry.hasDroppedSlots(track, compactHome, "custom_widget")) - .isTrue() - - AppWidgetTemplateRegistry.unregister( - widgetName = "custom_widget", - templateClass = TrackTemplate::class.java, - surface = AppWidgetSurface.MOBILE_LOCK_SCREEN, - ) - - assertThat(AppWidgetTemplateRegistry.hasDroppedSlots(track, compactLock, "custom_widget")) - .isTrue() + assertThat( + AppWidgetTemplateRegistry.hasOverride( + "custom_widget", + TrackTemplate::class.java, + AppWidgetSurface.MOBILE_HOME_SCREEN, + ) + ) + .isFalse() } }
diff --git a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/BaseWidgetDelegatePushUpdateTest.kt b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/BaseWidgetDelegatePushUpdateTest.kt index e6c729a..7383881 100644 --- a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/BaseWidgetDelegatePushUpdateTest.kt +++ b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/BaseWidgetDelegatePushUpdateTest.kt
@@ -641,5 +641,9 @@ options.getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS) ) .isFalse() + assertThat( + options.getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER) + ) + .isTrue() } }
diff --git a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManagerTest.kt b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManagerTest.kt index 87fec6e..bc93272 100644 --- a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManagerTest.kt +++ b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/GlanceAdaptiveAppWidgetManagerTest.kt
@@ -336,6 +336,26 @@ } @Test + fun registerRenderer_withBlankWidgetName_throwsIllegalArgumentException() { + val manager = GlanceAdaptiveWidgetManager(FakeAppWidgetDelegate()) + + assertThrows(IllegalArgumentException::class.java) { + manager.registerRenderer( + widgetName = "", + surface = AppWidgetSurface.MOBILE_HOME_SCREEN, + renderer = TemplateRenderer { _: TestTemplate, _ -> error("Never rendered") }, + ) + } + assertThrows(IllegalArgumentException::class.java) { + manager.registerRenderer( + widgetName = " ", + surface = AppWidgetSurface.MOBILE_HOME_SCREEN, + renderer = TemplateRenderer { _: TestTemplate, _ -> error("Never rendered") }, + ) + } + } + + @Test fun unregisterRenderer_restoresDefaultOnlyForTargetWidgetAndSurface() { val context = ApplicationProvider.getApplicationContext<Context>() val defaultViews = RemoteViews(context.packageName, android.R.layout.simple_list_item_1)
diff --git a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandlerTest.kt b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandlerTest.kt index e23859b..dfbda66 100644 --- a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandlerTest.kt +++ b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/WidgetTelemetryHandlerTest.kt
@@ -42,6 +42,7 @@ import org.mockito.kotlin.eq import org.mockito.kotlin.never import org.mockito.kotlin.spy +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner @@ -102,6 +103,10 @@ .isTrue() assertThat(options.getBoolean("android.appwidget.option.ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS")) .isFalse() + assertThat(options.containsKey("android.appwidget.option.ADAPTIVE_WIDGET_CUSTOM_RENDERER")) + .isTrue() + assertThat(options.getBoolean("android.appwidget.option.ADAPTIVE_WIDGET_CUSTOM_RENDERER")) + .isFalse() } @Test @@ -130,6 +135,7 @@ WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_TEMPLATE_TYPE, WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_SDK_VERSION_CODE, WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, + WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER, ) val options = appWidgetManager.getAppWidgetOptions(702) assertThat(options.getString(GlanceAdaptiveWidgetReceiver.EXTRA_WIDGET_ID)) @@ -153,6 +159,7 @@ WidgetTelemetryHandler.XFF_SDK_VERSION_CODE, ) putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, false) + putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER, false) }, ) @@ -162,6 +169,35 @@ } @Test + fun ensureTelemetryOptions_whenCustomRendererKeyIsMissing_updatesOptions() { + // Placements written by an older library version carry the other keys but not this one. + bindWidget( + 705, + Bundle().apply { + putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_ENABLED, true) + putInt(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_TEMPLATE_TYPE, 1) + putInt( + WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_SDK_VERSION_CODE, + WidgetTelemetryHandler.XFF_SDK_VERSION_CODE, + ) + putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, false) + }, + ) + + handler.ensureTelemetryOptions(mapOf(HOME_SCREEN_TARGET to listOf(705)), TestTemplate()) + + val options = appWidgetManager.getAppWidgetOptions(705) + assertThat( + options.containsKey(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER) + ) + .isTrue() + assertThat( + options.getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER) + ) + .isFalse() + } + + @Test fun ensureTelemetryOptions_whenTemplateTypeChanges_updatesOptions() { bindWidget( 704, @@ -173,6 +209,7 @@ WidgetTelemetryHandler.XFF_SDK_VERSION_CODE, ) putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, false) + putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER, false) }, ) @@ -237,6 +274,7 @@ WidgetTelemetryHandler.XFF_SDK_VERSION_CODE, ) putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS, false) + putBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER, false) }, ) val compactTarget = RenderTarget(AppWidgetSurface.MOBILE_HOME_SCREEN, Dimensions(88, 88)) @@ -312,6 +350,130 @@ .getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS) ) .isTrue() + assertThat( + customOptions.getBoolean( + WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER + ) + ) + .isTrue() + assertThat( + appWidgetManager + .getAppWidgetOptions(714) + .getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER) + ) + .isFalse() + } + + @Test + fun ensureTelemetryOptions_customRendererOnLockScreenOnly_reportsItPerSurface() { + bindWidget(715) + bindWidget(716) + val lockTarget = RenderTarget(AppWidgetSurface.MOBILE_LOCK_SCREEN, Dimensions(168, 28)) + val homeTarget = RenderTarget(AppWidgetSurface.MOBILE_HOME_SCREEN, Dimensions(88, 88)) + registerCustomTrackRenderer(AppWidgetSurface.MOBILE_LOCK_SCREEN) + + handler.ensureTelemetryOptions( + mapOf(lockTarget to listOf(715), homeTarget to listOf(716)), + droppingTrackTemplate(), + widgetName = CUSTOM_WIDGET, + ) + + val lockOptions = appWidgetManager.getAppWidgetOptions(715) + assertThat( + lockOptions.getBoolean( + WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER + ) + ) + .isTrue() + assertThat( + lockOptions.getBoolean( + WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS + ) + ) + .isFalse() + val homeOptions = appWidgetManager.getAppWidgetOptions(716) + assertThat( + homeOptions.getBoolean( + WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER + ) + ) + .isFalse() + assertThat( + homeOptions.getBoolean( + WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS + ) + ) + .isTrue() + } + + @Test + fun ensureTelemetryOptions_afterUnregisteringCustomRenderer_reportsBuiltInLayoutAgain() { + bindWidget(717) + val lockTarget = RenderTarget(AppWidgetSurface.MOBILE_LOCK_SCREEN, Dimensions(168, 28)) + registerCustomTrackRenderer(AppWidgetSurface.MOBILE_LOCK_SCREEN) + handler.ensureTelemetryOptions( + mapOf(lockTarget to listOf(717)), + droppingTrackTemplate(), + widgetName = CUSTOM_WIDGET, + ) + + AppWidgetTemplateRegistry.unregister( + widgetName = CUSTOM_WIDGET, + templateClass = TrackTemplate::class.java, + surface = AppWidgetSurface.MOBILE_LOCK_SCREEN, + ) + handler.ensureTelemetryOptions( + mapOf(lockTarget to listOf(717)), + droppingTrackTemplate(), + widgetName = CUSTOM_WIDGET, + ) + + val options = appWidgetManager.getAppWidgetOptions(717) + assertThat( + options.getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER) + ) + .isFalse() + assertThat( + options.getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS) + ) + .isTrue() + verify(appWidgetManager, times(2)).updateAppWidgetOptions(eq(717), any()) + } + + @Test + fun ensureTelemetryOptions_whenOnlyCustomRendererChanges_updatesOptions() { + bindWidget(718) + // At this size the built-in layout drops no slots, so only the custom renderer key changes. + val fullTarget = RenderTarget(AppWidgetSurface.MOBILE_HOME_SCREEN, Dimensions(348, 264)) + handler.ensureTelemetryOptions( + mapOf(fullTarget to listOf(718)), + droppingTrackTemplate(), + widgetName = CUSTOM_WIDGET, + ) + assertThat( + appWidgetManager + .getAppWidgetOptions(718) + .getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS) + ) + .isFalse() + + registerCustomTrackRenderer(AppWidgetSurface.MOBILE_HOME_SCREEN) + handler.ensureTelemetryOptions( + mapOf(fullTarget to listOf(718)), + droppingTrackTemplate(), + widgetName = CUSTOM_WIDGET, + ) + + val options = appWidgetManager.getAppWidgetOptions(718) + assertThat( + options.getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_CUSTOM_RENDERER) + ) + .isTrue() + assertThat( + options.getBoolean(WidgetTelemetryHandler.OPTION_ADAPTIVE_WIDGET_HAS_DROPPED_SLOTS) + ) + .isFalse() + verify(appWidgetManager, times(2)).updateAppWidgetOptions(eq(718), any()) } @Test @@ -384,6 +546,29 @@ assertThat(onUpdateCalled).isFalse() } + /** A [TrackTemplate] whose built-in layout drops slots at the compact test targets. */ + private fun droppingTrackTemplate() = + TrackTemplate( + leading = Ring(0.8f), + primary = TemplateText("7,922"), + secondary = TemplateText("steps"), + supporting = listOf(TemplateText("Goal: 10,000")), + ) + + private fun registerCustomTrackRenderer(surface: AppWidgetSurface) { + AppWidgetTemplateRegistry.register( + widgetName = CUSTOM_WIDGET, + templateClass = TrackTemplate::class.java, + renderer = + TemplateRenderer { _, _ -> + RemoteViewsRenderOutput( + RemoteViews(context.packageName, android.R.layout.simple_list_item_1) + ) + }, + surface = surface, + ) + } + /** Binds [appWidgetId] with [options] already stored, as a host would have left them. */ private fun bindWidget(appWidgetId: Int, options: Bundle = Bundle()) { val realManager = AppWidgetManager.getInstance(context) @@ -403,5 +588,6 @@ val HOME_SCREEN_TARGET = RenderTarget(AppWidgetSurface.MOBILE_HOME_SCREEN, Dimensions(0, 0)) val LOCK_SCREEN_TARGET = RenderTarget(AppWidgetSurface.MOBILE_LOCK_SCREEN, Dimensions(0, 0)) + const val CUSTOM_WIDGET = "custom_widget" } }
diff --git a/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/components/list/AdaptiveListRemoteViewsServiceTest.kt b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/components/list/AdaptiveListRemoteViewsServiceTest.kt new file mode 100644 index 0000000..a078d55 --- /dev/null +++ b/glance/adaptive/adaptive-appwidget/src/test/kotlin/androidx/glance/adaptive/appwidget/components/list/AdaptiveListRemoteViewsServiceTest.kt
@@ -0,0 +1,375 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.glance.adaptive.appwidget.components.list + +import android.app.Application +import android.app.PendingIntent +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.widget.RemoteViews +import androidx.glance.adaptive.appwidget.R +import androidx.test.core.app.ApplicationProvider +import androidx.test.filters.SdkSuppress +import com.google.common.truth.Truth.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +@Config(sdk = [Config.TARGET_SDK]) +@RunWith(RobolectricTestRunner::class) +class AdaptiveListRemoteViewsServiceTest { + + private lateinit var context: Context + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + AdaptiveListRemoteViewsService.clearForTesting() + } + + @After + fun tearDown() { + AdaptiveListRemoteViewsService.clearForTesting() + } + + @Test + fun serviceStore_defensivelyCopiesAndSuppliesFactoryItems() { + val row0 = + RemoteViews( + context.packageName, + R.layout.glance_adaptive_appwidget_remoteviews_list_item, + ) + val row1 = + RemoteViews( + context.packageName, + R.layout.glance_adaptive_appwidget_remoteviews_list_checkbox, + ) + val mutableInput = mutableListOf(row0, row1) + val key = "widget/special:-42_W2_night" + + AdaptiveListRemoteViewsService.putItems(key, mutableInput) + mutableInput.clear() + + val intent = AdaptiveListRemoteViewsService.serviceIntent(context, key) + assertThat(intent.data?.scheme).isEqualTo("glance-adaptive-list") + assertThat(intent.data?.authority).isEqualTo("list") + assertThat(intent.data?.lastPathSegment).isEqualTo(key) + assertThat( + intent.filterEquals(AdaptiveListRemoteViewsService.serviceIntent(context, "other")) + ) + .isFalse() + + val service = Robolectric.setupService(AdaptiveListRemoteViewsService::class.java) + val factory = service.onGetViewFactory(intent) + factory.onCreate() + assertThat(factory.count).isEqualTo(2) + assertThat(factory.viewTypeCount).isEqualTo(LIST_VIEW_TYPE_COUNT) + assertThat(factory.hasStableIds()).isFalse() + assertThat(factory.getItemId(1)).isEqualTo(1L) + assertThat(factory.getViewAt(0)).isSameInstanceAs(row0) + assertThat(factory.getViewAt(1)).isSameInstanceAs(row1) + // Out-of-bounds falls back safely to an empty row rather than throwing. + assertThat(factory.getViewAt(99)).isNotNull() + + AdaptiveListRemoteViewsService.putItems(key, listOf(row1)) + factory.onDataSetChanged() + assertThat(factory.count).isEqualTo(1) + } + + @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S) + @Test + fun clickReceiver_dispatchesValidActionAndIgnoresInvalidOrCanceled() { + val receiver = AdaptiveListClickReceiver() + val broadcastAction = "androidx.glance.adaptive.appwidget.test.CLICK_DISPATCHED" + val targetIntent = Intent(broadcastAction).setPackage(context.packageName) + val targetPendingIntent = + PendingIntent.getBroadcast( + context, + 42, + targetIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + // Wrong or missing action is ignored. + receiver.onReceive( + context, + Intent("unexpected.action").putExtra(EXTRA_LIST_PENDING_INTENT, targetPendingIntent), + ) + assertThat(shadowOf(context as Application).broadcastIntents).isEmpty() + + // Missing or wrong-type Parcelable extra is safely ignored without crashing. + receiver.onReceive(context, Intent(ACTION_LIST_ITEM_CLICK)) + receiver.onReceive( + context, + Intent(ACTION_LIST_ITEM_CLICK).putExtra(EXTRA_LIST_PENDING_INTENT, Uri.EMPTY), + ) + assertThat(shadowOf(context as Application).broadcastIntents).isEmpty() + + // Foreign creatorPackage is rejected so a hostile host cannot abuse the mutable template. + val foreignContext = + object : ContextWrapper(context) { + override fun getPackageName(): String = "com.example.foreign" + } + receiver.onReceive( + foreignContext, + Intent(ACTION_LIST_ITEM_CLICK).putExtra(EXTRA_LIST_PENDING_INTENT, targetPendingIntent), + ) + assertThat(shadowOf(context as Application).broadcastIntents).isEmpty() + + // Valid action dispatches the embedded PendingIntent. + receiver.onReceive( + context, + Intent(ACTION_LIST_ITEM_CLICK).putExtra(EXTRA_LIST_PENDING_INTENT, targetPendingIntent), + ) + val afterValidCount = shadowOf(context as Application).broadcastIntents.size + assertThat(shadowOf(context as Application).broadcastIntents.map { it.action }) + .contains(broadcastAction) + + // Canceled PendingIntent is silently ignored without crashing or delivering a broadcast. + targetPendingIntent.cancel() + receiver.onReceive( + context, + Intent(ACTION_LIST_ITEM_CLICK).putExtra(EXTRA_LIST_PENDING_INTENT, targetPendingIntent), + ) + assertThat(shadowOf(context as Application).broadcastIntents).hasSize(afterValidCount) + + // Template PendingIntent targets AdaptiveListClickReceiver with FLAG_MUTABLE on API 31+. + val template = AdaptiveListClickReceiver.pendingIntentTemplate(context) + assertThat(template.isBroadcast).isTrue() + assertThat(shadowOf(template).savedIntent.component?.className) + .isEqualTo(AdaptiveListClickReceiver::class.java.name) + assertThat(shadowOf(template).savedIntent.action).isEqualTo(ACTION_LIST_ITEM_CLICK) + assertThat(shadowOf(template).flags and PendingIntent.FLAG_MUTABLE).isNotEqualTo(0) + } + + @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S) + @Test + fun clickActivity_dispatchesActivityAndBroadcastActionsAndAlwaysFinishes() { + val activityAction = "androidx.glance.adaptive.appwidget.test.OPEN_ACTIVITY" + val targetActivityPendingIntent = + PendingIntent.getActivity( + context, + 11, + Intent(activityAction).setPackage(context.packageName), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + // Wrong action and invalid extra are ignored and still finish the NoDisplay activity. + val wrongActionActivity = + Robolectric.buildActivity( + AdaptiveListClickActivity::class.java, + Intent("unexpected.action") + .putExtra(EXTRA_LIST_PENDING_INTENT, targetActivityPendingIntent), + ) + .create() + .get() + assertThat(wrongActionActivity.isFinishing).isTrue() + assertThat(shadowOf(context as Application).nextStartedActivity).isNull() + + val badExtraActivity = + Robolectric.buildActivity( + AdaptiveListClickActivity::class.java, + Intent(ACTION_LIST_ITEM_CLICK).putExtra(EXTRA_LIST_PENDING_INTENT, Uri.EMPTY), + ) + .create() + .get() + assertThat(badExtraActivity.isFinishing).isTrue() + assertThat(shadowOf(context as Application).nextStartedActivity).isNull() + + // Valid activity PendingIntent launches the target activity and finishes. + val validActivity = + Robolectric.buildActivity( + AdaptiveListClickActivity::class.java, + Intent(ACTION_LIST_ITEM_CLICK) + .putExtra(EXTRA_LIST_PENDING_INTENT, targetActivityPendingIntent), + ) + .create() + .get() + assertThat(validActivity.isFinishing).isTrue() + assertThat(shadowOf(context as Application).nextStartedActivity?.action) + .isEqualTo(activityAction) + + // Mixed-list broadcast PendingIntent is also forwarded and finishes cleanly. + val broadcastAction = "androidx.glance.adaptive.appwidget.test.MIXED_LIST_CALLBACK" + val broadcastPendingIntent = + PendingIntent.getBroadcast( + context, + 12, + Intent(broadcastAction).setPackage(context.packageName), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val callbackActivity = + Robolectric.buildActivity( + AdaptiveListClickActivity::class.java, + Intent(ACTION_LIST_ITEM_CLICK) + .putExtra(EXTRA_LIST_PENDING_INTENT, broadcastPendingIntent), + ) + .create() + .get() + assertThat(callbackActivity.isFinishing).isTrue() + assertThat(shadowOf(context as Application).broadcastIntents.map { it.action }) + .contains(broadcastAction) + + // Canceled PendingIntent is ignored without crashing and still finishes. + targetActivityPendingIntent.cancel() + val canceledActivity = + Robolectric.buildActivity( + AdaptiveListClickActivity::class.java, + Intent(ACTION_LIST_ITEM_CLICK) + .putExtra(EXTRA_LIST_PENDING_INTENT, targetActivityPendingIntent), + ) + .create() + .get() + assertThat(canceledActivity.isFinishing).isTrue() + assertThat(shadowOf(context as Application).nextStartedActivity).isNull() + + // Template PendingIntent targets AdaptiveListClickActivity with FLAG_MUTABLE on API 31+. + val template = AdaptiveListClickActivity.pendingIntentTemplate(context) + assertThat(template.isActivity).isTrue() + assertThat(shadowOf(template).savedIntent.component?.className) + .isEqualTo(AdaptiveListClickActivity::class.java.name) + assertThat(shadowOf(template).savedIntent.action).isEqualTo(ACTION_LIST_ITEM_CLICK) + assertThat(shadowOf(template).flags and PendingIntent.FLAG_MUTABLE).isNotEqualTo(0) + } + + @Test + fun serviceStore_evictsLeastRecentlyUsedEntriesAndFactoryRetainsSnapshotOnEviction() { + val row0 = + RemoteViews( + context.packageName, + R.layout.glance_adaptive_appwidget_remoteviews_list_item, + ) + val row1 = + RemoteViews( + context.packageName, + R.layout.glance_adaptive_appwidget_remoteviews_list_checkbox, + ) + AdaptiveListRemoteViewsService.putItems("key_0", listOf(row0, row1)) + + val service = Robolectric.setupService(AdaptiveListRemoteViewsService::class.java) + val factory = + service.onGetViewFactory(AdaptiveListRemoteViewsService.serviceIntent(context, "key_0")) + factory.onCreate() + assertThat(factory.count).isEqualTo(2) + + for (i in 1..64) { + AdaptiveListRemoteViewsService.putItems("key_$i", listOf(row0)) + } + assertThat(AdaptiveListRemoteViewsService.getItems("key_0")).isNull() + assertThat(AdaptiveListRemoteViewsService.getItems("key_1")).hasSize(1) + assertThat(AdaptiveListRemoteViewsService.getItems("key_64")).hasSize(1) + + // Eviction from LruCache must not blank an already-populated factory on onDataSetChanged(). + factory.onDataSetChanged() + assertThat(factory.count).isEqualTo(2) + assertThat(factory.getViewAt(0)).isSameInstanceAs(row0) + assertThat(factory.getViewAt(1)).isSameInstanceAs(row1) + + // Once the key is re-populated, onDataSetChanged() picks up the new snapshot. + AdaptiveListRemoteViewsService.putItems("key_0", listOf(row1)) + factory.onDataSetChanged() + assertThat(factory.count).isEqualTo(1) + assertThat(factory.getViewAt(0)).isSameInstanceAs(row1) + } + + @Test + @Config(sdk = [30]) + fun clickDispatch_preApi34_dispatchesSafelyAndOmitsMutableFlagBelowApi31() { + val receiver = AdaptiveListClickReceiver() + val broadcastAction = "androidx.glance.adaptive.appwidget.test.PRE_API_34_CLICK" + val targetPendingIntent = + PendingIntent.getBroadcast( + context, + 7, + Intent(broadcastAction).setPackage(context.packageName), + PendingIntent.FLAG_UPDATE_CURRENT, + ) + + // Wrong-type Parcelable on < TIRAMISU must not throw ClassCastException. + receiver.onReceive( + context, + Intent(ACTION_LIST_ITEM_CLICK).putExtra(EXTRA_LIST_PENDING_INTENT, Uri.EMPTY), + ) + assertThat(shadowOf(context as Application).broadcastIntents).isEmpty() + + receiver.onReceive( + context, + Intent(ACTION_LIST_ITEM_CLICK).putExtra(EXTRA_LIST_PENDING_INTENT, targetPendingIntent), + ) + assertThat(shadowOf(context as Application).broadcastIntents.map { it.action }) + .contains(broadcastAction) + + val receiverTemplate = AdaptiveListClickReceiver.pendingIntentTemplate(context) + assertThat(shadowOf(receiverTemplate).flags and PendingIntent.FLAG_MUTABLE).isEqualTo(0) + + val activityAction = "androidx.glance.adaptive.appwidget.test.PRE_API_34_ACTIVITY" + val activityPendingIntent = + PendingIntent.getActivity( + context, + 8, + Intent(activityAction).setPackage(context.packageName), + PendingIntent.FLAG_UPDATE_CURRENT, + ) + val activity = + Robolectric.buildActivity( + AdaptiveListClickActivity::class.java, + Intent(ACTION_LIST_ITEM_CLICK) + .putExtra(EXTRA_LIST_PENDING_INTENT, activityPendingIntent), + ) + .create() + .get() + assertThat(activity.isFinishing).isTrue() + assertThat(shadowOf(context as Application).nextStartedActivity?.action) + .isEqualTo(activityAction) + + val activityTemplate = AdaptiveListClickActivity.pendingIntentTemplate(context) + assertThat(shadowOf(activityTemplate).flags and PendingIntent.FLAG_MUTABLE).isEqualTo(0) + } + + @Test + @Config(sdk = [34]) + fun clickActivity_api34_dispatchesWithForegroundActivityLaunchOptions() { + val activityAction = "androidx.glance.adaptive.appwidget.test.API_34_ACTIVITY" + val targetPendingIntent = + PendingIntent.getActivity( + context, + 9, + Intent(activityAction).setPackage(context.packageName), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + val activity = + Robolectric.buildActivity( + AdaptiveListClickActivity::class.java, + Intent(ACTION_LIST_ITEM_CLICK) + .putExtra(EXTRA_LIST_PENDING_INTENT, targetPendingIntent), + ) + .create() + .get() + assertThat(activity.isFinishing).isTrue() + assertThat(shadowOf(context as Application).nextStartedActivity?.action) + .isEqualTo(activityAction) + } +}
diff --git a/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistry.kt b/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistry.kt index 40424a3..04a8850 100644 --- a/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistry.kt +++ b/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistry.kt
@@ -166,11 +166,12 @@ * [templateClass] on [surface], or on every surface when [surface] is `null`. * * @param T The template type implementing [GlanceAdaptiveTemplate]. - * @param widgetName Developer widget identifier the override applies to. + * @param widgetName Developer widget identifier the override applies to. Must not be blank. * @param templateClass The concrete runtime class of the [GlanceAdaptiveTemplate] data payload. * @param renderer Draws [templateClass] for [widgetName]. * @param surface Optional surface to target, or `null` for all surfaces. - * @throws IllegalArgumentException if [templateClass] is an abstract class. + * @throws IllegalArgumentException if [widgetName] is blank or if [templateClass] is an + * abstract class. */ public fun <T : GlanceAdaptiveTemplate> registerOverride( widgetName: String, @@ -178,6 +179,7 @@ renderer: TemplateRenderer<T, S, R>, surface: S? = null, ) { + require(widgetName.isNotBlank()) { "widgetName must not be blank" } requireConcreteTemplateClass(templateClass) val untyped = renderer.asUntyped() synchronized(lock) {
diff --git a/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRenderer.kt b/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRenderer.kt index 4f79a7f..acca00e 100644 --- a/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRenderer.kt +++ b/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/renderer/TemplateRenderer.kt
@@ -21,26 +21,15 @@ import androidx.glance.adaptive.core.templates.GlanceAdaptiveTemplate /** - * Rendering contract turning a template of type [T] on a surface of type [S] into host content of - * type [R]. + * Renders a [GlanceAdaptiveTemplate] of type [T] on a [GlanceSurface] of type [S] into host content + * of type [R]. * - * This is the contract developers implement to draw a template themselves. The library's built-in - * templates implement it by pairing an internal archetype selector with an [ArchetypeRenderer]. + * [render] must be free of side effects and thread-safe: it may run concurrently on background + * threads and multiple times per update for different placement sizes. * - * The output type is a parameter because this module deliberately carries no UI dependency: it - * cannot name `@Composable`, `RemoteViews`, or any other host effect type. Leaving [R] open lets - * each host substitute its own, so the contract stays shared while the rendering mechanism stays - * host-specific: - * - Glance AppWidget hosts substitute `@Composable () -> Unit`. - * - Plain `RemoteViews` hosts substitute `RemoteViews`. - * - Tests substitute a value they can assert on. - * - * Implementations must be pure: [render] is expected to *produce* content rather than emit it, so - * that resolution can be exercised in a plain unit test, outside of any host runtime. - * - * @param T The template type implementing [GlanceAdaptiveTemplate]. - * @param S The surface type implementing [GlanceSurface]. - * @param R The host content type produced by [render]. + * @param T template type implementing [GlanceAdaptiveTemplate] + * @param S surface type implementing [GlanceSurface] + * @param R host content type produced by [render] */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public fun interface TemplateRenderer< @@ -52,10 +41,9 @@ /** * Produces host content for [template] on [surface]. * - * @param template Declarative template data payload. - * @param surface Target placement: the host surface, carrying its container size as - * [GlanceSurface.dimensions]. - * @return Host content of type [R]. + * @param template template data payload + * @param surface target host surface + * @return host content of type [R] */ public fun render(template: T, surface: S): R }
diff --git a/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/selection/SizeTiers.kt b/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/selection/SizeTiers.kt index 03e1fb1..5263231 100644 --- a/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/selection/SizeTiers.kt +++ b/glance/adaptive/adaptive-core/src/main/kotlin/androidx/glance/adaptive/core/selection/SizeTiers.kt
@@ -16,16 +16,35 @@ package androidx.glance.adaptive.core.selection +import androidx.annotation.Dimension +import androidx.annotation.IntRange import androidx.annotation.RestrictTo /** - * Represents 2D container dimensions in density-independent pixels. + * Container width and height in dp. * - * @param widthDp Container width in DP. - * @param heightDp Container height in DP. + * @property widthDp non-negative width in dp + * @property heightDp non-negative height in dp + * @throws IllegalArgumentException if [widthDp] or [heightDp] is negative */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) -public class Dimensions(public val widthDp: Int, public val heightDp: Int) { +public class Dimensions( + @param:Dimension(unit = Dimension.DP) + @get:Dimension(unit = Dimension.DP) + @param:IntRange(from = 0) + @get:IntRange(from = 0) + public val widthDp: Int, + @param:Dimension(unit = Dimension.DP) + @get:Dimension(unit = Dimension.DP) + @param:IntRange(from = 0) + @get:IntRange(from = 0) + public val heightDp: Int, +) { + init { + require(widthDp >= 0) { "widthDp must be non-negative, was $widthDp." } + require(heightDp >= 0) { "heightDp must be non-negative, was $heightDp." } + } + override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Dimensions) return false
diff --git a/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistryTest.kt b/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistryTest.kt index cf46387..6ed0dc5 100644 --- a/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistryTest.kt +++ b/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/renderer/TemplateRegistryTest.kt
@@ -230,6 +230,16 @@ } @Test + fun registerOverride_blankWidgetName_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException::class.java) { + registry.registerOverride("", TestTemplate::class.java, renderer("custom"), home) + } + assertThrows(IllegalArgumentException::class.java) { + registry.registerOverride(" ", TestTemplate::class.java, renderer("custom"), home) + } + } + + @Test fun removeOverride_restoresDefaultOnlyForTargetWidgetAndSurface() { registry.registerDefault(TestTemplate::class.java, renderer("default")) registry.registerOverride("custom", TestTemplate::class.java, renderer("custom-lock"), lock)
diff --git a/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/selection/SizeTiersTest.kt b/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/selection/SizeTiersTest.kt index 2e52ac7..97f4cba 100644 --- a/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/selection/SizeTiersTest.kt +++ b/glance/adaptive/adaptive-core/src/test/kotlin/androidx/glance/adaptive/core/selection/SizeTiersTest.kt
@@ -17,6 +17,7 @@ package androidx.glance.adaptive.core.selection import com.google.common.truth.Truth.assertThat +import org.junit.Assert.assertThrows import org.junit.Test class SizeTiersTest { @@ -80,6 +81,20 @@ } @Test + fun dimensions_zeroValues_areAllowed() { + val zero = Dimensions(0, 0) + + assertThat(zero.widthDp).isEqualTo(0) + assertThat(zero.heightDp).isEqualTo(0) + } + + @Test + fun dimensions_negativeWidthOrHeight_throwsIllegalArgumentException() { + assertThrows(IllegalArgumentException::class.java) { Dimensions(-1, 100) } + assertThrows(IllegalArgumentException::class.java) { Dimensions(100, -1) } + } + + @Test fun widthTier_fromDp_baselineResolution() { // The design's columns: 88, 176, 264, 352 dp, split at the midpoints between them. assertThat(WidthTier.fromDp(88)).isEqualTo(WidthTier.W1)
diff --git a/libraryversions.toml b/libraryversions.toml index fa813d3..795f207 100644 --- a/libraryversions.toml +++ b/libraryversions.toml
@@ -215,7 +215,7 @@ NAVIGATION = "2.11.0-alpha01" -NAVIGATION3 = "1.3.0-alpha05" +NAVIGATION3 = "1.3.0-alpha06" NAVIGATIONEVENT = "1.3.0-alpha01"
diff --git a/pdf/pdf-document-service/src/main/kotlin/androidx/pdf/utils/SdkUtils.kt b/pdf/pdf-document-service/src/main/kotlin/androidx/pdf/utils/SdkUtils.kt index 09621b6..78ff169 100644 --- a/pdf/pdf-document-service/src/main/kotlin/androidx/pdf/utils/SdkUtils.kt +++ b/pdf/pdf-document-service/src/main/kotlin/androidx/pdf/utils/SdkUtils.kt
@@ -37,4 +37,4 @@ internal fun isSignatureFeatureAvailable(): Boolean = isRequiredSdkExtensionAvailable(18) -internal fun isRgb565RenderingAvailable(): Boolean = isRequiredSdkExtensionAvailable(24) +internal fun isRgb565RenderingAvailable(): Boolean = isRequiredSdkExtensionAvailable(25)
diff --git a/settings.gradle b/settings.gradle index 0807edb..c5ce96d 100644 --- a/settings.gradle +++ b/settings.gradle
@@ -1284,6 +1284,7 @@ includeProject(":wear:watchfacepush:watchfacepush", [BuildType.MAIN, BuildType.WEAR]) includeProject(":web:web", [BuildType.MAIN]) includeProject(":web:web-compose", [BuildType.COMPOSE]) +includeProject(":web:web-compose:web-compose-samples", "web/web-compose/samples", [BuildType.COMPOSE]) includeProject(":web:integration-tests:testapp", [BuildType.COMPOSE]) includeProject(":web:integration-tests:macrobenchmark", [BuildType.COMPOSE]) includeProject(":webgpu:webgpu", [BuildType.MAIN])
diff --git a/tip-of-tree-or-alpha-dependency-exemptions.toml b/tip-of-tree-or-alpha-dependency-exemptions.toml index 7d84b7e..10505dc 100644 --- a/tip-of-tree-or-alpha-dependency-exemptions.toml +++ b/tip-of-tree-or-alpha-dependency-exemptions.toml
@@ -494,19 +494,19 @@ library = "androidx.wear.compose.remote:remote-material3" dependsOn = "androidx.compose.remote.foundation:foundation" validThroughLibraryVersion = "1.0.0-beta01" -reason = "b/TODO - <reason>" +reason = "b/567564599 - Remote Compose Foundation has no beta release yet and remote-material3 is developed and released alongside its evolving alpha APIs." [[exemption]] library = "androidx.wear.compose.remote:remote-material3" dependsOn = "androidx.compose.remote:remote-creation" validThroughLibraryVersion = "1.0.0-beta01" -reason = "b/TODO - <reason>" +reason = "b/567564599 - Remote Compose has no beta release yet and remote-material3 is developed and released alongside its evolving alpha APIs." [[exemption]] library = "androidx.wear.compose.remote:remote-material3" dependsOn = "androidx.compose.remote:remote-creation-compose" validThroughLibraryVersion = "1.0.0-beta01" -reason = "b/TODO - <reason>" +reason = "b/567564599 - Remote Compose has no beta release yet and remote-material3 is developed and released alongside its evolving alpha APIs." [[exemption]] library = "androidx.wear.tiles:tiles"
diff --git a/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategyTest.kt b/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategyTest.kt index e6b8f68..e5dbd04 100644 --- a/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategyTest.kt +++ b/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategyTest.kt
@@ -40,6 +40,7 @@ import androidx.wear.compose.foundation.lazy.layout.LazyLayoutItemAnimator import androidx.wear.compose.foundation.lazy.layout.LazyLayoutKeyIndexMap import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage import kotlin.coroutines.EmptyCoroutineContext import kotlin.math.roundToInt import kotlin.test.Test @@ -1581,9 +1582,7 @@ } @Test - fun initialCenterAnchor_nonZeroScrollOffsetInSteepTransitionArea_convergesAccurately() { - // Scales down in the top transition area steep enough that fixed-point iteration would - // oscillate; binary search should still converge to the exact centered offset. + fun initialCenterAnchor_nonZeroScrollOffsetInTopTransitionArea_usesUnscaledOffsetAndStaysStable() { val itemHeights = listOf(25, 25, 25, 76, 25, 25, 25) val transformedHeight: (Int, TransformingLazyColumnItemScrollProgress) -> Int = { height, progress -> @@ -1591,40 +1590,56 @@ (height * scale).roundToInt() } - val pass1 = - strategy.measure( - itemHeights = itemHeights, - transformedHeight = transformedHeight, - anchorItemIndex = 3, - anchorItemScrollOffset = 7, - lastMeasuredAnchorItemHeight = Int.MIN_VALUE, - ) - val pass1Item = pass1.visibleItems.first { it.index == 3 } - assertThat(pass1.anchorItemIndex).isEqualTo(3) - assertThat(pass1.anchorItemScrollOffset).isEqualTo(7) - assertThat(pass1Item.offset).isEqualTo(8) - assertThat(pass1Item.transformedHeight).isEqualTo(70) + for ((scrollOffset, expectedTransformedHeight) in listOf(7 to 61, 8 to 58)) { + val expectedOffset = screenHeight / 2 - 76 / 2 - scrollOffset + val pass1 = + strategy.measure( + itemHeights = itemHeights, + transformedHeight = transformedHeight, + anchorItemIndex = 3, + anchorItemScrollOffset = scrollOffset, + lastMeasuredAnchorItemHeight = Int.MIN_VALUE, + ) + val pass1Item = pass1.visibleItems.first { it.index == 3 } + assertWithMessage("scrollOffset=$scrollOffset").that(pass1.anchorItemIndex).isEqualTo(3) + assertWithMessage("scrollOffset=$scrollOffset") + .that(pass1.anchorItemScrollOffset) + .isEqualTo(scrollOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(pass1.lastMeasuredItemHeight) + .isEqualTo(76) + assertWithMessage("scrollOffset=$scrollOffset") + .that(pass1Item.offset) + .isEqualTo(expectedOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(pass1Item.transformedHeight) + .isEqualTo(expectedTransformedHeight) - val pass2 = - strategy.measure( - itemHeights = itemHeights, - transformedHeight = transformedHeight, - anchorItemKey = pass1.anchorItemKey, - anchorItemIndex = pass1.anchorItemIndex, - anchorItemScrollOffset = pass1.anchorItemScrollOffset, - lastMeasuredAnchorItemHeight = pass1.lastMeasuredItemHeight, - ) - val pass2Item = pass2.visibleItems.first { it.index == 3 } - assertThat(pass2.anchorItemIndex).isEqualTo(3) - assertThat(pass2.anchorItemScrollOffset).isEqualTo(7) - assertThat(pass2Item.offset).isEqualTo(pass1Item.offset) - assertThat(pass2Item.transformedHeight).isEqualTo(pass1Item.transformedHeight) + val pass2 = + strategy.measure( + itemHeights = itemHeights, + transformedHeight = transformedHeight, + anchorItemKey = pass1.anchorItemKey, + anchorItemIndex = pass1.anchorItemIndex, + anchorItemScrollOffset = pass1.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = pass1.lastMeasuredItemHeight, + ) + val pass2Item = pass2.visibleItems.first { it.index == 3 } + assertWithMessage("scrollOffset=$scrollOffset").that(pass2.anchorItemIndex).isEqualTo(3) + assertWithMessage("scrollOffset=$scrollOffset") + .that(pass2.anchorItemScrollOffset) + .isEqualTo(scrollOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(pass2Item.offset) + .isEqualTo(pass1Item.offset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(pass2Item.transformedHeight) + .isEqualTo(pass1Item.transformedHeight) + } } @Test - fun initialCenterAnchor_negativeScrollOffsetInBottomTransitionArea_convergesAccurately() { - // Scales down in the bottom transition area so both initial probes sit above the target - // center, exercising binary search above the scaled probe. + fun initialCenterAnchor_negativeScrollOffsetInBottomTransitionArea_usesUnscaledOffsetAndStaysStable() { val itemHeights = listOf(25, 25, 25, 80, 25, 25, 25) val transformedHeight: (Int, TransformingLazyColumnItemScrollProgress) -> Int = { height, progress -> @@ -1644,8 +1659,9 @@ val pass1Item = pass1.visibleItems.first { it.index == 3 } assertThat(pass1.anchorItemIndex).isEqualTo(3) assertThat(pass1.anchorItemScrollOffset).isEqualTo(-5) - assertThat(pass1Item.offset).isEqualTo(31) - assertThat(pass1Item.transformedHeight).isEqualTo(49) + assertThat(pass1.lastMeasuredItemHeight).isEqualTo(80) + assertThat(pass1Item.offset).isEqualTo(15) + assertThat(pass1Item.transformedHeight).isEqualTo(65) val pass2 = strategy.measure( @@ -1664,9 +1680,7 @@ } @Test - fun initialCenterAnchor_noExactCenterMatch_restoresClosestOffsetAndStaysStable() { - // Steep scaling skips an exact center match for scrollOffset = 8, exercising the - // post-loop restoration to the closest probed offset. + fun anchorItemScrollOffset_scrollingIntoTransitionArea_changesLinearlyAndRestoresAccurately() { val itemHeights = listOf(25, 25, 25, 76, 25, 25, 25) val transformedHeight: (Int, TransformingLazyColumnItemScrollProgress) -> Int = { height, progress -> @@ -1674,34 +1688,94 @@ (height * scale).roundToInt() } - val pass1 = + val initial = strategy.measure( itemHeights = itemHeights, transformedHeight = transformedHeight, anchorItemIndex = 3, - anchorItemScrollOffset = 8, + anchorItemScrollOffset = 0, lastMeasuredAnchorItemHeight = Int.MIN_VALUE, ) - val pass1Item = pass1.visibleItems.first { it.index == 3 } - assertThat(pass1.anchorItemIndex).isEqualTo(3) - assertThat(pass1.anchorItemScrollOffset).isEqualTo(7) - assertThat(pass1Item.offset).isEqualTo(8) - assertThat(pass1Item.transformedHeight).isEqualTo(70) + val initialItem = initial.visibleItems.first { it.index == 3 } + assertThat(initialItem.offset).isEqualTo(12) + assertThat(initialItem.transformedHeight).isEqualTo(76) - val pass2 = + // Scroll forward by 7px into the top transition area; on the subsequent remeasure pass + // transformedHeight shrinks from 76 to 61 while anchorItemScrollOffset remains linear at 7. + val scrolled = strategy.measure( itemHeights = itemHeights, transformedHeight = transformedHeight, - anchorItemKey = pass1.anchorItemKey, - anchorItemIndex = pass1.anchorItemIndex, - anchorItemScrollOffset = pass1.anchorItemScrollOffset, - lastMeasuredAnchorItemHeight = pass1.lastMeasuredItemHeight, + anchorItemKey = initial.anchorItemKey, + anchorItemIndex = initial.anchorItemIndex, + anchorItemScrollOffset = initial.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = initial.lastMeasuredItemHeight, + scrollToBeConsumed = -7f, ) - val pass2Item = pass2.visibleItems.first { it.index == 3 } - assertThat(pass2.anchorItemIndex).isEqualTo(3) - assertThat(pass2.anchorItemScrollOffset).isEqualTo(pass1.anchorItemScrollOffset) - assertThat(pass2Item.offset).isEqualTo(pass1Item.offset) - assertThat(pass2Item.transformedHeight).isEqualTo(pass1Item.transformedHeight) + val scrolledItem = scrolled.visibleItems.first { it.index == 3 } + assertThat(scrolled.anchorItemIndex).isEqualTo(3) + assertThat(scrolled.anchorItemScrollOffset).isEqualTo(7) + assertThat(scrolledItem.offset).isEqualTo(5) + + val settled = + strategy.measure( + itemHeights = itemHeights, + transformedHeight = transformedHeight, + anchorItemKey = scrolled.anchorItemKey, + anchorItemIndex = scrolled.anchorItemIndex, + anchorItemScrollOffset = scrolled.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = scrolled.lastMeasuredItemHeight, + ) + val settledItem = settled.visibleItems.first { it.index == 3 } + assertThat(settled.anchorItemIndex).isEqualTo(3) + assertThat(settled.anchorItemScrollOffset).isEqualTo(7) + assertThat(settledItem.offset).isEqualTo(5) + assertThat(settledItem.transformedHeight).isEqualTo(61) + + // Scroll forward another 2px while the anchor is already scaled (61px); offset should move + // to 3 and anchorItemScrollOffset should advance linearly to 9 without drift. + val scrolledAgain = + strategy.measure( + itemHeights = itemHeights, + transformedHeight = transformedHeight, + anchorItemKey = settled.anchorItemKey, + anchorItemIndex = settled.anchorItemIndex, + anchorItemScrollOffset = settled.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = settled.lastMeasuredItemHeight, + scrollToBeConsumed = -2f, + ) + val scrolledAgainItem = scrolledAgain.visibleItems.first { it.index == 3 } + assertThat(scrolledAgain.anchorItemIndex).isEqualTo(3) + assertThat(scrolledAgain.anchorItemScrollOffset).isEqualTo(9) + assertThat(scrolledAgainItem.offset).isEqualTo(3) + + val settledAgain = + strategy.measure( + itemHeights = itemHeights, + transformedHeight = transformedHeight, + anchorItemKey = scrolledAgain.anchorItemKey, + anchorItemIndex = scrolledAgain.anchorItemIndex, + anchorItemScrollOffset = scrolledAgain.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = scrolledAgain.lastMeasuredItemHeight, + ) + val settledAgainItem = settledAgain.visibleItems.first { it.index == 3 } + assertThat(settledAgain.anchorItemIndex).isEqualTo(3) + assertThat(settledAgain.anchorItemScrollOffset).isEqualTo(9) + assertThat(settledAgainItem.offset).isEqualTo(3) + assertThat(settledAgainItem.transformedHeight).isEqualTo(55) + + // Restoring from saved (anchorItemIndex, anchorItemScrollOffset) reproduces exact offset. + val restored = + strategy.measure( + itemHeights = itemHeights, + transformedHeight = transformedHeight, + anchorItemIndex = settledAgain.anchorItemIndex, + anchorItemScrollOffset = settledAgain.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = Int.MIN_VALUE, + ) + val restoredItem = restored.visibleItems.first { it.index == 3 } + assertThat(restoredItem.offset).isEqualTo(settledAgainItem.offset) + assertThat(restoredItem.transformedHeight).isEqualTo(settledAgainItem.transformedHeight) } @Test @@ -1737,7 +1811,7 @@ } @Test - fun initialCenterAnchor_expandingTransformation_convergesAccurately() { + fun initialCenterAnchor_expandingTransformation_usesUnscaledOffsetAndStaysStable() { val itemHeights = listOf(25, 25, 25, 50, 25, 25, 25) val transformedHeight: (Int, TransformingLazyColumnItemScrollProgress) -> Int = { height, progress -> @@ -1756,8 +1830,9 @@ val pass1Item = pass1.visibleItems.first { it.index == 3 } assertThat(pass1.anchorItemIndex).isEqualTo(3) assertThat(pass1.anchorItemScrollOffset).isEqualTo(0) - assertThat(pass1Item.offset).isEqualTo(19) - assertThat(pass1Item.transformedHeight).isEqualTo(62) + assertThat(pass1.lastMeasuredItemHeight).isEqualTo(50) + assertThat(pass1Item.offset).isEqualTo(25) + assertThat(pass1Item.transformedHeight).isEqualTo(60) val pass2 = strategy.measure( @@ -1775,6 +1850,99 @@ assertThat(pass2Item.transformedHeight).isEqualTo(pass1Item.transformedHeight) } + @Test + fun scaledAnchor_dynamicMeasuredHeightChange_preservesTopOffset() { + val transformedHeight: (Int, TransformingLazyColumnItemScrollProgress) -> Int = + { height, progress -> + val scale = 0.6f + 0.4f * (progress.topOffsetFraction / 0.1f).coerceIn(0f, 1f) + (height * scale).roundToInt() + } + + val pass1 = + strategy.measure( + itemHeights = listOf(25, 25, 25, 76, 25, 25, 25), + transformedHeight = transformedHeight, + anchorItemIndex = 3, + anchorItemScrollOffset = 7, + lastMeasuredAnchorItemHeight = Int.MIN_VALUE, + ) + val pass1Item = pass1.visibleItems.first { it.index == 3 } + assertThat(pass1Item.offset).isEqualTo(5) + assertThat(pass1Item.transformedHeight).isEqualTo(61) + assertThat(pass1.lastMeasuredItemHeight).isEqualTo(76) + + // Anchor measuredHeight grows from 76 to 90; top offset stays pinned at 5 while + // anchorItemScrollOffset and lastMeasuredItemHeight update to the new measuredHeight. + val pass2 = + strategy.measure( + itemHeights = listOf(25, 25, 25, 90, 25, 25, 25), + transformedHeight = transformedHeight, + anchorItemKey = pass1.anchorItemKey, + anchorItemIndex = pass1.anchorItemIndex, + anchorItemScrollOffset = pass1.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = pass1.lastMeasuredItemHeight, + ) + val pass2Item = pass2.visibleItems.first { it.index == 3 } + assertThat(pass2.anchorItemIndex).isEqualTo(3) + assertThat(pass2Item.offset).isEqualTo(5) + assertThat(pass2Item.transformedHeight).isEqualTo(72) + assertThat(pass2.anchorItemScrollOffset).isEqualTo(screenHeight / 2 - 90 / 2 - 5) + assertThat(pass2.lastMeasuredItemHeight).isEqualTo(90) + } + + @Test + fun zeroHeightAnchor_expandsOnRemeasure_preservesTopOffset() { + val spacing = Arrangement.spacedBy(12.dp) + val pass1 = + strategy.measure( + itemHeights = listOf(40, 40, 0, 40, 40), + verticalArrangement = spacing, + anchorItemIndex = 2, + anchorItemScrollOffset = 4, + lastMeasuredAnchorItemHeight = Int.MIN_VALUE, + ) + val pass1Item = pass1.visibleItems.first { it.index == 2 } + assertThat(pass1.anchorItemIndex).isEqualTo(2) + assertThat(pass1.anchorItemScrollOffset).isEqualTo(4) + assertThat(pass1.lastMeasuredItemHeight).isEqualTo(0) + assertThat(pass1Item.offset).isEqualTo(46) + + // Expanding from 0 to 40 must reuse lastMeasuredAnchorItemHeight == 0 (not treat 0 as + // unmeasured), preserving the top offset at 46 instead of jumping upward by 20px. + val pass2 = + strategy.measure( + itemHeights = listOf(40, 40, 40, 40, 40), + verticalArrangement = spacing, + anchorItemKey = pass1.anchorItemKey, + anchorItemIndex = pass1.anchorItemIndex, + anchorItemScrollOffset = pass1.anchorItemScrollOffset, + lastMeasuredAnchorItemHeight = pass1.lastMeasuredItemHeight, + ) + val pass2Item = pass2.visibleItems.first { it.index == 2 } + assertThat(pass2.anchorItemIndex).isEqualTo(2) + assertThat(pass2Item.offset).isEqualTo(46) + assertThat(pass2.anchorItemScrollOffset).isEqualTo(screenHeight / 2 - 40 / 2 - 46) + assertThat(pass2.lastMeasuredItemHeight).isEqualTo(40) + } + + @Test + fun zeroHeightAnchor_deletedWithPositiveScrollOffset_coercesReplacementOffsetToNonNegative() { + // Simulates deleting a measuredHeight == 0 anchor whose scrollOffset = 60 gave top + // offset = 50 - 0/2 - 60 = -10. Because lastMeasuredAnchorItemHeight == 0 is treated as + // measured, the replacement item inherits offset.coerceAtLeast(0) == 0. + val result = + strategy.measure( + itemHeights = listOf(25, 25, 40, 40, 40), + keys = listOf("a", "b", "c", "d", "e"), + anchorItemKey = "deleted", + anchorItemIndex = 2, + anchorItemScrollOffset = 60, + lastMeasuredAnchorItemHeight = 0, + ) + val replacementItem = result.visibleItems.first { it.index == 2 } + assertThat(replacementItem.offset).isEqualTo(0) + } + private val mockGraphicContext = object : GraphicsContext { override fun createGraphicsLayer(): GraphicsLayer {
diff --git a/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnScrollTest.kt b/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnScrollTest.kt index 6bc72fbe..cd52467 100644 --- a/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnScrollTest.kt +++ b/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnScrollTest.kt
@@ -29,6 +29,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage import java.util.concurrent.atomic.AtomicLong import kotlin.math.abs import kotlin.math.roundToInt @@ -126,6 +127,167 @@ } @Test + fun scrollToItem_withTransformedHeightAndScrollOffset_usesUnscaledCenterAndStaysStable() { + val containerSizePx = 300 + val viewportCenterPx = containerSizePx / 2 + val itemHeightPx = 160 + val targetIndex = 8 + rule.setContent { + state = rememberTransformingLazyColumnState() + scope = rememberCoroutineScope() + with(rule.density) { + TransformingLazyColumn( + Modifier.height(containerSizePx.toDp()).testTag(lazyListTag), + state, + verticalArrangement = Arrangement.spacedBy(0.toDp()), + ) { + items(itemsCount) { + Spacer( + modifier = + Modifier.height(itemHeightPx.toDp()).transformedHeight { + height, + progress -> + val centerFraction = + (progress.topOffsetFraction + + progress.bottomOffsetFraction) / 2f + val edgeDist = + (abs(centerFraction - 0.5f) - 0.05f).coerceAtLeast(0f) + val scale = (1f - edgeDist * 2f).coerceIn(0.5f, 1f) + (height * scale).roundToInt().coerceAtLeast(1) + } + ) + } + } + } + } + + for (scrollOffset in listOf(30, -30)) { + val expectedOffset = viewportCenterPx - itemHeightPx / 2 - scrollOffset + runBlocking(Dispatchers.Main) { state.scrollToItem(targetIndex, scrollOffset) } + + var settledTransformedHeight = 0 + rule.runOnIdle { + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.isScrollInProgress) + .isFalse() + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemIndex) + .isEqualTo(targetIndex) + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemScrollOffset) + .isEqualTo(scrollOffset) + val targetItem = state.layoutInfo.visibleItems.first { it.index == targetIndex } + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.offset) + .isEqualTo(expectedOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.transformedHeight) + .isLessThan(itemHeightPx) + settledTransformedHeight = targetItem.transformedHeight + checkNotNull(state.remeasurement).forceRemeasure() + } + + rule.runOnIdle { + val targetItem = state.layoutInfo.visibleItems.first { it.index == targetIndex } + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemIndex) + .isEqualTo(targetIndex) + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemScrollOffset) + .isEqualTo(scrollOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.offset) + .isEqualTo(expectedOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.transformedHeight) + .isEqualTo(settledTransformedHeight) + } + } + } + + @Test + fun requestScrollToItem_withTransformedHeightAndScrollOffset_usesUnscaledCenterAndStaysStable() { + val containerSizePx = 300 + val viewportCenterPx = containerSizePx / 2 + val itemHeightPx = 160 + val targetIndex = 8 + rule.setContent { + state = rememberTransformingLazyColumnState() + scope = rememberCoroutineScope() + with(rule.density) { + TransformingLazyColumn( + Modifier.height(containerSizePx.toDp()).testTag(lazyListTag), + state, + verticalArrangement = Arrangement.spacedBy(0.toDp()), + ) { + items(itemsCount) { + Spacer( + modifier = + Modifier.height(itemHeightPx.toDp()).transformedHeight { + height, + progress -> + val centerFraction = + (progress.topOffsetFraction + + progress.bottomOffsetFraction) / 2f + val edgeDist = + (abs(centerFraction - 0.5f) - 0.05f).coerceAtLeast(0f) + val scale = (1f - edgeDist * 2f).coerceIn(0.5f, 1f) + (height * scale).roundToInt().coerceAtLeast(1) + } + ) + } + } + } + } + + for (scrollOffset in listOf(30, -30)) { + val expectedOffset = viewportCenterPx - itemHeightPx / 2 - scrollOffset + rule.runOnIdle { + state.requestScrollToItem(targetIndex, scrollOffset) + checkNotNull(state.remeasurement).forceRemeasure() + } + + var settledTransformedHeight = 0 + rule.runOnIdle { + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.isScrollInProgress) + .isFalse() + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemIndex) + .isEqualTo(targetIndex) + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemScrollOffset) + .isEqualTo(scrollOffset) + val targetItem = state.layoutInfo.visibleItems.first { it.index == targetIndex } + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.offset) + .isEqualTo(expectedOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.transformedHeight) + .isLessThan(itemHeightPx) + settledTransformedHeight = targetItem.transformedHeight + checkNotNull(state.remeasurement).forceRemeasure() + } + + rule.runOnIdle { + val targetItem = state.layoutInfo.visibleItems.first { it.index == targetIndex } + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemIndex) + .isEqualTo(targetIndex) + assertWithMessage("scrollOffset=$scrollOffset") + .that(state.anchorItemScrollOffset) + .isEqualTo(scrollOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.offset) + .isEqualTo(expectedOffset) + assertWithMessage("scrollOffset=$scrollOffset") + .that(targetItem.transformedHeight) + .isEqualTo(settledTransformedHeight) + } + } + } + + @Test fun animateScrollToItem_anchorItemWithOffset_scrollsInCorrectDirectionWithoutJump() { val recordedOffsets = mutableListOf<Int>() testScroll( @@ -259,7 +421,7 @@ AutoTestFrameClock { state.layoutInfo.visibleItems .firstOrNull { it.index == targetIndex } - ?.let { targetCenters.add(it.offset + it.transformedHeight / 2) } + ?.let { targetCenters.add(it.offset + it.measuredHeight / 2) } } ) { state.animateScrollToItem(targetIndex, targetScrollOffset) @@ -272,7 +434,7 @@ val targetItem = state.layoutInfo.visibleItems.first { it.index == targetIndex } assertThat(targetItem.transformedHeight).isLessThan(itemSizePx) assertThat(targetItem.offset) - .isEqualTo(viewportCenterPx - targetItem.transformedHeight / 2 - targetScrollOffset) + .isEqualTo(viewportCenterPx - itemSizePx / 2 - targetScrollOffset) } }
diff --git a/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnStateTest.kt b/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnStateTest.kt index 5b14583..8cd92a128 100644 --- a/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnStateTest.kt +++ b/wear/compose/compose-foundation/src/androidTest/kotlin/androidx/wear/compose/foundation/lazy/TransformingLazyColumnStateTest.kt
@@ -31,6 +31,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo +import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.Dp @@ -39,6 +40,7 @@ import androidx.test.filters.MediumTest import androidx.wear.compose.foundation.lazy.TransformingLazyColumnState.Companion.OffsetToTriggerInitialPin import com.google.common.truth.Truth.assertThat +import kotlin.math.abs import kotlin.math.roundToInt import kotlin.test.Test import kotlinx.coroutines.CoroutineScope @@ -399,8 +401,7 @@ assertThat(tallItem.offset).isEqualTo(expectedTopPx) assertThat(tallItem.transformedHeight).isEqualTo(tallItemHeightPx) } - // Remeasure to exercise restoring the anchor from its top offset and last transformed - // height. + // Remeasure to exercise restoring the anchor from its top offset and last measured height. rule.runOnIdle { checkNotNull(state.remeasurement).forceRemeasure() } rule.runOnIdle { @@ -415,6 +416,73 @@ .assertTopPositionInRootIsEqualTo(with(rule.density) { expectedTopPx.toDp() }) } + @Test + fun stateRestoration_withTransformedHeightInTransitionArea_restoresExactLayout() { + val restorationTester = StateRestorationTester(rule) + val containerHeightPx = 300 + val itemHeightPx = 160 + val targetIndex = 8 + val targetScrollOffset = 30 + lateinit var state: TransformingLazyColumnState + lateinit var scope: CoroutineScope + + restorationTester.setContent { + state = rememberTransformingLazyColumnState() + scope = rememberCoroutineScope() + with(rule.density) { + TransformingLazyColumn( + modifier = Modifier.requiredHeight(containerHeightPx.toDp()), + state = state, + verticalArrangement = Arrangement.spacedBy(0.dp), + ) { + items(itemsCount) { + Spacer( + modifier = + Modifier.requiredHeight(itemHeightPx.toDp()).transformedHeight { + height, + progress -> + val centerFraction = + (progress.topOffsetFraction + + progress.bottomOffsetFraction) / 2f + val edgeDist = + (abs(centerFraction - 0.5f) - 0.05f).coerceAtLeast(0f) + val scale = (1f - edgeDist * 2f).coerceIn(0.5f, 1f) + (height * scale).roundToInt().coerceAtLeast(1) + } + ) + } + } + } + } + + rule.runOnIdle { scope.launch { state.scrollToItem(targetIndex, targetScrollOffset) } } + + var savedAnchorIndex = -1 + var savedAnchorScrollOffset = Int.MIN_VALUE + var savedItemOffset = Int.MIN_VALUE + var savedTransformedHeight = Int.MIN_VALUE + rule.runOnIdle { + val item = state.layoutInfo.visibleItems.first { it.index == targetIndex } + assertThat(state.anchorItemIndex).isEqualTo(targetIndex) + assertThat(state.anchorItemScrollOffset).isEqualTo(targetScrollOffset) + assertThat(item.transformedHeight).isLessThan(itemHeightPx) + savedAnchorIndex = state.anchorItemIndex + savedAnchorScrollOffset = state.anchorItemScrollOffset + savedItemOffset = item.offset + savedTransformedHeight = item.transformedHeight + } + + restorationTester.emulateSavedInstanceStateRestore() + + rule.runOnIdle { + val restoredItem = state.layoutInfo.visibleItems.first { it.index == targetIndex } + assertThat(state.anchorItemIndex).isEqualTo(savedAnchorIndex) + assertThat(state.anchorItemScrollOffset).isEqualTo(savedAnchorScrollOffset) + assertThat(restoredItem.offset).isEqualTo(savedItemOffset) + assertThat(restoredItem.transformedHeight).isEqualTo(savedTransformedHeight) + } + } + private fun setupLazyColumn(itemsCount: Int, itemsPerPage: Int): TransformingLazyColumnState { lateinit var state: TransformingLazyColumnState
diff --git a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategy.kt b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategy.kt index 7b11464..0985edb 100644 --- a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategy.kt +++ b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnContentPaddingMeasurementStrategy.kt
@@ -199,6 +199,9 @@ } } + // Anchor selection intentionally uses visual (transformedHeight) bounds to pick the item + // covering or nearest to the viewport center, whereas anchorItemScrollOffset is reported + // relative to the item's untransformed (measuredHeight) center. fun anchorItem(): TransformingLazyColumnMeasuredItem? = with(visibleItems) { if (isEmpty()) return null @@ -332,7 +335,7 @@ } // Restore the position of anchor item from the previous measurement. val defaultPreviousAnchorItem = - if (lastMeasuredAnchorItemHeight > 0) { + if (lastMeasuredAnchorItemHeight >= 0) { val offset = containerConstraints.maxHeight / 2 - lastMeasuredAnchorItemHeight / 2 - @@ -350,11 +353,13 @@ maxHeight = containerConstraints.maxHeight, ) } else { - resolveMeasuredItemForFixedCenter( - index = anchorItemIndex, - scrollOffset = anchorItemScrollOffset, + // Integer division centerOffset - measuredHeight / 2 is symmetric with + // maxHeight / 2 - measuredHeight / 2 - offset when reporting + // anchorItemScrollOffset, avoiding 1px drift for odd heights. + measuredItemProvider.centeredMeasuredItem( + anchorItemIndex, + centerOffset = containerConstraints.maxHeight / 2 - anchorItemScrollOffset, maxHeight = containerConstraints.maxHeight, - measuredItemProvider = measuredItemProvider, ) } @@ -652,12 +657,12 @@ anchorItemIndex = anchorItem.index, anchorItemScrollOffset = anchorItem.let { - containerConstraints.maxHeight / 2 - it.transformedHeight / 2 - it.offset + containerConstraints.maxHeight / 2 - it.measuredHeight / 2 - it.offset }, visibleItems = actuallyVisibleItems, positionedItems = positionedItems, totalItemsCount = itemsCount, - lastMeasuredItemHeight = anchorItem.transformedHeight, + lastMeasuredItemHeight = anchorItem.measuredHeight, canScrollForward = canScrollForward, canScrollBackward = canScrollBackward, coroutineScope = coroutineScope, @@ -804,98 +809,9 @@ return item } - /** - * Measures the item at [index] so that its center is [scrollOffset] above the viewport center. - * - * The item is measured downward, with a scroll progress computed from its actual top offset. - * This matches how the following measure passes restore the anchor item from its top offset and - * last transformed height, so the position doesn't drift on the next remeasure. - */ - private fun resolveMeasuredItemForFixedCenter( - index: Int, - scrollOffset: Int, - maxHeight: Int, - measuredItemProvider: MeasuredItemProvider, - ): TransformingLazyColumnMeasuredItem { - val targetCenter = maxHeight / 2 - scrollOffset - // Placeholder offset used only to obtain measuredHeight; transformedHeight isn't read here. - val item = - measuredItemProvider.downwardMeasuredItem( - index = index, - offset = targetCenter, - maxHeight = maxHeight, - ) - - // The item isn't scaled when centered, which is the most common case. - val unscaledTop = targetCenter - item.measuredHeight / 2 - item.moveBelow(unscaledTop) - val heightAtUnscaledTop = item.transformedHeight - val unscaledDiff = unscaledTop + heightAtUnscaledTop / 2 - targetCenter - if (unscaledDiff == 0) return item - - // The item has the same transformed height around the target, e.g. when it's offscreen. - val scaledTop = targetCenter - heightAtUnscaledTop / 2 - item.moveBelow(scaledTop) - val heightAtScaledTop = item.transformedHeight - val scaledDiff = scaledTop + heightAtScaledTop / 2 - targetCenter - if (scaledDiff == 0) return item - - var bestTop = unscaledTop - var minDiff = abs(unscaledDiff) - val absScaledDiff = abs(scaledDiff) - if (absScaledDiff < minDiff) { - minDiff = absScaledDiff - bestTop = scaledTop - } - - // Inside a transition area, iterating on the transformed height can oscillate when the - // height changes by more than 2px per px of offset. Binary search between offsets where - // the item center is above and below the target instead. - var lowTop: Int - var highTop: Int - if (unscaledDiff < 0) { - lowTop = if (scaledDiff > 0) unscaledTop + 1 else scaledTop + 1 - highTop = if (scaledDiff > 0) scaledTop - 1 else targetCenter - } else if (scaledDiff < 0) { - lowTop = scaledTop + 1 - highTop = unscaledTop - 1 - } else { - // Brackets the target when the transformation scales up by at most 2x; otherwise falls - // back to bestTop. - lowTop = targetCenter - heightAtScaledTop - highTop = scaledTop - 1 - } - - var repetitions = 0 - while (lowTop <= highTop && repetitions < CENTER_OFFSET_RESOLVE_REPETITIONS) { - val candidateTop = lowTop + (highTop - lowTop) / 2 - item.moveBelow(candidateTop) - val diff = candidateTop + item.transformedHeight / 2 - targetCenter - val absDiff = abs(diff) - if (absDiff < minDiff) { - minDiff = absDiff - bestTop = candidateTop - } - if (diff == 0) break - - if (diff > 0) { - highTop = candidateTop - 1 - } else { - lowTop = candidateTop + 1 - } - repetitions++ - } - // Ensure the mutated item settles at the position that yielded the minimal difference. - if (item.offset != bestTop) { - item.moveBelow(bestTop) - } - return item - } - private companion object { const val GRADIENT_DESCENT_REPETITIONS = 4 const val OFFSET_RESOLVE_REPETITIONS = 10 - const val CENTER_OFFSET_RESOLVE_REPETITIONS = 32 } }
diff --git a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasureResult.kt b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasureResult.kt index eb5ee99..3c22218 100644 --- a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasureResult.kt +++ b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasureResult.kt
@@ -35,14 +35,16 @@ /** The index of the item that should be considered as an anchor during scrolling. */ val anchorItemIndex: Int, /** - * The offset of the anchor item to the viewport center. + * The offset of the anchor item's untransformed (measured) center to the viewport center. * - * A positive value indicates that the anchor item's center-line is above the viewport - * center-line, a negative value indicates that the anchor item's center-line is below the - * viewport center-line. + * A positive value indicates that the anchor item's untransformed center-line is above the + * viewport center-line, a negative value indicates that the anchor item's untransformed + * center-line is below the viewport center-line. */ val anchorItemScrollOffset: Int, - /** Last known height for the anchor item or negative number if it hasn't been measured. */ + /** + * Last known measured height for the anchor item or negative number if it hasn't been measured. + */ val lastMeasuredItemHeight: Int, /** Scope for animations. */ val coroutineScope: CoroutineScope,
diff --git a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasuredItem.kt b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasuredItem.kt index 52ccefc..c35be2d 100644 --- a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasuredItem.kt +++ b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasuredItem.kt
@@ -260,14 +260,4 @@ } } } - - fun pinToCenter() { - measureScrollProgress = - downwardMeasuredItemScrollProgress( - containerConstraints.maxHeight / 2 - measuredHeight / 2, - measuredHeight, - containerConstraints.maxHeight, - ) - offset = containerConstraints.maxHeight / 2 - transformedHeight / 2 - } }
diff --git a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasurementStrategy.kt b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasurementStrategy.kt index dced26c..ce3c445 100644 --- a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasurementStrategy.kt +++ b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnMeasurementStrategy.kt
@@ -43,9 +43,11 @@ * @param anchorItemIndex The index of the anchor item. Anchor item is a visible item used to * position the rest of the items before and after it. Should be from 0 (inclusive) to * [itemsCount] (exclusive). - * @param anchorItemScrollOffset The scroll offset of the anchor item. Anchor item is a visible - * item used to position the rest of the items before and after it. - * @param lastMeasuredAnchorItemHeight Last measured height from the previous measurement. + * @param anchorItemScrollOffset The scroll offset of the anchor item's untransformed (measured) + * center relative to the viewport center. Anchor item is a visible item used to position the + * rest of the items before and after it. + * @param lastMeasuredAnchorItemHeight Last measured (untransformed) height of the anchor item + * from the previous measurement, or a negative number if it has not been measured. * @param coroutineScope Scope for animations. * @param density The [Density] of the current layout. * @param scrollToBeConsumed The amount of scroll to be consumed. @@ -99,6 +101,20 @@ } .also { it.offset -= it.transformedHeight } +internal fun MeasuredItemProvider.centeredMeasuredItem( + index: Int, + centerOffset: Int, + maxHeight: Int, +): TransformingLazyColumnMeasuredItem = + measuredItem(index, centerOffset, MeasurementDirection.DOWNWARD) { height -> + downwardMeasuredItemScrollProgress( + offset = centerOffset - height / 2, + height = height, + containerHeight = maxHeight, + ) + } + .also { it.offset -= it.measuredHeight / 2 } + internal fun emptyMeasureResult( containerConstraints: Constraints, beforeContentPadding: Int,
diff --git a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnState.kt b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnState.kt index ab15345..0d6fe9c 100644 --- a/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnState.kt +++ b/wear/compose/compose-foundation/src/main/java/androidx/wear/compose/foundation/lazy/TransformingLazyColumnState.kt
@@ -57,12 +57,14 @@ * index is provided, the state will attempt to center this item in the viewport. If a negative * index is provided then the list will be initialized with the first item (index 0) pinned to the * start of the viewport, respecting any content padding. This is the default behavior. - * @param initialAnchorItemScrollOffset The offset to be applied to the anchor item. Defaults to 0. - * This offset is ONLY used when a non-negative `initialAnchorItemIndex` is provided (i.e., when - * the item is being centered). It is ignored if `initialAnchorItemIndex` is less than 0. The - * offset is used when placing the item in the center of the screen; a positive value scrolls the - * item towards the end of the list, and a negative value scrolls it towards the start. This - * correlates with [TransformingLazyColumnState.anchorItemScrollOffset]. + * @param initialAnchorItemScrollOffset The offset, in pixels, to be applied to the anchor item. + * Defaults to 0. This offset is ONLY used when a non-negative `initialAnchorItemIndex` is + * provided (i.e., when the item is being centered). It is ignored if `initialAnchorItemIndex` is + * less than 0. The offset is applied relative to the item's untransformed + * ([TransformingLazyColumnVisibleItemInfo.measuredHeight]) center when placing it in the center + * of the viewport; a positive value shifts the item towards the start of the list (scrolling the + * list forward), and a negative value shifts it towards the end. This correlates with + * [TransformingLazyColumnState.anchorItemScrollOffset]. */ @Composable public fun rememberTransformingLazyColumnState( @@ -81,12 +83,14 @@ * index is provided, the state will attempt to center this item in the viewport. If a negative * index is provided then the list will be initialized with the first item (index 0) pinned to the * start of the viewport, respecting any content padding. This is the default behavior. - * @param initialAnchorItemScrollOffset The offset to be applied to the anchor item. Defaults to 0. - * This offset is ONLY used when a non-negative `initialAnchorItemIndex` is provided (i.e., when - * the item is being centered). It is ignored if `initialAnchorItemIndex` is less than 0. The - * offset is used when placing the item in the center of the screen; a positive value scrolls the - * item towards the end of the list, and a negative value scrolls it towards the start. This - * correlates with [TransformingLazyColumnState.anchorItemScrollOffset]. + * @param initialAnchorItemScrollOffset The offset, in pixels, to be applied to the anchor item. + * Defaults to 0. This offset is ONLY used when a non-negative `initialAnchorItemIndex` is + * provided (i.e., when the item is being centered). It is ignored if `initialAnchorItemIndex` is + * less than 0. The offset is applied relative to the item's untransformed + * ([TransformingLazyColumnVisibleItemInfo.measuredHeight]) center when placing it in the center + * of the viewport; a positive value shifts the item towards the start of the list (scrolling the + * list forward), and a negative value shifts it towards the end. This correlates with + * [TransformingLazyColumnState.anchorItemScrollOffset]. */ @Stable public class TransformingLazyColumnState @@ -176,8 +180,13 @@ private set /** - * The scroll offset of the anchor item. Scrolling forward is positive - i.e., the amount that - * the item is offset backwards. + * The scroll offset, in pixels, of the anchor item's untransformed + * ([TransformingLazyColumnVisibleItemInfo.measuredHeight]) center relative to the viewport + * center. Scrolling forward is positive - i.e., the amount that the item is offset backwards. + * When height transformation changes the item's height + * ([TransformingLazyColumnVisibleItemInfo.transformedHeight] differs from + * [TransformingLazyColumnVisibleItemInfo.measuredHeight]), the item's visual center may differ + * from its untransformed center. * * Note that this property is observable and if you use it in the composable function it will be * recomposed on every scroll causing potential performance issues. @@ -333,8 +342,10 @@ * This operation happens instantly without animation. * * @param index The index of the item to scroll to. Must be non-negative. - * @param scrollOffset The offset between the center of the screen and item's center. Positive - * offset means the item will be scrolled up. + * @param scrollOffset The offset, in pixels, between the viewport center and the item's + * untransformed ([TransformingLazyColumnVisibleItemInfo.measuredHeight]) center. A positive + * offset shifts the item towards the start of the list (e.g., up when `reverseLayout` is + * `false`). */ public suspend fun scrollToItem( @androidx.annotation.IntRange(from = 0) index: Int, @@ -359,8 +370,10 @@ * Any scroll in progress will be cancelled. * * @param index the index to which to scroll. Must be non-negative. - * @param scrollOffset The offset between the center of the screen and item's center. Positive - * offset means the item will be scrolled up. + * @param scrollOffset The offset, in pixels, between the viewport center and the item's + * untransformed ([TransformingLazyColumnVisibleItemInfo.measuredHeight]) center. A positive + * offset shifts the item towards the start of the list (e.g., up when `reverseLayout` is + * `false`). */ public fun requestScrollToItem( @androidx.annotation.IntRange(from = 0) index: Int, @@ -384,8 +397,10 @@ * * @sample androidx.wear.compose.foundation.samples.TransformingLazyColumnScrollToItemSample * @param index the index to which to scroll. Must be non-negative. - * @param scrollOffset The offset between the center of the screen and item's center. Positive - * offset means the item will be scrolled up. + * @param scrollOffset The offset, in pixels, between the viewport center and the item's + * untransformed ([TransformingLazyColumnVisibleItemInfo.measuredHeight]) center. A positive + * offset shifts the item towards the start of the list (e.g., up when `reverseLayout` is + * `false`). */ public suspend fun animateScrollToItem( @androidx.annotation.IntRange(from = 0) index: Int,
diff --git a/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureIndicatorScreenshotTest.kt b/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureIndicatorScreenshotTest.kt index 4368e8a..fa4f943 100644 --- a/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureIndicatorScreenshotTest.kt +++ b/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureIndicatorScreenshotTest.kt
@@ -27,6 +27,7 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.hasTestTag @@ -42,6 +43,7 @@ import androidx.wear.compose.material3.internal.Icons import androidx.wear.compose.material3.internal.LocalWristOrientation import androidx.wear.compose.material3.internal.WristOrientation +import androidx.wear.compose.material3.onehandedgesture.DeviceInteractivity import androidx.wear.compose.material3.onehandedgesture.INDICATOR_ANIMATION_START_DELAY_MILLIS import androidx.wear.compose.material3.onehandedgesture.LocalOneHandedGestureManager import androidx.wear.compose.material3.onehandedgesture.OneHandedGestureAction @@ -59,6 +61,7 @@ import com.google.testing.junit.testparameterinjector.TestParameter import com.google.testing.junit.testparameterinjector.TestParameterInjector import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.launch import org.junit.Rule import org.junit.Test @@ -235,8 +238,17 @@ rule.setContentWithTheme { scope = rememberCoroutineScope() + val applicationContext = LocalContext.current.applicationContext val gestureManager = - remember(scope) { OneHandedGestureManagerImpl(scope, SdkGestureInputManagerMock()) } + remember(scope) { + OneHandedGestureManagerImpl( + applicationContext = applicationContext, + scope = scope, + gestureInputManager = SdkGestureInputManagerMock(), + // Don't depend on whether the device screen is on. + deviceInteractivity = AlwaysInteractiveDeviceInteractivity, + ) + } CompositionLocalProvider( LocalLayoutDirection provides layoutDirection, @@ -258,6 +270,12 @@ ) } + private object AlwaysInteractiveDeviceInteractivity : DeviceInteractivity { + override fun isInteractive(context: Context): Boolean = true + + override suspend fun awaitScreenOff(context: Context) = awaitCancellation() + } + private class SdkGestureInputManagerMock : SdkGestureInputManager { override fun isAvailable(context: Context): Boolean = true
diff --git a/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureTest.kt b/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureTest.kt index 089fb99..9e6d30d 100644 --- a/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureTest.kt +++ b/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/OneHandedGestureTest.kt
@@ -60,6 +60,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage @@ -96,6 +97,7 @@ import androidx.wear.compose.foundation.pager.rememberPagerState import androidx.wear.compose.material3.lazy.rememberTransformationSpec import androidx.wear.compose.material3.lazy.transformedHeight +import androidx.wear.compose.material3.onehandedgesture.DeviceInteractivity import androidx.wear.compose.material3.onehandedgesture.INDICATOR_ANIMATION_START_DELAY_MILLIS import androidx.wear.compose.material3.onehandedgesture.LocalOneHandedGestureEnabled import androidx.wear.compose.material3.onehandedgesture.LocalOneHandedGestureManager @@ -124,6 +126,8 @@ import kotlin.test.assertNotNull import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import org.hamcrest.Matchers.containsString import org.hamcrest.Matchers.startsWith @@ -1225,6 +1229,415 @@ rule.runOnIdle { assertEquals(2, indicatorShownCount) } } + /** + * Verifies that if the device enters ambient mode before the indicator delay elapses, the + * indicator is neither queried nor shown. + */ + @Test + fun ambient_mode_during_delay_skips_indicator() { + var gestureAvailableCount = 0 + val sdkGestureInputManager = SdkGestureInputManagerMock() + val deviceInteractivity = FakeDeviceInteractivity() + + rule.mainClock.autoAdvance = false + rule.setContentWithTheme { + MockSdkGestureInputManager( + sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) { + val gestureConfig = + rememberOneHandedGestureConfiguration(action = OneHandedGestureAction.Primary) + Box( + Modifier.size(50.dp).oneHandedGesture( + gestureConfiguration = gestureConfig, + onGestureLabel = "click", + onGestureAvailable = { gestureAvailableCount++ }, + ) {} + ) + } + } + rule.waitForIdle() + rule.mainClock.advanceTimeBy(OneHandedGestureDefaults.ShowIndicatorDelayMillis / 2) + + rule.runOnUiThread { deviceInteractivity.setInteractive(false) } + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(0, gestureAvailableCount) + assertEquals(0, sdkGestureInputManager.shouldShowIndicatorCount) + } + + rule.runOnUiThread { deviceInteractivity.setInteractive(true) } + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(0, gestureAvailableCount) + assertEquals(0, sdkGestureInputManager.shouldShowIndicatorCount) + } + } + + /** + * Verifies that with several gestures with different indicator delays, only the indicators + * whose delay elapses in ambient mode are skipped, and later ones are still shown once the + * device exits ambient mode. + */ + @Test + fun ambient_mode_during_delay_only_skips_gestures_whose_delay_elapsed() { + var primaryGestureAvailableCount = 0 + var dismissGestureAvailableCount = 0 + val sdkGestureInputManager = SdkGestureInputManagerMock() + val deviceInteractivity = FakeDeviceInteractivity() + + rule.mainClock.autoAdvance = false + rule.setContentWithTheme { + MockSdkGestureInputManager( + sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) { + val primaryGestureConfig = + rememberOneHandedGestureConfiguration(action = OneHandedGestureAction.Primary) + val dismissGestureConfig = + rememberOneHandedGestureConfiguration(action = OneHandedGestureAction.Dismiss) + Column { + Box( + Modifier.size(50.dp).oneHandedGesture( + gestureConfiguration = primaryGestureConfig, + onGestureLabel = "click", + showIndicatorDelayMillis = 1000L, + onGestureAvailable = { primaryGestureAvailableCount++ }, + ) {} + ) + Box( + Modifier.size(50.dp).oneHandedGesture( + gestureConfiguration = dismissGestureConfig, + onGestureLabel = "dismiss", + showIndicatorDelayMillis = 2000L, + onGestureAvailable = { dismissGestureAvailableCount++ }, + ) {} + ) + } + } + } + rule.waitForIdle() + rule.mainClock.advanceTimeBy(500L) + + // Enter ambient mode while the first (primary) delay elapses at 1000ms... + rule.runOnUiThread { deviceInteractivity.setInteractive(false) } + rule.mainClock.advanceTimeBy(1000L) + rule.runOnIdle { assertEquals(0, primaryGestureAvailableCount) } + + // ...and exit it before the second (dismiss) delay elapses at 2000ms. + rule.runOnUiThread { deviceInteractivity.setInteractive(true) } + rule.mainClock.advanceTimeBy(600L) + + rule.runOnIdle { + assertEquals(0, primaryGestureAvailableCount) + assertEquals(1, dismissGestureAvailableCount) + } + } + + /** + * Verifies that if the device enters ambient mode while a click indicator is animating, the + * animation is cancelled, the content is restored, and the indicator is not reported as shown. + */ + @Test + fun ambient_mode_mid_animation_cancels_click_indicator() { + var gestureAvailableCount = 0 + val sdkGestureInputManager = SdkGestureInputManagerMock() + val deviceInteractivity = FakeDeviceInteractivity() + val indicatorState = OneHandedGestureClickIndicatorState() + + rule.mainClock.autoAdvance = false + rule.setContentWithTheme { + val coroutineScope = rememberCoroutineScope() + MockSdkGestureInputManager( + sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) { + val gestureConfig = + rememberOneHandedGestureConfiguration(action = OneHandedGestureAction.Primary) + Box( + Modifier.size(50.dp).oneHandedGesture( + gestureConfiguration = gestureConfig, + onGestureLabel = "click", + onGestureAvailable = { + gestureAvailableCount++ + coroutineScope.launch { indicatorState.showIndicator() } + }, + ) {} + ) { + OneHandedGestureClickIndicator(gestureConfig, indicatorState) { Text("Label") } + } + } + } + rule.waitForIdle() + rule.mainClock.advanceTimeBy( + OneHandedGestureDefaults.ShowIndicatorDelayMillis + + INDICATOR_ANIMATION_START_DELAY_MILLIS + + 100 + ) + rule.runOnIdle { assertEquals(true, indicatorState.active) } + + rule.runOnUiThread { deviceInteractivity.setInteractive(false) } + + rule.runOnIdle { + assertEquals(false, indicatorState.active) + assertEquals(1f, indicatorState.contentAlpha.value) + assertEquals(0f, indicatorState.scaleAnimatable.value) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + } + + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(false, indicatorState.active) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + assertEquals(1, gestureAvailableCount) + } + + rule.runOnUiThread { deviceInteractivity.setInteractive(true) } + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(1, gestureAvailableCount) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + } + } + + /** + * Verifies that if the device enters ambient mode while a scroll indicator is animating, the + * animation is cancelled, the indicator is reset, and it is not reported as shown. + */ + @Test + fun ambient_mode_mid_animation_cancels_scroll_indicator() { + var gestureAvailableCount = 0 + val sdkGestureInputManager = SdkGestureInputManagerMock() + val deviceInteractivity = FakeDeviceInteractivity() + lateinit var scrollIndicatorState: OneHandedGestureScrollIndicatorState + + rule.mainClock.autoAdvance = false + rule.setContentWithTheme { + val coroutineScope = rememberCoroutineScope() + MockSdkGestureInputManager( + sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) { + val gestureConfig = + rememberOneHandedGestureConfiguration( + action = OneHandedGestureAction.Primary, + priority = OneHandedGesturePriority.Scrollable, + ) + scrollIndicatorState = + remember(gestureConfig) { OneHandedGestureScrollIndicatorState() } + val scrollState = rememberTransformingLazyColumnState() + Box( + Modifier.fillMaxSize().oneHandedGesture( + gestureConfiguration = gestureConfig, + onGestureLabel = "scroll", + onGestureAvailable = { + gestureAvailableCount++ + coroutineScope.launch { scrollIndicatorState.showIndicator() } + }, + ) {} + ) { + TransformingLazyColumn(state = scrollState) { + items(20) { Text("Item $it") } + } + OneHandedGestureScrollIndicator( + gestureConfiguration = gestureConfig, + indicatorState = scrollIndicatorState, + scrollState = scrollState, + ) + } + } + } + rule.waitForIdle() + rule.mainClock.advanceTimeBy( + OneHandedGestureDefaults.ShowIndicatorDelayMillis + + INDICATOR_ANIMATION_START_DELAY_MILLIS + + 100 + ) + rule.runOnIdle { assertEquals(true, scrollIndicatorState.active) } + + rule.runOnUiThread { deviceInteractivity.setInteractive(false) } + + rule.runOnIdle { + assertEquals(false, scrollIndicatorState.active) + assertEquals(0f, scrollIndicatorState.scaleAnimatable.value) + assertEquals(0f, scrollIndicatorState.colorProgress.value) + assertEquals(0f, scrollIndicatorState.jiggleFractionAnimatable.value) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + } + + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(false, scrollIndicatorState.active) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + assertEquals(1, gestureAvailableCount) + } + + rule.runOnUiThread { deviceInteractivity.setInteractive(true) } + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(1, gestureAvailableCount) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + } + } + + /** + * Verifies that if the device enters ambient mode while a page indicator is animating, the + * animation is cancelled, the indicator is reset, and it is not reported as shown. + */ + @Test + fun ambient_mode_mid_animation_cancels_page_indicator() { + var gestureAvailableCount = 0 + val sdkGestureInputManager = SdkGestureInputManagerMock() + val deviceInteractivity = FakeDeviceInteractivity() + val pageIndicatorState = OneHandedGesturePageIndicatorState() + + rule.mainClock.autoAdvance = false + rule.setContentWithTheme { + val coroutineScope = rememberCoroutineScope() + MockSdkGestureInputManager( + sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) { + val gestureConfig = + rememberOneHandedGestureConfiguration(action = OneHandedGestureAction.Primary) + val pagerState = rememberPagerState(pageCount = { 3 }) + HorizontalPagerScaffold( + pagerState = pagerState, + pageIndicator = { + OneHandedGestureHorizontalPageIndicator( + gestureConfiguration = gestureConfig, + indicatorState = pageIndicatorState, + pagerState = pagerState, + ) + }, + ) { + HorizontalPager( + state = pagerState, + modifier = + Modifier.oneHandedGesture( + gestureConfiguration = gestureConfig, + onGestureLabel = "Page", + onGestureAvailable = { + gestureAvailableCount++ + coroutineScope.launch { pageIndicatorState.showIndicator() } + }, + onGesture = {}, + ), + ) { page -> + Text(text = "Page $page") + } + } + } + } + rule.waitForIdle() + rule.mainClock.advanceTimeBy( + OneHandedGestureDefaults.ShowIndicatorDelayMillis + + INDICATOR_ANIMATION_START_DELAY_MILLIS + + 100 + ) + rule.runOnIdle { assertEquals(true, pageIndicatorState.active) } + + rule.runOnUiThread { deviceInteractivity.setInteractive(false) } + + rule.runOnIdle { + assertEquals(false, pageIndicatorState.active) + assertEquals(0f, pageIndicatorState.scaleAnimatable.value) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + } + + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(false, pageIndicatorState.active) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + assertEquals(1, gestureAvailableCount) + } + + rule.runOnUiThread { deviceInteractivity.setInteractive(true) } + rule.mainClock.advanceTimeBy(GESTURE_AVAILABLE_DELAY) + + rule.runOnIdle { + assertEquals(1, gestureAvailableCount) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + } + } + + /** + * Verifies that showIndicator doesn't animate the indicator while the device is in ambient + * mode. + */ + @Test + fun show_indicator_in_ambient_mode_does_nothing() { + val sdkGestureInputManager = SdkGestureInputManagerMock() + val deviceInteractivity = FakeDeviceInteractivity(initiallyInteractive = false) + val indicatorState = OneHandedGestureClickIndicatorState() + lateinit var coroutineScope: CoroutineScope + + rule.mainClock.autoAdvance = false + rule.setContentWithTheme { + coroutineScope = rememberCoroutineScope() + MockSdkGestureInputManager( + sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) { + val gestureConfig = + rememberOneHandedGestureConfiguration(action = OneHandedGestureAction.Primary) + OneHandedGestureClickIndicator(gestureConfig, indicatorState) { Text("Label") } + } + } + rule.waitForIdle() + + var showIndicatorReturned = false + rule.runOnIdle { + coroutineScope.launch { + indicatorState.showIndicator() + showIndicatorReturned = true + } + } + rule.mainClock.advanceTimeBy(INDICATOR_ANIMATION_START_DELAY_MILLIS + 100) + + rule.runOnIdle { + assertEquals(true, showIndicatorReturned) + assertEquals(false, indicatorState.active) + assertEquals(1f, indicatorState.contentAlpha.value) + assertEquals(0f, indicatorState.scaleAnimatable.value) + assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) + } + } + + /** + * Verifies that an indicator that finishes while the device is in ambient mode is not reported + * as shown, e.g. if it finishes before the screen-off broadcast cancels it. + */ + @Test + fun notify_indicator_shown_in_ambient_mode_is_not_reported() { + val sdkGestureInputManager = SdkGestureInputManagerMock() + val deviceInteractivity = FakeDeviceInteractivity(initiallyInteractive = false) + lateinit var gestureManager: OneHandedGestureManager + lateinit var gestureConfig: OneHandedGestureConfiguration + + rule.setContentWithTheme { + MockSdkGestureInputManager( + sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) { + gestureManager = LocalOneHandedGestureManager.current + gestureConfig = + rememberOneHandedGestureConfiguration(action = OneHandedGestureAction.Primary) + } + } + + rule.runOnIdle { gestureManager.notifyIndicatorShown(gestureConfig) } + + rule.runOnIdle { assertEquals(0, sdkGestureInputManager.notifyIndicatorShownCount) } + } + @SuppressLint("UnusedBoxWithConstraintsScope") @Test fun moving_gesture_modifier_with_movable_content_does_not_crash() { @@ -3345,12 +3758,21 @@ private fun MockSdkGestureInputManager( sdkGestureInputManager: SdkGestureInputManager, results: MutableMap<HapticFeedbackType, Int> = mutableMapOf(), + deviceInteractivity: DeviceInteractivity = FakeDeviceInteractivity(), content: @Composable () -> Unit, ) { val scope: CoroutineScope = rememberCoroutineScope() val haptic = hapticFeedback(collectResultsFromHapticFeedback(results)) + val applicationContext = LocalContext.current.applicationContext val gestureManager = - remember(scope) { OneHandedGestureManagerImpl(scope, sdkGestureInputManager) } + remember(scope) { + OneHandedGestureManagerImpl( + applicationContext = applicationContext, + scope = scope, + gestureInputManager = sdkGestureInputManager, + deviceInteractivity = deviceInteractivity, + ) + } CompositionLocalProvider( LocalOneHandedGestureManager provides gestureManager, @@ -3403,12 +3825,18 @@ gestureId: String, sdkGestureAction: Int, isOverlay: Boolean, - ): Boolean = showIndicator + ): Boolean { + shouldShowIndicatorCount++ + return showIndicator + } + var shouldShowIndicatorCount = 0 + var notifyIndicatorShownCount = 0 var lastNotifiedGestureId: String? = null var lastNotifiedSdkGestureAction: Int? = null override fun notifyIndicatorShown(gestureId: String, sdkGestureAction: Int) { + notifyIndicatorShownCount++ lastNotifiedGestureId = gestureId lastNotifiedSdkGestureAction = sdkGestureAction } @@ -3426,6 +3854,22 @@ private val gestureConsumers = mutableMapOf<Int, (Int) -> Unit>() } + /** [DeviceInteractivity] whose interactivity is controlled by the test. */ + private class FakeDeviceInteractivity(initiallyInteractive: Boolean = true) : + DeviceInteractivity { + private val interactive = MutableStateFlow(initiallyInteractive) + + override fun isInteractive(context: Context): Boolean = interactive.value + + override suspend fun awaitScreenOff(context: Context) { + interactive.first { !it } + } + + fun setInteractive(isInteractive: Boolean) { + interactive.value = isInteractive + } + } + private fun verifyShowIndicatorDelay( showIndicatorDelayMillis: Long?, expectedDelayMillis: Long,
diff --git a/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/PowerManagerDeviceInteractivityTest.kt b/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/PowerManagerDeviceInteractivityTest.kt new file mode 100644 index 0000000..c8b2d74 --- /dev/null +++ b/wear/compose/compose-material3/src/androidTest/kotlin/androidx/wear/compose/material3/PowerManagerDeviceInteractivityTest.kt
@@ -0,0 +1,168 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.wear.compose.material3 + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.IntentFilter +import android.os.Handler +import android.os.PowerManager +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.MediumTest +import androidx.wear.compose.material3.onehandedgesture.PowerManagerDeviceInteractivity +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.yield +import org.junit.Assume.assumeTrue +import org.junit.Test +import org.junit.runner.RunWith + +@MediumTest +@RunWith(AndroidJUnit4::class) +class PowerManagerDeviceInteractivityTest { + @Test + fun is_interactive_matches_power_manager() { + val context = ApplicationProvider.getApplicationContext<Context>() + val powerManager = context.getSystemService(PowerManager::class.java) + + val isInteractive = PowerManagerDeviceInteractivity.isInteractive(context) + + assertEquals(powerManager.isInteractive, isInteractive) + } + + /** + * Verifies that awaitScreenOff registers a receiver for ACTION_SCREEN_OFF, completes when it is + * received, and then unregisters the receiver. + */ + @Test + fun await_screen_off_completes_on_screen_off_and_unregisters() { + val context = ReceiverRecordingContext(ApplicationProvider.getApplicationContext()) + // awaitScreenOff returns immediately if the device is not interactive. + assumeTrue(PowerManagerDeviceInteractivity.isInteractive(context)) + + runBlocking { + val job = + launch(start = CoroutineStart.UNDISPATCHED) { + PowerManagerDeviceInteractivity.awaitScreenOff(context) + } + val receiver = assertNotNull(context.registeredReceiver) + assertEquals(true, context.registeredFilter?.hasAction(Intent.ACTION_SCREEN_OFF)) + assertEquals(true, job.isActive) + + receiver.onReceive(context, Intent(Intent.ACTION_SCREEN_OFF)) + job.join() + + assertEquals(receiver, context.unregisteredReceiver) + } + } + + /** Verifies that awaitScreenOff ignores broadcasts other than ACTION_SCREEN_OFF. */ + @Test + fun await_screen_off_ignores_other_broadcasts() { + val context = ReceiverRecordingContext(ApplicationProvider.getApplicationContext()) + // awaitScreenOff returns immediately if the device is not interactive. + assumeTrue(PowerManagerDeviceInteractivity.isInteractive(context)) + + runBlocking { + val job = + launch(start = CoroutineStart.UNDISPATCHED) { + PowerManagerDeviceInteractivity.awaitScreenOff(context) + } + val receiver = assertNotNull(context.registeredReceiver) + + receiver.onReceive(context, Intent(Intent.ACTION_SCREEN_ON)) + yield() + + assertEquals(true, job.isActive) + assertEquals(null, context.unregisteredReceiver) + job.cancel() + } + } + + /** Verifies that awaitScreenOff unregisters its receiver when it is cancelled. */ + @Test + fun await_screen_off_unregisters_when_cancelled() { + val context = ReceiverRecordingContext(ApplicationProvider.getApplicationContext()) + // awaitScreenOff returns immediately if the device is not interactive. + assumeTrue(PowerManagerDeviceInteractivity.isInteractive(context)) + + runBlocking { + val job = + launch(start = CoroutineStart.UNDISPATCHED) { + PowerManagerDeviceInteractivity.awaitScreenOff(context) + } + val receiver = assertNotNull(context.registeredReceiver) + + job.cancelAndJoin() + + assertEquals(receiver, context.unregisteredReceiver) + } + } + + /** + * [ContextWrapper] that records broadcast receiver (un)registrations instead of performing + * them, so that tests can deliver broadcasts directly to the receiver. + */ + private class ReceiverRecordingContext(base: Context) : ContextWrapper(base) { + var registeredReceiver: BroadcastReceiver? = null + var registeredFilter: IntentFilter? = null + var unregisteredReceiver: BroadcastReceiver? = null + + override fun registerReceiver( + receiver: BroadcastReceiver?, + filter: IntentFilter?, + ): Intent? = record(receiver, filter) + + override fun registerReceiver( + receiver: BroadcastReceiver?, + filter: IntentFilter?, + flags: Int, + ): Intent? = record(receiver, filter) + + override fun registerReceiver( + receiver: BroadcastReceiver?, + filter: IntentFilter?, + broadcastPermission: String?, + scheduler: Handler?, + ): Intent? = record(receiver, filter) + + override fun registerReceiver( + receiver: BroadcastReceiver?, + filter: IntentFilter?, + broadcastPermission: String?, + scheduler: Handler?, + flags: Int, + ): Intent? = record(receiver, filter) + + override fun unregisterReceiver(receiver: BroadcastReceiver?) { + unregisteredReceiver = receiver + } + + private fun record(receiver: BroadcastReceiver?, filter: IntentFilter?): Intent? { + registeredReceiver = receiver + registeredFilter = filter + return null + } + } +}
diff --git a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureClickIndicator.kt b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureClickIndicator.kt index 2b59d002..0a807be 100644 --- a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureClickIndicator.kt +++ b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureClickIndicator.kt
@@ -34,7 +34,6 @@ import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable -import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex @@ -157,7 +156,9 @@ // animation val gestureIndicator = gestureManager.getRegisteredGestureIndicator(gestureConfiguration) - gestureIndicator?.let { coroutineScope { performAnimation(it) } } + gestureIndicator?.let { indicator -> + gestureManager.runIndicator { performAnimation(indicator) } + } } }
diff --git a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureManager.kt b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureManager.kt index 29a1df9..f11c32d 100644 --- a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureManager.kt +++ b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureManager.kt
@@ -17,7 +17,11 @@ package androidx.wear.compose.material3.onehandedgesture import android.annotation.SuppressLint +import android.content.BroadcastReceiver import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.PowerManager import android.view.View import android.view.ViewGroup import androidx.collection.MutableIntObjectMap @@ -29,6 +33,7 @@ import androidx.compose.ui.hapticfeedback.HapticFeedback import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.AndroidUiDispatcher +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.center import androidx.compose.ui.unit.toOffset @@ -45,10 +50,14 @@ import com.google.wear.input.GestureInputManager import java.util.function.Consumer import kotlin.collections.mutableMapOf +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch /** @@ -58,7 +67,8 @@ internal val LocalOneHandedGestureManager: ProvidableCompositionLocal<OneHandedGestureManager> = compositionLocalWithComputedDefaultOf { if (cachedGestureManager == null) { - cachedGestureManager = OneHandedGestureManagerImpl() + cachedGestureManager = + OneHandedGestureManagerImpl(LocalContext.currentValue.applicationContext) } cachedGestureManager!! } @@ -168,6 +178,17 @@ fun notifyIndicatorShown(gestureConfiguration: OneHandedGestureConfiguration) /** + * Runs the gesture indicator animation [block]. + * + * The [block] is not run if the device is not interactive (e.g. in ambient mode or with the + * screen off), and it is cancelled if the screen turns off while it is running, as the user + * can't see the indicator. In both cases this function returns normally. + * + * @param block The indicator animation. + */ + suspend fun runIndicator(block: suspend CoroutineScope.() -> Unit) + + /** * Retrieves the gesture indicator data for the specified [OneHandedGestureConfiguration]. * * @param gestureConfiguration The [OneHandedGestureConfiguration] to look up. @@ -179,8 +200,10 @@ } internal class OneHandedGestureManagerImpl( + private val applicationContext: Context, val scope: CoroutineScope = CoroutineScope(SupervisorJob() + AndroidUiDispatcher.Main), val gestureInputManager: SdkGestureInputManager = SdkGestureInputManagerImpl(), + private val deviceInteractivity: DeviceInteractivity = PowerManagerDeviceInteractivity, ) : OneHandedGestureManager { /** Map of registered gestures per View */ @@ -214,6 +237,7 @@ isOverlayProvider = { config -> indicatorRegistry[config]?.isFloating ?: false }, + deviceInteractivity, ) }, ) @@ -284,17 +308,48 @@ } override fun notifyIndicatorShown(gestureConfiguration: OneHandedGestureConfiguration) { + // An indicator that finished while the device was not interactive (e.g. in ambient mode) + // was not seen by the user, so it must not count towards the indicator display limits. + if (!isInteractive()) return + gestureInputManager.notifyIndicatorShown( gestureConfiguration.gestureId, toSdkGestureAction(gestureConfiguration.action), ) } + override suspend fun runIndicator(block: suspend CoroutineScope.() -> Unit) { + // Don't show the indicator when in ambient mode. + if (!isInteractive()) return + + coroutineScope { + ensureActive() + val indicatorJob = launch(block = block) + // Start undispatched, so that the screen-off receiver is registered (and the device + // re-checked) before the indicator animation starts. + val screenOffJob = + launch(start = CoroutineStart.UNDISPATCHED) { + awaitScreenOff() + // Cancel the hint animation when ACTION_SCREEN_OFF broadcast is received. + indicatorJob.cancel() + } + indicatorJob.join() + screenOffJob.cancel() + } + } + override fun getRegisteredGestureIndicator( gestureConfiguration: OneHandedGestureConfiguration ): RegisteredIndicator? { return indicatorRegistry[gestureConfiguration] } + + private fun isInteractive(): Boolean = deviceInteractivity.isInteractive(applicationContext) + + /** Suspends until the screen turns off or device enters ambient mode. */ + private suspend fun awaitScreenOff() { + deviceInteractivity.awaitScreenOff(applicationContext) + } } internal class GestureRegistry( @@ -303,6 +358,7 @@ private val scope: CoroutineScope, private val gestureInputManager: SdkGestureInputManager, private val isOverlayProvider: (OneHandedGestureConfiguration) -> Boolean, + private val deviceInteractivity: DeviceInteractivity, ) { val numberOfRegisteredGestures: Int get() = registeredGestures.size @@ -433,6 +489,10 @@ delay(maxOf(0L, gesture.showIndicatorDelayMillis - elapsedMillis)) elapsedMillis = gesture.showIndicatorDelayMillis + // Don't query or show the indicator while the user can't see it (e.g. in ambient + // mode), so that it isn't counted as shown. + if (!deviceInteractivity.isInteractive(view.context)) return@fastForEach + val gestureConfig = gesture.gestureConfiguration // Check whether to show the indicator, based on whether it is an // overlay(goes outside the bounds of the component) and frequency @@ -771,6 +831,58 @@ } } +/** + * Provides the device interactivity status. + * + * The device is not interactive in ambient mode and when the screen is off. + */ +internal interface DeviceInteractivity { + /** Whether the device is currently interactive. */ + fun isInteractive(context: Context): Boolean + + /** + * Suspends until the screen turns off, e.g. when the device enters ambient mode. Returns + * immediately if the device is already not interactive. + */ + suspend fun awaitScreenOff(context: Context) +} + +/** + * [DeviceInteractivity] backed by [PowerManager.isInteractive], which is false in ambient mode and + * when the screen is off, and by the [Intent.ACTION_SCREEN_OFF] broadcast, which is sent when the + * device stops being interactive. + */ +internal object PowerManagerDeviceInteractivity : DeviceInteractivity { + override fun isInteractive(context: Context): Boolean = + ContextCompat.getSystemService(context, PowerManager::class.java)?.isInteractive ?: true + + override suspend fun awaitScreenOff(context: Context) { + val screenOff = CompletableDeferred<Unit>() + val receiver = + object : BroadcastReceiver() { + override fun onReceive(receiverContext: Context, intent: Intent) { + if (intent.action == Intent.ACTION_SCREEN_OFF) { + screenOff.complete(Unit) + } + } + } + ContextCompat.registerReceiver( + context, + receiver, + IntentFilter(Intent.ACTION_SCREEN_OFF), + ContextCompat.RECEIVER_NOT_EXPORTED, + ) + try { + // ACTION_SCREEN_OFF isn't re-delivered to receivers registered later, so the screen may + // already have turned off before the receiver was registered. + if (!isInteractive(context)) return + screenOff.await() + } finally { + context.unregisterReceiver(receiver) + } + } +} + private fun toSdkGestureAction(gestureAction: OneHandedGestureAction): Int { return when (gestureAction) { OneHandedGestureAction.Dismiss -> GestureEvent.ACTION_DISMISS
diff --git a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGesturePageIndicator.kt b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGesturePageIndicator.kt index 3379123..b78710f 100644 --- a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGesturePageIndicator.kt +++ b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGesturePageIndicator.kt
@@ -48,7 +48,6 @@ import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable -import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex @@ -229,7 +228,9 @@ // animation val gestureIndicator = gestureManager.getRegisteredGestureIndicator(gestureConfiguration) - gestureIndicator?.let { coroutineScope { performAnimation(it) } } + gestureIndicator?.let { indicator -> + gestureManager.runIndicator { performAnimation(indicator) } + } } }
diff --git a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureScrollIndicator.kt b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureScrollIndicator.kt index 20258f3..6f8255d 100644 --- a/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureScrollIndicator.kt +++ b/wear/compose/compose-material3/src/main/java/androidx/wear/compose/material3/onehandedgesture/OneHandedGestureScrollIndicator.kt
@@ -58,7 +58,6 @@ import kotlin.time.Duration.Companion.milliseconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable -import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex @@ -237,7 +236,9 @@ // animation val gestureIndicator = gestureManager.getRegisteredGestureIndicator(gestureConfiguration) - gestureIndicator?.let { coroutineScope { performAnimation(it) } } + gestureIndicator?.let { indicator -> + gestureManager.runIndicator { performAnimation(indicator) } + } } }
diff --git a/web/web-compose/build.gradle b/web/web-compose/build.gradle index 50886e7..82ea5d6 100644 --- a/web/web-compose/build.gradle +++ b/web/web-compose/build.gradle
@@ -42,6 +42,8 @@ implementation("androidx.compose.ui:ui-graphics:$compose_version") implementation("androidx.compose.ui:ui-unit:$compose_version") implementation("androidx.compose.ui:ui-util:$compose_version") + implementation("androidx.compose.foundation:foundation-layout:$compose_version") + implementation("androidx.core:core:1.16.0") // Older versions of lifecycle-runtime lint checks use a deleted lint API implementation("androidx.lifecycle:lifecycle-runtime:2.10.0") @@ -75,6 +77,7 @@ inceptionYear = "2026" description = "This package provides a composable that displays web pages." + samples(project(":web:web-compose:web-compose-samples")) additionalDeviceTestApkKeys.add("chrome") deviceTests { maxShardCount = 1
diff --git a/web/web-compose/samples/build.gradle b/web/web-compose/samples/build.gradle new file mode 100644 index 0000000..1997330 --- /dev/null +++ b/web/web-compose/samples/build.gradle
@@ -0,0 +1,41 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import androidx.build.SoftwareType + +plugins { + id("AndroidXPlugin") + id("com.android.library") + id("AndroidXComposePlugin") +} + +dependencies { + compileOnly(project(":annotation:annotation-sampled")) + + implementation(project(":web:web-compose")) +} + +android { + namespace = "androidx.web.compose.samples" + compileSdk { version = release(35) } +} + +androidx { + name = "Web Compose Samples" + type = SoftwareType.SAMPLES + inceptionYear = "2026" + description = "Contains sample code for the AndroidX Web Compose library." +}
diff --git a/web/web-compose/src/androidTest/kotlin/androidx/web/compose/WebSurfaceTest.kt b/web/web-compose/src/androidTest/kotlin/androidx/web/compose/WebSurfaceTest.kt index d4d5e9a..57a6981 100644 --- a/web/web-compose/src/androidTest/kotlin/androidx/web/compose/WebSurfaceTest.kt +++ b/web/web-compose/src/androidTest/kotlin/androidx/web/compose/WebSurfaceTest.kt
@@ -40,7 +40,14 @@ import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets as ComposeWindowInsets +import androidx.compose.foundation.layout.consumeWindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState @@ -106,6 +113,10 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.roundToIntRect import androidx.compose.ui.viewinterop.AndroidView +import androidx.core.graphics.Insets +import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress @@ -117,6 +128,7 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.math.abs +import kotlin.math.roundToInt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking @@ -1839,7 +1851,7 @@ } @Test - fun testWindowInsetsNotDispatchedToBridgeAndPreservedForSiblingAndroidView() { + fun testWindowInsetsDispatchedToBridgeAndPreservedForSiblingAndroidView() { lateinit var hostView: View var bridgeSawInsets = false var siblingSawInsets = false @@ -1878,12 +1890,97 @@ val rootInsets = checkNotNull(hostView.rootWindowInsets) hostView.dispatchApplyWindowInsets(WindowInsets(rootInsets)) - assertFalse(bridgeSawInsets) + assertTrue(bridgeSawInsets) assertTrue(siblingSawInsets) } } @Test + fun testPageSafeAreaExcludesConsumedInsets() { + lateinit var bridge: WebViewBridge + var consumeInsets by mutableStateOf(false) + val window = composeTestRule.activity.window + composeTestRule.runOnUiThread { WindowCompat.setDecorFitsSystemWindows(window, false) } + + composeTestRule.setContent { + WebSurface( + content = webContent, + modifier = + Modifier.then( + if (consumeInsets) { + Modifier.consumeWindowInsets(ComposeWindowInsets.safeDrawing) + } else { + Modifier + } + ) + .size(100.dp), + bridgeFactory = { WebViewBridge(it).also { b -> bridge = b } }, + ) + } + val hasStatusBar = composeTestRule.runOnIdle { + ViewCompat.getRootWindowInsets(window.decorView) + ?.isVisible(WindowInsetsCompat.Type.statusBars()) == true + } + assumeTrue(hasStatusBar) + bridge.loadHtml( + composeTestRule, + "<meta name='viewport' content='width=device-width, viewport-fit=cover'>" + + "<body style='padding-top: env(safe-area-inset-top)'></body>", + ) + fun awaitPageSafeAreaTop(condition: (Float) -> Boolean) = + composeTestRule.waitUntil(TIMEOUT_MS) { + val top = + bridge.evaluateJs("parseFloat(getComputedStyle(document.body).paddingTop)") + condition(top.toFloatOrNull() ?: 0f) + } + + // Like other composables, the page gets the insets that nothing around it consumed. + awaitPageSafeAreaTop { it > 0f } + composeTestRule.runOnIdle { consumeInsets = true } + awaitPageSafeAreaTop { it == 0f } + } + + @Test + @SdkSuppress(minSdkVersion = Build.VERSION_CODES.R) + fun testPageKeyboardInsetAccountsForSurfacePosition() { + lateinit var hostView: View + lateinit var bridge: WebViewBridge + val window = composeTestRule.activity.window + composeTestRule.runOnUiThread { WindowCompat.setDecorFitsSystemWindows(window, false) } + + composeTestRule.setContent { + hostView = LocalView.current + Column(Modifier.fillMaxSize()) { + WebSurface( + content = webContent, + modifier = Modifier.fillMaxWidth().weight(1f), + bridgeFactory = { WebViewBridge(it).also { b -> bridge = b } }, + ) + Spacer(Modifier.height(100.dp)) + } + } + bridge.loadHtml( + composeTestRule, + "<meta name='viewport' content='width=device-width, initial-scale=1'>", + ) + // A 150dp keyboard covers the 100dp below the surface and the bottom 50dp of the page. + composeTestRule.runOnIdle { + val keyboard = (150 * hostView.resources.displayMetrics.density).roundToInt() + val insets = + WindowInsetsCompat.Builder() + .setInsets(WindowInsetsCompat.Type.ime(), Insets.of(0, 0, 0, keyboard)) + .setVisible(WindowInsetsCompat.Type.ime(), true) + .build() + hostView.dispatchApplyWindowInsets(checkNotNull(insets.toWindowInsets())) + } + // Like a WebView in a View hierarchy, the page's visual viewport shrinks by what's covered. + composeTestRule.waitUntil(TIMEOUT_MS) { + val covered = bridge.evaluateJs("innerHeight - visualViewport.height").toFloatOrNull() + covered != null && abs(covered - 50f) <= 1f + } + } + + @Test @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE) fun testTrackpadPanExitingBoundsCancelsGesture() { lateinit var bridge: WebViewBridge
diff --git a/web/web-compose/src/main/kotlin/androidx/web/compose/HeadlessWebContentViewHost.kt b/web/web-compose/src/main/kotlin/androidx/web/compose/HeadlessWebContentViewHost.kt index a0e962a..35a0233 100644 --- a/web/web-compose/src/main/kotlin/androidx/web/compose/HeadlessWebContentViewHost.kt +++ b/web/web-compose/src/main/kotlin/androidx/web/compose/HeadlessWebContentViewHost.kt
@@ -91,9 +91,18 @@ if (value != null) { addView(value) updateSize(width, height) + bridgeInsets?.let(value::dispatchApplyWindowInsets) } } + /** The window insets for [view], which WebSurface works out from Compose's insets. */ + var bridgeInsets: WindowInsets? = null + set(value) { + if (field == value) return + field = value + value?.let { view?.dispatchApplyWindowInsets(it) } + } + // Chromium positions anchor views for in-page popups (e.g. <datalist>, tablet <select>) via // layout params, so lay the holder subtree out locally instead of propagating the request to // the Compose host. Deferred to the next frame to coalesce requests and avoid re-entrancy. @@ -178,9 +187,13 @@ // at index 0 of AndroidComposeView from intercepting View drag events before Compose sees them. override fun dispatchDragEvent(event: DragEvent): Boolean = false - // Window insets belong to the Compose hierarchy; prevent listeners on the bridge from - // receiving or consuming insets ahead of sibling AndroidViews. - override fun dispatchApplyWindowInsets(insets: WindowInsets): WindowInsets = insets + // Window insets belong to the Compose hierarchy, so don't let the bridge, or listeners on it, + // receive or consume the View tree's insets ahead of sibling AndroidViews. It gets bridgeInsets + // instead, including when Chromium asks for insets again. + override fun dispatchApplyWindowInsets(insets: WindowInsets): WindowInsets { + bridgeInsets?.let { view?.dispatchApplyWindowInsets(it) } + return insets + } // Rendering is handled directly by WebSurfaceNode via Chromium's draw functor. override fun dispatchDraw(canvas: Canvas) {}
diff --git a/web/web-compose/src/main/kotlin/androidx/web/compose/WebSurface.kt b/web/web-compose/src/main/kotlin/androidx/web/compose/WebSurface.kt index e9e7a48..cf9bebb 100644 --- a/web/web-compose/src/main/kotlin/androidx/web/compose/WebSurface.kt +++ b/web/web-compose/src/main/kotlin/androidx/web/compose/WebSurface.kt
@@ -24,11 +24,21 @@ import android.view.ViewGroup import android.view.ViewTreeObserver import androidx.annotation.RequiresFeature +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.exclude +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.layout.onConsumedWindowInsetsChanged +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union import androidx.compose.runtime.Composable import androidx.compose.runtime.RememberObserver +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.retain.RetainObserver import androidx.compose.runtime.retain.retain +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.focus.FocusState @@ -68,12 +78,16 @@ import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.semantics.SemanticsPropertyReceiver +import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.round import androidx.compose.ui.util.fastAny import androidx.compose.ui.util.fastForEach import androidx.compose.ui.viewinterop.NoOpUpdate +import androidx.core.graphics.Insets +import androidx.core.view.WindowInsetsCompat import androidx.web.WebContent import androidx.web.WebFeature import androidx.web.WebSurfaceChromium @@ -203,6 +217,9 @@ bridgeRelease = bridgeRelease, ) } + // The page gets window insets like a composable, see pageInsets. + val safeArea = WindowInsets.systemBars.union(WindowInsets.displayCutout) + val ime = WindowInsets.ime Layout( modifier = Modifier.onKeyEvent { state.node?.dispatchKeyEvent(it.nativeKeyEvent) == true } @@ -212,6 +229,7 @@ } .focusTarget() .then(modifier) + .onConsumedWindowInsetsChanged { state.pageSafeArea = safeArea.exclude(it) } .clipToBounds() .then( WebSurfaceElement( @@ -222,7 +240,9 @@ ) ) ) { _, constraints -> - layout(constraints.minWidth, constraints.minHeight) {} + layout(constraints.minWidth, constraints.minHeight) { + state.node?.bridgeInsets = pageInsets(state.pageSafeArea, ime, layoutDirection) + } } } @@ -238,6 +258,9 @@ var node: WebSurfaceNode<T>? = null + /** The safe area insets that nothing around the surface consumed, like Scaffold's. */ + var pageSafeArea by mutableStateOf(WindowInsets()) + override fun onRemembered() { // Takes over from a WebSurface that hasn't left composition yet, e.g. one animating out or // in a lazy layout item disposed after the frame. A closed content shows nothing. @@ -320,6 +343,14 @@ private var webSurface: WebSurfaceChromium? = null private var size = IntSize.Zero private var holder: HeadlessViewHolder? = null + + /** The window insets for the page, see [pageInsets]. */ + var bridgeInsets: WindowInsetsCompat? = null + set(value) { + field = value + holder?.bridgeInsets = value?.toWindowInsets() + } + private var pinnedHandle: PinnableContainer.PinnedHandle? = null private var attachedViewTreeObserver: ViewTreeObserver? = null private var isPlaced: Boolean = false @@ -569,7 +600,11 @@ (hostView as? ViewGroup)?.let { host -> installHostAccessibilityDelegate(host) // Add ahead of AndroidViewsHandler so FOCUS_AFTER_DESCENDANTS checks holders first. - holder = HeadlessViewHolder(host.context, this).also { host.addView(it, 0) } + holder = + HeadlessViewHolder(host.context, this).also { + host.addView(it, 0) + it.bridgeInsets = bridgeInsets?.toWindowInsets() + } } // In-place LayoutNode reuse (e.g. ReusableContent) detaches and re-attaches without // unplacing or re-dispatching onGloballyPositioned, so size and position the new holder. @@ -858,6 +893,32 @@ private val MotionEvent.isTouchEnd: Boolean get() = actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_CANCEL +/** + * The window insets for the page. Like other composables, the page gets the [safeArea] that nothing + * around it consumed, as with `Modifier.windowInsetsPadding`. The [ime] stays as the window has it, + * because Chromium works out how much of the page it covers. + */ +private fun Density.pageInsets( + safeArea: WindowInsets, + ime: WindowInsets, + layoutDirection: LayoutDirection, +): WindowInsetsCompat { + val keyboard = ime.getBottom(this) + return WindowInsetsCompat.Builder() + .setInsets( + WindowInsetsCompat.Type.systemBars(), + Insets.of( + safeArea.getLeft(this, layoutDirection), + safeArea.getTop(this), + safeArea.getRight(this, layoutDirection), + safeArea.getBottom(this), + ), + ) + .setInsets(WindowInsetsCompat.Type.ime(), Insets.of(0, 0, 0, keyboard)) + .setVisible(WindowInsetsCompat.Type.ime(), keyboard > 0) + .build() +} + private inline fun MotionEvent.withOffset( dx: Float, dy: Float,
diff --git a/webkit/integration-tests/instrumentation/src/androidTest/java/androidx/webkit/DownloadHandlerTest.kt b/webkit/integration-tests/instrumentation/src/androidTest/java/androidx/webkit/DownloadHandlerTest.kt index 5c9d1b7..5bfde24 100644 --- a/webkit/integration-tests/instrumentation/src/androidTest/java/androidx/webkit/DownloadHandlerTest.kt +++ b/webkit/integration-tests/instrumentation/src/androidTest/java/androidx/webkit/DownloadHandlerTest.kt
@@ -29,6 +29,7 @@ import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Before @@ -110,6 +111,9 @@ assertEquals("text/plain", download.mimeType) assertEquals(CONTENT.length.toLong(), download.contentLength) assertEquals("hello.txt", download.suggestedFilename) + assertTrue(download.isExplicitDownload) + assertTrue(download.isForMainFrame) + assertFalse(download.hasGesture()) WebkitUtils.onMainThreadSync { download.cancel() } }
diff --git a/webkit/webkit/src/main/java/androidx/webkit/WebDownload.java b/webkit/webkit/src/main/java/androidx/webkit/WebDownload.java index 8bb3b2ed..17cff13 100644 --- a/webkit/webkit/src/main/java/androidx/webkit/WebDownload.java +++ b/webkit/webkit/src/main/java/androidx/webkit/WebDownload.java
@@ -104,6 +104,39 @@ } /** + * Returns whether the server or the page asked for the download, for example with the + * {@code Content-Disposition: attachment} response header or with {@code <a download>}. If + * not, WebView downloads the response only because it can't display it, for example a PDF. + * + * @return {@code true} if the server or the page asked for the download. + */ + @AnyThread + public boolean isExplicitDownload() { + return mBoundaryInterface.isExplicitDownload(); + } + + /** + * Returns whether the main frame of the {@link WebView} started the download, either by + * navigating to it or by asking for it, for example with {@code <a download>}. + * + * @return {@code true} if the main frame started the download. + */ + @AnyThread + public boolean isForMainFrame() { + return mBoundaryInterface.isForMainFrame(); + } + + /** + * Returns whether a user gesture, such as a tap, started the download. + * + * @return {@code true} if a user gesture started the download. + */ + @AnyThread + public boolean hasGesture() { + return mBoundaryInterface.hasGesture(); + } + + /** * Saves the download to {@code destination}. * * <p>The following destinations are supported:
diff --git a/xr/projected/integration-tests/xr-integration-tests/build.gradle b/xr/projected/integration-tests/xr-integration-tests/build.gradle index a043a99..1cde43a 100644 --- a/xr/projected/integration-tests/xr-integration-tests/build.gradle +++ b/xr/projected/integration-tests/xr-integration-tests/build.gradle
@@ -44,6 +44,7 @@ description = "Automated instrumented integration tests for JXR Projected to run in CI and on " + "paired emulators/devices." + addGoldenImageAssets() deviceTests { maxShardCount = 1 } @@ -54,6 +55,14 @@ implementation("androidx.activity:activity:1.12.1") + // TODO: b/590840667 - Remove emoji2 and lifecycle-process exclusions once :xr:testutils + // decouples transitive Compose UI deps or AGP resolves the .test startup-runtime DEX/manifest + // deduplication mismatch (note: tools:node="remove" in src/androidTest/AndroidManifest.xml + // emits a mergeDebugAndroidTestManifest warning that fails build_log_simplifier.py). + androidTestImplementation(project(":xr:testutils")) { + exclude group: "androidx.emoji2", module: "emoji2" + exclude group: "androidx.lifecycle", module: "lifecycle-process" + } androidTestImplementation(libs.junit) androidTestImplementation(libs.testCore) androidTestImplementation(libs.testExtJunit)
diff --git a/xr/projected/integration-tests/xr-integration-tests/src/androidTest/kotlin/androidx/xr/projected/integration/tests/ProjectedDisplayScreenshotTest.kt b/xr/projected/integration-tests/xr-integration-tests/src/androidTest/kotlin/androidx/xr/projected/integration/tests/ProjectedDisplayScreenshotTest.kt new file mode 100644 index 0000000..b68671a --- /dev/null +++ b/xr/projected/integration-tests/xr-integration-tests/src/androidTest/kotlin/androidx/xr/projected/integration/tests/ProjectedDisplayScreenshotTest.kt
@@ -0,0 +1,160 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.xr.projected.integration.tests + +import android.content.Intent +import android.graphics.Color +import android.graphics.Typeface +import android.graphics.drawable.GradientDrawable +import android.util.TypedValue +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.LinearLayout +import android.widget.TextView +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.filters.LargeTest +import androidx.test.platform.app.InstrumentationRegistry +import androidx.xr.projected.ProjectedContext +import androidx.xr.projected.experimental.ExperimentalProjectedApi +import androidx.xr.testutils.ProjectedScreenshotTestRule +import androidx.xr.testutils.assertAgainstGolden +import androidx.xr.testutils.captureProjectedDisplayToBitmap +import com.google.common.truth.Truth.assertThat +import org.junit.Rule +import org.junit.Test +import org.junit.rules.Timeout +import org.junit.runner.RunWith + +/** + * End-to-end golden screenshot tests verifying UI rendering on a paired Projected display using + * [ProjectedScreenshotTestRule] and [captureProjectedDisplayToBitmap]. + */ +@RunWith(AndroidJUnit4::class) +@LargeTest +@OptIn(ExperimentalProjectedApi::class) +class ProjectedDisplayScreenshotTest { + + @get:Rule(order = 0) val screenshotRule = ProjectedScreenshotTestRule(GOLDEN_PATH) + + @get:Rule(order = 1) val timeout: Timeout = Timeout.seconds(60) + + @Test + fun projectedActivity_rendersOnProjectedDisplay_matchesGolden() { + val targetContext = InstrumentationRegistry.getInstrumentation().targetContext + val projectedOptions = ProjectedContext.createProjectedActivityOptions(targetContext) + val intent = Intent(targetContext, ProjectedDisplayTestActivity::class.java) + ActivityScenario.launch<ProjectedDisplayTestActivity>(intent, projectedOptions.toBundle()) + .use { scenario -> + var expectedWidth = 0 + var expectedHeight = 0 + scenario.onActivity { activity -> + val bounds = activity.windowManager.currentWindowMetrics.bounds + expectedWidth = bounds.width() + expectedHeight = bounds.height() + activity.setContentView(createProjectedCardView(activity)) + } + + val screenshot = captureProjectedDisplayToBitmap() + + try { + assertThat(screenshot.width).isEqualTo(expectedWidth) + assertThat(screenshot.height).isEqualTo(expectedHeight) + screenshot.assertAgainstGolden(screenshotRule, "projected_display_basic") + } finally { + screenshot.recycle() + } + } + } + + private fun createProjectedCardView(activity: ProjectedDisplayTestActivity): View { + val density = activity.resources.displayMetrics.density + fun dp(value: Int): Int = (value * density).toInt() + + val root = + FrameLayout(activity).apply { + setBackgroundColor(Color.BLACK) + layoutParams = + ViewGroup.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT, + ) + } + + val cardBackground = + GradientDrawable().apply { + setColor(Color.rgb(30, 32, 40)) + cornerRadius = dp(20).toFloat() + setStroke(dp(2), Color.rgb(66, 133, 244)) + } + + val card = + LinearLayout(activity).apply { + orientation = LinearLayout.VERTICAL + gravity = Gravity.CENTER_HORIZONTAL + background = cardBackground + setPadding(dp(24), dp(20), dp(24), dp(20)) + layoutParams = + FrameLayout.LayoutParams(dp(340), ViewGroup.LayoutParams.WRAP_CONTENT).apply { + gravity = Gravity.CENTER + } + } + + val accentBar = + View(activity).apply { + setBackgroundColor(Color.rgb(52, 168, 83)) + layoutParams = + LinearLayout.LayoutParams(dp(120), dp(8)).apply { bottomMargin = dp(16) } + } + + val title = + TextView(activity).apply { + text = "Projected Display" + setTextColor(Color.WHITE) + setTextSize(TypedValue.COMPLEX_UNIT_DIP, 22f) + typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD) + gravity = Gravity.CENTER + } + + val subtitle = + TextView(activity).apply { + text = "AndroidX XR Screenshot Test" + setTextColor(Color.rgb(180, 210, 255)) + setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14f) + typeface = Typeface.SANS_SERIF + gravity = Gravity.CENTER + layoutParams = + LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT, + ) + .apply { topMargin = dp(8) } + } + + card.addView(accentBar) + card.addView(title) + card.addView(subtitle) + root.addView(card) + return root + } + + private companion object { + const val GOLDEN_PATH = "xr/projected/integration-tests/xr-integration-tests" + } +}
diff --git a/xr/testutils/src/main/kotlin/androidx/xr/testutils/ProjectedScreenshotTestRule.kt b/xr/testutils/src/main/kotlin/androidx/xr/testutils/ProjectedScreenshotTestRule.kt new file mode 100644 index 0000000..25da23b --- /dev/null +++ b/xr/testutils/src/main/kotlin/androidx/xr/testutils/ProjectedScreenshotTestRule.kt
@@ -0,0 +1,452 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.xr.testutils + +import android.app.UiAutomation +import android.companion.virtual.VirtualDeviceManager +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.Rect +import android.hardware.display.DisplayManager +import android.os.Build +import android.os.Looper +import android.os.ParcelFileDescriptor +import android.os.SystemClock +import android.util.Log +import androidx.annotation.RequiresApi +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.screenshot.matchers.BitmapMatcher +import androidx.xr.testutils.runtime.cpm.executeSceneShellCommand +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TimeSource +import org.junit.Assume + +/** + * Instrumentation runner argument key that, when set to `"true"`, causes + * [ProjectedScreenshotTestRule] to wait for a paired Projected device to connect and throw an + * [AssertionError] instead of skipping via [Assume] if none becomes available. + * + * Example usage: + * ``` + * ./gradlew :xr:projected:integration-tests:xr-integration-tests:connectedDebugAndroidTest \ + * -Pandroid.testInstrumentationRunnerArguments.requireProjectedDevice=true + * ``` + */ +public const val REQUIRE_PROJECTED_DEVICE_ARG: String = "requireProjectedDevice" + +/** + * Host-independent device suffix appended to golden filenames for Projected screenshot tests + * (`<goldenIdentifier>_xr_projected.png`), decoupling golden names from the companion phone's + * [Build.MODEL]. + * + * Goldens recorded with this suffix target the canonical CI Projected emulator display profile + * (`cf_x86_64_glasses`, `450x394` at `160 dpi`). Projected displays with a different native + * resolution or density (such as physical glasses hardware or alternate emulator profiles) are not + * currently distinguished by this suffix and will mismatch emulator-pair goldens. + */ +public const val PROJECTED_DEVICE_MODEL: String = "xr_projected" + +internal const val PROJECTED_DEVICE_NAME_PREFIX: String = "ProjectionDevice" +internal const val PROJECTED_DISPLAY_NAME: String = "ProjectionDisplay" + +private const val TAG = "ProjectedScreenshotTestRule" +private const val DUMPSYS_SURFACEFLINGER_DISPLAY_ID_CMD = "dumpsys SurfaceFlinger --display-id" +private val DEFAULT_PROJECTED_CONNECTION_TIMEOUT = 15.seconds +private val DEFAULT_PROJECTED_CONNECTION_POLL_INTERVAL = 250.milliseconds +private val SURFACE_FLINGER_PROJECTED_DISPLAY_REGEX = + Regex("""^\s*Display\s+(\d+)\b.*displayName="$PROJECTED_DISPLAY_NAME"(?:\s|$)""") + +/** + * [XrScreenshotTestRule] subclass for AndroidX screenshot tests running on paired Companion Phone + + * Glasses Projected setups. + * + * * **Projected device gating**: Verifies that a paired Projected virtual device + * (`ProjectionDevice*`) with an active `ProjectionDisplay` virtual display is present, keeping + * Projected tests cleanly isolated from standalone spatial XR headsets (`XrScreenshotTestRule`). + * Skips cleanly via [Assume] on unpaired phones (such as single-device FTL runs) and headsets, + * unless [requireProjectedDevice] (or `-e requireProjectedDevice true`) is enabled, in which case + * the rule waits up to 15 seconds for connection and fails with [AssertionError] if unavailable. + * * **Host-independent golden naming (emulator display profile)**: Overrides [getDeviceModel] to + * return [PROJECTED_DEVICE_MODEL] (`"xr_projected"`) so golden filenames + * (`<goldenId>_xr_projected.png`) do not vary across host phone models (e.g., Cuttlefish vs. + * Pixel). Note that goldens remain tied to the canonical CI Projected emulator display profile + * (`cf_x86_64_glasses`, `450x394` at `160 dpi`) and are intended for that emulator pair rather + * than arbitrary Projected display sizes/densities. + * * **No headset SystemUI AppOps mutation**: Disables `com.android.systemui` `TOAST_WINDOW` AppOps + * suppression so the host phone's SystemUI settings are untouched. + * * **Shared XR staging & matching**: Inherits [updateGoldens] staging under + * [stagedGoldensDirectory], hardware-to-software bitmap conversion, crop-size tolerance, and + * [XrSsimMatcher] defaults from [XrScreenshotTestRule], and works directly with + * [Bitmap.assertAgainstGolden] and [captureProjectedDisplayToBitmap]. + * + * @param moduleDirectory Relative path to the module containing the tests (e.g., + * `"xr/projected/integration-tests/xr-integration-tests"`). + * @param updateGoldens When `true`, stages captured bitmaps for missing or mismatched goldens and + * does not throw [AssertionError]. Defaults to reading the [UPDATE_GOLDENS_ARG] instrumentation + * argument. + * @param defaultMatcher Default [BitmapMatcher] used when calling `assertAgainstGolden` without an + * explicit matcher or calling the two-argument [assertBitmapAgainstGolden] overload. Defaults to + * [XrSsimMatcher]. + * @param requireProjectedDevice When `true`, waits for a Projected device to connect and throws + * [AssertionError] if unavailable instead of skipping via [Assume]. Defaults to reading the + * [REQUIRE_PROJECTED_DEVICE_ARG] instrumentation argument. + */ +public class ProjectedScreenshotTestRule +internal constructor( + moduleDirectory: String, + updateGoldens: Boolean, + defaultMatcher: BitmapMatcher = XrSsimMatcher(), + private val requireProjectedDevice: Boolean, + private val connectionTimeout: Duration = DEFAULT_PROJECTED_CONNECTION_TIMEOUT, + private val connectionPollInterval: Duration = DEFAULT_PROJECTED_CONNECTION_POLL_INTERVAL, + private val isProjectedDeviceAvailable: () -> Boolean, + private val sleeper: (Long) -> Unit = SystemClock::sleep, + private val timeSource: TimeSource = TimeSource.Monotonic, + shellCommandExecutor: (String) -> String = { "" }, +) : + XrScreenshotTestRule( + moduleDirectory = moduleDirectory, + updateGoldens = updateGoldens, + defaultMatcher = defaultMatcher, + shellCommandExecutor = shellCommandExecutor, + ) { + + @JvmOverloads + public constructor( + moduleDirectory: String, + updateGoldens: Boolean = isUpdateGoldensArgumentEnabled(), + defaultMatcher: BitmapMatcher = XrSsimMatcher(), + requireProjectedDevice: Boolean = isRequireProjectedDeviceArgumentEnabled(), + ) : this( + moduleDirectory = moduleDirectory, + updateGoldens = updateGoldens, + defaultMatcher = defaultMatcher, + requireProjectedDevice = requireProjectedDevice, + isProjectedDeviceAvailable = { isProjectedDeviceConnected() }, + ) + + override fun shouldSuppressSystemUiToasts(): Boolean = false + + /** + * Returns [PROJECTED_DEVICE_MODEL] (`"xr_projected"`), decoupling golden filenames from the + * companion phone's [Build.MODEL] for the canonical Projected emulator pair (`450x394`, `160 + * dpi`). + */ + override fun getDeviceModel(): String = PROJECTED_DEVICE_MODEL + + override fun assumeSupportedDevice() { + if (!requireProjectedDevice) { + Assume.assumeTrue( + "No paired Projected device connected; pass " + + "-e $REQUIRE_PROJECTED_DEVICE_ARG true to fail instead of skipping.", + isProjectedDeviceAvailable(), + ) + return + } + val start = timeSource.markNow() + while (!isProjectedDeviceAvailable()) { + if (start.elapsedNow() >= connectionTimeout) { + throw AssertionError( + "Projected device did not connect within $connectionTimeout " + + "($REQUIRE_PROJECTED_DEVICE_ARG=true)" + ) + } + sleeper(connectionPollInterval.inWholeMilliseconds) + } + } +} + +/** + * Captures the paired Projected virtual display (`ProjectionDisplay`) from SurfaceFlinger via + * `screencap -d <sf_display_id> -p`, waits for consecutive frames to stabilize, optionally crops to + * [cropBounds] (or foreground content when [autoCrop] is `true`), and returns a software-backed + * [Bitmap.Config.ARGB_8888] [Bitmap] for assertion with [ProjectedScreenshotTestRule]. + * + * Unlike zero-arg [UiAutomation.takeScreenshot] (which captures the host phone's default display, + * `displayId = 0`), targeting `ProjectionDisplay`'s SurfaceFlinger display ID captures the full + * projected display composition, including dialogs, popups, and `SurfaceView` layers. + * + * The caller owns the returned [Bitmap] and is responsible for calling [Bitmap.recycle] when + * finished. + * + * @param cropBounds Optional [Rect] in display pixel coordinates to crop from the captured frame. + * @param padding Extra padding in pixels to preserve around cropped foreground bounds when + * [cropBounds] is `null` and [autoCrop] is `true`. + * @param autoCrop When `true` and [cropBounds] is `null`, automatically crops out the background + * via [cropForeground]. Defaults to `false` so the full `ProjectionDisplay` viewport is asserted. + * @param timeout Maximum duration to wait for `ProjectionDisplay` to appear and consecutive frames + * to stabilize. If frames do not stabilize before [timeout], the latest frame is returned and a + * warning is logged. + * @param pollInterval Delay between successive display captures. + * @param uiAutomation The [UiAutomation] instance used to execute SurfaceFlinger and `screencap` + * shell commands. + * @return A software-backed [Bitmap.Config.ARGB_8888] [Bitmap] owned by the caller. + * @throws IllegalArgumentException if [padding] is negative or [cropBounds] does not overlap the + * captured bitmap. + * @throws AssertionError if `ProjectionDisplay` cannot be found or no frame could be captured + * within [timeout]. + */ +@JvmOverloads +public fun captureProjectedDisplayToBitmap( + cropBounds: Rect? = null, + padding: Int = 0, + autoCrop: Boolean = false, + timeout: Duration = 5.seconds, + pollInterval: Duration = 100.milliseconds, + uiAutomation: UiAutomation = InstrumentationRegistry.getInstrumentation().uiAutomation, +): Bitmap { + require(padding >= 0) { "padding must be non-negative, was $padding" } + if (Looper.myLooper() != Looper.getMainLooper()) { + InstrumentationRegistry.getInstrumentation().waitForIdleSync() + } + var lastCaptureError: Throwable? = null + return captureProjectedDisplayToBitmap( + cropBounds = cropBounds, + padding = padding, + autoCrop = autoCrop, + timeout = timeout, + pollInterval = pollInterval, + displayIdDumpProvider = { + executeSceneShellCommand(DUMPSYS_SURFACEFLINGER_DISPLAY_ID_CMD, uiAutomation) + }, + frameProvider = { sfDisplayId -> + captureSurfaceFlingerDisplayBitmap( + sfDisplayId = sfDisplayId, + uiAutomation = uiAutomation, + onError = { lastCaptureError = it }, + ) + ?.also { lastCaptureError = null } + }, + failureCause = { lastCaptureError }, + ) +} + +internal fun captureProjectedDisplayToBitmap( + cropBounds: Rect? = null, + padding: Int = 0, + autoCrop: Boolean = false, + timeout: Duration = 5.seconds, + pollInterval: Duration = 100.milliseconds, + displayIdDumpProvider: () -> String, + frameProvider: (String) -> Bitmap?, + sleeper: (Long) -> Unit = SystemClock::sleep, + timeSource: TimeSource = TimeSource.Monotonic, + failureCause: () -> Throwable? = { null }, +): Bitmap { + require(padding >= 0) { "padding must be non-negative, was $padding" } + var cachedDisplayId: String? = null + var lastResolvedDisplayId: String? = null + var lastDisplayDump = "" + val settledBitmap = + waitForSettledSoftwareScreenshot( + screenshotProvider = { + val displayId = + cachedDisplayId + ?: run { + val dump = displayIdDumpProvider() + lastDisplayDump = dump + parseProjectedSurfaceFlingerDisplayId(dump).also { + cachedDisplayId = it + lastResolvedDisplayId = it + } + } + if (displayId == null) { + null + } else { + val bitmap = frameProvider(displayId) + if (bitmap == null) { + // Re-query SurfaceFlinger on the next poll in case the virtual display was + // recreated with a new display ID. + cachedDisplayId = null + } + bitmap + } + }, + timeout = timeout, + pollInterval = pollInterval, + timeSource = timeSource, + sleepMillis = sleeper, + failureMessage = { + val displayId = lastResolvedDisplayId + if (displayId == null) { + "Timed out after $timeout waiting for SurfaceFlinger display " + + "\"$PROJECTED_DISPLAY_NAME\" in '$DUMPSYS_SURFACEFLINGER_DISPLAY_ID_CMD' " + + "output:\n$lastDisplayDump" + } else { + "Timed out after $timeout waiting for 'screencap -d $displayId -p' on " + + "\"$PROJECTED_DISPLAY_NAME\" to return a non-null Bitmap" + } + }, + failureCause = failureCause, + ) + return applyScreenshotCrop(settledBitmap, cropBounds, padding, autoCrop) +} + +/** + * Extracts the SurfaceFlinger display ID string for `"ProjectionDisplay"` from the output of + * `dumpsys SurfaceFlinger --display-id`. + * + * Returns the ID as a [String] because SurfaceFlinger virtual display IDs are unsigned 64-bit + * integers that can exceed [Long.MAX_VALUE]. When multiple matching entries exist, returns the last + * one. + */ +internal fun parseProjectedSurfaceFlingerDisplayId(dumpsysOutput: String): String? = + dumpsysOutput + .lineSequence() + .mapNotNull { line -> + SURFACE_FLINGER_PROJECTED_DISPLAY_REGEX.find(line)?.groupValues?.get(1) + } + .lastOrNull() + +private fun captureSurfaceFlingerDisplayBitmap( + sfDisplayId: String, + uiAutomation: UiAutomation, + onError: (Exception) -> Unit = {}, +): Bitmap? { + val command = "screencap -d $sfDisplayId -p" + return try { + val (stdoutBytes, stderrText) = executeBinaryShellCommand(command, uiAutomation) + if (stdoutBytes.isEmpty()) { + Log.w(TAG, "'$command' returned empty output (stderr=${stderrText.trim()})") + return null + } + val options = BitmapFactory.Options().apply { inPreferredConfig = Bitmap.Config.ARGB_8888 } + BitmapFactory.decodeByteArray(stdoutBytes, 0, stdoutBytes.size, options).also { decoded -> + if (decoded == null) { + Log.w( + TAG, + "Failed to decode PNG from '$command' (${stdoutBytes.size} bytes, " + + "stderr=${stderrText.trim()})", + ) + } + } + } catch (e: Exception) { + Log.w(TAG, "Error executing '$command'", e) + onError(e) + null + } +} + +private fun executeBinaryShellCommand( + command: String, + uiAutomation: UiAutomation, +): Pair<ByteArray, String> { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + val (stdout, stdin, stderr) = Api34ShellImpl.executeShellCommandRwe(uiAutomation, command) + return stdout.use { + stdin.use { + stderr.use { + // Close stdin immediately so the child process does not block waiting for + // input. + stdin.close() + val stdoutStream = ParcelFileDescriptor.AutoCloseInputStream(stdout) + val stderrStream = ParcelFileDescriptor.AutoCloseInputStream(stderr) + var stderrText = "" + var stderrError: Throwable? = null + val stderrThread = + Thread( + { + try { + stderrText = stderrStream.bufferedReader().readText() + } catch (t: Throwable) { + stderrError = t + } + }, + "ProjectedScreenshotStderrDrain", + ) + .apply { start() } + val stdoutBytes = + try { + stdoutStream.readBytes() + } catch (t: Throwable) { + runCatching { stderrStream.close() } + throw t + } finally { + try { + stderrThread.join() + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + } + } + stderrError?.let { error -> + if (stdoutBytes.isEmpty()) { + throw error + } + Log.w(TAG, "Error draining stderr for '$command'", error) + } + stdoutBytes to stderrText + } + } + } + } + val stdoutBytes = + uiAutomation.executeShellCommand(command).use { pfd -> + ParcelFileDescriptor.AutoCloseInputStream(pfd).use { it.readBytes() } + } + return stdoutBytes to "" +} + +@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) +private object Api34ShellImpl { + fun executeShellCommandRwe( + uiAutomation: UiAutomation, + command: String, + ): Array<ParcelFileDescriptor> = uiAutomation.executeShellCommandRwe(command) +} + +internal fun isProjectedDeviceConnected( + context: Context = InstrumentationRegistry.getInstrumentation().targetContext +): Boolean { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.VANILLA_ICE_CREAM) { + return false + } + return ProjectedDisplayApi35Impl.isProjectedDisplayAvailable(context) +} + +@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM) +private object ProjectedDisplayApi35Impl { + fun isProjectedDisplayAvailable(context: Context): Boolean { + val hostContext = + if (context.deviceId == Context.DEVICE_ID_DEFAULT) { + context + } else { + context.createDeviceContext(Context.DEVICE_ID_DEFAULT) + } + val virtualDeviceManager = + hostContext.getSystemService(VirtualDeviceManager::class.java) ?: return false + val displayManager = + hostContext.getSystemService(DisplayManager::class.java) ?: return false + val displays = displayManager.displays + return virtualDeviceManager.virtualDevices.any { device -> + device.name?.startsWith(PROJECTED_DEVICE_NAME_PREFIX) == true && + displays.any { display -> + display.name == PROJECTED_DISPLAY_NAME && + device.displayIds.contains(display.displayId) + } + } + } +} + +internal fun isRequireProjectedDeviceArgumentEnabled(): Boolean = runCatching { + InstrumentationRegistry.getArguments() + .getString(REQUIRE_PROJECTED_DEVICE_ARG) + .equals("true", ignoreCase = true) +} + .getOrDefault(false)
diff --git a/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneHelper.kt b/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneHelper.kt index 351446b..62eaa18 100644 --- a/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneHelper.kt +++ b/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneHelper.kt
@@ -202,34 +202,7 @@ maxWaitMs = max(MIN_SCREENSHOT_SCENE_SETTLE_WAIT_MS, timeout.inWholeMilliseconds), ) val settledBitmap = waitForSettledSoftwareScreenshot(uiAutomation, timeout, pollInterval) - if (cropBounds != null) { - val cropped = - try { - crop(settledBitmap, cropBounds) - } catch (t: Throwable) { - settledBitmap.recycle() - throw t - } - // createBitmap returns the source itself when the crop covers the whole bitmap. - if (cropped !== settledBitmap) { - settledBitmap.recycle() - } - return cropped - } - if (autoCrop) { - val cropped = - try { - cropForeground(settledBitmap, padding = padding) - } catch (t: Throwable) { - settledBitmap.recycle() - throw t - } - if (cropped !== settledBitmap) { - settledBitmap.recycle() - } - return cropped - } - return settledBitmap + return applyScreenshotCrop(settledBitmap, cropBounds, padding, autoCrop) } /**
diff --git a/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneScreenshotUtils.kt b/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneScreenshotUtils.kt index 9b786c4..1ee386d 100644 --- a/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneScreenshotUtils.kt +++ b/xr/testutils/src/main/kotlin/androidx/xr/testutils/SpatialSceneScreenshotUtils.kt
@@ -188,6 +188,11 @@ pollInterval: Duration, timeSource: TimeSource = TimeSource.Monotonic, sleepMillis: (Long) -> Unit = SystemClock::sleep, + failureMessage: () -> String = { + "Timed out after $timeout waiting for UiAutomation.takeScreenshot() to " + + "return a non-null Bitmap" + }, + failureCause: () -> Throwable? = { null }, ): Bitmap { val start = timeSource.markNow() val stabilityMatcher = MSSIMMatcher(threshold = FRAME_STABILITY_MSSIM_THRESHOLD) @@ -275,10 +280,7 @@ previousBitmap = null return it } - throw AssertionError( - "Timed out after $timeout waiting for UiAutomation.takeScreenshot() to " + - "return a non-null Bitmap" - ) + throw AssertionError(failureMessage(), failureCause()) } sleepMillis(pollInterval.inWholeMilliseconds) } @@ -292,3 +294,43 @@ throw t } } + +/** + * Applies optional [cropBounds] or [autoCrop] to [settledBitmap], recycling [settledBitmap] if a + * distinct cropped [Bitmap] is produced or if cropping throws. + */ +internal fun applyScreenshotCrop( + settledBitmap: Bitmap, + cropBounds: Rect?, + padding: Int, + autoCrop: Boolean, +): Bitmap { + if (cropBounds != null) { + val cropped = + try { + crop(settledBitmap, cropBounds) + } catch (t: Throwable) { + settledBitmap.recycle() + throw t + } + // createBitmap returns the source itself when the crop covers the whole bitmap. + if (cropped !== settledBitmap) { + settledBitmap.recycle() + } + return cropped + } + if (autoCrop) { + val cropped = + try { + cropForeground(settledBitmap, padding = padding) + } catch (t: Throwable) { + settledBitmap.recycle() + throw t + } + if (cropped !== settledBitmap) { + settledBitmap.recycle() + } + return cropped + } + return settledBitmap +}
diff --git a/xr/testutils/src/main/kotlin/androidx/xr/testutils/XrScreenshotTestRule.kt b/xr/testutils/src/main/kotlin/androidx/xr/testutils/XrScreenshotTestRule.kt index 0acbead..6a4cd25 100644 --- a/xr/testutils/src/main/kotlin/androidx/xr/testutils/XrScreenshotTestRule.kt +++ b/xr/testutils/src/main/kotlin/androidx/xr/testutils/XrScreenshotTestRule.kt
@@ -67,14 +67,16 @@ Regex("(?:TOAST_WINDOW|Uid mode):\\s*(allow|ignore|deny|default)\\b") /** - * [ScreenshotTestRule] for AndroidX tests running on XR devices. + * [ScreenshotTestRule] for AndroidX tests running on standalone spatial XR headsets. * * Uses the same golden repository root and [moduleDirectory] layout as * `AndroidXScreenshotTestRule`, but runs on any device with the XR spatial feature instead of only - * on API 35 emulators. Use it with [assertAgainstGolden] or [assertBitmapAgainstGolden] - * (`androidx.xr.testutils`). While a test is executing on an XR device, `com.android.systemui` - * `TOAST_WINDOW` overlays (such as the post-wake input-recovery toast) are temporarily suppressed - * via AppOps so transient system toasts cannot pollute compositor captures or auto-cropped bounds. + * on API 35 emulators. For paired Companion Phone + Glasses Projected setups, use + * [ProjectedScreenshotTestRule] instead. Use either rule with [assertAgainstGolden] or + * [assertBitmapAgainstGolden] (`androidx.xr.testutils`). While a test is executing on a spatial XR + * device, `com.android.systemui` `TOAST_WINDOW` overlays (such as the post-wake input-recovery + * toast) are temporarily suppressed via AppOps so transient system toasts cannot pollute compositor + * captures or auto-cropped bounds. * * When a golden is missing or mismatched, the captured bitmap is staged under * [stagedGoldensDirectory] using its repository-relative path so that it can be pulled directly @@ -108,7 +110,7 @@ * explicit matcher or calling the two-argument [assertBitmapAgainstGolden] overload. Defaults to * [XrSsimMatcher]. */ -public class XrScreenshotTestRule +public open class XrScreenshotTestRule internal constructor( moduleDirectory: String, private val updateGoldens: Boolean, @@ -146,10 +148,21 @@ public val stagedGoldensDirectory: File get() = File(deviceOutputDirectory, GOLDENS_SUBDIRECTORY) + /** + * Returns whether `com.android.systemui` `TOAST_WINDOW` overlays should be suppressed via + * AppOps around each test. Enabled on spatial XR headsets to block wake-up input-recovery + * toasts from polluting compositor captures. + */ + protected open fun shouldSuppressSystemUiToasts(): Boolean = isXrDevice() + override fun apply(base: Statement, description: Description?): Statement { val toastSuppressedStatement = object : Statement() { override fun evaluate() { + if (!shouldSuppressSystemUiToasts()) { + base.evaluate() + return + } val previousMode = querySystemUiToastWindowMode() shellCommandExecutor(IGNORE_SYSTEMUI_TOAST_APPOP_CMD) try { @@ -317,7 +330,7 @@ rule.assertBitmapAgainstGolden(this, goldenIdentifier, matcher) } -private fun isUpdateGoldensArgumentEnabled(): Boolean = runCatching { +internal fun isUpdateGoldensArgumentEnabled(): Boolean = runCatching { InstrumentationRegistry.getArguments().getString(UPDATE_GOLDENS_ARG)?.toBoolean() == true } .getOrDefault(false)
diff --git a/xr/testutils/src/test/assets/test_golden_xr_projected.png b/xr/testutils/src/test/assets/test_golden_xr_projected.png new file mode 100644 index 0000000..e1aabd8 --- /dev/null +++ b/xr/testutils/src/test/assets/test_golden_xr_projected.png Binary files differ
diff --git a/xr/testutils/src/test/kotlin/androidx/xr/testutils/ProjectedScreenshotTestRuleTest.kt b/xr/testutils/src/test/kotlin/androidx/xr/testutils/ProjectedScreenshotTestRuleTest.kt new file mode 100644 index 0000000..29f5485 --- /dev/null +++ b/xr/testutils/src/test/kotlin/androidx/xr/testutils/ProjectedScreenshotTestRuleTest.kt
@@ -0,0 +1,578 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package androidx.xr.testutils + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Color +import android.graphics.Rect +import android.os.Bundle +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.screenshot.matchers.PixelPerfectMatcher +import androidx.xr.runtime.manifest.FEATURE_XR_API_SPATIAL +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.TestTimeSource +import org.junit.After +import org.junit.AssumptionViolatedException +import org.junit.Before +import org.junit.Test +import org.junit.runner.Description +import org.junit.runner.RunWith +import org.junit.runners.model.Statement +import org.robolectric.Shadows +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowBuild + +@RunWith(AndroidJUnit4::class) +@Config(sdk = [34]) +class ProjectedScreenshotTestRuleTest { + + private lateinit var originalArguments: Bundle + private val createdOutputDirs = mutableListOf<File>() + + @Before + fun setUp() { + originalArguments = Bundle(InstrumentationRegistry.getArguments()) + ShadowBuild.setModel("Cuttlefish GMS x86_64") + setXrSystemFeature(false) + } + + @After + fun tearDown() { + InstrumentationRegistry.registerInstance( + InstrumentationRegistry.getInstrumentation(), + originalArguments, + ) + createdOutputDirs.forEach { it.deleteRecursively() } + } + + private fun setXrSystemFeature(enabled: Boolean) { + val context = ApplicationProvider.getApplicationContext<Context>() + Shadows.shadowOf(context.packageManager).setSystemFeature(FEATURE_XR_API_SPATIAL, enabled) + } + + private fun createSolidBitmap(color: Int, width: Int = 4, height: Int = 4): Bitmap = + Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply { eraseColor(color) } + + private fun createForegroundBitmap( + foregroundColor: Int, + width: Int = 16, + height: Int = 16, + ): Bitmap { + val pixels = IntArray(width * height) { Color.BLACK } + for (y in height / 4 until (height * 3) / 4) { + for (x in width / 4 until (width * 3) / 4) { + pixels[y * width + x] = foregroundColor + } + } + return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888) + } + + private fun runWithRule(rule: ProjectedScreenshotTestRule, block: () -> Unit) { + createdOutputDirs.add(rule.deviceOutputDirectory) + val description = + Description.createTestDescription( + ProjectedScreenshotTestRuleTest::class.java, + "sampleProjectedTest", + ) + rule + .apply( + object : Statement() { + override fun evaluate() { + block() + } + }, + description, + ) + .evaluate() + } + + @Test + fun assumeSupportedDevice_skipsWhenProjectedDisconnectedAndNotRequired() { + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = false, + requireProjectedDevice = false, + isProjectedDeviceAvailable = { false }, + ) + var bodyExecuted = false + + assertFailsWith<AssumptionViolatedException> { + runWithRule(rule) { bodyExecuted = true } + } + assertFalse(bodyExecuted) + } + + @Test + fun assumeSupportedDevice_skipsOnSpatialHeadsetWhenProjectedDisconnected() { + setXrSystemFeature(true) + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = false, + requireProjectedDevice = false, + isProjectedDeviceAvailable = { false }, + ) + var bodyExecuted = false + + assertFailsWith<AssumptionViolatedException> { + runWithRule(rule) { bodyExecuted = true } + } + assertFalse(bodyExecuted) + } + + @Test + fun assumeSupportedDevice_runsWhenProjectedConnectedWithoutSpatialFeature() { + setXrSystemFeature(false) + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = false, + requireProjectedDevice = false, + isProjectedDeviceAvailable = { true }, + ) + var bodyExecuted = false + + runWithRule(rule) { bodyExecuted = true } + assertTrue(bodyExecuted) + } + + @Test + fun assumeSupportedDevice_whenRequired_pollsUntilProjectedConnects() { + val timeSource = TestTimeSource() + var checks = 0 + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = false, + requireProjectedDevice = true, + connectionTimeout = 2.seconds, + connectionPollInterval = 250.milliseconds, + isProjectedDeviceAvailable = { + checks++ + checks >= 3 + }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + var bodyExecuted = false + + runWithRule(rule) { bodyExecuted = true } + assertTrue(bodyExecuted) + assertEquals(3, checks) + } + + @Test + fun assumeSupportedDevice_whenRequired_throwsAssertionErrorOnTimeout() { + val timeSource = TestTimeSource() + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = false, + requireProjectedDevice = true, + connectionTimeout = 1.seconds, + connectionPollInterval = 250.milliseconds, + isProjectedDeviceAvailable = { false }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + var bodyExecuted = false + + val error = assertFailsWith<AssertionError> { runWithRule(rule) { bodyExecuted = true } } + assertFalse(bodyExecuted) + assertTrue(error.message.orEmpty().contains(REQUIRE_PROJECTED_DEVICE_ARG)) + } + + @Test + fun requireProjectedDeviceArgument_defaultsFromInstrumentationArguments() { + assertFalse(isRequireProjectedDeviceArgumentEnabled()) + + val trueArgs = + Bundle(originalArguments).apply { putString(REQUIRE_PROJECTED_DEVICE_ARG, "TRUE") } + InstrumentationRegistry.registerInstance( + InstrumentationRegistry.getInstrumentation(), + trueArgs, + ) + assertTrue(isRequireProjectedDeviceArgumentEnabled()) + + val falseArgs = + Bundle(originalArguments).apply { putString(REQUIRE_PROJECTED_DEVICE_ARG, "false") } + InstrumentationRegistry.registerInstance( + InstrumentationRegistry.getInstrumentation(), + falseArgs, + ) + assertFalse(isRequireProjectedDeviceArgumentEnabled()) + } + + @Test + fun isProjectedDeviceConnected_returnsFalseBelowApi35() { + assertFalse(isProjectedDeviceConnected()) + } + + @Test + fun assertBitmapAgainstGolden_usesHostIndependentProjectedSuffix() { + val bitmap = createSolidBitmap(Color.BLUE) + try { + for (hostModel in listOf("Cuttlefish GMS x86_64", "Pixel 9")) { + ShadowBuild.setModel(hostModel) + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = true, + requireProjectedDevice = false, + isProjectedDeviceAvailable = { true }, + ) + runWithRule(rule) { + bitmap.assertAgainstGolden(rule, "host_independent", PixelPerfectMatcher()) + } + val expectedStagedFile = + File( + rule.stagedGoldensDirectory, + "xr/testutils/host_independent_$PROJECTED_DEVICE_MODEL.png", + ) + assertTrue( + expectedStagedFile.exists(), + "Expected staged golden at $expectedStagedFile for host model '$hostModel'", + ) + } + } finally { + bitmap.recycle() + } + } + + @Test + fun assertAgainstGolden_matchesProjectedGoldenAndDeletesStagedFile() { + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = false, + requireProjectedDevice = false, + isProjectedDeviceAvailable = { true }, + ) + val stagedFile = + File( + rule.stagedGoldensDirectory, + "xr/testutils/test_golden_$PROJECTED_DEVICE_MODEL.png", + ) + stagedFile.parentFile?.mkdirs() + stagedFile.writeBytes(byteArrayOf(1, 2, 3)) + assertTrue(stagedFile.exists()) + + val matchingBitmap = createSolidBitmap(Color.RED) + val mismatchedBitmap = createSolidBitmap(Color.BLUE) + try { + runWithRule(rule) { + matchingBitmap.assertAgainstGolden(rule, "test_golden") + assertFalse(stagedFile.exists()) + + val error = + assertFailsWith<AssertionError> { + mismatchedBitmap.assertAgainstGolden(rule, "test_golden") + } + assertTrue(stagedFile.exists()) + assertTrue( + error.message + .orEmpty() + .contains("xr/testutils/test_golden_$PROJECTED_DEVICE_MODEL.png") + ) + } + } finally { + matchingBitmap.recycle() + mismatchedBitmap.recycle() + } + } + + @Test + fun apply_neverModifiesSystemUiToastWindowAppOp() { + setXrSystemFeature(true) + val executedCommands = mutableListOf<String>() + val rule = + ProjectedScreenshotTestRule( + moduleDirectory = "xr/testutils", + updateGoldens = false, + requireProjectedDevice = false, + isProjectedDeviceAvailable = { true }, + shellCommandExecutor = { cmd -> + executedCommands.add(cmd) + "TOAST_WINDOW: allow" + }, + ) + + assertFailsWith<IllegalStateException> { + runWithRule(rule) { throw IllegalStateException("simulated test failure") } + } + assertTrue(executedCommands.isEmpty()) + } + + @Test + fun parseProjectedSurfaceFlingerDisplayId_extractsUnsigned64BitProjectionDisplayId() { + val dumpsysOutput = + """ + Display 4619827353912518656 (HWC display 0): port=0 pnpId=GGL screenPartStatus=UNSUPPORTED displayName="CrosvmDisplay" + Display 11529215047487655091 (Virtual display): displayName="ProjectionDisplay" uniqueId="virtual:com.google.android.glasses.core,10127,ProjectionDisplay,0" + Display 11529215048416665975 (Virtual display): displayName="ProjectionDisplaySysui" uniqueId="virtual:com.google.android.glasses.core,10127,ProjectionDisplaySysui,1" + """ + .trimIndent() + + assertEquals("11529215047487655091", parseProjectedSurfaceFlingerDisplayId(dumpsysOutput)) + } + + @Test + fun parseProjectedSurfaceFlingerDisplayId_ignoresOtherProjectionDisplays() { + val dumpsysOutput = + """ + Display 4619827353912518656 (HWC display 0): port=0 displayName="CrosvmDisplay" + Display 11529215048416665975 (Virtual display): displayName="ProjectionDisplaySysui" + Display 11529215048416665976 (Virtual display): displayName="ProjectionDisplayLockscreen" + Display 11529215048416665977 (Virtual display): displayName="ProjectionDisplayRestricted" + Display 11529215048416665978 (Virtual display): displayName="ProjectionDisplayPhone" + """ + .trimIndent() + + assertNull(parseProjectedSurfaceFlingerDisplayId(dumpsysOutput)) + assertNull(parseProjectedSurfaceFlingerDisplayId("")) + } + + @Test + fun parseProjectedSurfaceFlingerDisplayId_prefersLastMatchingDisplay() { + val dumpsysOutput = + """ + Display 11529215047000000001 (Virtual display): displayName="ProjectionDisplay" + Display 11529215047000000002 (Virtual display): displayName="ProjectionDisplay" + """ + .trimIndent() + + assertEquals("11529215047000000002", parseProjectedSurfaceFlingerDisplayId(dumpsysOutput)) + } + + @Test + fun captureProjectedDisplayToBitmap_waitsForSettledFrameAndCachesDisplayId() { + val timeSource = TestTimeSource() + var dumpQueries = 0 + val requestedIds = mutableListOf<String>() + val frames = + ArrayDeque( + listOf( + createForegroundBitmap(Color.RED, width = 16, height = 16), + createForegroundBitmap(Color.GREEN, width = 16, height = 16), + createForegroundBitmap(Color.GREEN, width = 16, height = 16), + createForegroundBitmap(Color.GREEN, width = 16, height = 16), + ) + ) + + val result = + captureProjectedDisplayToBitmap( + timeout = 5.seconds, + pollInterval = 100.milliseconds, + displayIdDumpProvider = { + dumpQueries++ + "Display 11529215047487655091 (Virtual display): displayName=\"ProjectionDisplay\"" + }, + frameProvider = { id -> + requestedIds.add(id) + frames.removeFirst() + }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + try { + assertEquals(1, dumpQueries) + assertEquals( + listOf( + "11529215047487655091", + "11529215047487655091", + "11529215047487655091", + "11529215047487655091", + ), + requestedIds, + ) + assertEquals(16, result.width) + assertEquals(16, result.height) + assertEquals(Color.GREEN, result.getPixel(8, 8)) + } finally { + result.recycle() + } + } + + @Test + fun captureProjectedDisplayToBitmap_reQueriesDisplayIdAfterFailedCapture() { + val timeSource = TestTimeSource() + var dumpQueries = 0 + val requestedIds = mutableListOf<String>() + + val result = + captureProjectedDisplayToBitmap( + timeout = 5.seconds, + pollInterval = 100.milliseconds, + displayIdDumpProvider = { + dumpQueries++ + val id = if (dumpQueries == 1) "1001" else "2002" + "Display $id (Virtual display): displayName=\"ProjectionDisplay\"" + }, + frameProvider = { id -> + requestedIds.add(id) + if (id == "1001") { + null + } else { + createForegroundBitmap(Color.CYAN, width = 16, height = 16) + } + }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + try { + assertEquals(2, dumpQueries) + assertEquals(listOf("1001", "2002", "2002", "2002"), requestedIds) + assertEquals(Color.CYAN, result.getPixel(8, 8)) + } finally { + result.recycle() + } + } + + @Test + fun captureProjectedDisplayToBitmap_appliesCropBoundsAndAutoCrop() { + val timeSource = TestTimeSource() + val width = 40 + val height = 30 + fun makeFrame(): Bitmap { + val pixels = IntArray(width * height) { Color.BLACK } + for (y in 10 until 20) { + for (x in 15 until 25) { + pixels[y * width + x] = Color.YELLOW + } + } + return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888) + } + val dump = + "Display 11529215047487655091 (Virtual display): displayName=\"ProjectionDisplay\"" + + val autoCropped = + captureProjectedDisplayToBitmap( + autoCrop = true, + padding = 2, + displayIdDumpProvider = { dump }, + frameProvider = { makeFrame() }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + val explicitCropped = + captureProjectedDisplayToBitmap( + cropBounds = Rect(15, 10, 25, 20), + displayIdDumpProvider = { dump }, + frameProvider = { makeFrame() }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + try { + assertEquals(14, autoCropped.width) + assertEquals(14, autoCropped.height) + assertEquals(Color.YELLOW, autoCropped.getPixel(7, 7)) + + assertEquals(10, explicitCropped.width) + assertEquals(10, explicitCropped.height) + assertEquals(Color.YELLOW, explicitCropped.getPixel(5, 5)) + } finally { + autoCropped.recycle() + explicitCropped.recycle() + } + } + + @Test + fun captureProjectedDisplayToBitmap_rejectsNegativePadding() { + assertFailsWith<IllegalArgumentException> { + captureProjectedDisplayToBitmap( + padding = -1, + displayIdDumpProvider = { "" }, + frameProvider = { null }, + ) + } + } + + @Test + fun captureProjectedDisplayToBitmap_throwsDiagnosticErrorWhenDisplayMissing() { + val timeSource = TestTimeSource() + val error = + assertFailsWith<AssertionError> { + captureProjectedDisplayToBitmap( + timeout = 300.milliseconds, + pollInterval = 100.milliseconds, + displayIdDumpProvider = { + "Display 4619827353912518656 (HWC display 0): displayName=\"CrosvmDisplay\"" + }, + frameProvider = { null }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + } + assertTrue(error.message.orEmpty().contains(PROJECTED_DISPLAY_NAME)) + assertTrue(error.message.orEmpty().contains("CrosvmDisplay")) + } + + @Test + fun captureProjectedDisplayToBitmap_throwsDiagnosticErrorWhenScreencapFails() { + val timeSource = TestTimeSource() + val error = + assertFailsWith<AssertionError> { + captureProjectedDisplayToBitmap( + timeout = 300.milliseconds, + pollInterval = 100.milliseconds, + displayIdDumpProvider = { + "Display 11529215047487655091 (Virtual display): displayName=\"ProjectionDisplay\"" + }, + frameProvider = { null }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + ) + } + assertTrue(error.message.orEmpty().contains("screencap -d 11529215047487655091 -p")) + } + + @Test + fun captureProjectedDisplayToBitmap_attachesFailureCauseOnTimeout() { + val timeSource = TestTimeSource() + val expectedCause = SecurityException("shell command denied") + var lastError: Throwable? = null + val error = + assertFailsWith<AssertionError> { + captureProjectedDisplayToBitmap( + timeout = 300.milliseconds, + pollInterval = 100.milliseconds, + displayIdDumpProvider = { + "Display 11529215047487655091 (Virtual display): displayName=\"ProjectionDisplay\"" + }, + frameProvider = { + lastError = expectedCause + null + }, + sleeper = { ms -> timeSource += ms.milliseconds }, + timeSource = timeSource, + failureCause = { lastError }, + ) + } + assertEquals(expectedCause, error.cause) + } +}