From 3b01588c77306bbd72acc6b1fe558b14bedf3b82 Mon Sep 17 00:00:00 2001 From: Arena Agent Date: Sun, 18 Oct 2026 16:50:44 +0000 Subject: [PATCH 01/11] feat: add independent UnityFS bundle browser and repacker --- .../strata/core/archive/ArchiveParent.kt | 7 + .../strata/core/archive/ArchiveReader.kt | 2 +- .../cluvex/strata/core/archive/ZipEditor.kt | 9 + .../dev/cluvex/strata/core/open/Opener.kt | 7 +- .../strata/core/unity/UnityBundleReader.kt | 656 ++++++++++++++++++ .../strata/core/unity/UnityPackageRepacker.kt | 85 +++ .../strata/feature/archive/ArchiveScreen.kt | 3 +- .../strata/feature/open/OpenWithDialog.kt | 1 + .../strata/feature/unity/UnityAssetScreen.kt | 355 ++++++++++ .../feature/unity/UnityAssetViewModel.kt | 168 +++++ .../java/dev/cluvex/strata/ui/AppShell.kt | 47 +- app/src/main/res/values-fa/strings_unity.xml | 39 ++ app/src/main/res/values-ru/strings_unity.xml | 41 ++ .../main/res/values-zh-rCN/strings_unity.xml | 38 + app/src/main/res/values/strings_unity.xml | 39 ++ .../core/unity/UnityBundleReaderTest.kt | 155 +++++ 16 files changed, 1643 insertions(+), 9 deletions(-) create mode 100644 app/src/main/java/dev/cluvex/strata/core/archive/ArchiveParent.kt create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt create mode 100644 app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt create mode 100644 app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt create mode 100644 app/src/main/res/values-fa/strings_unity.xml create mode 100644 app/src/main/res/values-ru/strings_unity.xml create mode 100644 app/src/main/res/values-zh-rCN/strings_unity.xml create mode 100644 app/src/main/res/values/strings_unity.xml create mode 100644 app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt diff --git a/app/src/main/java/dev/cluvex/strata/core/archive/ArchiveParent.kt b/app/src/main/java/dev/cluvex/strata/core/archive/ArchiveParent.kt new file mode 100644 index 0000000..a22eb27 --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/archive/ArchiveParent.kt @@ -0,0 +1,7 @@ +package dev.cluvex.strata.core.archive + +/** One containment edge from an extracted file back to its unchanged parent archive. */ +data class ArchiveParent( + val archivePath: String, + val entryPath: String, +) diff --git a/app/src/main/java/dev/cluvex/strata/core/archive/ArchiveReader.kt b/app/src/main/java/dev/cluvex/strata/core/archive/ArchiveReader.kt index c7a257b..fb140f8 100644 --- a/app/src/main/java/dev/cluvex/strata/core/archive/ArchiveReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/archive/ArchiveReader.kt @@ -81,7 +81,7 @@ class ArchiveTree(entries: List) { object ArchiveReader { - private val zipSuffixes = listOf(".zip", ".jar", ".apk", ".apks", ".xapk", ".apkm", ".war", ".aar") + private val zipSuffixes = listOf(".zip", ".jar", ".apk", ".apks", ".xapk", ".apkm", ".obb", ".war", ".aar") private val tarballSuffixes = listOf(".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar.zst", ".tar.zstd", ".tar.lz4", ".tar") private val singleSuffixes = listOf(".gz", ".bz2", ".xz", ".zst", ".zstd", ".lz4") diff --git a/app/src/main/java/dev/cluvex/strata/core/archive/ZipEditor.kt b/app/src/main/java/dev/cluvex/strata/core/archive/ZipEditor.kt index da1ee80..6332636 100644 --- a/app/src/main/java/dev/cluvex/strata/core/archive/ZipEditor.kt +++ b/app/src/main/java/dev/cluvex/strata/core/archive/ZipEditor.kt @@ -27,6 +27,15 @@ object ZipEditor { fun put(zip: File, entry: String, content: File) = putAll(zip, mapOf(ArchiveTree.normalize(entry) to content)) + fun replace(zip: File, entry: String, content: File) { + val normalized = ArchiveTree.normalize(entry) + ZipFile(zip).use { z -> + checkEditable(z) + if (z.getFileHeader(normalized) == null) throw IOException(tr(R.string.archive_not_in_archive, normalized)) + } + put(zip, normalized, content) + } + fun delete(zip: File, paths: Collection): Int = ZipFile(zip).use { z -> checkEditable(z) val names = matching(z, paths) diff --git a/app/src/main/java/dev/cluvex/strata/core/open/Opener.kt b/app/src/main/java/dev/cluvex/strata/core/open/Opener.kt index f46271e..cf95b2c 100644 --- a/app/src/main/java/dev/cluvex/strata/core/open/Opener.kt +++ b/app/src/main/java/dev/cluvex/strata/core/open/Opener.kt @@ -6,6 +6,8 @@ import dev.cluvex.strata.R import dev.cluvex.strata.core.model.FileItem import dev.cluvex.strata.core.util.FileKind import dev.cluvex.strata.core.util.FileKinds +import dev.cluvex.strata.core.unity.UnityBundleReader +import java.io.File enum class Opener(@StringRes val label: Int) { APK_VIEWER(R.string.model_opener_apk), @@ -23,6 +25,7 @@ enum class Opener(@StringRes val label: Int) { FONT_VIEWER(R.string.model_opener_font), DEX_EDITOR(R.string.model_opener_dex), ARSC_EDITOR(R.string.model_opener_arsc), + UNITY_ASSET(R.string.model_opener_unity), } sealed interface OpenTarget { @@ -67,6 +70,8 @@ object OpenResolver { ext in splitBundles -> Opener.SPLIT_APK_INSTALLER ext == "dex" || ext == "odex" -> Opener.DEX_EDITOR ext == "arsc" -> Opener.ARSC_EDITOR + ext == "obb" -> Opener.ARCHIVE_VIEWER + UnityBundleReader.isUnityRelated(item.name) || (File(item.path).isFile && UnityBundleReader.probe(File(item.path)).kind != dev.cluvex.strata.core.unity.UnityFileKind.UNKNOWN) -> Opener.UNITY_ASSET ext in browsable -> Opener.ARCHIVE_VIEWER ext in fonts -> Opener.FONT_VIEWER ext in markdown -> Opener.MARKDOWN_VIEWER @@ -92,7 +97,7 @@ object OpenResolver { private val anyFile = listOf( Opener.TEXT_EDITOR, Opener.MARKDOWN_VIEWER, Opener.PDF_READER, Opener.HEX_EDITOR, Opener.ARCHIVE_VIEWER, Opener.IMAGE_VIEWER, Opener.NINE_PATCH_EDITOR, Opener.MUSIC_PLAYER, Opener.VIDEO_PLAYER, Opener.FONT_VIEWER, Opener.APK_VIEWER, - Opener.SPLIT_APK_INSTALLER, Opener.DEX_EDITOR, Opener.ARSC_EDITOR, Opener.SIGNING_KEY, + Opener.SPLIT_APK_INSTALLER, Opener.DEX_EDITOR, Opener.ARSC_EDITOR, Opener.SIGNING_KEY, Opener.UNITY_ASSET, ) fun candidates(item: FileItem): List = (listOfNotNull(builtIn(item)) + anyFile).distinct() diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt new file mode 100644 index 0000000..f3cdc1c --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt @@ -0,0 +1,656 @@ +package dev.cluvex.strata.core.unity + +import org.tukaani.xz.LZMAInputStream +import java.io.BufferedInputStream +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.Closeable +import java.io.DataOutputStream +import java.io.EOFException +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.io.RandomAccessFile +import java.security.MessageDigest + +/** Unity container formats recognized by Strata's built-in Unity asset browser. */ +enum class UnityFileKind { + UNITY_FS, + UNITY_WEB, + UNITY_RAW, + SERIALIZED_FILE, + UNKNOWN, +} + +data class UnityProbe( + val kind: UnityFileKind, + val signature: String, + val fileVersion: Int? = null, + val engineVersion: String? = null, + val dataOffset: Long? = null, + val note: String? = null, +) { + val bundleSupported: Boolean get() = kind == UnityFileKind.UNITY_FS +} + +data class UnityBundleEntry( + val name: String, + val offset: Long, + val size: Long, + val flags: Long, +) { + val displayName: String get() = name.substringAfterLast('/').ifEmpty { name } +} + +data class UnityBundleSummary( + val signature: String, + val formatVersion: Int, + val playerVersion: String, + val engineVersion: String, + val fileSize: Long, + val dataSize: Long, + val blockCount: Int, + val entries: List, +) + +class UnityFormatException(message: String, cause: Throwable? = null) : IOException(message, cause) + +/** + * A parsed UnityFS bundle. The decompressed data stream is staged in app cache so entry reads + * and replacement/repacking do not require holding the whole bundle in memory. + */ +class UnityBundleDocument internal constructor( + val source: File, + val summary: UnityBundleSummary, + internal val dataFile: File, +) : Closeable { + + fun copyEntry(entry: UnityBundleEntry, output: File) { + requireEntry(entry) + output.parentFile?.mkdirs() + if (!output.createNewFile()) throw IOException("Output already exists: ${output.name}") + try { + RandomAccessFile(dataFile, "r").use { input -> + FileOutputStream(output).use { out -> + input.seek(entry.offset) + copyExactly(input, out, entry.size) + } + } + } catch (e: Throwable) { + output.delete() + throw e + } + } + + /** Writes a normalized UnityFS bundle. Inputs are never overwritten. */ + fun repack(output: File, replacements: Map = emptyMap()) { + if (output.canonicalFile == source.canonicalFile) throw IOException("Output must not replace the source bundle") + if (output.exists()) throw IOException("Output already exists: ${output.name}") + val unknown = replacements.keys - summary.entries.map { it.name }.toSet() + if (unknown.isNotEmpty()) throw IOException("Replacement entry is not in this bundle: ${unknown.first()}") + + val parent = output.parentFile ?: throw IOException("Output directory is missing") + parent.mkdirs() + if (!output.createNewFile()) throw IOException("Output already exists: ${output.name}") + val staged = File(parent, ".${output.name}.${System.nanoTime()}.data") + var stagedCreated = false + try { + if (!staged.createNewFile()) throw IOException("Could not create a unique Unity staging file") + stagedCreated = true + val outputOffsets = LongArray(summary.entries.size) + var sourceCursor = 0L + var outputCursor = 0L + RandomAccessFile(dataFile, "r").use { input -> + FileOutputStream(staged).buffered(BUFFER_SIZE).use { out -> + summary.entries.withIndex().sortedBy { it.value.offset }.forEach { (index, entry) -> + if (entry.offset > sourceCursor) { + val gap = entry.offset - sourceCursor + input.seek(sourceCursor) + copyExactly(input, out, gap) + outputCursor = checkedAdd(outputCursor, gap, "UnityFS data is too large") + sourceCursor = entry.offset + } + outputOffsets[index] = outputCursor + val replacement = replacements[entry.name] + if (replacement != null) { + val size = replacement.length() + val copied = replacement.inputStream().buffered().use { it.copyTo(out, BUFFER_SIZE) } + if (copied != size) throw IOException("Replacement changed while it was being read") + outputCursor = checkedAdd(outputCursor, size, "UnityFS data is too large") + } else { + input.seek(entry.offset) + copyExactly(input, out, entry.size) + outputCursor = checkedAdd(outputCursor, entry.size, "UnityFS data is too large") + } + sourceCursor = maxOf(sourceCursor, checkedAdd(entry.offset, entry.size, "UnityFS entry range overflows")) + } + if (sourceCursor < summary.dataSize) { + val tail = summary.dataSize - sourceCursor + input.seek(sourceCursor) + copyExactly(input, out, tail) + outputCursor = checkedAdd(outputCursor, tail, "UnityFS data is too large") + } + } + } + val updated = summary.entries.mapIndexed { index, entry -> + entry.copy(offset = outputOffsets[index], size = replacements[entry.name]?.length() ?: entry.size) + } + writeNormalizedUnityFs(staged, output, summary, updated, outputCursor) + } catch (e: Throwable) { + output.delete() + throw e + } finally { + if (stagedCreated) staged.delete() + } + } + + private fun requireEntry(entry: UnityBundleEntry) { + if (summary.entries.none { it == entry }) throw IllegalArgumentException("Entry does not belong to this bundle") + if (entry.offset < 0 || entry.size < 0 || entry.offset > summary.dataSize || entry.size > summary.dataSize - entry.offset) { + throw UnityFormatException("UnityFS entry is outside the data section") + } + } + + override fun close() { + dataFile.delete() + dataFile.parentFile?.delete() + } + + private companion object { + const val BUFFER_SIZE = 64 * 1024 + const val OUTPUT_BLOCK_SIZE = 32 * 1024 * 1024 + + fun writeNormalizedUnityFs( + data: File, + output: File, + original: UnityBundleSummary, + entries: List, + dataSize: Long, + ) { + val blockCountLong = if (dataSize == 0L) 0L else 1L + (dataSize - 1) / OUTPUT_BLOCK_SIZE + if (blockCountLong > MAX_BLOCKS) throw UnityFormatException("UnityFS has too many data blocks") + val blockCount = blockCountLong.toInt() + val blockInfo = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.write(md5(data)) + out.writeInt(blockCount) + var left = dataSize + repeat(blockCount) { + val size = minOf(left, OUTPUT_BLOCK_SIZE.toLong()).toInt() + out.writeInt(size) + out.writeInt(size) + out.writeShort(0) // Uncompressed data block. + left -= size + } + out.writeInt(entries.size) + entries.forEach { entry -> + out.writeLong(entry.offset) + out.writeLong(entry.size) + out.writeInt(entry.flags.toInt()) + writeCString(out, entry.name) + } + } + bytes.toByteArray() + } + val headerPrefix = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + writeCString(out, "UnityFS") + out.writeInt(original.formatVersion) + writeCString(out, original.playerVersion) + writeCString(out, original.engineVersion) + // Size is appended below after the total has been calculated. + } + bytes.toByteArray() + } + val headerSize = headerPrefix.size + 8 + 4 + 4 + 4 + val totalSize = checkedAdd(checkedAdd(headerSize.toLong(), blockInfo.size.toLong(), "UnityFS is too large"), dataSize, "UnityFS is too large") + try { + FileOutputStream(output).buffered(BUFFER_SIZE).use { fileOut -> + DataOutputStream(fileOut).use { out -> + out.write(headerPrefix) + out.writeLong(totalSize) + out.writeInt(blockInfo.size) + out.writeInt(blockInfo.size) + out.writeInt(BLOCK_INFO_AT_START) + out.write(blockInfo) + FileInputStream(data).buffered().use { it.copyTo(out, BUFFER_SIZE) } + } + } + } catch (e: Throwable) { + output.delete() + throw e + } + } + + private const val BLOCK_INFO_AT_START = 0x40 + private const val MAX_BLOCKS = 100_000 + } +} + + +private fun copyExactly(input: InputStream, output: OutputStream, length: Long): Long { + if (length < 0) throw UnityFormatException("Negative UnityFS block length") + val buffer = ByteArray(64 * 1024) + var left = length + var copied = 0L + while (left > 0) { + val n = input.read(buffer, 0, minOf(buffer.size.toLong(), left).toInt()) + if (n < 0) throw EOFException("Truncated UnityFS data") + output.write(buffer, 0, n) + left -= n + copied += n + } + return copied +} + +private fun copyExactly(input: RandomAccessFile, output: OutputStream, length: Long): Long { + if (length < 0) throw UnityFormatException("Negative UnityFS block length") + val buffer = ByteArray(64 * 1024) + var left = length + var copied = 0L + while (left > 0) { + val n = input.read(buffer, 0, minOf(buffer.size.toLong(), left).toInt()) + if (n < 0) throw EOFException("Truncated UnityFS data") + output.write(buffer, 0, n) + left -= n + copied += n + } + return copied +} + +private fun checkedAdd(a: Long, b: Long, message: String): Long { + if (b < 0 || a > Long.MAX_VALUE - b) throw UnityFormatException(message) + return a + b +} + +private fun md5(file: File): ByteArray { + val digest = MessageDigest.getInstance("MD5") + FileInputStream(file).buffered().use { input -> + val buffer = ByteArray(64 * 1024) + while (true) { + val n = input.read(buffer) + if (n < 0) break + digest.update(buffer, 0, n) + } + } + return digest.digest() +} + +private fun writeCString(output: DataOutputStream, value: String) { + if ('\u0000' in value) throw UnityFormatException("UnityFS string contains a null character") + output.write(value.toByteArray(Charsets.UTF_8)) + output.writeByte(0) +} + +object UnityBundleReader { + private const val MAX_INFO_BYTES = 64L * 1024 * 1024 + private const val MAX_NODES = 500_000 + private const val MAX_STRING_BYTES = 1024 * 1024 + private const val MAX_LZMA_DICTIONARY = 256 * 1024 * 1024 + private const val FLAG_BLOCK_INFO_AT_END = 0x80L + private const val FLAG_BLOCK_INFO_NEEDS_PADDING = 0x200L + private const val COMPRESSION_MASK = 0x3F + private const val BUFFER_SIZE = 64 * 1024 + + fun isUnityRelated(name: String): Boolean { + val n = name.substringAfterLast('/').lowercase() + val ext = n.substringAfterLast('.', "") + return ext in setOf("bundle", "assetbundle", "unity3d", "assets", "asset", "resource", "ress", "res") + } + + fun probe(file: File): UnityProbe { + if (!file.isFile) return UnityProbe(UnityFileKind.UNKNOWN, "", note = "Not a regular file") + return runCatching { + RandomAccessFile(file, "r").use { input -> + val signature = readCString(input, 32) + when (signature) { + "UnityFS" -> { + input.seek(0) + UnityProbe(UnityFileKind.UNITY_FS, signature, readBundleVersion(input), note = "UnityFS bundle") + } + "UnityWeb" -> UnityProbe(UnityFileKind.UNITY_WEB, signature, note = "Legacy UnityWeb container") + "UnityRaw" -> UnityProbe(UnityFileKind.UNITY_RAW, signature, note = "Legacy UnityRaw container") + else -> probeSerializedFile(file, signature) + } + } + }.getOrElse { UnityProbe(UnityFileKind.UNKNOWN, "", note = it.message ?: "Unknown Unity file") } + } + + fun open(file: File, cacheDir: File): UnityBundleDocument { + if (!file.isFile) throw UnityFormatException("Unity file is not a regular file") + val cache = File(cacheDir, "unity/${file.name.hashCode().toUInt().toString(16)}-${file.length()}-${file.lastModified()}-${System.nanoTime()}") + cache.mkdirs() + val dataFile = File(cache, "bundle-data.bin") + try { + val summary = parseUnityFs(file, dataFile) + return UnityBundleDocument(file, summary, dataFile) + } catch (e: Throwable) { + dataFile.delete() + cache.delete() + throw e + } + } + + private data class Block(val compressed: Long, val uncompressed: Long, val flags: Int) + + private fun parseUnityFs(file: File, dataFile: File): UnityBundleSummary { + RandomAccessFile(file, "r").use { input -> + val signature = readCString(input, 32) + if (signature != "UnityFS") { + val probe = probe(file) + val detail = probe.note?.let { ": $it" }.orEmpty() + throw UnityFormatException("Unsupported Unity format${detail}") + } + val versionLong = readU32(input) + if (versionLong !in 6L..7L) throw UnityFormatException("Unsupported UnityFS format version $versionLong") + val formatVersion = versionLong.toInt() + val playerVersion = readCString(input, 4096) + val engineVersion = readCString(input, 4096) + val bundleSize = input.readLong() + val compressedInfoSize = readU32(input) + val uncompressedInfoSize = readU32(input) + val flags = readU32(input) + val headerEnd = input.filePointer + if (bundleSize < headerEnd || bundleSize > file.length() || bundleSize <= 0) throw UnityFormatException("UnityFS bundle size is invalid") + if (compressedInfoSize > MAX_INFO_BYTES || uncompressedInfoSize > MAX_INFO_BYTES || compressedInfoSize > Int.MAX_VALUE || uncompressedInfoSize > Int.MAX_VALUE) { + throw UnityFormatException("UnityFS block table is too large") + } + if (compressedInfoSize > bundleSize) throw UnityFormatException("UnityFS block table is outside the file") + val infoAtEnd = flags and FLAG_BLOCK_INFO_AT_END != 0L + val infoOffset = if (infoAtEnd) bundleSize - compressedInfoSize else headerEnd + if (infoOffset < headerEnd || infoOffset + compressedInfoSize > bundleSize) throw UnityFormatException("UnityFS block table offset is invalid") + input.seek(infoOffset) + val compressedInfo = ByteArray(compressedInfoSize.toInt()) + input.readFully(compressedInfo) + val infoCompression = (flags and COMPRESSION_MASK.toLong()).toInt() + val infoBytes = decompressBytes(compressedInfo, uncompressedInfoSize.toInt(), infoCompression) + val table = Cursor(infoBytes) + table.readBytes(16) + val blockCount = table.readU32().toIntChecked("block count") + if (blockCount !in 0..MAX_NODES) throw UnityFormatException("UnityFS block count is invalid") + val blocks = ArrayList(blockCount) + var uncompressedTotal = 0L + var compressedTotal = 0L + repeat(blockCount) { + val uncompressed = table.readU32() + val compressed = table.readU32() + val blockFlags = table.readU16() + if (uncompressed <= 0 || compressed <= 0) throw UnityFormatException("UnityFS contains an empty data block") + if ((blockFlags and COMPRESSION_MASK) !in 0..3) throw UnityFormatException("Unsupported UnityFS block compression") + uncompressedTotal = checkedAdd(uncompressedTotal, uncompressed, "UnityFS data size overflows") + compressedTotal = checkedAdd(compressedTotal, compressed, "UnityFS compressed data size overflows") + blocks += Block(compressed, uncompressed, blockFlags) + } + val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE + if (uncompressedTotal > availableSpace) throw UnityFormatException("Not enough free space to stage UnityFS data") + val nodeCount = table.readU32().toIntChecked("node count") + if (nodeCount !in 0..MAX_NODES) throw UnityFormatException("UnityFS node count is invalid") + val nodes = ArrayList(nodeCount) + repeat(nodeCount) { + val offset = table.readI64() + val size = table.readI64() + val nodeFlags = table.readU32() + val path = table.readCString(MAX_STRING_BYTES) + if (offset < 0 || size < 0 || offset > uncompressedTotal || size > uncompressedTotal - offset) { + throw UnityFormatException("UnityFS entry is outside the data section") + } + nodes += UnityBundleEntry(path, offset, size, nodeFlags) + } + if (table.remaining > 16) throw UnityFormatException("UnityFS block table contains unexpected trailing data") + val dataOffset = if (infoAtEnd) headerEnd else { + val afterInfo = infoOffset + compressedInfoSize + if (flags and FLAG_BLOCK_INFO_NEEDS_PADDING != 0L) align16(afterInfo) else afterInfo + } + val dataEnd = if (infoAtEnd) infoOffset else bundleSize + if (dataOffset > dataEnd || compressedTotal > dataEnd - dataOffset) throw UnityFormatException("UnityFS data section is truncated or overlaps its block table") + input.seek(dataOffset) + dataFile.parentFile?.mkdirs() + FileOutputStream(dataFile).buffered(BUFFER_SIZE).use { out -> + var consumedCompressed = 0L + var written = 0L + blocks.forEach { block -> + if (dataOffset + consumedCompressed + block.compressed > bundleSize) throw UnityFormatException("UnityFS data block is truncated") + val slice = RandomAccessFileSlice(input, block.compressed) + val codec = block.flags and COMPRESSION_MASK + val count = when (codec) { + 0 -> copyExactly(slice, out, block.compressed) + 1 -> decompressLzma(slice, block.uncompressed, out) + 2, 3 -> decompressLz4(slice, block.compressed, block.uncompressed, out) + else -> throw UnityFormatException("UnityFS uses unsupported compression $codec") + } + if (count != block.uncompressed) throw UnityFormatException("UnityFS data block has an unexpected size") + consumedCompressed += block.compressed + written += count + input.seek(dataOffset + consumedCompressed) + } + if (written != uncompressedTotal) throw UnityFormatException("UnityFS data section size does not match its block table") + } + return UnityBundleSummary(signature, formatVersion, playerVersion, engineVersion, bundleSize, uncompressedTotal, blockCount, nodes) + } + } + + private fun readBundleVersion(input: RandomAccessFile): Int? = runCatching { + input.seek(8) + readU32(input).toInt() + }.getOrNull() + + private fun decompressBytes(input: ByteArray, expected: Int, compression: Int): ByteArray { + if (expected < 0) throw UnityFormatException("UnityFS block table has an invalid size") + val out = ByteArrayOutputStream(expected.coerceAtMost(1024 * 1024)) + val source = ByteArrayInputStream(input) + val written = when (compression) { + 0 -> copyExactly(source, out, expected.toLong()) + 1 -> decompressLzma(source, expected.toLong(), out) + 2, 3 -> decompressLz4(source, input.size.toLong(), expected.toLong(), out) + else -> throw UnityFormatException("UnityFS uses unsupported block-table compression $compression") + } + if (written != expected.toLong()) throw UnityFormatException("UnityFS block table could not be decompressed") + return out.toByteArray() + } + + private fun decompressLzma(input: InputStream, expected: Long, output: OutputStream): Long { + val properties = ByteArray(5) + readFully(input, properties) + val dictRaw = ((properties[1].toLong() and 0xFF) or + ((properties[2].toLong() and 0xFF) shl 8) or + ((properties[3].toLong() and 0xFF) shl 16) or + ((properties[4].toLong() and 0xFF) shl 24)) + if (dictRaw > LZMAInputStream.DICT_SIZE_MAX.toLong() || dictRaw > MAX_LZMA_DICTIONARY) { + throw UnityFormatException("UnityFS LZMA dictionary exceeds the supported size") + } + val dictSize = maxOf(dictRaw, 4096L).toInt() + val decoder = try { + LZMAInputStream(BufferedInputStream(input, BUFFER_SIZE), expected, properties[0], dictSize) + } catch (e: Exception) { + throw UnityFormatException("Could not initialize UnityFS LZMA decompression", e) + } + decoder.use { return copyExactly(it, output, expected) } + } + + private fun decompressLz4(input: InputStream, compressedSize: Long, expected: Long, output: OutputStream): Long { + if (compressedSize < 0 || expected < 0) throw UnityFormatException("Invalid UnityFS LZ4 block size") + val window = ByteArray(65_536) + val source = if (input is BufferedInputStream) input else BufferedInputStream(input, BUFFER_SIZE) + var consumed = 0L + var produced = 0L + + fun nextByte(): Int { + if (consumed >= compressedSize) throw UnityFormatException("Truncated UnityFS LZ4 block") + val value = source.read() + if (value < 0) throw UnityFormatException("Truncated UnityFS LZ4 block") + consumed++ + return value + } + + fun length(initial: Int): Int { + var result = initial + if (initial == 15) { + while (true) { + val extra = nextByte() + if (result > Int.MAX_VALUE - extra) throw UnityFormatException("UnityFS LZ4 length overflows") + result += extra + if (extra != 255) break + } + } + return result + } + + fun emit(value: Int) { + if (produced >= expected) throw UnityFormatException("UnityFS LZ4 block expands beyond its declared size") + val b = value.toByte() + output.write(value) + window[(produced and 0xFFFF).toInt()] = b + produced++ + } + + while (consumed < compressedSize) { + val token = nextByte() + val literals = length(token ushr 4) + repeat(literals) { emit(nextByte()) } + if (consumed == compressedSize) break + val distance = nextByte() or (nextByte() shl 8) + if (distance <= 0 || distance > minOf(produced, 65_535L)) throw UnityFormatException("Invalid UnityFS LZ4 back-reference") + val matchLength = length(token and 0x0F) + if (matchLength > Int.MAX_VALUE - 4) throw UnityFormatException("UnityFS LZ4 match length overflows") + val match = matchLength + 4 + if (match.toLong() > expected - produced) throw UnityFormatException("UnityFS LZ4 block expands beyond its declared size") + repeat(match) { + val source = ((produced - distance) and 0xFFFF).toInt() + emit(window[source].toInt() and 0xFF) + } + } + output.flush() + if (produced != expected) throw UnityFormatException("UnityFS LZ4 block expands to $produced bytes; expected $expected") + return produced + } + + private fun probeSerializedFile(file: File, signature: String): UnityProbe = runCatching { + RandomAccessFile(file, "r").use { input -> + if (input.length() < 20) return@use UnityProbe(UnityFileKind.UNKNOWN, signature, note = "Unknown or truncated Unity file") + var metadataSize = readU32(input) + var declaredSize = readU32(input) + val version = readU32(input).toInt() + var dataOffset = readU32(input) + if (version !in 9..100) return@use UnityProbe(UnityFileKind.UNKNOWN, signature, note = "Unknown Unity file signature") + val endian = input.readUnsignedByte() + input.skipBytes(3) + if (version >= 22 && input.filePointer + 32 <= input.length()) { + val extendedMetadata = input.readLong() + val extendedSize = input.readLong() + val extendedOffset = input.readLong() + input.readLong() + if (extendedMetadata in 1..MAX_INFO_BYTES && extendedSize in 1..file.length() && extendedOffset in 1..file.length()) { + metadataSize = extendedMetadata + declaredSize = extendedSize + dataOffset = extendedOffset + } + } + val headerSize = if (version >= 22) 52L else 20L + val plausible = metadataSize in 1..file.length() && + declaredSize in headerSize..file.length() && + dataOffset in headerSize..declaredSize && + metadataSize <= dataOffset - headerSize && + endian in 0..1 + if (!plausible) UnityProbe(UnityFileKind.UNKNOWN, signature, note = "Unknown Unity file signature") + else UnityProbe(UnityFileKind.SERIALIZED_FILE, "SerializedFile", version, dataOffset = dataOffset, note = "Unity serialized asset file") + } + }.getOrElse { UnityProbe(UnityFileKind.UNKNOWN, signature, note = "Unknown Unity file signature") } + + private fun align16(value: Long): Long = (value + 15L) and -16L + + private fun readCString(input: RandomAccessFile, max: Int): String { + val bytes = ByteArrayOutputStream() + while (bytes.size() < max) { + val b = input.read() + if (b < 0) throw EOFException("Truncated UnityFS string") + if (b == 0) return bytes.toByteArray().toString(Charsets.UTF_8) + bytes.write(b) + } + throw UnityFormatException("UnityFS string is too long") + } + + private fun readU32(input: RandomAccessFile): Long = input.readInt().toLong() and 0xFFFF_FFFFL + + private fun readFully(input: InputStream, bytes: ByteArray) { + var p = 0 + while (p < bytes.size) { + val n = input.read(bytes, p, bytes.size - p) + if (n < 0) throw EOFException("Truncated UnityFS compressed block") + p += n + } + } + + private class Cursor(private val bytes: ByteArray) { + private var position = 0 + val remaining: Int get() = bytes.size - position + + fun readU16(): Int { + requireBytes(2) + val value = ((bytes[position].toInt() and 0xFF) shl 8) or (bytes[position + 1].toInt() and 0xFF) + position += 2 + return value + } + + fun readU32(): Long { + requireBytes(4) + val value = ((bytes[position].toLong() and 0xFF) shl 24) or + ((bytes[position + 1].toLong() and 0xFF) shl 16) or + ((bytes[position + 2].toLong() and 0xFF) shl 8) or + (bytes[position + 3].toLong() and 0xFF) + position += 4 + return value + } + + fun readI64(): Long { + requireBytes(8) + var value = 0L + repeat(8) { value = (value shl 8) or (bytes[position++].toLong() and 0xFF) } + return value + } + + fun readBytes(length: Int): ByteArray { + requireBytes(length) + return bytes.copyOfRange(position, position + length).also { position += length } + } + + fun readCString(max: Int): String { + val start = position + while (position < bytes.size && position - start <= max && bytes[position] != 0.toByte()) position++ + if (position >= bytes.size || position - start > max) throw UnityFormatException("UnityFS entry name is invalid") + val value = bytes.copyOfRange(start, position).toString(Charsets.UTF_8) + position++ + return value + } + + private fun requireBytes(count: Int) { + if (count < 0 || count > remaining) throw UnityFormatException("UnityFS block table is truncated") + } + } + + private class RandomAccessFileSlice(private val input: RandomAccessFile, private var remaining: Long) : InputStream() { + override fun read(): Int { + if (remaining <= 0) return -1 + val value = input.read() + if (value >= 0) remaining-- + return value + } + + override fun read(buffer: ByteArray, offset: Int, length: Int): Int { + if (length == 0) return 0 + if (remaining <= 0) return -1 + val count = input.read(buffer, offset, minOf(length.toLong(), remaining).toInt()) + if (count > 0) remaining -= count + return count + } + + override fun close() = Unit + } + + private fun Long.toIntChecked(name: String): Int { + if (this > Int.MAX_VALUE) throw UnityFormatException("UnityFS $name is too large") + return toInt() + } +} diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt new file mode 100644 index 0000000..4a46d4c --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt @@ -0,0 +1,85 @@ +package dev.cluvex.strata.core.unity + +import dev.cluvex.strata.core.archive.ArchiveParent +import dev.cluvex.strata.core.archive.ZipEditor +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException + +/** Rebuilds a new Unity bundle and, when nested, copies each containing archive outward. */ +object UnityPackageRepacker { + fun repack( + document: UnityBundleDocument, + replacements: Map, + parents: List, + cacheDir: File, + ): File { + cacheDir.mkdirs() + val tempDir = File(cacheDir, "unity-repack-${System.nanoTime()}") + if (!tempDir.mkdir()) throw IOException("Could not create a unique Unity staging directory") + var cleanupFile: File? = null + try { + val bundle = if (parents.isEmpty()) { + uniqueSibling(document.source, "-unity-edited") + } else { + File(tempDir, "rebuilt-bundle.${document.source.extension.ifEmpty { "bundle" }}") + } + document.repack(bundle, replacements) + var current = bundle + cleanupFile = bundle + + for (index in parents.indices.reversed()) { + val parent = parents[index] + val source = File(parent.archivePath) + if (!source.isFile) throw IOException("Parent archive is missing: ${source.name}") + val isFinal = index == 0 + val destination = if (isFinal) uniqueSibling(source, "-unity-edited") else { + File(tempDir, "parent-${index}-${System.nanoTime()}-${source.name}") + } + copyExclusive(source, destination) + try { + ZipEditor.replace(destination, parent.entryPath, current) + } catch (e: Throwable) { + destination.delete() + throw e + } + if (current != bundle) current.delete() + current = destination + cleanupFile = destination + } + if (bundle != current) bundle.delete() + return current + } catch (e: Throwable) { + cleanupFile?.delete() + throw e + } finally { + tempDir.deleteRecursively() + } + } + + private fun copyExclusive(source: File, destination: File) { + if (!destination.createNewFile()) throw IOException("Output already exists: ${destination.name}") + try { + FileInputStream(source).buffered().use { input -> + FileOutputStream(destination).buffered().use { output -> input.copyTo(output) } + } + } catch (e: Throwable) { + destination.delete() + throw e + } + } + + private fun uniqueSibling(source: File, suffix: String): File { + val parent = source.parentFile ?: throw IOException("Source has no parent directory") + val extension = source.extension + val base = source.nameWithoutExtension + suffix + var candidate = File(parent, if (extension.isEmpty()) base else "$base.$extension") + var index = 1 + while (candidate.exists()) { + candidate = File(parent, if (extension.isEmpty()) "$base ($index)" else "$base ($index).$extension") + index++ + } + return candidate + } +} diff --git a/app/src/main/java/dev/cluvex/strata/feature/archive/ArchiveScreen.kt b/app/src/main/java/dev/cluvex/strata/feature/archive/ArchiveScreen.kt index 469ce22..6d89c27 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/archive/ArchiveScreen.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/archive/ArchiveScreen.kt @@ -95,6 +95,7 @@ data class ArchiveActions( val onSignApk: (String) -> Unit, val onLocate: (folder: String, reveal: String?) -> Unit, val onOpenArsc: (archive: String, entry: String) -> Unit, + val onOpenEntry: (archive: String, entry: ArchiveEntry, materialized: File) -> Unit, ) private sealed interface ArchiveDialog { @@ -166,7 +167,7 @@ fun ArchiveScreen( } scope.launch { try { - actions.onOpenFile(vm.materialize(entry)) + actions.onOpenEntry(s.path, entry, vm.materialize(entry)) } catch (e: PasswordRequiredException) { pendingOpen = entry dialog = ArchiveDialog.Password diff --git a/app/src/main/java/dev/cluvex/strata/feature/open/OpenWithDialog.kt b/app/src/main/java/dev/cluvex/strata/feature/open/OpenWithDialog.kt index 7bb1f2e..3967f63 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/open/OpenWithDialog.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/open/OpenWithDialog.kt @@ -101,6 +101,7 @@ val Opener.icon: ImageVector Opener.PDF_READER -> Icons.Rounded.PictureAsPdf Opener.DEX_EDITOR -> Icons.Rounded.Code Opener.ARSC_EDITOR -> Icons.Rounded.DataObject + Opener.UNITY_ASSET -> Icons.Rounded.FolderZip } private data class AppChoice(val target: OpenTarget.App, val label: String, val icon: ImageBitmap?) diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt new file mode 100644 index 0000000..bce0997 --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt @@ -0,0 +1,355 @@ +package dev.cluvex.strata.feature.unity + +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.clickable +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.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.rounded.ArrowBack +import androidx.compose.material.icons.rounded.FolderOpen +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +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.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import dev.cluvex.strata.R +import dev.cluvex.strata.core.archive.ArchiveParent +import dev.cluvex.strata.core.model.FileItem +import dev.cluvex.strata.core.unity.UnityBundleDocument +import dev.cluvex.strata.core.unity.UnityBundleEntry +import dev.cluvex.strata.core.unity.UnityFileKind +import dev.cluvex.strata.core.unity.UnityProbe +import dev.cluvex.strata.core.util.Formatters +import dev.cluvex.strata.ui.isolated +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException + +@Composable +fun UnityAssetScreen( + path: String, + parents: List, + refreshToken: Long, + onBack: () -> Unit, + onOpenFile: (FileItem) -> Unit, + onSignApk: (File) -> Unit, + onLocate: (folder: String, reveal: String?) -> Unit, + vm: UnityAssetViewModel = viewModel(), +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val snackbar = remember { SnackbarHostState() } + val state by vm.state.collectAsStateWithLifecycle() + var localBusy by remember(path) { mutableStateOf(false) } + var signPrompt by remember(path) { mutableStateOf(false) } + + LaunchedEffect(path, refreshToken) { + vm.open(path) + vm.refreshEditedFiles() + } + LifecycleResumeEffect(path) { + vm.refreshEditedFiles() + onPauseOrDispose { } + } + LaunchedEffect(state.message) { + state.message?.let { + snackbar.showSnackbar(it) + vm.consumeMessage() + } + } + + val document = state.document + val selectedEntry = remember(document, state.selectedName) { + document?.summary?.entries?.firstOrNull { it.name == state.selectedName } + } + val busy = state.busy || localBusy + + val replacePicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + val entry = selectedEntry + if (uri != null && entry != null) { + scope.launch { + localBusy = true + try { + vm.replaceEntry(entry, uri, context.contentResolver) + } catch (_: Exception) { + vm.notifyMessage(context.getString(R.string.unity_operation_failed)) + } finally { + localBusy = false + } + } + } + } + + val exportPicker = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("*/*")) { uri -> + val entry = selectedEntry + if (uri != null && entry != null) { + scope.launch { + localBusy = true + try { + val source = vm.fileFor(entry) + withContext(Dispatchers.IO) { + val target = context.contentResolver.openOutputStream(uri) ?: throw IOException("Export destination unavailable") + target.use { out -> source.inputStream().buffered().use { it.copyTo(out) } } + } + vm.notifyMessage(context.getString(R.string.unity_export_done, uri.lastPathSegment ?: entry.displayName)) + } catch (_: Exception) { + vm.notifyMessage(context.getString(R.string.unity_operation_failed)) + } finally { + localBusy = false + } + } + } + } + + BackHandler(enabled = !busy) { onBack() } + + Scaffold( + snackbarHost = { SnackbarHost(snackbar) }, + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = onBack, enabled = !busy) { + Icon(Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = stringResource(R.string.common_back)) + } + }, + title = { + Column { + Text(stringResource(R.string.unity_title), maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(isolated(File(path).name), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + }, + actions = { + IconButton(onClick = { onLocate(File(path).parent ?: "/", path) }) { + Icon(Icons.Rounded.FolderOpen, contentDescription = stringResource(R.string.archive_show_in_files)) + } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).padding(horizontal = 16.dp, vertical = 10.dp)) { + when { + state.loading -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) { + CircularProgressIndicator() + Text(stringResource(R.string.unity_loading), style = MaterialTheme.typography.bodyMedium) + } + } + state.error != null -> ErrorPanel(state.error ?: stringResource(R.string.unity_load_failed)) + document != null -> { + BundleSummaryCard(document) + if (parents.isNotEmpty()) { + Text(stringResource(R.string.unity_parent_copy_note), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp, bottom = 4.dp)) + } else { + Text(stringResource(R.string.unity_output_copy_note), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp, bottom = 4.dp)) + } + if (document.summary.entries.isEmpty()) { + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { + Text(stringResource(R.string.unity_no_entries), color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } else { + LazyColumn(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { + itemsIndexed(document.summary.entries, key = { index, entry -> "$index:${entry.name}" }) { index, entry -> + UnityEntryRow( + index = index, + entry = entry, + selected = state.selectedName == entry.name, + modified = entry.name in state.replacements || entry.name in state.editedFiles, + onClick = { vm.select(entry.name) }, + ) + } + } + } + selectedEntry?.let { entry -> + UnityEntryActions( + entry = entry, + busy = busy, + onOpen = { + scope.launch { + try { + onOpenFile(FileItem.of(vm.fileFor(entry))) + } catch (_: Exception) { + vm.notifyMessage(context.getString(R.string.unity_operation_failed)) + } + } + }, + onExport = { exportPicker.launch(entry.displayName) }, + onReplace = { replacePicker.launch(arrayOf("*/*")) }, + ) + } ?: Text(stringResource(R.string.unity_select_entry), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp)) + + val changedCount = state.replacements.size + state.editedFiles.keys.count { it !in state.replacements } + if (changedCount > 0) { + Text( + stringResource(R.string.unity_replacements_count, changedCount), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(vertical = 4.dp), + ) + } + Button( + onClick = { vm.repack(parents) }, + enabled = !busy, + modifier = Modifier.fillMaxWidth().padding(top = 4.dp), + ) { + if (busy) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + else Text(stringResource(R.string.unity_repack)) + } + state.output?.let { saved -> + Row(Modifier.fillMaxWidth().padding(top = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = { onLocate(saved.parent ?: "/", saved.path) }, modifier = Modifier.weight(1f)) { + Text(stringResource(R.string.archive_show_in_files), maxLines = 1) + } + if (saved.extension.equals("apk", ignoreCase = true)) { + OutlinedButton(onClick = { signPrompt = true }, modifier = Modifier.weight(1f)) { + Text(stringResource(R.string.unity_sign_copy), maxLines = 1) + } + } + } + } + } + else -> UnsupportedPanel(state.probe) + } + } + } + + if (signPrompt) { + AlertDialog( + onDismissRequest = { signPrompt = false }, + title = { Text(stringResource(R.string.unity_sign_copy)) }, + text = { Text(stringResource(R.string.unity_sign_prompt)) }, + confirmButton = { + TextButton(onClick = { + signPrompt = false + state.output?.let(onSignApk) + }) { Text(stringResource(R.string.common_sign_apk)) } + }, + dismissButton = { TextButton(onClick = { signPrompt = false }) { Text(stringResource(R.string.common_cancel)) } }, + ) + } +} + +@Composable +private fun BundleSummaryCard(document: UnityBundleDocument) { + val s = document.summary + Surface(shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.surfaceContainerLow, modifier = Modifier.fillMaxWidth()) { + Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text(stringResource(R.string.unity_bundle_format, s.formatVersion), style = MaterialTheme.typography.titleMedium) + Text(stringResource(R.string.unity_engine_version, s.engineVersion.ifEmpty { "—" }), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(stringResource(R.string.unity_player_version, s.playerVersion.ifEmpty { "—" }), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(stringResource(R.string.unity_entries_count, s.entries.size, Formatters.size(s.dataSize)), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary) + } + } +} + +@Composable +private fun UnityEntryRow( + index: Int, + entry: UnityBundleEntry, + selected: Boolean, + modified: Boolean, + onClick: () -> Unit, +) { + Surface( + shape = RoundedCornerShape(16.dp), + color = if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier.fillMaxWidth().clickable(onClick = onClick), + ) { + Row(Modifier.padding(horizontal = 14.dp, vertical = 11.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Text(index.toString(), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Column(Modifier.weight(1f)) { + Text(entry.displayName, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(isolated(entry.name), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Column(horizontalAlignment = Alignment.End) { + Text(Formatters.size(entry.size), style = MaterialTheme.typography.labelMedium) + if (modified) Text("•", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleMedium) + } + } + } +} + +@Composable +private fun UnityEntryActions( + entry: UnityBundleEntry, + busy: Boolean, + onOpen: () -> Unit, + onExport: () -> Unit, + onReplace: () -> Unit, +) { + Surface(shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.surfaceContainer, modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) { + Column(Modifier.padding(12.dp)) { + Text(isolated(entry.name), style = MaterialTheme.typography.labelMedium, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(stringResource(R.string.unity_entry_size, Formatters.size(entry.size)), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(stringResource(R.string.unity_entry_flags, "0x${entry.flags.toString(16).uppercase().padStart(8, '0')}"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + TextButton(onClick = onOpen, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_open_entry), maxLines = 1) } + TextButton(onClick = onExport, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_export_entry), maxLines = 1) } + TextButton(onClick = onReplace, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_replace_entry), maxLines = 1) } + } + } + } +} + +@Composable +private fun UnsupportedPanel(probe: UnityProbe?) { + Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + Text(stringResource(R.string.unity_not_supported), style = MaterialTheme.typography.bodyMedium) + Spacer(Modifier.size(12.dp)) + when (probe?.kind) { + UnityFileKind.SERIALIZED_FILE -> Text( + stringResource(R.string.unity_serialized_info, probe.fileVersion ?: 0, probe.dataOffset?.let(Formatters::size) ?: "—"), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + UnityFileKind.UNKNOWN, null -> Text(stringResource(R.string.unity_unknown_info), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + else -> Text(stringResource(R.string.unity_not_supported), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } +} + +@Composable +private fun ErrorPanel(message: String) { + Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + Text(stringResource(R.string.unity_error_title), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.error) + Text(message, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(top = 8.dp)) + } +} diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt new file mode 100644 index 0000000..ad0322d --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt @@ -0,0 +1,168 @@ +package dev.cluvex.strata.feature.unity + +import android.app.Application +import android.content.ContentResolver +import android.net.Uri +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import dev.cluvex.strata.R +import dev.cluvex.strata.core.archive.ArchiveParent +import dev.cluvex.strata.core.unity.UnityBundleDocument +import dev.cluvex.strata.core.unity.UnityBundleEntry +import dev.cluvex.strata.core.unity.UnityBundleReader +import dev.cluvex.strata.core.unity.UnityPackageRepacker +import dev.cluvex.strata.core.unity.UnityProbe +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.FileOutputStream +import java.io.IOException + +data class UnityAssetUiState( + val path: String = "", + val loading: Boolean = true, + val busy: Boolean = false, + val probe: UnityProbe? = null, + val document: UnityBundleDocument? = null, + val error: String? = null, + val selectedName: String? = null, + val workingFiles: Map = emptyMap(), + val editedFiles: Map = emptyMap(), + val replacements: Map = emptyMap(), + val output: File? = null, + val message: String? = null, +) + +class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { + private val _state = MutableStateFlow(UnityAssetUiState()) + val state: StateFlow = _state.asStateFlow() + + private var document: UnityBundleDocument? = null + private var stageDir: File? = null + private var workingBaselines: Map> = emptyMap() + + fun open(path: String) { + val current = _state.value + if (current.path == path && (current.loading || current.probe != null || current.error != null)) return + + document?.close() + stageDir?.deleteRecursively() + document = null + workingBaselines = emptyMap() + val newStageDir = File(getApplication().cacheDir, "unity-editor/${path.hashCode().toUInt().toString(16)}-${System.nanoTime()}") + newStageDir.mkdirs() + stageDir = newStageDir + _state.value = UnityAssetUiState(path = path, loading = true) + + viewModelScope.launch { + try { + val (probe, parsed) = withContext(Dispatchers.IO) { + val file = File(path) + val probe = UnityBundleReader.probe(file) + val parsed = if (probe.bundleSupported) UnityBundleReader.open(file, getApplication().cacheDir) else null + probe to parsed + } + document = parsed + _state.update { it.copy(loading = false, probe = probe, document = parsed) } + } catch (_: Exception) { + _state.update { it.copy(loading = false, error = getApplication().getString(R.string.unity_load_failed)) } + } + } + } + + fun select(name: String?) { + _state.update { it.copy(selectedName = name) } + } + + suspend fun fileFor(entry: UnityBundleEntry): File { + val current = _state.value + current.replacements[entry.name]?.takeIf { it.isFile }?.let { return it } + current.workingFiles[entry.name]?.takeIf { it.isFile }?.let { return it } + val doc = document ?: throw IOException("UnityFS bundle is not available") + val dir = stageDir ?: throw IOException("Unity staging directory is not available") + val index = doc.summary.entries.indexOf(entry).coerceAtLeast(0) + val suffix = entry.displayName.substringAfterLast('.', "").takeIf { it.length in 1..10 }?.let { ".$it" }.orEmpty() + val target = File(dir, "entry-$index$suffix") + withContext(Dispatchers.IO) { doc.copyEntry(entry, target) } + workingBaselines = workingBaselines + (entry.name to (target.length() to target.lastModified())) + _state.update { it.copy(workingFiles = it.workingFiles + (entry.name to target)) } + return target + } + + suspend fun replaceEntry(entry: UnityBundleEntry, uri: Uri, resolver: ContentResolver) { + val doc = document ?: throw IOException("UnityFS bundle is not available") + val dir = stageDir ?: throw IOException("Unity staging directory is not available") + val index = doc.summary.entries.indexOf(entry).coerceAtLeast(0) + val suffix = entry.displayName.substringAfterLast('.', "").takeIf { it.length in 1..10 }?.let { ".$it" }.orEmpty() + val staged = File(dir, "replacement-$index-${System.nanoTime()}$suffix") + try { + withContext(Dispatchers.IO) { + val input = resolver.openInputStream(uri) ?: throw IOException("Could not open replacement") + input.use { source -> FileOutputStream(staged).use { target -> source.copyTo(target) } } + } + _state.update { + it.copy( + replacements = it.replacements + (entry.name to staged), + message = getApplication().getString(R.string.unity_replace_done), + ) + } + } catch (e: Exception) { + staged.delete() + throw e + } + } + + fun refreshEditedFiles() { + val current = _state.value + val changed = current.workingFiles.filter { (name, file) -> + val baseline = workingBaselines[name] + baseline != null && (file.length() != baseline.first || file.lastModified() != baseline.second) + } + _state.update { it.copy(editedFiles = changed) } + } + + fun repack(parents: List) { + val doc = document ?: return + val current = _state.value + if (current.busy) return + val changes = current.editedFiles + current.replacements + _state.update { it.copy(busy = true, error = null) } + viewModelScope.launch { + try { + val output = withContext(Dispatchers.IO) { + UnityPackageRepacker.repack(doc, changes, parents, getApplication().cacheDir) + } + _state.update { + it.copy( + output = output, + message = getApplication().getString(R.string.unity_repack_done, output.path), + busy = false, + ) + } + } catch (_: Exception) { + _state.update { + it.copy(message = getApplication().getString(R.string.unity_operation_failed), busy = false) + } + } + } + } + + fun notifyMessage(text: String) { + _state.update { it.copy(message = text) } + } + + fun consumeMessage() { + _state.update { it.copy(message = null) } + } + + override fun onCleared() { + document?.close() + stageDir?.deleteRecursively() + super.onCleared() + } +} diff --git a/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt b/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt index e97feb6..a8e4b5d 100644 --- a/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt +++ b/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt @@ -69,6 +69,7 @@ import dev.cluvex.strata.core.i18n.tr import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import androidx.lifecycle.viewmodel.compose.viewModel +import dev.cluvex.strata.core.archive.ArchiveParent import dev.cluvex.strata.core.bookmarks.Bookmark import dev.cluvex.strata.core.bookmarks.Bookmarks import dev.cluvex.strata.core.data.SettingsRepository @@ -121,6 +122,7 @@ import dev.cluvex.strata.feature.settings.ToolbarTab import dev.cluvex.strata.feature.share.ShareScreen import dev.cluvex.strata.feature.termux.LanguagesScreen import dev.cluvex.strata.feature.trash.RecycleBinScreen +import dev.cluvex.strata.feature.unity.UnityAssetScreen import dev.cluvex.strata.ui.drawer.DrawerActions import dev.cluvex.strata.ui.drawer.StrataDrawerContent import java.io.File @@ -141,7 +143,8 @@ sealed interface Route { data class Hex(val path: String) : Route data class Search(val root: String) : Route data class ApkInfo(val path: String) : Route - data class Archive(val path: String) : Route + data class Archive(val path: String, val parents: List = emptyList()) : Route + data class UnityAsset(val path: String, val parents: List = emptyList()) : Route data class Image(val path: String) : Route data class Video(val path: String) : Route data class Font(val path: String) : Route @@ -159,8 +162,8 @@ sealed interface Route { } private sealed interface OpenDialog { - data class Apk(val path: String) : OpenDialog - data class SplitInstall(val path: String) : OpenDialog + data class Apk(val path: String, val parents: List = emptyList()) : OpenDialog + data class SplitInstall(val path: String, val parents: List = emptyList()) : OpenDialog data class OpenWith(val item: FileItem) : OpenDialog data class SignApk(val item: FileItem) : OpenDialog data class Music(val path: String) : OpenDialog @@ -172,6 +175,7 @@ private class ShellActions( val pop: () -> Unit, val replace: (Route) -> Unit, val openFile: (FileItem) -> Unit, + val openNestedFile: (File, List) -> Unit, val openWith: (FileItem) -> Unit, val openWithOpener: (FileItem, Opener) -> Unit, val signApk: (FileItem) -> Unit, @@ -270,6 +274,7 @@ fun AppShell( Opener.PDF_READER -> stack.push(Route.Pdf(item.path, null)) Opener.DEX_EDITOR -> stack.push(Route.Dex(item.path)) Opener.ARSC_EDITOR -> stack.push(Route.Arsc(item.path, null)) + Opener.UNITY_ASSET -> stack.push(Route.UnityAsset(item.path)) } } @@ -282,6 +287,22 @@ fun AppShell( } } + fun openNestedFile(file: File, parents: List) { + val item = FileItem.of(file) + when (val target = OpenResolver.resolve(item, settings.openDefaults)) { + null -> openDialog = OpenDialog.OpenWith(item) + is OpenTarget.App -> + if (!IntentUtils.openIn(context, item, target.packageName, target.activity)) openDialog = OpenDialog.OpenWith(item) + is OpenTarget.BuiltIn -> when (target.opener) { + Opener.UNITY_ASSET -> stack.push(Route.UnityAsset(file.path, parents)) + Opener.ARCHIVE_VIEWER -> stack.push(Route.Archive(file.path, parents)) + Opener.APK_VIEWER -> openDialog = OpenDialog.Apk(file.path, parents) + Opener.SPLIT_APK_INSTALLER -> openDialog = OpenDialog.SplitInstall(file.path, parents) + else -> openWith(item, target.opener) + } + } + } + fun locate(folder: String, reveal: String?) { stack.clear() openDialog = null @@ -293,6 +314,7 @@ fun AppShell( pop = { stack.pop() }, replace = { stack.replace(it) }, openFile = { openFile(it) }, + openNestedFile = { file, parents -> openNestedFile(file, parents) }, openWith = { openDialog = OpenDialog.OpenWith(it) }, openWithOpener = { item, opener -> openWith(item, opener) }, signApk = { openDialog = OpenDialog.SignApk(it) }, @@ -409,7 +431,7 @@ fun AppShell( saveable.SaveableStateProvider(entry.key) { CompositionLocalProvider(LocalViewModelStoreOwner provides entry) { Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { - Screen(entry.route, settings, settingsRepo, vm, actions) + Screen(entry.route, settings, settingsRepo, vm, actions, stack.top?.key ?: 0L) } } } @@ -430,7 +452,7 @@ fun AppShell( path = d.path, policy = policy, actions = ApkDialogActions( - onView = { stack.push(Route.Archive(d.path)) }, + onView = { stack.push(Route.Archive(d.path, d.parents)) }, onSign = { openDialog = OpenDialog.SignApk(FileItem.of(File(d.path))) }, onDetails = { openDialog = null; stack.push(Route.ApkInfo(d.path)) }, onDexTools = { openDialog = null; stack.push(Route.Dex(d.path)) }, @@ -442,7 +464,7 @@ fun AppShell( is OpenDialog.SplitInstall -> SplitInstallDialog( path = d.path, policy = policy, - onView = { stack.push(Route.Archive(d.path)) }, + onView = { stack.push(Route.Archive(d.path, d.parents)) }, onDismiss = { openDialog = null }, ) is OpenDialog.OpenWith -> OpenWithDialog( @@ -488,6 +510,7 @@ private fun Screen( settingsRepo: SettingsRepository, vm: ExplorerViewModel, actions: ShellActions, + refreshToken: Long, ) { when (r) { Route.Files -> Unit @@ -563,8 +586,20 @@ private fun Screen( onSignApk = { p -> actions.signApk(FileItem.of(File(p))) }, onLocate = actions.locate, onOpenArsc = { archive, entry -> actions.push(Route.Arsc(archive, entry)) }, + onOpenEntry = { archive, entry, materialized -> + actions.openNestedFile(materialized, r.parents + ArchiveParent(archive, entry.path)) + }, ), ) + is Route.UnityAsset -> UnityAssetScreen( + path = r.path, + parents = r.parents, + refreshToken = refreshToken, + onBack = actions.pop, + onOpenFile = actions.openFile, + onSignApk = { file -> actions.signApk(FileItem.of(file)) }, + onLocate = actions.locate, + ) is Route.Image -> ImageViewerScreen( path = r.path, showHidden = settings.showHidden, diff --git a/app/src/main/res/values-fa/strings_unity.xml b/app/src/main/res/values-fa/strings_unity.xml new file mode 100644 index 0000000..26c069a --- /dev/null +++ b/app/src/main/res/values-fa/strings_unity.xml @@ -0,0 +1,39 @@ + + + ویرایشگر فایل‌های Unity + ویرایشگر فایل‌های Unity + در حال خواندن فایل Unity… + قالب UnityFS %1$d + نسخهٔ موتور Unity: %1$s + Player: %1$s + %1$d ورودی · %2$s داده + برای بررسی، بازکردن، خروجی‌گرفتن یا جایگزینی، یک ورودی انتخاب کنید. + مسیر: %1$s + اندازه: %1$s + پرچم‌ها: %1$s + بازکردن / ویرایش با Strata + خروجی‌گرفتن از ورودی + جایگزینی ورودی… + بازسازی بسته + در حال بازسازی بستهٔ Unity… + نسخهٔ بازسازی‌شده در %1$s ذخیره شد + در %1$s خروجی گرفته شد + جایگزین آماده شد. برای ساخت نسخهٔ تازه، بسته را بازسازی کنید. + ورودی‌های ویرایش یا جایگزین‌شده: %1$d + این فایل به‌عنوان فایل Unity شناسایی شد، اما ساختار بسته برای ویرایش پشتیبانی نمی‌شود. + Unity SerializedFile · نسخهٔ %1$d · جابه‌جایی داده %2$s + سرآیند UnityFS پشتیبانی‌شده‌ای در این فایل پیدا نشد. + این بستهٔ UnityFS فایلی ندارد. + اگر فایل داخل یک آرشیو باشد، Strata از هر بستهٔ والد یک نسخهٔ جداگانه بازسازی می‌کند؛ فایل‌های اصلی تغییر نمی‌کنند. + بستهٔ بازسازی‌شده به‌صورت فایل تازه در کنار فایل اصلی ذخیره می‌شود؛ فایل اصلی بازنویسی نمی‌شود. + خطای فایل Unity + خواندن فایل Unity ممکن نشد؛ ممکن است فایل خراب باشد یا پشتیبانی نشود. + عملیات انجام نشد. قالب فایل، دسترسی ذخیره‌سازی و فضای خالی را بررسی کنید. + خواندن ورودی انتخاب‌شده ممکن نشد. + امضای نسخهٔ بازسازی‌شدهٔ APK + بازسازی APK امضای اصلی آن را باطل می‌کند. پیش از نصب، این کپی APK را با ابزار امضای موجود Strata امضا کنید. + + %1$d ورودی + %1$d ورودی + + diff --git a/app/src/main/res/values-ru/strings_unity.xml b/app/src/main/res/values-ru/strings_unity.xml new file mode 100644 index 0000000..d75ce7e --- /dev/null +++ b/app/src/main/res/values-ru/strings_unity.xml @@ -0,0 +1,41 @@ + + + Редактор ресурсов Unity + Редактор ресурсов Unity + Чтение файла Unity… + Формат UnityFS %1$d + Версия движка Unity: %1$s + Player: %1$s + Записей: %1$d · данных: %2$s + Выберите запись, чтобы просмотреть, открыть, экспортировать или заменить её. + Путь: %1$s + Размер: %1$s + Флаги: %1$s + Открыть / изменить в Strata + Экспортировать запись + Заменить запись… + Пересобрать пакет + Пересборка пакета Unity… + Пересобранная копия сохранена: %1$s + Экспортировано в %1$s + Замена подготовлена. Пересоберите пакет, чтобы создать новую копию. + Изменено или заменено записей: %1$d + Файл распознан как Unity, но его структура контейнера не поддерживается для редактирования. + Unity SerializedFile · версия %1$d · смещение данных %2$s + В файле не найден поддерживаемый заголовок UnityFS. + В этом пакете UnityFS нет файлов. + Для файла внутри архива Strata создаёт отдельную пересобранную копию каждого родительского пакета. Исходные файлы остаются неизменными. + Пересобранный пакет сохраняется рядом как новый файл; оригинал не перезаписывается. + Ошибка файла Unity + Не удалось прочитать файл Unity. Возможно, он повреждён или не поддерживается. + Не удалось выполнить операцию. Проверьте формат, доступ к хранилищу и свободное место. + Не удалось прочитать выбранную запись. + Подписать пересобранную копию APK + Пересборка APK аннулирует исходную подпись. Перед установкой подпишите эту копию встроенным инструментом Strata. + + %1$d запись + %1$d записи + %1$d записей + %1$d записи + + diff --git a/app/src/main/res/values-zh-rCN/strings_unity.xml b/app/src/main/res/values-zh-rCN/strings_unity.xml new file mode 100644 index 0000000..64ea017 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings_unity.xml @@ -0,0 +1,38 @@ + + + Unity 资源编辑器 + Unity 资源编辑器 + 正在读取 Unity 文件… + UnityFS 格式 %1$d + Unity 引擎:%1$s + Player:%1$s + %1$d 个条目 · 数据 %2$s + 选择条目以检查、打开、导出或替换。 + 路径:%1$s + 大小:%1$s + 标志:%1$s + 使用 Strata 打开 / 编辑 + 导出条目 + 替换条目… + 重建资源包 + 正在重建 Unity 资源包… + 重建副本已保存到 %1$s + 已导出到 %1$s + 替换已暂存。请重建资源包以生成新副本。 + 已编辑或替换条目:%1$d + 已识别此 Unity 文件,但不支持编辑其容器布局。 + Unity SerializedFile · 版本 %1$d · 数据偏移 %2$s + 文件中没有受支持的 UnityFS 标头。 + 此 UnityFS 资源包不包含文件。 + 如果文件位于归档中,Strata 会为每个父级资源包创建单独的重建副本。原文件不会更改。 + 重建后的资源包会作为新文件保存在原文件旁边;不会覆盖原文件。 + Unity 文件错误 + 无法读取此 Unity 文件。文件可能已损坏或不受支持。 + 操作失败。请检查文件格式、存储访问权限和可用空间。 + 无法读取所选条目。 + 签署重建后的 APK 副本 + 重建 APK 会使原签名失效。安装前,请使用 Strata 现有签名工具为此副本签名。 + + %1$d 个条目 + + diff --git a/app/src/main/res/values/strings_unity.xml b/app/src/main/res/values/strings_unity.xml new file mode 100644 index 0000000..33563af --- /dev/null +++ b/app/src/main/res/values/strings_unity.xml @@ -0,0 +1,39 @@ + + + Unity asset editor + Unity asset editor + Reading Unity file… + UnityFS format %1$d + Unity engine: %1$s + Player: %1$s + %1$d entries · %2$s data + Select an entry to inspect, open, export, or replace it. + Path: %1$s + Size: %1$s + Flags: %1$s + Open / edit with Strata + Export entry + Replace entry… + Rebuild bundle + Rebuilding Unity bundle… + A rebuilt copy was saved to %1$s + Exported to %1$s + Replacement staged. Rebuild the bundle to create a new copy. + Edited or replaced entries: %1$d + This Unity file was recognized, but its container layout is not supported for editing. + Unity SerializedFile · version %1$d · data offset %2$s + The file does not have a supported UnityFS header. + This UnityFS bundle contains no files. + For a file inside an archive, Strata rebuilds a separate copy of every parent package. The original files remain unchanged. + The rebuilt bundle is saved as a new sibling file; the original is never overwritten. + Unity file error + Could not read this Unity file. It may be damaged or unsupported. + Operation failed. Check the file format, storage access, and available space. + The selected entry could not be read. + Sign rebuilt APK copy + Rebuilding an APK invalidates its original signature. Sign this copied APK with Strata’s existing signing tool before installing it. + + %1$d entry + %1$d entries + + diff --git a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt new file mode 100644 index 0000000..b422e16 --- /dev/null +++ b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt @@ -0,0 +1,155 @@ +package dev.cluvex.strata.core.unity + +import com.google.common.truth.Truth.assertThat +import org.junit.Assert.assertThrows +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayOutputStream +import java.io.DataOutputStream +import java.io.File +import java.io.FileOutputStream +import java.security.MessageDigest + +class UnityBundleReaderTest { + private data class TestNode(val name: String, val offset: Long, val size: Long) + + @get:Rule + val temp = TemporaryFolder() + + @Test + fun readsAndRebuildsUncompressedUnityFs() { + val contents = "small text asset".toByteArray() + val source = writeBundle(temp.root, "source.bundle", contents, compression = 0) + val cache = File(temp.root, "cache") + + assertThat(UnityBundleReader.probe(source).kind).isEqualTo(UnityFileKind.UNITY_FS) + UnityBundleReader.open(source, cache).use { document -> + assertThat(document.summary.entries.map { it.name }).containsExactly("assets/message.txt") + val extracted = File(temp.root, "extracted.txt") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + + val replacement = File(temp.root, "replacement.txt").apply { writeText("updated") } + val output = File(temp.root, "rebuilt.bundle") + document.repack(output, mapOf("assets/message.txt" to replacement)) + UnityBundleReader.open(output, cache).use { rebuilt -> + val result = File(temp.root, "rebuilt-entry.txt") + rebuilt.copyEntry(rebuilt.summary.entries.single(), result) + assertThat(result.readText()).isEqualTo("updated") + assertThat(rebuilt.summary.entries.single().size).isEqualTo(7L) + } + } + } + + @Test + fun refusesToOverwriteExistingExtractionOrRepackOutput() { + val source = writeBundle(temp.root, "source.bundle", "content".toByteArray(), compression = 0) + val extraction = File(temp.root, "existing.txt").apply { writeText("keep me") } + val output = File(temp.root, "existing.bundle").apply { writeText("keep this too") } + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + assertThrows(java.io.IOException::class.java) { + document.copyEntry(document.summary.entries.single(), extraction) + } + assertThrows(java.io.IOException::class.java) { document.repack(output) } + } + assertThat(extraction.readText()).isEqualTo("keep me") + assertThat(output.readText()).isEqualTo("keep this too") + } + + @Test + fun preservesGapsAndFollowingEntriesWhenReplacementGrows() { + val source = writeBundle( + temp.root, + "gapped.bundle", + "headGAPoldTAIL".toByteArray(), + compression = 0, + nodes = listOf( + TestNode("assets/head.bin", 0L, 4L), + TestNode("assets/text.txt", 7L, 3L), + TestNode("assets/tail.bin", 10L, 4L), + ), + ) + val replacement = File(temp.root, "larger.txt").apply { writeText("updated") } + val output = File(temp.root, "gapped-rebuilt.bundle") + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + document.repack(output, mapOf("assets/text.txt" to replacement)) + } + UnityBundleReader.open(output, File(temp.root, "cache")).use { rebuilt -> + assertThat(rebuilt.summary.entries[2].offset).isEqualTo(14L) + val tail = File(temp.root, "tail.bin") + rebuilt.copyEntry(rebuilt.summary.entries[2], tail) + assertThat(tail.readText()).isEqualTo("TAIL") + assertThat(rebuilt.summary.dataSize).isEqualTo(18L) + } + } + + @Test + fun decodesRawLz4LiteralBlock() { + val contents = "unity".toByteArray() + val source = writeBundle(temp.root, "lz4.bundle", contents, compression = 2) + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + val extracted = File(temp.root, "lz4-output") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + } + } + + private fun writeBundle( + root: File, + name: String, + contents: ByteArray, + compression: Int, + nodes: List = listOf(TestNode("assets/message.txt", 0L, contents.size.toLong())), + ): File { + val compressed = if (compression == 2) { + byteArrayOf((contents.size shl 4).toByte()) + contents + } else { + contents + } + val info = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.write(MessageDigest.getInstance("MD5").digest(contents)) + out.writeInt(1) + out.writeInt(contents.size) + out.writeInt(compressed.size) + out.writeShort(compression) + out.writeInt(nodes.size) + nodes.forEach { node -> + out.writeLong(node.offset) + out.writeLong(node.size) + out.writeInt(0) + out.write(node.name.toByteArray(Charsets.UTF_8)) + out.writeByte(0) + } + } + bytes.toByteArray() + } + val headerPrefix = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.write("UnityFS".toByteArray(Charsets.UTF_8)) + out.writeByte(0) + out.writeInt(6) + out.write("2020.3.0f1".toByteArray(Charsets.UTF_8)) + out.writeByte(0) + out.write("2020.3.0f1".toByteArray(Charsets.UTF_8)) + out.writeByte(0) + } + bytes.toByteArray() + } + val headerSize = headerPrefix.size + 8 + 4 + 4 + 4 + val output = File(root, name) + FileOutputStream(output).use { stream -> + DataOutputStream(stream).use { out -> + out.write(headerPrefix) + out.writeLong((headerSize + info.size + compressed.size).toLong()) + out.writeInt(info.size) + out.writeInt(info.size) + out.writeInt(0x40) + out.write(info) + out.write(compressed) + } + } + return output + } +} From 313228ebc667d98d0d10e428950c1ec9bb315d08 Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Sun, 18 Oct 2026 20:39:28 +0000 Subject: [PATCH 02/11] feat: open UnityRaw, UnityWeb and SerializedFile assets - UnityBundleReader.open() now dispatches by probed kind: UnityFS keeps the existing parser; UnityRaw/UnityWeb go through the new legacy reader; bare serialized files (.assets/.resS/level*) through the new SerializedFile reader - UnityLegacyReader: big-endian UnityRaw/UnityWeb containers, format versions 1..9, LZMA-compressed UnityWeb streams - SerializedFileReader: serialized file versions 9..22, lists objects as "# " and extracts raw object bytes; older and newer versions fail with a clear error - repack stays UnityFS-only: UnityBundleDocument.repackSupported plus a guard in the view model with a new localized string (en/fa/ru/zh) - probe(): fix v22+ serialized file extended header layout (u32 + 3 x i64, header size 48) so modern files are recognized correctly - tests: legacy UnityRaw, LZMA UnityWeb, serialized file v17 listing and extraction, unsupported v23 rejection --- .../strata/core/unity/SerializedFileReader.kt | 160 ++++++++++++++++ .../strata/core/unity/UnityBundleReader.kt | 84 ++++++-- .../strata/core/unity/UnityLegacyReader.kt | 108 +++++++++++ .../feature/unity/UnityAssetViewModel.kt | 6 + app/src/main/res/values-fa/strings_unity.xml | 1 + app/src/main/res/values-ru/strings_unity.xml | 1 + .../main/res/values-zh-rCN/strings_unity.xml | 1 + app/src/main/res/values/strings_unity.xml | 1 + .../core/unity/UnityBundleReaderTest.kt | 179 ++++++++++++++++++ 9 files changed, 522 insertions(+), 19 deletions(-) create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt new file mode 100644 index 0000000..fdf6408 --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt @@ -0,0 +1,160 @@ +package dev.cluvex.strata.core.unity + +import java.io.File +import java.io.FileOutputStream +import java.io.RandomAccessFile + +/** + * Reader for Unity serialized asset files ("*.assets", "CAB-*", "level*", ".sharedAssets", ...). + * + * Every object in the file is exposed as an entry so it can be previewed or extracted raw. + * The metadata section (type table + object table) is parsed with the file's own endianness; + * object data offsets are relative to the header's data offset. Format versions 9..22 are + * supported; the Unity 2023+ (v23) shared type-tree layout is rejected with a clear error. + */ +internal object SerializedFileReader { + private const val MAX_OBJECTS = 2_000_000 + private const val MAX_TYPES = 100_000 + private const val MAX_TREE_NODES = 4_000_000 + private const val MAX_STRING_BYTES = 1024 * 1024 + private const val BUFFER_SIZE = 64 * 1024 + + fun parse(file: File, dataFile: File): UnityBundleSummary { + RandomAccessFile(file, "r").use { input -> + UnityBundleReader.readU32(input) // metadata size (32 bit, unused for v9+) + val fileSize32 = UnityBundleReader.readU32(input) + val version = UnityBundleReader.readU32(input) + val dataOffset32 = UnityBundleReader.readU32(input) + if (version !in 9..22) throw UnityFormatException("Unsupported serialized file version $version") + val bigEndian = input.readUnsignedByte() == 1 + input.skipBytes(3) + var fileSize = fileSize32 + var dataOffset = dataOffset32 + if (version >= 22) { + UnityBundleReader.readU32(input) // 32 bit metadata size repeat + fileSize = input.readLong() + dataOffset = input.readLong() + input.readLong() // unknown + } + val headerSize = input.filePointer + if (fileSize < headerSize || fileSize > file.length()) throw UnityFormatException("Serialized file size is invalid") + if (dataOffset < headerSize || dataOffset > fileSize) throw UnityFormatException("Serialized data offset is invalid") + val metadataSize = dataOffset - headerSize + if (metadataSize > MAX_STRING_BYTES * 64L) throw UnityFormatException("Serialized metadata is too large") + val metadata = ByteArray(metadataSize.toInt()) + input.seek(headerSize) + input.readFully(metadata) + val table = UnityBundleReader.Cursor(metadata, bigEndian) + + var unityVersion = "" + if (version >= 7) unityVersion = table.readCString(256) + if (version >= 8) table.readI32() // build target + val enableTypeTree = if (version >= 13) table.readU8() != 0 else true + + val typeCount = table.readI32() + if (typeCount !in 0..MAX_TYPES) throw UnityFormatException("Serialized type count is invalid") + val classIds = ArrayList(typeCount) + repeat(typeCount) { + val classId = table.readI32() + if (version >= 16) table.readU8() // is stripped + if (version >= 17) table.readI16() // script type index + if (version >= 13) { + if ((version < 16 && classId < 0) || (version >= 16 && classId == 114)) table.readBytes(16) + table.readBytes(16) // old type hash + } + if (enableTypeTree) skipTypeTree(table, version) + if (version >= 21) { + val deps = table.readI32() + if (deps !in 0..MAX_TYPES) throw UnityFormatException("Serialized type dependencies are invalid") + table.readBytes(deps * 4) + } + classIds += classId + } + + var bigId = false + if (version in 7..13) bigId = table.readI32() != 0 + + val objectCount = table.readI32() + if (objectCount !in 0..MAX_OBJECTS) throw UnityFormatException("Serialized object count is invalid") + val dataSize = fileSize - dataOffset + val entries = ArrayList(objectCount) + repeat(objectCount) { + val pathId = when { + bigId -> table.readI64() + version < 14 -> table.readI32().toLong() + else -> { + table.align4() + table.readI64() + } + } + val start = if (version >= 22) table.readI64() else table.readU32() + val size = table.readU32() + val typeId = table.readI32() + val classId = if (version < 16) table.readU16() else classIds.getOrElse(typeId) { -1 } + if (version < 11) table.readU16() // is destroyed + if (version in 11..16) table.readI16() // script type index + if (version == 15L || version == 16L) table.readU8() // is stripped + if (start < 0 || start > dataSize || size > dataSize - start) { + throw UnityFormatException("Serialized object is outside the data section") + } + entries += UnityBundleEntry("#$pathId ${className(classId)}", start, size, 0) + } + + val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE + if (dataSize > availableSpace) throw UnityFormatException("Not enough free space to stage Unity data") + dataFile.parentFile?.mkdirs() + input.seek(dataOffset) + FileOutputStream(dataFile).buffered(BUFFER_SIZE).use { out -> copyExactly(input, out, dataSize) } + return UnityBundleSummary( + "SerializedFile", version.toInt(), "", unityVersion, + fileSize, dataSize, 0, entries, + ) + } + } + + private fun skipTypeTree(table: UnityBundleReader.Cursor, version: Long) { + if (version >= 23) { + throw UnityFormatException("Serialized file uses the Unity 2023+ shared type-tree layout, which is not supported yet") + } + if (version >= 12 || version == 10L) { + val nodes = table.readI32() + val strings = table.readI32() + if (nodes !in 0..MAX_TREE_NODES || strings !in 0..MAX_STRING_BYTES) { + throw UnityFormatException("Serialized type tree is invalid") + } + val nodeSize = if (version >= 19) 32 else 24 + table.readBytes(nodes * nodeSize) + table.readBytes(strings) + } else { + skipTypeNodes(table, 0) + } + } + + private fun skipTypeNodes(table: UnityBundleReader.Cursor, depth: Int) { + if (depth > 96) throw UnityFormatException("Serialized type tree is too deep") + table.readCString(MAX_STRING_BYTES) // type + table.readCString(MAX_STRING_BYTES) // name + table.readI32() // byte size + table.readI32() // index + table.readI32() // flags + table.readI32() // version + table.readI32() // meta flag + val children = table.readI32() + if (children !in 0..100_000) throw UnityFormatException("Serialized type tree is invalid") + repeat(children) { skipTypeNodes(table, depth + 1) } + } + + private val CLASS_NAMES = mapOf( + 1 to "GameObject", 2 to "Component", 4 to "Transform", 8 to "Behaviour", + 11 to "AudioManager", 13 to "InputManager", 20 to "Camera", 21 to "Material", + 23 to "Texture", 25 to "Renderer", 28 to "Texture2D", 33 to "MeshFilter", + 43 to "Mesh", 45 to "Skybox", 47 to "QualitySettings", 48 to "Shader", + 49 to "TextAsset", 60 to "Rigidbody", 65 to "BoxCollider", 74 to "AnimationClip", + 83 to "AudioClip", 95 to "Animator", 104 to "MeshRenderer", 114 to "MonoBehaviour", + 115 to "MonoScript", 128 to "Font", 142 to "AssetBundle", 155 to "AnimatorController", + 213 to "Sprite", 222 to "CanvasRenderer", 223 to "Canvas", 224 to "RectTransform", + 329 to "VideoClip", + ) + + private fun className(classId: Int): String = CLASS_NAMES[classId] ?: "Class$classId" +} diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt index f3cdc1c..eb6dcd8 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt @@ -33,7 +33,8 @@ data class UnityProbe( val dataOffset: Long? = null, val note: String? = null, ) { - val bundleSupported: Boolean get() = kind == UnityFileKind.UNITY_FS + /** True when the built-in browser can open and list this kind. Repacking may still be unsupported. */ + val bundleSupported: Boolean get() = kind != UnityFileKind.UNKNOWN } data class UnityBundleEntry( @@ -68,6 +69,9 @@ class UnityBundleDocument internal constructor( internal val dataFile: File, ) : Closeable { + /** Repacking is implemented for UnityFS only; legacy bundles and serialized files are read-only. */ + val repackSupported: Boolean get() = summary.signature == "UnityFS" + fun copyEntry(entry: UnityBundleEntry, output: File) { requireEntry(entry) output.parentFile?.mkdirs() @@ -87,6 +91,7 @@ class UnityBundleDocument internal constructor( /** Writes a normalized UnityFS bundle. Inputs are never overwritten. */ fun repack(output: File, replacements: Map = emptyMap()) { + if (!repackSupported) throw UnityFormatException("This Unity format is read-only; repacking needs a UnityFS bundle") if (output.canonicalFile == source.canonicalFile) throw IOException("Output must not replace the source bundle") if (output.exists()) throw IOException("Output already exists: ${output.name}") val unknown = replacements.keys - summary.entries.map { it.name }.toSet() @@ -231,7 +236,7 @@ class UnityBundleDocument internal constructor( } -private fun copyExactly(input: InputStream, output: OutputStream, length: Long): Long { +internal fun copyExactly(input: InputStream, output: OutputStream, length: Long): Long { if (length < 0) throw UnityFormatException("Negative UnityFS block length") val buffer = ByteArray(64 * 1024) var left = length @@ -246,7 +251,7 @@ private fun copyExactly(input: InputStream, output: OutputStream, length: Long): return copied } -private fun copyExactly(input: RandomAccessFile, output: OutputStream, length: Long): Long { +internal fun copyExactly(input: RandomAccessFile, output: OutputStream, length: Long): Long { if (length < 0) throw UnityFormatException("Negative UnityFS block length") val buffer = ByteArray(64 * 1024) var left = length @@ -261,7 +266,7 @@ private fun copyExactly(input: RandomAccessFile, output: OutputStream, length: L return copied } -private fun checkedAdd(a: Long, b: Long, message: String): Long { +internal fun checkedAdd(a: Long, b: Long, message: String): Long { if (b < 0 || a > Long.MAX_VALUE - b) throw UnityFormatException(message) return a + b } @@ -325,7 +330,12 @@ object UnityBundleReader { cache.mkdirs() val dataFile = File(cache, "bundle-data.bin") try { - val summary = parseUnityFs(file, dataFile) + val summary = when (probe(file).kind) { + UnityFileKind.UNITY_FS -> parseUnityFs(file, dataFile) + UnityFileKind.UNITY_WEB, UnityFileKind.UNITY_RAW -> UnityLegacyReader.parse(file, dataFile) + UnityFileKind.SERIALIZED_FILE -> SerializedFileReader.parse(file, dataFile) + UnityFileKind.UNKNOWN -> throw UnityFormatException("Not a Unity file: ${file.name}") + } return UnityBundleDocument(file, summary, dataFile) } catch (e: Throwable) { dataFile.delete() @@ -454,6 +464,10 @@ object UnityBundleReader { private fun decompressLzma(input: InputStream, expected: Long, output: OutputStream): Long { val properties = ByteArray(5) readFully(input, properties) + return decompressLzmaRaw(input, expected, output, properties) + } + + internal fun decompressLzmaRaw(input: InputStream, expected: Long, output: OutputStream, properties: ByteArray): Long { val dictRaw = ((properties[1].toLong() and 0xFF) or ((properties[2].toLong() and 0xFF) shl 8) or ((properties[3].toLong() and 0xFF) shl 16) or @@ -537,8 +551,8 @@ object UnityBundleReader { if (version !in 9..100) return@use UnityProbe(UnityFileKind.UNKNOWN, signature, note = "Unknown Unity file signature") val endian = input.readUnsignedByte() input.skipBytes(3) - if (version >= 22 && input.filePointer + 32 <= input.length()) { - val extendedMetadata = input.readLong() + if (version >= 22 && input.filePointer + 28 <= input.length()) { + val extendedMetadata = readU32(input) val extendedSize = input.readLong() val extendedOffset = input.readLong() input.readLong() @@ -548,7 +562,7 @@ object UnityBundleReader { dataOffset = extendedOffset } } - val headerSize = if (version >= 22) 52L else 20L + val headerSize = if (version >= 22) 48L else 20L val plausible = metadataSize in 1..file.length() && declaredSize in headerSize..file.length() && dataOffset in headerSize..declaredSize && @@ -561,7 +575,7 @@ object UnityBundleReader { private fun align16(value: Long): Long = (value + 15L) and -16L - private fun readCString(input: RandomAccessFile, max: Int): String { + internal fun readCString(input: RandomAccessFile, max: Int): String { val bytes = ByteArrayOutputStream() while (bytes.size() < max) { val b = input.read() @@ -572,9 +586,9 @@ object UnityBundleReader { throw UnityFormatException("UnityFS string is too long") } - private fun readU32(input: RandomAccessFile): Long = input.readInt().toLong() and 0xFFFF_FFFFL + internal fun readU32(input: RandomAccessFile): Long = input.readInt().toLong() and 0xFFFF_FFFFL - private fun readFully(input: InputStream, bytes: ByteArray) { + internal fun readFully(input: InputStream, bytes: ByteArray) { var p = 0 while (p < bytes.size) { val n = input.read(bytes, p, bytes.size - p) @@ -583,31 +597,63 @@ object UnityBundleReader { } } - private class Cursor(private val bytes: ByteArray) { + internal class Cursor(private val bytes: ByteArray, private val bigEndian: Boolean = true) { private var position = 0 val remaining: Int get() = bytes.size - position + fun align4() { + position = (position + 3) and 3.inv() + } + + fun readU8(): Int { + requireBytes(1) + return bytes[position++].toInt() and 0xFF + } + fun readU16(): Int { requireBytes(2) - val value = ((bytes[position].toInt() and 0xFF) shl 8) or (bytes[position + 1].toInt() and 0xFF) + val value = if (bigEndian) { + ((bytes[position].toInt() and 0xFF) shl 8) or (bytes[position + 1].toInt() and 0xFF) + } else { + (bytes[position].toInt() and 0xFF) or ((bytes[position + 1].toInt() and 0xFF) shl 8) + } position += 2 return value } + fun readI16(): Int { + val value = readU16() + return if (value and 0x8000 != 0) value - 0x10000 else value + } + fun readU32(): Long { requireBytes(4) - val value = ((bytes[position].toLong() and 0xFF) shl 24) or - ((bytes[position + 1].toLong() and 0xFF) shl 16) or - ((bytes[position + 2].toLong() and 0xFF) shl 8) or - (bytes[position + 3].toLong() and 0xFF) + val value = if (bigEndian) { + ((bytes[position].toLong() and 0xFF) shl 24) or + ((bytes[position + 1].toLong() and 0xFF) shl 16) or + ((bytes[position + 2].toLong() and 0xFF) shl 8) or + (bytes[position + 3].toLong() and 0xFF) + } else { + (bytes[position].toLong() and 0xFF) or + ((bytes[position + 1].toLong() and 0xFF) shl 8) or + ((bytes[position + 2].toLong() and 0xFF) shl 16) or + ((bytes[position + 3].toLong() and 0xFF) shl 24) + } position += 4 return value } + fun readI32(): Int = readU32().toInt() + fun readI64(): Long { requireBytes(8) var value = 0L - repeat(8) { value = (value shl 8) or (bytes[position++].toLong() and 0xFF) } + if (bigEndian) { + repeat(8) { value = (value shl 8) or (bytes[position++].toLong() and 0xFF) } + } else { + for (i in 7 downTo 0) value = (value shl 8) or (bytes[position + i].toLong() and 0xFF) + position += 8 + } return value } @@ -625,7 +671,7 @@ object UnityBundleReader { return value } - private fun requireBytes(count: Int) { + internal fun requireBytes(count: Int) { if (count < 0 || count > remaining) throw UnityFormatException("UnityFS block table is truncated") } } diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt new file mode 100644 index 0000000..561e5bb --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt @@ -0,0 +1,108 @@ +package dev.cluvex.strata.core.unity + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream +import java.io.RandomAccessFile + +/** + * Parser for the legacy streamed Unity containers: UnityRaw (uncompressed) and UnityWeb (LZMA). + * + * Layout (big endian): signature, version, player version, engine version, [hash + crc when + * version >= 4], minimum streamed bytes, header size, level streaming knobs, the compressed + * directory+data block at [headerSize], then optional file size fields. The decompressed stream + * starts with the directory (node count, then name/offset/size triples) followed by the file + * data; node offsets are absolute file offsets with the stream mapped at [headerSize]. + */ +internal object UnityLegacyReader { + private const val MAX_STREAM_BYTES = 4L * 1024 * 1024 * 1024 + private const val MAX_LEVELS = 1024 + private const val MAX_NODES = 500_000 + private const val MAX_STRING_BYTES = 1024 * 1024 + private const val BUFFER_SIZE = 64 * 1024 + + fun parse(file: File, dataFile: File): UnityBundleSummary { + RandomAccessFile(file, "r").use { input -> + val signature = UnityBundleReader.readCString(input, 32) + if (signature != "UnityWeb" && signature != "UnityRaw") { + throw UnityFormatException("Unsupported legacy Unity container") + } + val version = UnityBundleReader.readU32(input) + if (version !in 1..9) throw UnityFormatException("Unsupported legacy Unity bundle version $version") + val playerVersion = UnityBundleReader.readCString(input, 4096) + val engineVersion = UnityBundleReader.readCString(input, 4096) + if (version >= 4) { + input.skipBytes(16) // bundle hash + UnityBundleReader.readU32(input) // crc + } + UnityBundleReader.readU32(input) // minimumStreamedBytes + val headerSize = UnityBundleReader.readU32(input) + UnityBundleReader.readU32(input) // numberOfLevelsToDownloadBeforeStreaming + val levelCount = input.readInt() + if (levelCount !in 1..MAX_LEVELS) throw UnityFormatException("Legacy Unity bundle has an invalid level count") + input.skipBytes(8 * (levelCount - 1)) + val compressedSize = UnityBundleReader.readU32(input) + val uncompressedSize = UnityBundleReader.readU32(input) + var completeFileSize = 0L + if (version >= 2) completeFileSize = UnityBundleReader.readU32(input) + if (version >= 3) UnityBundleReader.readU32(input) // fileInfoHeaderSize + if (headerSize < input.filePointer || headerSize > file.length()) { + throw UnityFormatException("Legacy Unity header size is invalid") + } + if (compressedSize > file.length() - headerSize) { + throw UnityFormatException("Legacy Unity data block is outside the file") + } + if (uncompressedSize > MAX_STREAM_BYTES) throw UnityFormatException("Legacy Unity stream is too large") + val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE + if (uncompressedSize > availableSpace) throw UnityFormatException("Not enough free space to stage Unity data") + input.seek(headerSize) + val compressed = ByteArray(compressedSize.toInt()) + input.readFully(compressed) + val stream = if (signature == "UnityWeb") { + decompressWeb(compressed, uncompressedSize) + } else { + if (compressedSize != uncompressedSize) throw UnityFormatException("UnityRaw block sizes disagree") + compressed + } + if (stream.size.toLong() != uncompressedSize) { + throw UnityFormatException("Legacy Unity stream has an unexpected size") + } + val table = UnityBundleReader.Cursor(stream) + val nodeCount = table.readI32() + if (nodeCount !in 0..MAX_NODES) throw UnityFormatException("Legacy Unity node count is invalid") + val entries = ArrayList(nodeCount) + repeat(nodeCount) { + val path = table.readCString(MAX_STRING_BYTES) + val offset = table.readU32() + val size = table.readU32() + val relative = offset - headerSize + if (relative < 0 || relative > stream.size || size > stream.size - relative) { + throw UnityFormatException("Legacy Unity entry is outside the stream") + } + entries += UnityBundleEntry(path, relative, size, 0) + } + dataFile.parentFile?.mkdirs() + FileOutputStream(dataFile).buffered(BUFFER_SIZE).use { out -> out.write(stream) } + val fileSize = if (completeFileSize > 0) completeFileSize else file.length() + return UnityBundleSummary( + signature, version.toInt(), playerVersion, engineVersion, + fileSize, stream.size.toLong(), levelCount, entries, + ) + } + } + + /** UnityWeb stores LZMA with a 5 byte property header plus a little endian uncompressed size. */ + private fun decompressWeb(compressed: ByteArray, expected: Long): ByteArray { + if (compressed.size < 13) throw UnityFormatException("Truncated UnityWeb LZMA header") + var declared = 0L + for (i in 7 downTo 0) declared = (declared shl 8) or (compressed[5 + i].toLong() and 0xFF) + if (declared != expected) throw UnityFormatException("UnityWeb LZMA size mismatch") + val properties = compressed.copyOfRange(0, 5) + val out = ByteArrayOutputStream(expected.coerceAtMost(1024 * 1024).toInt()) + val source = ByteArrayInputStream(compressed, 13, compressed.size - 13) + val written = UnityBundleReader.decompressLzmaRaw(source, expected, out, properties) + if (written != expected) throw UnityFormatException("UnityWeb LZMA stream has an unexpected size") + return out.toByteArray() + } +} diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt index ad0322d..6d7c40f 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt @@ -128,6 +128,12 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { fun repack(parents: List) { val doc = document ?: return + if (!doc.repackSupported) { + _state.update { + it.copy(message = getApplication().getString(R.string.unity_repack_unsupported)) + } + return + } val current = _state.value if (current.busy) return val changes = current.editedFiles + current.replacements diff --git a/app/src/main/res/values-fa/strings_unity.xml b/app/src/main/res/values-fa/strings_unity.xml index 26c069a..b0486cd 100644 --- a/app/src/main/res/values-fa/strings_unity.xml +++ b/app/src/main/res/values-fa/strings_unity.xml @@ -36,4 +36,5 @@ %1$d ورودی %1$d ورودی + این قالب فقط‌خواندنی است؛ بازبسته‌بندی تنها برای بسته‌های UnityFS پشتیبانی می‌شود. diff --git a/app/src/main/res/values-ru/strings_unity.xml b/app/src/main/res/values-ru/strings_unity.xml index d75ce7e..b327b26 100644 --- a/app/src/main/res/values-ru/strings_unity.xml +++ b/app/src/main/res/values-ru/strings_unity.xml @@ -38,4 +38,5 @@ %1$d записей %1$d записи + Этот формат доступен только для чтения: пересборка поддерживается лишь для UnityFS. diff --git a/app/src/main/res/values-zh-rCN/strings_unity.xml b/app/src/main/res/values-zh-rCN/strings_unity.xml index 64ea017..9f59fa6 100644 --- a/app/src/main/res/values-zh-rCN/strings_unity.xml +++ b/app/src/main/res/values-zh-rCN/strings_unity.xml @@ -35,4 +35,5 @@ %1$d 个条目 + 此格式为只读;仅 UnityFS 包支持重新打包。 diff --git a/app/src/main/res/values/strings_unity.xml b/app/src/main/res/values/strings_unity.xml index 33563af..8781e5d 100644 --- a/app/src/main/res/values/strings_unity.xml +++ b/app/src/main/res/values/strings_unity.xml @@ -36,4 +36,5 @@ %1$d entry %1$d entries + This format is read-only. Repacking is supported for UnityFS bundles only. diff --git a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt index b422e16..20fbb24 100644 --- a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt +++ b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt @@ -95,6 +95,63 @@ class UnityBundleReaderTest { } } + @Test + fun readsLegacyUnityRawBundle() { + val contents = "legacy unity payload".toByteArray() + val source = writeLegacy(temp.root, "legacy.raw", contents, web = false) + assertThat(UnityBundleReader.probe(source).kind).isEqualTo(UnityFileKind.UNITY_RAW) + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + assertThat(document.summary.entries.map { it.name }).containsExactly("assets/data.bin") + val extracted = File(temp.root, "legacy-out.bin") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + assertThat(document.repackSupported).isFalse() + assertThrows(java.io.IOException::class.java) { + document.repack(File(temp.root, "should-not-exist.bundle")) + } + } + } + + @Test + fun decompressesLegacyUnityWebBundle() { + val contents = "compressed legacy payload".toByteArray() + val source = writeLegacy(temp.root, "legacy.web", contents, web = true) + assertThat(UnityBundleReader.probe(source).kind).isEqualTo(UnityFileKind.UNITY_WEB) + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + val extracted = File(temp.root, "web-out.bin") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + } + } + + @Test + fun listsSerializedFileObjectsAndExtractsRawBytes() { + val source = writeSerialized(temp.root, "level.assets", version = 17) + assertThat(UnityBundleReader.probe(source).kind).isEqualTo(UnityFileKind.SERIALIZED_FILE) + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + assertThat(document.summary.entries.map { it.name }) + .containsExactly("#101 TextAsset", "#102 TextAsset") + .inOrder() + val first = File(temp.root, "object-1.bin") + val second = File(temp.root, "object-2.bin") + document.copyEntry(document.summary.entries[0], first) + document.copyEntry(document.summary.entries[1], second) + assertThat(first.readText()).isEqualTo("hello") + assertThat(second.readText()).isEqualTo("world") + assertThat(document.repackSupported).isFalse() + } + } + + @Test + fun refusesSerializedFileVersionOutsideSupportedRange() { + val source = writeSerialized(temp.root, "future.assets", version = 23) + assertThat(UnityBundleReader.probe(source).kind).isEqualTo(UnityFileKind.SERIALIZED_FILE) + val error = assertThrows(UnityFormatException::class.java) { + UnityBundleReader.open(source, File(temp.root, "cache")) + } + assertThat(error).hasMessageThat().contains("Unsupported serialized file version") + } + private fun writeBundle( root: File, name: String, @@ -152,4 +209,126 @@ class UnityBundleReaderTest { } return output } + + /** Legacy UnityRaw / UnityWeb container (big-endian header) with a single entry. */ + private fun writeLegacy(root: File, name: String, contents: ByteArray, web: Boolean): File { + val signature = if (web) "UnityWeb" else "UnityRaw" + fun header(headerSize: Int, compressedSize: Int, uncompressedSize: Int): ByteArray = + ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.write(signature.toByteArray(Charsets.UTF_8)) + out.writeByte(0) + out.writeInt(6) // format version + out.write("5.x.x".toByteArray(Charsets.UTF_8)); out.writeByte(0) + out.write("2019.4.0f1".toByteArray(Charsets.UTF_8)); out.writeByte(0) + out.write(ByteArray(16)); out.writeInt(0) // hash + crc (version >= 4) + out.writeInt(0) // minimum streamed bytes + out.writeInt(headerSize) + out.writeInt(0) // levels before streaming + out.writeInt(1) // level count + out.writeInt(compressedSize) + out.writeInt(uncompressedSize) + out.writeInt(headerSize + compressedSize) // complete file size (version >= 2) + out.writeInt(headerSize) // file info header size (version >= 3) + } + bytes.toByteArray() + } + val headerSize = header(0, 0, 0).size // Every field is fixed width. + val directory = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.writeInt(1) // node count + out.write("assets/data.bin".toByteArray(Charsets.UTF_8)) + out.writeByte(0) + out.writeInt(0) // absolute data offset, patched below + out.writeInt(contents.size) + } + bytes.toByteArray() + } + val dataOffset = headerSize + directory.size + directory[20] = (dataOffset ushr 24).toByte() + directory[21] = (dataOffset ushr 16).toByte() + directory[22] = (dataOffset ushr 8).toByte() + directory[23] = dataOffset.toByte() + val stream = directory + contents + val compressed = if (web) lzmaAlone(stream) else stream + val output = File(root, name) + FileOutputStream(output).use { it.write(header(headerSize, compressed.size, stream.size) + compressed) } + return output + } + + /** LZMA1 stream with the 13-byte "alone" prefix (props + dictionary + size), as Unity emits. */ + private fun lzmaAlone(payload: ByteArray): ByteArray { + val raw = ByteArrayOutputStream() + org.tukaani.xz.LZMAOutputStream(raw, org.tukaani.xz.LZMA2Options(), false).use { it.write(payload) } + val dictionary = 1 shl 23 // 8 MiB + val header = byteArrayOf(0x5D) + // lc = 3, lp = 0, pb = 2 + byteArrayOf( + dictionary.toByte(), + (dictionary ushr 8).toByte(), + (dictionary ushr 16).toByte(), + (dictionary ushr 24).toByte(), + ) + + ByteArray(8) { index -> ((payload.size.toLong() ushr (8 * index)) and 0xFF).toByte() } + return header + raw.toByteArray() + } + + /** Serialized file with a big-endian header, one TextAsset type and two small objects. */ + private fun writeSerialized(root: File, name: String, version: Int): File { + val metadata = ByteArrayOutputStream() + fun int(value: Long) = metadata.write( + byteArrayOf( + value.toByte(), + (value ushr 8).toByte(), + (value ushr 16).toByte(), + (value ushr 24).toByte(), + ), + ) + fun align() = metadata.write(ByteArray((4 - metadata.size() % 4) % 4)) + metadata.write("2021.3.0f1".toByteArray(Charsets.UTF_8)); metadata.write(0) // unity version + int(13) // build target (version >= 8) + metadata.write(1) // enable type tree (version >= 13) + int(1) // type count + int(49) // class id: TextAsset + metadata.write(0) // is stripped (version >= 16) + metadata.write(byteArrayOf(0xFF.toByte(), 0xFF.toByte())) // script type index (version >= 17) + metadata.write(ByteArray(16)) // old type hash (version >= 13) + int(1) // type tree blob: node count (version >= 12) + int(8) // string buffer size + metadata.write(ByteArray(24)) // one blob node (version < 19) + metadata.write(ByteArray(8)) // type tree strings + int(2) // object count + align() // object path ids are 4-byte aligned (version >= 14) + metadata.write(ByteArray(8) { index -> if (index == 0) 101 else 0 }) // path id 101 + int(0); int(5); int(0) // offset, size, type id + align() + metadata.write(ByteArray(8) { index -> if (index == 0) 102 else 0 }) // path id 102 + int(8); int(5); int(0) + val metadataBytes = metadata.toByteArray() + val headerSize = if (version >= 22) 48 else 20 + val dataOffset = (headerSize + metadataBytes.size + 15) / 16 * 16 + val data = ByteArray(16) + "hello".toByteArray(Charsets.UTF_8).copyInto(data, 0) + "world".toByteArray(Charsets.UTF_8).copyInto(data, 8) + val output = File(root, name) + FileOutputStream(output).use { stream -> + DataOutputStream(stream).use { out -> + out.writeInt(metadataBytes.size) // metadata size (header is big-endian) + out.writeInt(dataOffset + data.size) // file size + out.writeInt(version) + out.writeInt(dataOffset) + out.writeByte(0) // little-endian metadata + out.write(ByteArray(3)) // reserved + if (version >= 22) { + out.writeInt(metadataBytes.size) // 32-bit metadata size repeat + out.writeLong((dataOffset + data.size).toLong()) + out.writeLong(dataOffset.toLong()) + out.writeLong(0) // unknown + } + out.write(metadataBytes) + out.write(ByteArray(dataOffset - headerSize - metadataBytes.size)) + out.write(data) + } + } + return output + } } From 06578840562ab7f1f898d420d79541ee9c8d745b Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Sun, 18 Oct 2026 21:15:55 +0000 Subject: [PATCH 03/11] fix: support UnityFS format version 8 with aligned block tables - accept UnityFS format versions 6..8 (Unity 2022.3+ / Tuanjie bundles) - align the stream to 16 bytes after the header for format version 7+ (plus the known 2019.4.15+ version-6 quirk) before reading the block table, and use the aligned offset for the data section when the table sits at the end of the file - write the same alignment when repacking so version 7/8 output stays loadable by Unity and by the reader itself - treat flag 0x200 on pre-2020.3.34 / 2021.3.2 / 2022.1.1 engines as UnityCN encryption and fail with a clear message instead of misreading it as block-table padding - tests: version 8 with padding flag and LZ4HC info/blocks, version 8 repack round-trip, version 7 without padding, legacy encryption flag Verified end to end against a real UnityFS v8 bundle (Unity 2022.3.62f2, 12 LZ4HC blocks) containing a version 22 serialized file with 28 objects. --- .../strata/core/unity/UnityBundleReader.kt | 58 +++++++- .../core/unity/UnityBundleReaderTest.kt | 138 ++++++++++++++++++ 2 files changed, 190 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt index eb6dcd8..f4804ba 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt @@ -211,7 +211,15 @@ class UnityBundleDocument internal constructor( bytes.toByteArray() } val headerSize = headerPrefix.size + 8 + 4 + 4 + 4 - val totalSize = checkedAdd(checkedAdd(headerSize.toLong(), blockInfo.size.toLong(), "UnityFS is too large"), dataSize, "UnityFS is too large") + // UnityFS format version 7 and later align the block table to a 16-byte boundary, + // matching the quirk that some 2019.4.15+ games align version 6 bundles as well. + val alignmentPadding = + if (original.formatVersion >= 7 || UnityBundleReader.usesLegacyBlockAlignment(original.engineVersion)) { + (16 - headerSize % 16) % 16 + } else { + 0 + } + val totalSize = checkedAdd(checkedAdd((headerSize + alignmentPadding).toLong(), blockInfo.size.toLong(), "UnityFS is too large"), dataSize, "UnityFS is too large") try { FileOutputStream(output).buffered(BUFFER_SIZE).use { fileOut -> DataOutputStream(fileOut).use { out -> @@ -220,6 +228,7 @@ class UnityBundleDocument internal constructor( out.writeInt(blockInfo.size) out.writeInt(blockInfo.size) out.writeInt(BLOCK_INFO_AT_START) + if (alignmentPadding > 0) out.write(ByteArray(alignmentPadding)) out.write(blockInfo) FileInputStream(data).buffered().use { it.copyTo(out, BUFFER_SIZE) } } @@ -355,7 +364,7 @@ object UnityBundleReader { throw UnityFormatException("Unsupported Unity format${detail}") } val versionLong = readU32(input) - if (versionLong !in 6L..7L) throw UnityFormatException("Unsupported UnityFS format version $versionLong") + if (versionLong !in 6L..8L) throw UnityFormatException("Unsupported UnityFS format version $versionLong") val formatVersion = versionLong.toInt() val playerVersion = readCString(input, 4096) val engineVersion = readCString(input, 4096) @@ -364,14 +373,22 @@ object UnityBundleReader { val uncompressedInfoSize = readU32(input) val flags = readU32(input) val headerEnd = input.filePointer - if (bundleSize < headerEnd || bundleSize > file.length() || bundleSize <= 0) throw UnityFormatException("UnityFS bundle size is invalid") + if (flags and FLAG_BLOCK_INFO_NEEDS_PADDING != 0L && usesOldArchiveFlags(engineVersion)) { + // Engines before the alignment fix used 0x200 for UnityCN encryption instead of padding. + throw UnityFormatException("UnityCN-encrypted bundles are not supported") + } + // UnityFS format version 7 and later align the stream to 16 bytes right after the header. + // Quirk: some 2019.4.15+ games write format version 6 with the aligned layout as well. + val aligned = formatVersion >= 7 || usesLegacyBlockAlignment(engineVersion) + val alignedHeaderEnd = if (aligned) align16(headerEnd.toLong()) else headerEnd.toLong() + if (bundleSize < alignedHeaderEnd || bundleSize > file.length() || bundleSize <= 0) throw UnityFormatException("UnityFS bundle size is invalid") if (compressedInfoSize > MAX_INFO_BYTES || uncompressedInfoSize > MAX_INFO_BYTES || compressedInfoSize > Int.MAX_VALUE || uncompressedInfoSize > Int.MAX_VALUE) { throw UnityFormatException("UnityFS block table is too large") } if (compressedInfoSize > bundleSize) throw UnityFormatException("UnityFS block table is outside the file") val infoAtEnd = flags and FLAG_BLOCK_INFO_AT_END != 0L - val infoOffset = if (infoAtEnd) bundleSize - compressedInfoSize else headerEnd - if (infoOffset < headerEnd || infoOffset + compressedInfoSize > bundleSize) throw UnityFormatException("UnityFS block table offset is invalid") + val infoOffset = if (infoAtEnd) bundleSize - compressedInfoSize else alignedHeaderEnd + if (infoOffset < alignedHeaderEnd || infoOffset + compressedInfoSize > bundleSize) throw UnityFormatException("UnityFS block table offset is invalid") input.seek(infoOffset) val compressedInfo = ByteArray(compressedInfoSize.toInt()) input.readFully(compressedInfo) @@ -410,7 +427,7 @@ object UnityBundleReader { nodes += UnityBundleEntry(path, offset, size, nodeFlags) } if (table.remaining > 16) throw UnityFormatException("UnityFS block table contains unexpected trailing data") - val dataOffset = if (infoAtEnd) headerEnd else { + val dataOffset = if (infoAtEnd) alignedHeaderEnd else { val afterInfo = infoOffset + compressedInfoSize if (flags and FLAG_BLOCK_INFO_NEEDS_PADDING != 0L) align16(afterInfo) else afterInfo } @@ -575,6 +592,35 @@ object UnityBundleReader { private fun align16(value: Long): Long = (value + 15L) and -16L + /** + * Engines older than 2020.3.34 / 2021.3.2 / 2022.1.1 used archive flag 0x200 for UnityCN + * encryption; newer engines reuse the same bit for block-info start padding. + */ + private fun usesOldArchiveFlags(engineVersion: String): Boolean { + val parts = parseEngineVersion(engineVersion) ?: return false + val (major, minor, patch) = parts + return when { + major < 2020 -> true + major == 2020 -> minor < 3 || (minor == 3 && patch < 34) + major == 2021 -> minor < 3 || (minor == 3 && patch < 2) + major == 2022 -> minor < 1 + else -> false + } + } + + /** Quirk: some 2019.4.15+ games write format version 6 bundles with the aligned (version 7) layout. */ + internal fun usesLegacyBlockAlignment(engineVersion: String): Boolean { + val parts = parseEngineVersion(engineVersion) ?: return false + val (major, minor, patch) = parts + return major == 2019 && (minor > 4 || (minor == 4 && patch >= 15)) + } + + private fun parseEngineVersion(engineVersion: String): Triple? { + val parts = Regex("\\d+").findAll(engineVersion).mapNotNull { it.value.toIntOrNull() }.toList() + if (parts.isEmpty()) return null + return Triple(parts[0], parts.getOrElse(1) { 0 }, parts.getOrElse(2) { 0 }) + } + internal fun readCString(input: RandomAccessFile, max: Int): String { val bytes = ByteArrayOutputStream() while (bytes.size() < max) { diff --git a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt index 20fbb24..5788004 100644 --- a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt +++ b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt @@ -152,6 +152,67 @@ class UnityBundleReaderTest { assertThat(error).hasMessageThat().contains("Unsupported serialized file version") } + @Test + fun readsVersion8BundleWithPaddingFlagAndLz4hcBlocks() { + val contents = ByteArray(70_000) { (it % 251).toByte() } + val source = writeAlignedBundle(temp.root, "v8.bundle", contents, formatVersion = 8, paddingFlag = true, lz4 = true) + val probe = UnityBundleReader.probe(source) + assertThat(probe.kind).isEqualTo(UnityFileKind.UNITY_FS) + assertThat(probe.fileVersion).isEqualTo(8) + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + assertThat(document.summary.entries.map { it.name }).containsExactly("assets/data.bin") + val extracted = File(temp.root, "v8-out.bin") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + assertThat(document.repackSupported).isTrue() + } + } + + @Test + fun repacksVersion8BundleIntoAlignedLayout() { + val contents = ByteArray(40_000) { (it % 199).toByte() } + val source = writeAlignedBundle(temp.root, "v8.bundle", contents, formatVersion = 8, paddingFlag = true, lz4 = true) + val replacement = File(temp.root, "replacement.bin").apply { writeText("updated-v8") } + val output = File(temp.root, "rebuilt-v8.bundle") + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + document.repack(output, mapOf("assets/data.bin" to replacement)) + } + UnityBundleReader.open(output, File(temp.root, "cache")).use { rebuilt -> + assertThat(rebuilt.summary.formatVersion).isEqualTo(8) + val result = File(temp.root, "rebuilt-entry.bin") + rebuilt.copyEntry(rebuilt.summary.entries.single(), result) + assertThat(result.readText()).isEqualTo("updated-v8") + } + } + + @Test + fun readsVersion7BundleWithoutPaddingFlag() { + val contents = "aligned but uncompressed".toByteArray() + val source = writeAlignedBundle(temp.root, "v7.bundle", contents, formatVersion = 7, paddingFlag = false, lz4 = false) + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + val extracted = File(temp.root, "v7-out.bin") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + } + } + + @Test + fun rejectsLegacyEngineEncryptionFlag() { + val source = writeAlignedBundle( + temp.root, + "encrypted.bundle", + "payload".toByteArray(), + formatVersion = 6, + paddingFlag = true, + lz4 = false, + engineVersion = "2019.4.10f1", + ) + val error = assertThrows(UnityFormatException::class.java) { + UnityBundleReader.open(source, File(temp.root, "cache")) + } + assertThat(error).hasMessageThat().contains("encrypted") + } + private fun writeBundle( root: File, name: String, @@ -331,4 +392,81 @@ class UnityBundleReaderTest { } return output } + + /** Aligned UnityFS container (format version 6..8) mirroring what Unity 2019.4.15+ writes. */ + private fun writeAlignedBundle( + root: File, + name: String, + contents: ByteArray, + formatVersion: Int, + paddingFlag: Boolean, + lz4: Boolean, + engineVersion: String = "2022.3.62f2", + ): File { + val blockFlags = if (lz4) 3 else 0 + val blockPayload = if (lz4) lz4LiteralRun(contents) else contents + val info = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.write(MessageDigest.getInstance("MD5").digest(contents)) + out.writeInt(1) + out.writeInt(contents.size) + out.writeInt(blockPayload.size) + out.writeShort(blockFlags) + out.writeInt(1) + out.writeLong(0) + out.writeLong(contents.size.toLong()) + out.writeInt(4) + out.write("assets/data.bin".toByteArray(Charsets.UTF_8)) + out.writeByte(0) + } + bytes.toByteArray() + } + val infoPayload = if (lz4) lz4LiteralRun(info) else info + val infoFlags = 0x40 or (if (paddingFlag) 0x200 else 0) or blockFlags + val headerPrefix = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.write("UnityFS".toByteArray(Charsets.UTF_8)) + out.writeByte(0) + out.writeInt(formatVersion) + out.write("5.x.x".toByteArray(Charsets.UTF_8)) + out.writeByte(0) + out.write(engineVersion.toByteArray(Charsets.UTF_8)) + out.writeByte(0) + } + bytes.toByteArray() + } + val headerSize = headerPrefix.size + 8 + 4 + 4 + 4 + val padding = if (formatVersion >= 7) (16 - headerSize % 16) % 16 else 0 + val dataPadding = if (paddingFlag) (16 - (headerSize + padding + infoPayload.size) % 16) % 16 else 0 + val total = headerSize + padding + infoPayload.size + dataPadding + blockPayload.size + val output = File(root, name) + FileOutputStream(output).use { stream -> + DataOutputStream(stream).use { out -> + out.write(headerPrefix) + out.writeLong(total.toLong()) + out.writeInt(infoPayload.size) + out.writeInt(info.size) + out.writeInt(infoFlags) + out.write(ByteArray(padding)) + out.write(infoPayload) + out.write(ByteArray(dataPadding)) + out.write(blockPayload) + } + } + return output + } + + /** Valid LZ4 block made of a single literal run (no matches), like an incompressible payload. */ + private fun lz4LiteralRun(payload: ByteArray): ByteArray { + val out = ByteArrayOutputStream() + val run = payload.size + out.write(if (run >= 15) 0xF0 else run shl 4) + var remaining = run - 15 + while (remaining >= 0) { + out.write(minOf(remaining, 255)) + remaining -= 255 + } + out.write(payload) + return out.toByteArray() + } } From 500fb1b7c8aad56156e193eb02305aa54b8d04f1 Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Sun, 18 Oct 2026 21:52:11 +0000 Subject: [PATCH 04/11] feat: decode type trees so game texts can be found and edited - TypeTreeCodec: generic Unity type-tree decoder/encoder (blob and legacy layouts, common-string table, alignment semantics mirrored from the reference implementation) plus a flat path->string JSON bridge and a minimal dependency-free JSON reader/writer - SerializedFileReader keeps parsed type trees and object-table field positions; the new SerializedFileIndex decodes objects, re-encodes edited values and rebuilds the file with replaced objects (metadata patched in place, self-check by reparse) - UnityBundleDocument: serialized files are now repackable; new textInfo / exportTexts / rebuildTexts APIs - UI: per-object text badge (string count + object name), an Edit texts action that exports every string as JSON and opens it in the text editor; repack automatically re-applies modified JSON exports - localized strings for en/fa/ru/zh - tests: typed object decode, edited-text rebuild, raw replacement rebuild, JSON round-trip; suite is now 16 tests Verified end to end on a real UnityFS v8 bundle with I2 Localization game data: all 28 objects decode->encode byte-identical, 4388 subtitle strings exported and matched against UnityPy, and the full edit -> object rebuild -> file rebuild -> bundle repack round-trip was cross-validated by re-reading the outputs with UnityPy. --- .../strata/core/unity/SerializedFileReader.kt | 289 ++++++- .../cluvex/strata/core/unity/TypeTreeCodec.kt | 718 ++++++++++++++++++ .../strata/core/unity/UnityBundleReader.kt | 59 +- .../strata/feature/unity/UnityAssetScreen.kt | 32 +- .../feature/unity/UnityAssetViewModel.kt | 91 ++- app/src/main/res/values-fa/strings_unity.xml | 4 + app/src/main/res/values-ru/strings_unity.xml | 4 + .../main/res/values-zh-rCN/strings_unity.xml | 4 + app/src/main/res/values/strings_unity.xml | 4 + .../core/unity/UnityBundleReaderTest.kt | 215 +++++- 10 files changed, 1382 insertions(+), 38 deletions(-) create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt index fdf6408..8b7fe54 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt @@ -2,6 +2,7 @@ package dev.cluvex.strata.core.unity import java.io.File import java.io.FileOutputStream +import java.io.IOException import java.io.RandomAccessFile /** @@ -11,15 +12,19 @@ import java.io.RandomAccessFile * The metadata section (type table + object table) is parsed with the file's own endianness; * object data offsets are relative to the header's data offset. Format versions 9..22 are * supported; the Unity 2023+ (v23) shared type-tree layout is rejected with a clear error. + * + * When the file stores type trees, objects can also be decoded into editable values through + * [SerializedFileIndex], which additionally supports rebuilding the file with replaced objects. */ internal object SerializedFileReader { private const val MAX_OBJECTS = 2_000_000 private const val MAX_TYPES = 100_000 private const val MAX_TREE_NODES = 4_000_000 private const val MAX_STRING_BYTES = 1024 * 1024 + private const val MAX_DECODE_BYTES = 256 * 1024 * 1024 private const val BUFFER_SIZE = 64 * 1024 - fun parse(file: File, dataFile: File): UnityBundleSummary { + fun parse(file: File, dataFile: File): Pair { RandomAccessFile(file, "r").use { input -> UnityBundleReader.readU32(input) // metadata size (32 bit, unused for v9+) val fileSize32 = UnityBundleReader.readU32(input) @@ -45,6 +50,7 @@ internal object SerializedFileReader { input.seek(headerSize) input.readFully(metadata) val table = UnityBundleReader.Cursor(metadata, bigEndian) + fun pos(): Int = metadata.size - table.remaining var unityVersion = "" if (version >= 7) unityVersion = table.readCString(256) @@ -54,6 +60,7 @@ internal object SerializedFileReader { val typeCount = table.readI32() if (typeCount !in 0..MAX_TYPES) throw UnityFormatException("Serialized type count is invalid") val classIds = ArrayList(typeCount) + val trees = ArrayList(typeCount) repeat(typeCount) { val classId = table.readI32() if (version >= 16) table.readU8() // is stripped @@ -62,13 +69,14 @@ internal object SerializedFileReader { if ((version < 16 && classId < 0) || (version >= 16 && classId == 114)) table.readBytes(16) table.readBytes(16) // old type hash } - if (enableTypeTree) skipTypeTree(table, version) + val tree = if (enableTypeTree) readTypeTree(table, version) else null if (version >= 21) { val deps = table.readI32() if (deps !in 0..MAX_TYPES) throw UnityFormatException("Serialized type dependencies are invalid") table.readBytes(deps * 4) } classIds += classId + trees += tree } var bigId = false @@ -78,6 +86,7 @@ internal object SerializedFileReader { if (objectCount !in 0..MAX_OBJECTS) throw UnityFormatException("Serialized object count is invalid") val dataSize = fileSize - dataOffset val entries = ArrayList(objectCount) + val slots = ArrayList(objectCount) repeat(objectCount) { val pathId = when { bigId -> table.readI64() @@ -87,7 +96,10 @@ internal object SerializedFileReader { table.readI64() } } - val start = if (version >= 22) table.readI64() else table.readU32() + val startIsI64 = version >= 22 + val startFieldPos = pos() + val start = if (startIsI64) table.readI64() else table.readU32() + val sizeFieldPos = pos() val size = table.readU32() val typeId = table.readI32() val classId = if (version < 16) table.readU16() else classIds.getOrElse(typeId) { -1 } @@ -97,7 +109,9 @@ internal object SerializedFileReader { if (start < 0 || start > dataSize || size > dataSize - start) { throw UnityFormatException("Serialized object is outside the data section") } - entries += UnityBundleEntry("#$pathId ${className(classId)}", start, size, 0) + val name = "#$pathId ${className(classId)}" + entries += UnityBundleEntry(name, start, size, 0) + slots += SerializedFileIndex.Slot(pathId, typeId, classId, start, size, startFieldPos, startIsI64, sizeFieldPos, name) } val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE @@ -105,45 +119,70 @@ internal object SerializedFileReader { dataFile.parentFile?.mkdirs() input.seek(dataOffset) FileOutputStream(dataFile).buffered(BUFFER_SIZE).use { out -> copyExactly(input, out, dataSize) } - return UnityBundleSummary( + val summary = UnityBundleSummary( "SerializedFile", version.toInt(), "", unityVersion, fileSize, dataSize, 0, entries, ) + val index = SerializedFileIndex( + source = file, + version = version, + bigEndian = bigEndian, + headerSize = headerSize.toInt(), + dataOffset = dataOffset, + metadataBytes = metadata, + slots = slots, + trees = trees, + ) + return summary to index } } - private fun skipTypeTree(table: UnityBundleReader.Cursor, version: Long) { + private fun readTypeTree(table: UnityBundleReader.Cursor, version: Long): TypeTree { if (version >= 23) { throw UnityFormatException("Serialized file uses the Unity 2023+ shared type-tree layout, which is not supported yet") } - if (version >= 12 || version == 10L) { + return if (version >= 12 || version == 10L) { val nodes = table.readI32() val strings = table.readI32() - if (nodes !in 0..MAX_TREE_NODES || strings !in 0..MAX_STRING_BYTES) { + if (nodes !in 1..MAX_TREE_NODES || strings !in 0..MAX_STRING_BYTES) { throw UnityFormatException("Serialized type tree is invalid") } - val nodeSize = if (version >= 19) 32 else 24 - table.readBytes(nodes * nodeSize) - table.readBytes(strings) + val blobNodes = ArrayList(nodes) + repeat(nodes) { + val nodeVersion = table.readU16() + val level = table.readU8() + table.readU8() // type flags + val typeOffset = table.readI32() + val nameOffset = table.readI32() + val byteSize = table.readI32() + table.readI32() // index + val metaFlag = table.readI32() + if (version >= 19) table.readBytes(8) // ref type hash + blobNodes += TypeTreeCodec.BlobNode(nodeVersion, level, typeOffset, nameOffset, byteSize, metaFlag) + } + val stringBytes = table.readBytes(strings) + TypeTreeCodec.treeFromBlob(blobNodes, stringBytes) } else { - skipTypeNodes(table, 0) + TypeTree(TypeTreeCodec.treeFromLegacy(table)) } } - private fun skipTypeNodes(table: UnityBundleReader.Cursor, depth: Int) { - if (depth > 96) throw UnityFormatException("Serialized type tree is too deep") - table.readCString(MAX_STRING_BYTES) // type - table.readCString(MAX_STRING_BYTES) // name - table.readI32() // byte size - table.readI32() // index - table.readI32() // flags - table.readI32() // version - table.readI32() // meta flag - val children = table.readI32() - if (children !in 0..100_000) throw UnityFormatException("Serialized type tree is invalid") - repeat(children) { skipTypeNodes(table, depth + 1) } + private fun copyExactly(input: RandomAccessFile, out: FileOutputStream, length: Long): Long { + val buffer = ByteArray(BUFFER_SIZE) + var left = length + var total = 0L + while (left > 0) { + val read = input.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()) + if (read < 0) throw UnityFormatException("Serialized file is truncated") + out.write(buffer, 0, read) + left -= read + total += read + } + return total } + internal fun className(classId: Int): String = CLASS_NAMES[classId] ?: "Class$classId" + private val CLASS_NAMES = mapOf( 1 to "GameObject", 2 to "Component", 4 to "Transform", 8 to "Behaviour", 11 to "AudioManager", 13 to "InputManager", 20 to "Camera", 21 to "Material", @@ -155,6 +194,206 @@ internal object SerializedFileReader { 213 to "Sprite", 222 to "CanvasRenderer", 223 to "Canvas", 224 to "RectTransform", 329 to "VideoClip", ) +} + +/** + * Everything needed to decode, re-encode and rebuild a parsed serialized file. Object table + * field positions are recorded during parsing so a rebuild only patches offsets/sizes in place: + * the metadata length (and therefore the data offset) never changes. + */ +internal class SerializedFileIndex( + val source: File, + val version: Long, + val bigEndian: Boolean, + val headerSize: Int, + val dataOffset: Long, + val metadataBytes: ByteArray, + val slots: List, + val trees: List, +) { + internal class Slot( + val pathId: Long, + val typeIndex: Int, + val classId: Int, + val start: Long, + val size: Long, + val startFieldPos: Int, + val startIsI64: Boolean, + val sizeFieldPos: Int, + val entryName: String, + ) + + private val slotsByName: Map = slots.associateBy { it.entryName } + + fun slotFor(entry: UnityBundleEntry): Slot? = slotsByName[entry.name] + + fun hasTreeFor(entry: UnityBundleEntry): Boolean { + val slot = slotFor(entry) ?: return false + return trees.getOrNull(slot.typeIndex) != null || slot.classId == 49 + } + + fun readObjectBytes(dataFile: File, slot: Slot): ByteArray { + if (slot.size > MAX_DECODE_BYTES) throw UnityFormatException("Serialized object is too large to decode") + val bytes = ByteArray(slot.size.toInt()) + RandomAccessFile(dataFile, "r").use { input -> + input.seek(slot.start) + input.readFully(bytes) + } + return bytes + } + + /** Decodes an object into an editable value tree; null when it cannot be decoded safely. */ + fun decode(dataFile: File, entry: UnityBundleEntry): UVal? { + val slot = slotFor(entry) ?: return null + return try { + val bytes = readObjectBytes(dataFile, slot) + val tree = trees.getOrNull(slot.typeIndex) + if (tree != null) { + val (value, consumed) = TypeTreeCodec.decodeChecked(tree, bytes, bigEndian) + if (consumed != bytes.size) null else value + } else if (slot.classId == 49) { + TypeTreeCodec.decodeTextAsset(bytes, bigEndian)?.let { (name, script) -> + UVal.Struct( + linkedMapOf( + "m_Name" to UVal.Str(name), + "m_Script" to UVal.Bytes(script), + ), + ) + } + } else { + null + } + } catch (e: Exception) { + null + } + } + + /** Re-encodes a (possibly edited) value tree back into raw object bytes. */ + fun encode(dataFile: File, entry: UnityBundleEntry, value: UVal): ByteArray { + val slot = slotFor(entry) ?: throw UnityFormatException("Entry does not belong to this serialized file") + val tree = trees.getOrNull(slot.typeIndex) + return if (tree != null) { + TypeTreeCodec.encode(tree, value, bigEndian) + } else if (slot.classId == 49 && value is UVal.Struct) { + val name = (value.fields["m_Name"] as? UVal.Str)?.value + val script = (value.fields["m_Script"] as? UVal.Bytes)?.data + if (name == null || script == null) throw UnityFormatException("TextAsset value is incomplete") + TypeTreeCodec.encodeTextAsset(name, script, bigEndian) + } else { + throw UnityFormatException("This object has no type tree and cannot be re-encoded") + } + } + + fun objectName(value: UVal): String? = + (value as? UVal.Struct)?.fields?.get("m_Name")?.let { (it as? UVal.Str)?.value } + + /** + * Writes a new serialized file where entries listed in [replacements] use the replacement + * file's bytes. Objects are written sequentially in table order; the object table is patched + * in place (fixed width fields) so metadata size and data offset stay valid. + */ + fun rebuild(output: File, dataFile: File, replacements: Map, entries: List) { + if (entries.size != slots.size) throw IOException("Entry list does not match this serialized file") + val unknown = replacements.keys - slotsByName.keys + if (unknown.isNotEmpty()) throw IOException("Replacement entry is not in this serialized file: ${unknown.first()}") + val parent = output.parentFile ?: throw IOException("Output directory is missing") + parent.mkdirs() + + val newStarts = LongArray(slots.size) + val newSizes = LongArray(slots.size) + var cursor = 0L + slots.forEachIndexed { index, slot -> + val replacement = replacements[slot.entryName] + if (replacement != null && !replacement.isFile) throw IOException("Replacement file is missing: ${replacement.name}") + newStarts[index] = cursor + newSizes[index] = replacement?.length() ?: slot.size + cursor += newSizes[index] + if (cursor < 0) throw IOException("Serialized data is too large") + } + val newDataSize = cursor + val space = parent.usableSpace + if (space != 0L && newDataSize > space) throw IOException("Not enough free space to rebuild the serialized file") + + val metadata = metadataBytes.copyOf() + slots.forEachIndexed { index, slot -> + if (newStarts[index] != slot.start) writeField(metadata, slot.startFieldPos, newStarts[index], if (slot.startIsI64) 8 else 4) + if (newSizes[index] != slot.size) writeField(metadata, slot.sizeFieldPos, newSizes[index], 4) + } + val newFileSize = dataOffset + newDataSize + + if (!output.createNewFile()) throw IOException("Output already exists: ${output.name}") + try { + val header = ByteArray(headerSize) + RandomAccessFile(source, "r").use { it.readFully(header) } + if (version >= 22) { + writeField(header, 24, newFileSize, 8, bigEndian = true) + } else { + writeField(header, 4, newFileSize, 4, bigEndian = true) + } + FileOutputStream(output).buffered(64 * 1024).use { out -> + out.write(header) + out.write(metadata) + val padding = dataOffset - headerSize - metadata.size + if (padding > 0) out.write(ByteArray(padding.toInt())) + RandomAccessFile(dataFile, "r").use { staged -> + val buffer = ByteArray(64 * 1024) + slots.forEachIndexed { index, slot -> + val replacement = replacements[slot.entryName] + if (replacement != null) { + replacement.inputStream().buffered().use { input -> + var left = newSizes[index] + while (left > 0) { + val read = input.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()) + if (read < 0) throw IOException("Replacement changed while it was being read") + out.write(buffer, 0, read) + left -= read + } + } + } else { + staged.seek(slot.start) + var left = slot.size + while (left > 0) { + val read = staged.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()) + if (read < 0) throw UnityFormatException("Staged serialized data is truncated") + out.write(buffer, 0, read) + left -= read + } + } + } + } + } + } catch (e: Throwable) { + output.delete() + throw e + } + + // Self-check: the rebuilt file must parse and expose the expected object sizes. + val verifyData = File(parent, ".${output.name}.${System.nanoTime()}.verify") + try { + val (summary, _) = SerializedFileReader.parse(output, verifyData) + if (summary.entries.size != slots.size) throw IOException("Rebuilt serialized file has a wrong object count") + summary.entries.forEachIndexed { index, entry -> + if (entry.size != newSizes[index]) throw IOException("Rebuilt serialized file has a wrong object size") + } + } catch (e: Throwable) { + output.delete() + throw e + } finally { + verifyData.delete() + } + } + + private fun writeField(bytes: ByteArray, pos: Int, value: Long, width: Int, bigEndian: Boolean = this.bigEndian) { + if (pos < 0 || pos + width > bytes.size) throw IOException("Serialized metadata patch is out of bounds") + if (width == 4 && (value < 0 || value > 0xFFFFFFFFL)) throw IOException("Serialized object is too large for its 32-bit field") + if (bigEndian) { + for (i in width - 1 downTo 0) bytes[pos + (width - 1 - i)] = ((value ushr (8 * i)) and 0xFF).toByte() + } else { + for (i in 0 until width) bytes[pos + i] = ((value ushr (8 * i)) and 0xFF).toByte() + } + } - private fun className(classId: Int): String = CLASS_NAMES[classId] ?: "Class$classId" + companion object { + private const val MAX_DECODE_BYTES = 256 * 1024 * 1024 + } } diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt b/app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt new file mode 100644 index 0000000..c5501c4 --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt @@ -0,0 +1,718 @@ +package dev.cluvex.strata.core.unity + +import java.io.ByteArrayOutputStream + +/** + * Decoder/encoder for Unity type trees (blob and legacy layouts). + * + * Objects of any class can be decoded into [UVal] trees when the serialized file stores type + * trees, which is the common case for asset bundles. The codec mirrors the reference semantics + * (UnityPy TypeTreeHelper): primitive widths by type name, aligned strings, Array/vector/map/pair + * handling, per-node 0x4000 alignment flags and the array-level alignment propagation quirk. + */ +internal class TTNode( + val version: Int, + val type: String, + val name: String, + val byteSize: Int, + val metaFlag: Int, + val children: MutableList = ArrayList(), +) { + val aligns: Boolean get() = metaFlag and ALIGN_FLAG != 0 + + companion object { + const val ALIGN_FLAG = 0x4000 + } +} + +internal class TypeTree(val root: TTNode) + +/** Decoded type-tree value. Preserves exact widths so unedited data re-encodes bit-identically. */ +internal sealed interface UVal { + class Struct(val fields: LinkedHashMap) : UVal + class Arr(val items: ArrayList) : UVal + class Str(var value: String) : UVal + class Num(val value: Long, val width: Int) : UVal + class Flt(val value: Double, val single: Boolean) : UVal + class Bool(val raw: Int) : UVal + class Bytes(val data: ByteArray) : UVal +} + +internal object TypeTreeCodec { + private const val MAX_STRING_BYTES = 8 * 1024 * 1024 + private const val MAX_DATA_BYTES = 256 * 1024 * 1024 + private const val MAX_ELEMENTS = 4_000_000 + + private val PRIMITIVE_WIDTHS = mapOf( + "SInt8" to 1, "UInt8" to 1, "char" to 1, + "short" to 2, "SInt16" to 2, "unsigned short" to 2, "UInt16" to 2, + "int" to 4, "SInt32" to 4, "unsigned int" to 4, "UInt32" to 4, "Type*" to 4, + "long long" to 8, "SInt64" to 8, "unsigned long long" to 8, "UInt64" to 8, "FileSize" to 8, + ) + + // ---------------------------------------------------------------- reading + + private class TTReader(val data: ByteArray, val bigEndian: Boolean) { + var pos = 0 + + fun require(n: Int) { + if (n < 0 || pos > data.size - n) throw UnityFormatException("Type tree read is out of bounds") + } + + fun readU8(): Int { + require(1) + return data[pos++].toInt() and 0xFF + } + + fun readRaw(width: Int): Long { + require(width) + var v = 0L + if (bigEndian) { + for (i in 0 until width) v = (v shl 8) or (data[pos + i].toLong() and 0xFF) + } else { + for (i in width - 1 downTo 0) v = (v shl 8) or (data[pos + i].toLong() and 0xFF) + } + pos += width + return v + } + + fun readI32(): Int = readRaw(4).toInt() + + fun readFloat(): Float = Float.fromBits(readRaw(4).toInt()) + + fun readDouble(): Double = Double.fromBits(readRaw(8)) + + fun readAlignedString(): String { + val size = readI32() + if (size < 0 || size > MAX_STRING_BYTES) throw UnityFormatException("Type tree string is too large") + val bytes = readBytes(size) + align4() + return bytes.toString(Charsets.UTF_8) + } + + fun readByteArray(): ByteArray { + val size = readI32() + if (size < 0 || size > MAX_DATA_BYTES) throw UnityFormatException("Type tree byte array is too large") + return readBytes(size) + } + + fun readBytes(n: Int): ByteArray { + require(n) + val out = data.copyOfRange(pos, pos + n) + pos += n + return out + } + + fun align4() { + val rem = pos and 3 + if (rem != 0) { + require(4 - rem) + pos += 4 - rem + } + } + } + + fun decode(tree: TypeTree, data: ByteArray, bigEndian: Boolean): UVal { + val reader = TTReader(data, bigEndian) + return readValue(tree.root, reader) + } + + /** Bytes consumed by the last [decode] call's reader; used for size validation. */ + fun decodeChecked(tree: TypeTree, data: ByteArray, bigEndian: Boolean): Pair { + val reader = TTReader(data, bigEndian) + val value = readValue(tree.root, reader) + return value to reader.pos + } + + private fun readValue(node: TTNode, reader: TTReader): UVal { + var align = node.aligns + val value: UVal + val width = PRIMITIVE_WIDTHS[node.type] + when { + node.type == "string" -> value = UVal.Str(reader.readAlignedString()) + node.type == "TypelessData" -> value = UVal.Bytes(reader.readByteArray()) + node.type == "bool" -> value = UVal.Bool(reader.readU8()) + node.type == "float" -> value = UVal.Flt(reader.readFloat().toDouble(), true) + node.type == "double" -> value = UVal.Flt(reader.readDouble(), false) + width != null -> value = UVal.Num(reader.readRaw(width), width) + node.type == "pair" -> { + if (node.children.size < 2) throw UnityFormatException("Type tree pair node is malformed") + val fields = LinkedHashMap(2) + fields.put(unique(fields, node.children[0].name), readValue(node.children[0], reader)) + fields.put(unique(fields, node.children[1].name), readValue(node.children[1], reader)) + value = UVal.Struct(fields) + } + node.children.isNotEmpty() && node.children[0].type == "Array" -> { + val array = node.children[0] + if (array.aligns) align = true + val size = reader.readI32() + if (size < 0 || size > MAX_ELEMENTS) throw UnityFormatException("Type tree array is too large") + val subtype = array.children.getOrElse(1) { throw UnityFormatException("Type tree array is malformed") } + value = if (subtype.aligns) { + readValueArray(subtype, size, reader) + } else { + val items = ArrayList(size) + repeat(size) { items += readValue(subtype, reader) } + UVal.Arr(items) + } + } + else -> { + val fields = LinkedHashMap(node.children.size) + node.children.forEach { child -> + fields.put(unique(fields, child.name), readValue(child, reader)) + } + value = UVal.Struct(fields) + } + } + if (align) reader.align4() + return value + } + + /** Mirrors UnityPy read_value_array: elements are read without per-element self alignment. */ + private fun readValueArray(node: TTNode, size: Int, reader: TTReader): UVal.Arr { + var align = node.aligns + val items = ArrayList(size) + val width = PRIMITIVE_WIDTHS[node.type] + when { + node.type == "string" -> repeat(size) { items += UVal.Str(reader.readAlignedString()) } + node.type == "TypelessData" -> repeat(size) { items += UVal.Bytes(reader.readByteArray()) } + node.type == "bool" -> repeat(size) { items += UVal.Bool(reader.readU8()) } + node.type == "float" -> repeat(size) { items += UVal.Flt(reader.readFloat().toDouble(), true) } + node.type == "double" -> repeat(size) { items += UVal.Flt(reader.readDouble(), false) } + width != null -> repeat(size) { items += UVal.Num(reader.readRaw(width), width) } + node.type == "pair" -> repeat(size) { + if (node.children.size < 2) throw UnityFormatException("Type tree pair node is malformed") + val fields = LinkedHashMap(2) + fields.put(unique(fields, node.children[0].name), readValue(node.children[0], reader)) + fields.put(unique(fields, node.children[1].name), readValue(node.children[1], reader)) + items += UVal.Struct(fields) + } + node.children.isNotEmpty() && node.children[0].type == "Array" -> { + val array = node.children[0] + if (array.aligns) align = true + val subtype = array.children.getOrElse(1) { throw UnityFormatException("Type tree array is malformed") } + repeat(size) { + val inner = reader.readI32() + if (inner < 0 || inner > MAX_ELEMENTS) throw UnityFormatException("Type tree array is too large") + items += if (subtype.aligns) { + readValueArray(subtype, inner, reader) + } else { + val innerItems = ArrayList(inner) + repeat(inner) { innerItems += readValue(subtype, reader) } + UVal.Arr(innerItems) + } + } + } + else -> repeat(size) { + val fields = LinkedHashMap(node.children.size) + node.children.forEach { child -> + fields.put(unique(fields, child.name), readValue(child, reader)) + } + items += UVal.Struct(fields) + } + } + if (align) reader.align4() + return UVal.Arr(items) + } + + private fun unique(fields: LinkedHashMap, name: String): String { + if (!fields.containsKey(name)) return name + var index = 2 + while (fields.containsKey("$name#$index")) index++ + return "$name#$index" + } + + // ---------------------------------------------------------------- writing + + private class TTWriter(val bigEndian: Boolean) { + val out = ByteArrayOutputStream() + + fun writeRaw(value: Long, width: Int) { + if (bigEndian) { + for (i in width - 1 downTo 0) out.write(((value ushr (8 * i)) and 0xFF).toInt()) + } else { + for (i in 0 until width) out.write(((value ushr (8 * i)) and 0xFF).toInt()) + } + } + + fun writeAlignedString(value: String) { + val bytes = value.toByteArray(Charsets.UTF_8) + writeRaw(bytes.size.toLong(), 4) + out.write(bytes) + align4() + } + + fun align4() { + val rem = out.size() and 3 + if (rem != 0) out.write(ByteArray(4 - rem)) + } + + fun toByteArray(): ByteArray = out.toByteArray() + } + + fun encode(tree: TypeTree, value: UVal, bigEndian: Boolean): ByteArray { + val writer = TTWriter(bigEndian) + writeValue(tree.root, value, writer) + return writer.toByteArray() + } + + private fun writeValue(node: TTNode, value: UVal, writer: TTWriter) { + var align = node.aligns + val width = PRIMITIVE_WIDTHS[node.type] + when { + node.type == "string" -> writer.writeAlignedString((value as UVal.Str).value) + node.type == "TypelessData" -> { + val bytes = (value as UVal.Bytes).data + writer.writeRaw(bytes.size.toLong(), 4) + writer.out.write(bytes) + } + node.type == "bool" -> writer.writeRaw((value as UVal.Bool).raw.toLong(), 1) + node.type == "float" -> writer.writeRaw((value as UVal.Flt).value.toFloat().toRawBits().toLong(), 4) + node.type == "double" -> writer.writeRaw((value as UVal.Flt).value.toRawBits(), 8) + width != null -> writer.writeRaw((value as UVal.Num).value, width) + node.children.isNotEmpty() && node.children[0].type == "Array" -> { + val array = node.children[0] + if (array.aligns) align = true + val items = (value as UVal.Arr).items + writer.writeRaw(items.size.toLong(), 4) + val subtype = array.children.getOrElse(1) { throw UnityFormatException("Type tree array is malformed") } + if (subtype.aligns) { + writeValueArray(subtype, items, writer) + } else { + items.forEach { writeValue(subtype, it, writer) } + } + } + else -> { + val fields = (value as UVal.Struct).fields + node.children.forEach { child -> + val key = fields.keys.firstOrNull { it == child.name || it.startsWith(child.name + "#") } + ?: throw UnityFormatException("Decoded value is missing field ${child.name}") + writeValue(child, fields.getValue(key), writer) + } + } + } + if (align) writer.align4() + } + + /** Mirrors read_value_array on the write side: single alignment after all elements. */ + private fun writeValueArray(node: TTNode, items: List, writer: TTWriter) { + var align = node.aligns + val width = PRIMITIVE_WIDTHS[node.type] + when { + node.type == "string" -> items.forEach { writer.writeAlignedString((it as UVal.Str).value) } + node.type == "TypelessData" -> items.forEach { + val bytes = (it as UVal.Bytes).data + writer.writeRaw(bytes.size.toLong(), 4) + writer.out.write(bytes) + } + node.type == "bool" -> items.forEach { writer.writeRaw((it as UVal.Bool).raw.toLong(), 1) } + node.type == "float" -> items.forEach { writer.writeRaw((it as UVal.Flt).value.toFloat().toRawBits().toLong(), 4) } + node.type == "double" -> items.forEach { writer.writeRaw((it as UVal.Flt).value.toRawBits(), 8) } + width != null -> items.forEach { writer.writeRaw((it as UVal.Num).value, width) } + node.type == "pair" -> items.forEach { item -> + val fields = (item as UVal.Struct).fields + val values = fields.values.toList() + writeValue(node.children[0], values[0], writer) + writeValue(node.children[1], values[1], writer) + } + node.children.isNotEmpty() && node.children[0].type == "Array" -> { + val array = node.children[0] + if (array.aligns) align = true + val subtype = array.children.getOrElse(1) { throw UnityFormatException("Type tree array is malformed") } + items.forEach { item -> + val inner = (item as UVal.Arr).items + writer.writeRaw(inner.size.toLong(), 4) + if (subtype.aligns) { + writeValueArray(subtype, inner, writer) + } else { + inner.forEach { writeValue(subtype, it, writer) } + } + } + } + else -> items.forEach { item -> + val fields = (item as UVal.Struct).fields + node.children.forEach { child -> + val key = fields.keys.firstOrNull { it == child.name || it.startsWith(child.name + "#") } + ?: throw UnityFormatException("Decoded value is missing field ${child.name}") + writeValue(child, fields.getValue(key), writer) + } + } + } + if (align) writer.align4() + } + + // ---------------------------------------------------------------- strings + + /** Flat "path -> string value" map of every string leaf, in decode order. */ + fun exportStrings(value: UVal): LinkedHashMap { + val out = LinkedHashMap() + collectStrings(value, "", out) + return out + } + + private fun collectStrings(value: UVal, path: String, out: LinkedHashMap) { + when (value) { + is UVal.Str -> out[path] = value.value + is UVal.Struct -> value.fields.forEach { (key, child) -> + collectStrings(child, if (path.isEmpty()) key else "$path.$key", out) + } + is UVal.Arr -> value.items.forEachIndexed { index, child -> + collectStrings(child, "$path[$index]", out) + } + else -> Unit + } + } + + /** Replaces string leaves listed in [edits]; unknown paths are rejected. Returns edit count. */ + fun applyStrings(value: UVal, edits: Map): Int { + if (edits.isEmpty()) return 0 + val remaining = LinkedHashMap(edits) + applyStringsInto(value, "", remaining) + if (remaining.isNotEmpty()) { + throw UnityFormatException("Edited JSON contains unknown text path: ${remaining.keys.first()}") + } + return edits.size + } + + private fun applyStringsInto(value: UVal, path: String, remaining: MutableMap) { + when (value) { + is UVal.Str -> { + if (remaining.containsKey(path)) value.value = remaining.remove(path)!! + } + is UVal.Struct -> value.fields.forEach { (key, child) -> + applyStringsInto(child, if (path.isEmpty()) key else "$path.$key", remaining) + } + is UVal.Arr -> value.items.forEachIndexed { index, child -> + applyStringsInto(child, "$path[$index]", remaining) + } + else -> Unit + } + } + + /** True when the value holds meaningful text (for "game text" detection). */ + fun textStats(value: UVal): Triple { + var count = 0 + var bytes = 0L + var sample = "" + fun walk(v: UVal) { + when (v) { + is UVal.Str -> { + if (v.value.isNotEmpty()) { + count++ + bytes += v.value.toByteArray(Charsets.UTF_8).size + if (sample.length < 120 && v.value.length > sample.length) sample = v.value.take(120) + } + } + is UVal.Struct -> v.fields.values.forEach { walk(it) } + is UVal.Arr -> v.items.forEach { walk(it) } + else -> Unit + } + } + walk(value) + return Triple(count, bytes, sample) + } + + // ---------------------------------------------------------------- json + + /** Writes a flat string map as a JSON object (paths as keys). */ + fun writeJson(map: Map): String { + val sb = StringBuilder() + sb.append("{\n") + var first = true + map.forEach { (key, value) -> + if (!first) sb.append(",\n") + first = false + writeJsonString(sb, key) + sb.append(": ") + writeJsonString(sb, value) + } + sb.append("\n}\n") + return sb.toString() + } + + private fun writeJsonString(sb: StringBuilder, value: String) { + sb.append('"') + value.forEach { c -> + when (c) { + '"' -> sb.append("\\\"") + '\\' -> sb.append("\\\\") + '\n' -> sb.append("\\n") + '\r' -> sb.append("\\r") + '\t' -> sb.append("\\t") + '\b' -> sb.append("\\b") + '\u000C' -> sb.append("\\f") + else -> if (c < ' ') sb.append("\\u%04x".format(c.code)) else sb.append(c) + } + } + sb.append('"') + } + + /** Parses a flat JSON object of string -> string. Rejects other shapes with a clear error. */ + fun parseJson(text: String): LinkedHashMap { + val parser = JsonParser(text) + val map = parser.parseObject() + parser.skipWhitespace() + if (!parser.atEnd()) throw UnityFormatException("Edited JSON has trailing content") + return map + } + + private class JsonParser(val text: String) { + var pos = 0 + + fun atEnd() = pos >= text.length + + fun skipWhitespace() { + while (pos < text.length && text[pos].isWhitespace()) pos++ + } + + fun expect(c: Char) { + skipWhitespace() + if (atEnd() || text[pos] != c) throw UnityFormatException("Edited JSON is malformed at offset $pos") + pos++ + } + + fun parseObject(): LinkedHashMap { + val map = LinkedHashMap() + expect('{') + skipWhitespace() + if (!atEnd() && text[pos] == '}') { + pos++ + return map + } + while (true) { + val key = parseString() + expect(':') + val value = parseString() + map[key] = value + skipWhitespace() + when { + atEnd() -> throw UnityFormatException("Edited JSON ends inside the object") + text[pos] == ',' -> { pos++; skipWhitespace() } + text[pos] == '}' -> { pos++; return map } + else -> throw UnityFormatException("Edited JSON is malformed at offset $pos") + } + } + } + + fun parseString(): String { + expect('"') + val sb = StringBuilder() + while (true) { + if (atEnd()) throw UnityFormatException("Edited JSON ends inside a string") + val c = text[pos++] + when (c) { + '"' -> return sb.toString() + '\\' -> { + if (atEnd()) throw UnityFormatException("Edited JSON ends inside an escape") + when (val e = text[pos++]) { + '"', '\\', '/' -> sb.append(e) + 'n' -> sb.append('\n') + 'r' -> sb.append('\r') + 't' -> sb.append('\t') + 'b' -> sb.append('\b') + 'f' -> sb.append('\u000C') + 'u' -> { + if (pos + 4 > text.length) throw UnityFormatException("Edited JSON has a bad \\u escape") + sb.append(text.substring(pos, pos + 4).toInt(16).toChar()) + pos += 4 + } + else -> throw UnityFormatException("Edited JSON has an unknown escape \\$e") + } + } + else -> sb.append(c) + } + } + } + } + + // ---------------------------------------------------------------- trees + + class BlobNode( + val version: Int, + val level: Int, + val typeOffset: Int, + val nameOffset: Int, + val byteSize: Int, + val metaFlag: Int, + ) + + /** Builds a [TypeTree] from blob nodes (flat level list) plus the tree string buffer. */ + fun treeFromBlob(nodes: List, strings: ByteArray): TypeTree { + if (nodes.isEmpty()) throw UnityFormatException("Serialized type tree is empty") + fun resolve(offset: Int): String { + return if (offset >= 0) { + if (offset >= strings.size) throw UnityFormatException("Serialized type tree string is out of bounds") + var end = offset + while (end < strings.size && strings[end] != 0.toByte()) end++ + strings.copyOfRange(offset, end).toString(Charsets.UTF_8) + } else { + COMMON_STRINGS[offset and 0x7FFFFFFF] ?: (offset and 0x7FFFFFFF).toString() + } + } + val roots = ArrayList() + val stack = ArrayList() + nodes.forEach { blob -> + val node = TTNode(blob.version, resolve(blob.typeOffset), resolve(blob.nameOffset), blob.byteSize, blob.metaFlag) + while (stack.size > blob.level) stack.removeAt(stack.size - 1) + if (stack.isEmpty()) roots += node else stack[stack.size - 1].children += node + stack += node + } + if (roots.size != 1) throw UnityFormatException("Serialized type tree has multiple roots") + return TypeTree(roots[0]) + } + + /** Builds a [TypeTree] from the legacy recursive node layout (version 10/11 files). */ + fun treeFromLegacy(table: UnityBundleReader.Cursor, depth: Int = 0): TTNode { + if (depth > 96) throw UnityFormatException("Serialized type tree is too deep") + val type = table.readCString(MAX_STRING_BYTES) + val name = table.readCString(MAX_STRING_BYTES) + val byteSize = table.readI32() + table.readI32() // index + val flags = table.readI32() + val version = table.readI32() + val metaFlag = table.readI32() + val node = TTNode(version, type, name, byteSize, metaFlag) + val children = table.readI32() + if (children !in 0..100_000) throw UnityFormatException("Serialized type tree is invalid") + repeat(children) { node.children += treeFromLegacy(table, depth + 1) } + return node + } + + /** TextAsset fallback decoding (used when no type tree is available). */ + fun decodeTextAsset(data: ByteArray, bigEndian: Boolean): Pair? { + return try { + val reader = TTReader(data, bigEndian) + val name = reader.readAlignedString() + val script = reader.readByteArray() + name to script + } catch (e: Exception) { + null + } + } + + /** TextAsset fallback encoding, symmetric to [decodeTextAsset]. */ + fun encodeTextAsset(name: String, script: ByteArray, bigEndian: Boolean): ByteArray { + val writer = TTWriter(bigEndian) + writer.writeAlignedString(name) + writer.writeRaw(script.size.toLong(), 4) + writer.out.write(script) + return writer.toByteArray() + } + + internal val COMMON_STRINGS: Map = mapOf( + 0 to "AABB", + 5 to "AnimationClip", + 19 to "AnimationCurve", + 34 to "AnimationState", + 49 to "Array", + 55 to "Base", + 60 to "BitField", + 69 to "bitset", + 76 to "bool", + 81 to "char", + 86 to "ColorRGBA", + 96 to "Component", + 106 to "data", + 111 to "deque", + 117 to "double", + 124 to "dynamic_array", + 138 to "FastPropertyName", + 155 to "first", + 161 to "float", + 167 to "Font", + 172 to "GameObject", + 183 to "Generic Mono", + 196 to "GradientNEW", + 208 to "GUID", + 213 to "GUIStyle", + 222 to "int", + 226 to "list", + 231 to "long long", + 241 to "map", + 245 to "Matrix4x4f", + 256 to "MdFour", + 263 to "MonoBehaviour", + 277 to "MonoScript", + 288 to "m_ByteSize", + 299 to "m_Curve", + 307 to "m_EditorClassIdentifier", + 331 to "m_EditorHideFlags", + 349 to "m_Enabled", + 359 to "m_ExtensionPtr", + 374 to "m_GameObject", + 387 to "m_Index", + 395 to "m_IsArray", + 405 to "m_IsStatic", + 416 to "m_MetaFlag", + 427 to "m_Name", + 434 to "m_ObjectHideFlags", + 452 to "m_PrefabInternal", + 469 to "m_PrefabParentObject", + 490 to "m_Script", + 499 to "m_StaticEditorFlags", + 519 to "m_Type", + 526 to "m_Version", + 536 to "Object", + 543 to "pair", + 548 to "PPtr", + 564 to "PPtr", + 581 to "PPtr", + 596 to "PPtr", + 616 to "PPtr", + 633 to "PPtr", + 646 to "PPtr", + 659 to "PPtr", + 672 to "PPtr", + 688 to "PPtr", + 702 to "PPtr", + 718 to "PPtr", + 734 to "Prefab", + 741 to "Quaternionf", + 753 to "Rectf", + 759 to "RectInt", + 767 to "RectOffset", + 778 to "second", + 785 to "set", + 789 to "short", + 795 to "size", + 800 to "SInt16", + 807 to "SInt32", + 814 to "SInt64", + 821 to "SInt8", + 827 to "staticvector", + 840 to "string", + 847 to "TextAsset", + 857 to "TextMesh", + 866 to "Texture", + 874 to "Texture2D", + 884 to "Transform", + 894 to "TypelessData", + 907 to "UInt16", + 914 to "UInt32", + 921 to "UInt64", + 928 to "UInt8", + 934 to "unsigned int", + 947 to "unsigned long long", + 966 to "unsigned short", + 981 to "vector", + 988 to "Vector2f", + 997 to "Vector3f", + 1006 to "Vector4f", + 1015 to "m_ScriptingClassIdentifier", + 1042 to "Gradient", + 1051 to "Type*", + 1057 to "int2_storage", + 1070 to "int3_storage", + 1083 to "BoundsInt", + 1093 to "m_CorrespondingSourceObject", + 1121 to "m_PrefabInstance", + 1138 to "m_PrefabAsset", + 1152 to "FileSize", + 1161 to "Hash128", + 1169 to "RenderingLayerMask", + 1188 to "fixed_array", + 1200 to "EntityId", + 1209 to "LoadableObjectId", + 1226 to "LoadableSceneId", + ) +} diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt index f4804ba..25f2d6a 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt @@ -57,6 +57,15 @@ data class UnityBundleSummary( val entries: List, ) +/** Result of scanning one serialized-file object for editable game text. */ +data class UnityTextInfo( + val objectName: String?, + val className: String, + val stringCount: Int, + val textBytes: Long, + val sample: String, +) + class UnityFormatException(message: String, cause: Throwable? = null) : IOException(message, cause) /** @@ -67,10 +76,40 @@ class UnityBundleDocument internal constructor( val source: File, val summary: UnityBundleSummary, internal val dataFile: File, + internal val serialized: SerializedFileIndex? = null, ) : Closeable { - /** Repacking is implemented for UnityFS only; legacy bundles and serialized files are read-only. */ - val repackSupported: Boolean get() = summary.signature == "UnityFS" + /** Repacking is implemented for UnityFS bundles and serialized files; legacy containers are read-only. */ + val repackSupported: Boolean get() = summary.signature == "UnityFS" || serialized != null + + /** True when objects can be decoded through type trees and their texts edited. */ + val supportsTextEditing: Boolean get() = serialized != null + + /** Text statistics for one serialized-file object; null when it holds no decodable text. */ + fun textInfo(entry: UnityBundleEntry): UnityTextInfo? { + val ser = serialized ?: return null + val slot = ser.slotFor(entry) ?: return null + if (!ser.hasTreeFor(entry)) return null + val value = ser.decode(dataFile, entry) ?: return null + val (count, bytes, sample) = TypeTreeCodec.textStats(value) + if (count == 0) return null + return UnityTextInfo(ser.objectName(value), SerializedFileReader.className(slot.classId), count, bytes, sample) + } + + /** Flat "path -> value" map of every string inside the object, in decode order. */ + fun exportTexts(entry: UnityBundleEntry): LinkedHashMap? { + val ser = serialized ?: return null + val value = ser.decode(dataFile, entry) ?: return null + return TypeTreeCodec.exportStrings(value) + } + + /** Re-encodes the object with the edited strings applied; returns the new raw object bytes. */ + fun rebuildTexts(entry: UnityBundleEntry, edits: Map): ByteArray { + val ser = serialized ?: throw UnityFormatException("This document does not support text editing") + val value = ser.decode(dataFile, entry) ?: throw UnityFormatException("Object cannot be decoded for editing") + TypeTreeCodec.applyStrings(value, edits) + return ser.encode(dataFile, entry, value) + } fun copyEntry(entry: UnityBundleEntry, output: File) { requireEntry(entry) @@ -91,9 +130,14 @@ class UnityBundleDocument internal constructor( /** Writes a normalized UnityFS bundle. Inputs are never overwritten. */ fun repack(output: File, replacements: Map = emptyMap()) { - if (!repackSupported) throw UnityFormatException("This Unity format is read-only; repacking needs a UnityFS bundle") + if (!repackSupported) throw UnityFormatException("This Unity format is read-only; repacking needs a UnityFS bundle or serialized file") if (output.canonicalFile == source.canonicalFile) throw IOException("Output must not replace the source bundle") if (output.exists()) throw IOException("Output already exists: ${output.name}") + val serializedIndex = serialized + if (serializedIndex != null) { + serializedIndex.rebuild(output, dataFile, replacements, summary.entries) + return + } val unknown = replacements.keys - summary.entries.map { it.name }.toSet() if (unknown.isNotEmpty()) throw IOException("Replacement entry is not in this bundle: ${unknown.first()}") @@ -339,13 +383,18 @@ object UnityBundleReader { cache.mkdirs() val dataFile = File(cache, "bundle-data.bin") try { + var serializedIndex: SerializedFileIndex? = null val summary = when (probe(file).kind) { UnityFileKind.UNITY_FS -> parseUnityFs(file, dataFile) UnityFileKind.UNITY_WEB, UnityFileKind.UNITY_RAW -> UnityLegacyReader.parse(file, dataFile) - UnityFileKind.SERIALIZED_FILE -> SerializedFileReader.parse(file, dataFile) + UnityFileKind.SERIALIZED_FILE -> { + val (parsed, index) = SerializedFileReader.parse(file, dataFile) + serializedIndex = index + parsed + } UnityFileKind.UNKNOWN -> throw UnityFormatException("Not a Unity file: ${file.name}") } - return UnityBundleDocument(file, summary, dataFile) + return UnityBundleDocument(file, summary, dataFile, serializedIndex) } catch (e: Throwable) { dataFile.delete() cache.delete() diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt index bce0997..d8e25ff 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt @@ -56,6 +56,7 @@ import dev.cluvex.strata.core.unity.UnityBundleDocument import dev.cluvex.strata.core.unity.UnityBundleEntry import dev.cluvex.strata.core.unity.UnityFileKind import dev.cluvex.strata.core.unity.UnityProbe +import dev.cluvex.strata.core.unity.UnityTextInfo import dev.cluvex.strata.core.util.Formatters import dev.cluvex.strata.ui.isolated import kotlinx.coroutines.Dispatchers @@ -96,6 +97,12 @@ fun UnityAssetScreen( vm.consumeMessage() } } + LaunchedEffect(state.navigateTo) { + state.navigateTo?.let { target -> + vm.consumeNavigate() + onOpenFile(FileItem.of(File(target))) + } + } val document = state.document val selectedEntry = remember(document, state.selectedName) { @@ -193,6 +200,7 @@ fun UnityAssetScreen( entry = entry, selected = state.selectedName == entry.name, modified = entry.name in state.replacements || entry.name in state.editedFiles, + textInfo = state.textInfos[entry.name], onClick = { vm.select(entry.name) }, ) } @@ -213,6 +221,11 @@ fun UnityAssetScreen( }, onExport = { exportPicker.launch(entry.displayName) }, onReplace = { replacePicker.launch(arrayOf("*/*")) }, + onExportTexts = if (state.textInfos.containsKey(entry.name)) { + { vm.exportTexts(entry) } + } else { + null + }, ) } ?: Text(stringResource(R.string.unity_select_entry), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp)) @@ -286,6 +299,7 @@ private fun UnityEntryRow( entry: UnityBundleEntry, selected: Boolean, modified: Boolean, + textInfo: UnityTextInfo? = null, onClick: () -> Unit, ) { Surface( @@ -297,7 +311,17 @@ private fun UnityEntryRow( Text(index.toString(), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) Column(Modifier.weight(1f)) { Text(entry.displayName, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text(isolated(entry.name), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (textInfo != null) { + Text( + stringResource(R.string.unity_texts_badge, textInfo.stringCount, textInfo.objectName ?: textInfo.className), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } else { + Text(isolated(entry.name), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + } } Column(horizontalAlignment = Alignment.End) { Text(Formatters.size(entry.size), style = MaterialTheme.typography.labelMedium) @@ -314,6 +338,7 @@ private fun UnityEntryActions( onOpen: () -> Unit, onExport: () -> Unit, onReplace: () -> Unit, + onExportTexts: (() -> Unit)? = null, ) { Surface(shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.surfaceContainer, modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) { Column(Modifier.padding(12.dp)) { @@ -325,6 +350,11 @@ private fun UnityEntryActions( TextButton(onClick = onExport, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_export_entry), maxLines = 1) } TextButton(onClick = onReplace, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_replace_entry), maxLines = 1) } } + if (onExportTexts != null) { + Button(onClick = onExportTexts, enabled = !busy, modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) { + Text(stringResource(R.string.unity_export_texts), maxLines = 1) + } + } } } } diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt index 6d7c40f..1e545b1 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt @@ -7,11 +7,14 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import dev.cluvex.strata.R import dev.cluvex.strata.core.archive.ArchiveParent +import dev.cluvex.strata.core.unity.TypeTreeCodec import dev.cluvex.strata.core.unity.UnityBundleDocument import dev.cluvex.strata.core.unity.UnityBundleEntry import dev.cluvex.strata.core.unity.UnityBundleReader +import dev.cluvex.strata.core.unity.UnityFormatException import dev.cluvex.strata.core.unity.UnityPackageRepacker import dev.cluvex.strata.core.unity.UnityProbe +import dev.cluvex.strata.core.unity.UnityTextInfo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -34,17 +37,25 @@ data class UnityAssetUiState( val workingFiles: Map = emptyMap(), val editedFiles: Map = emptyMap(), val replacements: Map = emptyMap(), + val textInfos: Map = emptyMap(), + val exportedTexts: Map = emptyMap(), + val navigateTo: String? = null, val output: File? = null, val message: String? = null, ) class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { + private companion object { + const val MAX_TEXT_SCAN_OBJECTS = 5_000 + } + private val _state = MutableStateFlow(UnityAssetUiState()) val state: StateFlow = _state.asStateFlow() private var document: UnityBundleDocument? = null private var stageDir: File? = null private var workingBaselines: Map> = emptyMap() + private var exportedBaselines: Map> = emptyMap() fun open(path: String) { val current = _state.value @@ -54,6 +65,7 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { stageDir?.deleteRecursively() document = null workingBaselines = emptyMap() + exportedBaselines = emptyMap() val newStageDir = File(getApplication().cacheDir, "unity-editor/${path.hashCode().toUInt().toString(16)}-${System.nanoTime()}") newStageDir.mkdirs() stageDir = newStageDir @@ -68,7 +80,16 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { probe to parsed } document = parsed - _state.update { it.copy(loading = false, probe = probe, document = parsed) } + val infos = withContext(Dispatchers.IO) { + if (parsed?.supportsTextEditing == true && parsed.summary.entries.size <= MAX_TEXT_SCAN_OBJECTS) { + parsed.summary.entries.mapNotNull { entry -> + parsed.textInfo(entry)?.let { entry.name to it } + }.toMap() + } else { + emptyMap() + } + } + _state.update { it.copy(loading = false, probe = probe, document = parsed, textInfos = infos) } } catch (_: Exception) { _state.update { it.copy(loading = false, error = getApplication().getString(R.string.unity_load_failed)) } } @@ -117,6 +138,41 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { } } + /** Exports every string inside a serialized-file object as an editable JSON file. */ + fun exportTexts(entry: UnityBundleEntry) { + val doc = document ?: return + val dir = stageDir ?: return + if (_state.value.busy) return + _state.update { it.copy(busy = true) } + viewModelScope.launch { + try { + val result = withContext(Dispatchers.IO) { + val texts = doc.exportTexts(entry) ?: throw IOException("Entry has no editable text") + val index = doc.summary.entries.indexOf(entry).coerceAtLeast(0) + val safe = entry.displayName.replace(Regex("[^A-Za-z0-9._-]"), "_").take(48).ifEmpty { "object" } + val file = File(dir, "texts-$index-$safe.json") + file.writeText(TypeTreeCodec.writeJson(texts)) + Triple(file, texts.size, file.length() to file.lastModified()) + } + exportedBaselines = exportedBaselines + (entry.name to result.third) + _state.update { + it.copy( + busy = false, + exportedTexts = it.exportedTexts + (entry.name to result.first), + navigateTo = result.first.path, + message = getApplication().getString(R.string.unity_texts_exported, result.second), + ) + } + } catch (_: Exception) { + _state.update { it.copy(busy = false, message = getApplication().getString(R.string.unity_operation_failed)) } + } + } + } + + fun consumeNavigate() { + _state.update { it.copy(navigateTo = null) } + } + fun refreshEditedFiles() { val current = _state.value val changed = current.workingFiles.filter { (name, file) -> @@ -136,12 +192,11 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { } val current = _state.value if (current.busy) return - val changes = current.editedFiles + current.replacements _state.update { it.copy(busy = true, error = null) } viewModelScope.launch { try { val output = withContext(Dispatchers.IO) { - UnityPackageRepacker.repack(doc, changes, parents, getApplication().cacheDir) + UnityPackageRepacker.repack(doc, collectChanges(doc, current), parents, getApplication().cacheDir) } _state.update { it.copy( @@ -150,12 +205,36 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { busy = false, ) } - } catch (_: Exception) { - _state.update { - it.copy(message = getApplication().getString(R.string.unity_operation_failed), busy = false) + } catch (e: Exception) { + val message = if (e is UnityFormatException && e.message?.contains("JSON") == true) { + getApplication().getString(R.string.unity_texts_bad_json, e.message ?: "") + } else { + getApplication().getString(R.string.unity_operation_failed) } + _state.update { it.copy(message = message, busy = false) } + } + } + } + + /** Merges staged edits, picked replacements and any exported text JSON the user has modified. */ + private fun collectChanges(doc: UnityBundleDocument, current: UnityAssetUiState): Map { + val dir = stageDir + val textChanges = HashMap() + if (dir != null) { + current.exportedTexts.forEach { (name, jsonFile) -> + if (!jsonFile.isFile) return@forEach + val baseline = exportedBaselines[name] + if (baseline != null && jsonFile.length() == baseline.first && jsonFile.lastModified() == baseline.second) return@forEach + val entry = doc.summary.entries.firstOrNull { it.name == name } ?: return@forEach + val edits = TypeTreeCodec.parseJson(jsonFile.readText()) + val bytes = doc.rebuildTexts(entry, edits) + val staged = File(dir, "text-${name.hashCode().toUInt().toString(16)}-${System.nanoTime()}.bin") + staged.writeBytes(bytes) + textChanges[name] = staged + exportedBaselines = exportedBaselines + (name to (jsonFile.length() to jsonFile.lastModified())) } } + return current.editedFiles + textChanges + current.replacements } fun notifyMessage(text: String) { diff --git a/app/src/main/res/values-fa/strings_unity.xml b/app/src/main/res/values-fa/strings_unity.xml index b0486cd..fd3733a 100644 --- a/app/src/main/res/values-fa/strings_unity.xml +++ b/app/src/main/res/values-fa/strings_unity.xml @@ -37,4 +37,8 @@ %1$d ورودی این قالب فقط‌خواندنی است؛ بازبسته‌بندی تنها برای بسته‌های UnityFS پشتیبانی می‌شود. + ویرایش متن‌ها + ‏%1$d رشتهٔ متنی به‌صورت JSON باز شد — ویرایش و ذخیره کنید، سپس بازبسته‌بندی را بزنید. + ‏%1$d متن · %2$s + فایل JSON ویرایش‌شده معتبر نیست: %1$s diff --git a/app/src/main/res/values-ru/strings_unity.xml b/app/src/main/res/values-ru/strings_unity.xml index b327b26..97ed916 100644 --- a/app/src/main/res/values-ru/strings_unity.xml +++ b/app/src/main/res/values-ru/strings_unity.xml @@ -39,4 +39,8 @@ %1$d записи Этот формат доступен только для чтения: пересборка поддерживается лишь для UnityFS. + Правка текстов + Открыто строк: %1$d в JSON — отредактируйте, сохраните и нажмите пересборку. + Текстов: %1$d · %2$s + Изменённый JSON повреждён: %1$s diff --git a/app/src/main/res/values-zh-rCN/strings_unity.xml b/app/src/main/res/values-zh-rCN/strings_unity.xml index 9f59fa6..1911899 100644 --- a/app/src/main/res/values-zh-rCN/strings_unity.xml +++ b/app/src/main/res/values-zh-rCN/strings_unity.xml @@ -36,4 +36,8 @@ %1$d 个条目 此格式为只读;仅 UnityFS 包支持重新打包。 + 编辑文本 + 已以 JSON 打开 %1$d 条文本 — 编辑保存后点击重新打包。 + %1$d 条文本 · %2$s + 编辑后的 JSON 无效:%1$s diff --git a/app/src/main/res/values/strings_unity.xml b/app/src/main/res/values/strings_unity.xml index 8781e5d..2a4f2e3 100644 --- a/app/src/main/res/values/strings_unity.xml +++ b/app/src/main/res/values/strings_unity.xml @@ -37,4 +37,8 @@ %1$d entries This format is read-only. Repacking is supported for UnityFS bundles only. + Edit texts + Opened %1$d text entries as JSON — edit, save, then tap repack. + %1$d texts · %2$s + The edited JSON is invalid: %1$s diff --git a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt index 5788004..228ec75 100644 --- a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt +++ b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt @@ -138,7 +138,7 @@ class UnityBundleReaderTest { document.copyEntry(document.summary.entries[1], second) assertThat(first.readText()).isEqualTo("hello") assertThat(second.readText()).isEqualTo("world") - assertThat(document.repackSupported).isFalse() + assertThat(document.repackSupported).isTrue() } } @@ -213,6 +213,92 @@ class UnityBundleReaderTest { assertThat(error).hasMessageThat().contains("encrypted") } + @Test + fun decodesTypedObjectsFromSerializedFile() { + val source = writeTypedSerialized(temp.root, "typed.assets", typedObjectOne(), typedObjectOne()) + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + assertThat(document.supportsTextEditing).isTrue() + val first = document.summary.entries[0] + val info = document.textInfo(first) + assertThat(info).isNotNull() + assertThat(info!!.stringCount).isEqualTo(6) + val texts = document.exportTexts(first)!! + assertThat(texts["m_Name"]).isEqualTo("obj1") + assertThat(texts["m_Items[0].Key"]).isEqualTo("k1") + assertThat(texts["m_Items[0].Value"]).isEqualTo("v1-long") + assertThat(texts["m_Items[1].Key"]).isEqualTo("key2") + assertThat(texts["m_Items[1].Value"]).isEqualTo("value2") + assertThat(texts["m_Script"]).isEqualTo("print('hi')") + } + } + + @Test + fun rebuildsSerializedFileWithEditedTexts() { + val source = writeTypedSerialized(temp.root, "typed.assets", typedObjectOne(), typedObjectOne()) + val output = File(temp.root, "typed-edited.assets") + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + val first = document.summary.entries[0] + val edited = document.rebuildTexts( + first, + mapOf( + "m_Items[0].Value" to "TRANSLATED", + "m_Script" to "println()", + ), + ) + val replacement = File(temp.root, "edited-object.bin").apply { writeBytes(edited) } + document.repack(output, mapOf(first.name to replacement)) + } + UnityBundleReader.open(output, File(temp.root, "cache")).use { rebuilt -> + val first = rebuilt.summary.entries[0] + val texts = rebuilt.exportTexts(first)!! + assertThat(texts["m_Items[0].Value"]).isEqualTo("TRANSLATED") + assertThat(texts["m_Script"]).isEqualTo("println()") + assertThat(texts["m_Name"]).isEqualTo("obj1") + assertThat(texts["m_Items[1].Value"]).isEqualTo("value2") + assertThat(rebuilt.exportTexts(rebuilt.summary.entries[1])!!["m_Name"]).isEqualTo("obj1") + } + } + + @Test + fun rebuildsSerializedFileWithRawReplacement() { + val source = writeTypedSerialized(temp.root, "typed.assets", typedObjectOne(), typedObjectOne()) + val output = File(temp.root, "typed-raw.assets") + UnityBundleReader.open(source, File(temp.root, "cache")).use { document -> + val first = document.summary.entries[0] + val replacement = File(temp.root, "raw-object.bin").apply { writeBytes(typedObjectTwo()) } + document.repack(output, mapOf(first.name to replacement)) + } + UnityBundleReader.open(output, File(temp.root, "cache")).use { rebuilt -> + val texts = rebuilt.exportTexts(rebuilt.summary.entries[0])!! + assertThat(texts["m_Name"]).isEqualTo("renamed") + assertThat(texts["m_Script"]).isEqualTo("edited-script") + assertThat(rebuilt.summary.entries[0].size).isEqualTo(typedObjectTwo().size.toLong()) + assertThat(rebuilt.exportTexts(rebuilt.summary.entries[1])!!["m_Items[0].Key"]).isEqualTo("k1") + } + } + + @Test + fun jsonRoundTripPreservesEscapesAndRejectsUnknownPaths() { + val map = linkedMapOf( + "a.b[0]" to "quote \" backslash \\ newline\nline2", + "uni" to "سلام دنیا \u00e9\u4e2d", + "empty" to "", + ) + val parsed = TypeTreeCodec.parseJson(TypeTreeCodec.writeJson(map)) + assertThat(parsed).isEqualTo(map) + val value = UVal.Struct( + linkedMapOf( + "keep" to UVal.Str("old"), + "drop" to UVal.Str("other"), + ), + ) + assertThat(TypeTreeCodec.applyStrings(value, mapOf("keep" to "new"))).isEqualTo(1) + assertThat((value.fields["keep"] as UVal.Str).value).isEqualTo("new") + assertThrows(UnityFormatException::class.java) { + TypeTreeCodec.applyStrings(value, mapOf("missing.path" to "x")) + } + } + private fun writeBundle( root: File, name: String, @@ -469,4 +555,131 @@ class UnityBundleReaderTest { out.write(payload) return out.toByteArray() } + // --------------------------------------------------------------------------------------- + // Typed serialized-file fixtures. Object bytes are hand-built (independent of the codec) + // from this type tree: + // Base(TestObj): m_Name string; m_Items vector; + // m_Count int; m_Script string + // --------------------------------------------------------------------------------------- + + private fun le32(value: Long): ByteArray = byteArrayOf( + value.toByte(), + (value ushr 8).toByte(), + (value ushr 16).toByte(), + (value ushr 24).toByte(), + ) + + private fun le64(value: Long): ByteArray = ByteArray(8) { index -> ((value ushr (8 * index)) and 0xFF).toByte() } + + private fun common(id: Int): Int = (id.toLong() or 0x80000000L).toInt() + + private fun leStr(out: ByteArrayOutputStream, value: String) { + val bytes = value.toByteArray(Charsets.UTF_8) + out.write(le32(bytes.size.toLong())) + out.write(bytes) + out.write(ByteArray((4 - bytes.size % 4) % 4)) + } + + private fun typedObjectOne(): ByteArray { + val out = ByteArrayOutputStream() + leStr(out, "obj1") // m_Name + out.write(le32(2)) // m_Items count + leStr(out, "k1") // item 0 key + leStr(out, "v1-long") // item 0 value + leStr(out, "key2") // item 1 key + leStr(out, "value2") // item 1 value + out.write(le32(7)) // m_Count + leStr(out, "print('hi')") // m_Script + return out.toByteArray() + } + + private fun typedObjectTwo(): ByteArray { + val out = ByteArrayOutputStream() + leStr(out, "renamed") + out.write(le32(0)) + out.write(le32(9)) + leStr(out, "edited-script") + return out.toByteArray() + } + + private fun typeTreeBlob(): Pair { + val strings = "TestObj\u0000m_Items\u0000Item\u0000Key\u0000Value\u0000m_Count\u0000".replace("\\u0000", "\u0000").toByteArray(Charsets.UTF_8) + val testObj = 0 + val mItems = 8 + val item = 16 + val key = 21 + val value = 25 + val mCount = 31 + val nodes = ByteArrayOutputStream() + fun node(level: Int, type: Int, name: Int, metaFlag: Int) { + nodes.write(byteArrayOf(1, 0)) // node version u16 + nodes.write(level) // level u8 + nodes.write(0) // type flags u8 + nodes.write(le32(type.toLong() and 0xFFFFFFFFL)) + nodes.write(le32(name.toLong() and 0xFFFFFFFFL)) + nodes.write(le32(-1L and 0xFFFFFFFFL)) // byte size (variable) + nodes.write(le32(0)) // index + nodes.write(le32(metaFlag.toLong() and 0xFFFFFFFFL)) + } + node(0, testObj, common(55), 0) // Base + node(1, common(840), common(427), 0) // m_Name: string + node(1, common(981), mItems, 0) // m_Items: vector + node(2, common(49), common(49), 0x4000) // Array (align after) + node(3, common(222), common(795), 0) // size: int + node(3, item, common(106), 0) // data: Item + node(4, common(840), key, 0) // Key: string + node(4, common(840), value, 0) // Value: string + node(1, common(222), mCount, 0) // m_Count: int + node(1, common(840), common(490), 0) // m_Script: string + return nodes.toByteArray() to strings + } + + private fun writeTypedSerialized(root: File, name: String, vararg objects: ByteArray): File { + val (nodes, strings) = typeTreeBlob() + val meta = ByteArrayOutputStream() + meta.write("2021.3.0f1".toByteArray(Charsets.UTF_8)); meta.write(0) // unity version + meta.write(le32(13)) // build target + meta.write(1) // enable type tree + meta.write(le32(1)) // type count + meta.write(le32(114)) // class id: MonoBehaviour + meta.write(0) // is stripped + meta.write(byteArrayOf(0xFF.toByte(), 0xFF.toByte())) // script type index -1 + meta.write(ByteArray(16)) // script id (class 114) + meta.write(ByteArray(16)) // old type hash + meta.write(le32((nodes.size / 24).toLong())) + meta.write(le32(strings.size.toLong())) + meta.write(nodes) + meta.write(strings) + meta.write(le32(objects.size.toLong())) + var dataOffsetInSection = 0 + val data = ByteArrayOutputStream() + objects.forEachIndexed { index, bytes -> + meta.write(ByteArray((4 - meta.size() % 4) % 4)) // align4 before path id + meta.write(le64((100 + index).toLong())) + meta.write(le32(dataOffsetInSection.toLong())) + meta.write(le32(bytes.size.toLong())) + meta.write(le32(0)) // type id 0 + data.write(bytes) + dataOffsetInSection += bytes.size + } + val metadata = meta.toByteArray() + val dataBytes = data.toByteArray() + val headerSize = 20 + val dataStart = (headerSize + metadata.size + 15) / 16 * 16 + val output = File(root, name) + FileOutputStream(output).use { stream -> + DataOutputStream(stream).use { out -> + out.writeInt(metadata.size) + out.writeInt(dataStart + dataBytes.size) + out.writeInt(17) + out.writeInt(dataStart) + out.writeByte(0) + out.write(ByteArray(3)) + out.write(metadata) + out.write(ByteArray(dataStart - headerSize - metadata.size)) + out.write(dataBytes) + } + } + return output + } } From 6e3392600b5941040580518b22ddf5411d20f61b Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Sun, 18 Oct 2026 22:15:40 +0000 Subject: [PATCH 05/11] feat: repack Unity bundle parents so nested edits land in the original bundle - opening an entry that is itself a Unity file now pushes the Unity screen with the containing bundle recorded as a parent (same mechanism the archive browser already uses) - UnityPackageRepacker: when a parent archive is a UnityFS bundle, the rebuilt child is repacked into it instead of going through the zip editor, so editing subtitles inside a CAB yields an edited copy of the original bundle in one tap; the original file is never touched --- .../strata/core/unity/UnityPackageRepacker.kt | 19 +++++++++++++------ .../strata/feature/unity/UnityAssetScreen.kt | 7 ++++++- .../java/dev/cluvex/strata/ui/AppShell.kt | 1 + 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt index 4a46d4c..7ed7191 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityPackageRepacker.kt @@ -37,12 +37,19 @@ object UnityPackageRepacker { val destination = if (isFinal) uniqueSibling(source, "-unity-edited") else { File(tempDir, "parent-${index}-${System.nanoTime()}-${source.name}") } - copyExclusive(source, destination) - try { - ZipEditor.replace(destination, parent.entryPath, current) - } catch (e: Throwable) { - destination.delete() - throw e + if (UnityBundleReader.probe(source).kind == UnityFileKind.UNITY_FS) { + // The parent is itself a Unity bundle: rebuild it with the child entry replaced. + UnityBundleReader.open(source, File(tempDir, "parent-cache-$index")).use { parentDoc -> + parentDoc.repack(destination, mapOf(parent.entryPath to current)) + } + } else { + copyExclusive(source, destination) + try { + ZipEditor.replace(destination, parent.entryPath, current) + } catch (e: Throwable) { + destination.delete() + throw e + } } if (current != bundle) current.delete() current = destination diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt index d8e25ff..48711cf 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt @@ -72,6 +72,7 @@ fun UnityAssetScreen( refreshToken: Long, onBack: () -> Unit, onOpenFile: (FileItem) -> Unit, + onOpenNested: (File, List) -> Unit, onSignApk: (File) -> Unit, onLocate: (folder: String, reveal: String?) -> Unit, vm: UnityAssetViewModel = viewModel(), @@ -213,7 +214,11 @@ fun UnityAssetScreen( onOpen = { scope.launch { try { - onOpenFile(FileItem.of(vm.fileFor(entry))) + val staged = vm.fileFor(entry) + onOpenNested( + staged, + parents + ArchiveParent(document.source.path, entry.name), + ) } catch (_: Exception) { vm.notifyMessage(context.getString(R.string.unity_operation_failed)) } diff --git a/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt b/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt index a8e4b5d..e946d50 100644 --- a/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt +++ b/app/src/main/java/dev/cluvex/strata/ui/AppShell.kt @@ -597,6 +597,7 @@ private fun Screen( refreshToken = refreshToken, onBack = actions.pop, onOpenFile = actions.openFile, + onOpenNested = actions.openNestedFile, onSignApk = { file -> actions.signApk(FileItem.of(file)) }, onLocate = actions.locate, ) From 87861ea2d50ad34cf6d226fd1d4f11a357b4a480 Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Mon, 19 Oct 2026 00:00:20 +0000 Subject: [PATCH 06/11] fix: compress UnityFS output and edit nested serialized text --- .../strata/core/unity/Lz4BlockEncoder.kt | 161 ++++ .../strata/core/unity/SerializedFileReader.kt | 236 ++++- .../cluvex/strata/core/unity/TypeTreeCodec.kt | 11 +- .../strata/core/unity/UnityBundleReader.kt | 812 +++++++++++++++--- .../strata/core/unity/UnityLegacyReader.kt | 2 +- .../core/unity/UnityBundleReaderTest.kt | 620 ++++++++++++- 6 files changed, 1670 insertions(+), 172 deletions(-) create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/Lz4BlockEncoder.kt diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/Lz4BlockEncoder.kt b/app/src/main/java/dev/cluvex/strata/core/unity/Lz4BlockEncoder.kt new file mode 100644 index 0000000..ba6c62e --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/Lz4BlockEncoder.kt @@ -0,0 +1,161 @@ +package dev.cluvex.strata.core.unity + +import java.io.ByteArrayOutputStream + +/** + * Small raw LZ4 block encoder for UnityFS output. + * + * UnityFS stores raw LZ4 blocks: there is no frame magic, checksum or content-size header. The + * encoder uses a bounded hash chain (similar to an LZ4HC search) and deliberately works on one + * small UnityFS block at a time, keeping memory independent of the full bundle size. + */ +internal object Lz4BlockEncoder { + private const val MIN_MATCH = 4 + private const val LAST_LITERALS = 5 + private const val MATCH_FIND_LIMIT = 12 + private const val MAX_DISTANCE = 65_535 + private const val HASH_BITS = 16 + private const val HASH_SIZE = 1 shl HASH_BITS + private const val MAX_CHAIN_ATTEMPTS = 64 + + /** Returns one raw LZ4 block. [length] may be smaller than [input].size for a final block. */ + fun encode(input: ByteArray, length: Int = input.size): ByteArray { + require(length in 0..input.size) { "Invalid LZ4 input length" } + if (length == 0) return byteArrayOf(0) + if (length < MATCH_FIND_LIMIT) return literalOnly(input, length) + + val heads = IntArray(HASH_SIZE) { -1 } + val previous = IntArray(length) { -1 } + val inserted = BooleanArray(length) + val out = ByteArrayOutputStream(length) + var anchor = 0 + var position = 0 + val matchLimit = length - LAST_LITERALS + val searchLimit = length - MATCH_FIND_LIMIT + + fun insert(at: Int): Int { + if (at + MIN_MATCH > length) return -1 + if (inserted[at]) return previous[at] + val hash = hash(readInt(input, at)) + val candidate = heads[hash] + previous[at] = candidate + heads[hash] = at + inserted[at] = true + return candidate + } + + while (position <= searchLimit) { + if (position and 0x3FF == 0) ensureUnityOperationActive() + var candidate = insert(position) + var bestPosition = -1 + var bestLength = 0 + var attempts = MAX_CHAIN_ATTEMPTS + val oldest = maxOf(0, position - MAX_DISTANCE) + while (candidate >= oldest && attempts-- > 0) { + if (readInt(input, candidate) == readInt(input, position)) { + var count = MIN_MATCH + val maximum = matchLimit - position + while (count < maximum && input[candidate + count] == input[position + count]) count++ + if (count > bestLength) { + bestLength = count + bestPosition = candidate + if (count == maximum) break + } + } + candidate = previous[candidate] + } + + if (bestLength < MIN_MATCH) { + position++ + continue + } + + // A one-byte lazy check avoids committing to a short match when the next position has + // a substantially longer one. The next position is inserted here exactly once. + if (position + 1 <= searchLimit) { + var nextCandidate = insert(position + 1) + var nextBest = 0 + var nextAttempts = MAX_CHAIN_ATTEMPTS / 2 + val nextOldest = maxOf(0, position + 1 - MAX_DISTANCE) + while (nextCandidate >= nextOldest && nextAttempts-- > 0) { + if (readInt(input, nextCandidate) == readInt(input, position + 1)) { + var count = MIN_MATCH + val maximum = matchLimit - position - 1 + while (count < maximum && input[nextCandidate + count] == input[position + 1 + count]) count++ + if (count > nextBest) nextBest = count + } + nextCandidate = previous[nextCandidate] + } + if (nextBest > bestLength + 1) { + position++ + continue + } + } + + writeSequence(out, input, anchor, position, position - bestPosition, bestLength) + val matchEnd = position + bestLength + var insertAt = position + 1 + while (insertAt < matchEnd && insertAt <= searchLimit) { + // position + 1 may already have been inserted by the lazy check. + if (!inserted[insertAt]) insert(insertAt) + insertAt++ + } + position = matchEnd + anchor = matchEnd + } + + writeLastLiterals(out, input, anchor, length) + return out.toByteArray() + } + + private fun writeSequence( + out: ByteArrayOutputStream, + input: ByteArray, + anchor: Int, + matchPosition: Int, + distance: Int, + matchLength: Int, + ) { + check(distance in 1..MAX_DISTANCE) { "LZ4 match distance is out of range" } + val literalLength = matchPosition - anchor + val encodedMatchLength = matchLength - MIN_MATCH + out.write((minOf(literalLength, 15) shl 4) or minOf(encodedMatchLength, 15)) + writeLength(out, literalLength - 15) + out.write(input, anchor, literalLength) + out.write(distance and 0xFF) + out.write(distance ushr 8) + writeLength(out, encodedMatchLength - 15) + } + + private fun writeLastLiterals(out: ByteArrayOutputStream, input: ByteArray, anchor: Int, length: Int) { + val literalLength = length - anchor + out.write(minOf(literalLength, 15) shl 4) + writeLength(out, literalLength - 15) + out.write(input, anchor, literalLength) + } + + private fun literalOnly(input: ByteArray, length: Int): ByteArray { + val out = ByteArrayOutputStream(length + 8) + writeLastLiterals(out, input, 0, length) + return out.toByteArray() + } + + /** LZ4 writes an extension byte even when the nibble is 15 and the extra length is zero. */ + private fun writeLength(out: ByteArrayOutputStream, extra: Int) { + if (extra < 0) return + var left = extra + while (left >= 255) { + out.write(255) + left -= 255 + } + out.write(left) + } + + private fun readInt(input: ByteArray, offset: Int): Int = + (input[offset].toInt() and 0xFF) or + ((input[offset + 1].toInt() and 0xFF) shl 8) or + ((input[offset + 2].toInt() and 0xFF) shl 16) or + ((input[offset + 3].toInt() and 0xFF) shl 24) + + private fun hash(value: Int): Int = (value * -1_640_531_535).ushr(32 - HASH_BITS) +} diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt index 8b7fe54..e41fa90 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/SerializedFileReader.kt @@ -4,6 +4,8 @@ import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.RandomAccessFile +import java.nio.ByteBuffer +import java.nio.charset.CodingErrorAction /** * Reader for Unity serialized asset files ("*.assets", "CAB-*", "level*", ".sharedAssets", ...). @@ -24,13 +26,56 @@ internal object SerializedFileReader { private const val MAX_DECODE_BYTES = 256 * 1024 * 1024 private const val BUFFER_SIZE = 64 * 1024 - fun parse(file: File, dataFile: File): Pair { + fun parse(file: File, dataFile: File): Pair = + parseInternal(file, 0L, file.length(), dataFile, stageObjectData = true) + + /** Parses a serialized file stored inside an already-staged UnityFS data section. */ + fun parseEmbedded(file: File, fileOffset: Long, fileLength: Long): Pair = + parseInternal(file, fileOffset, fileLength, file, stageObjectData = false) + + /** Cheap header check that separates arbitrary entry bytes from an unsupported file version. */ + fun looksLikeSerializedHeader(file: File, fileOffset: Long, fileLength: Long): Boolean = runCatching { + if (fileOffset < 0 || fileLength < 20 || fileOffset > file.length() || fileLength > file.length() - fileOffset) { + return@runCatching false + } + RandomAccessFile(file, "r").use { input -> + input.seek(fileOffset) + var metadataSize = UnityBundleReader.readU32(input) + var declaredSize = UnityBundleReader.readU32(input) + val version = UnityBundleReader.readU32(input) + var dataOffset = UnityBundleReader.readU32(input) + val endian = input.readUnsignedByte() + input.skipBytes(3) + var headerSize = 20L + if (version >= 22 && fileLength >= 48) { + metadataSize = UnityBundleReader.readU32(input) + declaredSize = input.readLong() + dataOffset = input.readLong() + input.readLong() + headerSize = 48L + } + metadataSize > 0 && declaredSize in headerSize..fileLength && + dataOffset in headerSize..declaredSize && metadataSize <= dataOffset - headerSize && endian in 0..1 + } + }.getOrDefault(false) + + private fun parseInternal( + file: File, + sourceOffset: Long, + regionLength: Long, + dataFile: File, + stageObjectData: Boolean, + ): Pair { RandomAccessFile(file, "r").use { input -> + if (sourceOffset < 0 || regionLength < 0 || sourceOffset > input.length() || regionLength > input.length() - sourceOffset) { + throw UnityFormatException("Serialized file range is outside its container") + } + input.seek(sourceOffset) UnityBundleReader.readU32(input) // metadata size (32 bit, unused for v9+) val fileSize32 = UnityBundleReader.readU32(input) val version = UnityBundleReader.readU32(input) val dataOffset32 = UnityBundleReader.readU32(input) - if (version !in 9..22) throw UnityFormatException("Unsupported serialized file version $version") + if (version !in 9..22) throw UnityUnsupportedVersionException("Unsupported serialized file version $version") val bigEndian = input.readUnsignedByte() == 1 input.skipBytes(3) var fileSize = fileSize32 @@ -41,13 +86,13 @@ internal object SerializedFileReader { dataOffset = input.readLong() input.readLong() // unknown } - val headerSize = input.filePointer - if (fileSize < headerSize || fileSize > file.length()) throw UnityFormatException("Serialized file size is invalid") + val headerSize = input.filePointer - sourceOffset + if (fileSize < headerSize || fileSize > regionLength) throw UnityFormatException("Serialized file size is invalid") if (dataOffset < headerSize || dataOffset > fileSize) throw UnityFormatException("Serialized data offset is invalid") val metadataSize = dataOffset - headerSize if (metadataSize > MAX_STRING_BYTES * 64L) throw UnityFormatException("Serialized metadata is too large") val metadata = ByteArray(metadataSize.toInt()) - input.seek(headerSize) + input.seek(sourceOffset + headerSize) input.readFully(metadata) val table = UnityBundleReader.Cursor(metadata, bigEndian) fun pos(): Int = metadata.size - table.remaining @@ -114,19 +159,27 @@ internal object SerializedFileReader { slots += SerializedFileIndex.Slot(pathId, typeId, classId, start, size, startFieldPos, startIsI64, sizeFieldPos, name) } - val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE - if (dataSize > availableSpace) throw UnityFormatException("Not enough free space to stage Unity data") - dataFile.parentFile?.mkdirs() - input.seek(dataOffset) - FileOutputStream(dataFile).buffered(BUFFER_SIZE).use { out -> copyExactly(input, out, dataSize) } + val dataBaseOffset = if (stageObjectData) { + val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE + if (dataSize > availableSpace) throw UnityFormatException("Not enough free space to stage Unity data") + dataFile.parentFile?.mkdirs() + input.seek(sourceOffset + dataOffset) + FileOutputStream(dataFile).buffered(BUFFER_SIZE).use { out -> copyExactly(input, out, dataSize) } + 0L + } else { + sourceOffset + dataOffset + } val summary = UnityBundleSummary( "SerializedFile", version.toInt(), "", unityVersion, fileSize, dataSize, 0, entries, ) val index = SerializedFileIndex( source = file, + sourceOffset = sourceOffset, + dataBaseOffset = dataBaseOffset, version = version, bigEndian = bigEndian, + enableTypeTree = enableTypeTree, headerSize = headerSize.toInt(), dataOffset = dataOffset, metadataBytes = metadata, @@ -196,15 +249,36 @@ internal object SerializedFileReader { ) } +internal enum class SerializedDecodeIssue { + ENTRY_NOT_FOUND, + NO_TYPE_TREE, + UNSUPPORTED_CLASS, + OBJECT_TOO_LARGE, + MALFORMED_OBJECT, +} + +internal sealed class SerializedDecodeResult { + data class Success(val value: UVal) : SerializedDecodeResult() + data class Failure( + val issue: SerializedDecodeIssue, + val detail: String, + val cause: Throwable? = null, + ) : SerializedDecodeResult() +} + /** * Everything needed to decode, re-encode and rebuild a parsed serialized file. Object table - * field positions are recorded during parsing so a rebuild only patches offsets/sizes in place: - * the metadata length (and therefore the data offset) never changes. + * field positions are recorded during parsing so a rebuild only patches offsets/sizes in place. + * Rebuilds may resize existing objects, but cannot grow metadata or add/remove object-table rows; + * callers that need a different object count must use a full serialized-file authoring pipeline. */ internal class SerializedFileIndex( val source: File, + val sourceOffset: Long, + val dataBaseOffset: Long, val version: Long, val bigEndian: Boolean, + val enableTypeTree: Boolean, val headerSize: Int, val dataOffset: Long, val metadataBytes: ByteArray, @@ -227,61 +301,127 @@ internal class SerializedFileIndex( fun slotFor(entry: UnityBundleEntry): Slot? = slotsByName[entry.name] - fun hasTreeFor(entry: UnityBundleEntry): Boolean { - val slot = slotFor(entry) ?: return false - return trees.getOrNull(slot.typeIndex) != null || slot.classId == 49 - } - fun readObjectBytes(dataFile: File, slot: Slot): ByteArray { if (slot.size > MAX_DECODE_BYTES) throw UnityFormatException("Serialized object is too large to decode") val bytes = ByteArray(slot.size.toInt()) RandomAccessFile(dataFile, "r").use { input -> - input.seek(slot.start) + input.seek(dataBaseOffset + slot.start) input.readFully(bytes) } return bytes } - /** Decodes an object into an editable value tree; null when it cannot be decoded safely. */ - fun decode(dataFile: File, entry: UnityBundleEntry): UVal? { - val slot = slotFor(entry) ?: return null - return try { - val bytes = readObjectBytes(dataFile, slot) - val tree = trees.getOrNull(slot.typeIndex) - if (tree != null) { + /** Typed decode result; failures keep the concrete reason instead of disappearing as null. */ + fun decodeResult(dataFile: File, entry: UnityBundleEntry): SerializedDecodeResult { + val slot = slotFor(entry) ?: return SerializedDecodeResult.Failure( + SerializedDecodeIssue.ENTRY_NOT_FOUND, + "Entry does not belong to this serialized file", + ) + val bytes = try { + readObjectBytes(dataFile, slot) + } catch (e: UnityFormatException) { + return SerializedDecodeResult.Failure(SerializedDecodeIssue.OBJECT_TOO_LARGE, e.message ?: "Object is too large", e) + } catch (e: Exception) { + return SerializedDecodeResult.Failure(SerializedDecodeIssue.MALFORMED_OBJECT, e.message ?: "Object could not be read", e) + } + return decodeBytes(slot, bytes) + } + + private fun decodeBytes(slot: Slot, bytes: ByteArray): SerializedDecodeResult { + val tree = trees.getOrNull(slot.typeIndex) + if (tree != null) { + return try { val (value, consumed) = TypeTreeCodec.decodeChecked(tree, bytes, bigEndian) - if (consumed != bytes.size) null else value - } else if (slot.classId == 49) { - TypeTreeCodec.decodeTextAsset(bytes, bigEndian)?.let { (name, script) -> - UVal.Struct( - linkedMapOf( - "m_Name" to UVal.Str(name), - "m_Script" to UVal.Bytes(script), - ), + if (consumed != bytes.size) { + SerializedDecodeResult.Failure( + SerializedDecodeIssue.MALFORMED_OBJECT, + "Decoded ${consumed} of ${bytes.size} object bytes", ) + } else { + SerializedDecodeResult.Success(value) } - } else { - null + } catch (e: Exception) { + SerializedDecodeResult.Failure( + SerializedDecodeIssue.MALFORMED_OBJECT, + e.message ?: "Object does not match its type tree", + e, + ) } - } catch (e: Exception) { - null } + if (slot.classId == TEXT_ASSET_CLASS_ID) { + val decoded = try { + TypeTreeCodec.decodeTextAsset(bytes, bigEndian) + } catch (e: Exception) { + return SerializedDecodeResult.Failure( + SerializedDecodeIssue.MALFORMED_OBJECT, + "TextAsset does not match the built-in fallback layout", + e, + ) + } + val (name, script) = decoded + val scriptText = decodeUtf8(script) + val scriptValue: UVal = if (scriptText != null) UVal.Str(scriptText) else UVal.Bytes(script) + return SerializedDecodeResult.Success( + UVal.Struct( + linkedMapOf( + "m_Name" to UVal.Str(name), + "m_Script" to scriptValue, + ), + ), + ) + } + val className = SerializedFileReader.className(slot.classId) + val detail = when (slot.classId) { + MONO_BEHAVIOUR_CLASS_ID -> "MonoBehaviour custom fields require a type tree or managed script schema" + FONT_CLASS_ID -> "Font layout requires a type tree for this Unity version" + else -> "$className has no type tree and no safe built-in fallback" + } + return SerializedDecodeResult.Failure( + if (enableTypeTree) SerializedDecodeIssue.UNSUPPORTED_CLASS else SerializedDecodeIssue.NO_TYPE_TREE, + detail, + ) } - /** Re-encodes a (possibly edited) value tree back into raw object bytes. */ + /** Re-encodes a value and immediately decodes it again with the same schema. */ fun encode(dataFile: File, entry: UnityBundleEntry, value: UVal): ByteArray { val slot = slotFor(entry) ?: throw UnityFormatException("Entry does not belong to this serialized file") val tree = trees.getOrNull(slot.typeIndex) - return if (tree != null) { + val encoded = if (tree != null) { TypeTreeCodec.encode(tree, value, bigEndian) - } else if (slot.classId == 49 && value is UVal.Struct) { + } else if (slot.classId == TEXT_ASSET_CLASS_ID && value is UVal.Struct) { val name = (value.fields["m_Name"] as? UVal.Str)?.value - val script = (value.fields["m_Script"] as? UVal.Bytes)?.data - if (name == null || script == null) throw UnityFormatException("TextAsset value is incomplete") + ?: throw UnityFormatException("TextAsset value is missing m_Name") + val script = when (val scriptValue = value.fields["m_Script"]) { + is UVal.Str -> scriptValue.value.toByteArray(Charsets.UTF_8) + is UVal.Bytes -> scriptValue.data + else -> throw UnityFormatException("TextAsset value is missing m_Script") + } TypeTreeCodec.encodeTextAsset(name, script, bigEndian) } else { - throw UnityFormatException("This object has no type tree and cannot be re-encoded") + throw UnityFormatException("${SerializedFileReader.className(slot.classId)} has no type information and cannot be re-encoded safely") } + when (val verified = decodeBytes(slot, encoded)) { + is SerializedDecodeResult.Failure -> throw UnityFormatException( + "Re-encoded object failed its self-check: ${verified.detail}", + verified.cause, + ) + is SerializedDecodeResult.Success -> { + if (TypeTreeCodec.exportStrings(verified.value) != TypeTreeCodec.exportStrings(value)) { + throw UnityFormatException("Re-encoded object failed its text round-trip self-check") + } + } + } + return encoded + } + + private fun decodeUtf8(bytes: ByteArray): String? = try { + Charsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString() + } catch (_: Exception) { + null } fun objectName(value: UVal): String? = @@ -324,7 +464,10 @@ internal class SerializedFileIndex( if (!output.createNewFile()) throw IOException("Output already exists: ${output.name}") try { val header = ByteArray(headerSize) - RandomAccessFile(source, "r").use { it.readFully(header) } + RandomAccessFile(source, "r").use { + it.seek(sourceOffset) + it.readFully(header) + } if (version >= 22) { writeField(header, 24, newFileSize, 8, bigEndian = true) } else { @@ -350,7 +493,7 @@ internal class SerializedFileIndex( } } } else { - staged.seek(slot.start) + staged.seek(dataBaseOffset + slot.start) var left = slot.size while (left > 0) { val read = staged.read(buffer, 0, minOf(left, buffer.size.toLong()).toInt()) @@ -395,5 +538,8 @@ internal class SerializedFileIndex( companion object { private const val MAX_DECODE_BYTES = 256 * 1024 * 1024 + private const val TEXT_ASSET_CLASS_ID = 49 + private const val MONO_BEHAVIOUR_CLASS_ID = 114 + private const val FONT_CLASS_ID = 128 } } diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt b/app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt index c5501c4..59ad8d1 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/TypeTreeCodec.kt @@ -579,14 +579,17 @@ internal object TypeTreeCodec { } /** TextAsset fallback decoding (used when no type tree is available). */ - fun decodeTextAsset(data: ByteArray, bigEndian: Boolean): Pair? { - return try { + fun decodeTextAsset(data: ByteArray, bigEndian: Boolean): Pair { + try { val reader = TTReader(data, bigEndian) val name = reader.readAlignedString() val script = reader.readByteArray() - name to script + if (reader.pos != data.size) throw UnityFormatException("TextAsset has unexpected trailing bytes") + return name to script + } catch (e: UnityFormatException) { + throw e } catch (e: Exception) { - null + throw UnityFormatException("TextAsset fallback decode failed", e) } } diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt index 25f2d6a..0e6194a 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt @@ -12,9 +12,13 @@ import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.io.InputStream +import java.io.InterruptedIOException import java.io.OutputStream import java.io.RandomAccessFile +import java.security.DigestOutputStream import java.security.MessageDigest +import java.util.concurrent.locks.ReentrantReadWriteLock +import java.util.logging.Logger /** Unity container formats recognized by Strata's built-in Unity asset browser. */ enum class UnityFileKind { @@ -66,7 +70,52 @@ data class UnityTextInfo( val sample: String, ) -class UnityFormatException(message: String, cause: Throwable? = null) : IOException(message, cause) +enum class UnityTextUnavailableReason { + NOT_SERIALIZED_FILE, + NO_TYPE_INFORMATION, + UNSUPPORTED_OBJECT, + UNSUPPORTED_VERSION, + NO_TEXT, + TOO_MANY_OBJECTS, + DECODE_FAILED, + DOCUMENT_CLOSED, +} + +/** Per-entry text capability, including a diagnostic when editing is unsafe or impossible. */ +sealed class UnityTextInspection { + data class Editable(val info: UnityTextInfo) : UnityTextInspection() + data class Unavailable( + val reason: UnityTextUnavailableReason, + val diagnostic: String, + ) : UnityTextInspection() +} + +open class UnityFormatException(message: String, cause: Throwable? = null) : IOException(message, cause) + +class UnityDocumentClosedException : UnityFormatException( + "Unity document is closed and its staged data is unavailable", +) + +class UnityOperationCancelledException : InterruptedIOException("Unity operation was cancelled") + +class UnityUnsupportedVersionException(message: String) : UnityFormatException(message) + +internal enum class UnityFsHashConvention { + ZERO, + UNCOMPRESSED_MD5, + COMPRESSED_MD5, + PRESERVE, +} + +/** Source layout choices that must survive a normalized UnityFS rewrite. */ +internal data class UnityFsWriteProfile( + val preferredCodec: Int, + val sourceFlags: Long, + val hashConvention: UnityFsHashConvention, + val sourceHash: ByteArray, + val declaredBundleSize: Long, + val physicalFileSize: Long, +) /** * A parsed UnityFS bundle. The decompressed data stream is staged in app cache so entry reads @@ -77,62 +126,392 @@ class UnityBundleDocument internal constructor( val summary: UnityBundleSummary, internal val dataFile: File, internal val serialized: SerializedFileIndex? = null, + private val unityFsProfile: UnityFsWriteProfile? = null, ) : Closeable { + private data class EmbeddedPart( + val partIndex: Int, + val relativeOffset: Long, + val declaredSize: Long, + val summary: UnityBundleSummary, + val index: SerializedFileIndex, + ) + + private sealed class EmbeddedParse { + data class Success( + val parts: List, + val parsedBytes: Long, + ) : EmbeddedParse() { + val objectCount: Int get() = parts.sumOf { it.summary.entries.size } + } + data class Failure( + val reason: UnityTextUnavailableReason, + val diagnostic: String, + ) : EmbeddedParse() + } + + private val embeddedLock = Any() + private val embeddedIndexes = HashMap() + private val lifecycleLock = ReentrantReadWriteLock(true) + @Volatile private var closed = false /** Repacking is implemented for UnityFS bundles and serialized files; legacy containers are read-only. */ val repackSupported: Boolean get() = summary.signature == "UnityFS" || serialized != null - /** True when objects can be decoded through type trees and their texts edited. */ - val supportsTextEditing: Boolean get() = serialized != null + /** True when this document can contain editable serialized objects. Check individual entries too. */ + val supportsTextEditing: Boolean get() = serialized != null || summary.signature == "UnityFS" + + /** Exact, per-entry predicate. Parsing of a UnityFS child is lazy and metadata-only. */ + fun supportsTextEditing(entry: UnityBundleEntry): Boolean = inspectText(entry) is UnityTextInspection.Editable - /** Text statistics for one serialized-file object; null when it holds no decodable text. */ - fun textInfo(entry: UnityBundleEntry): UnityTextInfo? { - val ser = serialized ?: return null - val slot = ser.slotFor(entry) ?: return null - if (!ser.hasTreeFor(entry)) return null - val value = ser.decode(dataFile, entry) ?: return null - val (count, bytes, sample) = TypeTreeCodec.textStats(value) - if (count == 0) return null - return UnityTextInfo(ser.objectName(value), SerializedFileReader.className(slot.classId), count, bytes, sample) + /** Returns either text statistics or a concrete reason that this entry is not editable. */ + fun inspectText(entry: UnityBundleEntry): UnityTextInspection = try { + withOpenDocument { inspectTextOpen(entry) } + } catch (_: UnityDocumentClosedException) { + unavailable(UnityTextUnavailableReason.DOCUMENT_CLOSED, "Unity document is closed") } - /** Flat "path -> value" map of every string inside the object, in decode order. */ - fun exportTexts(entry: UnityBundleEntry): LinkedHashMap? { - val ser = serialized ?: return null - val value = ser.decode(dataFile, entry) ?: return null - return TypeTreeCodec.exportStrings(value) + private fun inspectTextOpen(entry: UnityBundleEntry): UnityTextInspection = try { + requireEntry(entry) + val standalone = serialized + if (standalone != null) { + inspectObject(standalone, entry) + } else if (summary.signature == "UnityFS") { + inspectEmbedded(entry) + } else { + unavailable(UnityTextUnavailableReason.NOT_SERIALIZED_FILE, "Entry is not a serialized file") + } + } catch (e: UnityDocumentClosedException) { + throw e + } catch (e: Exception) { + unavailable(UnityTextUnavailableReason.DECODE_FAILED, e.message ?: "Text inspection failed") } - /** Re-encodes the object with the edited strings applied; returns the new raw object bytes. */ - fun rebuildTexts(entry: UnityBundleEntry, edits: Map): ByteArray { - val ser = serialized ?: throw UnityFormatException("This document does not support text editing") - val value = ser.decode(dataFile, entry) ?: throw UnityFormatException("Object cannot be decoded for editing") - TypeTreeCodec.applyStrings(value, edits) - return ser.encode(dataFile, entry, value) + /** Compatibility API: null means callers should use [inspectText] to retrieve the reason. */ + fun textInfo(entry: UnityBundleEntry): UnityTextInfo? = + (inspectText(entry) as? UnityTextInspection.Editable)?.info + + /** Flat "path -> value" map of every string inside the entry, in decode order. */ + fun exportTexts(entry: UnityBundleEntry): LinkedHashMap? = + withOpenDocument { exportTextsOpen(entry) } + + private fun exportTextsOpen(entry: UnityBundleEntry): LinkedHashMap? { + requireEntry(entry) + val standalone = serialized + if (standalone != null) { + val value = decodeOrThrow(standalone, entry) + return TypeTreeCodec.exportStrings(value).takeIf { it.isNotEmpty() } + } + val embedded = embeddedOrThrow(entry) + if (embedded.objectCount > MAX_EMBEDDED_TEXT_OBJECTS) { + throw UnityFormatException("Serialized entry has too many objects to scan safely") + } + val exported = LinkedHashMap() + embedded.parts.forEach { part -> + part.summary.entries.forEach { objectEntry -> + val decoded = part.index.decodeResult(dataFile, objectEntry) + if (decoded is SerializedDecodeResult.Success) { + val slot = part.index.slotFor(objectEntry) ?: return@forEach + TypeTreeCodec.exportStrings(decoded.value).forEach { (path, text) -> + exported[embeddedPath(part.partIndex, slot.pathId, path)] = text + } + } + } + } + return exported.takeIf { it.isNotEmpty() } } - fun copyEntry(entry: UnityBundleEntry, output: File) { + /** Re-encodes the entry with edited strings applied; returns its new raw bytes. */ + fun rebuildTexts(entry: UnityBundleEntry, edits: Map): ByteArray = + withOpenDocument { rebuildTextsOpen(entry, edits) } + + private fun rebuildTextsOpen(entry: UnityBundleEntry, edits: Map): ByteArray { requireEntry(entry) - output.parentFile?.mkdirs() - if (!output.createNewFile()) throw IOException("Output already exists: ${output.name}") + val standalone = serialized + if (standalone != null) { + val value = decodeOrThrow(standalone, entry) + TypeTreeCodec.applyStrings(value, edits) + return standalone.encode(dataFile, entry, value) + } + + val embedded = embeddedOrThrow(entry) + val editsByPart = LinkedHashMap>>() + edits.forEach { (path, text) -> + val match = EMBEDDED_PATH.matchEntire(path) + ?: throw UnityFormatException("Edited JSON contains an invalid embedded text path: $path") + val partIndex = match.groupValues[1].toIntOrNull() + ?: throw UnityFormatException("Edited JSON contains an invalid serialized-file index: $path") + val pathId = match.groupValues[2].toLongOrNull() + ?: throw UnityFormatException("Edited JSON contains an invalid object id: $path") + val localPath = match.groupValues[3] + editsByPart.getOrPut(partIndex) { LinkedHashMap() } + .getOrPut(pathId) { LinkedHashMap() }[localPath] = text + } + val knownParts = embedded.parts.map { it.partIndex }.toSet() + val unknownPart = editsByPart.keys.firstOrNull { it !in knownParts } + if (unknownPart != null) throw UnityFormatException("Edited JSON refers to unknown serialized file $unknownPart") + + val scratch = dataFile.parentFile ?: throw IOException("Unity cache directory is missing") + val rebuiltEntry = File(scratch, ".embedded-${System.nanoTime()}.entry") + val temporaryFiles = ArrayList() + try { + RandomAccessFile(dataFile, "r").use { sourceData -> + FileOutputStream(rebuiltEntry).buffered(BUFFER_SIZE).use { combinedOut -> + var sourceCursor = 0L + embedded.parts.forEach { part -> + if (part.relativeOffset < sourceCursor) { + throw UnityFormatException("Embedded serialized-file ranges overlap") + } + val gap = part.relativeOffset - sourceCursor + if (gap > 0) { + sourceData.seek(entry.offset + sourceCursor) + copyExactly(sourceData, combinedOut, gap) + } + val partEdits = editsByPart[part.partIndex] + if (partEdits.isNullOrEmpty()) { + sourceData.seek(entry.offset + part.relativeOffset) + copyExactly(sourceData, combinedOut, part.declaredSize) + } else { + val slotsByPathId = part.index.slots.associateBy { it.pathId } + val objectReplacements = LinkedHashMap() + partEdits.forEach { (pathId, objectEdits) -> + val slot = slotsByPathId[pathId] + ?: throw UnityFormatException("Edited JSON refers to unknown serialized object $pathId") + val objectEntry = part.summary.entries.firstOrNull { it.name == slot.entryName } + ?: throw UnityFormatException("Serialized object table is inconsistent for $pathId") + val value = decodeOrThrow(part.index, objectEntry) + TypeTreeCodec.applyStrings(value, objectEdits) + val encoded = part.index.encode(dataFile, objectEntry, value) + val replacement = File(scratch, ".object-${part.partIndex}-$pathId-${System.nanoTime()}.bin") + replacement.writeBytes(encoded) + temporaryFiles += replacement + objectReplacements[slot.entryName] = replacement + } + val rebuiltPart = File(scratch, ".part-${part.partIndex}-${System.nanoTime()}.assets") + temporaryFiles += rebuiltPart + part.index.rebuild(rebuiltPart, dataFile, objectReplacements, part.summary.entries) + rebuiltPart.inputStream().buffered(BUFFER_SIZE).use { it.copyTo(combinedOut, BUFFER_SIZE) } + } + sourceCursor = checkedAdd(part.relativeOffset, part.declaredSize, "Embedded serialized-file range overflows") + } + if (sourceCursor < entry.size) { + sourceData.seek(entry.offset + sourceCursor) + copyExactly(sourceData, combinedOut, entry.size - sourceCursor) + } + } + } + if (rebuiltEntry.length() > MAX_REBUILD_BYTES || rebuiltEntry.length() > Int.MAX_VALUE) { + throw UnityFormatException("Rebuilt serialized entry is too large for the text-editing API") + } + return rebuiltEntry.readBytes() + } finally { + temporaryFiles.forEach { it.delete() } + rebuiltEntry.delete() + } + } + + private fun inspectObject(index: SerializedFileIndex, entry: UnityBundleEntry): UnityTextInspection { + return when (val decoded = index.decodeResult(dataFile, entry)) { + is SerializedDecodeResult.Failure -> inspectionFailure(decoded) + is SerializedDecodeResult.Success -> { + val (count, bytes, sample) = TypeTreeCodec.textStats(decoded.value) + if (count == 0) { + unavailable(UnityTextUnavailableReason.NO_TEXT, "Decoded object contains no string fields") + } else { + val slot = index.slotFor(entry) + ?: return unavailable(UnityTextUnavailableReason.DECODE_FAILED, "Serialized object table is inconsistent") + UnityTextInspection.Editable( + UnityTextInfo( + index.objectName(decoded.value), + SerializedFileReader.className(slot.classId), + count, + bytes, + sample, + ), + ) + } + } + } + } + + private fun inspectEmbedded(entry: UnityBundleEntry): UnityTextInspection { + val embedded = when (val parsed = embedded(entry)) { + is EmbeddedParse.Failure -> return unavailable(parsed.reason, parsed.diagnostic) + is EmbeddedParse.Success -> parsed + } + if (embedded.objectCount > MAX_EMBEDDED_TEXT_OBJECTS) { + return unavailable(UnityTextUnavailableReason.TOO_MANY_OBJECTS, "Serialized entry has ${embedded.objectCount} objects") + } + var count = 0 + var bytes = 0L + var sample = "" + var decodedObjects = 0 + var namedObject: String? = null + var firstFailure: SerializedDecodeResult.Failure? = null + embedded.parts.forEach { part -> + part.summary.entries.forEach { objectEntry -> + when (val decoded = part.index.decodeResult(dataFile, objectEntry)) { + is SerializedDecodeResult.Failure -> if (firstFailure == null) firstFailure = decoded + is SerializedDecodeResult.Success -> { + decodedObjects++ + val stats = TypeTreeCodec.textStats(decoded.value) + if (stats.first > 0) { + count += stats.first + bytes += stats.second + if (stats.third.length > sample.length) sample = stats.third + if (namedObject == null) namedObject = part.index.objectName(decoded.value) + } + } + } + } + } + if (count > 0) { + return UnityTextInspection.Editable( + UnityTextInfo(namedObject ?: entry.displayName, "SerializedFile", count, bytes, sample), + ) + } + if (decodedObjects > 0) { + return unavailable(UnityTextUnavailableReason.NO_TEXT, "Serialized entry was decoded but contains no string fields") + } + return firstFailure?.let(::inspectionFailure) + ?: unavailable(UnityTextUnavailableReason.NO_TEXT, "Serialized entry contains no objects") + } + + private fun inspectionFailure(failure: SerializedDecodeResult.Failure): UnityTextInspection.Unavailable { + val reason = when (failure.issue) { + SerializedDecodeIssue.NO_TYPE_TREE -> UnityTextUnavailableReason.NO_TYPE_INFORMATION + SerializedDecodeIssue.UNSUPPORTED_CLASS -> UnityTextUnavailableReason.UNSUPPORTED_OBJECT + SerializedDecodeIssue.OBJECT_TOO_LARGE -> UnityTextUnavailableReason.DECODE_FAILED + SerializedDecodeIssue.ENTRY_NOT_FOUND, SerializedDecodeIssue.MALFORMED_OBJECT -> UnityTextUnavailableReason.DECODE_FAILED + } + return unavailable(reason, failure.detail) + } + + private fun decodeOrThrow(index: SerializedFileIndex, entry: UnityBundleEntry): UVal = + when (val decoded = index.decodeResult(dataFile, entry)) { + is SerializedDecodeResult.Success -> decoded.value + is SerializedDecodeResult.Failure -> throw UnityFormatException(decoded.detail, decoded.cause) + } + + private fun embeddedOrThrow(entry: UnityBundleEntry): EmbeddedParse.Success = when (val parsed = embedded(entry)) { + is EmbeddedParse.Success -> parsed + is EmbeddedParse.Failure -> if (parsed.reason == UnityTextUnavailableReason.UNSUPPORTED_VERSION) { + throw UnityUnsupportedVersionException(parsed.diagnostic) + } else { + throw UnityFormatException(parsed.diagnostic) + } + } + + private fun embedded(entry: UnityBundleEntry): EmbeddedParse = synchronized(embeddedLock) { + embeddedIndexes[entry]?.let { return@synchronized it } + if (closed || !dataFile.isFile) { + return@synchronized EmbeddedParse.Failure( + UnityTextUnavailableReason.DOCUMENT_CLOSED, + "Unity document is closed and its staged data is unavailable", + ) + } + val parts = ArrayList() + var cursor = 0L + var firstFailure: Exception? = null + while (entry.size - cursor >= SERIALIZED_HEADER_MIN_BYTES) { + val remaining = entry.size - cursor + if (!SerializedFileReader.looksLikeSerializedHeader(dataFile, entry.offset + cursor, remaining)) break + val parsed = try { + SerializedFileReader.parseEmbedded(dataFile, entry.offset + cursor, remaining) + } catch (e: Exception) { + firstFailure = e + break + } + val nestedSummary = parsed.first + if (nestedSummary.fileSize <= 0 || nestedSummary.fileSize > remaining) { + firstFailure = UnityFormatException("Embedded serialized file has an invalid declared size") + break + } + parts += EmbeddedPart(parts.size, cursor, nestedSummary.fileSize, nestedSummary, parsed.second) + cursor = checkedAdd(cursor, nestedSummary.fileSize, "Embedded serialized-file sizes overflow") + } + val result = if (parts.isEmpty()) { + EmbeddedParse.Failure( + if (firstFailure is UnityUnsupportedVersionException) { + UnityTextUnavailableReason.UNSUPPORTED_VERSION + } else { + UnityTextUnavailableReason.NOT_SERIALIZED_FILE + }, + firstFailure?.message ?: "Entry is not a supported serialized file", + ) + } else { + EmbeddedParse.Success(parts, cursor) + } + embeddedIndexes[entry] = result + result + } + + internal val cachedEmbeddedEntryCount: Int + get() = synchronized(embeddedLock) { embeddedIndexes.size } + + private fun embeddedPath(partIndex: Int, pathId: Long, path: String): String = + "files[$partIndex].objects[$pathId].$path" + + private fun unavailable(reason: UnityTextUnavailableReason, diagnostic: String) = + UnityTextInspection.Unavailable(reason, diagnostic) + + private inline fun withOpenDocument(block: () -> T): T { + val read = lifecycleLock.readLock() + read.lock() + try { + if (closed || !dataFile.isFile) throw UnityDocumentClosedException() + return block() + } finally { + read.unlock() + } + } + + fun copyEntry(entry: UnityBundleEntry, output: File) = + withOpenDocument { copyEntryOpen(entry, output) } + + private fun copyEntryOpen(entry: UnityBundleEntry, output: File) { + requireEntry(entry) + val parent = output.parentFile ?: throw IOException("Output directory is missing") + parent.mkdirs() + if (output.exists()) throw IOException("Output already exists: ${output.name}") + val temporary = temporarySibling(output, "extract") try { RandomAccessFile(dataFile, "r").use { input -> - FileOutputStream(output).use { out -> + FileOutputStream(temporary).use { out -> input.seek(entry.offset) copyExactly(input, out, entry.size) + out.fd.sync() } } + if (temporary.length() != entry.size) throw IOException("Extracted Unity entry failed size verification") + publishTemporary(temporary, output) } catch (e: Throwable) { - output.delete() + temporary.delete() throw e } } /** Writes a normalized UnityFS bundle. Inputs are never overwritten. */ - fun repack(output: File, replacements: Map = emptyMap()) { + fun repack(output: File, replacements: Map = emptyMap()) = + withOpenDocument { repackOpen(output, replacements) } + + private fun repackOpen(output: File, replacements: Map) { if (!repackSupported) throw UnityFormatException("This Unity format is read-only; repacking needs a UnityFS bundle or serialized file") if (output.canonicalFile == source.canonicalFile) throw IOException("Output must not replace the source bundle") if (output.exists()) throw IOException("Output already exists: ${output.name}") + val parent = output.parentFile ?: throw IOException("Output directory is missing") + parent.mkdirs() + val temporary = temporarySibling(output, "repack") + try { + repackTo(temporary, replacements) + RandomAccessFile(temporary, "rw").use { it.fd.sync() } + publishTemporary(temporary, output) + } catch (e: Throwable) { + temporary.delete() + throw e + } + } + + private fun repackTo(output: File, replacements: Map) { val serializedIndex = serialized if (serializedIndex != null) { serializedIndex.rebuild(output, dataFile, replacements, summary.entries) @@ -187,7 +566,8 @@ class UnityBundleDocument internal constructor( val updated = summary.entries.mapIndexed { index, entry -> entry.copy(offset = outputOffsets[index], size = replacements[entry.name]?.length() ?: entry.size) } - writeNormalizedUnityFs(staged, output, summary, updated, outputCursor) + writeNormalizedUnityFs(staged, output, source, summary, updated, outputCursor, unityFsProfile) + UnityBundleReader.verifyUnityFsOutput(output, updated, outputCursor, unityFsProfile) } catch (e: Throwable) { output.delete() throw e @@ -204,97 +584,246 @@ class UnityBundleDocument internal constructor( } override fun close() { - dataFile.delete() - dataFile.parentFile?.delete() + // A writer lock makes close wait for every in-flight copy/decode/repack operation. New + // operations cannot acquire a read lease after [closed] is set, so staged data is never + // deleted underneath a worker thread. + val write = lifecycleLock.writeLock() + write.lock() + try { + if (closed) return + closed = true + synchronized(embeddedLock) { embeddedIndexes.clear() } + dataFile.delete() + dataFile.parentFile?.delete() + } finally { + write.unlock() + } } private companion object { + private val PUBLISH_LOCK = Any() + private val LOGGER = Logger.getLogger("dev.cluvex.strata.core.unity") + + fun temporarySibling(output: File, purpose: String): File { + val parent = output.parentFile ?: throw IOException("Output directory is missing") + repeat(100) { + val candidate = File(parent, ".${output.name}.${System.nanoTime()}.$purpose.tmp") + if (!candidate.exists()) return candidate + } + throw IOException("Could not allocate a unique temporary output") + } + + fun publishTemporary(temporary: File, output: File) { + synchronized(PUBLISH_LOCK) { + if (output.exists()) throw IOException("Output already exists: ${output.name}") + if (!temporary.renameTo(output)) throw IOException("Could not atomically publish ${output.name}") + } + } + const val BUFFER_SIZE = 64 * 1024 - const val OUTPUT_BLOCK_SIZE = 32 * 1024 * 1024 + const val MAX_EMBEDDED_TEXT_OBJECTS = 5_000 + const val MAX_REBUILD_BYTES = 256L * 1024 * 1024 + val EMBEDDED_PATH = Regex("""files\[(\d+)]\.objects\[(-?\d+)]\.(.+)""") + const val SERIALIZED_HEADER_MIN_BYTES = 20L + + // The measured Unity 2022 sample uses 128 KiB blocks. This is small enough for LZ4's + // 64 KiB match window to remain effective and bounds encoder memory on very large bundles. + const val OUTPUT_BLOCK_SIZE = 128 * 1024 + + data class OutputBlock(val uncompressed: Int, val compressed: Int, val flags: Int) fun writeNormalizedUnityFs( data: File, output: File, + source: File, original: UnityBundleSummary, entries: List, dataSize: Long, + profile: UnityFsWriteProfile?, ) { val blockCountLong = if (dataSize == 0L) 0L else 1L + (dataSize - 1) / OUTPUT_BLOCK_SIZE if (blockCountLong > MAX_BLOCKS) throw UnityFormatException("UnityFS has too many data blocks") - val blockCount = blockCountLong.toInt() - val blockInfo = ByteArrayOutputStream().use { bytes -> - DataOutputStream(bytes).use { out -> - out.write(md5(data)) - out.writeInt(blockCount) - var left = dataSize - repeat(blockCount) { - val size = minOf(left, OUTPUT_BLOCK_SIZE.toLong()).toInt() - out.writeInt(size) - out.writeInt(size) - out.writeShort(0) // Uncompressed data block. - left -= size + val preferredCodec = profile?.preferredCodec?.takeIf { it == LZ4 || it == LZ4HC } ?: LZ4HC + val convention = profile?.hashConvention ?: UnityFsHashConvention.ZERO + val uncompressedDigest = if (convention == UnityFsHashConvention.UNCOMPRESSED_MD5) MessageDigest.getInstance("MD5") else null + val compressedDigest = if (convention == UnityFsHashConvention.COMPRESSED_MD5) MessageDigest.getInstance("MD5") else null + val parent = output.parentFile ?: throw IOException("Output directory is missing") + val compressedData = File(parent, ".${output.name}.${System.nanoTime()}.blocks") + val blocks = ArrayList(blockCountLong.toInt()) + var rawFallbackBlocks = 0 + + try { + FileInputStream(data).buffered(BUFFER_SIZE).use { input -> + FileOutputStream(compressedData).buffered(BUFFER_SIZE).use { blockOut -> + val buffer = ByteArray(OUTPUT_BLOCK_SIZE) + var left = dataSize + while (left > 0) { + ensureUnityOperationActive() + val size = minOf(left, OUTPUT_BLOCK_SIZE.toLong()).toInt() + readExactly(input, buffer, size) + uncompressedDigest?.update(buffer, 0, size) + val encoded = try { + Lz4BlockEncoder.encode(buffer, size) + } catch (_: Exception) { + null + } + if (encoded != null && encoded.size < size) { + blockOut.write(encoded) + compressedDigest?.update(encoded) + blocks += OutputBlock(size, encoded.size, preferredCodec) + } else { + blockOut.write(buffer, 0, size) + compressedDigest?.update(buffer, 0, size) + blocks += OutputBlock(size, size, UNCOMPRESSED) + rawFallbackBlocks++ + } + left -= size + } + if (input.read() >= 0) throw IOException("UnityFS staging data grew while it was being compressed") } - out.writeInt(entries.size) - entries.forEach { entry -> - out.writeLong(entry.offset) - out.writeLong(entry.size) - out.writeInt(entry.flags.toInt()) - writeCString(out, entry.name) + } + if (rawFallbackBlocks > 0) { + LOGGER.fine("UnityFS repack used raw fallback for $rawFallbackBlocks of ${blocks.size} data blocks") + } + + val storedHash = when (convention) { + UnityFsHashConvention.ZERO -> ByteArray(16) + UnityFsHashConvention.UNCOMPRESSED_MD5 -> uncompressedDigest!!.digest() + UnityFsHashConvention.COMPRESSED_MD5 -> compressedDigest!!.digest() + UnityFsHashConvention.PRESERVE -> profile?.sourceHash?.copyOf() ?: ByteArray(16) + } + val blockInfo = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + out.write(storedHash) + out.writeInt(blocks.size) + blocks.forEach { block -> + out.writeInt(block.uncompressed) + out.writeInt(block.compressed) + out.writeShort(block.flags) + } + out.writeInt(entries.size) + entries.forEach { entry -> + out.writeLong(entry.offset) + out.writeLong(entry.size) + out.writeInt(entry.flags.toInt()) + writeCString(out, entry.name) + } } + bytes.toByteArray() + } + val compressedInfoCandidate = try { + Lz4BlockEncoder.encode(blockInfo) + } catch (_: Exception) { + null + } + val infoCodec: Int + val infoPayload: ByteArray + if (compressedInfoCandidate != null && compressedInfoCandidate.size < blockInfo.size) { + infoCodec = preferredCodec + infoPayload = compressedInfoCandidate + } else { + infoCodec = UNCOMPRESSED + infoPayload = blockInfo } - bytes.toByteArray() - } - val headerPrefix = ByteArrayOutputStream().use { bytes -> - DataOutputStream(bytes).use { out -> - writeCString(out, "UnityFS") - out.writeInt(original.formatVersion) - writeCString(out, original.playerVersion) - writeCString(out, original.engineVersion) - // Size is appended below after the total has been calculated. + + val headerPrefix = ByteArrayOutputStream().use { bytes -> + DataOutputStream(bytes).use { out -> + writeCString(out, "UnityFS") + out.writeInt(original.formatVersion) + writeCString(out, original.playerVersion) + writeCString(out, original.engineVersion) + // Size is appended below after the compressed table and payload are known. + } + bytes.toByteArray() } - bytes.toByteArray() - } - val headerSize = headerPrefix.size + 8 + 4 + 4 + 4 - // UnityFS format version 7 and later align the block table to a 16-byte boundary, - // matching the quirk that some 2019.4.15+ games align version 6 bundles as well. - val alignmentPadding = - if (original.formatVersion >= 7 || UnityBundleReader.usesLegacyBlockAlignment(original.engineVersion)) { - (16 - headerSize % 16) % 16 + val headerSize = headerPrefix.size + 8 + 4 + 4 + 4 + // UnityFS format version 7 and later align the block table to a 16-byte boundary, + // matching the quirk that some 2019.4.15+ games apply to version 6 bundles too. + val alignmentPadding = + if (original.formatVersion >= 7 || UnityBundleReader.usesLegacyBlockAlignment(original.engineVersion)) { + (16 - headerSize % 16) % 16 + } else { + 0 + } + // Keep the source's post-table alignment convention. Old engines using 0x200 for + // UnityCN encryption were rejected during parsing, so it is safe to preserve here. + val sourceLayoutFlags = profile?.sourceFlags?.and(PRESERVED_LAYOUT_FLAGS) ?: 0L + val outputFlags = sourceLayoutFlags or BLOCKS_AND_DIRECTORY_COMBINED or infoCodec.toLong() + val beforeData = checkedAdd( + (headerSize + alignmentPadding).toLong(), + infoPayload.size.toLong(), + "UnityFS is too large", + ) + val dataPadding = if (outputFlags and BLOCK_INFO_NEEDS_PADDING != 0L) { + ((16L - beforeData % 16L) % 16L).toInt() } else { 0 } - val totalSize = checkedAdd(checkedAdd((headerSize + alignmentPadding).toLong(), blockInfo.size.toLong(), "UnityFS is too large"), dataSize, "UnityFS is too large") - try { + val declaredSize = checkedAdd( + checkedAdd(beforeData, dataPadding.toLong(), "UnityFS is too large"), + compressedData.length(), + "UnityFS is too large", + ) + val trailingSize = profile?.let { (it.physicalFileSize - it.declaredBundleSize).coerceAtLeast(0L) } ?: 0L + FileOutputStream(output).buffered(BUFFER_SIZE).use { fileOut -> DataOutputStream(fileOut).use { out -> out.write(headerPrefix) - out.writeLong(totalSize) - out.writeInt(blockInfo.size) + out.writeLong(declaredSize) + out.writeInt(infoPayload.size) out.writeInt(blockInfo.size) - out.writeInt(BLOCK_INFO_AT_START) + out.writeInt(outputFlags.toInt()) if (alignmentPadding > 0) out.write(ByteArray(alignmentPadding)) - out.write(blockInfo) - FileInputStream(data).buffered().use { it.copyTo(out, BUFFER_SIZE) } + out.write(infoPayload) + if (dataPadding > 0) out.write(ByteArray(dataPadding)) + FileInputStream(compressedData).buffered(BUFFER_SIZE).use { it.copyTo(out, BUFFER_SIZE) } + if (trailingSize > 0) { + RandomAccessFile(source, "r").use { tail -> + tail.seek(profile!!.declaredBundleSize) + copyExactly(tail, out, trailingSize) + } + } } } } catch (e: Throwable) { output.delete() throw e + } finally { + compressedData.delete() + } + } + + private fun readExactly(input: InputStream, buffer: ByteArray, length: Int) { + var position = 0 + while (position < length) { + val count = input.read(buffer, position, length - position) + if (count < 0) throw EOFException("UnityFS staging data is truncated") + position += count } } - private const val BLOCK_INFO_AT_START = 0x40 + private const val UNCOMPRESSED = 0 + private const val LZ4 = 2 + private const val LZ4HC = 3 + private const val BLOCKS_AND_DIRECTORY_COMBINED = 0x40L + private const val BLOCK_INFO_NEEDS_PADDING = 0x200L + private const val PRESERVED_LAYOUT_FLAGS = 0x300L private const val MAX_BLOCKS = 100_000 } } +internal fun ensureUnityOperationActive() { + if (Thread.currentThread().isInterrupted) throw UnityOperationCancelledException() +} + internal fun copyExactly(input: InputStream, output: OutputStream, length: Long): Long { if (length < 0) throw UnityFormatException("Negative UnityFS block length") val buffer = ByteArray(64 * 1024) var left = length var copied = 0L while (left > 0) { + ensureUnityOperationActive() val n = input.read(buffer, 0, minOf(buffer.size.toLong(), left).toInt()) if (n < 0) throw EOFException("Truncated UnityFS data") output.write(buffer, 0, n) @@ -310,6 +839,7 @@ internal fun copyExactly(input: RandomAccessFile, output: OutputStream, length: var left = length var copied = 0L while (left > 0) { + ensureUnityOperationActive() val n = input.read(buffer, 0, minOf(buffer.size.toLong(), left).toInt()) if (n < 0) throw EOFException("Truncated UnityFS data") output.write(buffer, 0, n) @@ -324,19 +854,6 @@ internal fun checkedAdd(a: Long, b: Long, message: String): Long { return a + b } -private fun md5(file: File): ByteArray { - val digest = MessageDigest.getInstance("MD5") - FileInputStream(file).buffered().use { input -> - val buffer = ByteArray(64 * 1024) - while (true) { - val n = input.read(buffer) - if (n < 0) break - digest.update(buffer, 0, n) - } - } - return digest.digest() -} - private fun writeCString(output: DataOutputStream, value: String) { if ('\u0000' in value) throw UnityFormatException("UnityFS string contains a null character") output.write(value.toByteArray(Charsets.UTF_8)) @@ -384,8 +901,12 @@ object UnityBundleReader { val dataFile = File(cache, "bundle-data.bin") try { var serializedIndex: SerializedFileIndex? = null + var unityFsProfile: UnityFsWriteProfile? = null val summary = when (probe(file).kind) { - UnityFileKind.UNITY_FS -> parseUnityFs(file, dataFile) + UnityFileKind.UNITY_FS -> parseUnityFs(file, dataFile).let { parsed -> + unityFsProfile = parsed.profile + parsed.summary + } UnityFileKind.UNITY_WEB, UnityFileKind.UNITY_RAW -> UnityLegacyReader.parse(file, dataFile) UnityFileKind.SERIALIZED_FILE -> { val (parsed, index) = SerializedFileReader.parse(file, dataFile) @@ -394,7 +915,7 @@ object UnityBundleReader { } UnityFileKind.UNKNOWN -> throw UnityFormatException("Not a Unity file: ${file.name}") } - return UnityBundleDocument(file, summary, dataFile, serializedIndex) + return UnityBundleDocument(file, summary, dataFile, serializedIndex, unityFsProfile) } catch (e: Throwable) { dataFile.delete() cache.delete() @@ -402,9 +923,30 @@ object UnityBundleReader { } } + /** Full streaming verification used before an atomically written bundle is published. */ + internal fun verifyUnityFsOutput( + file: File, + expectedEntries: List, + expectedDataSize: Long, + expectedProfile: UnityFsWriteProfile?, + ) { + val verified = parseUnityFs(file, dataFile = null) + if (verified.summary.dataSize != expectedDataSize) throw UnityFormatException("Rebuilt UnityFS data size failed verification") + if (verified.summary.entries != expectedEntries) throw UnityFormatException("Rebuilt UnityFS entry table failed verification") + if (expectedProfile != null && verified.profile.hashConvention != expectedProfile.hashConvention) { + throw UnityFormatException("Rebuilt UnityFS hash convention failed verification") + } + if (expectedProfile?.hashConvention == UnityFsHashConvention.PRESERVE && + !verified.profile.sourceHash.contentEquals(expectedProfile.sourceHash) + ) { + throw UnityFormatException("Rebuilt UnityFS preserved hash failed verification") + } + } + private data class Block(val compressed: Long, val uncompressed: Long, val flags: Int) + private data class ParsedUnityFs(val summary: UnityBundleSummary, val profile: UnityFsWriteProfile) - private fun parseUnityFs(file: File, dataFile: File): UnityBundleSummary { + private fun parseUnityFs(file: File, dataFile: File?): ParsedUnityFs { RandomAccessFile(file, "r").use { input -> val signature = readCString(input, 32) if (signature != "UnityFS") { @@ -413,7 +955,7 @@ object UnityBundleReader { throw UnityFormatException("Unsupported Unity format${detail}") } val versionLong = readU32(input) - if (versionLong !in 6L..8L) throw UnityFormatException("Unsupported UnityFS format version $versionLong") + if (versionLong !in 6L..8L) throw UnityUnsupportedVersionException("Unsupported UnityFS format version $versionLong") val formatVersion = versionLong.toInt() val playerVersion = readCString(input, 4096) val engineVersion = readCString(input, 4096) @@ -444,7 +986,7 @@ object UnityBundleReader { val infoCompression = (flags and COMPRESSION_MASK.toLong()).toInt() val infoBytes = decompressBytes(compressedInfo, uncompressedInfoSize.toInt(), infoCompression) val table = Cursor(infoBytes) - table.readBytes(16) + val storedHash = table.readBytes(16) val blockCount = table.readU32().toIntChecked("block count") if (blockCount !in 0..MAX_NODES) throw UnityFormatException("UnityFS block count is invalid") val blocks = ArrayList(blockCount) @@ -460,8 +1002,10 @@ object UnityBundleReader { compressedTotal = checkedAdd(compressedTotal, compressed, "UnityFS compressed data size overflows") blocks += Block(compressed, uncompressed, blockFlags) } - val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE - if (uncompressedTotal > availableSpace) throw UnityFormatException("Not enough free space to stage UnityFS data") + if (dataFile != null) { + val availableSpace = dataFile.parentFile?.usableSpace ?: Long.MAX_VALUE + if (uncompressedTotal > availableSpace) throw UnityFormatException("Not enough free space to stage UnityFS data") + } val nodeCount = table.readU32().toIntChecked("node count") if (nodeCount !in 0..MAX_NODES) throw UnityFormatException("UnityFS node count is invalid") val nodes = ArrayList(nodeCount) @@ -483,13 +1027,23 @@ object UnityBundleReader { val dataEnd = if (infoAtEnd) infoOffset else bundleSize if (dataOffset > dataEnd || compressedTotal > dataEnd - dataOffset) throw UnityFormatException("UnityFS data section is truncated or overlaps its block table") input.seek(dataOffset) - dataFile.parentFile?.mkdirs() - FileOutputStream(dataFile).buffered(BUFFER_SIZE).use { out -> + dataFile?.parentFile?.mkdirs() + val detectHashConvention = storedHash.any { it != 0.toByte() } + val uncompressedDigest = if (detectHashConvention) MessageDigest.getInstance("MD5") else null + val compressedDigest = if (detectHashConvention) MessageDigest.getInstance("MD5") else null + val destination: OutputStream = if (dataFile != null) { + FileOutputStream(dataFile).buffered(BUFFER_SIZE) + } else { + DiscardOutputStream + } + destination.use { stagedOut -> + val out: OutputStream = if (uncompressedDigest != null) DigestOutputStream(stagedOut, uncompressedDigest) else stagedOut var consumedCompressed = 0L var written = 0L blocks.forEach { block -> + ensureUnityOperationActive() if (dataOffset + consumedCompressed + block.compressed > bundleSize) throw UnityFormatException("UnityFS data block is truncated") - val slice = RandomAccessFileSlice(input, block.compressed) + val slice = RandomAccessFileSlice(input, block.compressed, compressedDigest) val codec = block.flags and COMPRESSION_MASK val count = when (codec) { 0 -> copyExactly(slice, out, block.compressed) @@ -497,14 +1051,42 @@ object UnityBundleReader { 2, 3 -> decompressLz4(slice, block.compressed, block.uncompressed, out) else -> throw UnityFormatException("UnityFS uses unsupported compression $codec") } + // Some decoders can finish before consuming codec padding. Include all stored + // payload bytes when detecting a source convention based on compressed MD5. + slice.drain() if (count != block.uncompressed) throw UnityFormatException("UnityFS data block has an unexpected size") consumedCompressed += block.compressed written += count input.seek(dataOffset + consumedCompressed) } + out.flush() if (written != uncompressedTotal) throw UnityFormatException("UnityFS data section size does not match its block table") } - return UnityBundleSummary(signature, formatVersion, playerVersion, engineVersion, bundleSize, uncompressedTotal, blockCount, nodes) + val hashConvention = when { + !detectHashConvention -> UnityFsHashConvention.ZERO + storedHash.contentEquals(uncompressedDigest!!.digest()) -> UnityFsHashConvention.UNCOMPRESSED_MD5 + storedHash.contentEquals(compressedDigest!!.digest()) -> UnityFsHashConvention.COMPRESSED_MD5 + else -> UnityFsHashConvention.PRESERVE + } + val preferredCodec = blocks.asSequence() + .map { it.flags and COMPRESSION_MASK } + .filter { it == 2 || it == 3 } + .groupingBy { it } + .eachCount() + .maxByOrNull { it.value } + ?.key + ?: infoCompression.takeIf { it == 2 || it == 3 } + ?: 3 + val summary = UnityBundleSummary(signature, formatVersion, playerVersion, engineVersion, bundleSize, uncompressedTotal, blockCount, nodes) + val profile = UnityFsWriteProfile( + preferredCodec = preferredCodec, + sourceFlags = flags, + hashConvention = hashConvention, + sourceHash = storedHash, + declaredBundleSize = bundleSize, + physicalFileSize = file.length(), + ) + return ParsedUnityFs(summary, profile) } } @@ -771,11 +1353,24 @@ object UnityBundleReader { } } - private class RandomAccessFileSlice(private val input: RandomAccessFile, private var remaining: Long) : InputStream() { + private object DiscardOutputStream : OutputStream() { + override fun write(value: Int) = Unit + override fun write(buffer: ByteArray, offset: Int, length: Int) = Unit + override fun close() = Unit + } + + private class RandomAccessFileSlice( + private val input: RandomAccessFile, + private var remaining: Long, + private val digest: MessageDigest? = null, + ) : InputStream() { override fun read(): Int { if (remaining <= 0) return -1 val value = input.read() - if (value >= 0) remaining-- + if (value >= 0) { + remaining-- + digest?.update(value.toByte()) + } return value } @@ -783,10 +1378,21 @@ object UnityBundleReader { if (length == 0) return 0 if (remaining <= 0) return -1 val count = input.read(buffer, offset, minOf(length.toLong(), remaining).toInt()) - if (count > 0) remaining -= count + if (count > 0) { + remaining -= count + digest?.update(buffer, offset, count) + } return count } + fun drain() { + val buffer = ByteArray(BUFFER_SIZE) + while (remaining > 0) { + val count = read(buffer, 0, minOf(remaining, buffer.size.toLong()).toInt()) + if (count < 0) throw EOFException("Truncated UnityFS data block") + } + } + override fun close() = Unit } diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt index 561e5bb..5fe4729 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityLegacyReader.kt @@ -29,7 +29,7 @@ internal object UnityLegacyReader { throw UnityFormatException("Unsupported legacy Unity container") } val version = UnityBundleReader.readU32(input) - if (version !in 1..9) throw UnityFormatException("Unsupported legacy Unity bundle version $version") + if (version !in 1..9) throw UnityUnsupportedVersionException("Unsupported legacy Unity bundle version $version") val playerVersion = UnityBundleReader.readCString(input, 4096) val engineVersion = UnityBundleReader.readCString(input, 4096) if (version >= 4) { diff --git a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt index 228ec75..6b6dbca 100644 --- a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt +++ b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt @@ -5,14 +5,26 @@ import org.junit.Assert.assertThrows import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream +import java.io.DataInputStream import java.io.DataOutputStream import java.io.File import java.io.FileOutputStream +import java.io.RandomAccessFile import java.security.MessageDigest +import java.util.concurrent.atomic.AtomicReference class UnityBundleReaderTest { private data class TestNode(val name: String, val offset: Long, val size: Long) + private data class TestBlock(val uncompressed: Int, val compressed: Int, val codec: Int) + private data class TestBundleTable( + val declaredSize: Long, + val hash: ByteArray, + val infoCodec: Int, + val infoAtEnd: Boolean, + val blocks: List, + ) @get:Rule val temp = TemporaryFolder() @@ -185,6 +197,236 @@ class UnityBundleReaderTest { } } + @Test + fun repackKeepsRealLz4FixtureCompressedAndStable() { + // The fixture encoder below emits a genuine LZ4 match and is deliberately independent + // from the production encoder. The old writer expands this bundle from a few KiB to 700 KiB. + val contents = ByteArray(700_000) { (it % 251).toByte() } + val source = writeAlignedBundle(temp.root, "compressed-source.bundle", contents, formatVersion = 8, paddingFlag = true, lz4 = true) + val first = File(temp.root, "compressed-first.bundle") + val second = File(temp.root, "compressed-second.bundle") + + UnityBundleReader.open(source, File(temp.root, "cache-1")).use { it.repack(first) } + assertThat(first.length()).isAtMost((source.length() * 1.15).toLong()) + UnityBundleReader.open(first, File(temp.root, "cache-2")).use { rebuilt -> + val extracted = File(temp.root, "compressed-result.bin") + rebuilt.copyEntry(rebuilt.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + rebuilt.repack(second) + } + assertThat(second.length()).isAtMost((first.length() * 1.05).toLong()) + } + + @Test + fun lz4EncoderCoversEmptyShortRepeatedRandomAndWindowBoundaryInputs() { + val empty = ByteArray(0) + assertThat(decodeLz4Fixture(Lz4BlockEncoder.encode(empty), 0)).isEqualTo(empty) + + listOf(byteArrayOf(1), byteArrayOf(1, 2, 3), "short literal".toByteArray()).forEach { input -> + assertThat(decodeLz4Fixture(Lz4BlockEncoder.encode(input), input.size)).isEqualTo(input) + } + + val repeated = ByteArray(40_000) { (it % 17).toByte() } + val repeatedEncoded = Lz4BlockEncoder.encode(repeated) + assertThat(repeatedEncoded.size).isLessThan(repeated.size / 10) + assertThat(decodeLz4Fixture(repeatedEncoded, repeated.size)).isEqualTo(repeated) + + var randomState = 0x2468ACE1 + val random = ByteArray(128 * 1024) { + randomState = randomState xor (randomState shl 13) + randomState = randomState xor (randomState ushr 17) + randomState = randomState xor (randomState shl 5) + randomState.toByte() + } + val randomEncoded = Lz4BlockEncoder.encode(random) + assertThat(decodeLz4Fixture(randomEncoded, random.size)).isEqualTo(random) + assertThat(randomEncoded.size).isAtLeast(random.size) + + val prefix = random.copyOfRange(0, 65_535) + val boundary = prefix + prefix.copyOfRange(0, 64) + ByteArray(5) { 0x5A } + val boundaryEncoded = Lz4BlockEncoder.encode(boundary) + assertThat(decodeLz4Fixture(boundaryEncoded, boundary.size)).isEqualTo(boundary) + assertThat(readLz4Distances(boundaryEncoded)).contains(65_535) + } + + @Test + fun repackWritesMixedLz4AndRawBlocks() { + val blockSize = 128 * 1024 + val compressible = ByteArray(blockSize) { (it % 13).toByte() } + var state = 0x13579BDF + val random = ByteArray(blockSize) { + state = state xor (state shl 13) + state = state xor (state ushr 17) + state = state xor (state shl 5) + state.toByte() + } + val contents = compressible + random + val source = writeBundle(temp.root, "mixed-source.bundle", contents, compression = 0) + val output = File(temp.root, "mixed-output.bundle") + UnityBundleReader.open(source, File(temp.root, "cache-mixed")).use { it.repack(output) } + + val table = readBundleTable(output) + assertThat(table.blocks.map { it.codec }).containsExactly(3, 0).inOrder() + assertThat(table.blocks.map { it.uncompressed }).containsExactly(blockSize, blockSize).inOrder() + assertThat(table.infoCodec).isEqualTo(3) + UnityBundleReader.open(output, File(temp.root, "cache-mixed-output")).use { document -> + val extracted = File(temp.root, "mixed-extracted.bin") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + } + } + + @Test + fun repackCarriesSourceHashConvention() { + val contents = ByteArray(180_000) { (it % 79).toByte() } + val replacementBytes = ByteArray(190_000) { (it % 83).toByte() } + val replacement = File(temp.root, "hash-replacement.bin").apply { writeBytes(replacementBytes) } + + val zeroSource = writeAlignedBundle( + temp.root, "zero-hash.bundle", contents, 8, paddingFlag = true, lz4 = true, + storedHash = ByteArray(16), + ) + val zeroOutput = File(temp.root, "zero-hash-output.bundle") + UnityBundleReader.open(zeroSource, File(temp.root, "cache-zero-hash")).use { document -> + document.repack(zeroOutput, mapOf(document.summary.entries.single().name to replacement)) + } + assertThat(readBundleTable(zeroOutput).hash).isEqualTo(ByteArray(16)) + + val md5Source = writeAlignedBundle(temp.root, "md5-hash.bundle", contents, 8, paddingFlag = true, lz4 = true) + val md5Output = File(temp.root, "md5-hash-output.bundle") + UnityBundleReader.open(md5Source, File(temp.root, "cache-md5-hash")).use { document -> + document.repack(md5Output, mapOf(document.summary.entries.single().name to replacement)) + } + assertThat(readBundleTable(md5Output).hash) + .isEqualTo(MessageDigest.getInstance("MD5").digest(replacementBytes)) + + val customHash = ByteArray(16) { (it * 7 + 1).toByte() } + val customSource = writeAlignedBundle( + temp.root, "custom-hash.bundle", contents, 8, paddingFlag = true, lz4 = true, + storedHash = customHash, + ) + val customOutput = File(temp.root, "custom-hash-output.bundle") + UnityBundleReader.open(customSource, File(temp.root, "cache-custom-hash")).use { it.repack(customOutput) } + assertThat(readBundleTable(customOutput).hash).isEqualTo(customHash) + } + + @Test + fun repackPreservesBytesPastDeclaredBundleSize() { + val trailer = "TRAILING-SIGNATURE-DATA".toByteArray() + val source = writeAlignedBundle( + temp.root, + "trailing.bundle", + ByteArray(90_000) { (it % 31).toByte() }, + formatVersion = 8, + paddingFlag = true, + lz4 = true, + ) + source.appendBytes(trailer) + val output = File(temp.root, "trailing-output.bundle") + UnityBundleReader.open(source, File(temp.root, "cache-trailing")).use { it.repack(output) } + + assertThat(output.readBytes().takeLast(trailer.size).toByteArray()).isEqualTo(trailer) + assertThat(readBundleTable(output).declaredSize).isEqualTo(output.length() - trailer.size) + } + + @Test + fun closedDocumentFailsExplicitlyInsteadOfReadingDeletedStage() { + val source = writeBundle(temp.root, "close.bundle", "content".toByteArray(), compression = 0) + val document = UnityBundleReader.open(source, File(temp.root, "cache-close")) + val entry = document.summary.entries.single() + document.close() + + val error = assertThrows(UnityFormatException::class.java) { + document.copyEntry(entry, File(temp.root, "after-close.bin")) + } + assertThat(error).hasMessageThat().contains("closed") + val inspection = document.inspectText(entry) as UnityTextInspection.Unavailable + assertThat(inspection.reason).isEqualTo(UnityTextUnavailableReason.DOCUMENT_CLOSED) + } + + @Test + fun cancelledRepackLeavesNoPublishedOrTemporaryOutput() { + val source = writeBundle(temp.root, "cancel-source.bundle", ByteArray(300_000) { it.toByte() }, compression = 0) + val output = File(temp.root, "cancel-output.bundle") + UnityBundleReader.open(source, File(temp.root, "cache-cancel")).use { document -> + Thread.currentThread().interrupt() + try { + assertThrows(UnityOperationCancelledException::class.java) { document.repack(output) } + } finally { + Thread.interrupted() // clear the JUnit worker's interrupt flag + } + } + assertThat(output.exists()).isFalse() + assertThat(temp.root.listFiles().orEmpty().filter { it.name.contains("cancel-output") }).isEmpty() + } + + @Test + fun closeWaitsForAnInFlightEntryCopy() { + val stage = temp.newFolder("inflight-stage") + val stagedData = File(stage, "bundle-data.bin") + val dataSize = 64L * 1024 * 1024 + RandomAccessFile(stagedData, "rw").use { it.setLength(dataSize) } + val source = File(temp.root, "inflight-source.bundle").apply { writeText("source") } + val entry = UnityBundleEntry("large.bin", 0, dataSize, 0) + val document = UnityBundleDocument( + source, + UnityBundleSummary("UnityFS", 8, "5.x.x", "2022.3.62f2", dataSize, dataSize, 1, listOf(entry)), + stagedData, + ) + val output = File(temp.root, "inflight-copy.bin") + val failure = AtomicReference() + val worker = Thread { + try { + document.copyEntry(entry, output) + } catch (e: Throwable) { + failure.set(e) + } + } + worker.start() + while (worker.isAlive && temp.root.listFiles().orEmpty().none { + it.name.startsWith(".${output.name}.") && it.name.endsWith(".extract.tmp") + } + ) { + Thread.yield() + } + document.close() + worker.join(10_000) + + assertThat(worker.isAlive).isFalse() + assertThat(failure.get()).isNull() + assertThat(output.length()).isEqualTo(dataSize) + assertThat(stagedData.exists()).isFalse() + } + + @Test + fun readsCompressedBlockInfoAtEndAndRewritesItAtStart() { + val contents = ByteArray(260_000) { (it % 113).toByte() } + val source = writeAlignedBundle( + temp.root, + "info-at-end.bundle", + contents, + formatVersion = 8, + paddingFlag = false, + lz4 = true, + infoAtEnd = true, + ) + val output = File(temp.root, "info-at-start-output.bundle") + UnityBundleReader.open(source, File(temp.root, "cache-info-end")).use { document -> + val extracted = File(temp.root, "info-end-extracted.bin") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + document.repack(output) + } + val outputTable = readBundleTable(output) + assertThat(outputTable.infoCodec).isEqualTo(3) + assertThat(outputTable.infoAtEnd).isFalse() + UnityBundleReader.open(output, File(temp.root, "cache-info-start")).use { document -> + val extracted = File(temp.root, "info-start-extracted.bin") + document.copyEntry(document.summary.entries.single(), extracted) + assertThat(extracted.readBytes()).isEqualTo(contents) + } + } + @Test fun readsVersion7BundleWithoutPaddingFlag() { val contents = "aligned but uncompressed".toByteArray() @@ -259,6 +501,27 @@ class UnityBundleReaderTest { } } + @Test + fun growingPersianTextRecomputesFollowingObjectOffsets() { + val source = writeTypedSerialized(temp.root, "growing.assets", typedObjectOne(), typedObjectOne()) + val output = File(temp.root, "growing-output.assets") + var oldSecondOffset = 0L + val longPersian = "این یک متن فارسی بلندتر برای آزمون جابه‌جایی شیء بعدی است. ".repeat(200) + UnityBundleReader.open(source, File(temp.root, "cache-growing")).use { document -> + val first = document.summary.entries[0] + oldSecondOffset = document.summary.entries[1].offset + val replacement = File(temp.root, "growing-object.bin").apply { + writeBytes(document.rebuildTexts(first, mapOf("m_Script" to longPersian))) + } + document.repack(output, mapOf(first.name to replacement)) + } + UnityBundleReader.open(output, File(temp.root, "cache-growing-output")).use { document -> + assertThat(document.summary.entries[1].offset).isGreaterThan(oldSecondOffset) + assertThat(document.exportTexts(document.summary.entries[0])!!["m_Script"]).isEqualTo(longPersian) + assertThat(document.exportTexts(document.summary.entries[1])!!["m_Script"]).isEqualTo("print('hi')") + } + } + @Test fun rebuildsSerializedFileWithRawReplacement() { val source = writeTypedSerialized(temp.root, "typed.assets", typedObjectOne(), typedObjectOne()) @@ -277,6 +540,155 @@ class UnityBundleReaderTest { } } + @Test + fun editsSerializedEntryInsideUnityFsBundle() { + val serialized = writeTypedSerialized(temp.root, "inner.assets", typedObjectOne()) + val source = writeBundle(temp.root, "outer.bundle", serialized.readBytes(), compression = 0) + val output = File(temp.root, "outer-edited.bundle") + + UnityBundleReader.open(source, File(temp.root, "cache-outer")).use { document -> + val entry = document.summary.entries.single() + val inspection = document.inspectText(entry) + assertThat(inspection).isInstanceOf(UnityTextInspection.Editable::class.java) + assertThat((inspection as UnityTextInspection.Editable).info.stringCount).isEqualTo(6) + val texts = document.exportTexts(entry)!! + assertThat(texts["files[0].objects[100].m_Items[0].Value"]).isEqualTo("v1-long") + texts["files[0].objects[100].m_Items[0].Value"] = "متن فارسی" + val rebuiltEntry = File(temp.root, "rebuilt-inner.assets").apply { + writeBytes(document.rebuildTexts(entry, texts)) + } + document.repack(output, mapOf(entry.name to rebuiltEntry)) + } + + UnityBundleReader.open(output, File(temp.root, "cache-reopen")).use { document -> + val texts = document.exportTexts(document.summary.entries.single())!! + assertThat(texts["files[0].objects[100].m_Items[0].Value"]).isEqualTo("متن فارسی") + assertThat(texts["files[0].objects[100].m_Script"]).isEqualTo("print('hi')") + } + } + + @Test + fun walksAndRebuildsConcatenatedSerializedFilesInsideOneEntry() { + val first = writeTypedSerialized(temp.root, "concat-first.assets", typedObjectOne()) + val second = writeTypedSerialized(temp.root, "concat-second.assets", typedObjectTwo()) + val trailer = "ENTRY-TRAILER".toByteArray() + val payload = first.readBytes() + second.readBytes() + trailer + val source = writeBundle(temp.root, "concat.bundle", payload, compression = 0) + val output = File(temp.root, "concat-edited.bundle") + + UnityBundleReader.open(source, File(temp.root, "cache-concat")).use { document -> + val entry = document.summary.entries.single() + assertThat(document.cachedEmbeddedEntryCount).isEqualTo(0) + val texts = document.exportTexts(entry)!! + assertThat(document.cachedEmbeddedEntryCount).isEqualTo(1) + assertThat(texts["files[0].objects[100].m_Name"]).isEqualTo("obj1") + assertThat(texts["files[1].objects[100].m_Name"]).isEqualTo("renamed") + texts["files[0].objects[100].m_Script"] = "first-file-grew-before-second-سلام" + texts["files[1].objects[100].m_Script"] = "second-file-grew-سلام" + val replacement = File(temp.root, "concat-entry.bin").apply { + writeBytes(document.rebuildTexts(entry, texts)) + } + assertThat(replacement.readBytes().takeLast(trailer.size).toByteArray()).isEqualTo(trailer) + document.repack(output, mapOf(entry.name to replacement)) + } + + UnityBundleReader.open(output, File(temp.root, "cache-concat-output")).use { document -> + val entry = document.summary.entries.single() + val texts = document.exportTexts(entry)!! + assertThat(texts["files[0].objects[100].m_Script"]).isEqualTo("first-file-grew-before-second-سلام") + assertThat(texts["files[1].objects[100].m_Script"]).isEqualTo("second-file-grew-سلام") + val extracted = File(temp.root, "concat-extracted.bin") + document.copyEntry(entry, extracted) + assertThat(extracted.readBytes().takeLast(trailer.size).toByteArray()).isEqualTo(trailer) + } + } + + @Test + fun embeddedIndexesAreParsedLazilyAndCachedPerEntry() { + val serialized = writeTypedSerialized(temp.root, "lazy.assets", typedObjectOne()).readBytes() + val raw = ByteArray(128) { it.toByte() } + val payload = serialized + raw + val source = writeBundle( + temp.root, + "lazy.bundle", + payload, + compression = 0, + nodes = listOf( + TestNode("first", 0, serialized.size.toLong()), + TestNode("second", serialized.size.toLong(), raw.size.toLong()), + ), + ) + UnityBundleReader.open(source, File(temp.root, "cache-lazy")).use { document -> + assertThat(document.cachedEmbeddedEntryCount).isEqualTo(0) + assertThat(document.inspectText(document.summary.entries[0])).isInstanceOf(UnityTextInspection.Editable::class.java) + assertThat(document.cachedEmbeddedEntryCount).isEqualTo(1) + document.inspectText(document.summary.entries[0]) + assertThat(document.cachedEmbeddedEntryCount).isEqualTo(1) + val rawInspection = document.inspectText(document.summary.entries[1]) as UnityTextInspection.Unavailable + assertThat(rawInspection.reason).isEqualTo(UnityTextUnavailableReason.NOT_SERIALIZED_FILE) + assertThat(document.cachedEmbeddedEntryCount).isEqualTo(2) + } + } + + @Test + fun textAssetFallbackEditsUtf8WithoutATypeTree() { + val objectBytes = ByteArrayOutputStream().also { out -> + leStr(out, "dialogue") + val script = "hello from TextAsset".toByteArray(Charsets.UTF_8) + out.write(le32(script.size.toLong())) + out.write(script) + }.toByteArray() + val source = writeTypedSerialized( + temp.root, + "textasset-no-tree.assets", + objectBytes, + enableTypeTree = false, + classId = 49, + ) + val output = File(temp.root, "textasset-no-tree-output.assets") + UnityBundleReader.open(source, File(temp.root, "cache-textasset")).use { document -> + val entry = document.summary.entries.single() + val texts = document.exportTexts(entry)!! + assertThat(texts["m_Script"]).isEqualTo("hello from TextAsset") + val replacement = File(temp.root, "textasset-object.bin").apply { + writeBytes(document.rebuildTexts(entry, mapOf("m_Script" to "متن بلندتر TextAsset"))) + } + document.repack(output, mapOf(entry.name to replacement)) + } + UnityBundleReader.open(output, File(temp.root, "cache-textasset-output")).use { document -> + assertThat(document.exportTexts(document.summary.entries.single())!!["m_Script"]) + .isEqualTo("متن بلندتر TextAsset") + } + } + + @Test + fun reportsUnsupportedVersionSeparatelyForEmbeddedSerializedEntry() { + val future = writeSerialized(temp.root, "future-inner.assets", version = 23) + val source = writeBundle(temp.root, "future-inner.bundle", future.readBytes(), compression = 0) + UnityBundleReader.open(source, File(temp.root, "cache-future-inner")).use { document -> + val inspection = document.inspectText(document.summary.entries.single()) as UnityTextInspection.Unavailable + assertThat(inspection.reason).isEqualTo(UnityTextUnavailableReason.UNSUPPORTED_VERSION) + } + } + + @Test + fun reportsMissingTypeInformationForEmbeddedSerializedEntry() { + val serialized = writeTypedSerialized( + temp.root, + "stripped.assets", + typedObjectOne(), + enableTypeTree = false, + ) + val source = writeBundle(temp.root, "stripped.bundle", serialized.readBytes(), compression = 0) + UnityBundleReader.open(source, File(temp.root, "cache-stripped")).use { document -> + val inspection = document.inspectText(document.summary.entries.single()) + assertThat(inspection).isInstanceOf(UnityTextInspection.Unavailable::class.java) + val unavailable = inspection as UnityTextInspection.Unavailable + assertThat(unavailable.reason).isEqualTo(UnityTextUnavailableReason.NO_TYPE_INFORMATION) + assertThat(unavailable.diagnostic).contains("type tree") + } + } + @Test fun jsonRoundTripPreservesEscapesAndRejectsUnknownPaths() { val map = linkedMapOf( @@ -299,6 +711,113 @@ class UnityBundleReaderTest { } } + private fun readBundleTable(file: File): TestBundleTable { + RandomAccessFile(file, "r").use { input -> + fun cString(): String { + val out = ByteArrayOutputStream() + while (true) { + val value = input.read() + check(value >= 0) + if (value == 0) return out.toByteArray().toString(Charsets.UTF_8) + out.write(value) + } + } + check(cString() == "UnityFS") + val version = input.readInt() + cString() // player version + cString() // engine version + val declaredSize = input.readLong() + val compressedInfoSize = input.readInt() + val uncompressedInfoSize = input.readInt() + val flags = input.readInt() + val alignedHeaderEnd = if (version >= 7) (input.filePointer + 15L) and -16L else input.filePointer + val infoOffset = if (flags and 0x80 != 0) declaredSize - compressedInfoSize else alignedHeaderEnd + input.seek(infoOffset) + val payload = ByteArray(compressedInfoSize) + input.readFully(payload) + val info = when (flags and 0x3F) { + 0 -> payload + 2, 3 -> decodeLz4Fixture(payload, uncompressedInfoSize) + else -> error("Unexpected test block-info codec") + } + DataInputStream(ByteArrayInputStream(info)).use { table -> + val hash = ByteArray(16).also(table::readFully) + val count = table.readInt() + val blocks = List(count) { + TestBlock(table.readInt(), table.readInt(), table.readUnsignedShort() and 0x3F) + } + return TestBundleTable(declaredSize, hash, flags and 0x3F, flags and 0x80 != 0, blocks) + } + } + } + + private fun readLz4Distances(input: ByteArray): List { + val distances = ArrayList() + var source = 0 + fun length(nibble: Int): Int { + var value = nibble + if (nibble == 15) { + var extra: Int + do { + extra = input[source++].toInt() and 0xFF + value += extra + } while (extra == 255) + } + return value + } + while (source < input.size) { + val token = input[source++].toInt() and 0xFF + val literals = length(token ushr 4) + source += literals + if (source == input.size) break + val distance = (input[source].toInt() and 0xFF) or ((input[source + 1].toInt() and 0xFF) shl 8) + source += 2 + distances += distance + length(token and 0x0F) + } + return distances + } + + /** Independent test decoder for raw LZ4 blocks written by the production repacker. */ + private fun decodeLz4Fixture(input: ByteArray, expected: Int): ByteArray { + val output = ByteArray(expected) + var source = 0 + var target = 0 + fun length(nibble: Int): Int { + var value = nibble + if (nibble == 15) { + var extra: Int + do { + check(source < input.size) + extra = input[source++].toInt() and 0xFF + value += extra + } while (extra == 255) + } + return value + } + while (source < input.size) { + val token = input[source++].toInt() and 0xFF + val literals = length(token ushr 4) + check(source + literals <= input.size && target + literals <= output.size) + input.copyInto(output, target, source, source + literals) + source += literals + target += literals + if (source == input.size) break + check(source + 2 <= input.size) + val distance = (input[source].toInt() and 0xFF) or ((input[source + 1].toInt() and 0xFF) shl 8) + source += 2 + check(distance in 1..target) + val match = length(token and 0x0F) + 4 + repeat(match) { + check(target < output.size) + output[target] = output[target - distance] + target++ + } + } + check(target == expected) + return output + } + private fun writeBundle( root: File, name: String, @@ -488,16 +1007,30 @@ class UnityBundleReaderTest { paddingFlag: Boolean, lz4: Boolean, engineVersion: String = "2022.3.62f2", + storedHash: ByteArray = MessageDigest.getInstance("MD5").digest(contents), + infoAtEnd: Boolean = false, ): File { val blockFlags = if (lz4) 3 else 0 - val blockPayload = if (lz4) lz4LiteralRun(contents) else contents + val fixtureBlockSize = 128 * 1024 + val blocks = if (lz4) { + contents.asList().chunked(fixtureBlockSize).map { chunk -> + val raw = chunk.toByteArray() + raw to lz4FixtureBlock(raw) + } + } else { + listOf(contents to contents) + } + val blockPayload = ByteArrayOutputStream().also { data -> blocks.forEach { data.write(it.second) } }.toByteArray() val info = ByteArrayOutputStream().use { bytes -> DataOutputStream(bytes).use { out -> - out.write(MessageDigest.getInstance("MD5").digest(contents)) - out.writeInt(1) - out.writeInt(contents.size) - out.writeInt(blockPayload.size) - out.writeShort(blockFlags) + require(storedHash.size == 16) + out.write(storedHash) + out.writeInt(blocks.size) + blocks.forEach { (raw, encoded) -> + out.writeInt(raw.size) + out.writeInt(encoded.size) + out.writeShort(blockFlags) + } out.writeInt(1) out.writeLong(0) out.writeLong(contents.size.toLong()) @@ -508,7 +1041,7 @@ class UnityBundleReaderTest { bytes.toByteArray() } val infoPayload = if (lz4) lz4LiteralRun(info) else info - val infoFlags = 0x40 or (if (paddingFlag) 0x200 else 0) or blockFlags + val infoFlags = 0x40 or (if (infoAtEnd) 0x80 else 0) or (if (paddingFlag) 0x200 else 0) or blockFlags val headerPrefix = ByteArrayOutputStream().use { bytes -> DataOutputStream(bytes).use { out -> out.write("UnityFS".toByteArray(Charsets.UTF_8)) @@ -523,7 +1056,7 @@ class UnityBundleReaderTest { } val headerSize = headerPrefix.size + 8 + 4 + 4 + 4 val padding = if (formatVersion >= 7) (16 - headerSize % 16) % 16 else 0 - val dataPadding = if (paddingFlag) (16 - (headerSize + padding + infoPayload.size) % 16) % 16 else 0 + val dataPadding = if (!infoAtEnd && paddingFlag) (16 - (headerSize + padding + infoPayload.size) % 16) % 16 else 0 val total = headerSize + padding + infoPayload.size + dataPadding + blockPayload.size val output = File(root, name) FileOutputStream(output).use { stream -> @@ -534,14 +1067,55 @@ class UnityBundleReaderTest { out.writeInt(info.size) out.writeInt(infoFlags) out.write(ByteArray(padding)) - out.write(infoPayload) - out.write(ByteArray(dataPadding)) - out.write(blockPayload) + if (infoAtEnd) { + out.write(blockPayload) + out.write(infoPayload) + } else { + out.write(infoPayload) + out.write(ByteArray(dataPadding)) + out.write(blockPayload) + } } } return output } + /** + * Test-only LZ4 encoder for periodic fixtures. It writes one literal sequence, one overlapping + * match and the required final literals. This intentionally does not call production code. + */ + private fun lz4FixtureBlock(payload: ByteArray): ByteArray { + val lastLiterals = 5 + val maxPeriod = minOf(1024, payload.size - 12) + val period = (1..maxPeriod).firstOrNull { distance -> + (distance until payload.size).all { payload[it] == payload[it - distance] } + } ?: return lz4LiteralRun(payload) + val matchLength = payload.size - period - lastLiterals + if (matchLength < 4 || period > 65_535) return lz4LiteralRun(payload) + + val out = ByteArrayOutputStream() + val encodedMatchLength = matchLength - 4 + out.write((minOf(period, 15) shl 4) or minOf(encodedMatchLength, 15)) + writeLz4Length(out, period - 15) + out.write(payload, 0, period) + out.write(period and 0xFF) + out.write(period ushr 8) + writeLz4Length(out, encodedMatchLength - 15) + out.write(lastLiterals shl 4) + out.write(payload, payload.size - lastLiterals, lastLiterals) + return out.toByteArray() + } + + private fun writeLz4Length(out: ByteArrayOutputStream, extra: Int) { + if (extra < 0) return + var left = extra + while (left >= 255) { + out.write(255) + left -= 255 + } + out.write(left) + } + /** Valid LZ4 block made of a single literal run (no matches), like an incompressible payload. */ private fun lz4LiteralRun(payload: ByteArray): ByteArray { val out = ByteArrayOutputStream() @@ -634,22 +1208,30 @@ class UnityBundleReaderTest { return nodes.toByteArray() to strings } - private fun writeTypedSerialized(root: File, name: String, vararg objects: ByteArray): File { + private fun writeTypedSerialized( + root: File, + name: String, + vararg objects: ByteArray, + enableTypeTree: Boolean = true, + classId: Int = 114, + ): File { val (nodes, strings) = typeTreeBlob() val meta = ByteArrayOutputStream() meta.write("2021.3.0f1".toByteArray(Charsets.UTF_8)); meta.write(0) // unity version meta.write(le32(13)) // build target - meta.write(1) // enable type tree + meta.write(if (enableTypeTree) 1 else 0) meta.write(le32(1)) // type count - meta.write(le32(114)) // class id: MonoBehaviour + meta.write(le32(classId.toLong())) meta.write(0) // is stripped meta.write(byteArrayOf(0xFF.toByte(), 0xFF.toByte())) // script type index -1 - meta.write(ByteArray(16)) // script id (class 114) + if (classId == 114) meta.write(ByteArray(16)) // script id (MonoBehaviour only) meta.write(ByteArray(16)) // old type hash - meta.write(le32((nodes.size / 24).toLong())) - meta.write(le32(strings.size.toLong())) - meta.write(nodes) - meta.write(strings) + if (enableTypeTree) { + meta.write(le32((nodes.size / 24).toLong())) + meta.write(le32(strings.size.toLong())) + meta.write(nodes) + meta.write(strings) + } meta.write(le32(objects.size.toLong())) var dataOffsetInSection = 0 val data = ByteArrayOutputStream() From f99d72382a47ba188752f0c704b7dc639be829c8 Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Mon, 19 Oct 2026 00:00:26 +0000 Subject: [PATCH 07/11] feat: surface per-entry Unity text capability --- .../strata/feature/unity/UnityAssetScreen.kt | 33 +++++ .../feature/unity/UnityAssetViewModel.kt | 116 ++++++++++++++---- app/src/main/res/values-fa/strings_unity.xml | 11 ++ app/src/main/res/values-ru/strings_unity.xml | 11 ++ .../main/res/values-zh-rCN/strings_unity.xml | 11 ++ app/src/main/res/values/strings_unity.xml | 11 ++ 6 files changed, 168 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt index 48711cf..c77d39d 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt @@ -57,6 +57,7 @@ import dev.cluvex.strata.core.unity.UnityBundleEntry import dev.cluvex.strata.core.unity.UnityFileKind import dev.cluvex.strata.core.unity.UnityProbe import dev.cluvex.strata.core.unity.UnityTextInfo +import dev.cluvex.strata.core.unity.UnityTextUnavailableReason import dev.cluvex.strata.core.util.Formatters import dev.cluvex.strata.ui.isolated import kotlinx.coroutines.Dispatchers @@ -202,6 +203,7 @@ fun UnityAssetScreen( selected = state.selectedName == entry.name, modified = entry.name in state.replacements || entry.name in state.editedFiles, textInfo = state.textInfos[entry.name], + textIssue = state.textIssues[entry.name], onClick = { vm.select(entry.name) }, ) } @@ -231,6 +233,7 @@ fun UnityAssetScreen( } else { null }, + textIssue = state.textIssues[entry.name], ) } ?: Text(stringResource(R.string.unity_select_entry), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp)) @@ -305,6 +308,7 @@ private fun UnityEntryRow( selected: Boolean, modified: Boolean, textInfo: UnityTextInfo? = null, + textIssue: UnityTextUnavailableReason? = null, onClick: () -> Unit, ) { Surface( @@ -324,6 +328,14 @@ private fun UnityEntryRow( maxLines = 1, overflow = TextOverflow.Ellipsis, ) + } else if (textIssue != null) { + Text( + unityTextIssueLabel(textIssue), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) } else { Text(isolated(entry.name), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) } @@ -344,12 +356,21 @@ private fun UnityEntryActions( onExport: () -> Unit, onReplace: () -> Unit, onExportTexts: (() -> Unit)? = null, + textIssue: UnityTextUnavailableReason? = null, ) { Surface(shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.surfaceContainer, modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) { Column(Modifier.padding(12.dp)) { Text(isolated(entry.name), style = MaterialTheme.typography.labelMedium, maxLines = 2, overflow = TextOverflow.Ellipsis) Text(stringResource(R.string.unity_entry_size, Formatters.size(entry.size)), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Text(stringResource(R.string.unity_entry_flags, "0x${entry.flags.toString(16).uppercase().padStart(8, '0')}"), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (textIssue != null) { + Text( + unityTextIssueLabel(textIssue), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(top = 4.dp), + ) + } Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) { TextButton(onClick = onOpen, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_open_entry), maxLines = 1) } TextButton(onClick = onExport, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_export_entry), maxLines = 1) } @@ -364,6 +385,18 @@ private fun UnityEntryActions( } } +@Composable +private fun unityTextIssueLabel(reason: UnityTextUnavailableReason): String = when (reason) { + UnityTextUnavailableReason.NOT_SERIALIZED_FILE -> stringResource(R.string.unity_text_not_serialized) + UnityTextUnavailableReason.NO_TYPE_INFORMATION -> stringResource(R.string.unity_text_no_type_info) + UnityTextUnavailableReason.UNSUPPORTED_OBJECT -> stringResource(R.string.unity_text_unsupported_object) + UnityTextUnavailableReason.UNSUPPORTED_VERSION -> stringResource(R.string.unity_unsupported_version) + UnityTextUnavailableReason.NO_TEXT -> stringResource(R.string.unity_text_none_found) + UnityTextUnavailableReason.TOO_MANY_OBJECTS -> stringResource(R.string.unity_text_too_many_objects) + UnityTextUnavailableReason.DECODE_FAILED -> stringResource(R.string.unity_text_decode_failed) + UnityTextUnavailableReason.DOCUMENT_CLOSED -> stringResource(R.string.unity_text_document_closed) +} + @Composable private fun UnsupportedPanel(probe: UnityProbe?) { Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt index 1e545b1..8e418c0 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt @@ -11,17 +11,23 @@ import dev.cluvex.strata.core.unity.TypeTreeCodec import dev.cluvex.strata.core.unity.UnityBundleDocument import dev.cluvex.strata.core.unity.UnityBundleEntry import dev.cluvex.strata.core.unity.UnityBundleReader +import dev.cluvex.strata.core.unity.UnityDocumentClosedException import dev.cluvex.strata.core.unity.UnityFormatException +import dev.cluvex.strata.core.unity.UnityOperationCancelledException import dev.cluvex.strata.core.unity.UnityPackageRepacker import dev.cluvex.strata.core.unity.UnityProbe import dev.cluvex.strata.core.unity.UnityTextInfo +import dev.cluvex.strata.core.unity.UnityTextInspection +import dev.cluvex.strata.core.unity.UnityTextUnavailableReason +import dev.cluvex.strata.core.unity.UnityUnsupportedVersionException +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext +import kotlinx.coroutines.runInterruptible import java.io.File import java.io.FileOutputStream import java.io.IOException @@ -38,6 +44,7 @@ data class UnityAssetUiState( val editedFiles: Map = emptyMap(), val replacements: Map = emptyMap(), val textInfos: Map = emptyMap(), + val textIssues: Map = emptyMap(), val exportedTexts: Map = emptyMap(), val navigateTo: String? = null, val output: File? = null, @@ -45,10 +52,6 @@ data class UnityAssetUiState( ) class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { - private companion object { - const val MAX_TEXT_SCAN_OBJECTS = 5_000 - } - private val _state = MutableStateFlow(UnityAssetUiState()) val state: StateFlow = _state.asStateFlow() @@ -56,6 +59,7 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { private var stageDir: File? = null private var workingBaselines: Map> = emptyMap() private var exportedBaselines: Map> = emptyMap() + private val inspectingNames = HashSet() fun open(path: String) { val current = _state.value @@ -66,6 +70,7 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { document = null workingBaselines = emptyMap() exportedBaselines = emptyMap() + inspectingNames.clear() val newStageDir = File(getApplication().cacheDir, "unity-editor/${path.hashCode().toUInt().toString(16)}-${System.nanoTime()}") newStageDir.mkdirs() stageDir = newStageDir @@ -73,31 +78,65 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { viewModelScope.launch { try { - val (probe, parsed) = withContext(Dispatchers.IO) { + val (probe, parsed) = runInterruptible(Dispatchers.IO) { val file = File(path) val probe = UnityBundleReader.probe(file) val parsed = if (probe.bundleSupported) UnityBundleReader.open(file, getApplication().cacheDir) else null probe to parsed } document = parsed - val infos = withContext(Dispatchers.IO) { - if (parsed?.supportsTextEditing == true && parsed.summary.entries.size <= MAX_TEXT_SCAN_OBJECTS) { - parsed.summary.entries.mapNotNull { entry -> - parsed.textInfo(entry)?.let { entry.name to it } - }.toMap() - } else { - emptyMap() - } + _state.update { + it.copy( + loading = false, + probe = probe, + document = parsed, + ) } - _state.update { it.copy(loading = false, probe = probe, document = parsed, textInfos = infos) } - } catch (_: Exception) { - _state.update { it.copy(loading = false, error = getApplication().getString(R.string.unity_load_failed)) } + } catch (e: CancellationException) { + document?.close() + document = null + throw e + } catch (e: Exception) { + document?.close() + document = null + val message = if (e is UnityUnsupportedVersionException) { + getApplication().getString(R.string.unity_unsupported_version) + } else { + getApplication().getString(R.string.unity_load_failed) + } + _state.update { it.copy(loading = false, error = message) } } } } fun select(name: String?) { _state.update { it.copy(selectedName = name) } + if (name == null || name in _state.value.textInfos || name in _state.value.textIssues) return + val doc = document ?: return + val entry = doc.summary.entries.firstOrNull { it.name == name } ?: return + if (!inspectingNames.add(name)) return + viewModelScope.launch { + try { + val inspection = runInterruptible(Dispatchers.IO) { doc.inspectText(entry) } + if (document !== doc) return@launch + _state.update { current -> + when (inspection) { + is UnityTextInspection.Editable -> current.copy( + textInfos = current.textInfos + (name to inspection.info), + textIssues = current.textIssues - name, + ) + is UnityTextInspection.Unavailable -> current.copy( + textIssues = current.textIssues + (name to inspection.reason), + textInfos = current.textInfos - name, + ) + } + } + } catch (e: CancellationException) { + throw e + } finally { + inspectingNames.remove(name) + } + } } suspend fun fileFor(entry: UnityBundleEntry): File { @@ -109,7 +148,7 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { val index = doc.summary.entries.indexOf(entry).coerceAtLeast(0) val suffix = entry.displayName.substringAfterLast('.', "").takeIf { it.length in 1..10 }?.let { ".$it" }.orEmpty() val target = File(dir, "entry-$index$suffix") - withContext(Dispatchers.IO) { doc.copyEntry(entry, target) } + runInterruptible(Dispatchers.IO) { doc.copyEntry(entry, target) } workingBaselines = workingBaselines + (entry.name to (target.length() to target.lastModified())) _state.update { it.copy(workingFiles = it.workingFiles + (entry.name to target)) } return target @@ -122,7 +161,7 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { val suffix = entry.displayName.substringAfterLast('.', "").takeIf { it.length in 1..10 }?.let { ".$it" }.orEmpty() val staged = File(dir, "replacement-$index-${System.nanoTime()}$suffix") try { - withContext(Dispatchers.IO) { + runInterruptible(Dispatchers.IO) { val input = resolver.openInputStream(uri) ?: throw IOException("Could not open replacement") input.use { source -> FileOutputStream(staged).use { target -> source.copyTo(target) } } } @@ -146,7 +185,7 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { _state.update { it.copy(busy = true) } viewModelScope.launch { try { - val result = withContext(Dispatchers.IO) { + val result = runInterruptible(Dispatchers.IO) { val texts = doc.exportTexts(entry) ?: throw IOException("Entry has no editable text") val index = doc.summary.entries.indexOf(entry).coerceAtLeast(0) val safe = entry.displayName.replace(Regex("[^A-Za-z0-9._-]"), "_").take(48).ifEmpty { "object" } @@ -163,8 +202,18 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { message = getApplication().getString(R.string.unity_texts_exported, result.second), ) } - } catch (_: Exception) { - _state.update { it.copy(busy = false, message = getApplication().getString(R.string.unity_operation_failed)) } + } catch (e: CancellationException) { + _state.update { it.copy(busy = false, message = getApplication().getString(R.string.unity_operation_cancelled)) } + throw e + } catch (e: Exception) { + val detail = e.message?.takeIf { it.isNotBlank() } + val message = when { + e is UnityDocumentClosedException -> getApplication().getString(R.string.unity_staging_unavailable) + e is UnityOperationCancelledException -> getApplication().getString(R.string.unity_operation_cancelled) + detail != null -> getApplication().getString(R.string.unity_operation_failed_detail, detail) + else -> getApplication().getString(R.string.unity_operation_failed) + } + _state.update { it.copy(busy = false, message = message) } } } } @@ -195,7 +244,7 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { _state.update { it.copy(busy = true, error = null) } viewModelScope.launch { try { - val output = withContext(Dispatchers.IO) { + val output = runInterruptible(Dispatchers.IO) { UnityPackageRepacker.repack(doc, collectChanges(doc, current), parents, getApplication().cacheDir) } _state.update { @@ -205,9 +254,26 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { busy = false, ) } + } catch (e: CancellationException) { + _state.update { + it.copy( + message = getApplication().getString(R.string.unity_operation_cancelled), + busy = false, + ) + } + throw e } catch (e: Exception) { - val message = if (e is UnityFormatException && e.message?.contains("JSON") == true) { - getApplication().getString(R.string.unity_texts_bad_json, e.message ?: "") + val detail = e.message?.takeIf { it.isNotBlank() } + val message = if (e is UnityOperationCancelledException) { + getApplication().getString(R.string.unity_operation_cancelled) + } else if (e is UnityDocumentClosedException) { + getApplication().getString(R.string.unity_staging_unavailable) + } else if (e is UnityUnsupportedVersionException) { + getApplication().getString(R.string.unity_unsupported_version) + } else if (e is UnityFormatException && detail?.contains("JSON") == true) { + getApplication().getString(R.string.unity_texts_bad_json, detail) + } else if (detail != null) { + getApplication().getString(R.string.unity_operation_failed_detail, detail) } else { getApplication().getString(R.string.unity_operation_failed) } diff --git a/app/src/main/res/values-fa/strings_unity.xml b/app/src/main/res/values-fa/strings_unity.xml index fd3733a..fdc4b5e 100644 --- a/app/src/main/res/values-fa/strings_unity.xml +++ b/app/src/main/res/values-fa/strings_unity.xml @@ -41,4 +41,15 @@ ‏%1$d رشتهٔ متنی به‌صورت JSON باز شد — ویرایش و ذخیره کنید، سپس بازبسته‌بندی را بزنید. ‏%1$d متن · %2$s فایل JSON ویرایش‌شده معتبر نیست: %1$s + عملیات انجام نشد: %1$s + این ورودی یک فایل سریال‌شدهٔ Unity نیست. + این فایل اطلاعات نوع ندارد؛ بنابراین ویرایش امن متن‌های سفارشی آن ممکن نیست. + برای این نوع شیء هنوز رمزگشای متنی امنی وجود ندارد. + فایل با موفقیت خوانده شد، اما متن قابل‌ویرایشی پیدا نشد. + تعداد اشیای این فایل برای پویش امن متن بیش از حد زیاد است. + رمزگشایی امن این شیء ممکن نشد. + دادهٔ موقت Unity دیگر در دسترس نیست. + عملیات لغو شد. + نسخهٔ این فایل Unity پشتیبانی نمی‌شود. + دادهٔ موقت Unity دیگر در دسترس نیست؛ فایل را دوباره باز کنید. diff --git a/app/src/main/res/values-ru/strings_unity.xml b/app/src/main/res/values-ru/strings_unity.xml index 97ed916..05bb45e 100644 --- a/app/src/main/res/values-ru/strings_unity.xml +++ b/app/src/main/res/values-ru/strings_unity.xml @@ -43,4 +43,15 @@ Открыто строк: %1$d в JSON — отредактируйте, сохраните и нажмите пересборку. Текстов: %1$d · %2$s Изменённый JSON повреждён: %1$s + Ошибка операции: %1$s + Эта запись не является сериализованным файлом Unity. + В файле нет сведений о типах; безопасное редактирование текста невозможно. + Для этого типа объекта пока нет безопасного текстового декодера. + Файл прочитан, но редактируемый текст не найден. + В файле слишком много объектов для безопасного поиска текста. + Не удалось безопасно декодировать объект. + Временные данные Unity больше недоступны. + Операция отменена. + Эта версия файла Unity не поддерживается. + Временные данные Unity больше недоступны; откройте файл заново. diff --git a/app/src/main/res/values-zh-rCN/strings_unity.xml b/app/src/main/res/values-zh-rCN/strings_unity.xml index 1911899..6d0d870 100644 --- a/app/src/main/res/values-zh-rCN/strings_unity.xml +++ b/app/src/main/res/values-zh-rCN/strings_unity.xml @@ -40,4 +40,15 @@ 已以 JSON 打开 %1$d 条文本 — 编辑保存后点击重新打包。 %1$d 条文本 · %2$s 编辑后的 JSON 无效:%1$s + 操作失败:%1$s + 此条目不是 Unity 序列化文件。 + 此文件没有类型信息,无法安全编辑其自定义文本。 + 此对象类型尚无安全的文本解码器。 + 文件已解码,但未找到可编辑文本。 + 此文件的对象过多,无法进行安全文本扫描。 + 无法安全解码此对象。 + 暂存的 Unity 数据已不可用。 + 操作已取消。 + 不支持此 Unity 文件版本。 + 暂存的 Unity 数据已不可用;请重新打开文件。 diff --git a/app/src/main/res/values/strings_unity.xml b/app/src/main/res/values/strings_unity.xml index 2a4f2e3..76a8f06 100644 --- a/app/src/main/res/values/strings_unity.xml +++ b/app/src/main/res/values/strings_unity.xml @@ -41,4 +41,15 @@ Opened %1$d text entries as JSON — edit, save, then tap repack. %1$d texts · %2$s The edited JSON is invalid: %1$s + Operation failed: %1$s + This entry is not a Unity serialized file. + This file has no type information, so its custom text cannot be edited safely. + This object type has no safe text decoder yet. + The file was decoded, but no editable text was found. + This file has too many objects for the safe text scan. + The object could not be decoded safely. + The staged Unity data is no longer available. + Operation cancelled. + This Unity file version is not supported. + The staged Unity data is no longer available; reopen the file. From 81fabef0611c9a4c841466c3b4828435a047089d Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Mon, 19 Oct 2026 00:00:30 +0000 Subject: [PATCH 08/11] ci: run JVM unit tests before packaging --- .github/workflows/build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a08a7b1..8e4c718 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,6 +50,9 @@ jobs: - name: Build the native core run: native/build.sh + - name: Run JVM unit tests + run: ./gradlew --stacktrace :app:testDebugUnitTest + - name: Build the debug APK if: ${{ !startsWith(github.ref, 'refs/tags/') }} run: ./gradlew --stacktrace :app:assembleDebug From de9284a9f6eaa2234177827a6932a9f99fea9ab9 Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Mon, 19 Oct 2026 00:02:15 +0000 Subject: [PATCH 09/11] test: cover the exact 64 KiB LZ4 boundary --- .../dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt index 6b6dbca..766280f 100644 --- a/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt +++ b/app/src/test/java/dev/cluvex/strata/core/unity/UnityBundleReaderTest.kt @@ -231,6 +231,11 @@ class UnityBundleReaderTest { assertThat(repeatedEncoded.size).isLessThan(repeated.size / 10) assertThat(decodeLz4Fixture(repeatedEncoded, repeated.size)).isEqualTo(repeated) + listOf(65_535, 65_536, 65_537).forEach { size -> + val exactBoundary = ByteArray(size) { (it % 193).toByte() } + assertThat(decodeLz4Fixture(Lz4BlockEncoder.encode(exactBoundary), size)).isEqualTo(exactBoundary) + } + var randomState = 0x2468ACE1 val random = ByteArray(128 * 1024) { randomState = randomState xor (randomState shl 13) From 9b16137079e82404abdb6cbc97589d00ed64c5c7 Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Mon, 19 Oct 2026 00:02:44 +0000 Subject: [PATCH 10/11] ci: run JVM tests before native builds --- .github/workflows/build.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8e4c718..740781f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -33,6 +33,9 @@ jobs: with: cache-provider: basic + - name: Run JVM unit tests + run: ./gradlew --stacktrace :app:testDebugUnitTest + - uses: dtolnay/rust-toolchain@stable with: targets: aarch64-linux-android,armv7-linux-androideabi,x86_64-linux-android @@ -50,9 +53,6 @@ jobs: - name: Build the native core run: native/build.sh - - name: Run JVM unit tests - run: ./gradlew --stacktrace :app:testDebugUnitTest - - name: Build the debug APK if: ${{ !startsWith(github.ref, 'refs/tags/') }} run: ./gradlew --stacktrace :app:assembleDebug From a114ce04bd1d88f74069255c40e0d3278d3c3b27 Mon Sep 17 00:00:00 2001 From: Strata Dev Date: Mon, 19 Oct 2026 09:27:37 +0000 Subject: [PATCH 11/11] feat: add Unity TMP font capability inspection, dynamic TTF binding, and Persian/RTL shaping --- .../strata/core/unity/UnityBundleReader.kt | 626 +++++++++++++++- .../strata/core/unity/UnityFontInspector.kt | 685 ++++++++++++++++++ .../strata/core/unity/UnityTextShaper.kt | 425 +++++++++++ .../strata/feature/unity/UnityAssetScreen.kt | 128 ++++ .../feature/unity/UnityAssetViewModel.kt | 134 +++- app/src/main/res/values-fa/strings_unity.xml | 12 + app/src/main/res/values-ru/strings_unity.xml | 12 + .../main/res/values-zh-rCN/strings_unity.xml | 12 + app/src/main/res/values/strings_unity.xml | 12 + .../core/unity/UnityFontAndShapingTest.kt | 671 +++++++++++++++++ 10 files changed, 2709 insertions(+), 8 deletions(-) create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/UnityFontInspector.kt create mode 100644 app/src/main/java/dev/cluvex/strata/core/unity/UnityTextShaper.kt create mode 100644 app/src/test/java/dev/cluvex/strata/core/unity/UnityFontAndShapingTest.kt diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt index 0e6194a..3facc8f 100644 --- a/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityBundleReader.kt @@ -79,6 +79,10 @@ enum class UnityTextUnavailableReason { TOO_MANY_OBJECTS, DECODE_FAILED, DOCUMENT_CLOSED, + FONT_NO_GLYPHS, + FONT_STATIC_NO_SOURCE, + FONT_ATLAS_FULL, + FONT_ASSET_NOT_FOUND, } /** Per-entry text capability, including a diagnostic when editing is unsafe or impossible. */ @@ -221,21 +225,33 @@ class UnityBundleDocument internal constructor( } /** Re-encodes the entry with edited strings applied; returns its new raw bytes. */ - fun rebuildTexts(entry: UnityBundleEntry, edits: Map): ByteArray = - withOpenDocument { rebuildTextsOpen(entry, edits) } - - private fun rebuildTextsOpen(entry: UnityBundleEntry, edits: Map): ByteArray { + fun rebuildTexts( + entry: UnityBundleEntry, + edits: Map, + transformOptions: UnityTextTransformOptions = UnityTextTransformOptions(), + ): ByteArray = withOpenDocument { rebuildTextsOpen(entry, edits, transformOptions) } + + private fun rebuildTextsOpen( + entry: UnityBundleEntry, + edits: Map, + transformOptions: UnityTextTransformOptions, + ): ByteArray { requireEntry(entry) + val effectiveEdits = if (transformOptions.isEnabled) { + UnityTextShaper.transformEdits(edits, transformOptions) + } else { + edits + } val standalone = serialized if (standalone != null) { val value = decodeOrThrow(standalone, entry) - TypeTreeCodec.applyStrings(value, edits) + TypeTreeCodec.applyStrings(value, effectiveEdits) return standalone.encode(dataFile, entry, value) } val embedded = embeddedOrThrow(entry) val editsByPart = LinkedHashMap>>() - edits.forEach { (path, text) -> + effectiveEdits.forEach { (path, text) -> val match = EMBEDDED_PATH.matchEntire(path) ?: throw UnityFormatException("Edited JSON contains an invalid embedded text path: $path") val partIndex = match.groupValues[1].toIntOrNull() @@ -309,6 +325,604 @@ class UnityBundleDocument internal constructor( } } + /** Estimates disk space and duration required to rewrite this bundle or serialized file. */ + fun estimateRewrite(): UnityBundleRewriteEstimate = + UnityFontInspector.estimateRewrite(source.name, summary.dataSize) + + /** + * Read-only font capability inspection, scoped either to a single [entry] or to all serialized + * entries in this document. Results are cached by `(path, size, lastModified, scope)`. + */ + fun inspectFonts(entry: UnityBundleEntry? = null): UnityFontReport = try { + withOpenDocument { inspectFontsOpen(entry) } + } catch (_: UnityDocumentClosedException) { + UnityFontReport( + inspectedEntries = 0, + tmpFontAssets = emptyList(), + rawFonts = emptyList(), + unavailableReason = UnityTextUnavailableReason.DOCUMENT_CLOSED, + summaryStatement = "Unity document is closed", + ) + } + + private fun inspectFontsOpen(entry: UnityBundleEntry?): UnityFontReport { + if (entry != null) requireEntry(entry) + val canonicalPath = runCatching { source.canonicalPath }.getOrDefault(source.path) + val fileLength = source.length() + val lastModified = source.lastModified() + val scope = entry?.name ?: "*" + UnityFontInspector.getCachedReport(canonicalPath, fileLength, lastModified, scope)?.let { return it } + + val standalone = serialized + val report = if (standalone != null) { + inspectStandaloneFonts(standalone, entry) + } else if (summary.signature == "UnityFS") { + val targets = if (entry != null) listOf(entry) else summary.entries + inspectEmbeddedFonts(targets) + } else { + UnityFontReport( + inspectedEntries = 0, + tmpFontAssets = emptyList(), + rawFonts = emptyList(), + unavailableReason = UnityTextUnavailableReason.NOT_SERIALIZED_FILE, + summaryStatement = "Bundle format does not expose serialized font objects", + ) + } + UnityFontInspector.putCachedReport(canonicalPath, fileLength, lastModified, scope, report) + return report + } + + private fun inspectStandaloneFonts( + index: SerializedFileIndex, + singleEntry: UnityBundleEntry?, + ): UnityFontReport { + ensureUnityOperationActive() + val rawFonts = ArrayList() + val rawByPartAndId = LinkedHashMap, UnityRawFontReport>() + var strippedTypeTrees = 0 + + // Always scan Font (class 128) slots first so m_SourceFontFile references resolve cleanly. + index.slots.forEach { slot -> + ensureUnityOperationActive() + if (slot.classId == UnityFontInspector.FONT_CLASS_ID) { + val tree = index.trees.getOrNull(slot.typeIndex) + if (tree == null) { + strippedTypeTrees++ + return@forEach + } + val entryObj = summary.entries.firstOrNull { it.name == slot.entryName } ?: return@forEach + val decoded = index.decodeResult(dataFile, entryObj) + if (decoded is SerializedDecodeResult.Success && decoded.value is UVal.Struct) { + val raw = UnityFontInspector.inspectRawFont(slot.entryName, 0, slot.pathId, decoded.value) + if (singleEntry == null || singleEntry.name == slot.entryName) rawFonts += raw + rawByPartAndId[0 to slot.pathId] = raw + } + } + } + + val tmpAssets = ArrayList() + val targetSlots = if (singleEntry != null) { + listOfNotNull(index.slotFor(singleEntry)) + } else { + index.slots + } + targetSlots.forEach { slot -> + ensureUnityOperationActive() + if (slot.classId == UnityFontInspector.MONO_BEHAVIOUR_CLASS_ID) { + val tree = index.trees.getOrNull(slot.typeIndex) + if (tree == null) { + strippedTypeTrees++ + return@forEach + } + if (!UnityFontInspector.hasTmpFontAssetShape(tree.root)) return@forEach + val entryObj = summary.entries.firstOrNull { it.name == slot.entryName } ?: return@forEach + val decoded = index.decodeResult(dataFile, entryObj) + if (decoded is SerializedDecodeResult.Success && + decoded.value is UVal.Struct && + UnityFontInspector.isTmpFontAsset(decoded.value) + ) { + tmpAssets += UnityFontInspector.inspectTmpFontAsset( + entryName = slot.entryName, + partIndex = 0, + pathId = slot.pathId, + struct = decoded.value, + rawFontsByPartAndId = rawByPartAndId, + ) + } + } + } + + val reason = deriveFontUnavailableReason(tmpAssets, rawFonts, strippedTypeTrees) + return UnityFontReport( + inspectedEntries = if (singleEntry != null) 1 else summary.entries.size, + tmpFontAssets = tmpAssets, + rawFonts = rawFonts, + strippedTypeTreeObjects = strippedTypeTrees, + unavailableReason = reason, + summaryStatement = UnityFontInspector.buildSummaryStatement(tmpAssets, rawFonts, strippedTypeTrees), + ) + } + + private fun inspectEmbeddedFonts(entries: List): UnityFontReport { + val rawFonts = ArrayList() + val tmpAssets = ArrayList() + var strippedTypeTrees = 0 + var serializedEntriesCount = 0 + var firstParseFailure: EmbeddedParse.Failure? = null + + entries.forEach { bundleEntry -> + ensureUnityOperationActive() + val parsed = embedded(bundleEntry) + if (parsed is EmbeddedParse.Failure) { + if (firstParseFailure == null) firstParseFailure = parsed + return@forEach + } + val embeddedSuccess = parsed as EmbeddedParse.Success + serializedEntriesCount++ + val rawByPartAndId = LinkedHashMap, UnityRawFontReport>() + + embeddedSuccess.parts.forEach { part -> + part.index.slots.forEach { slot -> + ensureUnityOperationActive() + if (slot.classId == UnityFontInspector.FONT_CLASS_ID) { + val tree = part.index.trees.getOrNull(slot.typeIndex) + if (tree == null) { + strippedTypeTrees++ + return@forEach + } + val objectEntry = part.summary.entries.firstOrNull { it.name == slot.entryName } ?: return@forEach + val decoded = part.index.decodeResult(dataFile, objectEntry) + if (decoded is SerializedDecodeResult.Success && decoded.value is UVal.Struct) { + val raw = UnityFontInspector.inspectRawFont( + entryName = bundleEntry.name, + partIndex = part.partIndex, + pathId = slot.pathId, + struct = decoded.value, + ) + rawFonts += raw + rawByPartAndId[part.partIndex to slot.pathId] = raw + } + } + } + + part.index.slots.forEach { slot -> + ensureUnityOperationActive() + if (slot.classId == UnityFontInspector.MONO_BEHAVIOUR_CLASS_ID) { + val tree = part.index.trees.getOrNull(slot.typeIndex) + if (tree == null) { + strippedTypeTrees++ + return@forEach + } + if (!UnityFontInspector.hasTmpFontAssetShape(tree.root)) return@forEach + val objectEntry = part.summary.entries.firstOrNull { it.name == slot.entryName } ?: return@forEach + val decoded = part.index.decodeResult(dataFile, objectEntry) + if (decoded is SerializedDecodeResult.Success && + decoded.value is UVal.Struct && + UnityFontInspector.isTmpFontAsset(decoded.value) + ) { + tmpAssets += UnityFontInspector.inspectTmpFontAsset( + entryName = bundleEntry.name, + partIndex = part.partIndex, + pathId = slot.pathId, + struct = decoded.value, + rawFontsByPartAndId = rawByPartAndId, + ) + } + } + } + } + } + + if (serializedEntriesCount == 0 && firstParseFailure != null) { + return UnityFontReport( + inspectedEntries = 0, + tmpFontAssets = emptyList(), + rawFonts = emptyList(), + unavailableReason = firstParseFailure!!.reason, + summaryStatement = firstParseFailure!!.diagnostic, + ) + } + + val reason = deriveFontUnavailableReason(tmpAssets, rawFonts, strippedTypeTrees) + return UnityFontReport( + inspectedEntries = serializedEntriesCount, + tmpFontAssets = tmpAssets, + rawFonts = rawFonts, + strippedTypeTreeObjects = strippedTypeTrees, + unavailableReason = reason, + summaryStatement = UnityFontInspector.buildSummaryStatement(tmpAssets, rawFonts, strippedTypeTrees), + ) + } + + private fun deriveFontUnavailableReason( + tmpAssets: List, + rawFonts: List, + strippedTypeTrees: Int, + ): UnityTextUnavailableReason? { + if (tmpAssets.isEmpty() && rawFonts.isEmpty()) { + return if (strippedTypeTrees > 0) { + UnityTextUnavailableReason.NO_TYPE_INFORMATION + } else { + UnityTextUnavailableReason.FONT_ASSET_NOT_FOUND + } + } + if (tmpAssets.any { it.canRenderPersian }) return null + tmpAssets.firstNotNullOfOrNull { it.statusReason }?.let { return it } + if (tmpAssets.isEmpty() && rawFonts.none { it.supportsArabicCmap }) { + return UnityTextUnavailableReason.FONT_NO_GLYPHS + } + return null + } + + /** + * Option A: Switches `TMP_FontAsset` object(s) in [entry] to `m_AtlasPopulationMode = 1` + * (Dynamic) and binds `m_SourceFontFile` to a same-file `Font` (`classId = 128`), optionally + * replacing that `Font`'s `m_FontData` with [ttfBytes]. + */ + fun patchFontForDynamicGeneration( + entry: UnityBundleEntry, + ttfBytes: ByteArray? = null, + targetTmpPathId: Long? = null, + targetFontPathId: Long? = null, + ): UnityFontPatchResult = try { + withOpenDocument { + patchFontForDynamicGenerationOpen(entry, ttfBytes, targetTmpPathId, targetFontPathId) + } + } catch (_: UnityDocumentClosedException) { + UnityFontPatchResult.Unavailable( + UnityTextUnavailableReason.DOCUMENT_CLOSED, + "Unity document is closed", + ) + } + + private fun patchFontForDynamicGenerationOpen( + entry: UnityBundleEntry, + ttfBytes: ByteArray?, + targetTmpPathId: Long?, + targetFontPathId: Long?, + ): UnityFontPatchResult { + requireEntry(entry) + if (ttfBytes != null) { + if (!TtfCmapInspector.isValidFontHeader(ttfBytes)) { + return UnityFontPatchResult.Unavailable( + UnityTextUnavailableReason.DECODE_FAILED, + "Supplied font file is not a valid TrueType/OpenType (sfnt) font", + ) + } + if (!TtfCmapInspector.supportsArabicScript(ttfBytes)) { + return UnityFontPatchResult.Unavailable( + UnityTextUnavailableReason.FONT_NO_GLYPHS, + "Supplied font file does not contain Arabic/Persian codepoints in its cmap table", + ) + } + } + + val standalone = serialized + if (standalone != null) { + return patchStandaloneFont(standalone, entry, ttfBytes, targetTmpPathId, targetFontPathId) + } + val embedded = when (val parsed = embedded(entry)) { + is EmbeddedParse.Failure -> return UnityFontPatchResult.Unavailable(parsed.reason, parsed.diagnostic) + is EmbeddedParse.Success -> parsed + } + return patchEmbeddedFont(entry, embedded, ttfBytes, targetTmpPathId, targetFontPathId) + } + + private fun patchStandaloneFont( + index: SerializedFileIndex, + selectedEntry: UnityBundleEntry, + ttfBytes: ByteArray?, + targetTmpPathId: Long?, + targetFontPathId: Long?, + ): UnityFontPatchResult { + val scratch = dataFile.parentFile ?: throw IOException("Unity cache directory is missing") + val replacements = LinkedHashMap() + val tempFiles = ArrayList() + try { + val partResult = buildPartFontReplacements( + partIndex = 0, + index = index, + entries = summary.entries, + scratch = scratch, + ttfBytes = ttfBytes, + targetTmpPathId = targetTmpPathId ?: index.slotFor(selectedEntry)?.takeIf { + it.classId == UnityFontInspector.MONO_BEHAVIOUR_CLASS_ID + }?.pathId, + targetFontPathId = targetFontPathId, + tempFiles = tempFiles, + ) + when (partResult) { + is PartFontPatchOutcome.Unavailable -> return UnityFontPatchResult.Unavailable(partResult.reason, partResult.diagnostic) + is PartFontPatchOutcome.Patched -> replacements.putAll(partResult.replacements) + } + + val rebuiltFile = File(scratch, ".standalone-font-${System.nanoTime()}.assets") + tempFiles += rebuiltFile + index.rebuild(rebuiltFile, dataFile, replacements, summary.entries) + val verifyData = File(scratch, ".standalone-verify-${System.nanoTime()}.data") + tempFiles += verifyData + val (rebuiltSummary, rebuiltIndex) = SerializedFileReader.parse(rebuiltFile, verifyData) + val updatedDoc = UnityBundleDocument(rebuiltFile, rebuiltSummary, verifyData, rebuiltIndex) + val updatedReport = updatedDoc.inspectFonts() + UnityFontInspector.clearCache() + return UnityFontPatchResult.Success( + rebuiltEntryBytes = rebuiltFile.readBytes(), + patchedTmpAssets = partResult.patchedTmpCount, + boundFontPathId = partResult.boundFontPathId, + updatedReport = updatedReport, + ) + } finally { + tempFiles.forEach { it.delete() } + } + } + + private fun patchEmbeddedFont( + entry: UnityBundleEntry, + embedded: EmbeddedParse.Success, + ttfBytes: ByteArray?, + targetTmpPathId: Long?, + targetFontPathId: Long?, + ): UnityFontPatchResult { + val scratch = dataFile.parentFile ?: throw IOException("Unity cache directory is missing") + val rebuiltEntry = File(scratch, ".font-entry-${System.nanoTime()}.bin") + val tempFiles = ArrayList() + var totalPatchedTmp = 0 + var chosenFontPathId = 0L + var lastUnavailable: PartFontPatchOutcome.Unavailable? = null + + try { + RandomAccessFile(dataFile, "r").use { sourceData -> + FileOutputStream(rebuiltEntry).buffered(BUFFER_SIZE).use { combinedOut -> + var sourceCursor = 0L + embedded.parts.forEach { part -> + if (part.relativeOffset < sourceCursor) { + throw UnityFormatException("Embedded serialized-file ranges overlap") + } + val gap = part.relativeOffset - sourceCursor + if (gap > 0) { + sourceData.seek(entry.offset + sourceCursor) + copyExactly(sourceData, combinedOut, gap) + } + val outcome = buildPartFontReplacements( + partIndex = part.partIndex, + index = part.index, + entries = part.summary.entries, + scratch = scratch, + ttfBytes = ttfBytes, + targetTmpPathId = targetTmpPathId, + targetFontPathId = targetFontPathId, + tempFiles = tempFiles, + ) + when (outcome) { + is PartFontPatchOutcome.Unavailable -> { + lastUnavailable = outcome + sourceData.seek(entry.offset + part.relativeOffset) + copyExactly(sourceData, combinedOut, part.declaredSize) + } + is PartFontPatchOutcome.Patched -> { + totalPatchedTmp += outcome.patchedTmpCount + chosenFontPathId = outcome.boundFontPathId + val rebuiltPart = File(scratch, ".font-part-${part.partIndex}-${System.nanoTime()}.assets") + tempFiles += rebuiltPart + part.index.rebuild(rebuiltPart, dataFile, outcome.replacements, part.summary.entries) + rebuiltPart.inputStream().buffered(BUFFER_SIZE).use { it.copyTo(combinedOut, BUFFER_SIZE) } + } + } + sourceCursor = checkedAdd(part.relativeOffset, part.declaredSize, "Embedded serialized-file range overflows") + } + if (sourceCursor < entry.size) { + sourceData.seek(entry.offset + sourceCursor) + copyExactly(sourceData, combinedOut, entry.size - sourceCursor) + } + } + } + + if (totalPatchedTmp == 0) { + val unavail = lastUnavailable + return UnityFontPatchResult.Unavailable( + unavail?.reason ?: UnityTextUnavailableReason.FONT_ASSET_NOT_FOUND, + unavail?.diagnostic ?: "No compatible TMP_FontAsset could be patched in ${entry.name}", + ) + } + if (rebuiltEntry.length() > MAX_REBUILD_BYTES || rebuiltEntry.length() > Int.MAX_VALUE) { + throw UnityFormatException("Rebuilt serialized entry is too large") + } + + // Re-parse the rebuilt embedded entry to verify all structural invariants and build the updated report. + val verifyParsed = SerializedFileReader.parseEmbedded(rebuiltEntry, 0L, rebuiltEntry.length()) + val verifyDoc = UnityBundleDocument(rebuiltEntry, verifyParsed.first, rebuiltEntry, verifyParsed.second) + val updatedReport = verifyDoc.inspectFonts() + UnityFontInspector.clearCache() + return UnityFontPatchResult.Success( + rebuiltEntryBytes = rebuiltEntry.readBytes(), + patchedTmpAssets = totalPatchedTmp, + boundFontPathId = chosenFontPathId, + updatedReport = updatedReport, + ) + } finally { + tempFiles.forEach { it.delete() } + rebuiltEntry.delete() + } + } + + private sealed class PartFontPatchOutcome { + data class Patched( + val replacements: Map, + val patchedTmpCount: Int, + val boundFontPathId: Long, + ) : PartFontPatchOutcome() + + data class Unavailable( + val reason: UnityTextUnavailableReason, + val diagnostic: String, + ) : PartFontPatchOutcome() + } + + private fun buildPartFontReplacements( + partIndex: Int, + index: SerializedFileIndex, + entries: List, + scratch: File, + ttfBytes: ByteArray?, + targetTmpPathId: Long?, + targetFontPathId: Long?, + tempFiles: MutableList, + ): PartFontPatchOutcome { + val entriesByName = entries.associateBy { it.name } + val fontSlots = index.slots.filter { it.classId == UnityFontInspector.FONT_CLASS_ID } + val tmpCandidates = index.slots.filter { slot -> + slot.classId == UnityFontInspector.MONO_BEHAVIOUR_CLASS_ID && + (targetTmpPathId == null || slot.pathId == targetTmpPathId) + } + + val decodedTmps = ArrayList>() + var missingTypeTree = false + tmpCandidates.forEach { slot -> + val tree = index.trees.getOrNull(slot.typeIndex) + if (tree == null) { + missingTypeTree = true + return@forEach + } + if (!UnityFontInspector.hasTmpFontAssetShape(tree.root)) return@forEach + val objEntry = entriesByName[slot.entryName] ?: return@forEach + val decoded = index.decodeResult(dataFile, objEntry) + if (decoded is SerializedDecodeResult.Success && + decoded.value is UVal.Struct && + UnityFontInspector.isTmpFontAsset(decoded.value) + ) { + decodedTmps += slot to decoded.value + } + } + + if (decodedTmps.isEmpty()) { + return if (missingTypeTree) { + PartFontPatchOutcome.Unavailable( + UnityTextUnavailableReason.NO_TYPE_INFORMATION, + "MonoBehaviour objects in part $partIndex have no type trees", + ) + } else { + PartFontPatchOutcome.Unavailable( + UnityTextUnavailableReason.FONT_ASSET_NOT_FOUND, + "No TMP_FontAsset MonoBehaviour found in part $partIndex", + ) + } + } + + val chosenFontSlot = when { + targetFontPathId != null -> fontSlots.firstOrNull { it.pathId == targetFontPathId } + else -> { + val existingReferencedId = decodedTmps.firstNotNullOfOrNull { (_, struct) -> + val pptr = struct.fields["m_SourceFontFile"] as? UVal.Struct + val fileId = (pptr?.fields?.get("m_FileID") as? UVal.Num)?.value?.toInt() ?: 0 + val pathId = (pptr?.fields?.get("m_PathID") as? UVal.Num)?.value ?: 0L + pathId.takeIf { fileId == 0 && it != 0L } + } + if (existingReferencedId != null) { + fontSlots.firstOrNull { it.pathId == existingReferencedId } ?: fontSlots.firstOrNull() + } else { + fontSlots.firstOrNull() + } + } + } + + val replacements = LinkedHashMap() + + if (chosenFontSlot != null) { + val fontTree = index.trees.getOrNull(chosenFontSlot.typeIndex) + ?: return PartFontPatchOutcome.Unavailable( + UnityTextUnavailableReason.NO_TYPE_INFORMATION, + "Font #${chosenFontSlot.pathId} has no type tree", + ) + val fontEntry = entriesByName[chosenFontSlot.entryName] + ?: return PartFontPatchOutcome.Unavailable( + UnityTextUnavailableReason.DECODE_FAILED, + "Font slot #${chosenFontSlot.pathId} is missing from entry table", + ) + val decodedFont = index.decodeResult(dataFile, fontEntry) + val fontStruct = (decodedFont as? SerializedDecodeResult.Success)?.value as? UVal.Struct + ?: return PartFontPatchOutcome.Unavailable( + UnityTextUnavailableReason.DECODE_FAILED, + "Could not decode Font #${chosenFontSlot.pathId}", + ) + if (ttfBytes != null) { + UnityFontInspector.replaceRawFontData(fontStruct, ttfBytes) + val encodedFont = index.encode(dataFile, fontEntry, fontStruct) + val fontFile = File(scratch, ".font-obj-$partIndex-${chosenFontSlot.pathId}-${System.nanoTime()}.bin") + fontFile.writeBytes(encodedFont) + tempFiles += fontFile + replacements[chosenFontSlot.entryName] = fontFile + } else { + val existingBytes = UnityFontInspector.extractFontDataBytes(fontStruct) + if (!TtfCmapInspector.supportsArabicScript(existingBytes)) { + return PartFontPatchOutcome.Unavailable( + UnityTextUnavailableReason.FONT_NO_GLYPHS, + "In-bundle Font #${chosenFontSlot.pathId} does not contain Arabic/Persian glyphs; supply a TTF font", + ) + } + } + + decodedTmps.forEach { (tmpSlot, tmpStruct) -> + val tmpEntry = entriesByName.getValue(tmpSlot.entryName) + UnityFontInspector.applyDynamicFontBinding( + tmpStruct = tmpStruct, + sourceFileId = 0, + sourcePathId = chosenFontSlot.pathId, + sameFileSlots = index.slots, + ) + val encodedTmp = index.encode(dataFile, tmpEntry, tmpStruct) + val tmpFile = File(scratch, ".tmp-obj-$partIndex-${tmpSlot.pathId}-${System.nanoTime()}.bin") + tmpFile.writeBytes(encodedTmp) + tempFiles += tmpFile + replacements[tmpSlot.entryName] = tmpFile + } + + return PartFontPatchOutcome.Patched( + replacements = replacements, + patchedTmpCount = decodedTmps.size, + boundFontPathId = chosenFontSlot.pathId, + ) + } + + // No same-file Font (classId = 128) slot exists. + // If ttfBytes == null and the TMP_FontAsset already references an external m_SourceFontFile + // (m_FileID != 0 && m_PathID != 0), we can still switch m_AtlasPopulationMode from 0 to 1. + if (ttfBytes == null) { + var externalPathId = 0L + decodedTmps.forEach { (tmpSlot, tmpStruct) -> + val pptr = tmpStruct.fields["m_SourceFontFile"] as? UVal.Struct + val fileId = (pptr?.fields?.get("m_FileID") as? UVal.Num)?.value?.toInt() ?: 0 + val pathId = (pptr?.fields?.get("m_PathID") as? UVal.Num)?.value ?: 0L + if (fileId != 0 && pathId != 0L) { + val tmpEntry = entriesByName.getValue(tmpSlot.entryName) + UnityFontInspector.applyDynamicFontBinding( + tmpStruct = tmpStruct, + sourceFileId = fileId, + sourcePathId = pathId, + sameFileSlots = index.slots, + ) + val encodedTmp = index.encode(dataFile, tmpEntry, tmpStruct) + val tmpFile = File(scratch, ".tmp-ext-$partIndex-${tmpSlot.pathId}-${System.nanoTime()}.bin") + tmpFile.writeBytes(encodedTmp) + tempFiles += tmpFile + replacements[tmpSlot.entryName] = tmpFile + externalPathId = pathId + } + } + if (replacements.isNotEmpty()) { + return PartFontPatchOutcome.Patched( + replacements = replacements, + patchedTmpCount = replacements.size, + boundFontPathId = externalPathId, + ) + } + } + + return PartFontPatchOutcome.Unavailable( + UnityTextUnavailableReason.FONT_STATIC_NO_SOURCE, + "Serialized file has no Font (classID 128) object slot and SerializedFileIndex cannot insert new object-table rows", + ) + } + private fun inspectObject(index: SerializedFileIndex, entry: UnityBundleEntry): UnityTextInspection { return when (val decoded = index.decodeResult(dataFile, entry)) { is SerializedDecodeResult.Failure -> inspectionFailure(decoded) diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityFontInspector.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityFontInspector.kt new file mode 100644 index 0000000..d4ccd42 --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityFontInspector.kt @@ -0,0 +1,685 @@ +package dev.cluvex.strata.core.unity + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +enum class UnityFontPopulationMode { + STATIC, + DYNAMIC, + STATIC_WITH_SOURCE, + UNKNOWN, +} + +data class UnicodeBlockCoverage( + val arabicBaseCount: Int = 0, + val presentationFormsACount: Int = 0, + val presentationFormsBCount: Int = 0, + val basicLatinCount: Int = 0, + val latinSupplementCount: Int = 0, + val cyrillicCount: Int = 0, + val generalPunctuationCount: Int = 0, + val cjkCount: Int = 0, + val otherCount: Int = 0, +) { + val arabicTotalCount: Int + get() = arabicBaseCount + presentationFormsACount + presentationFormsBCount + + val latinTotalCount: Int + get() = basicLatinCount + latinSupplementCount + + val totalCount: Int + get() = arabicTotalCount + latinTotalCount + cyrillicCount + generalPunctuationCount + cjkCount + otherCount + + fun coveredScriptNames(): List { + val scripts = ArrayList(5) + if (latinTotalCount > 0) scripts += "Latin" + if (cyrillicCount > 0) scripts += "Cyrillic" + if (arabicBaseCount > 0) scripts += "Arabic" + if (presentationFormsACount > 0 || presentationFormsBCount > 0) scripts += "Arabic Presentation Forms" + if (cjkCount > 0) scripts += "CJK" + if (generalPunctuationCount > 0 && scripts.isEmpty()) scripts += "Punctuation" + if (otherCount > 0 && scripts.isEmpty()) scripts += "Symbols" + return scripts + } +} + +data class UnityTmpFontAssetReport( + val entryName: String, + val partIndex: Int, + val pathId: Long, + val name: String, + val glyphCount: Int, + val characterCount: Int, + val populationModeRaw: Int, + val populationMode: UnityFontPopulationMode, + val sourceFontFileId: Int, + val sourceFontPathId: Long, + val resolvedSourceFontName: String?, + val sourceFontSupportsArabic: Boolean, + val atlasTextureCount: Int, + val atlasWidth: Int, + val atlasHeight: Int, + val coverage: UnicodeBlockCoverage, + val codepoints: Set, + val statusReason: UnityTextUnavailableReason?, + val capabilityStatement: String, +) { + val canRenderPersian: Boolean + get() = statusReason == null && ( + coverage.arabicTotalCount > 0 || + (populationMode == UnityFontPopulationMode.DYNAMIC && sourceFontPathId != 0L && sourceFontSupportsArabic) + ) +} + +data class UnityRawFontReport( + val entryName: String, + val partIndex: Int, + val pathId: Long, + val name: String, + val embeddedFontBytes: Int, + val fontFormat: String?, + val supportsArabicCmap: Boolean, + val characterRectCount: Int, +) + +data class UnityFontReport( + val inspectedEntries: Int, + val tmpFontAssets: List, + val rawFonts: List, + val strippedTypeTreeObjects: Int = 0, + val unavailableReason: UnityTextUnavailableReason? = null, + val summaryStatement: String, +) { + val canRenderPersian: Boolean + get() = tmpFontAssets.any { it.canRenderPersian } || + (tmpFontAssets.isEmpty() && rawFonts.any { it.supportsArabicCmap }) + + /** + * Returns all non-whitespace codepoints from [text] that are missing across every static + * `TMP_FontAsset` when no dynamic Arabic-capable `TMP_FontAsset` is present. + */ + fun missingCodepointsFor(text: String): Set { + if (tmpFontAssets.any { it.populationMode == UnityFontPopulationMode.DYNAMIC && it.sourceFontSupportsArabic }) { + return emptySet() + } + val available = HashSet() + tmpFontAssets.forEach { available.addAll(it.codepoints) } + val missing = LinkedHashSet() + var i = 0 + while (i < text.length) { + val cp = Character.codePointAt(text, i) + i += Character.charCount(cp) + if (!Character.isWhitespace(cp) && cp !in available) { + missing += cp + } + } + return missing + } +} + +sealed class UnityFontPatchResult { + data class Success( + val rebuiltEntryBytes: ByteArray, + val patchedTmpAssets: Int, + val boundFontPathId: Long, + val updatedReport: UnityFontReport, + ) : UnityFontPatchResult() + + data class Unavailable( + val reason: UnityTextUnavailableReason, + val diagnostic: String, + ) : UnityFontPatchResult() +} + +data class UnityBundleRewriteEstimate( + val bundleName: String, + val uncompressedBytes: Long, + val temporaryDiskBytes: Long, + val estimatedMinSeconds: Int, + val estimatedMaxSeconds: Int, + val isLargeBundle: Boolean, +) + +internal object UnityFontInspector { + private const val FAST_REPACK_BYTES_PER_SEC = 105L * 1024 * 1024 // ~105 MiB/s midrange fast bound + private const val SLOW_REPACK_BYTES_PER_SEC = 35L * 1024 * 1024 // ~35 MiB/s midrange conservative bound + private const val LARGE_BUNDLE_THRESHOLD_BYTES = 50L * 1024 * 1024 // 50 MiB + + private data class CacheKey( + val path: String, + val size: Long, + val lastModified: Long, + val scope: String, + ) + + private val reportCache = object : LinkedHashMap(32, 0.75f, true) { + override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean = size > 32 + } + + fun getCachedReport(path: String, size: Long, lastModified: Long, scope: String): UnityFontReport? = + synchronized(reportCache) { reportCache[CacheKey(path, size, lastModified, scope)] } + + fun putCachedReport(path: String, size: Long, lastModified: Long, scope: String, report: UnityFontReport) { + synchronized(reportCache) { reportCache[CacheKey(path, size, lastModified, scope)] = report } + } + + fun clearCache() { + synchronized(reportCache) { reportCache.clear() } + } + + fun estimateRewrite(bundleName: String, uncompressedBytes: Long): UnityBundleRewriteEstimate { + val safeBytes = uncompressedBytes.coerceAtLeast(0L) + val minSec = ((safeBytes + FAST_REPACK_BYTES_PER_SEC / 2) / FAST_REPACK_BYTES_PER_SEC).toInt().coerceAtLeast(1) + val maxSec = ((safeBytes + SLOW_REPACK_BYTES_PER_SEC - 1) / SLOW_REPACK_BYTES_PER_SEC).toInt().coerceAtLeast(minSec + 1) + return UnityBundleRewriteEstimate( + bundleName = bundleName, + uncompressedBytes = safeBytes, + temporaryDiskBytes = safeBytes, + estimatedMinSeconds = minSec, + estimatedMaxSeconds = maxSec, + isLargeBundle = safeBytes >= LARGE_BUNDLE_THRESHOLD_BYTES, + ) + } + + /** + * Cheap type-tree check on a `MonoBehaviour` (`classId = 114`) so non-font `MonoBehaviour` + * objects are skipped without reading or decoding their payload bytes from disk. + */ + fun hasTmpFontAssetShape(root: TTNode): Boolean { + var hasGlyphTable = false + var hasCharTable = false + var hasFontMeta = false + root.children.forEach { child -> + when (child.name) { + "m_GlyphTable", "m_glyphInfoList" -> hasGlyphTable = true + "m_CharacterTable", "m_characterDictionary" -> hasCharTable = true + "m_AtlasPopulationMode", "m_SourceFontFile", "m_FaceInfo", "m_fontInfo", "m_AtlasTextures", "atlas" -> { + hasFontMeta = true + } + } + } + return hasGlyphTable && hasCharTable && hasFontMeta + } + + /** Shape-based check on a decoded [UVal.Struct] (never matches by asset name). */ + fun isTmpFontAsset(struct: UVal.Struct): Boolean { + val fields = struct.fields + val glyphTable = (fields["m_GlyphTable"] ?: fields["m_glyphInfoList"]) as? UVal.Arr + val charTable = (fields["m_CharacterTable"] ?: fields["m_characterDictionary"]) as? UVal.Arr + if (glyphTable == null || charTable == null) return false + return fields.containsKey("m_AtlasPopulationMode") || + fields.containsKey("m_SourceFontFile") || + fields.containsKey("m_FaceInfo") || + fields.containsKey("m_fontInfo") || + fields.containsKey("m_AtlasTextures") || + fields.containsKey("atlas") + } + + /** + * Enforces structural invariants on a decoded `TMP_FontAsset` before or after modification: + * - `m_GlyphTable` and `m_CharacterTable` must be parallel arrays (`size` must match). + * - Every `m_CharacterTable` entry's `m_GlyphIndex` must index `0 until m_GlyphTable.size`. + * - Every glyph's `m_GlyphRect` must lie within `0..m_AtlasWidth` × `0..m_AtlasHeight` (when positive). + * - Every glyph's `m_AtlasIndex` must lie within `0 until maxOf(1, m_AtlasTextures.size)`. + * - When `m_AtlasPopulationMode == 1` (Dynamic), `m_SourceFontFile.m_PathID` must be non-zero + * and (when `m_FileID == 0` and [sameFileSlots] is provided) resolve to a `Font` (class 128) slot. + */ + fun validateTmpFontAssetInvariants( + value: UVal, + sameFileSlots: List? = null, + ) { + val struct = value as? UVal.Struct + ?: throw UnityFormatException("TMP_FontAsset root value is not a struct") + if (!isTmpFontAsset(struct)) { + throw UnityFormatException("Decoded MonoBehaviour does not have TMP_FontAsset field shape") + } + val fields = struct.fields + val glyphs = ((fields["m_GlyphTable"] ?: fields["m_glyphInfoList"]) as? UVal.Arr)?.items + ?: throw UnityFormatException("TMP_FontAsset is missing m_GlyphTable") + val characters = ((fields["m_CharacterTable"] ?: fields["m_characterDictionary"]) as? UVal.Arr)?.items + ?: throw UnityFormatException("TMP_FontAsset is missing m_CharacterTable") + + if (glyphs.size != characters.size) { + throw UnityFormatException( + "TMP_FontAsset parallel table invariant violated: m_GlyphTable.size (${glyphs.size}) != m_CharacterTable.size (${characters.size})", + ) + } + + val (atlasWidth, atlasHeight) = extractAtlasDimensions(fields) + val atlasCount = ((fields["m_AtlasTextures"] as? UVal.Arr)?.items?.size ?: 1).coerceAtLeast(1) + + glyphs.forEachIndexed { idx, glyphVal -> + val glyph = glyphVal as? UVal.Struct + ?: throw UnityFormatException("m_GlyphTable[$idx] is not a struct") + val atlasIndex = (glyph.fields["m_AtlasIndex"] as? UVal.Num)?.value?.toInt() ?: 0 + if (atlasIndex !in 0 until atlasCount) { + throw UnityFormatException("m_GlyphTable[$idx].m_AtlasIndex ($atlasIndex) is outside 0 until $atlasCount") + } + val rect = glyph.fields["m_GlyphRect"] as? UVal.Struct + if (rect != null && atlasWidth > 0 && atlasHeight > 0) { + val x = (rect.fields["m_X"] as? UVal.Num)?.value?.toInt() ?: 0 + val y = (rect.fields["m_Y"] as? UVal.Num)?.value?.toInt() ?: 0 + val w = (rect.fields["m_Width"] as? UVal.Num)?.value?.toInt() ?: 0 + val h = (rect.fields["m_Height"] as? UVal.Num)?.value?.toInt() ?: 0 + if (x < 0 || y < 0 || w < 0 || h < 0 || x + w > atlasWidth || y + h > atlasHeight) { + throw UnityFormatException( + "m_GlyphTable[$idx].m_GlyphRect ($x,$y,${w}x$h) exceeds atlas bounds ${atlasWidth}x$atlasHeight", + ) + } + } + } + + characters.forEachIndexed { idx, charVal -> + val ch = charVal as? UVal.Struct + ?: throw UnityFormatException("m_CharacterTable[$idx] is not a struct") + val glyphIndex = (ch.fields["m_GlyphIndex"] as? UVal.Num)?.value?.toInt() + if (glyphIndex != null && glyphs.isNotEmpty() && glyphIndex !in 0 until glyphs.size) { + throw UnityFormatException( + "m_CharacterTable[$idx].m_GlyphIndex ($glyphIndex) is outside 0 until ${glyphs.size}", + ) + } + } + + val popMode = (fields["m_AtlasPopulationMode"] as? UVal.Num)?.value?.toInt() ?: 0 + if (popMode == 1) { + val (fileId, pathId) = extractSourceFontPPtr(fields) + if (pathId == 0L) { + throw UnityFormatException("Dynamic TMP_FontAsset (m_AtlasPopulationMode=1) has unbound m_SourceFontFile (m_PathID=0)") + } + if (fileId == 0 && sameFileSlots != null) { + val targetSlot = sameFileSlots.firstOrNull { it.pathId == pathId } + ?: throw UnityFormatException("Dynamic TMP_FontAsset references missing same-file m_SourceFontFile #$pathId") + if (targetSlot.classId != FONT_CLASS_ID) { + throw UnityFormatException( + "Dynamic TMP_FontAsset m_SourceFontFile #$pathId points to classID ${targetSlot.classId}, expected Font ($FONT_CLASS_ID)", + ) + } + } + } + } + + fun inspectRawFont( + entryName: String, + partIndex: Int, + pathId: Long, + struct: UVal.Struct, + ): UnityRawFontReport { + val name = (struct.fields["m_Name"] as? UVal.Str)?.value ?: "" + val fontBytes = extractFontDataBytes(struct) + val format = detectFontFormat(fontBytes) + val supportsArabic = if (fontBytes.isNotEmpty()) { + TtfCmapInspector.supportsArabicScript(fontBytes) + } else { + false + } + val charRects = ((struct.fields["m_CharacterRects"] as? UVal.Arr)?.items?.size) ?: 0 + return UnityRawFontReport( + entryName = entryName, + partIndex = partIndex, + pathId = pathId, + name = name, + embeddedFontBytes = fontBytes.size, + fontFormat = format, + supportsArabicCmap = supportsArabic, + characterRectCount = charRects, + ) + } + + fun inspectTmpFontAsset( + entryName: String, + partIndex: Int, + pathId: Long, + struct: UVal.Struct, + rawFontsByPartAndId: Map, UnityRawFontReport> = emptyMap(), + ): UnityTmpFontAssetReport { + val fields = struct.fields + val name = (fields["m_Name"] as? UVal.Str)?.value ?: "" + val glyphs = ((fields["m_GlyphTable"] ?: fields["m_glyphInfoList"]) as? UVal.Arr)?.items ?: emptyList() + val characters = ((fields["m_CharacterTable"] ?: fields["m_characterDictionary"]) as? UVal.Arr)?.items ?: emptyList() + val popModeRaw = (fields["m_AtlasPopulationMode"] as? UVal.Num)?.value?.toInt() ?: 0 + val (sourceFileId, sourcePathId) = extractSourceFontPPtr(fields) + val resolvedRawFont = if (sourceFileId == 0 && sourcePathId != 0L) { + rawFontsByPartAndId[partIndex to sourcePathId] + } else { + null + } + val populationMode = when { + popModeRaw == 1 || popModeRaw == 2 -> UnityFontPopulationMode.DYNAMIC + popModeRaw == 0 && sourcePathId != 0L -> UnityFontPopulationMode.STATIC_WITH_SOURCE + popModeRaw == 0 -> UnityFontPopulationMode.STATIC + else -> UnityFontPopulationMode.UNKNOWN + } + val (atlasWidth, atlasHeight) = extractAtlasDimensions(fields) + val atlasTextures = ((fields["m_AtlasTextures"] as? UVal.Arr)?.items ?: emptyList()).count { item -> + val pptr = item as? UVal.Struct ?: return@count false + val pid = (pptr.fields["m_PathID"] as? UVal.Num)?.value ?: 0L + pid != 0L + } + + val codepoints = LinkedHashSet(characters.size) + var arabicBase = 0 + var formsA = 0 + var formsB = 0 + var basicLatin = 0 + var latinSupp = 0 + var cyrillic = 0 + var punctuation = 0 + var cjk = 0 + var other = 0 + + characters.forEach { item -> + val charStruct = item as? UVal.Struct ?: return@forEach + val cp = ((charStruct.fields["m_Unicode"] ?: charStruct.fields["id"]) as? UVal.Num)?.value?.toInt() + ?: return@forEach + if (!codepoints.add(cp)) return@forEach + when (cp) { + in 0x0600..0x06FF, in 0x0750..0x077F, in 0x08A0..0x08FF -> arabicBase++ + in 0xFB50..0xFDFF -> formsA++ + in 0xFE70..0xFEFF -> formsB++ + in 0x0020..0x007E -> basicLatin++ + in 0x00A0..0x024F -> latinSupp++ + in 0x0400..0x04FF -> cyrillic++ + in 0x2000..0x206F -> punctuation++ + in 0x3000..0x30FF, in 0x4E00..0x9FFF, in 0xAC00..0xD7AF -> cjk++ + else -> if (cp > 0x0020) other++ + } + } + + val coverage = UnicodeBlockCoverage( + arabicBaseCount = arabicBase, + presentationFormsACount = formsA, + presentationFormsBCount = formsB, + basicLatinCount = basicLatin, + latinSupplementCount = latinSupp, + cyrillicCount = cyrillic, + generalPunctuationCount = punctuation, + cjkCount = cjk, + otherCount = other, + ) + + val sourceSupportsArabic = when { + resolvedRawFont != null -> resolvedRawFont.supportsArabicCmap + sourceFileId != 0 && sourcePathId != 0L -> true // external dependency bundle reference + else -> false + } + + val statusReason = when (populationMode) { + UnityFontPopulationMode.DYNAMIC -> when { + sourcePathId == 0L && coverage.arabicTotalCount == 0 -> UnityTextUnavailableReason.FONT_STATIC_NO_SOURCE + resolvedRawFont != null && !resolvedRawFont.supportsArabicCmap && coverage.arabicTotalCount == 0 -> { + UnityTextUnavailableReason.FONT_NO_GLYPHS + } + else -> null + } + UnityFontPopulationMode.STATIC -> when { + coverage.arabicTotalCount > 0 -> null + characters.isEmpty() -> UnityTextUnavailableReason.FONT_NO_GLYPHS + else -> UnityTextUnavailableReason.FONT_STATIC_NO_SOURCE + } + UnityFontPopulationMode.STATIC_WITH_SOURCE -> when { + coverage.arabicTotalCount > 0 -> null + else -> UnityTextUnavailableReason.FONT_NO_GLYPHS + } + UnityFontPopulationMode.UNKNOWN -> if (coverage.arabicTotalCount > 0) null else UnityTextUnavailableReason.FONT_NO_GLYPHS + } + + val modeLabel = when (populationMode) { + UnityFontPopulationMode.STATIC -> "Static" + UnityFontPopulationMode.DYNAMIC -> "Dynamic" + UnityFontPopulationMode.STATIC_WITH_SOURCE -> "Static + SourceFont" + UnityFontPopulationMode.UNKNOWN -> "Mode($popModeRaw)" + } + val scriptsLabel = coverage.coveredScriptNames().joinToString(", ").ifEmpty { "none" } + val sourceLabel = when { + sourcePathId == 0L -> "no source TTF attached" + resolvedRawFont != null -> { + val fontLabel = resolvedRawFont.name.ifEmpty { "#$sourcePathId" } + val cmapNote = if (resolvedRawFont.supportsArabicCmap) "Arabic cmap" else "no Arabic cmap" + "source TTF '$fontLabel' (#$sourcePathId, $cmapNote) attached" + } + else -> "external source Font (fileID=$sourceFileId, pathID=$sourcePathId) attached" + } + val displayName = name.ifEmpty { "#$pathId" } + val statement = "TMP_FontAsset '$displayName' is $modeLabel with ${glyphs.size} glyphs ($scriptsLabel); " + + "${coverage.arabicTotalCount} Arabic/Persian glyphs; $sourceLabel." + + return UnityTmpFontAssetReport( + entryName = entryName, + partIndex = partIndex, + pathId = pathId, + name = name, + glyphCount = glyphs.size, + characterCount = characters.size, + populationModeRaw = popModeRaw, + populationMode = populationMode, + sourceFontFileId = sourceFileId, + sourceFontPathId = sourcePathId, + resolvedSourceFontName = resolvedRawFont?.name, + sourceFontSupportsArabic = sourceSupportsArabic, + atlasTextureCount = atlasTextures, + atlasWidth = atlasWidth, + atlasHeight = atlasHeight, + coverage = coverage, + codepoints = codepoints, + statusReason = statusReason, + capabilityStatement = statement, + ) + } + + fun buildSummaryStatement( + tmpAssets: List, + rawFonts: List, + strippedTypeTreeObjects: Int, + ): String { + if (tmpAssets.isEmpty() && rawFonts.isEmpty()) { + return if (strippedTypeTreeObjects > 0) { + "No readable font assets ($strippedTypeTreeObjects objects lack type trees)." + } else { + "0 TMP_FontAsset objects and 0 raw Font objects in this scope." + } + } + val statements = ArrayList(tmpAssets.size + 1) + statements += "${tmpAssets.size} TMP_FontAsset(s), ${rawFonts.size} raw Font(s)." + tmpAssets.forEach { statements += it.capabilityStatement } + return statements.joinToString(" ") + } + + /** + * Modifies a decoded `TMP_FontAsset` ([tmpStruct]) in place to use Dynamic population mode + * (`m_AtlasPopulationMode = 1`) and binds `m_SourceFontFile` to `(m_FileID = sourceFileId, m_PathID = sourcePathId)`. + */ + fun applyDynamicFontBinding( + tmpStruct: UVal.Struct, + sourceFileId: Int, + sourcePathId: Long, + sameFileSlots: List? = null, + ) { + val fields = tmpStruct.fields + val currentMode = fields["m_AtlasPopulationMode"] as? UVal.Num + ?: throw UnityFormatException("TMP_FontAsset is missing m_AtlasPopulationMode") + fields["m_AtlasPopulationMode"] = UVal.Num(1L, currentMode.width) + + val sourceFont = fields["m_SourceFontFile"] as? UVal.Struct + ?: throw UnityFormatException("TMP_FontAsset is missing m_SourceFontFile") + val fileIdField = sourceFont.fields["m_FileID"] as? UVal.Num + ?: throw UnityFormatException("m_SourceFontFile is missing m_FileID") + val pathIdField = sourceFont.fields["m_PathID"] as? UVal.Num + ?: throw UnityFormatException("m_SourceFontFile is missing m_PathID") + sourceFont.fields["m_FileID"] = UVal.Num(sourceFileId.toLong(), fileIdField.width) + sourceFont.fields["m_PathID"] = UVal.Num(sourcePathId, pathIdField.width) + + val multiAtlas = fields["m_IsMultiAtlasTexturesEnabled"] + if (multiAtlas is UVal.Bool) { + fields["m_IsMultiAtlasTexturesEnabled"] = UVal.Bool(1) + } + + validateTmpFontAssetInvariants(tmpStruct, sameFileSlots) + } + + /** Replaces `m_FontData` inside a decoded raw `Font` (`classId = 128`) [fontStruct]. */ + fun replaceRawFontData(fontStruct: UVal.Struct, ttfBytes: ByteArray) { + if (!TtfCmapInspector.isValidFontHeader(ttfBytes)) { + throw UnityFormatException("Supplied font file is not a valid TrueType/OpenType (sfnt) font") + } + if (!TtfCmapInspector.supportsArabicScript(ttfBytes)) { + throw UnityFormatException("Supplied font file does not contain Arabic/Persian glyphs in its cmap table") + } + val existing = fontStruct.fields["m_FontData"] + ?: throw UnityFormatException("Font object is missing m_FontData") + when (existing) { + is UVal.Bytes -> fontStruct.fields["m_FontData"] = UVal.Bytes(ttfBytes.copyOf()) + is UVal.Arr -> { + val items = ArrayList(ttfBytes.size) + for (b in ttfBytes) { + items += UVal.Num(b.toLong() and 0xFFL, 1) + } + fontStruct.fields["m_FontData"] = UVal.Arr(items) + } + else -> throw UnityFormatException("Font.m_FontData has unexpected decoded type ${existing::class.simpleName}") + } + } + + fun extractFontDataBytes(fontStruct: UVal.Struct): ByteArray { + return when (val fontData = fontStruct.fields["m_FontData"]) { + is UVal.Bytes -> fontData.data + is UVal.Arr -> { + val out = ByteArray(fontData.items.size) + for (i in fontData.items.indices) { + val num = fontData.items[i] as? UVal.Num ?: return ByteArray(0) + out[i] = num.value.toByte() + } + out + } + else -> ByteArray(0) + } + } + + private fun detectFontFormat(bytes: ByteArray): String? { + if (bytes.size < 4) return null + val b0 = bytes[0].toInt() and 0xFF + val b1 = bytes[1].toInt() and 0xFF + val b2 = bytes[2].toInt() and 0xFF + val b3 = bytes[3].toInt() and 0xFF + return when { + b0 == 0x00 && b1 == 0x01 && b2 == 0x00 && b3 == 0x00 -> "TTF" + b0 == 't'.code && b1 == 'r'.code && b2 == 'u'.code && b3 == 'e'.code -> "TTF" + b0 == 'O'.code && b1 == 'T'.code && b2 == 'T'.code && b3 == 'O'.code -> "OTF" + b0 == 't'.code && b1 == 't'.code && b2 == 'c'.code && b3 == 'f'.code -> "TTC" + else -> null + } + } + + private fun extractSourceFontPPtr(fields: Map): Pair { + val pptr = (fields["m_SourceFontFile"] ?: fields["m_fontAsset"]) as? UVal.Struct + ?: return 0 to 0L + val fileId = (pptr.fields["m_FileID"] as? UVal.Num)?.value?.toInt() ?: 0 + val pathId = (pptr.fields["m_PathID"] as? UVal.Num)?.value ?: 0L + return fileId to pathId + } + + private fun extractAtlasDimensions(fields: Map): Pair { + val directW = (fields["m_AtlasWidth"] as? UVal.Num)?.value?.toInt() + val directH = (fields["m_AtlasHeight"] as? UVal.Num)?.value?.toInt() + if (directW != null && directH != null) return directW to directH + val face = (fields["m_FaceInfo"] ?: fields["m_fontInfo"]) as? UVal.Struct + val faceW = (face?.fields?.get("m_AtlasWidth") as? UVal.Num)?.value?.toInt() + ?: (face?.fields?.get("AtlasWidth") as? UVal.Num)?.value?.toInt() + ?: 0 + val faceH = (face?.fields?.get("m_AtlasHeight") as? UVal.Num)?.value?.toInt() + ?: (face?.fields?.get("AtlasHeight") as? UVal.Num)?.value?.toInt() + ?: 0 + return faceW to faceH + } + + internal const val MONO_BEHAVIOUR_CLASS_ID = 114 + internal const val FONT_CLASS_ID = 128 +} + +/** + * Lightweight, zero-dependency TrueType/OpenType `cmap` inspector for verifying whether an + * embedded or user-supplied font file contains Arabic/Persian Unicode mappings. + */ +internal object TtfCmapInspector { + fun isValidFontHeader(bytes: ByteArray): Boolean { + if (bytes.size < 12) return false + val magic = ByteBuffer.wrap(bytes, 0, 4).order(ByteOrder.BIG_ENDIAN).int + return magic == 0x00010000 || // TrueType + magic == 0x4F54544F || // 'OTTO' OpenType CFF + magic == 0x74727565 || // 'true' + magic == 0x74746366 // 'ttcf' TrueType Collection + } + + fun supportsArabicScript(bytes: ByteArray): Boolean { + if (!isValidFontHeader(bytes)) return false + return runCatching { + val buf = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN) + val sfntOffset = if (buf.getInt(0) == 0x74746366) { + if (bytes.size < 16) return false + val numFonts = buf.getInt(8) + if (numFonts <= 0) return false + buf.getInt(12) + } else { + 0 + } + if (sfntOffset < 0 || sfntOffset + 12 > bytes.size) return false + val numTables = buf.getShort(sfntOffset + 4).toInt() and 0xFFFF + var cmapOffset = -1 + var cmapLength = 0 + val tableDir = sfntOffset + 12 + for (i in 0 until numTables) { + val entry = tableDir + i * 16 + if (entry + 16 > bytes.size) break + val tag = buf.getInt(entry) + if (tag == 0x636D6170) { // 'cmap' + cmapOffset = buf.getInt(entry + 8) + cmapLength = buf.getInt(entry + 12) + break + } + } + if (cmapOffset <= 0 || cmapLength <= 4 || cmapOffset + cmapLength > bytes.size) return false + val numSubtables = buf.getShort(cmapOffset + 2).toInt() and 0xFFFF + for (i in 0 until numSubtables) { + val rec = cmapOffset + 4 + i * 8 + if (rec + 8 > cmapOffset + cmapLength) break + val subOffset = cmapOffset + buf.getInt(rec + 4) + if (subOffset < cmapOffset || subOffset + 4 > bytes.size) continue + val format = buf.getShort(subOffset).toInt() and 0xFFFF + if (format == 4 && subtableFormat4CoversArabic(buf, subOffset, bytes.size)) return true + if (format == 12 && subtableFormat12CoversArabic(buf, subOffset, bytes.size)) return true + } + false + }.getOrDefault(false) + } + + private fun subtableFormat4CoversArabic(buf: ByteBuffer, offset: Int, limit: Int): Boolean { + if (offset + 14 > limit) return false + val segCountX2 = buf.getShort(offset + 6).toInt() and 0xFFFF + val segCount = segCountX2 / 2 + val endCodesOffset = offset + 14 + val startCodesOffset = endCodesOffset + segCountX2 + 2 + if (startCodesOffset + segCountX2 > limit) return false + for (s in 0 until segCount) { + val endCode = buf.getShort(endCodesOffset + s * 2).toInt() and 0xFFFF + val startCode = buf.getShort(startCodesOffset + s * 2).toInt() and 0xFFFF + if (startCode <= 0x064A && endCode >= 0x0627) return true + if (startCode <= 0xFEFC && endCode >= 0xFE80) return true + } + return false + } + + private fun subtableFormat12CoversArabic(buf: ByteBuffer, offset: Int, limit: Int): Boolean { + if (offset + 16 > limit) return false + val numGroups = buf.getInt(offset + 12) + if (numGroups <= 0 || numGroups > 100_000) return false + val groupsOffset = offset + 16 + if (groupsOffset + numGroups * 12 > limit) return false + for (g in 0 until numGroups) { + val base = groupsOffset + g * 12 + val startCode = buf.getInt(base) + val endCode = buf.getInt(base + 4) + if (startCode <= 0x064A && endCode >= 0x0627) return true + if (startCode <= 0xFEFC && endCode >= 0xFE80) return true + } + return false + } +} diff --git a/app/src/main/java/dev/cluvex/strata/core/unity/UnityTextShaper.kt b/app/src/main/java/dev/cluvex/strata/core/unity/UnityTextShaper.kt new file mode 100644 index 0000000..70fdd2c --- /dev/null +++ b/app/src/main/java/dev/cluvex/strata/core/unity/UnityTextShaper.kt @@ -0,0 +1,425 @@ +package dev.cluvex.strata.core.unity + +import java.text.Bidi + +/** + * Individually toggleable text transformations applied before [UnityBundleDocument.rebuildTexts] + * encodes edited strings back into a serialized Unity asset. + * + * - [shapeArabic]: converts logical Arabic/Persian characters (`0x0600..0x06FF`) into contextual + * Unicode Presentation Forms-A (`0xFB50..0xFDFF`) and Presentation Forms-B (`0xFE70..0xFEFF`), + * including mandatory Lam-Alef (`لا`, `لآ`, `لأ`, `لإ`) ligatures and ZWNJ (`\u200C`) boundaries. + * - [reverseBidi]: converts logical bidirectional text into visual left-to-right order using + * [java.text.Bidi] (UAX #9) so renderers without RTL support draw RTL runs right-to-left while + * keeping embedded Latin words and digits (`120`, `2022`, `۱۲۳`) left-to-right. + */ +data class UnityTextTransformOptions( + val shapeArabic: Boolean = false, + val reverseBidi: Boolean = false, +) { + val isEnabled: Boolean get() = shapeArabic || reverseBidi +} + +internal object UnityTextShaper { + private const val ZWNJ = '\u200C' + private const val ZWJ = '\u200D' + private const val TATWEEL = '\u0640' + private const val LAM = '\u0644' + + private enum class JoinType { + NONE, + RIGHT, + DUAL, + TRANSPARENT, + } + + private data class LetterForms( + val isolated: Char, + val finalForm: Char, + val initial: Char = isolated, + val medial: Char = finalForm, + val joinType: JoinType, + ) + + private val LETTER_TABLE: Map = buildMap { + fun right(base: Int, isolated: Int, finalForm: Int) { + put(base.toChar(), LetterForms(isolated.toChar(), finalForm.toChar(), joinType = JoinType.RIGHT)) + } + fun dual(base: Int, isolated: Int, finalForm: Int, initial: Int, medial: Int) { + put( + base.toChar(), + LetterForms( + isolated = isolated.toChar(), + finalForm = finalForm.toChar(), + initial = initial.toChar(), + medial = medial.toChar(), + joinType = JoinType.DUAL, + ), + ) + } + + // Standard Arabic letters (Presentation Forms-B: 0xFE70..0xFEFF) + put('\u0621', LetterForms('\uFE80', '\uFE80', joinType = JoinType.NONE)) // Hamza + right(0x0622, 0xFE81, 0xFE82) // Alef with Madda + right(0x0623, 0xFE83, 0xFE84) // Alef with Hamza above + right(0x0624, 0xFE85, 0xFE86) // Waw with Hamza + right(0x0625, 0xFE87, 0xFE88) // Alef with Hamza below + dual(0x0626, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C) // Yeh with Hamza + right(0x0627, 0xFE8D, 0xFE8E) // Alef + dual(0x0628, 0xFE8F, 0xFE90, 0xFE91, 0xFE92) // Beh + right(0x0629, 0xFE93, 0xFE94) // Teh Marbuta + dual(0x062A, 0xFE95, 0xFE96, 0xFE97, 0xFE98) // Teh + dual(0x062B, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C) // Theh + dual(0x062C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0) // Jeem + dual(0x062D, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4) // Hah + dual(0x062E, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8) // Khah + right(0x062F, 0xFEA9, 0xFEAA) // Dal + right(0x0630, 0xFEAB, 0xFEAC) // Thal + right(0x0631, 0xFEAD, 0xFEAE) // Reh + right(0x0632, 0xFEAF, 0xFEB0) // Zain + dual(0x0633, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4) // Seen + dual(0x0634, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8) // Sheen + dual(0x0635, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC) // Sad + dual(0x0636, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0) // Dad + dual(0x0637, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4) // Tah + dual(0x0638, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8) // Zah + dual(0x0639, 0xFEC9, 0xFECA, 0xFECB, 0xFECC) // Ain + dual(0x063A, 0xFECD, 0xFECE, 0xFECF, 0xFED0) // Ghain + dual(0x0640, 0x0640, 0x0640, 0x0640, 0x0640) // Tatweel + dual(0x0641, 0xFED1, 0xFED2, 0xFED3, 0xFED4) // Feh + dual(0x0642, 0xFED5, 0xFED6, 0xFED7, 0xFED8) // Qaf + dual(0x0643, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC) // Arabic Kaf + dual(0x0644, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0) // Lam + dual(0x0645, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4) // Meem + dual(0x0646, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8) // Noon + dual(0x0647, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC) // Heh + right(0x0648, 0xFEED, 0xFEEE) // Waw + dual(0x0649, 0xFEEF, 0xFEF0, 0xFBE8, 0xFBE9) // Alef Maksura + dual(0x064A, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4) // Arabic Yeh + + // Persian / extended Arabic letters (Presentation Forms-A: 0xFB50..0xFDFF) + right(0x0671, 0xFB50, 0xFB51) // Alef Wasla + dual(0x0679, 0xFB66, 0xFB67, 0xFB68, 0xFB69) // Tteh + dual(0x067E, 0xFB56, 0xFB57, 0xFB58, 0xFB59) // Persian Peh (پ) + dual(0x0686, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D) // Persian Tcheh (چ) + right(0x0688, 0xFB88, 0xFB89) // Ddal + right(0x0691, 0xFB8C, 0xFB8D) // Rreh + right(0x0698, 0xFB8A, 0xFB8B) // Persian Jeh (ژ) + dual(0x06A9, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91) // Persian Keheh (ک) + dual(0x06AF, 0xFB92, 0xFB93, 0xFB94, 0xFB95) // Persian Gaf (گ) + dual(0x06BA, 0xFB9E, 0xFB9F, 0xFB9E, 0xFB9F) // Noon Ghunna + dual(0x06BE, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD) // Heh Doachashmee + right(0x06C0, 0xFBA4, 0xFBA5) // Heh with Yeh above (ۀ) + dual(0x06C1, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9) // Heh Goal + right(0x06C6, 0xFBD9, 0xFBDA) // Oe + right(0x06C7, 0xFBD7, 0xFBD8) // U + right(0x06CB, 0xFBDE, 0xFBDF) // Ve + dual(0x06CC, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF) // Persian Farsi Yeh (ی) + right(0x06D2, 0xFBAE, 0xFBAF) // Yeh Barree + } + + private val LAM_ALEF_LIGATURES: Map> = mapOf( + '\u0622' to ('\uFEF5' to '\uFEF6'), // لآ (isolated, final) + '\u0623' to ('\uFEF7' to '\uFEF8'), // لأ (isolated, final) + '\u0625' to ('\uFEF9' to '\uFEFA'), // لإ (isolated, final) + '\u0627' to ('\uFEFB' to '\uFEFC'), // لا (isolated, final) + ) + + private val MIRRORED_CHARS: Map = mapOf( + '(' to ')', ')' to '(', + '[' to ']', ']' to '[', + '{' to '}', '}' to '{', + '<' to '>', '>' to '<', + '«' to '»', '»' to '«', + '‹' to '›', '›' to '‹', + ) + + /** Applies [options] to every edited value except Unity `m_Name` object identifiers. */ + fun transformEdits( + edits: Map, + options: UnityTextTransformOptions, + ): LinkedHashMap { + val out = LinkedHashMap(edits.size) + edits.forEach { (path, value) -> + val isAssetName = path == "m_Name" || path.endsWith(".m_Name") + out[path] = if (isAssetName || !options.isEnabled) { + value + } else { + transform(value, options) + } + } + return out + } + + fun transform(text: String, options: UnityTextTransformOptions): String { + if (text.isEmpty() || !options.isEnabled) return text + var current = text + if (options.shapeArabic) { + current = shapeArabicPersian(current) + } + if (options.reverseBidi) { + current = reorderBidiVisual(current) + } + return current + } + + /** + * Contextual Arabic/Persian glyph shaping into Presentation Forms-A (`0xFB50..0xFDFF`) and + * Presentation Forms-B (`0xFE70..0xFEFF`). + * + * Handles initial/medial/final/isolated selection, transparent combining marks + * (`0x064B..0x065F`, `0x0670`), ZWNJ (`\u200C`) non-joining boundaries, and mandatory + * Lam-Alef (`لا`, `لآ`, `لأ`, `لإ`) ligatures. + */ + fun shapeArabicPersian(text: String, stripJoinControls: Boolean = true): String { + if (text.isEmpty() || !containsArabicLetters(text)) return text + val n = text.length + val out = StringBuilder(n) + var i = 0 + while (i < n) { + val ch = text[i] + if (ch == ZWNJ || ch == ZWJ) { + if (!stripJoinControls) out.append(ch) + i++ + continue + } + val forms = LETTER_TABLE[ch] + if (forms == null) { + out.append(ch) + i++ + continue + } + + val joinsPrev = canJoinWithPrevious(text, i) + + // Mandatory Lam + Alef ligature check (skipping transparent marks between Lam and Alef) + if (ch == LAM) { + val alefIndex = nextNonTransparentIndex(text, i + 1) + if (alefIndex < n) { + val ligature = LAM_ALEF_LIGATURES[text[alefIndex]] + if (ligature != null) { + out.append(if (joinsPrev) ligature.second else ligature.first) + // Preserve any transparent harakat that appeared between Lam and Alef + for (t in (i + 1) until alefIndex) { + out.append(text[t]) + } + i = alefIndex + 1 + continue + } + } + } + + val joinsNext = (forms.joinType == JoinType.DUAL) && canJoinWithNext(text, i) + val shaped = when { + joinsPrev && joinsNext -> forms.medial + joinsPrev && !joinsNext -> forms.finalForm + !joinsPrev && joinsNext -> forms.initial + else -> forms.isolated + } + out.append(shaped) + i++ + } + return out.toString() + } + + /** + * Visual bidirectional reordering (UAX #9 via [java.text.Bidi]). + * + * Processes each line independently: + * - Pure LTR lines are returned untouched. + * - Lines containing RTL characters are segmented into directional runs; odd-level (RTL) runs + * have their grapheme clusters reversed into visual left-to-right order with mirrored brackets, + * while even-level (LTR) runs — such as Latin identifiers (`Unity`) and digits (`120`, `500`, + * `2022`, `۱۲۳`) — remain left-to-right. + */ + fun reorderBidiVisual(text: String): String { + if (text.isEmpty()) return text + val sb = StringBuilder(text.length) + var lineStart = 0 + var i = 0 + while (i < text.length) { + val ch = text[i] + if (ch == '\r' || ch == '\n') { + sb.append(reorderLineVisual(text.substring(lineStart, i))) + sb.append(ch) + if (ch == '\r' && i + 1 < text.length && text[i + 1] == '\n') { + i++ + sb.append('\n') + } + lineStart = i + 1 + } + i++ + } + if (lineStart <= text.length) { + sb.append(reorderLineVisual(text.substring(lineStart))) + } + return sb.toString() + } + + private data class BidiRun( + val start: Int, + val limit: Int, + val level: Int, + ) + + private fun reorderLineVisual(line: String): String { + if (line.isEmpty()) return line + val normalizedForBidi = normalizePresentationFormsForBidi(line) + val chars = normalizedForBidi.toCharArray() + if (!Bidi.requiresBidi(chars, 0, chars.size) && !containsRtlCharacters(line)) { + return line + } + val baseDirection = if (containsRtlCharacters(line)) { + Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT + } else { + Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT + } + val bidi = Bidi(normalizedForBidi, baseDirection) + if (bidi.isLeftToRight) return line + + val runCount = bidi.runCount + val levels = ByteArray(runCount) + val runs = Array(runCount) { idx -> + val level = bidi.getRunLevel(idx) + levels[idx] = level.toByte() + BidiRun(bidi.getRunStart(idx), bidi.getRunLimit(idx), level) + } + Bidi.reorderVisually(levels, 0, runs, 0, runCount) + + val out = StringBuilder(line.length) + for (r in 0 until runCount) { + val run = runs[r] as BidiRun + val slice = line.substring(run.start, run.limit) + if (run.level and 1 != 0) { + appendReversedRtlRun(out, slice) + } else { + out.append(slice) + } + } + return out.toString() + } + + /** + * Maps Arabic Presentation Forms and Extended Arabic-Indic digits (`۰`..`۹`) where needed + * so [Bidi] assigns the same directional classes after [shapeArabicPersian] as before it. + */ + private fun normalizePresentationFormsForBidi(line: String): String { + var changed = false + val chars = CharArray(line.length) + for (i in line.indices) { + val c = line[i] + // Extended Arabic-Indic digits (U+06F0..U+06F9) have bidi class EN, whereas + // Arabic-Indic digits (U+0660..U+0669) have bidi class AN; both are even-level LTR runs, + // but normalizing Presentation Forms (0xFB50..0xFDFF, 0xFE70..0xFEFF) to AL guarantees + // consistent UAX #9 run levels even on stripped JVM char tables. + val replacement = if (c.code in 0xFB50..0xFDFF || c.code in 0xFE70..0xFEFC) { + changed = true + '\u0628' // AL (Arabic Letter) + } else { + c + } + chars[i] = replacement + } + return if (changed) String(chars) else line + } + + private fun appendReversedRtlRun(out: StringBuilder, run: String) { + // Group each base codepoint with any trailing transparent combining marks so diacritics + // stay attached to their base letter when the RTL run is reversed into visual order. + val clusters = ArrayList(run.length) + var i = 0 + while (i < run.length) { + val start = i + val cp = Character.codePointAt(run, i) + i += Character.charCount(cp) + while (i < run.length && isCombiningMark(Character.codePointAt(run, i))) { + i += Character.charCount(Character.codePointAt(run, i)) + } + val cluster = run.substring(start, i) + if (cluster.length == 1) { + val mirrored = MIRRORED_CHARS[cluster[0]] + clusters += (mirrored?.toString() ?: cluster) + } else { + clusters += cluster + } + } + for (idx in clusters.size - 1 downTo 0) { + out.append(clusters[idx]) + } + } + + private fun joinTypeOf(ch: Char): JoinType { + if (ch == ZWNJ) return JoinType.NONE + if (ch == ZWJ || ch == TATWEEL) return JoinType.DUAL + if (isTransparentChar(ch)) return JoinType.TRANSPARENT + return LETTER_TABLE[ch]?.joinType ?: JoinType.NONE + } + + private fun canJoinWithPrevious(text: String, index: Int): Boolean { + var p = index - 1 + while (p >= 0) { + when (joinTypeOf(text[p])) { + JoinType.TRANSPARENT -> p-- + JoinType.DUAL -> return true + JoinType.RIGHT, JoinType.NONE -> return false + } + } + return false + } + + private fun canJoinWithNext(text: String, index: Int): Boolean { + val next = nextNonTransparentIndex(text, index + 1) + if (next >= text.length) return false + return when (joinTypeOf(text[next])) { + JoinType.DUAL, JoinType.RIGHT -> true + JoinType.NONE, JoinType.TRANSPARENT -> false + } + } + + private fun nextNonTransparentIndex(text: String, startIndex: Int): Int { + var n = startIndex + while (n < text.length && joinTypeOf(text[n]) == JoinType.TRANSPARENT) { + n++ + } + return n + } + + private fun isTransparentChar(ch: Char): Boolean { + val code = ch.code + return code in 0x0610..0x061A || + code in 0x064B..0x065F || + code == 0x0670 || + code in 0x06D6..0x06ED || + code in 0x08D3..0x08FF || + Character.getType(ch).let { + it == Character.NON_SPACING_MARK.toInt() || it == Character.ENCLOSING_MARK.toInt() + } + } + + private fun isCombiningMark(cp: Int): Boolean { + val type = Character.getType(cp) + return type == Character.NON_SPACING_MARK.toInt() || + type == Character.ENCLOSING_MARK.toInt() || + type == Character.COMBINING_SPACING_MARK.toInt() + } + + fun containsArabicLetters(text: String): Boolean { + for (i in text.indices) { + val code = text[i].code + if (code in 0x0600..0x06FF || code in 0x0750..0x077F || code in 0x08A0..0x08FF) { + return true + } + } + return false + } + + fun containsRtlCharacters(text: String): Boolean { + for (i in text.indices) { + val code = text[i].code + if (code in 0x0590..0x08FF || code in 0xFB1D..0xFDFF || code in 0xFE70..0xFEFC) { + return true + } + } + return false + } +} diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt index c77d39d..ec0617c 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetScreen.kt @@ -21,6 +21,7 @@ import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material.icons.rounded.FolderOpen import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button +import androidx.compose.material3.Checkbox import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -54,9 +55,12 @@ import dev.cluvex.strata.core.archive.ArchiveParent import dev.cluvex.strata.core.model.FileItem import dev.cluvex.strata.core.unity.UnityBundleDocument import dev.cluvex.strata.core.unity.UnityBundleEntry +import dev.cluvex.strata.core.unity.UnityBundleRewriteEstimate import dev.cluvex.strata.core.unity.UnityFileKind +import dev.cluvex.strata.core.unity.UnityFontReport import dev.cluvex.strata.core.unity.UnityProbe import dev.cluvex.strata.core.unity.UnityTextInfo +import dev.cluvex.strata.core.unity.UnityTextTransformOptions import dev.cluvex.strata.core.unity.UnityTextUnavailableReason import dev.cluvex.strata.core.util.Formatters import dev.cluvex.strata.ui.isolated @@ -84,6 +88,7 @@ fun UnityAssetScreen( val state by vm.state.collectAsStateWithLifecycle() var localBusy by remember(path) { mutableStateOf(false) } var signPrompt by remember(path) { mutableStateOf(false) } + var fontRewritePrompt by remember(path) { mutableStateOf(null) } LaunchedEffect(path, refreshToken) { vm.open(path) @@ -149,6 +154,13 @@ fun UnityAssetScreen( } } + val fontTtfPicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + val entry = selectedEntry + if (uri != null && entry != null) { + vm.applyDynamicFont(entry, uri, context.contentResolver) + } + } + BackHandler(enabled = !busy) { onBack() } Scaffold( @@ -233,6 +245,19 @@ fun UnityAssetScreen( } else { null }, + onInspectFonts = { vm.inspectFonts(entry) }, + onBindDynamicFont = { + val estimate = vm.estimateRewrite() + if (estimate != null) { + fontRewritePrompt = estimate + } else { + fontTtfPicker.launch(arrayOf("*/*")) + } + }, + fontReport = state.fontReports[entry.name], + textTransformOptions = state.textTransformOptions, + onToggleShapeArabic = vm::setShapeArabic, + onToggleReverseBidi = vm::setReverseBidi, textIssue = state.textIssues[entry.name], ) } ?: Text(stringResource(R.string.unity_select_entry), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 8.dp)) @@ -286,6 +311,35 @@ fun UnityAssetScreen( dismissButton = { TextButton(onClick = { signPrompt = false }) { Text(stringResource(R.string.common_cancel)) } }, ) } + + fontRewritePrompt?.let { estimate -> + AlertDialog( + onDismissRequest = { fontRewritePrompt = null }, + title = { Text(stringResource(R.string.unity_font_rewrite_warning_title)) }, + text = { + Text( + stringResource( + R.string.unity_font_rewrite_warning_body, + isolated(estimate.bundleName), + Formatters.size(estimate.temporaryDiskBytes), + estimate.estimatedMinSeconds, + estimate.estimatedMaxSeconds, + ), + ) + }, + confirmButton = { + TextButton(onClick = { + fontRewritePrompt = null + fontTtfPicker.launch(arrayOf("*/*")) + }) { Text(stringResource(R.string.unity_font_enable_dynamic)) } + }, + dismissButton = { + TextButton(onClick = { fontRewritePrompt = null }) { + Text(stringResource(R.string.common_cancel)) + } + }, + ) + } } @Composable @@ -356,6 +410,12 @@ private fun UnityEntryActions( onExport: () -> Unit, onReplace: () -> Unit, onExportTexts: (() -> Unit)? = null, + onInspectFonts: (() -> Unit)? = null, + onBindDynamicFont: (() -> Unit)? = null, + fontReport: UnityFontReport? = null, + textTransformOptions: UnityTextTransformOptions = UnityTextTransformOptions(), + onToggleShapeArabic: ((Boolean) -> Unit)? = null, + onToggleReverseBidi: ((Boolean) -> Unit)? = null, textIssue: UnityTextUnavailableReason? = null, ) { Surface(shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.surfaceContainer, modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) { @@ -371,12 +431,76 @@ private fun UnityEntryActions( modifier = Modifier.padding(top = 4.dp), ) } + if (fontReport != null) { + Text( + stringResource( + R.string.unity_font_report_title, + fontReport.tmpFontAssets.size, + fontReport.rawFonts.size, + ), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(top = 6.dp), + ) + fontReport.tmpFontAssets.forEach { tmp -> + Text( + isolated(tmp.capabilityStatement), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 2.dp), + ) + } + } Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) { TextButton(onClick = onOpen, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_open_entry), maxLines = 1) } TextButton(onClick = onExport, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_export_entry), maxLines = 1) } TextButton(onClick = onReplace, enabled = !busy, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.unity_replace_entry), maxLines = 1) } } + if (onInspectFonts != null) { + Row(Modifier.fillMaxWidth().padding(top = 4.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + OutlinedButton(onClick = onInspectFonts, enabled = !busy, modifier = Modifier.weight(1f)) { + Text(stringResource(R.string.unity_inspect_fonts), maxLines = 1) + } + if (onBindDynamicFont != null && fontReport != null && fontReport.tmpFontAssets.isNotEmpty()) { + OutlinedButton(onClick = onBindDynamicFont, enabled = !busy, modifier = Modifier.weight(1f)) { + Text(stringResource(R.string.unity_font_enable_dynamic), maxLines = 1) + } + } + } + } if (onExportTexts != null) { + if (onToggleShapeArabic != null && onToggleReverseBidi != null) { + Row( + Modifier.fillMaxWidth().padding(top = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox( + checked = textTransformOptions.shapeArabic, + onCheckedChange = onToggleShapeArabic, + enabled = !busy, + ) + Text( + stringResource(R.string.unity_shape_arabic), + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f), + ) + } + Row( + Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox( + checked = textTransformOptions.reverseBidi, + onCheckedChange = onToggleReverseBidi, + enabled = !busy, + ) + Text( + stringResource(R.string.unity_reverse_bidi), + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.weight(1f), + ) + } + } Button(onClick = onExportTexts, enabled = !busy, modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) { Text(stringResource(R.string.unity_export_texts), maxLines = 1) } @@ -395,6 +519,10 @@ private fun unityTextIssueLabel(reason: UnityTextUnavailableReason): String = wh UnityTextUnavailableReason.TOO_MANY_OBJECTS -> stringResource(R.string.unity_text_too_many_objects) UnityTextUnavailableReason.DECODE_FAILED -> stringResource(R.string.unity_text_decode_failed) UnityTextUnavailableReason.DOCUMENT_CLOSED -> stringResource(R.string.unity_text_document_closed) + UnityTextUnavailableReason.FONT_NO_GLYPHS -> stringResource(R.string.unity_text_font_no_glyphs) + UnityTextUnavailableReason.FONT_STATIC_NO_SOURCE -> stringResource(R.string.unity_text_font_static_no_source) + UnityTextUnavailableReason.FONT_ATLAS_FULL -> stringResource(R.string.unity_text_font_atlas_full) + UnityTextUnavailableReason.FONT_ASSET_NOT_FOUND -> stringResource(R.string.unity_text_font_not_found) } @Composable diff --git a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt index 8e418c0..5453655 100644 --- a/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt +++ b/app/src/main/java/dev/cluvex/strata/feature/unity/UnityAssetViewModel.kt @@ -11,13 +11,17 @@ import dev.cluvex.strata.core.unity.TypeTreeCodec import dev.cluvex.strata.core.unity.UnityBundleDocument import dev.cluvex.strata.core.unity.UnityBundleEntry import dev.cluvex.strata.core.unity.UnityBundleReader +import dev.cluvex.strata.core.unity.UnityBundleRewriteEstimate import dev.cluvex.strata.core.unity.UnityDocumentClosedException +import dev.cluvex.strata.core.unity.UnityFontPatchResult +import dev.cluvex.strata.core.unity.UnityFontReport import dev.cluvex.strata.core.unity.UnityFormatException import dev.cluvex.strata.core.unity.UnityOperationCancelledException import dev.cluvex.strata.core.unity.UnityPackageRepacker import dev.cluvex.strata.core.unity.UnityProbe import dev.cluvex.strata.core.unity.UnityTextInfo import dev.cluvex.strata.core.unity.UnityTextInspection +import dev.cluvex.strata.core.unity.UnityTextTransformOptions import dev.cluvex.strata.core.unity.UnityTextUnavailableReason import dev.cluvex.strata.core.unity.UnityUnsupportedVersionException import kotlinx.coroutines.CancellationException @@ -45,6 +49,8 @@ data class UnityAssetUiState( val replacements: Map = emptyMap(), val textInfos: Map = emptyMap(), val textIssues: Map = emptyMap(), + val fontReports: Map = emptyMap(), + val textTransformOptions: UnityTextTransformOptions = UnityTextTransformOptions(), val exportedTexts: Map = emptyMap(), val navigateTo: String? = null, val output: File? = null, @@ -282,6 +288,124 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { } } + fun setShapeArabic(enabled: Boolean) { + exportedBaselines = emptyMap() + _state.update { + it.copy(textTransformOptions = it.textTransformOptions.copy(shapeArabic = enabled)) + } + } + + fun setReverseBidi(enabled: Boolean) { + exportedBaselines = emptyMap() + _state.update { + it.copy(textTransformOptions = it.textTransformOptions.copy(reverseBidi = enabled)) + } + } + + fun estimateRewrite(): UnityBundleRewriteEstimate? = document?.estimateRewrite() + + fun inspectFonts(entry: UnityBundleEntry) { + val doc = document ?: return + if (_state.value.busy) return + _state.update { it.copy(busy = true) } + viewModelScope.launch { + try { + val report = runInterruptible(Dispatchers.IO) { doc.inspectFonts(entry) } + if (document !== doc) return@launch + _state.update { current -> + current.copy( + busy = false, + fontReports = current.fontReports + (entry.name to report), + message = report.summaryStatement, + ) + } + } catch (e: CancellationException) { + _state.update { + it.copy( + busy = false, + message = getApplication().getString(R.string.unity_operation_cancelled), + ) + } + throw e + } catch (e: Exception) { + val detail = e.message?.takeIf { it.isNotBlank() } + val message = when { + e is UnityDocumentClosedException -> getApplication().getString(R.string.unity_staging_unavailable) + e is UnityOperationCancelledException -> getApplication().getString(R.string.unity_operation_cancelled) + detail != null -> getApplication().getString(R.string.unity_operation_failed_detail, detail) + else -> getApplication().getString(R.string.unity_operation_failed) + } + _state.update { it.copy(busy = false, message = message) } + } + } + } + + fun applyDynamicFont(entry: UnityBundleEntry, ttfUri: Uri?, resolver: ContentResolver) { + val doc = document ?: return + val dir = stageDir ?: return + if (_state.value.busy) return + _state.update { it.copy(busy = true) } + viewModelScope.launch { + try { + val outcome = runInterruptible(Dispatchers.IO) { + val ttfBytes = if (ttfUri != null) { + resolver.openInputStream(ttfUri)?.use { it.readBytes() } + ?: throw IOException("Could not open selected TTF font") + } else { + null + } + doc.patchFontForDynamicGeneration(entry, ttfBytes) + } + when (outcome) { + is UnityFontPatchResult.Success -> { + val staged = runInterruptible(Dispatchers.IO) { + File(dir, "font-${entry.name.hashCode().toUInt().toString(16)}-${System.nanoTime()}.bin").apply { + writeBytes(outcome.rebuiltEntryBytes) + } + } + _state.update { + it.copy( + busy = false, + replacements = it.replacements + (entry.name to staged), + fontReports = it.fontReports + (entry.name to outcome.updatedReport), + message = getApplication().getString( + R.string.unity_font_patch_done, + outcome.patchedTmpAssets, + ), + ) + } + } + is UnityFontPatchResult.Unavailable -> { + _state.update { + it.copy( + busy = false, + textIssues = it.textIssues + (entry.name to outcome.reason), + message = outcome.diagnostic, + ) + } + } + } + } catch (e: CancellationException) { + _state.update { + it.copy( + busy = false, + message = getApplication().getString(R.string.unity_operation_cancelled), + ) + } + throw e + } catch (e: Exception) { + val detail = e.message?.takeIf { it.isNotBlank() } + val message = when { + e is UnityDocumentClosedException -> getApplication().getString(R.string.unity_staging_unavailable) + e is UnityOperationCancelledException -> getApplication().getString(R.string.unity_operation_cancelled) + detail != null -> getApplication().getString(R.string.unity_operation_failed_detail, detail) + else -> getApplication().getString(R.string.unity_operation_failed) + } + _state.update { it.copy(busy = false, message = message) } + } + } + } + /** Merges staged edits, picked replacements and any exported text JSON the user has modified. */ private fun collectChanges(doc: UnityBundleDocument, current: UnityAssetUiState): Map { val dir = stageDir @@ -290,10 +414,16 @@ class UnityAssetViewModel(app: Application) : AndroidViewModel(app) { current.exportedTexts.forEach { (name, jsonFile) -> if (!jsonFile.isFile) return@forEach val baseline = exportedBaselines[name] - if (baseline != null && jsonFile.length() == baseline.first && jsonFile.lastModified() == baseline.second) return@forEach + if (!current.textTransformOptions.isEnabled && + baseline != null && + jsonFile.length() == baseline.first && + jsonFile.lastModified() == baseline.second + ) { + return@forEach + } val entry = doc.summary.entries.firstOrNull { it.name == name } ?: return@forEach val edits = TypeTreeCodec.parseJson(jsonFile.readText()) - val bytes = doc.rebuildTexts(entry, edits) + val bytes = doc.rebuildTexts(entry, edits, current.textTransformOptions) val staged = File(dir, "text-${name.hashCode().toUInt().toString(16)}-${System.nanoTime()}.bin") staged.writeBytes(bytes) textChanges[name] = staged diff --git a/app/src/main/res/values-fa/strings_unity.xml b/app/src/main/res/values-fa/strings_unity.xml index fdc4b5e..d1b67d9 100644 --- a/app/src/main/res/values-fa/strings_unity.xml +++ b/app/src/main/res/values-fa/strings_unity.xml @@ -52,4 +52,16 @@ عملیات لغو شد. نسخهٔ این فایل Unity پشتیبانی نمی‌شود. دادهٔ موقت Unity دیگر در دسترس نیست؛ فایل را دوباره باز کنید. + فونت فاقد گلیف برای خط هدف است. + فونت TMP ایستا فاقد گلیف فارسی/عربی و بدون فایل TTF منبع است. + اطلس بافت فونت فضای خالی برای گلیف‌های جدید ندارد. + هیچ Font یا TMP_FontAsset سازگاری در این ورودی پیدا نشد. + بررسی فونت‌ها + قابلیت فونت (%1$d TMP، %2$d Font) + شکل‌دهی بافتاری حروف فارسی/عربی + بازچینی بصری راست‌به‌چپ (Bidi) + اتصال فونت پویا (TTF)… + بازنویسی بسته برای تغییر فونت؟ + اصلاح فونت در %1$s نیازمند بازخوانی و فشرده‌سازی LZ4 حدود %2$s دادهٔ موقت است (زمان تخمینی %3$d تا %4$d ثانیه). + ‏%1$d فونت TMP به حالت پویا (Dynamic) تبدیل شد. برای ذخیره، بسته را بازسازی کنید. diff --git a/app/src/main/res/values-ru/strings_unity.xml b/app/src/main/res/values-ru/strings_unity.xml index 05bb45e..550a541 100644 --- a/app/src/main/res/values-ru/strings_unity.xml +++ b/app/src/main/res/values-ru/strings_unity.xml @@ -54,4 +54,16 @@ Операция отменена. Эта версия файла Unity не поддерживается. Временные данные Unity больше недоступны; откройте файл заново. + В шрифте отсутствуют глифы для целевой письменности. + Статический шрифт TMP не содержит арабских/персидских глифов и исходного TTF. + В текстурном атласе шрифта нет места для новых глифов. + В этой записи не найдено совместимых Font или TMP_FontAsset. + Проверить шрифты + Возможности шрифтов (%1$d TMP, %2$d Font) + Контекстное соединение арабских/персидских букв + Визуальная перестановка RTL (Bidi) + Привязать динамический шрифт TTF… + Перезаписать пакет для обновления шрифта? + Обновление шрифта в %1$s потребует потоковой перезаписи и LZ4-сжатия %2$s временных данных (около %3$d–%4$d с). + Обновлено шрифтов TMP в динамический режим: %1$d. Пересоберите пакет для сохранения. diff --git a/app/src/main/res/values-zh-rCN/strings_unity.xml b/app/src/main/res/values-zh-rCN/strings_unity.xml index 6d0d870..7e72e61 100644 --- a/app/src/main/res/values-zh-rCN/strings_unity.xml +++ b/app/src/main/res/values-zh-rCN/strings_unity.xml @@ -51,4 +51,16 @@ 操作已取消。 不支持此 Unity 文件版本。 暂存的 Unity 数据已不可用;请重新打开文件。 + 字体资源缺少目标文字的字形。 + 静态 TMP 字体不包含阿拉伯/波斯字形且未附加源 TTF。 + 字体图集纹理已满,无法容纳新字形。 + 此条目中未找到兼容的 Font 或 TMP_FontAsset。 + 检查字体 + 字体能力(%1$d 个 TMP,%2$d 个 Font) + 波斯语/阿拉伯语上下文连字整形 + 视觉 RTL 双向重排 (Bidi) + 绑定动态 TTF 字体… + 重写资源包以更新字体? + 修补 %1$s 中的字体需要重新流式写入并 LZ4 压缩 %2$s 临时数据(预计 %3$d–%4$d 秒)。 + 已将 %1$d 个 TMP 字体资源切换为动态模式。请重建资源包以保存。 diff --git a/app/src/main/res/values/strings_unity.xml b/app/src/main/res/values/strings_unity.xml index 76a8f06..95f242d 100644 --- a/app/src/main/res/values/strings_unity.xml +++ b/app/src/main/res/values/strings_unity.xml @@ -52,4 +52,16 @@ Operation cancelled. This Unity file version is not supported. The staged Unity data is no longer available; reopen the file. + Font asset has no glyphs for the target script. + Static TMP font has 0 Arabic/Persian glyphs and no source TTF. + Font atlas texture has no remaining space for new glyphs. + No compatible Font or TMP_FontAsset found in this entry. + Inspect fonts + Font capability (%1$d TMP, %2$d Font) + Persian/Arabic contextual shaping + Visual RTL bidi reordering + Bind dynamic TTF font… + Rewrite bundle for font update? + Patching fonts in %1$s requires restreaming and LZ4-compressing %2$s of temporary data (estimated %3$d–%4$d s). + Patched %1$d TMP font asset(s) to Dynamic mode. Rebuild the bundle to save. diff --git a/app/src/test/java/dev/cluvex/strata/core/unity/UnityFontAndShapingTest.kt b/app/src/test/java/dev/cluvex/strata/core/unity/UnityFontAndShapingTest.kt new file mode 100644 index 0000000..dd61f69 --- /dev/null +++ b/app/src/test/java/dev/cluvex/strata/core/unity/UnityFontAndShapingTest.kt @@ -0,0 +1,671 @@ +package dev.cluvex.strata.core.unity + +import com.google.common.truth.Truth.assertThat +import org.junit.Assert.assertThrows +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.ByteArrayOutputStream +import java.io.DataOutputStream +import java.io.File +import java.io.FileOutputStream +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class UnityFontAndShapingTest { + @get:Rule + val temp = TemporaryFolder() + + @Test + fun shapesPersianWordsAndLamAlefLigaturesIntoPresentationForms() { + // سلام -> Seen initial (0xFEB3), Lam-Alef final ligature (0xFEFC), Meem isolated (0xFEE1) + assertThat(UnityTextShaper.shapeArabicPersian("سلام")) + .isEqualTo("\uFEB3\uFEFC\uFEE1") + + // ایران -> Alef isolated (0xFE8D), Farsi Yeh initial (0xFBFE), Reh final (0xFEAE), + // Alef isolated (0xFE8D), Noon isolated (0xFEE5) + assertThat(UnityTextShaper.shapeArabicPersian("ایران")) + .isEqualTo("\uFE8D\uFBFE\uFEAE\uFE8D\uFEE5") + + // کتاب -> Persian Keheh initial (0xFB90), Teh medial (0xFE98), Alef final (0xFE8E), Beh isolated (0xFE8F) + assertThat(UnityTextShaper.shapeArabicPersian("کتاب")) + .isEqualTo("\uFB90\uFE98\uFE8E\uFE8F") + + // می‌شود (with ZWNJ \u200C) -> Meem initial (0xFEE3), Farsi Yeh final (0xFBFD), + // ZWNJ stripped, Sheen initial (0xFEB7), Waw final (0xFEEE), Dal isolated (0xFEA9) + assertThat(UnityTextShaper.shapeArabicPersian("می\u200Cشود")) + .isEqualTo("\uFEE3\uFBFD\uFEB7\uFEEE\uFEA9") + + // Persian-specific letters پ چ ژ گ (Presentation Forms-A) + // گچ‌پژ -> Gaf initial (0xFB94), Tcheh final (0xFB7B), Peh initial (0xFB58), Jeh final (0xFB8B) + assertThat(UnityTextShaper.shapeArabicPersian("گچ\u200Cپژ")) + .isEqualTo("\uFB94\uFB7B\uFB58\uFB8B") + + // Mandatory Lam-Alef ligatures: isolated (لا لآ لأ لإ) and final (بلا بلآ بلأ بلإ) + assertThat(UnityTextShaper.shapeArabicPersian("لا لآ لأ لإ")) + .isEqualTo("\uFEFB \uFEF5 \uFEF7 \uFEF9") + assertThat(UnityTextShaper.shapeArabicPersian("بلا بلآ بلأ بلإ")) + .isEqualTo("\uFE91\uFEFC \uFE91\uFEF6 \uFE91\uFEF8 \uFE91\uFEFA") + } + + @Test + fun reordersMixedPersianEnglishAndDigitsVisually() { + val scoreLine = "امتیاز: 120 از 500" + val reorderedScore = UnityTextShaper.reorderBidiVisual(scoreLine) + // Digits "500" and "120" must stay left-to-right; RTL words and run order reverse visually + assertThat(reorderedScore).isEqualTo("500 زا 120 :زایتما") + assertThat(reorderedScore).contains("120") + assertThat(reorderedScore).contains("500") + assertThat(reorderedScore).doesNotContain("021") + assertThat(reorderedScore).doesNotContain("005") + + val versionLine = "نسخه Unity 2022" + val reorderedVersion = UnityTextShaper.reorderBidiVisual(versionLine) + assertThat(reorderedVersion).isEqualTo("Unity 2022 هخسن") + + // Combined shaping + visual bidi reordering + val combined = UnityTextShaper.transform( + "نسخه Unity 2022", + UnityTextTransformOptions(shapeArabic = true, reverseBidi = true), + ) + // نسخه shaped is \uFEE7\uFEB4\uFEA8\uFEEA; reversed visually is \uFEEA\uFEA8\uFEB4\uFEE7 + assertThat(combined).isEqualTo("Unity 2022 \uFEEA\uFEA8\uFEB4\uFEE7") + + // Mirrored parentheses inside an RTL line + assertThat(UnityTextShaper.reorderBidiVisual("سلام (12)")).isEqualTo("(12) مالس") + } + + @Test + fun detectsFontCapabilityAndUnicodeBlockCoverageOnSyntheticTmpAsset() { + // Synthetic TMP_FontAsset with 3 Latin ('A', 'B', 'C'), 2 Cyrillic ('Д', 'Ж'), + // 2 Arabic base ('س', 'م'), 1 Presentation Form-A ('ﭘ'), and 1 Presentation Form-B ('ﻼ') + val codepoints = listOf( + 0x0041, 0x0042, 0x0043, + 0x0414, 0x0416, + 0x0633, 0x0645, + 0xFB58, + 0xFEFC, + ) + val file = writeFontSerializedFile( + root = temp.root, + name = "capable-font.assets", + tmpAssets = listOf( + SyntheticTmpAsset( + pathId = 100L, + name = "DialogueFont SDF", + populationMode = 0, + sourceFontFileId = 0, + sourceFontPathId = 0L, + codepoints = codepoints, + ), + ), + rawFonts = emptyList(), + ) + + UnityBundleReader.open(file, File(temp.root, "cache")).use { document -> + val report = document.inspectFonts() + assertThat(report.tmpFontAssets).hasSize(1) + val tmp = report.tmpFontAssets.single() + assertThat(tmp.name).isEqualTo("DialogueFont SDF") + assertThat(tmp.populationMode).isEqualTo(UnityFontPopulationMode.STATIC) + assertThat(tmp.glyphCount).isEqualTo(9) + assertThat(tmp.characterCount).isEqualTo(9) + assertThat(tmp.coverage.basicLatinCount).isEqualTo(3) + assertThat(tmp.coverage.cyrillicCount).isEqualTo(2) + assertThat(tmp.coverage.arabicBaseCount).isEqualTo(2) + assertThat(tmp.coverage.presentationFormsACount).isEqualTo(1) + assertThat(tmp.coverage.presentationFormsBCount).isEqualTo(1) + assertThat(tmp.coverage.arabicTotalCount).isEqualTo(4) + assertThat(tmp.statusReason).isNull() + assertThat(tmp.canRenderPersian).isTrue() + assertThat(report.canRenderPersian).isTrue() + assertThat(tmp.capabilityStatement).contains("4 Arabic/Persian glyphs") + } + } + + @Test + fun detectsEmptyCharacterTableAndStaticAssetWithoutSourceFont() { + val file = writeFontSerializedFile( + root = temp.root, + name = "missing-arabic.assets", + tmpAssets = listOf( + SyntheticTmpAsset( + pathId = 200L, + name = "EmptyFont SDF", + populationMode = 0, + sourceFontFileId = 0, + sourceFontPathId = 0L, + codepoints = emptyList(), + ), + SyntheticTmpAsset( + pathId = 201L, + name = "TitleFont", + populationMode = 0, + sourceFontFileId = 0, + sourceFontPathId = 0L, + codepoints = listOf(0x0041, 0x0042, 0x0410), // Latin + Cyrillic only + ), + ), + rawFonts = emptyList(), + ) + + UnityBundleReader.open(file, File(temp.root, "cache")).use { document -> + val emptyReport = document.inspectFonts(document.summary.entries[0]) + val emptyAsset = emptyReport.tmpFontAssets.single() + assertThat(emptyAsset.characterCount).isEqualTo(0) + assertThat(emptyAsset.statusReason).isEqualTo(UnityTextUnavailableReason.FONT_NO_GLYPHS) + assertThat(emptyReport.unavailableReason).isEqualTo(UnityTextUnavailableReason.FONT_NO_GLYPHS) + + val staticReport = document.inspectFonts(document.summary.entries[1]) + val staticAsset = staticReport.tmpFontAssets.single() + assertThat(staticAsset.populationMode).isEqualTo(UnityFontPopulationMode.STATIC) + assertThat(staticAsset.coverage.latinTotalCount).isEqualTo(2) + assertThat(staticAsset.coverage.cyrillicCount).isEqualTo(1) + assertThat(staticAsset.coverage.arabicTotalCount).isEqualTo(0) + assertThat(staticAsset.statusReason).isEqualTo(UnityTextUnavailableReason.FONT_STATIC_NO_SOURCE) + assertThat(staticAsset.capabilityStatement).isEqualTo( + "TMP_FontAsset 'TitleFont' is Static with 3 glyphs (Latin, Cyrillic); 0 Arabic/Persian glyphs; no source TTF attached.", + ) + assertThat(staticReport.missingCodepointsFor("سلام")).containsExactly(0x0633, 0x0644, 0x0627, 0x0645) + } + } + + @Test + fun rejectsMismatchedGlyphAndCharacterTableSizes() { + // 3 glyphs in m_GlyphTable vs 2 entries in m_CharacterTable violates the parallel-array invariant. + val struct = buildDecodedTmpStruct( + name = "BrokenFont SDF", + populationMode = 0, + sourceFileId = 0, + sourcePathId = 0L, + glyphCount = 3, + codepoints = listOf(0x0041, 0x0042), + ) + val error = assertThrows(UnityFormatException::class.java) { + UnityFontInspector.validateTmpFontAssetInvariants(struct) + } + assertThat(error).hasMessageThat().contains("m_GlyphTable.size (3) != m_CharacterTable.size (2)") + } + + @Test + fun patchesStaticTmpFontToDynamicWithEmbeddedArabicTtfAndVerifiesRoundTrip() { + val arabicTtf = buildMinimalTtfWithCmap( + ranges = listOf(0x0020..0x007E, 0x0600..0x06FF, 0xFB50..0xFDFF, 0xFE70..0xFEFF), + ) + val file = writeFontSerializedFile( + root = temp.root, + name = "patchable.assets", + tmpAssets = listOf( + SyntheticTmpAsset( + pathId = 300L, + name = "BodyFont SDF", + populationMode = 0, + sourceFontFileId = 0, + sourceFontPathId = 0L, + codepoints = listOf(0x0041, 0x0042), + ), + ), + rawFonts = listOf( + SyntheticRawFont( + pathId = 400L, + name = "Vazirmatn-Regular", + fontData = ByteArray(16), // placeholder before replacement + ), + ), + ) + + UnityBundleReader.open(file, File(temp.root, "cache")).use { document -> + val before = document.inspectFonts() + assertThat(before.canRenderPersian).isFalse() + assertThat(before.tmpFontAssets.single().statusReason) + .isEqualTo(UnityTextUnavailableReason.FONT_STATIC_NO_SOURCE) + + val patchResult = document.patchFontForDynamicGeneration( + entry = document.summary.entries.first(), + ttfBytes = arabicTtf, + ) + assertThat(patchResult).isInstanceOf(UnityFontPatchResult.Success::class.java) + val success = patchResult as UnityFontPatchResult.Success + assertThat(success.patchedTmpAssets).isEqualTo(1) + assertThat(success.boundFontPathId).isEqualTo(400L) + assertThat(success.updatedReport.canRenderPersian).isTrue() + + val updatedTmp = success.updatedReport.tmpFontAssets.single() + assertThat(updatedTmp.populationMode).isEqualTo(UnityFontPopulationMode.DYNAMIC) + assertThat(updatedTmp.sourceFontFileId).isEqualTo(0) + assertThat(updatedTmp.sourceFontPathId).isEqualTo(400L) + assertThat(updatedTmp.sourceFontSupportsArabic).isTrue() + assertThat(updatedTmp.statusReason).isNull() + } + } + + @Test + fun reportsStaticNoSourceWhenPatchingBundleWithZeroRawFontObjects() { + val arabicTtf = buildMinimalTtfWithCmap(ranges = listOf(0x0600..0x06FF)) + val file = writeFontSerializedFile( + root = temp.root, + name = "no-raw-font.assets", + tmpAssets = listOf( + SyntheticTmpAsset( + pathId = 500L, + name = "OrphanStatic SDF", + populationMode = 0, + sourceFontFileId = 0, + sourceFontPathId = 0L, + codepoints = listOf(0x0041), + ), + ), + rawFonts = emptyList(), + ) + + UnityBundleReader.open(file, File(temp.root, "cache")).use { document -> + val result = document.patchFontForDynamicGeneration( + entry = document.summary.entries.single(), + ttfBytes = arabicTtf, + ) + assertThat(result).isInstanceOf(UnityFontPatchResult.Unavailable::class.java) + val unavailable = result as UnityFontPatchResult.Unavailable + assertThat(unavailable.reason).isEqualTo(UnityTextUnavailableReason.FONT_STATIC_NO_SOURCE) + } + } + + @Test + fun rebuildsTextAssetWithToggleableShapingAndBidiWhilePreservingAssetName() { + val file = writeSimpleTextAssetSerializedFile(temp.root, "dialogue.assets", "Localization", "Hello 123") + UnityBundleReader.open(file, File(temp.root, "cache")).use { document -> + val entry = document.summary.entries.single() + val edits = mapOf( + "m_Name" to "Localization", + "m_Script" to "امتیاز: 120 از 500", + ) + val rebuiltBytes = document.rebuildTexts( + entry = entry, + edits = edits, + transformOptions = UnityTextTransformOptions(shapeArabic = true, reverseBidi = true), + ) + val replacement = File(temp.root, "rebuilt-script.bin").apply { writeBytes(rebuiltBytes) } + val output = File(temp.root, "dialogue-rebuilt.assets") + document.repack(output, mapOf(entry.name to replacement)) + + UnityBundleReader.open(output, File(temp.root, "cache2")).use { rebuiltDoc -> + val exported = rebuiltDoc.exportTexts(rebuiltDoc.summary.entries.single())!! + assertThat(exported["m_Name"]).isEqualTo("Localization") + val expectedShapedAndBidi = UnityTextShaper.transform( + "امتیاز: 120 از 500", + UnityTextTransformOptions(shapeArabic = true, reverseBidi = true), + ) + assertThat(exported["m_Script"]).isEqualTo(expectedShapedAndBidi) + } + } + } + + // --------------------------------------------------------------------------------------- + // Synthetic fixtures for TMP_FontAsset (MonoBehaviour class 114), Font (class 128), and TTF + // --------------------------------------------------------------------------------------- + + private data class SyntheticTmpAsset( + val pathId: Long, + val name: String, + val populationMode: Int, + val sourceFontFileId: Int, + val sourceFontPathId: Long, + val codepoints: List, + val atlasWidth: Int = 1024, + val atlasHeight: Int = 1024, + ) + + private data class SyntheticRawFont( + val pathId: Long, + val name: String, + val fontData: ByteArray, + ) + + private fun buildDecodedTmpStruct( + name: String, + populationMode: Int, + sourceFileId: Int, + sourcePathId: Long, + glyphCount: Int, + codepoints: List, + atlasWidth: Int = 1024, + atlasHeight: Int = 1024, + ): UVal.Struct { + val glyphItems = ArrayList(glyphCount) + for (i in 0 until glyphCount) { + glyphItems += UVal.Struct( + linkedMapOf( + "m_Index" to UVal.Num(i.toLong(), 4), + "m_GlyphRect" to UVal.Struct( + linkedMapOf( + "m_X" to UVal.Num((i * 16).toLong(), 4), + "m_Y" to UVal.Num(0L, 4), + "m_Width" to UVal.Num(12L, 4), + "m_Height" to UVal.Num(16L, 4), + ), + ), + "m_AtlasIndex" to UVal.Num(0L, 4), + ), + ) + } + val charItems = ArrayList(codepoints.size) + codepoints.forEachIndexed { idx, cp -> + charItems += UVal.Struct( + linkedMapOf( + "m_Unicode" to UVal.Num(cp.toLong(), 4), + "m_GlyphIndex" to UVal.Num(idx.toLong(), 4), + ), + ) + } + return UVal.Struct( + linkedMapOf( + "m_Name" to UVal.Str(name), + "m_AtlasPopulationMode" to UVal.Num(populationMode.toLong(), 4), + "m_SourceFontFile" to UVal.Struct( + linkedMapOf( + "m_FileID" to UVal.Num(sourceFileId.toLong(), 4), + "m_PathID" to UVal.Num(sourcePathId, 8), + ), + ), + "m_AtlasWidth" to UVal.Num(atlasWidth.toLong(), 4), + "m_AtlasHeight" to UVal.Num(atlasHeight.toLong(), 4), + "m_GlyphTable" to UVal.Arr(glyphItems), + "m_CharacterTable" to UVal.Arr(charItems), + ), + ) + } + + private fun tmpFontTypeTree(): TypeTree { + fun intNode(name: String) = TTNode(1, "int", name, 4, 0) + fun uintNode(name: String) = TTNode(1, "UInt32", name, 4, 0) + fun i64Node(name: String) = TTNode(1, "SInt64", name, 8, 0) + fun strNode(name: String) = TTNode(1, "string", name, -1, 0x4000) + fun vectorOf(name: String, itemNode: TTNode): TTNode { + val array = TTNode(1, "Array", "Array", -1, 0x4000, mutableListOf(intNode("size"), itemNode)) + return TTNode(1, "vector", name, -1, 0, mutableListOf(array)) + } + + val glyphRectNode = TTNode( + 1, + "GlyphRect", + "m_GlyphRect", + 16, + 0, + mutableListOf(intNode("m_X"), intNode("m_Y"), intNode("m_Width"), intNode("m_Height")), + ) + val glyphNode = TTNode( + 1, + "Glyph", + "data", + 24, + 0, + mutableListOf(uintNode("m_Index"), glyphRectNode, intNode("m_AtlasIndex")), + ) + val charNode = TTNode( + 1, + "TMP_Character", + "data", + 8, + 0, + mutableListOf(uintNode("m_Unicode"), uintNode("m_GlyphIndex")), + ) + val sourceFontNode = TTNode( + 1, + "PPtr", + "m_SourceFontFile", + 12, + 0, + mutableListOf(intNode("m_FileID"), i64Node("m_PathID")), + ) + val root = TTNode( + 1, + "MonoBehaviour", + "Base", + -1, + 0, + mutableListOf( + strNode("m_Name"), + intNode("m_AtlasPopulationMode"), + sourceFontNode, + intNode("m_AtlasWidth"), + intNode("m_AtlasHeight"), + vectorOf("m_GlyphTable", glyphNode), + vectorOf("m_CharacterTable", charNode), + ), + ) + return TypeTree(root) + } + + private fun rawFontTypeTree(): TypeTree { + val strNode = TTNode(1, "string", "m_Name", -1, 0x4000) + val fontDataNode = TTNode(1, "TypelessData", "m_FontData", -1, 0x4000) + val root = TTNode(1, "Font", "Base", -1, 0, mutableListOf(strNode, fontDataNode)) + return TypeTree(root) + } + + private fun encodeTreeToBlob(tree: TypeTree): Pair { + val stringPool = ByteArrayOutputStream() + val offsets = LinkedHashMap() + fun offsetOf(s: String): Int = offsets.getOrPut(s) { + val pos = stringPool.size() + stringPool.write(s.toByteArray(Charsets.UTF_8)) + stringPool.write(0) + pos + } + val nodesOut = ByteArrayOutputStream() + fun walk(node: TTNode, level: Int) { + nodesOut.write(byteArrayOf(node.version.toByte(), (node.version ushr 8).toByte())) + nodesOut.write(level) + nodesOut.write(if (node.type == "Array") 1 else 0) + nodesOut.write(le32(offsetOf(node.type).toLong())) + nodesOut.write(le32(offsetOf(node.name).toLong())) + nodesOut.write(le32(node.byteSize.toLong() and 0xFFFFFFFFL)) + nodesOut.write(le32(0)) + nodesOut.write(le32(node.metaFlag.toLong() and 0xFFFFFFFFL)) + node.children.forEach { walk(it, level + 1) } + } + walk(tree.root, 0) + return nodesOut.toByteArray() to stringPool.toByteArray() + } + + private fun writeFontSerializedFile( + root: File, + name: String, + tmpAssets: List, + rawFonts: List, + ): File { + val tmpTree = tmpFontTypeTree() + val fontTree = rawFontTypeTree() + val (tmpNodes, tmpStrings) = encodeTreeToBlob(tmpTree) + val (fontNodes, fontStrings) = encodeTreeToBlob(fontTree) + + val hasRaw = rawFonts.isNotEmpty() + val typeCount = if (hasRaw) 2 else 1 + + val meta = ByteArrayOutputStream() + meta.write("2022.3.62f2".toByteArray(Charsets.UTF_8)) + meta.write(0) + meta.write(le32(13)) // Android build target + meta.write(1) // enableTypeTree = true + meta.write(le32(typeCount.toLong())) + + // Type 0: MonoBehaviour (114) + meta.write(le32(114)) + meta.write(0) + meta.write(byteArrayOf(0xFF.toByte(), 0xFF.toByte())) + meta.write(ByteArray(16)) // script id + meta.write(ByteArray(16)) // old type hash + meta.write(le32((tmpNodes.size / 24).toLong())) + meta.write(le32(tmpStrings.size.toLong())) + meta.write(tmpNodes) + meta.write(tmpStrings) + + // Type 1: Font (128) if present + if (hasRaw) { + meta.write(le32(128)) + meta.write(0) + meta.write(byteArrayOf(0xFF.toByte(), 0xFF.toByte())) + meta.write(ByteArray(16)) + meta.write(le32((fontNodes.size / 24).toLong())) + meta.write(le32(fontStrings.size.toLong())) + meta.write(fontNodes) + meta.write(fontStrings) + } + + val encodedObjects = ArrayList>() + tmpAssets.forEach { asset -> + val struct = buildDecodedTmpStruct( + name = asset.name, + populationMode = asset.populationMode, + sourceFileId = asset.sourceFontFileId, + sourcePathId = asset.sourceFontPathId, + glyphCount = asset.codepoints.size, + codepoints = asset.codepoints, + atlasWidth = asset.atlasWidth, + atlasHeight = asset.atlasHeight, + ) + encodedObjects += Triple(asset.pathId, 0, TypeTreeCodec.encode(tmpTree, struct, bigEndian = false)) + } + rawFonts.forEach { raw -> + val struct = UVal.Struct( + linkedMapOf( + "m_Name" to UVal.Str(raw.name), + "m_FontData" to UVal.Bytes(raw.fontData), + ), + ) + encodedObjects += Triple(raw.pathId, 1, TypeTreeCodec.encode(fontTree, struct, bigEndian = false)) + } + + meta.write(le32(encodedObjects.size.toLong())) + var dataOffsetInSection = 0 + val data = ByteArrayOutputStream() + encodedObjects.forEach { (pathId, typeIdx, bytes) -> + meta.write(ByteArray((4 - meta.size() % 4) % 4)) + meta.write(le64(pathId)) + meta.write(le32(dataOffsetInSection.toLong())) + meta.write(le32(bytes.size.toLong())) + meta.write(le32(typeIdx.toLong())) + data.write(bytes) + dataOffsetInSection += bytes.size + } + + val metadata = meta.toByteArray() + val dataBytes = data.toByteArray() + val headerSize = 20 + val dataStart = (headerSize + metadata.size + 15) / 16 * 16 + val output = File(root, name) + FileOutputStream(output).use { stream -> + DataOutputStream(stream).use { out -> + out.writeInt(metadata.size) + out.writeInt(dataStart + dataBytes.size) + out.writeInt(17) + out.writeInt(dataStart) + out.writeByte(0) + out.write(ByteArray(3)) + out.write(metadata) + out.write(ByteArray(dataStart - headerSize - metadata.size)) + out.write(dataBytes) + } + } + return output + } + + private fun writeSimpleTextAssetSerializedFile( + root: File, + fileName: String, + assetName: String, + scriptText: String, + ): File { + val bytes = TypeTreeCodec.encodeTextAsset(assetName, scriptText.toByteArray(Charsets.UTF_8), bigEndian = false) + val meta = ByteArrayOutputStream() + meta.write("2022.3.62f2".toByteArray(Charsets.UTF_8)) + meta.write(0) + meta.write(le32(13)) + meta.write(0) // enableTypeTree = false (uses TextAsset built-in fallback) + meta.write(le32(1)) + meta.write(le32(49)) // TextAsset + meta.write(0) + meta.write(byteArrayOf(0xFF.toByte(), 0xFF.toByte())) + meta.write(ByteArray(16)) + meta.write(le32(1)) + meta.write(ByteArray((4 - meta.size() % 4) % 4)) + meta.write(le64(1L)) + meta.write(le32(0L)) + meta.write(le32(bytes.size.toLong())) + meta.write(le32(0L)) + + val metadata = meta.toByteArray() + val headerSize = 20 + val dataStart = (headerSize + metadata.size + 15) / 16 * 16 + val output = File(root, fileName) + FileOutputStream(output).use { stream -> + DataOutputStream(stream).use { out -> + out.writeInt(metadata.size) + out.writeInt(dataStart + bytes.size) + out.writeInt(17) + out.writeInt(dataStart) + out.writeByte(0) + out.write(ByteArray(3)) + out.write(metadata) + out.write(ByteArray(dataStart - headerSize - metadata.size)) + out.write(bytes) + } + } + return output + } + + private fun buildMinimalTtfWithCmap(ranges: List): ByteArray { + val allRanges = ranges + listOf(0xFFFF..0xFFFF) + val segCount = allRanges.size + val segCountX2 = segCount * 2 + val subtableLen = 16 + segCount * 8 + val cmapLen = 12 + subtableLen + val totalLen = 12 + 16 + cmapLen + val buf = ByteBuffer.allocate(totalLen).order(ByteOrder.BIG_ENDIAN) + + // sfnt header (TrueType 0x00010000, 1 table) + buf.putInt(0x00010000) + buf.putShort(1) + buf.putShort(16) + buf.putShort(0) + buf.putShort(0) + + // Table directory entry for 'cmap' + buf.putInt(0x636D6170) // 'cmap' + buf.putInt(0) // checksum + buf.putInt(28) // offset + buf.putInt(cmapLen) // length + + // cmap header (version 0, 1 encoding record -> subtable at offset 12) + buf.putShort(0) + buf.putShort(1) + buf.putShort(3) // platformID = Windows + buf.putShort(1) // encodingID = Unicode BMP + buf.putInt(12) + + // Format 4 subtable + buf.putShort(4) + buf.putShort(subtableLen.toShort()) + buf.putShort(0) + buf.putShort(segCountX2.toShort()) + buf.putShort(2) + buf.putShort(1) + buf.putShort(0) + allRanges.forEach { buf.putShort(it.last.toShort()) } + buf.putShort(0) // reservedPad + allRanges.forEach { buf.putShort(it.first.toShort()) } + allRanges.forEach { _ -> buf.putShort(0) } // idDelta + allRanges.forEach { _ -> buf.putShort(0) } // idRangeOffset + + return buf.array() + } + + private fun le32(value: Long): ByteArray = byteArrayOf( + value.toByte(), + (value ushr 8).toByte(), + (value ushr 16).toByte(), + (value ushr 24).toByte(), + ) + + private fun le64(value: Long): ByteArray = + ByteArray(8) { index -> ((value ushr (8 * index)) and 0xFF).toByte() } +}