From 3bd9574c261ac5c18963a5b24911a263bbb0692a Mon Sep 17 00:00:00 2001 From: Siubeng Date: Sun, 15 Nov 2026 00:21:55 +0000 Subject: [PATCH] feat: embed plugin settings with schema and Remote Compose --- common/build.gradle.kts | 5 + .../projection/plugin/PluginSettingsClient.kt | 83 +++++++ .../projection/plugin/ProjectionPlugins.kt | 14 +- .../moe/feng/wheelplay/WheelPlayActivity.kt | 21 +- .../settings/PluginSettingsDialog.kt | 203 +++++++++++++++++ .../settings/RemoteComposeSettings.kt | 110 +++++++++ .../res/values-zh-rCN/settings_strings.xml | 13 ++ .../res/values-zh-rTW/settings_strings.xml | 13 ++ .../src/main/res/values/settings_strings.xml | 13 ++ .../plugin/ProjectionPluginRegistryTest.kt | 35 +++ .../feng/wheelplay/PluginSettingsUiTest.kt | 211 ++++++++++++++++++ docs/PLUGIN_SETTINGS.md | 148 ++++++++++++ docs/PROJECTION_PLUGINS.md | 6 +- docs/README.md | 1 + gradle/libs.versions.toml | 6 + .../wheelplay/plugin/ProjectionSettings.kt | 168 ++++++++++++++ .../plugin/ProjectionSettingsProvider.kt | 117 ++++++++++ .../plugin/ProjectionSettingsProviderTest.kt | 161 +++++++++++++ projection-plugin-sample/build.gradle.kts | 16 +- .../src/main/AndroidManifest.xml | 3 + .../plugin/sample/SampleProjectionService.kt | 16 +- .../plugin/sample/SampleSettingsActivity.kt | 2 +- .../plugin/sample/SampleSettingsProvider.kt | 74 ++++++ .../sample/SampleSettingsProviderTest.kt | 90 ++++++++ 24 files changed, 1515 insertions(+), 14 deletions(-) create mode 100644 common/src/main/java/com/shilapi/xcertplay/projection/plugin/PluginSettingsClient.kt create mode 100644 common/src/main/java/moe/feng/wheelplay/settings/PluginSettingsDialog.kt create mode 100644 common/src/main/java/moe/feng/wheelplay/settings/RemoteComposeSettings.kt create mode 100644 common/src/test/java/moe/feng/wheelplay/PluginSettingsUiTest.kt create mode 100644 docs/PLUGIN_SETTINGS.md create mode 100644 projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettings.kt create mode 100644 projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettingsProvider.kt create mode 100644 projection-plugin-api/src/test/java/moe/feng/wheelplay/plugin/ProjectionSettingsProviderTest.kt create mode 100644 projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProvider.kt create mode 100644 projection-plugin-sample/src/test/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProviderTest.kt diff --git a/common/build.gradle.kts b/common/build.gradle.kts index abbd9b1f..f7721ca6 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -33,6 +33,9 @@ android { } dependencies { + implementation(libs.androidx.remote.core) + implementation(libs.androidx.remote.player.core) + implementation(libs.androidx.remote.player.view) implementation("dev.rikka.shizuku:api:13.1.5") implementation("dev.rikka.shizuku:provider:13.1.5") implementation(project(":projection-plugin-api")) @@ -57,6 +60,8 @@ dependencies { implementation("androidx.lifecycle:lifecycle-runtime-compose:2.6.1") implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:2.6.1") testImplementation(libs.junit) + testImplementation(libs.androidx.remote.creation.android) + testImplementation(libs.androidx.remote.creation.core) testImplementation("androidx.compose.ui:ui-test-junit4") debugImplementation("androidx.compose.ui:ui-test-manifest") debugImplementation(libs.androidx.compose.ui.tooling) diff --git a/common/src/main/java/com/shilapi/xcertplay/projection/plugin/PluginSettingsClient.kt b/common/src/main/java/com/shilapi/xcertplay/projection/plugin/PluginSettingsClient.kt new file mode 100644 index 00000000..d91f966d --- /dev/null +++ b/common/src/main/java/com/shilapi/xcertplay/projection/plugin/PluginSettingsClient.kt @@ -0,0 +1,83 @@ +package com.shilapi.xcertplay.projection.plugin + +import android.content.Context +import android.content.pm.PackageManager +import android.os.Bundle +import moe.feng.wheelplay.plugin.* +import kotlinx.coroutines.suspendCancellableCoroutine +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.FutureTask +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit +import java.security.MessageDigest + +internal data class PluginSettingsSnapshot( + val schema: PluginSettingsSchema, + val supportsRemoteCompose: Boolean, + val document: PluginSettingsDocument?, + val conflict: Boolean = false, +) + +/** Blocking transport; callers must use a worker. No plugin classes cross this boundary. */ +internal class PluginSettingsClient( + private val context: Context, + val plugin: InstalledProjectionPlugin, + private val isRegistered: () -> Boolean, +) { + val uri = ProjectionSettings.uri(requireNotNull(plugin.settingsProvider)) + + suspend fun requestAsync(method: String, extras: Bundle): PluginSettingsSnapshot = suspendCancellableCoroutine { continuation -> + val task = FutureTask { + try { continuation.resumeWith(Result.success(request(method, extras))) } + catch (error: Exception) { continuation.resumeWith(Result.failure(error)) } + } + continuation.invokeOnCancellation { task.cancel(true); workers.remove(task) } + try { workers.execute(task) } + catch (error: Exception) { continuation.resumeWith(Result.failure(error)) } + } + + companion object { + // A hung provider cannot create an unbounded number of blocked host threads. + private val workers = ThreadPoolExecutor(2, 2, 30, TimeUnit.SECONDS, ArrayBlockingQueue(16), + { runnable -> Thread(runnable, "plugin-settings-io").apply { isDaemon = true } }) + } + + @Suppress("DEPRECATION") + fun checkIdentity() { + check(isRegistered()) { "Plugin changed or was removed" } + val pkg = context.packageManager.getPackageInfo(plugin.component.packageName, PackageManager.GET_SIGNING_CERTIFICATES) + check(pkg.lastUpdateTime == plugin.updatedAt && pkg.longVersionCode == plugin.version && + pkg.firstInstallTime == plugin.installedAt) { "Plugin was updated" } + val signer = pkg.signingInfo?.apkContentsSigners?.map { + MessageDigest.getInstance("SHA-256").digest(it.toByteArray()).joinToString("") { byte -> "%02x".format(byte) } + }?.sorted()?.joinToString(":").orEmpty() + check(signer.isNotEmpty() && signer == plugin.signer) { "Plugin signer changed" } + val provider = context.packageManager.resolveContentProvider(uri.authority!!, 0) + check(provider != null && provider.packageName == plugin.component.packageName && + provider.applicationInfo.uid == plugin.uid && provider.enabled && provider.exported && provider.applicationInfo.enabled) { + "Plugin settings provider unavailable" + } + } + + fun request(method: String = ProjectionSettings.GET, extras: Bundle = ProjectionSettings.request()): PluginSettingsSnapshot { + checkIdentity() + val response = requireNotNull(context.contentResolver.acquireUnstableContentProviderClient(uri)) { + "Plugin settings provider unavailable" + }.use { it.call(method, plugin.component.flattenToString(), extras) } + checkIdentity() // Discard replies from an APK that changed during the call. + requireNotNull(response) + require(response.getInt("version") == ProjectionSettings.VERSION) { "Unsupported settings protocol" } + val status = response.getString("status") + check(status == "ok" || status == "conflict") { + response.getString("message").orEmpty().take(256).ifBlank { "Plugin settings request failed" } + } + val schema = PluginSettingsSchema.fromJson(requireNotNull(response.getString("schema"))) + val document = response.getByteArray("remote_document")?.let { bytes -> + require(response.getString("remote_version") == ProjectionSettings.REMOTE_COMPOSE_VERSION) { + "Unsupported Remote Compose version" + } + PluginSettingsDocument(bytes, response.getInt("remote_width"), response.getInt("remote_height")) + } + return PluginSettingsSnapshot(schema, response.getBoolean("supports_remote"), document, status == "conflict") + } +} diff --git a/common/src/main/java/com/shilapi/xcertplay/projection/plugin/ProjectionPlugins.kt b/common/src/main/java/com/shilapi/xcertplay/projection/plugin/ProjectionPlugins.kt index 916ec70c..362ada8b 100644 --- a/common/src/main/java/com/shilapi/xcertplay/projection/plugin/ProjectionPlugins.kt +++ b/common/src/main/java/com/shilapi/xcertplay/projection/plugin/ProjectionPlugins.kt @@ -7,6 +7,7 @@ import android.os.Looper import android.os.Build import com.shilapi.xcertplay.projection.* import moe.feng.wheelplay.plugin.ProjectionPlugin +import moe.feng.wheelplay.plugin.ProjectionSettings import java.security.MessageDigest import java.util.concurrent.CompletableFuture import com.shilapi.xcertplay.shared.R as UiR @@ -22,6 +23,7 @@ internal data class InstalledProjectionPlugin( val problem: String?, val installedAt: Long = 0, val sourceId: String? = null, + val settingsProvider: String? = null, ) { val id get() = PREFIX + component.flattenToString() val consentKey get() = "$signer@$installedAt" @@ -117,9 +119,19 @@ internal class ProjectionPluginRegistry(private val context: Context, private va (it.permission == null || pm.checkPermission(it.permission, context.packageName) == PackageManager.PERMISSION_GRANTED) }?.let { activity } } + val settingsProvider = service.metaData?.getString(ProjectionSettings.META_PROVIDER)?.takeIf { + Regex("[A-Za-z][A-Za-z0-9_.]*").matches(it) + }?.takeIf { authority -> + pm.resolveContentProvider(authority, 0)?.let { + it.packageName == service.packageName && it.applicationInfo.uid == service.applicationInfo.uid && + it.exported && it.enabled && it.applicationInfo.enabled && + (it.readPermission == null || pm.checkPermission(it.readPermission, context.packageName) == PackageManager.PERMISSION_GRANTED) && + (it.writePermission == null || pm.checkPermission(it.writePermission, context.packageName) == PackageManager.PERMISSION_GRANTED) + } == true + } InstalledProjectionPlugin(component, service.loadLabel(pm).toString().take(120), service.applicationInfo.uid, signer, pkg.lastUpdateTime, pkg.longVersionCode, settings, problem, pkg.firstInstallTime, - service.metaData?.getString(ProjectionPlugin.META_SOURCE_ID)) + service.metaData?.getString(ProjectionPlugin.META_SOURCE_ID), settingsProvider) }.getOrNull() }.distinctBy { it.id }.sortedBy { it.name } failures.entries.removeAll { it.value.plugin !in installed } diff --git a/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt b/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt index fab3e364..473b54a3 100644 --- a/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt +++ b/common/src/main/java/moe/feng/wheelplay/WheelPlayActivity.kt @@ -8,6 +8,7 @@ import com.shilapi.xcertplay.projection.ProjectionSourceIds import com.shilapi.xcertplay.projection.projectionSessions import com.shilapi.xcertplay.projection.plugin.projectionPlugins import com.shilapi.xcertplay.projection.plugin.RemotePluginSession +import com.shilapi.xcertplay.projection.plugin.InstalledProjectionPlugin import com.shilapi.xcertplay.projection.ProjectionSession import moe.feng.wheelplay.plugin.ProjectionPlugin import com.shilapi.xcertplay.projection.registerProjectionSources @@ -72,6 +73,7 @@ class WheelPlayActivity : AppCompatActivity() { private val settingsModel by lazy { ViewModelProvider(this)[SettingsViewModel::class.java] } private val settingsDialogs = SettingsDialogHost() private var webBusy = false + private var embeddedPlugin by mutableStateOf(null) private var awaitingTeslaVpnConsent = false private val localAndroidAutoSettings = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (!isFinishing && !isDestroyed) showLocalAndroidAutoSetup() @@ -330,6 +332,15 @@ class WheelPlayActivity : AppCompatActivity() { refreshSettings() setContent { WheelPlayScreen(page, aaConnection, uiState, settingsModel, settingsActions, settingsDialogs, dialogs, snackbar, ::dispatch) + embeddedPlugin?.let { plugin -> key(plugin) { + PluginSettingsDialog(plugin, lifecycle, onDismiss = { embeddedPlugin = null }, + onExternal = plugin.settings?.let { component -> { + embeddedPlugin = null + if (projectionPlugins(this).entries().contains(plugin)) + runCatching { startActivity(Intent().setComponent(component)) } + .onFailure { toast(getString(UiR.string.plugin_unavailable)) } + } }) + } } } } @@ -390,9 +401,10 @@ class WheelPlayActivity : AppCompatActivity() { refreshUiState() } UiAction.PLUGIN_DISABLE -> { registry.setEnabled(plugin, false); refreshUiState() } - UiAction.PLUGIN_SETTINGS -> plugin.settings?.let { component -> - runCatching { startActivity(Intent().setComponent(component)) }.onFailure { toast(getString(UiR.string.plugin_unavailable)) } - } + UiAction.PLUGIN_SETTINGS -> if (plugin.settingsProvider != null) embeddedPlugin = plugin + else plugin.settings?.let { component -> + runCatching { startActivity(Intent().setComponent(component)) }.onFailure { toast(getString(UiR.string.plugin_unavailable)) } + } UiAction.PLUGIN_CONNECT -> startProjectionSource(plugin.id) else -> Unit } @@ -479,7 +491,8 @@ class WheelPlayActivity : AppCompatActivity() { val plugins = registry.entries().map { plugin -> PluginUi( plugin.id, plugin.name, plugin.component.packageName, plugin.sourceId == ProjectionPlugin.SOURCE_ICCOA_CARLINK, registry.enabled(plugin), plugin.problem, registry.lastFailure(plugin.id)?.let { getString(UiR.string.projection_failed, it) }, - plugin.settings != null, !(running && (state.source?.id == plugin.id || active?.descriptor?.id == plugin.id)), + plugin.settings != null || plugin.settingsProvider != null, + !(running && (state.source?.id == plugin.id || active?.descriptor?.id == plugin.id)), ) } val addresses = if (WebSession.running && WebSession.error == null) WebSession.addresses(this) else emptyList() val primary = addresses.firstOrNull() diff --git a/common/src/main/java/moe/feng/wheelplay/settings/PluginSettingsDialog.kt b/common/src/main/java/moe/feng/wheelplay/settings/PluginSettingsDialog.kt new file mode 100644 index 00000000..73ac41ce --- /dev/null +++ b/common/src/main/java/moe/feng/wheelplay/settings/PluginSettingsDialog.kt @@ -0,0 +1,203 @@ +package moe.feng.wheelplay.settings + +import android.database.ContentObserver +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import com.shilapi.xcertplay.host.R +import com.shilapi.xcertplay.projection.plugin.* +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout +import moe.feng.wheelplay.plugin.* +import moe.feng.wheelplay.ui.theme.WheelPlayTheme + +@Composable +internal fun PluginSettingsDialog(plugin: InstalledProjectionPlugin, lifecycle: Lifecycle, + onDismiss: () -> Unit, onExternal: (() -> Unit)?) { + val context = LocalContext.current.applicationContext + val client = remember(plugin) { PluginSettingsClient(context, plugin) { + projectionPlugins(context).entries().contains(plugin) + } } + var active by remember { mutableStateOf(false) } + var snapshot by remember(plugin) { mutableStateOf(null) } + var busy by remember { mutableStateOf(false) } + var remote by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(null) } + var reloadPending by remember { mutableStateOf(false) } + var editing by remember { mutableStateOf(null) } + var editingRevision by remember { mutableStateOf(0L) } + val commands = remember(plugin) { Channel>(8) } + fun submit(method: String = ProjectionSettings.GET, extras: Bundle = ProjectionSettings.request(remote = remote)) { + if (!active) return + if (method == ProjectionSettings.GET && busy) { reloadPending = true; return } + if (commands.trySend(method to extras).isFailure) error = context.getString(R.string.plugin_settings_busy) + else busy = true + } + val reload by rememberUpdatedState({ submit() }) + + DisposableEffect(client, lifecycle) { + val observer = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) { reload() } + } + var observing = false + fun update() { + val started = lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) + if (started == observing) return + if (started) { + try { + context.contentResolver.registerContentObserver(client.uri, true, observer) + observing = true; active = true; reload() + } catch (failure: Exception) { error = failure.message.orEmpty(); active = false } + } else { + runCatching { context.contentResolver.unregisterContentObserver(observer) } + observing = false; active = false; snapshot = null; editing = null; busy = false + while (commands.tryReceive().isSuccess) { /* Discard queued writes on leaving the screen. */ } + } + } + val listener = LifecycleEventObserver { _, _ -> update() } + lifecycle.addObserver(listener) + update() + onDispose { + lifecycle.removeObserver(listener) + if (observing) runCatching { context.contentResolver.unregisterContentObserver(observer) } + active = false; commands.close() + } + } + + LaunchedEffect(client, active) { + if (!active) return@LaunchedEffect + for ((method, extras) in commands) { + busy = true + try { + val result = withTimeout(5000) { client.requestAsync(method, extras) } + snapshot = result + error = if (result.conflict) context.getString(R.string.plugin_settings_conflict) else null + } catch (_: TimeoutCancellationException) { + snapshot = null; error = context.getString(R.string.plugin_settings_timeout) + } catch (cancelled: CancellationException) { throw cancelled } + catch (failure: Exception) { snapshot = null; error = failure.message.orEmpty().take(256) } + finally { busy = false } + if (reloadPending) { reloadPending = false; submit() } + } + } + LaunchedEffect(plugin, active) { + if (!active) return@LaunchedEffect + while (true) { + delay(1000) + if (!projectionPlugins(context).entries().contains(plugin)) { + snapshot = null; error = context.getString(R.string.plugin_settings_changed) + break + } + } + } + + fun save(field: PluginSetting, value: Any?, expectedRevision: Long? = null) { + val revision = expectedRevision ?: snapshot?.schema?.revision ?: return + submit(ProjectionSettings.SET, ProjectionSettings.request(revision, remote).apply { + putString("key", field.key) + putString("value", ProjectionSettings.encodeValue(value)) + }) + } + + WheelPlayTheme { + AlertDialog(onDismissRequest = onDismiss, + title = { Text(snapshot?.schema?.title ?: plugin.name) }, + confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.plugin_settings_close)) } }, + dismissButton = { + if (onExternal != null) TextButton(onClick = onExternal) { + Text(stringResource(R.string.plugin_settings_external)) + } + }, + text = { + Column(Modifier.fillMaxWidth().heightIn(max = 600.dp).verticalScroll(rememberScrollState()) + .testTag("plugin:embedded-settings"), verticalArrangement = Arrangement.spacedBy(12.dp)) { + if (busy) LinearProgressIndicator(Modifier.fillMaxWidth()) + error?.let { Text(it, color = MaterialTheme.colorScheme.error) } + if (error != null) TextButton(enabled = active && !busy, onClick = { submit() }) { + Text(stringResource(R.string.plugin_settings_retry)) + } + val state = snapshot + // Keep a route back to schema if the remote version/document is rejected. + if (remote || state?.supportsRemoteCompose == true) Row { + TextButton(enabled = !busy, onClick = { remote = false; submit() }) { + Text(stringResource(R.string.plugin_settings_schema)) + } + TextButton(enabled = !busy && state?.supportsRemoteCompose == true, onClick = { remote = true; submit() }) { + Text(stringResource(R.string.plugin_settings_remote)) + } + } + if (remote && state?.document != null) { + RemoteSettingsPlayer.Content(state.document, active && !busy, + onAction = { id, value -> + submit(ProjectionSettings.ACTION, ProjectionSettings.request(state.schema.revision, true).apply { + putInt("action_id", id); putString("action_value", value) + }) + }, onNamedAction = { name, value -> + runCatching { + submit(ProjectionSettings.ACTION, ProjectionSettings.request(state.schema.revision, true).apply { + putString("action_name", name); putString("action_json", ProjectionSettings.encodeValue(value)) + }) + }.onFailure { error = it.message.orEmpty() } + }, onFailure = { error = it }) + } else if (!remote) state?.schema?.fields?.forEach { field -> + Column(Modifier.fillMaxWidth().testTag("plugin:setting:${field.key}")) { + val enabled = active && !busy && field.enabled + if (field.type == SettingType.BOOLEAN) Row(Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween) { + Text(field.title, Modifier.weight(1f)) + Switch(field.value as Boolean, onCheckedChange = { save(field, it) }, enabled = enabled, + modifier = Modifier.testTag("plugin:setting:${field.key}:switch")) + } else { + Text(field.title, style = MaterialTheme.typography.titleSmall) + if (field.type != SettingType.ACTION) Text(field.choices.find { it.value == field.value }?.label + ?: field.value.toString()) + TextButton(enabled = enabled, onClick = { + if (field.type == SettingType.ACTION) save(field, null) else { + editingRevision = state.schema.revision; editing = field + } + }) { Text(stringResource(if (field.type == SettingType.ACTION) + R.string.plugin_settings_run else R.string.plugin_settings_edit)) } + } + if (field.summary.isNotEmpty()) Text(field.summary) + if (field.restartRequired) Text(stringResource(R.string.plugin_settings_reconnect)) + } + } + } + }) + editing?.let { field -> + if (field.type == SettingType.CHOICE) { + AlertDialog(onDismissRequest = { editing = null }, title = { Text(field.title) }, + text = { Column(Modifier.heightIn(max = 400.dp).verticalScroll(rememberScrollState())) { + field.choices.forEach { choice -> TextButton(onClick = { editing = null; save(field, choice.value, editingRevision) }) { + Text(choice.label) + } } + } }, confirmButton = { TextButton(onClick = { editing = null }) { Text(stringResource(R.string.plugin_settings_close)) } }) + } else { + var input by remember(field) { mutableStateOf(field.value.toString()) } + val value: Any? = if (field.type == SettingType.INTEGER) input.toLongOrNull() else input + val valid = runCatching { field.validateValue(value) }.isSuccess + AlertDialog(onDismissRequest = { editing = null }, title = { Text(field.title) }, + text = { OutlinedTextField(input, onValueChange = { input = it.take(4096) }, isError = !valid, + modifier = Modifier.testTag("plugin:setting-input")) }, + confirmButton = { TextButton(enabled = valid, onClick = { editing = null; save(field, value, editingRevision) }) { + Text(stringResource(R.string.plugin_settings_save)) + } }, dismissButton = { TextButton(onClick = { editing = null }) { Text(stringResource(R.string.plugin_settings_close)) } }) + } + } + } +} diff --git a/common/src/main/java/moe/feng/wheelplay/settings/RemoteComposeSettings.kt b/common/src/main/java/moe/feng/wheelplay/settings/RemoteComposeSettings.kt new file mode 100644 index 00000000..8dd38fd6 --- /dev/null +++ b/common/src/main/java/moe/feng/wheelplay/settings/RemoteComposeSettings.kt @@ -0,0 +1,110 @@ +package moe.feng.wheelplay.settings + +import android.annotation.SuppressLint +import android.widget.FrameLayout +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.core.Limits +import androidx.compose.remote.core.operations.Header +import androidx.compose.remote.core.operations.utilities.IntMap +import androidx.compose.remote.player.core.RemoteDocument +import androidx.compose.remote.player.core.platform.BitmapLoader +import androidx.compose.remote.player.core.platform.AndroidRemoteContext +import androidx.compose.remote.player.core.action.StateUpdaterActionCallback +import androidx.compose.remote.player.view.RemoteComposePlayer +import androidx.compose.runtime.* +import androidx.compose.foundation.layout.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import moe.feng.wheelplay.plugin.PluginSettingsDocument +import java.util.concurrent.CancellationException + +/** Keep the alpha/restricted AndroidX APIs in one adapter, pinned with the producer version. */ +@SuppressLint("RestrictedApi") +internal object RemoteSettingsPlayer { + fun parse(document: PluginSettingsDocument): RemoteDocument { + Limits.MAX_DECOMPRESSED_SIZE = 2 * 1024 * 1024 + Limits.MAX_OP_COUNT = 4000 + Limits.MAX_IMAGE_DIMENSION = 2048 + Limits.MAX_BITMAP_MEMORY = 8 * 1024 * 1024 + Limits.MAX_FPS = 30 + Limits.DEFAULT_MAX_FPS = 30 + Limits.ENABLE_IMAGE_URLS = false + Limits.ENABLE_IMAGE_FILES = false + Limits.ENABLE_RUN_ACTION_HOST_ACTIONS = false + return RemoteDocument(document.bytes).also { + require(it.canBeDisplayed(CoreDocument.MAJOR_VERSION, CoreDocument.MINOR_VERSION, 0)) { + "Remote Compose document version is unsupported" + } + // Viewport dimensions are set only when a player initializes the document. + // Inspect the header without initializing any resources or running operations. + val header = it.document.operations.filterIsInstance
().single() + header.apply(object : AndroidRemoteContext() { + override fun header(majorVersion: Int, minorVersion: Int, patchVersion: Int, + width: Int, height: Int, capabilities: Long, properties: IntMap?) { + require(width == document.width && height == document.height) { + "Remote Compose dimensions do not match the descriptor" + } + } + }) + } + } + + @Composable + fun Content(document: PluginSettingsDocument, enabled: Boolean, onAction: (Int, String?) -> Unit, + onNamedAction: (String, Any?) -> Unit, onFailure: (String) -> Unit) { + var parsed by remember(document) { mutableStateOf(null) } + val currentAction by rememberUpdatedState(onAction) + val currentEnabled by rememberUpdatedState(enabled) + val currentNamedAction by rememberUpdatedState(onNamedAction) + LaunchedEffect(document) { + try { parsed = withContext(Dispatchers.IO) { parse(document) } } + catch (error: CancellationException) { throw error } + catch (error: Exception) { onFailure(error.message.orEmpty()) } + } + val value = parsed ?: return + BoxWithConstraints(Modifier.fillMaxWidth()) { + val height = (maxWidth * document.height.toFloat() / document.width).coerceIn(120.dp, 1200.dp) + AndroidView(modifier = Modifier.fillMaxWidth().height(height).testTag("plugin:remote-compose"), + factory = { context -> FrameLayout(context).apply { + val frame = this + addView(RemoteComposePlayer(context).apply { + setBitmapLoader(BitmapLoader.UNSUPPORTED) + setShaderControl { false } + setDefaultMaxFps(30) + pivotX = 0f; pivotY = 0f + }, FrameLayout.LayoutParams(document.width, document.height)) + addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> scale(frame) } + } }, + update = { frame -> + val player = frame.getChildAt(0) as RemoteComposePlayer + try { if (player.tag !== value) { + player.layoutParams = FrameLayout.LayoutParams(document.width, document.height) + player.setDocument(value) + check(player.document === value) { "Remote Compose player rejected the document" } + player.addIdActionListener { id, metadata -> + if (currentEnabled && frame.isEnabled) currentAction(id, metadata) + } + value.document.addActionCallback(object : StateUpdaterActionCallback(player.stateUpdater, + { name, payload, _ -> if (currentEnabled && frame.isEnabled) currentNamedAction(name, payload) }) {}) + player.tag = value + scale(frame) + } } + catch (error: Exception) { onFailure(error.message.orEmpty()) } + }, + onRelease = { it.isEnabled = false; it.removeAllViews() }, + ) + } + } + + private fun scale(frame: FrameLayout) { + val player = frame.getChildAt(0) ?: return + if (frame.width == 0 || frame.height == 0) return + val scale = minOf(frame.width.toFloat() / player.layoutParams.width, + frame.height.toFloat() / player.layoutParams.height) + player.scaleX = scale; player.scaleY = scale + } +} diff --git a/common/src/main/res/values-zh-rCN/settings_strings.xml b/common/src/main/res/values-zh-rCN/settings_strings.xml index 497ce5e2..8979aac1 100644 --- a/common/src/main/res/values-zh-rCN/settings_strings.xml +++ b/common/src/main/res/values-zh-rCN/settings_strings.xml @@ -218,4 +218,17 @@ %1$s增加 1%% %1$s减少 1%% 分辨率:%1$d × %2$d · 独立保存 + 设置正在更新,请稍后重试 + 设置已在其他位置修改,已载入最新值。 + 插件未响应,请重试或打开插件独立设置页。 + 插件已更新或移除,请关闭此页并重新打开设置。 + 关闭 + 在插件中打开 + 重试 + 标准设置 + 插件布局 + 执行 + 修改 + 下次连接时生效 + 保存 diff --git a/common/src/main/res/values-zh-rTW/settings_strings.xml b/common/src/main/res/values-zh-rTW/settings_strings.xml index 38cbf6c0..79e6bfa6 100644 --- a/common/src/main/res/values-zh-rTW/settings_strings.xml +++ b/common/src/main/res/values-zh-rTW/settings_strings.xml @@ -218,4 +218,17 @@ %1$s增加 1%% %1$s減少 1%% 解析度:%1$d × %2$d · 獨立儲存 + 設定正在更新,請稍後重試 + 設定已在其他位置修改,已載入最新值。 + 外掛程式未回應,請重試或開啟外掛程式獨立設定頁。 + 外掛程式已更新或移除,請關閉此頁並重新開啟設定。 + 關閉 + 在外掛程式中開啟 + 重試 + 標準設定 + 外掛程式版面 + 執行 + 修改 + 下次連線時生效 + 儲存 diff --git a/common/src/main/res/values/settings_strings.xml b/common/src/main/res/values/settings_strings.xml index f3e987f5..0239df11 100644 --- a/common/src/main/res/values/settings_strings.xml +++ b/common/src/main/res/values/settings_strings.xml @@ -218,4 +218,17 @@ Increase %1$s by 1%% Decrease %1$s by 1%% Resolution: %1$d × %2$d · Saved separately + Settings are busy; try again + Settings changed elsewhere. The latest values have been loaded. + The plugin did not respond. Retry or open its separate settings page. + The plugin was updated or removed. Close this page and reopen settings. + Close + Open in plugin + Retry + Standard settings + Plugin layout + Run + Edit + Applies on the next connection + Save diff --git a/common/src/test/java/com/shilapi/xcertplay/projection/plugin/ProjectionPluginRegistryTest.kt b/common/src/test/java/com/shilapi/xcertplay/projection/plugin/ProjectionPluginRegistryTest.kt index 43c9e4aa..ce82bf36 100644 --- a/common/src/test/java/com/shilapi/xcertplay/projection/plugin/ProjectionPluginRegistryTest.kt +++ b/common/src/test/java/com/shilapi/xcertplay/projection/plugin/ProjectionPluginRegistryTest.kt @@ -5,6 +5,7 @@ import android.content.pm.* import android.os.Bundle import com.shilapi.xcertplay.projection.* import moe.feng.wheelplay.plugin.ProjectionPlugin +import moe.feng.wheelplay.plugin.ProjectionSettings import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith @@ -107,4 +108,38 @@ class ProjectionPluginRegistryTest { registry.refresh() assertFalse(registry.enabled(registry.entries().single())) } + + @Test fun embeddedSettingsOnlyAcceptAnAccessibleProviderFromTheSamePluginUid() { + val registry = ProjectionPluginRegistry(context, ProjectionRuntime()) + install() + val pkg = context.packageManager.getPackageInfo(component.packageName, PackageManager.GET_SERVICES or PackageManager.GET_META_DATA) + pkg.services!!.single().metaData.putString(ProjectionSettings.META_PROVIDER, "test.plugin.settings") + val provider = ProviderInfo().apply { + name = "test.plugin.Settings"; packageName = component.packageName + authority = "test.plugin.settings"; applicationInfo = pkg.applicationInfo + exported = true; enabled = true + } + pkg.providers = arrayOf(provider) + pm.installPackage(pkg) + pm.setResolveInfosForIntent(Intent(ProjectionPlugin.ACTION), listOf(ResolveInfo().apply { + serviceInfo = pkg.services!!.single() + })) + registry.refresh() + assertEquals("test.plugin.settings", registry.entries().single().settingsProvider) + assertFalse(registry.enabled(registry.entries().single())) + provider.exported = false; pkg.providers = arrayOf(provider); pm.installPackage(pkg); registry.refresh() + assertNull(registry.entries().single().settingsProvider) + provider.exported = true + // An authority owned by another installed APK must not become a settings entry. + pm.removeProvider(ComponentName(component.packageName, provider.name)) + val foreignApp = ApplicationInfo(pkg.applicationInfo).apply { packageName = "other.plugin"; uid += 1 } + pm.installPackage(PackageInfo().apply { + packageName = foreignApp.packageName; applicationInfo = foreignApp + providers = arrayOf(ProviderInfo(provider).apply { + packageName = foreignApp.packageName; applicationInfo = foreignApp + }) + }) + registry.refresh() + assertNull(registry.entries().single().settingsProvider) + } } diff --git a/common/src/test/java/moe/feng/wheelplay/PluginSettingsUiTest.kt b/common/src/test/java/moe/feng/wheelplay/PluginSettingsUiTest.kt new file mode 100644 index 00000000..46d478c1 --- /dev/null +++ b/common/src/test/java/moe/feng/wheelplay/PluginSettingsUiTest.kt @@ -0,0 +1,211 @@ +package moe.feng.wheelplay + +import android.content.ComponentName +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.pm.* +import android.os.Bundle +import android.os.Looper +import android.annotation.SuppressLint +import android.graphics.Color +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.ui.test.* +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.profile.RcPlatformProfiles +import androidx.compose.remote.core.operations.Header +import com.shilapi.xcertplay.projection.plugin.* +import moe.feng.wheelplay.plugin.* +import moe.feng.wheelplay.settings.PluginSettingsDialog +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import org.robolectric.shadows.ShadowContentResolver + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [29], qualifiers = "en-mdpi") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@SuppressLint("RestrictedApi") +class PluginSettingsUiTest : ComposeSettingsTest() { + class HostActivity : ComponentActivity() + class Provider : ProjectionSettingsProvider() { + var revision = 0L + var counter = false + var caption = "Initial caption" + var reads = 0 + var remoteSupported = false + var rejectRemote = false + override val supportsRemoteCompose get() = remoteSupported + override fun isHostAllowed(uid: Int) = true + override fun readSettings(source: ComponentName): PluginSettingsSchema { + reads++ + return PluginSettingsSchema(revision, "Plugin settings fixture", listOf( + PluginSetting("counter", "Counter", SettingType.BOOLEAN, counter), + PluginSetting("caption", "Caption", SettingType.TEXT, caption, maxLength = 40))) + } + override fun writeSetting(source: ComponentName, key: String, value: Any?) { + if (key == "counter") counter = value as Boolean else caption = value as String + revision++ + } + fun externalChange() { counter = false; revision++; notifySettingsChanged() } + fun externalCaptionChange() { caption = "Changed elsewhere"; revision++; notifySettingsChanged() } + override fun remoteDocument(source: ComponentName): PluginSettingsDocument { + require(!rejectRemote) { "Remote layout unavailable" } + val writer = RemoteComposeWriter(RcPlatformProfiles.ANDROIDX, + RemoteComposeWriter.hTag(Header.DOC_WIDTH, 320), RemoteComposeWriter.hTag(Header.DOC_HEIGHT, 180)) + writer.rcPaint.setColor(if (counter) Color.GREEN else Color.BLUE).commit() + writer.drawRect(0f, 0f, 320f, 180f) + writer.addClickArea(1, "Toggle counter", 0f, 0f, 320f, 180f, null) + return PluginSettingsDocument(writer.encodeToByteArray(), 320, 180) + } + override fun onRemoteAction(source: ComponentName, actionId: Int, value: String?) { + require(actionId == 1); counter = !counter; revision++ + } + } + private fun install(): Pair { + val app = RuntimeEnvironment.getApplication() + val component = ComponentName("test.plugin", "test.plugin.Source") + val application = ApplicationInfo().apply { packageName = "test.plugin"; uid = 12345; enabled = true } + val service = ServiceInfo().apply { + name = component.className; packageName = component.packageName; applicationInfo = application + enabled = true; exported = true + metaData = Bundle().apply { + putInt(ProjectionPlugin.META_API_VERSION, ProjectionPlugin.API_VERSION) + putString(ProjectionSettings.META_PROVIDER, "test.plugin.settings") + } + } + val providerInfo = ProviderInfo().apply { + name = Provider::class.java.name; packageName = component.packageName; applicationInfo = application + authority = "test.plugin.settings"; enabled = true; exported = true + } + val pkg = PackageInfo().apply { + packageName = component.packageName; applicationInfo = application + versionCode = 1; lastUpdateTime = 10; firstInstallTime = 5 + services = arrayOf(service); providers = arrayOf(providerInfo) + signingInfo = SigningInfo().also { shadowOf(it).setSignatures(arrayOf(Signature("1234"))) } + } + val pm = shadowOf(app.packageManager) + pm.installPackage(pkg) + pm.setResolveInfosForIntent(Intent(ProjectionPlugin.ACTION), listOf(ResolveInfo().apply { serviceInfo = service })) + val pluginContext = object : ContextWrapper(app) { + override fun getPackageName() = component.packageName + override fun getApplicationInfo() = application + } + val provider = Provider().apply { attachInfo(pluginContext, providerInfo) } + ShadowContentResolver.registerProviderInternal(providerInfo.authority, provider) + val registry = projectionPlugins(app) + registry.refresh() + val plugin = registry.entries().single() + assertFalse(registry.enabled(plugin)) // Setup must be accessible before projection is enabled. + return plugin to provider + } + private fun waitFor(predicate: () -> Boolean) = compose.waitUntil(10_000) { + shadowOf(Looper.getMainLooper()).idle() + predicate() + } + + @Test fun hostActivityRendersSchemaPersistsEditsAndObservesExternalChangesWithoutLaunchingPluginActivity() { + val (plugin, provider) = install() + val controller = Robolectric.buildActivity(HostActivity::class.java).setup() + val activity = controller.get() + try { + activity.setContent { PluginSettingsDialog(plugin, activity.lifecycle, {}, null) } + waitFor { compose.onAllNodesWithTag("plugin:setting:counter:switch").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithTag("plugin:setting:counter:switch").assertIsOff().performClick() + waitFor { provider.counter } + compose.onNodeWithTag("plugin:setting:counter:switch").assertIsOn() + compose.onNodeWithText("Edit").performScrollTo().performClick() + compose.onNodeWithTag("plugin:setting-input").performTextReplacement("Saved inside host") + compose.onNodeWithText("Save").performClick() + waitFor { provider.caption == "Saved inside host" } + compose.onNodeWithText("Saved inside host").assertExists() + provider.externalChange() + waitFor { compose.onNodeWithTag("plugin:setting:counter:switch").fetchSemanticsNode() + .config[androidx.compose.ui.semantics.SemanticsProperties.ToggleableState] == androidx.compose.ui.state.ToggleableState.Off } + assertNull(shadowOf(activity).nextStartedActivity) + } finally { controller.pause().stop().destroy() } + } + + @Test fun leavingTheActivityStopsObservingAndResumeReloadsCurrentSettings() { + val (plugin, provider) = install() + val controller = Robolectric.buildActivity(HostActivity::class.java).setup() + try { + val activity = controller.get() + activity.setContent { PluginSettingsDialog(plugin, activity.lifecycle, {}, null) } + waitFor { provider.reads >= 2 } + compose.waitForIdle() + controller.pause().stop() + val reads = provider.reads + provider.externalChange() + shadowOf(Looper.getMainLooper()).idle() + assertEquals(reads, provider.reads) + controller.restart().start().resume() + waitFor { provider.reads > reads } + compose.onNodeWithTag("plugin:setting:counter:switch").assertIsOff() + } finally { controller.pause().stop().destroy() } + } + + @Test fun anOpenEditorCannotOverwriteAConcurrentExternalChange() { + val (plugin, provider) = install() + val controller = Robolectric.buildActivity(HostActivity::class.java).setup() + try { + val activity = controller.get() + activity.setContent { PluginSettingsDialog(plugin, activity.lifecycle, {}, null) } + waitFor { compose.onAllNodesWithText("Edit").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithText("Edit").performScrollTo().performClick() + compose.onNodeWithTag("plugin:setting-input").performTextReplacement("Old editor value") + val reads = provider.reads + provider.externalCaptionChange() + waitFor { provider.reads > reads } + compose.onNodeWithText("Save").performClick() + waitFor { compose.onAllNodesWithText("Settings changed elsewhere. The latest values have been loaded.").fetchSemanticsNodes().isNotEmpty() } + assertEquals("Changed elsewhere", provider.caption) + assertEquals(1L, provider.revision) + } finally { controller.pause().stop().destroy() } + } + + @Test fun remoteComposeIsRenderedInTheHostAndScaledTouchUpdatesTheSchema() { + val (plugin, provider) = install() + provider.remoteSupported = true + val controller = Robolectric.buildActivity(HostActivity::class.java).setup() + try { + val activity = controller.get() + activity.setContent { PluginSettingsDialog(plugin, activity.lifecycle, {}, null) } + waitFor { compose.onAllNodesWithText("Plugin layout").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithText("Plugin layout").performClick() + waitFor { compose.onAllNodesWithTag("plugin:remote-compose").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithTag("plugin:remote-compose").performScrollTo().performTouchInput { + click(center) + } + waitFor { provider.counter } + compose.onNodeWithText("Standard settings").performScrollTo().performClick() + waitFor { compose.onAllNodesWithTag("plugin:setting:counter:switch").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithTag("plugin:setting:counter:switch").assertIsOn() + assertNull(shadowOf(activity).nextStartedActivity) + } finally { controller.pause().stop().destroy() } + } + + @Test fun failedRemoteLayoutCanReturnToTheStandardForm() { + val (plugin, provider) = install() + provider.remoteSupported = true + provider.rejectRemote = true + val controller = Robolectric.buildActivity(HostActivity::class.java).setup() + try { + val activity = controller.get() + activity.setContent { PluginSettingsDialog(plugin, activity.lifecycle, {}, null) } + waitFor { compose.onAllNodesWithText("Plugin layout").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithText("Plugin layout").performClick() + waitFor { compose.onAllNodesWithText("Remote layout unavailable").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithText("Standard settings").performClick() + waitFor { compose.onAllNodesWithTag("plugin:setting:counter:switch").fetchSemanticsNodes().isNotEmpty() } + compose.onNodeWithTag("plugin:setting:counter:switch").assertIsOff() + } finally { controller.pause().stop().destroy() } + } +} diff --git a/docs/PLUGIN_SETTINGS.md b/docs/PLUGIN_SETTINGS.md new file mode 100644 index 00000000..554377d6 --- /dev/null +++ b/docs/PLUGIN_SETTINGS.md @@ -0,0 +1,148 @@ +# 插件内嵌设置:schema 与 Jetpack Remote Compose + +输入源插件可以将设置显示在 **WheelPlay 的 Activity 内**。配置仍由插件 APK 保存和处理,宿主不加载插件 dex、Composable 或自定义 View。提供两种呈现方式: + +| 方式 | 数据 | 宿主呈现 | 适用场景 | +| --- | --- | --- | --- | +| Schema | 版本化 JSON schema 和当前值 | WheelPlay 的 Compose 设置控件 | 开关、文本、整数、选项、操作按钮 | +| Remote Compose | Jetpack Remote Compose 二进制文档 | 固定版本的官方播放器 | 插件定制布局、绘制和交互 | + +两种方式共用 ContentProvider、配置修订号和变更通知。不使用 RemoteViews。现有设置 Activity 保留为独立页面入口;仅声明 Activity 的旧插件继续按原方式打开。投影 Binder API 仍为 v2,设置协议独立为 v1。 + +## 声明与开发 + +在投影 Service 上声明 Provider authority: + +```xml + +``` + +在 application 内注册插件自己的 Provider: + +```xml + +``` + +继承独立 SDK 中的 `ProjectionSettingsProvider`: + +```kotlin +class SettingsProvider : ProjectionSettingsProvider() { + override fun readSettings(source: ComponentName) = PluginSettingsSchema( + revision = loadRevision(), + title = "插件设置", + fields = listOf( + PluginSetting("enabled", "启用功能", SettingType.BOOLEAN, + loadEnabled(), restartRequired = true) + ) + ) + + override fun writeSetting(source: ComponentName, key: String, value: Any?) { + // 保存值,并在同一事务中递增 revision。 + } +} +``` + +上面存储函数由插件实现。一个 Provider 可服务同一 APK 的多个输入源,`source` 为投影 Service 的 `ComponentName`。`readSettings()` 不得启动投影、申请设备权限或占用设备资源。 + +SDK 在写入前检查字段存在、可编辑、类型、范围、字符串长度和选项有效性。插件仍负责业务校验和持久化。字段种类为 `BOOLEAN`、`TEXT`、`INTEGER`、`CHOICE`、`ACTION`;操作按钮的值为 JSON `null`。`enabled=false` 的字段不可写,`restartRequired=true` 在宿主显示“下次连接时生效”。 + +最小 schema 的线格式示例: + +```json +{ + "version": 1, + "revision": 12, + "title": "插件设置", + "fields": [ + { + "key": "enabled", + "title": "启用功能", + "type": "boolean", + "value": true, + "enabled": true, + "restartRequired": true + } + ] +} +``` + +`choices` 为 `{ "value": "stable-id", "label": "显示文字" }` 数组。整数使用 `minimum` / `maximum`,文本使用 `maxLength`,各字段可有 `summary`。字段 key 在当前 schema 中唯一,最多 64 个字段,schema UTF-8 总大小不超过 64 KiB。 + +## ContentProvider 协议 v1 + +所有设置 RPC 使用 `ContentResolver.call()`;查询游标和直接 SQL 更新不属于此协议。变更通知 URI 固定为 `content:///wheelplay-settings`。宿主只在用户打开设置页后访问 Provider,列表发现阶段仅读取安装元数据。 + +每次调用的 `arg` 是投影 Service 的 `ComponentName.flattenToString()`。`extras.version` 必须为 `1`,`include_remote` 表示是否需要 Remote Compose 文档。 + +| Method | 额外请求字段 | 行为 | +| --- | --- | --- | +| `wheelplay.settings.get` | 无 | 返回当前快照 | +| `wheelplay.settings.set` | `revision`、`key`、`value` | 写入一个字段;value 是 JSON 标量的字符串编码 | +| `wheelplay.settings.action` | `revision`、`action_id`、可选 `action_value` | 执行 Remote Compose ID action,value 是可选字符串 | +| 同上 | `revision`、`action_name`、`action_json` | 执行 named action,action_json 是 JSON 标量编码 | + +响应为仅含基础值的 Bundle:`version`、`status`、`schema`、`supports_remote`,必要时包含 `message`。成功状态为 `ok`;写入修订号过期时返回 `conflict` 及最新快照,并且不执行修改;其他状态为 `invalid`、`unsupported` 或 `error`。鉴权和来源验证失败会抛出异常。 + +成功写入/动作后,插件应返回新的 revision。SDK 串行处理其调用,并在修改后发送 `notifyChange()`。插件通过其他页面更改配置时,应调用 `notifySettingsChanged()`。编辑框使用**打开编辑时**的修订号,外部更新不会让旧输入悄悄覆盖新值。 + +## Remote Compose 接入 + +宿主固定使用官方 `androidx.compose.remote` **`1.0.0-alpha23`**。复杂 UI 的插件需使用匹配版本的 creation 库生成文档;仅使用 schema 的插件无需依赖 Remote Compose。 + +```kotlin +override val supportsRemoteCompose = true + +override fun remoteDocument(source: ComponentName): PluginSettingsDocument { + // 使用 Jetpack Remote Compose creation API / Remote Compose DSL 生成文档。 + return PluginSettingsDocument(documentBytes, width = 720, height = 360) +} + +override fun onRemoteAction(source: ComponentName, actionId: Int, value: String?) { + // 验证 action,并修改插件配置及 revision。 +} + +override fun onNamedRemoteAction(source: ComponentName, name: String, value: Any?) { + // 验证名称和 JSON 标量;不接受任意 Parcelable 或插件对象。 +} +``` + +RPC 的远程快照额外包含 `remote_version`、`remote_document`、`remote_width`、`remote_height`。二进制文档最多 256 KiB,声明尺寸单边为 1–4096 且总像素不超过 8,388,608,须与解码文档一致。宿主拒绝不匹配的 renderer 版本;仍可切回标准 schema 或打开独立 Activity。 + +宿主在自己的 Activity 中通过 `AndroidView` 承载官方 `RemoteComposePlayer`,并转发 ID 和 named action。返回快照后重新播放新的文档,使复杂布局和标准表单保持同一配置状态。插件负责 action 的业务验证,不能依赖普通字段校验来保护另一个 action 路径。 + +Remote Compose 当前是 alpha,部分播放器 API 标为 `RestrictedApi`;宿主将相关引用和 lint 抑制集中在 `RemoteComposeSettings.kt`,升级时应一起更新版本目录、SDK renderer 版本、生产端和渲染测试。文档只能使用播放器支持的远程操作,不能直接传入普通 Compose 函数或任意自定义 Android View。 + +播放器限制解压大小、操作数、位图尺寸、位图内存和帧率;禁用外部图片 URL、文件加载、文档自动触发的 host action 和自定义 shader。资源应随文档提供。 + +## 身份与生命周期 + +- Provider 必须属于投影插件同一 APK、同一 UID,已启用、可导出,并满足宿主的权限要求。宿主在请求前后再次核对安装时间、版本、更新时间和签名;APK 更新或移除后丢弃旧页面与旧响应。 +- SDK 默认只接受插件自身 UID,以及 `moe.feng.wheelplay` / `moe.feng.wheelplay.debug` 的 UID。插件需要限定特定宿主发行者时,可覆盖 `isHostAllowed()` 校验签名,规则与现有投影 Service 相同。 +- RPC 在数量受限的后台线程执行,UI 请求有五秒截止时间。超时只表示宿主停止等待,不保证 Android 已取消插件中的 Binder 方法;因此 Provider 实现必须短时返回。 +- 页面停止可见时移除 ContentObserver、撤销等待并丢弃排队修改;关闭时销毁播放器。恢复可见后重新读取当前值,不复用旧快照执行修改。 +- 配置更新不自动重启正在进行的投影。设备权限继续在插件自己的 Activity 中申请;跨进程存储同步仍由插件负责。 + +## 示例与验证 + +`projection-plugin-sample` 同时提供标准表单和真实 Remote Compose 文档,两者操作相同的帧计数开关、帧率配置。schema 还演示字幕、分辨率和恢复默认操作。示例的绘图和 click-area 文档使用官方 AndroidX profile,由当前播放器解码;宿主按文档原始尺寸等比缩放,并保留 Android 的触控坐标变换,像素测试覆盖实际背景及按钮区域。投影采用专用进程,在停止退出并重新连接后读取最新偏好,示例中的配置均标明下次连接生效。 + +```bash +./gradlew :projection-plugin-api:testDebugUnitTest \ + :common:testDebugUnitTest \ + :projection-plugin-sample:testDebugUnitTest \ + :mobile:assembleDebug :projection-plugin-sample:assembleDebug +``` + +安装宿主和示例后,在输入源插件卡片点击“设置”,可在宿主 Activity 内切换“标准设置”和“插件布局”;“在插件中打开”继续打开旧 Activity。 + +本次验证通过 58 项 JVM/Robolectric 测试:SDK 16 项,宿主插件设置、注册表、投影会话、生命周期与输入源导航 41 项,示例 1 项。覆盖真实 Remote Compose 解码、像素绘制、点击回写、并发编辑冲突、外部通知、前后台恢复和远程布局失败后的 schema 回退。宿主与示例 Debug APK 已构建。Robolectric 中的 Provider 不代替不同 UID 的车机真机验收;安装两个 APK 后仍需检查目标设备上的跨进程调用和输入行为。 + +`mobile:lintDebug` 和 `projection-plugin-sample:lintDebug` 通过。`common:lintDebug` 报告 27 个错误,位置均在本次未修改的代码行,涉及既有权限声明、常量和字符串格式;新增设置实现没有 lint 错误,common 全模块 lint 尚未通过。 + +官方参考:[Remote Compose 发布说明](https://developer.android.com/jetpack/androidx/releases/compose-remote)、[播放器源码](https://github.com/androidx/androidx/tree/androidx-main/compose/remote/remote-player-view)、[生成 API 源码](https://github.com/androidx/androidx/tree/androidx-main/compose/remote/remote-creation-core)。 diff --git a/docs/PROJECTION_PLUGINS.md b/docs/PROJECTION_PLUGINS.md index f0de6ca4..dda04ee5 100644 --- a/docs/PROJECTION_PLUGINS.md +++ b/docs/PROJECTION_PLUGINS.md @@ -27,7 +27,7 @@ WheelPlay 可以发现独立安装的第三方插件 APK,通过显式绑定的 | 分辨率 | 握手声明,单边 1–4096 像素,总像素不超过 8,388,608;变更需重连 | | 触控 | 0–10 点,稳定 ID 0–31,内容区域归一化坐标;空快照释放全部触点 | | 夜间模式 | 可选,必须实际实现后声明 | -| 设置 | 同一 APK 内可导出的设置 Activity | +| 设置 | 同 APK ContentProvider schema / Jetpack Remote Compose 内嵌设置,以及可导出的独立设置 Activity | | 音频/麦克风、媒体信息、桌面键盘/鼠标 | 暂未开放插件端口;不能声明浏览器音频能力 | | 编码帧/framebuffer IPC、多显示器 | 暂不支持;需要后续版本协商及有界媒体通道 | @@ -61,7 +61,9 @@ adb install -r projection-plugin-sample/build/outputs/apk/debug/projection-plugi 可选元数据 `SOURCE_ID` 用于关联内置输入源页面。ICCOA CarLink 插件声明 `iccoa-carlink`(SDK 常量 `SOURCE_ICCOA_CARLINK`)后,内置 ICCOA 卡片会显示已安装插件,其详情页提供插件设置、启用、连接和会话停止操作;未安装时显示安装引导。安装或从插件设置返回后会重新发现。多个插件声明同一 ID 时逐个列出,由用户选择;不兼容插件显示具体原因。缺省或未知 ID 仍可在通用插件页使用。 -该 ID 仅用于界面关联,不替代组件生成的运行时 ID,不授予权限或自动启用,也不按名称或包名猜测匹配。设置入口仍只接受插件同包内可访问的 Activity,浏览页面不会执行插件代码。 +该 ID 仅用于界面关联,不替代组件生成的运行时 ID,不授予权限或自动启用,也不按名称或包名猜测匹配。设置入口接受插件同包内可访问的 Activity 或设置 Provider;发现插件时只读取元数据,打开设置后才调用 Provider。 + +插件也可声明 `moe.feng.wheelplay.plugin.SETTINGS_PROVIDER`,通过独立的设置协议 v1 在宿主 Activity 内显示标准 schema 表单或 Jetpack Remote Compose 页面。旧的 Activity 入口继续兼容,不改变投影 Binder API v2。完整协议、示例和生命周期见 [插件内嵌设置](PLUGIN_SETTINGS.md)。 建议继承 `ProjectionPluginService`,实现: diff --git a/docs/README.md b/docs/README.md index 0e64ddd5..5538cd55 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,6 +10,7 @@ - [VNC 远程桌面](VNC.md):连接方法、RFB 协议范围、通用桌面输入和设备验收。 - [Android 虚拟桌面](ANDROID_DESKTOP.md):Shizuku 安装授权、本机应用选择、图像/触控链路、生命周期及尚未完成的真机验收。 - [APK 输入源插件](PROJECTION_PLUGINS.md):安装启用、独立 SDK/示例 APK、Surface 与触控协议,以及 ICCOA 插件接入边界。 +- [插件内嵌设置](PLUGIN_SETTINGS.md):ContentProvider schema、Jetpack Remote Compose、宿主内呈现与插件配置读写。 - [投影输入源实现与设备验收](PROJECTION_IMPLEMENTATION.md):当前框架、CarPlay 适配、三类诊断源及后续协议接入范围。 - [通用输入源框架设计草案](INPUT_SOURCE_FRAMEWORK.md):CarPlay、Android Auto、ICCOA、桌面与 VNC 的接口边界、研究证据及分阶段迁移建议(研究时点的方案)。 - [WebRTC 稳定性与卡顿恢复](WEBRTC_RECOVERY.md):回退原因、可配置容忍时间及真机排查方法。 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 55919896..32f9f0e2 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -6,12 +6,18 @@ lifecycleRuntimeKtx = "2.6.1" activityCompose = "1.8.0" kotlin = "2.2.10" composeBom = "2026.02.01" +remoteCompose = "1.0.0-alpha23" appcompat = "1.7.1" junit = "4.13.2" bouncycastle = "1.79" jmdns = "3.6.3" [libraries] +androidx-remote-core = { module = "androidx.compose.remote:remote-core", version.ref = "remoteCompose" } +androidx-remote-player-core = { module = "androidx.compose.remote:remote-player-core", version.ref = "remoteCompose" } +androidx-remote-player-view = { module = "androidx.compose.remote:remote-player-view", version.ref = "remoteCompose" } +androidx-remote-creation-android = { module = "androidx.compose.remote:remote-creation-android", version.ref = "remoteCompose" } +androidx-remote-creation-core = { module = "androidx.compose.remote:remote-creation-core", version.ref = "remoteCompose" } androidx-annotation = { group = "androidx.annotation", name = "annotation", version.ref = "annotation" } androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" } diff --git a/projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettings.kt b/projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettings.kt new file mode 100644 index 00000000..5a452cde --- /dev/null +++ b/projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettings.kt @@ -0,0 +1,168 @@ +package moe.feng.wheelplay.plugin + +import android.net.Uri +import android.os.Bundle +import org.json.JSONArray +import org.json.JSONObject +import org.json.JSONTokener +import java.util.Locale + +/** Independent settings protocol; does not change the projection Binder API version. */ +object ProjectionSettings { + const val VERSION = 1 + const val META_PROVIDER = "moe.feng.wheelplay.plugin.SETTINGS_PROVIDER" + const val GET = "wheelplay.settings.get" + const val SET = "wheelplay.settings.set" + const val ACTION = "wheelplay.settings.action" + const val REMOTE_COMPOSE_VERSION = "1.0.0-alpha23" + const val MAX_SCHEMA_BYTES = 64 * 1024 + const val MAX_DOCUMENT_BYTES = 256 * 1024 + fun uri(authority: String): Uri = Uri.Builder().scheme("content").authority(authority) + .appendPath("wheelplay-settings").build() + fun request(revision: Long? = null, remote: Boolean = false) = Bundle().apply { + putInt("version", VERSION) + putBoolean("include_remote", remote) + revision?.let { putLong("revision", it) } + } + + fun encodeValue(value: Any?): String { + require(value == null || value is String || value is Boolean || value is Number) + if (value is String) require(value.length <= 4096) + if (value is Number) require(value.toDouble().isFinite()) + return if (value is String) JSONObject.quote(value) else value?.toString() ?: "null" + } + + fun decodeValue(encoded: String): Any? { + require(encoded.toByteArray(Charsets.UTF_8).size <= 32 * 1024) + val text = encoded.trim() + require(text.startsWith('"') || text in listOf("true", "false", "null") || + Regex("-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?").matches(text)) + val parser = JSONTokener(text) + val value = parser.nextValue().takeUnless { it == JSONObject.NULL } + require(parser.nextClean() == '\u0000') { "Expected one JSON scalar" } + encodeValue(value) // Reject arrays, objects, and nonfinite numbers. + return value + } +} + +enum class SettingType { BOOLEAN, TEXT, INTEGER, CHOICE, ACTION } +data class SettingChoice(val value: String, val label: String) + +/** Values are JSON primitives. Provider and host both validate the same schema. */ +data class PluginSetting( + val key: String, + val title: String, + val type: SettingType, + val value: Any? = null, + val summary: String = "", + val enabled: Boolean = true, + val restartRequired: Boolean = false, + val choices: List = emptyList(), + val minimum: Int = Int.MIN_VALUE, + val maximum: Int = Int.MAX_VALUE, + val maxLength: Int = 1024, +) { + init { + require(Regex("[A-Za-z][A-Za-z0-9_.-]{0,63}").matches(key)) { "Invalid setting key" } + require(title.isNotBlank() && title.length <= 256 && summary.length <= 1024) + require(minimum <= maximum && maxLength in 1..4096) + require(choices.size <= 64 && choices.map { it.value }.distinct().size == choices.size) + require(choices.all { it.value.length in 1..256 && it.label.length in 1..256 }) + if (type == SettingType.CHOICE) require(choices.isNotEmpty()) + validateValue(value) + } + + fun validateValue(candidate: Any?) { + require(when (type) { + SettingType.BOOLEAN -> candidate is Boolean + SettingType.TEXT -> candidate is String && candidate.length <= maxLength + SettingType.INTEGER -> (candidate is Int || candidate is Long) && + (candidate as Number).toLong() in minimum.toLong()..maximum.toLong() + SettingType.CHOICE -> candidate is String && choices.any { it.value == candidate } + SettingType.ACTION -> candidate == null + }) { "Invalid value for setting $key" } + } + + internal fun json() = JSONObject().apply { + put("key", key); put("title", title); put("type", type.name.lowercase(Locale.ROOT)) + put("value", value ?: JSONObject.NULL); put("summary", summary) + put("enabled", enabled); put("restartRequired", restartRequired) + put("minimum", minimum); put("maximum", maximum); put("maxLength", maxLength) + put("choices", JSONArray().apply { choices.forEach { + put(JSONObject().put("value", it.value).put("label", it.label)) + } }) + } +} + +data class PluginSettingsSchema(val revision: Long, val title: String, val fields: List) { + init { + require(revision >= 0 && title.isNotBlank() && title.length <= 256) + require(fields.size <= 64 && fields.map { it.key }.distinct().size == fields.size) + } + fun toJson(): String = JSONObject().put("version", ProjectionSettings.VERSION) + .put("revision", revision).put("title", title) + .put("fields", JSONArray().apply { fields.forEach { put(it.json()) } }).toString().also { + require(it.toByteArray(Charsets.UTF_8).size <= ProjectionSettings.MAX_SCHEMA_BYTES) + } + + companion object { + fun fromJson(text: String): PluginSettingsSchema { + require(text.toByteArray(Charsets.UTF_8).size <= ProjectionSettings.MAX_SCHEMA_BYTES) + var depth = 0; var quoted = false; var escaped = false + for (character in text) { + if (quoted) { + if (escaped) escaped = false + else if (character == '\\') escaped = true + else if (character == '"') quoted = false + } else when (character) { + '"' -> quoted = true + '{', '[' -> { depth++; require(depth <= 16) { "Settings schema nesting is too deep" } } + '}', ']' -> { depth--; require(depth >= 0) } + } + } + require(depth == 0 && !quoted) + val parser = JSONTokener(text) + val root = parser.nextValue() as? JSONObject ?: throw IllegalArgumentException("Expected settings object") + require(parser.nextClean() == '\u0000') { "Expected one settings object" } + require(root.get("version") == ProjectionSettings.VERSION) { "Unsupported settings schema version" } + require(root.get("revision") is Int || root.get("revision") is Long) { "Invalid settings revision" } + val array = root.getJSONArray("fields") + require(array.length() <= 64) + return PluginSettingsSchema(root.getLong("revision"), string(root, "title"), + (0 until array.length()).map { index -> + val item = array.getJSONObject(index) + val choices = if (item.has("choices")) item.getJSONArray("choices") else JSONArray() + require(choices.length() <= 64) + PluginSetting(string(item, "key"), string(item, "title"), + SettingType.valueOf(string(item, "type").uppercase(Locale.ROOT)), + item.opt("value").takeUnless { it == JSONObject.NULL }, + if (item.has("summary")) string(item, "summary") else "", boolean(item, "enabled", true), + boolean(item, "restartRequired", false), + (0 until choices.length()).map { + val choice = choices.getJSONObject(it) + SettingChoice(string(choice, "value"), string(choice, "label")) + }, integer(item, "minimum", Int.MIN_VALUE), integer(item, "maximum", Int.MAX_VALUE), + integer(item, "maxLength", 1024)) + }) + } + private fun string(json: JSONObject, key: String): String = + (json.get(key) as? String) ?: throw IllegalArgumentException("Invalid string field $key") + private fun boolean(json: JSONObject, key: String, default: Boolean): Boolean = + if (!json.has(key)) default else (json.get(key) as? Boolean) + ?: throw IllegalArgumentException("Invalid boolean field $key") + private fun integer(json: JSONObject, key: String, default: Int): Int { + if (!json.has(key)) return default + val value = json.get(key) + require((value is Int || value is Long) && (value as Number).toLong() in Int.MIN_VALUE.toLong()..Int.MAX_VALUE.toLong()) + return (value as Number).toInt() + } + } +} + +/** The bytes are a real Jetpack Remote Compose document, never HTML or RemoteViews. */ +data class PluginSettingsDocument(val bytes: ByteArray, val width: Int, val height: Int) { + init { + require(bytes.size in 1..ProjectionSettings.MAX_DOCUMENT_BYTES) + require(width in 1..4096 && height in 1..4096 && width.toLong() * height <= 8_388_608) + } +} diff --git a/projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettingsProvider.kt b/projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettingsProvider.kt new file mode 100644 index 00000000..0a42ac63 --- /dev/null +++ b/projection-plugin-api/src/main/java/moe/feng/wheelplay/plugin/ProjectionSettingsProvider.kt @@ -0,0 +1,117 @@ +package moe.feng.wheelplay.plugin + +import android.content.ComponentName +import android.content.ContentProvider +import android.content.ContentValues +import android.content.pm.PackageManager +import android.database.Cursor +import android.net.Uri +import android.os.Binder +import android.os.Bundle +import android.os.Process + +/** A plugin owns persistence and permission flows; reads must not start projection resources. */ +abstract class ProjectionSettingsProvider : ContentProvider() { + protected abstract fun readSettings(source: ComponentName): PluginSettingsSchema + protected abstract fun writeSetting(source: ComponentName, key: String, value: Any?) + protected open val supportsRemoteCompose: Boolean = false + protected open fun remoteDocument(source: ComponentName): PluginSettingsDocument? = null + protected open fun onRemoteAction(source: ComponentName, actionId: Int, value: String?) { + throw UnsupportedOperationException("Unknown remote settings action") + } + protected open fun onNamedRemoteAction(source: ComponentName, name: String, value: Any?) { + throw UnsupportedOperationException("Unknown named remote settings action") + } + protected open fun isHostAllowed(uid: Int): Boolean = uid == Process.myUid() || + requireNotNull(context).packageManager.getPackagesForUid(uid).orEmpty().any { + it == "moe.feng.wheelplay" || it == "moe.feng.wheelplay.debug" + } + final override fun onCreate() = true + + @Suppress("DEPRECATION") + @Synchronized + final override fun call(method: String, arg: String?, extras: Bundle?): Bundle { + if (!isHostAllowed(Binder.getCallingUid())) throw SecurityException("Settings caller not allowed") + require(extras?.getInt("version") == ProjectionSettings.VERSION) { "Unsupported settings protocol" } + val source = requireNotNull(arg?.let(ComponentName::unflattenFromString)) { "Missing settings source" } + require(source.packageName == requireNotNull(context).packageName) { "Settings source belongs to another APK" } + val service = requireNotNull(context).packageManager.getServiceInfo(source, PackageManager.GET_META_DATA) + require(service.metaData?.getInt(ProjectionPlugin.META_API_VERSION) == ProjectionPlugin.API_VERSION) { + "Not a projection source" + } + return try { + val before = readSettings(source) + if (method != ProjectionSettings.GET && extras.getLong("revision", -1) != before.revision) + return snapshot(source, extras.getBoolean("include_remote"), "conflict") + when (method) { + ProjectionSettings.GET -> Unit + ProjectionSettings.SET -> { + val key = requireNotNull(extras.getString("key")) + val field = requireNotNull(before.fields.singleOrNull { it.key == key }) { "Unknown setting" } + require(field.enabled) { "Setting is disabled" } + val encoded = requireNotNull(extras.getString("value")) + val value = ProjectionSettings.decodeValue(encoded) + field.validateValue(value) + writeSetting(source, key, value) + } + ProjectionSettings.ACTION -> { + require(supportsRemoteCompose) + val name = extras.getString("action_name") + if (name != null) { + require(name.length in 1..128) + onNamedRemoteAction(source, name, + ProjectionSettings.decodeValue(requireNotNull(extras.getString("action_json")))) + } else { + require(extras.containsKey("action_id")) + val value = extras.getString("action_value") + require(value == null || value.length <= 4096) + onRemoteAction(source, extras.getInt("action_id"), value) + } + } + else -> throw UnsupportedOperationException("Unknown settings method") + } + snapshot(source, extras.getBoolean("include_remote")).also { + if (method != ProjectionSettings.GET) notifySettingsChanged() + } + } catch (error: IllegalArgumentException) { + failure("invalid", error) + } catch (error: UnsupportedOperationException) { + failure("unsupported", error) + } catch (error: Exception) { + failure("error", error) + } + } + + private fun failure(status: String, error: Exception) = Bundle().apply { + putInt("version", ProjectionSettings.VERSION); putString("status", status) + putString("message", error.message.orEmpty().take(256)) + } + + private fun snapshot(source: ComponentName, includeRemote: Boolean, status: String = "ok") = Bundle().apply { + putInt("version", ProjectionSettings.VERSION); putString("status", status) + putString("schema", readSettings(source).toJson()) + putBoolean("supports_remote", supportsRemoteCompose) + if (includeRemote && supportsRemoteCompose) { + val document = requireNotNull(remoteDocument(source)) { "Remote Compose document unavailable" } + putString("remote_version", ProjectionSettings.REMOTE_COMPOSE_VERSION) + putByteArray("remote_document", document.bytes) + putInt("remote_width", document.width); putInt("remote_height", document.height) + } + } + + /** Also call after configuration changes outside this provider. */ + protected fun notifySettingsChanged() { + val authority = requireNotNull(context).packageManager.getProviderInfo( + ComponentName(requireNotNull(context), javaClass), 0).authority + authority.split(';').forEach { + requireNotNull(context).contentResolver.notifyChange(ProjectionSettings.uri(it), null) + } + } + + final override fun getType(uri: Uri) = "vnd.android.cursor.item/vnd.wheelplay.plugin-settings" + final override fun query(uri: Uri, projection: Array?, selection: String?, + selectionArgs: Array?, sortOrder: String?): Cursor? = null + final override fun insert(uri: Uri, values: ContentValues?): Uri? = throw UnsupportedOperationException() + final override fun delete(uri: Uri, selection: String?, selectionArgs: Array?) = throw UnsupportedOperationException() + final override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?) = throw UnsupportedOperationException() +} diff --git a/projection-plugin-api/src/test/java/moe/feng/wheelplay/plugin/ProjectionSettingsProviderTest.kt b/projection-plugin-api/src/test/java/moe/feng/wheelplay/plugin/ProjectionSettingsProviderTest.kt new file mode 100644 index 00000000..e04d070e --- /dev/null +++ b/projection-plugin-api/src/test/java/moe/feng/wheelplay/plugin/ProjectionSettingsProviderTest.kt @@ -0,0 +1,161 @@ +package moe.feng.wheelplay.plugin + +import android.content.ComponentName +import android.content.Context +import android.content.pm.PackageManager +import android.content.pm.ProviderInfo +import android.content.pm.ServiceInfo +import android.database.ContentObserver +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.ShadowContentResolver + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [29]) +class ProjectionSettingsProviderTest { + class Provider : ProjectionSettingsProvider() { + var allowed = true + var revision = 0L + var value = false + var writes = 0 + override fun isHostAllowed(uid: Int) = allowed + override val supportsRemoteCompose = true + override fun readSettings(source: ComponentName) = PluginSettingsSchema(revision, "Test", listOf( + PluginSetting("enabled", "Enabled", SettingType.BOOLEAN, value), + PluginSetting("locked", "Locked", SettingType.BOOLEAN, false, enabled = false), + PluginSetting("fps", "FPS", SettingType.INTEGER, 15, minimum = 5, maximum = 30), + )) + override fun writeSetting(source: ComponentName, key: String, value: Any?) { + writes++; revision++ + if (key == "enabled") this.value = value as Boolean + } + override fun remoteDocument(source: ComponentName) = PluginSettingsDocument(byteArrayOf(1, 2, 3), 320, 180) + override fun onRemoteAction(source: ComponentName, actionId: Int, value: String?) { + require(actionId == 7); this.value = !this.value; revision++ + } + override fun onNamedRemoteAction(source: ComponentName, name: String, value: Any?) { + require(name == "toggle" && value is Boolean); this.value = value; revision++ + } + } + private lateinit var context: Context + private lateinit var provider: Provider + private lateinit var source: ComponentName + private val authority = "test.plugin.settings" + @Before fun install() { + context = RuntimeEnvironment.getApplication() + source = ComponentName(context.packageName, context.packageName + ".ProjectionService") + val info = ProviderInfo().apply { + name = Provider::class.java.name; packageName = context.packageName + applicationInfo = context.applicationInfo; this.authority = this@ProjectionSettingsProviderTest.authority + exported = true; enabled = true + } + val service = ServiceInfo().apply { + name = source.className; packageName = context.packageName; applicationInfo = context.applicationInfo + enabled = true; exported = true + metaData = Bundle().apply { putInt(ProjectionPlugin.META_API_VERSION, ProjectionPlugin.API_VERSION) } + } + val pkg = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_META_DATA).apply { + services = arrayOf(service); providers = arrayOf(info) + } + shadowOf(context.packageManager).installPackage(pkg) + provider = Provider().apply { attachInfo(this@ProjectionSettingsProviderTest.context, info) } + ShadowContentResolver.registerProviderInternal(authority, provider) + } + private fun call(method: String = ProjectionSettings.GET, bundle: Bundle = ProjectionSettings.request()): Bundle = + requireNotNull(context.contentResolver.call(ProjectionSettings.uri(authority), method, source.flattenToString(), bundle)) + private fun set(key: String, value: Any?, revision: Long = provider.revision) = call(ProjectionSettings.SET, + ProjectionSettings.request(revision).apply { putString("key", key); putString("value", ProjectionSettings.encodeValue(value)) }) + + @Test fun schemaRoundTripUsesStrictTypesAndBounds() { + val schema = PluginSettingsSchema(4, "Settings", listOf( + PluginSetting("text", "Text", SettingType.TEXT, "a\"b", maxLength = 8), + PluginSetting("flag", "Flag", SettingType.BOOLEAN, true), + PluginSetting("choice", "Choice", SettingType.CHOICE, "a", + choices = listOf(SettingChoice("a", "A"), SettingChoice("b", "B"))), + )) + assertEquals(schema, PluginSettingsSchema.fromJson(schema.toJson())) + assertEquals("a\"b", ProjectionSettings.decodeValue(ProjectionSettings.encodeValue("a\"b"))) + for (invalid in listOf("true", 1)) assertThrows(IllegalArgumentException::class.java) { + schema.fields[1].validateValue(invalid) + } + assertThrows(IllegalArgumentException::class.java) { schema.fields.first().validateValue("123456789") } + assertThrows(IllegalArgumentException::class.java) { schema.fields.last().validateValue("unknown") } + assertThrows(IllegalArgumentException::class.java) { PluginSettingsSchema.fromJson(schema.toJson() + " true") } + val locale = java.util.Locale.getDefault() + try { + java.util.Locale.setDefault(java.util.Locale.forLanguageTag("tr-TR")) + val integer = PluginSettingsSchema(0, "Integer", listOf(PluginSetting("fps", "FPS", SettingType.INTEGER, 15))) + assertEquals(integer, PluginSettingsSchema.fromJson(integer.toJson())) + } finally { java.util.Locale.setDefault(locale) } + } + @Test fun realContentResolverReadWriteAndRevisionConflicts() { + assertEquals(0L, PluginSettingsSchema.fromJson(call().getString("schema")!!).revision) + assertEquals("ok", set("enabled", true).getString("status")) + assertTrue(provider.value); assertEquals(1L, provider.revision) + val stale = set("enabled", false, 0) + assertEquals("conflict", stale.getString("status")) + assertTrue(provider.value); assertEquals(1, provider.writes) + assertEquals(1L, PluginSettingsSchema.fromJson(stale.getString("schema")!!).revision) + } + @Test fun disabledUnknownAndInvalidValuesNeverReachPluginPersistence() { + for ((key, value) in listOf("locked" to true, "unknown" to true, "enabled" to "true", "fps" to 31, "fps" to 5.5)) + assertEquals("invalid", set(key, value).getString("status")) + assertEquals(0, provider.writes) + } + @Test fun unauthorizedCallersAndForeignSourcesAreRejected() { + provider.allowed = false + assertThrows(SecurityException::class.java) { call() } + provider.allowed = true + assertThrows(IllegalArgumentException::class.java) { + provider.call(ProjectionSettings.GET, "other.apk/.Source", ProjectionSettings.request()) + } + assertThrows(IllegalArgumentException::class.java) { + call(bundle = ProjectionSettings.request().apply { putInt("version", 99) }) + } + } + @Test fun remoteDocumentsAndBothActionKindsShareTheSchemaRevision() { + val first = call(bundle = ProjectionSettings.request(remote = true)) + assertTrue(first.getBoolean("supports_remote")) + assertArrayEquals(byteArrayOf(1, 2, 3), first.getByteArray("remote_document")) + assertEquals("ok", call(ProjectionSettings.ACTION, ProjectionSettings.request(0, true).apply { + putInt("action_id", 7) + }).getString("status")) + assertTrue(provider.value) + assertEquals("ok", call(ProjectionSettings.ACTION, ProjectionSettings.request(1).apply { + putString("action_name", "toggle"); putString("action_json", "false") + }).getString("status")) + assertFalse(provider.value); assertEquals(2L, provider.revision) + } + @Test fun successfulChangesNotifyObserversAndReadsDoNot() { + var changes = 0 + val observer = object : ContentObserver(Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) { changes++ } + } + context.contentResolver.registerContentObserver(ProjectionSettings.uri(authority), true, observer) + try { + call(); shadowOf(Looper.getMainLooper()).idle(); assertEquals(0, changes) + set("enabled", true); shadowOf(Looper.getMainLooper()).idle(); assertEquals(1, changes) + } finally { context.contentResolver.unregisterContentObserver(observer) } + } + @Test fun schemasAndDocumentsHaveBoundedSizeAndUniqueKeys() { + val field = PluginSetting("value", "Value", SettingType.TEXT, "") + assertThrows(IllegalArgumentException::class.java) { PluginSettingsSchema(0, "Test", listOf(field, field)) } + assertThrows(IllegalArgumentException::class.java) { PluginSettingsDocument(ByteArray(ProjectionSettings.MAX_DOCUMENT_BYTES + 1), 1, 1) } + assertThrows(IllegalArgumentException::class.java) { PluginSettingsDocument(byteArrayOf(1), 4096, 4096) } + assertThrows(IllegalArgumentException::class.java) { + PluginSettingsSchema(0, "Large", (0 until 64).map { + PluginSetting("text$it", "Text", SettingType.TEXT, "x".repeat(4096), maxLength = 4096) + }).toJson() + } + assertThrows(IllegalArgumentException::class.java) { ProjectionSettings.decodeValue("[1,2]") } + } +} diff --git a/projection-plugin-sample/build.gradle.kts b/projection-plugin-sample/build.gradle.kts index e0a436c2..3b18affe 100644 --- a/projection-plugin-sample/build.gradle.kts +++ b/projection-plugin-sample/build.gradle.kts @@ -15,4 +15,18 @@ android { targetCompatibility = JavaVersion.VERSION_11 } } -dependencies { implementation(project(":projection-plugin-api")) } +dependencies { + implementation(project(":projection-plugin-api")) + implementation(libs.androidx.remote.creation.android) + implementation(libs.androidx.remote.creation.core) + testImplementation(libs.junit) + testImplementation("org.robolectric:robolectric:4.17") + testImplementation(libs.androidx.remote.player.core) + testImplementation(libs.androidx.remote.player.view) +} + +android.testOptions.unitTests.isIncludeAndroidResources = true + +tasks.withType().configureEach { + jvmArgs("--add-exports=java.base/jdk.internal.access=ALL-UNNAMED") +} diff --git a/projection-plugin-sample/src/main/AndroidManifest.xml b/projection-plugin-sample/src/main/AndroidManifest.xml index bc1cf595..8fb694a7 100644 --- a/projection-plugin-sample/src/main/AndroidManifest.xml +++ b/projection-plugin-sample/src/main/AndroidManifest.xml @@ -6,7 +6,10 @@ + + diff --git a/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleProjectionService.kt b/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleProjectionService.kt index 95c0969d..341fd504 100644 --- a/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleProjectionService.kt +++ b/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleProjectionService.kt @@ -15,8 +15,14 @@ class SampleProjectionService : ProjectionPluginService() { private var worker: ScheduledExecutorService? = null @Volatile private var contacts = emptyList() @Volatile private var night = false - override fun videoInfo() = PluginVideoInfo(640, 360, 10, nightMode = true) + private val preferences get() = getSharedPreferences("sample-settings", 0) + override fun videoInfo() = if (preferences.getString("resolution", "360p") == "720p") + PluginVideoInfo(1280, 720, 10, nightMode = true) + else PluginVideoInfo(640, 360, 10, nightMode = true) override fun onStartProjection(surface: Surface, events: Events) { + val caption = preferences.getString("caption", "Independent APK · Surface plugin").orEmpty() + val counter = preferences.getBoolean("counter", true) + val period = 1000L / preferences.getInt("fps", 15).coerceIn(5, 30) var frame = 0L val paint = Paint(Paint.ANTI_ALIAS_FLAG) worker = Executors.newSingleThreadScheduledExecutor().also { executor -> @@ -26,19 +32,19 @@ class SampleProjectionService : ProjectionPluginService() { try { canvas.drawColor(if (night) Color.rgb(16, 20, 32) else Color.rgb(25, 70, 100)) paint.color = Color.WHITE; paint.textSize = 28f - canvas.drawText("Independent APK · Surface plugin", 24f, 48f, paint) + canvas.drawText(caption, 24f, 48f, paint) paint.textSize = 20f - canvas.drawText("Frame $frame · ${contacts.count { it.down }} contacts", 24f, 80f, paint) + canvas.drawText("${if (counter) "Frame $frame · " else ""}${contacts.count { it.down }} contacts", 24f, 80f, paint) canvas.drawText("Touch the car browser to draw circles", 24f, 330f, paint) paint.color = Color.CYAN canvas.drawRect((frame % 580).toFloat(), 120f, (frame % 580 + 50).toFloat(), 150f, paint) contacts.filter { it.down }.forEach { - canvas.drawCircle((it.x * 639).toFloat(), (it.y * 359).toFloat(), 20f, paint) + canvas.drawCircle((it.x * (canvas.width - 1)).toFloat(), (it.y * (canvas.height - 1)).toFloat(), 20f, paint) } } finally { surface.unlockCanvasAndPost(canvas) } if (frame++ == 0L) events.state(ProjectionPlugin.READY, "Separate APK connected") } catch (failure: Exception) { events.ended(failure.message ?: "Surface failed") } - }, 0, 66, TimeUnit.MILLISECONDS) + }, 0, period, TimeUnit.MILLISECONDS) } } override fun onTouch(contacts: List) { this.contacts = contacts } diff --git a/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsActivity.kt b/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsActivity.kt index dddfc43c..de99056d 100644 --- a/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsActivity.kt +++ b/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsActivity.kt @@ -10,7 +10,7 @@ class SampleSettingsActivity : Activity() { setContentView(TextView(this).apply { textSize = 20f setPadding(32, 64, 32, 32) - text = "WheelPlay plugin sample\n\nOpen WheelPlay → Sources → Plugin sources. Enable Surface plugin demo, then connect.\n\nThis sample draws in a separate APK and receives up to ten browser touches. It needs no network, microphone or USB permissions.\n\nA real CarLink plugin can provide its own configuration and Android permission flow here." + text = "WheelPlay plugin sample\n\nOpen WheelPlay → Sources → Plugin sources → Settings. The host now embeds a standard settings form and a Jetpack Remote Compose page. Both edit this plugin's own settings; reconnect projection to apply changes.\n\nEnable Surface plugin demo, then connect. This sample draws in a separate APK and receives up to ten browser touches. It needs no network, microphone or USB permissions.\n\nA real CarLink plugin can keep its device permission and SDK setup flow in this separate Activity." }) } } diff --git a/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProvider.kt b/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProvider.kt new file mode 100644 index 00000000..7ea441e5 --- /dev/null +++ b/projection-plugin-sample/src/main/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProvider.kt @@ -0,0 +1,74 @@ +package moe.feng.wheelplay.plugin.sample + +import android.annotation.SuppressLint +import android.content.ComponentName +import android.graphics.Color +import androidx.compose.remote.creation.RemoteComposeWriter +import androidx.compose.remote.creation.profile.RcPlatformProfiles +import androidx.compose.remote.core.operations.Header +import moe.feng.wheelplay.plugin.* + +/** The schema and Remote Compose page edit the same plugin-owned preferences. */ +class SampleSettingsProvider : ProjectionSettingsProvider() { + private val preferences get() = requireNotNull(context).getSharedPreferences("sample-settings", 0) + override val supportsRemoteCompose = true + + override fun readSettings(source: ComponentName) = PluginSettingsSchema( + preferences.getLong("revision", 0), "Surface demo settings", listOf( + PluginSetting("counter", "Show frame counter", SettingType.BOOLEAN, + preferences.getBoolean("counter", true), restartRequired = true), + PluginSetting("fps", "Animation frame rate", SettingType.INTEGER, + preferences.getInt("fps", 15), minimum = 5, maximum = 30, restartRequired = true), + PluginSetting("caption", "Caption", SettingType.TEXT, + preferences.getString("caption", "Independent APK · Surface plugin"), maxLength = 80, restartRequired = true), + PluginSetting("resolution", "Resolution", SettingType.CHOICE, + preferences.getString("resolution", "360p"), restartRequired = true, + choices = listOf(SettingChoice("360p", "640 × 360"), SettingChoice("720p", "1280 × 720"))), + PluginSetting("reset", "Reset demo settings", SettingType.ACTION), + )) + + override fun writeSetting(source: ComponentName, key: String, value: Any?) { + val next = preferences.getLong("revision", 0) + 1 + val edit = preferences.edit() + when (key) { + "counter" -> edit.putBoolean(key, value as Boolean) + "fps" -> edit.putInt(key, (value as Number).toInt()) + "caption", "resolution" -> edit.putString(key, value as String) + "reset" -> edit.clear() + else -> error("Unknown sample setting") + } + check(edit.putLong("revision", next).commit()) { "Could not save settings" } + } + + override fun onRemoteAction(source: ComponentName, actionId: Int, value: String?) { + when (actionId) { + 1 -> writeSetting(source, "counter", !preferences.getBoolean("counter", true)) + 2 -> writeSetting(source, "fps", (preferences.getInt("fps", 15) + 5).let { if (it > 30) 5 else it }) + else -> throw IllegalArgumentException("Unknown sample action") + } + } + + @SuppressLint("RestrictedApi") + override fun remoteDocument(source: ComponentName): PluginSettingsDocument { + val writer = RemoteComposeWriter(RcPlatformProfiles.ANDROIDX, + RemoteComposeWriter.hTag(Header.DOC_WIDTH, 720), RemoteComposeWriter.hTag(Header.DOC_HEIGHT, 360), + RemoteComposeWriter.hTag(Header.DOC_CONTENT_DESCRIPTION, "Surface demo settings")) + val paint = writer.rcPaint + paint.setColor(Color.rgb(24, 32, 48)).commit() + writer.drawRect(0f, 0f, 720f, 360f) + fun text(value: String, y: Float, size: Float = 24f) { + paint.setColor(Color.WHITE).setTextSize(size).commit() + writer.drawTextRun(value, 0, value.length, 0, value.length, 24f, y, false) + } + text("Remote Compose · Surface demo", 44f, 30f) + text("Changes apply on the next projection connection", 80f, 21f) + paint.setColor(Color.rgb(49, 75, 106)).commit() + writer.drawRect(16f, 108f, 704f, 196f) + writer.drawRect(16f, 212f, 704f, 300f) + text("Frame counter: ${if (preferences.getBoolean("counter", true)) "on" else "off"} · tap to toggle", 160f) + text("Animation: ${preferences.getInt("fps", 15)} fps · tap for next speed", 266f) + writer.addClickArea(1, "Toggle frame counter", 16f, 108f, 704f, 196f, null) + writer.addClickArea(2, "Change animation frame rate", 16f, 212f, 704f, 300f, null) + return PluginSettingsDocument(writer.encodeToByteArray(), 720, 360) + } +} diff --git a/projection-plugin-sample/src/test/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProviderTest.kt b/projection-plugin-sample/src/test/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProviderTest.kt new file mode 100644 index 00000000..67abcef3 --- /dev/null +++ b/projection-plugin-sample/src/test/java/moe/feng/wheelplay/plugin/sample/SampleSettingsProviderTest.kt @@ -0,0 +1,90 @@ +package moe.feng.wheelplay.plugin.sample + +import android.annotation.SuppressLint +import android.content.ComponentName +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.os.Bundle +import android.view.View +import android.view.MotionEvent +import android.os.SystemClock +import java.io.File +import androidx.compose.remote.core.CoreDocument +import androidx.compose.remote.player.core.RemoteDocument +import androidx.compose.remote.player.view.RemoteComposePlayer +import moe.feng.wheelplay.plugin.* +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [29]) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@SuppressLint("RestrictedApi") +class SampleSettingsProviderTest { + @Test fun schemaAndRealRemoteComposeDocumentEditTheSamePreferences() { + val context = RuntimeEnvironment.getApplication() + val controller = Robolectric.buildContentProvider(SampleSettingsProvider::class.java).create() + val provider = controller.get() + val source = ComponentName(context, SampleProjectionService::class.java).flattenToString() + fun request(method: String = ProjectionSettings.GET, extras: Bundle = ProjectionSettings.request(remote = true)) = + provider.call(method, source, extras) + val first = request() + assertEquals(first.getString("message"), "ok", first.getString("status")) + val schema = PluginSettingsSchema.fromJson(first.getString("schema")!!) + assertEquals(true, schema.fields.first { it.key == "counter" }.value) + val bytes = first.getByteArray("remote_document")!! + val document = RemoteDocument(bytes) + assertTrue(document.canBeDisplayed(CoreDocument.MAJOR_VERSION, CoreDocument.MINOR_VERSION, 0)) + val player = RemoteComposePlayer(context) + var action: Int? = null + player.setDocument(document) + player.addIdActionListener { id, _ -> action = id } + val activityController = Robolectric.buildActivity(android.app.Activity::class.java).setup() + activityController.get().setContentView(player) + org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() + assertEquals(720, document.document.width) + assertEquals(360, document.document.height) + player.measure(View.MeasureSpec.makeMeasureSpec(720, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(360, View.MeasureSpec.EXACTLY)) + player.layout(0, 0, 720, 360) + val bitmap = Bitmap.createBitmap(720, 360, Bitmap.Config.ARGB_8888) + player.draw(Canvas(bitmap)) + assertEquals(Color.rgb(24, 32, 48), bitmap.getPixel(4, 4)) + assertEquals(Color.rgb(49, 75, 106), bitmap.getPixel(20, 120)) + assertTrue(document.document.clickAreas.any { it.id == 1 }) + val image = File("build/reports/plugin-settings/sample-remote-compose.png") + requireNotNull(image.parentFile).mkdirs() + image.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } + val time = SystemClock.uptimeMillis() + for (kind in listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP)) { + val event = MotionEvent.obtain(time, time + 16, kind, 100f, 150f, 0) + player.dispatchTouchEvent(event) + event.recycle() + } + org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle() + assertEquals(1, action) + val changed = request(ProjectionSettings.ACTION, ProjectionSettings.request(schema.revision, true).apply { + putInt("action_id", action!!) + }) + assertEquals("ok", changed.getString("status")) + val updated = PluginSettingsSchema.fromJson(changed.getString("schema")!!) + assertEquals(false, updated.fields.first { it.key == "counter" }.value) + assertFalse(bytes.contentEquals(changed.getByteArray("remote_document")!!)) + val afterSchemaWrite = request(ProjectionSettings.SET, ProjectionSettings.request(updated.revision, true).apply { + putString("key", "fps"); putString("value", "25") + }) + assertEquals(25, PluginSettingsSchema.fromJson(afterSchemaWrite.getString("schema")!!) + .fields.first { it.key == "fps" }.value) + assertFalse(changed.getByteArray("remote_document")!!.contentEquals(afterSchemaWrite.getByteArray("remote_document")!!)) + bitmap.recycle() + activityController.pause().stop().destroy() + controller.shutdown() + } +}