fix: 按图片真实尺寸登记文档,避免播放端尺寸校验失败
This commit is contained in:
1 parent
5c24941d50
commit
c6a5938e33
7 files changed
+203
-14
No files matched your search
@@ -22,7 +22,7 @@ spec:
|
||||
spec:
|
||||
containers:
|
||||
- name: server
|
||||
image: composeremote/server:1.0.0-editor6
|
||||
image: composeremote/server:1.0.0-editor7
|
||||
imagePullPolicy: Never
|
||||
ports:
|
||||
- name: http
|
||||
|
||||
+2
-1
@@ -80,7 +80,8 @@ public class LayoutAdminController {
|
||||
body.getItems()
|
||||
);
|
||||
try {
|
||||
LayoutStore.INSTANCE.put(document);
|
||||
// 保存时会把站内图片的像素宽高按文件真实尺寸校正,返回给编辑器的是校正后的文档。
|
||||
document = LayoutStore.INSTANCE.put(document);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
|
||||
}
|
||||
|
||||
+7
-1
@@ -1,19 +1,25 @@
|
||||
package com.ttstd.composeremote.server.config
|
||||
|
||||
import com.ttstd.composeremote.server.layout.AssetImageSizes
|
||||
import com.ttstd.composeremote.server.layout.LayoutStore
|
||||
import jakarta.annotation.PostConstruct
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import java.nio.file.Path
|
||||
|
||||
/** 启动时把布局目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖)交给 [LayoutStore]。 */
|
||||
/**
|
||||
* 启动时把布局目录(默认 `./data/layouts`,可用 `LAYOUT_DIR` 覆盖)交给 [LayoutStore],
|
||||
* 把上传图片目录(默认 `./data/assets`,可用 `ASSETS_DIR` 覆盖)交给 [AssetImageSizes]。
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class LayoutStoreConfiguration(
|
||||
@Value("\${app.layout-dir:./data/layouts}") private val layoutDir: String,
|
||||
@Value("\${app.assets-dir:./data/assets}") private val assetsDir: String,
|
||||
) {
|
||||
|
||||
@PostConstruct
|
||||
fun init() {
|
||||
LayoutStore.initialize(Path.of(layoutDir))
|
||||
AssetImageSizes.initialize(Path.of(assetsDir))
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.ttstd.composeremote.server.layout
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.core.io.ClassPathResource
|
||||
import java.io.InputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import javax.imageio.ImageIO
|
||||
|
||||
/**
|
||||
* 布局图片的真实尺寸。
|
||||
*
|
||||
* 播放端对 URL 图片做严格校验:文档里登记的宽高必须与解码结果一致,否则抛
|
||||
* `dimensions don't match`。编辑器里的像素宽高由用户或预设写入,改 URL 后很容易过期,
|
||||
* 因此站内资源库图片一律以磁盘文件为准重新读取,外部 URL 才回落到组件属性。
|
||||
*/
|
||||
object AssetImageSizes {
|
||||
|
||||
private val log = LoggerFactory.getLogger(AssetImageSizes::class.java)
|
||||
|
||||
/** 资源库图片的 URL 路径前缀。 */
|
||||
private const val ASSET_PATH = "/api/remote-ui/assets/"
|
||||
|
||||
private val ASSET_NAME = Regex("[A-Za-z0-9._-]+")
|
||||
|
||||
@Volatile
|
||||
private var directory: Path? = null
|
||||
|
||||
/** 由 Spring 启动时调用,注入上传图片目录。 */
|
||||
fun initialize(assetsDir: Path) {
|
||||
directory = assetsDir.toAbsolutePath().normalize()
|
||||
}
|
||||
|
||||
/** 解析站内资源图片名;外部 URL 返回 null。 */
|
||||
fun localAssetName(url: String): String? {
|
||||
val path = url.substringBefore('?').substringBefore('#')
|
||||
val index = path.indexOf(ASSET_PATH)
|
||||
if (index < 0) return null
|
||||
val name = path.substring(index + ASSET_PATH.length)
|
||||
return name.takeIf { it.matches(ASSET_NAME) }
|
||||
}
|
||||
|
||||
/** 图片真实宽高:站内资源读文件头,外部 URL 回落到组件属性。 */
|
||||
fun resolve(item: LayoutItem): Pair<Int, Int>? {
|
||||
val url = item.props["url"].orEmpty()
|
||||
if (url.isBlank()) return null
|
||||
localAssetName(url)?.let { name ->
|
||||
sizeOf(name)?.let { return it }
|
||||
}
|
||||
val width = item.props["pixelWidth"]?.toIntOrNull() ?: return null
|
||||
val height = item.props["pixelHeight"]?.toIntOrNull() ?: return null
|
||||
return width to height
|
||||
}
|
||||
|
||||
/** 把布局里站内图片的像素宽高校正为真实尺寸,没有变化时返回原文档。 */
|
||||
fun normalize(document: LayoutDocument): LayoutDocument {
|
||||
var changed = false
|
||||
val items = document.items.map { item ->
|
||||
if (item.type != ItemType.IMAGE) return@map item
|
||||
val name = localAssetName(item.props["url"].orEmpty()) ?: return@map item
|
||||
val size = sizeOf(name) ?: return@map item
|
||||
val width = size.first.toString()
|
||||
val height = size.second.toString()
|
||||
if (item.props["pixelWidth"] == width && item.props["pixelHeight"] == height) {
|
||||
item
|
||||
} else {
|
||||
changed = true
|
||||
item.copy(props = item.props + ("pixelWidth" to width) + ("pixelHeight" to height))
|
||||
}
|
||||
}
|
||||
return if (changed) document.copy(items = items) else document
|
||||
}
|
||||
|
||||
/** 读取资源图片宽高:外部上传目录优先,其次 classpath 内置图片。 */
|
||||
private fun sizeOf(name: String): Pair<Int, Int>? {
|
||||
val external = directory?.resolve(name)
|
||||
if (external != null && Files.isRegularFile(external)) {
|
||||
return runCatching { Files.newInputStream(external).use(::readSize) }
|
||||
.onFailure { log.warn("读取图片尺寸失败: {}", external, it) }
|
||||
.getOrNull()
|
||||
}
|
||||
val resource = ClassPathResource("static/api/$name")
|
||||
if (!resource.exists()) return null
|
||||
return runCatching { resource.inputStream.use(::readSize) }
|
||||
.onFailure { log.warn("读取内置图片尺寸失败: {}", name, it) }
|
||||
.getOrNull()
|
||||
}
|
||||
|
||||
/** 只读图片文件头,不解码整张图。 */
|
||||
private fun readSize(stream: InputStream): Pair<Int, Int>? {
|
||||
val input = ImageIO.createImageInputStream(stream) ?: return null
|
||||
input.use {
|
||||
val readers = ImageIO.getImageReaders(it)
|
||||
if (!readers.hasNext()) return null
|
||||
val reader = readers.next()
|
||||
return try {
|
||||
reader.setInput(it, true, true)
|
||||
reader.getWidth(0) to reader.getHeight(0)
|
||||
} finally {
|
||||
reader.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -105,10 +105,11 @@ object LayoutCompiler {
|
||||
document.items
|
||||
.filter { it.type == ItemType.IMAGE }
|
||||
.forEach { item ->
|
||||
val url = item.props["url"] ?: return@forEach
|
||||
val pixelWidth = item.props["pixelWidth"]?.toIntOrNull() ?: return@forEach
|
||||
val pixelHeight = item.props["pixelHeight"]?.toIntOrNull() ?: return@forEach
|
||||
writer?.addBitmapUrl(url, pixelWidth, pixelHeight)
|
||||
val url = item.props["url"].orEmpty()
|
||||
if (url.isBlank()) return@forEach
|
||||
// 站内资源以磁盘文件真实尺寸为准,编辑器里过期的像素宽高不会再导致播放失败。
|
||||
val size = AssetImageSizes.resolve(item) ?: return@forEach
|
||||
writer?.addBitmapUrl(url, size.first, size.second)
|
||||
}
|
||||
|
||||
Column(
|
||||
|
||||
+12
-7
@@ -103,12 +103,14 @@ object LayoutStore {
|
||||
}
|
||||
}
|
||||
|
||||
/** 校验并保存草稿;校验不通过时抛 [IllegalArgumentException]。 */
|
||||
/** 校验并保存草稿;站内图片的像素宽高会按磁盘真实尺寸校正。 */
|
||||
@Synchronized
|
||||
fun put(document: LayoutDocument) {
|
||||
validate(document)
|
||||
drafts[document.id] = document
|
||||
persist(document, draftFileOf(document.id))
|
||||
fun put(document: LayoutDocument): LayoutDocument {
|
||||
val normalized = AssetImageSizes.normalize(document)
|
||||
validate(normalized)
|
||||
drafts[normalized.id] = normalized
|
||||
persist(normalized, draftFileOf(normalized.id))
|
||||
return normalized
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,7 +120,8 @@ object LayoutStore {
|
||||
*/
|
||||
@Synchronized
|
||||
fun publish(id: String): LayoutDocument? {
|
||||
val draft = drafts[id] ?: return published[id]
|
||||
val stored = drafts[id] ?: return published[id]
|
||||
val draft = AssetImageSizes.normalize(stored)
|
||||
validate(draft)
|
||||
published[id]?.let { archive(it) }
|
||||
published[draft.id] = draft
|
||||
@@ -188,7 +191,9 @@ object LayoutStore {
|
||||
require(VERSION_NAME.matches(version)) { "版本号格式不正确: $version" }
|
||||
val file = historyDirOf(id).resolve("$version.json")
|
||||
if (!Files.isRegularFile(file)) return null
|
||||
val document = mapper.readValue(file.toFile(), LayoutDocument::class.java).copy(id = id)
|
||||
val document = AssetImageSizes.normalize(
|
||||
mapper.readValue(file.toFile(), LayoutDocument::class.java).copy(id = id)
|
||||
)
|
||||
validate(document)
|
||||
drafts[id] = document
|
||||
persist(document, draftFileOf(id))
|
||||
|
||||
@@ -629,6 +629,7 @@
|
||||
history.replaceState(null, '', `?id=${encodeURIComponent(id)}`);
|
||||
renderAll();
|
||||
toast('已加载「' + (state.doc.title || id) + '」');
|
||||
normalizeImageSizes();
|
||||
} catch (e) {
|
||||
toast(e.message, true);
|
||||
}
|
||||
@@ -849,6 +850,72 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------- 图片尺寸校正 ---------------- */
|
||||
|
||||
/** 浏览器加载图片拿真实像素尺寸;失败返回 null(保留原值,避免写成 0)。 */
|
||||
function probeImageSize(url) {
|
||||
return new Promise((resolve) => {
|
||||
const image = new Image();
|
||||
image.onload = () => resolve({ w: image.naturalWidth, h: image.naturalHeight });
|
||||
image.onerror = () => resolve(null);
|
||||
image.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/** 把组件像素宽高写成真实尺寸,返回是否有变化。 */
|
||||
function applyImageSize(item, size) {
|
||||
if (!size || !size.w || !size.h) return false;
|
||||
const width = String(size.w);
|
||||
const height = String(size.h);
|
||||
if (item.props.pixelWidth === width && item.props.pixelHeight === height) return false;
|
||||
item.props.pixelWidth = width;
|
||||
item.props.pixelHeight = height;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 修改 URL 后自动探测尺寸,避免登记的宽高与图片实际尺寸不一致导致播放端报错。 */
|
||||
async function syncImageSize(item) {
|
||||
const doc = state.doc;
|
||||
const url = ((item.props && item.props.url) || '').trim();
|
||||
if (!url) return;
|
||||
const size = await probeImageSize(url);
|
||||
if (state.doc !== doc || !applyImageSize(item, size)) return;
|
||||
renderAll();
|
||||
refreshDirty();
|
||||
toast(`已校正图片尺寸为 ${size.w}×${size.h}`);
|
||||
}
|
||||
|
||||
/** 载入页面后批量校正图片尺寸:站内资源取资源库数据,外部 URL 用浏览器探测。 */
|
||||
async function normalizeImageSizes() {
|
||||
const doc = state.doc;
|
||||
if (!doc) return;
|
||||
const images = doc.items.filter((item) => item.type === 'IMAGE' && item.props && item.props.url);
|
||||
if (!images.length) return;
|
||||
|
||||
let assets = [];
|
||||
try {
|
||||
const res = await fetch('/api/remote-ui/assets');
|
||||
if (res.ok) assets = await res.json();
|
||||
} catch (ignored) {
|
||||
// 资源库不可用时仍然尝试逐个探测外部图片。
|
||||
}
|
||||
|
||||
let changed = 0;
|
||||
for (const item of images) {
|
||||
if (state.doc !== doc) return;
|
||||
const url = item.props.url.split('?')[0];
|
||||
const asset = assets.find((candidate) => url.endsWith(candidate.path));
|
||||
const size = asset
|
||||
? { w: asset.pixelWidth, h: asset.pixelHeight }
|
||||
: await probeImageSize(item.props.url);
|
||||
if (applyImageSize(item, size)) changed += 1;
|
||||
}
|
||||
if (state.doc !== doc || !changed) return;
|
||||
renderAll();
|
||||
refreshDirty();
|
||||
toast(`已自动校正 ${changed} 张图片尺寸,请保存并发布`);
|
||||
}
|
||||
|
||||
async function readError(res) {
|
||||
try {
|
||||
const body = await res.json();
|
||||
@@ -1233,6 +1300,11 @@
|
||||
};
|
||||
});
|
||||
|
||||
const imageUrlInput = inspector.querySelector('[data-prop="url"]');
|
||||
if (imageUrlInput && item.type === 'IMAGE') {
|
||||
imageUrlInput.addEventListener('change', () => syncImageSize(item));
|
||||
}
|
||||
|
||||
const actionSelect = inspector.querySelector('[data-action="type"]');
|
||||
const actionTarget = inspector.querySelector('[data-action="target"]');
|
||||
actionSelect.value = item.action ? item.action.type : '';
|
||||
|
||||
Reference in new issue
Block a user