fix: 修复远程 UI 间距/自适应/服务端导航,并消除文字锯齿
- 服务端:Spacer 改用 Modifier.height(RcDp);画布改为 400×900dp + RcDensityBehavior.Dp; 字号统一 RcSp;卡片通过 hostAction 下发跳转目标 - Android:文档在后台解析并做 LRU 缓存;复用播放器实例;在 setDocument 之后注册 addIdActionListener,实现服务端驱动跳转;移除硬编码的 FilterChip - Android:代理播放器内部 PaintChanges,在每次画笔变更时强制开启 antiAlias, 规避 alpha24 播放端文字锯齿 - 配置:删除 Java 17 下无效的 spring.threads.virtual.enabled;部署镜像更新为 1.0.0-nav
This commit is contained in:
1 parent
5c5585debe
commit
8a5d0375a6
5 files changed
+304
-154
No files matched your search
@@ -4,22 +4,10 @@ import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
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.material3.FilterChip
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.ttstd.composeremote.ui.RemoteUIScreen
|
||||
import com.ttstd.composeremote.ui.theme.ComposeRemoteAndroidTheme
|
||||
|
||||
@@ -29,29 +17,9 @@ class MainActivity : ComponentActivity() {
|
||||
enableEdgeToEdge()
|
||||
setContent {
|
||||
ComposeRemoteAndroidTheme {
|
||||
// 页面 id 列表,每个 id 对应后端一个独立接口 /api/remote-ui/{page}
|
||||
var page by remember { mutableStateOf("home") }
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
FilterChip(
|
||||
selected = page == "home",
|
||||
onClick = { page = "home" },
|
||||
label = { Text("首页") }
|
||||
)
|
||||
FilterChip(
|
||||
selected = page == "detail",
|
||||
onClick = { page = "detail" },
|
||||
label = { Text("详情") }
|
||||
)
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxSize().weight(1f)) {
|
||||
RemoteUIScreen(page = page)
|
||||
}
|
||||
// 页面切换完全由服务端文档中的点击动作驱动,客户端只提供初始页面。
|
||||
Box(modifier = Modifier.fillMaxSize().systemBarsPadding()) {
|
||||
RemoteUIScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+178
-50
@@ -1,6 +1,7 @@
|
||||
package com.ttstd.composeremote.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -11,49 +12,73 @@ import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ElevatedButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.remote.player.core.RemoteDocument
|
||||
import androidx.compose.remote.player.view.RemoteComposePlayer
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.remote.player.view.RemoteComposePlayer
|
||||
import androidx.compose.remote.player.core.RemoteDocument
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.ttstd.composeremote.RemoteConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.IOException
|
||||
import java.lang.reflect.InvocationTargetException
|
||||
import java.lang.reflect.Proxy
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 与后端约定的 action id:跳转到 metadata 指定的页面。
|
||||
* 具体跳到哪个页面由文档内容决定,客户端不再写死页面列表。
|
||||
*/
|
||||
private const val ACTION_NAVIGATE = 1
|
||||
|
||||
private val client = OkHttpClient.Builder()
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(10, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
private sealed interface RemoteUiState {
|
||||
data object Loading : RemoteUiState
|
||||
data class Success(val bytes: ByteArray) : RemoteUiState {
|
||||
override fun equals(other: Any?): Boolean =
|
||||
other is Success && bytes.contentEquals(other.bytes)
|
||||
|
||||
override fun hashCode(): Int = bytes.contentHashCode()
|
||||
/**
|
||||
* 已解析文档缓存。
|
||||
*
|
||||
* 切页时优先复用已解析的 [RemoteDocument],避免重复下载与重复解析;
|
||||
* 文档较大时解析成本高,因此只缓存有限个页面(LRU)。
|
||||
*/
|
||||
private object RemoteDocumentStore {
|
||||
private const val MAX_ENTRIES = 8
|
||||
private val documents = object :
|
||||
LinkedHashMap<String, RemoteDocument>(MAX_ENTRIES, 0.75f, true) {
|
||||
override fun removeEldestEntry(
|
||||
eldest: MutableMap.MutableEntry<String, RemoteDocument>,
|
||||
): Boolean = size > MAX_ENTRIES
|
||||
}
|
||||
|
||||
fun get(page: String): RemoteDocument? = documents[page]
|
||||
|
||||
fun put(page: String, document: RemoteDocument) {
|
||||
documents[page] = document
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface RemoteUiState {
|
||||
data object Loading : RemoteUiState
|
||||
data class Success(val document: RemoteDocument) : RemoteUiState
|
||||
data class Error(val message: String) : RemoteUiState
|
||||
}
|
||||
|
||||
private suspend fun fetchRemoteUi(page: String, baseUrl: String): ByteArray =
|
||||
withContext(Dispatchers.IO) {
|
||||
val url = "$baseUrl/api/remote-ui/$page"
|
||||
val request = Request.Builder().url(url).build()
|
||||
val request = Request.Builder().url("$baseUrl/api/remote-ui/$page").build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
throw IOException("HTTP ${response.code}")
|
||||
@@ -63,67 +88,170 @@ private suspend fun fetchRemoteUi(page: String, baseUrl: String): ByteArray =
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 [RemoteComposePlayer] 渲染 Remote Compose 文档。
|
||||
* 下载并解析页面文档。
|
||||
*
|
||||
* 在 alpha17 版本中,建议显式创建 [RemoteDocument] 并使用 [RemoteComposePlayer.setDocument]
|
||||
* 的 RemoteDocument 重载版本。同时将 setDocument 放在 AndroidView 的 update 块中,
|
||||
* 以确保在数据变化时能正确触发 View 的更新。
|
||||
* 解析([RemoteDocument] 构造)放在 [Dispatchers.Default],避免大文档阻塞主线程。
|
||||
*/
|
||||
private suspend fun loadDocument(page: String, baseUrl: String): RemoteDocument {
|
||||
RemoteDocumentStore.get(page)?.let { return it }
|
||||
val bytes = fetchRemoteUi(page, baseUrl)
|
||||
val document = withContext(Dispatchers.Default) { RemoteDocument(bytes) }
|
||||
RemoteDocumentStore.put(page, document)
|
||||
return document
|
||||
}
|
||||
|
||||
/**
|
||||
* 规避 alpha24 播放器的文字锯齿。
|
||||
*
|
||||
* 播放端共享的 `android.graphics.Paint` 默认 `isAntiAlias = false`,而 `CoreText`
|
||||
* 每次绘制文字都会 `replacePaint()`:先 `Paint.reset()`(抗锯齿归零)再应用文本
|
||||
* 自带的 PaintBundle,该 bundle 不含 antiAlias 标记,因此服务端无法通过文档打开
|
||||
* 文字抗锯齿。这里把播放器内部的 `PaintChanges` 换成代理,在每次应用画笔变更时
|
||||
* 顺带打开 antiAlias。
|
||||
*
|
||||
* 不直接替换 `mPaint` 实例:`savePaint()/restorePaint()` 会把 `mPaint` 换回普通
|
||||
* `Paint` 拷贝,替换只对第一帧有效。
|
||||
*/
|
||||
private class AntiAliasRemoteComposePlayer(context: Context) : RemoteComposePlayer(context) {
|
||||
|
||||
/**
|
||||
* `mInner` 是父类的 protected 字段,`mARContext` / `mPaintContext` /
|
||||
* `mCachedPaintChanges` 是播放库内部字段,只能通过反射拿到;
|
||||
* 任一步取不到都保持原样,不影响正常渲染。
|
||||
*/
|
||||
fun enableAntiAliasing() {
|
||||
try {
|
||||
val arContext = mInner.declaredField("mARContext").get(mInner) ?: return
|
||||
val paintContext = arContext.findDeclaredField("mPaintContext")?.get(arContext) ?: return
|
||||
val changesField = paintContext.declaredField("mCachedPaintChanges")
|
||||
val delegate = changesField.get(paintContext) ?: return
|
||||
if (Proxy.isProxyClass(delegate.javaClass)) return
|
||||
|
||||
val changesClass = delegate.javaClass.interfaces.first()
|
||||
val setAntiAlias = changesClass.getMethod("setAntiAlias", Boolean::class.javaPrimitiveType)
|
||||
val proxy = Proxy.newProxyInstance(changesClass.classLoader, arrayOf(changesClass)) { _, method, args ->
|
||||
when {
|
||||
method.declaringClass == Any::class.java -> when (method.name) {
|
||||
"equals" -> delegate === args?.firstOrNull()
|
||||
"hashCode" -> System.identityHashCode(delegate)
|
||||
else -> "AntiAliasPaintChanges"
|
||||
}
|
||||
|
||||
else -> {
|
||||
if (method.name.startsWith("set")) {
|
||||
// 代理在绘制线程被调用,任何反射异常都不能冒泡到播放器绘制流程。
|
||||
runCatching { setAntiAlias.invoke(delegate, true) }
|
||||
}
|
||||
try {
|
||||
method.invoke(delegate, *(args ?: emptyArray<Any?>()))
|
||||
} catch (e: InvocationTargetException) {
|
||||
throw e.targetException
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
changesField.set(paintContext, proxy)
|
||||
} catch (e: Exception) {
|
||||
Log.w("RemoteUIScreen", "开启文字抗锯齿失败", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun Any.declaredField(name: String) =
|
||||
javaClass.getDeclaredField(name).apply { isAccessible = true }
|
||||
|
||||
/** 沿继承链查找字段(`mPaintContext` 声明在父类上)。 */
|
||||
private fun Any.findDeclaredField(name: String): java.lang.reflect.Field? {
|
||||
var cls: Class<*>? = javaClass
|
||||
while (cls != null) {
|
||||
cls.declaredFields.firstOrNull { it.name == name }?.let {
|
||||
return it.apply { isAccessible = true }
|
||||
}
|
||||
cls = cls.superclass
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放器只创建一次,切页时复用同一个 [RemoteComposePlayer] 实例,仅替换文档。
|
||||
*
|
||||
* 服务端通过 hostAction 下发的点击会回调 [RemoteComposePlayer.addIdActionListener],
|
||||
* 这里把 metadata(页面 id)交给上层完成跳转,实现真正的服务端驱动导航。
|
||||
*/
|
||||
@SuppressLint("RestrictedApiAndroidX")
|
||||
@Composable
|
||||
private fun RemoteDocumentView(
|
||||
bytes: ByteArray,
|
||||
document: RemoteDocument?,
|
||||
onNavigate: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
contentKey: Any = bytes.contentHashCode(),
|
||||
) {
|
||||
key(contentKey) {
|
||||
AndroidView(
|
||||
factory = { ctx ->
|
||||
// 仅创建播放器实例
|
||||
RemoteComposePlayer(ctx)
|
||||
},
|
||||
update = { view ->
|
||||
// factory 只执行一次,用 rememberUpdatedState 保证回调始终指向最新的 lambda。
|
||||
val currentOnNavigate by rememberUpdatedState(onNavigate)
|
||||
|
||||
AndroidView(
|
||||
factory = { context -> AntiAliasRemoteComposePlayer(context) },
|
||||
update = { view ->
|
||||
if (document != null && view.tag !== document) {
|
||||
try {
|
||||
// 1. 将二进制显式解析为 RemoteDocument 对象
|
||||
val document = RemoteDocument(bytes)
|
||||
// 2. 使用 RemoteDocument 重载版本设置文档,确保解析与生命周期同步
|
||||
view.setDocument(document)
|
||||
Log.d("RemoteUIScreen", "文档解析并加载成功: ${bytes.size} 字节")
|
||||
view.tag = document
|
||||
// 文字绘制会重置画笔,因此在设置文档后再次确保抗锯齿生效。
|
||||
view.enableAntiAliasing()
|
||||
// 播放器只在已设置文档时才会真正登记点击回调,因此必须在 setDocument 之后注册。
|
||||
if (document.document.idActionListeners.isEmpty()) {
|
||||
view.addIdActionListener(
|
||||
RemoteComposePlayer.IdActionCallbacks { actionId, metadata ->
|
||||
if (actionId == ACTION_NAVIGATE && !metadata.isNullOrBlank()) {
|
||||
currentOnNavigate(metadata)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("RemoteUIScreen", "文档解析失败", e)
|
||||
Log.e("RemoteUIScreen", "文档加载失败", e)
|
||||
}
|
||||
},
|
||||
modifier = modifier
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = modifier
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RemoteUIScreen(page: String, baseUrl: String = RemoteConfig.SERVER_BASE_URL) {
|
||||
var state by remember(page) { mutableStateOf<RemoteUiState>(RemoteUiState.Loading) }
|
||||
fun RemoteUIScreen(
|
||||
startPage: String = "home",
|
||||
baseUrl: String = RemoteConfig.SERVER_BASE_URL,
|
||||
) {
|
||||
var page by rememberSaveable { mutableStateOf(startPage) }
|
||||
var state by remember { mutableStateOf<RemoteUiState>(RemoteUiState.Loading) }
|
||||
var retryToken by remember { mutableIntStateOf(0) }
|
||||
|
||||
LaunchedEffect(page, retryToken) {
|
||||
// 命中缓存时直接渲染,不闪 loading、不重复请求。
|
||||
RemoteDocumentStore.get(page)?.let {
|
||||
state = RemoteUiState.Success(it)
|
||||
return@LaunchedEffect
|
||||
}
|
||||
state = RemoteUiState.Loading
|
||||
state = try {
|
||||
val bytes = fetchRemoteUi(page, baseUrl)
|
||||
RemoteUiState.Success(bytes)
|
||||
RemoteUiState.Success(loadDocument(page, baseUrl))
|
||||
} catch (e: Exception) {
|
||||
Log.e("RemoteUIScreen", "Fetch failed", e)
|
||||
Log.e("RemoteUIScreen", "加载页面 $page 失败", e)
|
||||
RemoteUiState.Error(e.message ?: "加载失败")
|
||||
}
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
when (val s = state) {
|
||||
is RemoteUiState.Loading -> CircularProgressIndicator()
|
||||
is RemoteUiState.Error -> ErrorView(s.message) { retryToken++ }
|
||||
is RemoteUiState.Success -> {
|
||||
RemoteDocumentView(
|
||||
bytes = s.bytes,
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
RemoteDocumentView(
|
||||
document = (state as? RemoteUiState.Success)?.document,
|
||||
onNavigate = { target -> page = target },
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
when (val current = state) {
|
||||
is RemoteUiState.Loading ->
|
||||
CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
is RemoteUiState.Error -> ErrorView(current.message) { retryToken++ }
|
||||
is RemoteUiState.Success -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user