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
|
||||
|
||||
@@ -22,7 +22,7 @@ spec:
|
||||
spec:
|
||||
containers:
|
||||
- name: server
|
||||
image: composeremote/server:1.0.0-list
|
||||
image: composeremote/server:1.0.0-imgcache5
|
||||
imagePullPolicy: Never
|
||||
ports:
|
||||
- name: http
|
||||
|
||||
+42
-2
@@ -1,11 +1,20 @@
|
||||
package com.ttstd.composeremote.server.controller;
|
||||
|
||||
import com.ttstd.composeremote.server.RemoteDocumentBuilderKt;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 服务端驱动 UI 接口。
|
||||
@@ -17,6 +26,9 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
* </ul>
|
||||
* 返回 {@code application/octet-stream} 的 Remote Compose 二进制文档,
|
||||
* 由 Android 端 {@code RemoteComposePlayer} 原生渲染。
|
||||
*
|
||||
* <p>页面引用图片时,通过 {@code X-Remote-Assets} 响应头下发图片清单,
|
||||
* 播放端先异步预取并缓存,再交给播放器渲染。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/remote-ui")
|
||||
@@ -26,8 +38,36 @@ public class RemoteUIController {
|
||||
value = {"/{page}", ""},
|
||||
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
|
||||
)
|
||||
public byte[] getPage(@PathVariable(name = "page", required = false) String page) {
|
||||
public ResponseEntity<byte[]> getPage(@PathVariable(name = "page", required = false) String page) {
|
||||
String target = (page == null || page.isBlank()) ? "home" : page;
|
||||
return RemoteDocumentBuilderKt.buildRemoteDocument(target);
|
||||
byte[] document = RemoteDocumentBuilderKt.buildRemoteDocument(target);
|
||||
List<String> assets = RemoteDocumentBuilderKt.buildRemoteDocumentAssets(target);
|
||||
|
||||
ResponseEntity.BodyBuilder builder = ResponseEntity.ok()
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||
if (!assets.isEmpty()) {
|
||||
builder.header("X-Remote-Assets", String.join(",", assets));
|
||||
}
|
||||
return builder.body(document);
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面引用的图片资源。
|
||||
*
|
||||
* <p>图片 URL 带内容标识时,可以在此长期缓存;当前先固定 30 天。
|
||||
*/
|
||||
@GetMapping(value = "/assets/{name:.+}", produces = MediaType.IMAGE_PNG_VALUE)
|
||||
public ResponseEntity<byte[]> getAsset(@PathVariable("name") String name) throws IOException {
|
||||
if (!name.matches("[A-Za-z0-9._-]+")) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
ClassPathResource resource = new ClassPathResource("static/api/" + name);
|
||||
if (!resource.exists()) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.IMAGE_PNG)
|
||||
.cacheControl(CacheControl.maxAge(Duration.ofDays(30)).cachePublic())
|
||||
.body(resource.getContentAsByteArray());
|
||||
}
|
||||
}
|
||||
+246
@@ -4,6 +4,7 @@ import androidx.compose.remote.core.CoreDocument
|
||||
import androidx.compose.remote.creation.JvmRcPlatformServices
|
||||
import androidx.compose.remote.creation.RemoteComposeWriter
|
||||
import androidx.compose.remote.creation.dsl.Modifier
|
||||
import androidx.compose.remote.creation.dsl.RcContentScale
|
||||
import androidx.compose.remote.creation.dsl.RcDensityBehavior
|
||||
import androidx.compose.remote.creation.dsl.RcDp
|
||||
import androidx.compose.remote.creation.dsl.RcHeaderTag
|
||||
@@ -19,8 +20,10 @@ import androidx.compose.remote.creation.dsl.height
|
||||
import androidx.compose.remote.creation.dsl.onClick
|
||||
import androidx.compose.remote.creation.dsl.padding
|
||||
import androidx.compose.remote.creation.dsl.verticalScroll
|
||||
import androidx.compose.remote.creation.dsl.width
|
||||
import androidx.compose.remote.creation.profile.Profile
|
||||
import androidx.compose.remote.creation.profile.RemoteComposeWriterFactory
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* 文档逻辑画布尺寸,单位 dp。
|
||||
@@ -60,6 +63,9 @@ fun buildRemoteDocument(page: String): ByteArray {
|
||||
)
|
||||
|
||||
return createRcBuffer(rcProfile, *header) {
|
||||
// URL 图片需要底层 writer 登记真实尺寸,见 composeWriter() 的说明。
|
||||
val docWriter = composeWriter()
|
||||
|
||||
// 跳转目标以文本形式随文档下发,播放端只负责把 metadata 当作页面 id 使用。
|
||||
val homeTarget = remoteText("home")
|
||||
val detailTarget = remoteText("detail")
|
||||
@@ -71,12 +77,29 @@ fun buildRemoteDocument(page: String): ByteArray {
|
||||
when (page) {
|
||||
"detail" -> detailContent(homeTarget)
|
||||
"list" -> listContent(homeTarget)
|
||||
"spike" -> spikeContent(homeTarget)
|
||||
"spike-image" -> imageSpikeContent(homeTarget, docWriter)
|
||||
else -> homeContent(detailTarget, listTarget)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出 DSL 背后的 [RemoteComposeWriter]。
|
||||
*
|
||||
* `createRcBuffer` 只把 [RcScope] 交给内容 lambda,不会调用 Profile 里的 writer 工厂;
|
||||
* 而 URL 图片必须以真实尺寸登记到 writer(DSL 的 `remoteBitmapUrl` 固定按 1×1 写入,
|
||||
* 播放端解码时会因尺寸不匹配报 `dimensions don't match`)。
|
||||
* alpha24 没有公开入口,这里读 [androidx.compose.remote.creation.dsl.RcScopeImpl]
|
||||
* 的 writer 字段;取不到时返回 null,退回 1×1 的旧行为。
|
||||
*/
|
||||
private fun RcScope.composeWriter(): RemoteComposeWriter? = runCatching {
|
||||
val field = javaClass.getDeclaredField("writer")
|
||||
field.isAccessible = true
|
||||
field.get(this) as RemoteComposeWriter
|
||||
}.getOrNull()
|
||||
|
||||
private fun RcScope.homeContent(detailTarget: RcText, listTarget: RcText) {
|
||||
Text(
|
||||
text = "Remote Compose",
|
||||
@@ -118,6 +141,22 @@ private fun RcScope.homeContent(detailTarget: RcText, listTarget: RcText) {
|
||||
target = detailTarget,
|
||||
actionId = ACTION_OPEN_ACTIVITY
|
||||
)
|
||||
// 临时入口:Spike 验证完成后删除。
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
card(
|
||||
title = "Spike",
|
||||
body = "Row + weight 渲染验证页。",
|
||||
hint = "进入验证页 →",
|
||||
target = remoteText("spike")
|
||||
)
|
||||
// 临时入口:图片验证完成后删除。
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
card(
|
||||
title = "图片",
|
||||
body = "网络图片加载与 ImageScale 裁切验证。",
|
||||
hint = "进入验证页 →",
|
||||
target = remoteText("spike-image")
|
||||
)
|
||||
}
|
||||
|
||||
private fun RcScope.detailContent(homeTarget: RcText) {
|
||||
@@ -198,6 +237,184 @@ private fun RcScope.listItem(index: Int) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Spike 页面:验证 Row + weight 的渲染效果,以及「无固定高度」时的自适应能力。
|
||||
*
|
||||
* 用于评估「相对坐标 → 行分组 → Row/horizontalWeight」这套编译方案是否可行,
|
||||
* 验证完成后可以整体删除。
|
||||
*/
|
||||
private fun RcScope.spikeContent(homeTarget: RcText) {
|
||||
Text(text = "Spike · Row 权重", fontSize = RcSp(22f), color = TITLE_COLOR)
|
||||
Spacer(Modifier.height(RcDp(4f)))
|
||||
Text(
|
||||
text = "下面三行分别验证:1:2:3 权重、12 等分、带间距的列",
|
||||
fontSize = RcSp(13f),
|
||||
color = BODY_COLOR
|
||||
)
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
// 1) 权重比 1 : 2 : 3
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.weight(1f).height(RcDp(56f)).background(SPIKE_RED)) {
|
||||
Text(text = "1", fontSize = RcSp(16f), color = WHITE)
|
||||
}
|
||||
Box(Modifier.weight(2f).height(RcDp(56f)).background(SPIKE_GREEN)) {
|
||||
Text(text = "2", fontSize = RcSp(16f), color = WHITE)
|
||||
}
|
||||
Box(Modifier.weight(3f).height(RcDp(56f)).background(SPIKE_BLUE)) {
|
||||
Text(text = "3", fontSize = RcSp(16f), color = WHITE)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
// 2) 12 等分(模拟 12 列网格)
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
repeat(12) { index ->
|
||||
Box(
|
||||
Modifier
|
||||
.weight(1f)
|
||||
.height(RcDp(24f))
|
||||
.background(if (index % 2 == 0) SPIKE_BLUE else SPIKE_GREEN)
|
||||
) {}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
// 3) 三列 + 8dp 间距
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.weight(1f).height(RcDp(48f)).background(SPIKE_RED)) {}
|
||||
Spacer(Modifier.width(RcDp(8f)))
|
||||
Box(Modifier.weight(1f).height(RcDp(48f)).background(SPIKE_GREEN)) {}
|
||||
Spacer(Modifier.width(RcDp(8f)))
|
||||
Box(Modifier.weight(1f).height(RcDp(48f)).background(SPIKE_BLUE)) {}
|
||||
}
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
// 4) 不写高度:验证文字卡片能否按内容自适应高度
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.weight(1f).background(CARD_BG).padding(RcDp(10f))) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(text = "自适应 A", fontSize = RcSp(14f), color = TITLE_COLOR)
|
||||
Spacer(Modifier.height(RcDp(4f)))
|
||||
Text(
|
||||
text = "两行文字,用来观察高度是否随内容撑开。",
|
||||
fontSize = RcSp(12f),
|
||||
color = BODY_COLOR
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(RcDp(8f)))
|
||||
Box(Modifier.weight(1f).background(CARD_BG).padding(RcDp(10f))) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(text = "自适应 B", fontSize = RcSp(14f), color = TITLE_COLOR)
|
||||
Spacer(Modifier.height(RcDp(4f)))
|
||||
Text(
|
||||
text = "这段文字更长一些,用来验证同一行内两个卡片的高度和对齐表现。",
|
||||
fontSize = RcSp(12f),
|
||||
color = BODY_COLOR
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
// 5) 嵌套:Row 里再放 Column,模拟网格单元内部结构
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Box(Modifier.weight(2f).height(RcDp(72f)).background(SPIKE_PURPLE).padding(RcDp(8f))) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(text = "嵌套 Row > Column", fontSize = RcSp(13f), color = WHITE)
|
||||
Spacer(Modifier.height(RcDp(4f)))
|
||||
Text(text = "2/3 宽度", fontSize = RcSp(11f), color = WHITE)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(RcDp(8f)))
|
||||
Box(Modifier.weight(1f).height(RcDp(72f)).background(SPIKE_ORANGE)) {
|
||||
Text(text = "1/3", fontSize = RcSp(13f), color = WHITE)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(RcDp(16f)))
|
||||
|
||||
card(
|
||||
title = "返回",
|
||||
body = "Spike 验证完成后回到首页。",
|
||||
hint = "点击返回首页 →",
|
||||
target = homeTarget
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Spike 页面:验证网络图片加载与 contentScale 的表现。
|
||||
*
|
||||
* 图片以 URL 形式随文档下发,由播放端预取并缓存后渲染;
|
||||
* 验证完成后可整体删除。
|
||||
*/
|
||||
private fun RcScope.imageSpikeContent(homeTarget: RcText, writer: RemoteComposeWriter?) {
|
||||
// DSL 的 remoteBitmapUrl(url) 会把声明尺寸写成 1×1,播放端解码后尺寸校验会失败;
|
||||
// 先用 writer 按真实尺寸注册同一个 URL,后续 remoteBitmapUrl 会复用已注册的 id。
|
||||
val (imageWidth, imageHeight) = spikeImageSize
|
||||
writer?.addBitmapUrl(SPIKE_IMAGE_URL, imageWidth, imageHeight)
|
||||
val bitmap = remoteBitmapUrl(SPIKE_IMAGE_URL)
|
||||
|
||||
Text(text = "Spike · 图片", fontSize = RcSp(22f), color = TITLE_COLOR)
|
||||
Spacer(Modifier.height(RcDp(4f)))
|
||||
Text(
|
||||
text = "原图 800×450,下面分别用 Fit / Crop / FillBounds 渲染",
|
||||
fontSize = RcSp(13f),
|
||||
color = BODY_COLOR
|
||||
)
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
Text(text = "1) Fit:完整显示,可能留边", fontSize = RcSp(13f), color = ACCENT_COLOR)
|
||||
Spacer(Modifier.height(RcDp(6f)))
|
||||
Image(
|
||||
bitmap,
|
||||
Modifier.fillMaxWidth().height(RcDp(160f)).background(CARD_BG),
|
||||
"fit",
|
||||
RcContentScale.Fit,
|
||||
1f
|
||||
)
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
Text(text = "2) Crop:填满容器,超出裁切", fontSize = RcSp(13f), color = ACCENT_COLOR)
|
||||
Spacer(Modifier.height(RcDp(6f)))
|
||||
Image(
|
||||
bitmap,
|
||||
Modifier.fillMaxWidth().height(RcDp(120f)),
|
||||
"crop",
|
||||
RcContentScale.Crop,
|
||||
1f
|
||||
)
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
Text(text = "3) 两列 + FillBounds(拉伸)", fontSize = RcSp(13f), color = ACCENT_COLOR)
|
||||
Spacer(Modifier.height(RcDp(6f)))
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Image(
|
||||
bitmap,
|
||||
Modifier.weight(1f).height(RcDp(90f)),
|
||||
"left",
|
||||
RcContentScale.Crop,
|
||||
1f
|
||||
)
|
||||
Spacer(Modifier.width(RcDp(8f)))
|
||||
Image(
|
||||
bitmap,
|
||||
Modifier.weight(1f).height(RcDp(90f)),
|
||||
"right",
|
||||
RcContentScale.FillBounds,
|
||||
1f
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(RcDp(12f)))
|
||||
|
||||
card(
|
||||
title = "返回",
|
||||
body = "图片验证完成后回到首页。",
|
||||
hint = "点击返回首页 →",
|
||||
target = homeTarget
|
||||
)
|
||||
}
|
||||
|
||||
private fun RcScope.card(
|
||||
title: String,
|
||||
body: String,
|
||||
@@ -227,3 +444,32 @@ private const val TITLE_COLOR = 0xFF0D47A1.toInt()
|
||||
private const val BODY_COLOR = 0xFF212121.toInt()
|
||||
private const val ACCENT_COLOR = 0xFF1565C0.toInt()
|
||||
private const val CARD_BG = 0xFFE3F2FD.toInt()
|
||||
|
||||
// Spike 页面用的对比色,验证通过后可一并删除。
|
||||
private const val WHITE = 0xFFFFFFFF.toInt()
|
||||
private const val SPIKE_RED = 0xFFE53935.toInt()
|
||||
private const val SPIKE_GREEN = 0xFF43A047.toInt()
|
||||
private const val SPIKE_BLUE = 0xFF1E88E5.toInt()
|
||||
private const val SPIKE_PURPLE = 0xFF8E24AA.toInt()
|
||||
private const val SPIKE_ORANGE = 0xFFFB8C00.toInt()
|
||||
|
||||
/** Spike 图片页使用的测试图(部署在服务端静态资源下)。 */
|
||||
private const val SPIKE_IMAGE_URL = "https://ttstd.com/api/remote-ui/assets/spike-image.png"
|
||||
|
||||
/** 测试图真实像素尺寸,用于在文档里声明图片的最大解码尺寸。 */
|
||||
private val spikeImageSize: Pair<Int, Int> by lazy {
|
||||
val stream = checkNotNull(
|
||||
Thread.currentThread().contextClassLoader?.getResourceAsStream("static/api/spike-image.png")
|
||||
) { "缺少 spike-image.png 测试图" }
|
||||
stream.use { ImageIO.read(it).let { image -> image.width to image.height } }
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面引用的图片资源清单。
|
||||
*
|
||||
* 播放端在 setDocument 前按该清单预取图片,避免播放器在主线程同步下载。
|
||||
*/
|
||||
fun buildRemoteDocumentAssets(page: String): List<String> = when (page) {
|
||||
"spike-image" -> listOf(SPIKE_IMAGE_URL)
|
||||
else -> emptyList()
|
||||
}
|
||||
@@ -4,3 +4,10 @@ server:
|
||||
spring:
|
||||
application:
|
||||
name: ComposeRemoteServer
|
||||
web:
|
||||
resources:
|
||||
cache:
|
||||
cachecontrol:
|
||||
# 静态图片允许客户端长期缓存,避免图片多时反复回源。
|
||||
max-age: 30d
|
||||
cache-public: true
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Reference in new issue
Block a user