feat: 新增 Row 权重与网络图片验证页,图片改为客户端预取缓存
服务端:spike 页验证 Row/horizontalWeight 与 ContentScale;图片以 URL 下发,通过 X-Remote-Assets 提供清单,并从 RcScopeImpl 取 writer 用真实尺寸登记 addBitmapUrl,修复播放端 1x1 尺寸校验失败。Android:文档声明的图片先异步预取到内存 LRU 与本地文件缓存,自定义 BitmapLoader 同步读内存,消除 NetworkOnMainThreadException;缺图时用透明占位图避免整页黑屏。
This commit is contained in:
1 parent
8cc8107222
commit
244e539b47
6 files changed
+457
-15
No files matched your search
+161
-12
@@ -2,7 +2,9 @@ package com.ttstd.composeremote.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import android.util.LruCache
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -13,7 +15,9 @@ import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ElevatedButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.remote.core.Limits
|
||||
import androidx.compose.remote.player.core.RemoteDocument
|
||||
import androidx.compose.remote.player.core.platform.BitmapLoader
|
||||
import androidx.compose.remote.player.view.RemoteComposePlayer
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
@@ -26,14 +30,21 @@ 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.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.ttstd.composeremote.RemoteConfig
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.security.MessageDigest
|
||||
import java.lang.reflect.InvocationTargetException
|
||||
import java.lang.reflect.Proxy
|
||||
import java.util.concurrent.TimeUnit
|
||||
@@ -52,6 +63,12 @@ private val client = OkHttpClient.Builder()
|
||||
.readTimeout(10, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
/** 一次页面请求的结果:文档字节 + 文档引用的图片地址。 */
|
||||
private class RemoteUiPayload(
|
||||
val bytes: ByteArray,
|
||||
val assets: List<String>,
|
||||
)
|
||||
|
||||
/**
|
||||
* 文档原始字节缓存。
|
||||
*
|
||||
@@ -63,16 +80,16 @@ private val client = OkHttpClient.Builder()
|
||||
private object RemoteDocumentStore {
|
||||
private const val MAX_ENTRIES = 8
|
||||
private val documents = object :
|
||||
LinkedHashMap<String, ByteArray>(MAX_ENTRIES, 0.75f, true) {
|
||||
LinkedHashMap<String, RemoteUiPayload>(MAX_ENTRIES, 0.75f, true) {
|
||||
override fun removeEldestEntry(
|
||||
eldest: MutableMap.MutableEntry<String, ByteArray>,
|
||||
eldest: MutableMap.MutableEntry<String, RemoteUiPayload>,
|
||||
): Boolean = size > MAX_ENTRIES
|
||||
}
|
||||
|
||||
fun get(page: String): ByteArray? = documents[page]
|
||||
fun get(page: String): RemoteUiPayload? = documents[page]
|
||||
|
||||
fun put(page: String, bytes: ByteArray) {
|
||||
documents[page] = bytes
|
||||
fun put(page: String, payload: RemoteUiPayload) {
|
||||
documents[page] = payload
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,27 +99,151 @@ private sealed interface RemoteUiState {
|
||||
data class Error(val message: String) : RemoteUiState
|
||||
}
|
||||
|
||||
private suspend fun fetchRemoteUi(page: String, baseUrl: String): ByteArray =
|
||||
/**
|
||||
* 文档图片的预取与缓存。
|
||||
*
|
||||
* 播放器在 setDocument 阶段会同步调用 [BitmapLoader] 取图片字节;如果交给系统实现
|
||||
* 直接下载,会在主线程访问网络并抛 NetworkOnMainThreadException。因此先把文档声明的
|
||||
* 图片异步下载到「内存 LRU + 本地文件缓存」,播放器随后从内存同步读取。
|
||||
*
|
||||
* 不用 OkHttp 自带的 Cache:公网入口(nginx/Cloudflare)会给图片响应追加
|
||||
* `Cache-Control: no-store`,OkHttp 据此拒绝写缓存;这里改成自己按 URL 存文件,
|
||||
* 只要 URL 不变就不再回源。服务端替换图片时应换新文件名,以触发客户端更新。
|
||||
*/
|
||||
private class RemoteImageLoader(context: Context) {
|
||||
|
||||
private val memory = object : LruCache<String, ByteArray>(
|
||||
(Runtime.getRuntime().maxMemory() / 8).toInt()
|
||||
) {
|
||||
override fun sizeOf(key: String, value: ByteArray): Int = value.size
|
||||
}
|
||||
|
||||
/** 本地图片目录,文件名取 URL 的 SHA-256,避免特殊字符并防止重名。 */
|
||||
private val diskDir = File(context.cacheDir, "remote-images").apply { mkdirs() }
|
||||
|
||||
private val client = OkHttpClient.Builder()
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(10, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
/** 逐张预取:内存 → 本地文件 → 网络;失败重试一次,仍失败则渲染时退回占位图。 */
|
||||
suspend fun prefetch(urls: List<String>) = withContext(Dispatchers.IO) {
|
||||
urls.distinct().forEach { url ->
|
||||
if (memory.get(url) != null) {
|
||||
Log.d(TAG, "内存命中 $url")
|
||||
return@forEach
|
||||
}
|
||||
readFromDisk(url)?.let { bytes ->
|
||||
memory.put(url, bytes)
|
||||
Log.d(TAG, "本地命中 ${bytes.size}B $url")
|
||||
return@forEach
|
||||
}
|
||||
var bytes: ByteArray? = null
|
||||
for (attempt in 0 until 2) {
|
||||
bytes = runCatching {
|
||||
client.newCall(Request.Builder().url(url).build()).execute().use { response ->
|
||||
if (!response.isSuccessful) throw IOException("HTTP ${response.code}")
|
||||
response.body?.bytes() ?: throw IOException("空响应")
|
||||
}
|
||||
}.getOrElse { e ->
|
||||
Log.w(TAG, "预取失败 ${attempt + 1}/2 $url: ${e.message}")
|
||||
null
|
||||
}
|
||||
if (bytes != null) break
|
||||
delay(500)
|
||||
}
|
||||
if (bytes == null) {
|
||||
Log.w(TAG, "图片最终未取到,渲染时使用占位图 $url")
|
||||
return@forEach
|
||||
}
|
||||
memory.put(url, bytes)
|
||||
writeToDisk(url, bytes)
|
||||
Log.d(TAG, "下载完成 ${bytes.size}B $url")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放器在 setDocument 时同步调用,这里只读内存。
|
||||
*
|
||||
* 取不到时返回透明白图而不是抛异常:播放器对 BitmapLoader 异常没有兜底,
|
||||
* 会整页黑屏并显示错误信息,缺一张图不应影响整个页面。
|
||||
*/
|
||||
fun open(url: String): InputStream {
|
||||
val bytes = memory.get(url)
|
||||
Log.d(TAG, if (bytes != null) "命中 ${bytes.size}B $url" else "未命中,返回占位图 $url")
|
||||
return ByteArrayInputStream(bytes ?: placeholder)
|
||||
}
|
||||
|
||||
private fun cacheFile(url: String): File =
|
||||
File(diskDir, MessageDigest.getInstance("SHA-256").digest(url.toByteArray()).toHex())
|
||||
|
||||
private fun readFromDisk(url: String): ByteArray? = runCatching {
|
||||
cacheFile(url).takeIf { it.isFile }?.readBytes()
|
||||
}.getOrNull()
|
||||
|
||||
private fun writeToDisk(url: String, bytes: ByteArray) {
|
||||
runCatching {
|
||||
val target = cacheFile(url)
|
||||
val temp = File(diskDir, target.name + ".tmp")
|
||||
temp.writeBytes(bytes)
|
||||
if (!temp.renameTo(target)) temp.delete()
|
||||
}.onFailure { Log.w(TAG, "写入本地缓存失败 $url: ${it.message}") }
|
||||
}
|
||||
|
||||
private fun ByteArray.toHex(): String =
|
||||
joinToString("") { "%02x".format(it.toInt() and 0xFF) }
|
||||
|
||||
/** 1×1 透明 PNG,在缺图时占位。 */
|
||||
private val placeholder: ByteArray by lazy {
|
||||
val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888)
|
||||
ByteArrayOutputStream().use { out ->
|
||||
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||
bitmap.recycle()
|
||||
out.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "RemoteImageLoader"
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun fetchRemoteUi(page: String, baseUrl: String): RemoteUiPayload =
|
||||
withContext(Dispatchers.IO) {
|
||||
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}")
|
||||
}
|
||||
response.body?.bytes() ?: throw IOException("空响应")
|
||||
val bytes = response.body?.bytes() ?: throw IOException("空响应")
|
||||
val assets = response.header("X-Remote-Assets")
|
||||
?.split(",")
|
||||
?.map { it.trim() }
|
||||
?.filter { it.isNotEmpty() }
|
||||
.orEmpty()
|
||||
RemoteUiPayload(bytes, assets)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出页面文档字节:命中缓存就不重复下载。
|
||||
*
|
||||
* 解析([RemoteDocument] 构造)放在 [Dispatchers.Default],避免大文档阻塞主线程。
|
||||
* 解析([RemoteDocument] 构造)放在 [Dispatchers.Default],避免大文档阻塞主线程;
|
||||
* 图片必须在返回前完成预取,否则播放器渲染时会取不到图片。
|
||||
*/
|
||||
private suspend fun loadDocument(page: String, baseUrl: String): RemoteDocument {
|
||||
val bytes = RemoteDocumentStore.get(page) ?: fetchRemoteUi(page, baseUrl).also {
|
||||
private suspend fun loadDocument(
|
||||
page: String,
|
||||
baseUrl: String,
|
||||
imageLoader: RemoteImageLoader,
|
||||
): RemoteDocument {
|
||||
val payload = RemoteDocumentStore.get(page) ?: fetchRemoteUi(page, baseUrl).also {
|
||||
RemoteDocumentStore.put(page, it)
|
||||
}
|
||||
return withContext(Dispatchers.Default) { RemoteDocument(bytes) }
|
||||
// 文档以 URL 形式声明图片,解析阶段就会校验该开关(默认关闭)。
|
||||
Limits.ENABLE_IMAGE_URLS = true
|
||||
val document = withContext(Dispatchers.Default) { RemoteDocument(payload.bytes) }
|
||||
imageLoader.prefetch(payload.assets)
|
||||
return document
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -190,6 +331,7 @@ private fun Any.findDeclaredField(name: String): java.lang.reflect.Field? {
|
||||
@Composable
|
||||
private fun RemoteDocumentView(
|
||||
document: RemoteDocument?,
|
||||
imageLoader: RemoteImageLoader,
|
||||
onNavigate: (String) -> Unit,
|
||||
onOpenActivity: ((String) -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
@@ -201,6 +343,10 @@ private fun RemoteDocumentView(
|
||||
AndroidView(
|
||||
factory = { context ->
|
||||
val player = AntiAliasRemoteComposePlayer(context)
|
||||
// 播放器同步取图,这里只从预取好的内存缓存读取,避免主线程联网。
|
||||
player.setBitmapLoader(object : BitmapLoader {
|
||||
override fun loadBitmap(url: String): InputStream = imageLoader.open(url)
|
||||
})
|
||||
// 每个播放器实例一个稳定的回调对象,避免同一个 view 反复注册。
|
||||
player.idActionCallback = RemoteComposePlayer.IdActionCallbacks { actionId, metadata ->
|
||||
if (!metadata.isNullOrBlank()) {
|
||||
@@ -245,6 +391,8 @@ fun RemoteUIScreen(
|
||||
var backStack by rememberSaveable { mutableStateOf(listOf<String>()) }
|
||||
var state by remember { mutableStateOf<RemoteUiState>(RemoteUiState.Loading) }
|
||||
var retryToken by remember { mutableIntStateOf(0) }
|
||||
val appContext = LocalContext.current.applicationContext
|
||||
val imageLoader = remember(appContext) { RemoteImageLoader(appContext) }
|
||||
|
||||
BackHandler(enabled = backStack.isNotEmpty()) {
|
||||
page = backStack.last()
|
||||
@@ -257,7 +405,7 @@ fun RemoteUIScreen(
|
||||
state = RemoteUiState.Loading
|
||||
}
|
||||
state = try {
|
||||
RemoteUiState.Success(loadDocument(page, baseUrl))
|
||||
RemoteUiState.Success(loadDocument(page, baseUrl, imageLoader))
|
||||
} catch (e: Exception) {
|
||||
Log.e("RemoteUIScreen", "加载页面 $page 失败", e)
|
||||
RemoteUiState.Error(e.message ?: "加载失败")
|
||||
@@ -267,6 +415,7 @@ fun RemoteUIScreen(
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
RemoteDocumentView(
|
||||
document = (state as? RemoteUiState.Success)?.document,
|
||||
imageLoader = imageLoader,
|
||||
onNavigate = { target ->
|
||||
if (target != page) {
|
||||
backStack = backStack + page
|
||||
|
||||
Reference in new issue
Block a user