diff --git a/server/android/src/androidTest/java/dev/slimevr/android/ResourcePackSmokeTest.kt b/server/android/src/androidTest/java/dev/slimevr/android/ResourcePackSmokeTest.kt new file mode 100644 index 000000000..5dd3fc96d --- /dev/null +++ b/server/android/src/androidTest/java/dev/slimevr/android/ResourcePackSmokeTest.kt @@ -0,0 +1,27 @@ +package dev.slimevr.android + +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import dev.slimevr.android.config.AndroidConfigStorage +import dev.slimevr.resourcepacks.ResourcePackManager +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import java.io.File + +@RunWith(AndroidJUnit4::class) +class ResourcePackSmokeTest { + @Test + fun loadsBundledCoreAndCreatesLocalPackDirectory() = runBlocking { + val context = ApplicationProvider.getApplicationContext() + val catalog = ResourcePackManager.load( + AndroidConfigStorage(context.filesDir), + context.javaClass.classLoader ?: ClassLoader.getSystemClassLoader(), + ) + + assertEquals("slimevr:core", catalog.core.manifest.value.id) + assertTrue(File(context.filesDir, "resourcepacks").isDirectory) + } +} diff --git a/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt b/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt index c9ab32dd4..4073785f0 100644 --- a/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt +++ b/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt @@ -36,6 +36,7 @@ import dev.slimevr.keybind.KeybindManager import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsManager +import dev.slimevr.resourcepacks.ResourcePackManager import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.skeleton.Skeleton import dev.slimevr.solarxr.rpc.ServerInfos @@ -149,6 +150,7 @@ class ForegroundService : Service() { private suspend fun startServer(scope: CoroutineScope) { val storage = AndroidConfigStorage(filesDir) val config = AppConfig.create(scope = scope, storage = storage) + ResourcePackManager.load(storage, javaClass.classLoader ?: ClassLoader.getSystemClassLoader()) val server = VRServer.create(scope = scope) val serialServer = createAndroidSerialServer(context = this, scope = scope) val bones = BoneRegistryManager.create(scope = scope) diff --git a/server/android/src/main/java/dev/slimevr/android/config/storage.kt b/server/android/src/main/java/dev/slimevr/android/config/storage.kt index 6df85d367..eac57a3b3 100644 --- a/server/android/src/main/java/dev/slimevr/android/config/storage.kt +++ b/server/android/src/main/java/dev/slimevr/android/config/storage.kt @@ -1,12 +1,15 @@ package dev.slimevr.android.config import dev.slimevr.config.ConfigStorage +import dev.slimevr.config.StorageEntry +import dev.slimevr.config.StorageEntryType import dev.slimevr.config.TextFileHandle import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.io.RandomAccessFile import java.nio.file.Files +import java.nio.file.LinkOption import java.nio.file.StandardCopyOption class AndroidConfigStorage(private val root: File) : ConfigStorage { @@ -46,6 +49,22 @@ class AndroidConfigStorage(private val root: File) : ConfigStorage { directory.isDirectory || directory.mkdirs() } + override suspend fun list(path: String): List = withContext(Dispatchers.IO) { + val directory = resolve(path).toPath() + if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) return@withContext emptyList() + Files.list(directory).use { stream -> + stream.map { child -> + val type = when { + Files.isSymbolicLink(child) -> StorageEntryType.SYMLINK + Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.DIRECTORY + Files.isRegularFile(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.FILE + else -> StorageEntryType.OTHER + } + StorageEntry(child.fileName.toString(), type) + }.sorted(compareBy { it.name }).toList() + } + } + override suspend fun openTextFile(path: String): TextFileHandle = withContext(Dispatchers.IO) { val file = resolve(path) file.parentFile?.mkdirs() diff --git a/server/core/build.gradle.kts b/server/core/build.gradle.kts index 70b12c057..15edc88ae 100644 --- a/server/core/build.gradle.kts +++ b/server/core/build.gradle.kts @@ -15,6 +15,24 @@ tasks.withType { from("../../LICENSE-MIT") } +val generateCoreResourcePackIndex = tasks.register("generateCoreResourcePackIndex") { + val corePack = layout.projectDirectory.dir("src/main/resources/dev/slimevr/resourcepacks/core") + val index = layout.buildDirectory.file("generated/resources/dev/slimevr/resourcepacks/core/index.txt") + inputs.dir(corePack) + outputs.file(index) + doLast { + val root = corePack.asFile.toPath() + val files = corePack.asFile.walkTopDown() + .filter { it.isFile && !it.relativeTo(corePack.asFile).invariantSeparatorsPath.startsWith("schemas/") } + .map { root.relativize(it.toPath()).toString().replace('\\', '/') } + .sorted() + index.get().asFile.apply { + parentFile.mkdirs() + writeText(files.joinToString("\n", postfix = "\n")) + } + } +} + allprojects { repositories { // Use jcenter for resolving dependencies. @@ -31,10 +49,15 @@ kotlin { sourceSets { val commonMain = getByName("commonMain") { kotlin.srcDir("src/main/java") + resources.srcDir("src/main/resources") + resources.srcDir(layout.buildDirectory.dir("generated/resources")) dependencies { api(project(":solarxr-protocol:generated")) api("com.google.flatbuffers:flatbuffers-java:22.10.26") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0") + implementation("com.github.erosb:json-sKema:0.31.0") { + exclude(group = "org.yaml", module = "snakeyaml") + } implementation("com.mayakapps.kache:kache:2.1.1") implementation("io.klogging:klogging:0.11.7") api("com.appstractive:dns-sd-kt:1.1.0") @@ -64,6 +87,10 @@ kotlin { } } +tasks.matching { it.name.endsWith("ProcessResources") }.configureEach { + dependsOn(generateCoreResourcePackIndex) +} + tasks.withType { options.encoding = "UTF-8" } diff --git a/server/core/src/main/java/dev/slimevr/config/io.kt b/server/core/src/main/java/dev/slimevr/config/io.kt index 162d40827..ae981e9f3 100644 --- a/server/core/src/main/java/dev/slimevr/config/io.kt +++ b/server/core/src/main/java/dev/slimevr/config/io.kt @@ -22,10 +22,20 @@ interface ConfigStorage { suspend fun backup(path: String) suspend fun exists(path: String): Boolean suspend fun ensureDirectory(path: String): Boolean + + /** Lists direct children only. Implementations must not follow symbolic links. */ + suspend fun list(path: String): List = emptyList() suspend fun openTextFile(path: String): TextFileHandle fun displayPath(path: String): String = path } +enum class StorageEntryType { FILE, DIRECTORY, SYMLINK, OTHER } + +data class StorageEntry( + val name: String, + val type: StorageEntryType, +) + interface TextFileHandle { suspend fun write(text: String) suspend fun flush() diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/catalog-models.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/catalog-models.kt new file mode 100644 index 000000000..474a93b46 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/catalog-models.kt @@ -0,0 +1,31 @@ +package dev.slimevr.resourcepacks + +import kotlinx.serialization.Serializable + +data class SourcedResource(val path: String, val value: T) + +@Serializable(with = LanguageResourceSerializer::class) +data class LanguageResource(val schema: String?, val translations: Map) + +data class ParsedResourcePack( + val source: String, + val manifest: SourcedResource, + val bones: List>, + val proportions: List>, + val boneOverrides: List>, + val proportionOverrides: List>, + val languages: List>, +) + +data class ResourcePackDiagnostic(val path: String, val pointer: String = "", val message: String) +class ResourcePackParseException(val diagnostics: List) : + IllegalArgumentException( + diagnostics.joinToString("\n") { "${it.path}${it.pointer}: ${it.message}" }, + ) + +data class ResourcePackFailure(val folder: String, val diagnostics: List) +data class ResourcePackCatalog( + val core: ParsedResourcePack, + val userPacks: List, + val failures: List, +) diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/definitions.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/definitions.kt new file mode 100644 index 000000000..dc6d0f715 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/definitions.kt @@ -0,0 +1,61 @@ +package dev.slimevr.resourcepacks + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +data class PackManifest( + @SerialName("$" + "schema") val schema: String? = null, + val formatVersion: Int, + val id: String, + val nameKey: String, + val descriptionKey: String, + val version: List, + val authors: List, +) + +@Serializable +data class BoneDefinition( + @SerialName("$" + "schema") val schema: String? = null, + val key: String, + val nameKey: String, + val mirror: String? = null, + val batterySources: List? = null, + val candidateSources: List? = null, + val overridable: Boolean? = null, + val parent: String? = null, + val headOffset: Offset? = null, + val tailOffset: Offset? = null, + val rotationFallback: RotationFallback? = null, + val constraint: Constraint? = null, + val outputs: BoneOutputs? = null, + val inputs: BoneInputs? = null, +) + +@Serializable +data class ProportionDefinition( + @SerialName("$" + "schema") val schema: String? = null, + val key: String, + val nameKey: String, + val descriptionKey: String? = null, + val contributesToHeight: Boolean? = null, + val minimum: Float? = null, + val maximum: Float? = null, + val default: ProportionDefault, +) + +@Serializable +data class BoneOverride( + @SerialName("$" + "schema") val schema: String? = null, + val target: String, + val set: BoneOverrideSet? = null, + val remove: List>? = null, +) + +@Serializable +data class ProportionOverride( + @SerialName("$" + "schema") val schema: String? = null, + val target: String, + val set: ProportionOverrideSet? = null, + val remove: List? = null, +) diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/json-adapters.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/json-adapters.kt new file mode 100644 index 000000000..03db23e27 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/json-adapters.kt @@ -0,0 +1,121 @@ +package dev.slimevr.resourcepacks + +import kotlinx.serialization.KSerializer +import kotlinx.serialization.SerializationException +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonEncoder +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.json.encodeToJsonElement +import kotlinx.serialization.json.float +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put + +private fun Decoder.requireJson(): JsonDecoder = this as? JsonDecoder ?: throw SerializationException("Resource packs require a JSON decoder") +private fun Encoder.requireJson(): JsonEncoder = this as? JsonEncoder ?: throw SerializationException("Resource packs require a JSON encoder") +private fun JsonElement.objectValue(): JsonObject = this as? JsonObject ?: throw SerializationException("Expected a JSON object") + +object VmcNamesSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("VmcNames", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder) = decoder.requireJson().decodeJsonElement().let { VmcNames(if (it is JsonArray) it.map { name -> name.jsonPrimitive.content } else listOf(it.jsonPrimitive.content)) } + override fun serialize(encoder: Encoder, value: VmcNames) = encoder.requireJson().encodeJsonElement(if (value.values.size == 1) JsonPrimitive(value.values.single()) else encoder.requireJson().json.encodeToJsonElement(value.values)) +} + +object VmcOutputSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("VmcOutput", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): VmcOutput { + val json = decoder.requireJson().json + val objectValue = decoder.requireJson().decodeJsonElement().objectValue() + val parent = when (val raw = objectValue["inputParent"]) { + null -> VmcInputParent.Omitted + JsonNull -> VmcInputParent.ExplicitNull + else -> VmcInputParent.Bone(raw.jsonPrimitive.content) + } + return VmcOutput(json.decodeFromJsonElement(objectValue["name"]!!), objectValue["outputParent"]?.jsonPrimitive?.contentOrNull, parent, objectValue["restRotation"]?.let { json.decodeFromJsonElement(it) }) + } + override fun serialize(encoder: Encoder, value: VmcOutput) { + val json = encoder.requireJson().json + encoder.requireJson().encodeJsonElement( + buildJsonObject { + put("name", json.encodeToJsonElement(value.name)) + value.outputParent?.let { put("outputParent", it) } + when (val parent = value.inputParent) { + VmcInputParent.Omitted -> Unit + VmcInputParent.ExplicitNull -> put("inputParent", JsonNull) + is VmcInputParent.Bone -> put("inputParent", parent.key) + } + value.restRotation?.let { put("restRotation", json.encodeToJsonElement(it)) } + }, + ) + } +} + +object EulerSpecSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("EulerSpec", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): EulerSpec { + val json = decoder.requireJson().json + val value = decoder.requireJson().decodeJsonElement() + if (value is JsonPrimitive) return EulerSpec(axis = json.decodeFromJsonElement(value)) + val objectValue = value.objectValue() + return EulerSpec(objectValue["axis"]?.let { json.decodeFromJsonElement(it) }, objectValue["order"]?.let { json.decodeFromJsonElement(it) }, objectValue["unit"]?.let { json.decodeFromJsonElement(it) }) + } + override fun serialize(encoder: Encoder, value: EulerSpec) { + val json = encoder.requireJson().json + if (value.order == null && value.unit == null && value.axis != null) { + encoder.requireJson().encodeJsonElement(json.encodeToJsonElement(value.axis)) + } else { + encoder.requireJson().encodeJsonElement( + buildJsonObject { + value.axis?.let { put("axis", json.encodeToJsonElement(it)) } + value.order?.let { put("order", json.encodeToJsonElement(it)) } + value.unit?.let { put("unit", json.encodeToJsonElement(it)) } + }, + ) + } + } +} + +object ScalarOrVectorSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("ScalarOrVector", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): ScalarOrVector { + val json = decoder.requireJson().json + val value = decoder.requireJson().decodeJsonElement() + return if (value is JsonPrimitive) ScalarOrVector.Scalar(value.float) else ScalarOrVector.Vector(json.decodeFromJsonElement(value)) + } + override fun serialize(encoder: Encoder, value: ScalarOrVector) = encoder.requireJson().encodeJsonElement( + when (value) { + is ScalarOrVector.Scalar -> JsonPrimitive(value.value) + is ScalarOrVector.Vector -> encoder.requireJson().json.encodeToJsonElement(value.value) + }, + ) +} + +/** A language file has `$schema` alongside otherwise flat translation entries. */ +object LanguageResourceSerializer : KSerializer { + override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LanguageResource", PrimitiveKind.STRING) + override fun deserialize(decoder: Decoder): LanguageResource { + val document = decoder.requireJson().decodeJsonElement().objectValue() + val schema = document["$" + "schema"]?.jsonPrimitive?.contentOrNull + val translations = document.filterKeys { it != "$" + "schema" }.mapValues { (_, value) -> + (value as? JsonPrimitive)?.content ?: throw SerializationException("Language values must be strings") + } + return LanguageResource(schema, translations) + } + override fun serialize(encoder: Encoder, value: LanguageResource) = encoder.requireJson().encodeJsonElement( + buildJsonObject { + value.schema?.let { put("$" + "schema", it) } + value.translations.forEach { (key, translation) -> put(key, translation) } + }, + ) +} diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/manager.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/manager.kt new file mode 100644 index 000000000..6872cb369 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/manager.kt @@ -0,0 +1,45 @@ +package dev.slimevr.resourcepacks + +import dev.slimevr.config.ConfigStorage +import dev.slimevr.config.StorageEntryType +import dev.slimevr.config.configPath +import dev.slimevr.logging.AppLogger + +object ResourcePackManager { + suspend fun load(storage: ConfigStorage, classLoader: ClassLoader): ResourcePackCatalog { + val parser = ResourcePackParser() + val core = parser.parse(ClasspathResourcePackSource.core(classLoader)) + val root = "resourcepacks" + if (!storage.ensureDirectory(root)) { + AppLogger.config.error("Unable to create ${storage.displayPath(root)}; loading bundled core pack only") + return ResourcePackCatalog(core, emptyList(), emptyList()) + } + val folders = try { + storage.list(root).filter { it.type == StorageEntryType.DIRECTORY }.sortedBy { it.name } + } catch (e: Exception) { + AppLogger.config.error(e, "Unable to enumerate ${storage.displayPath(root)}; loading bundled core pack only") + return ResourcePackCatalog(core, emptyList(), emptyList()) + } + val packs = mutableListOf() + val failures = mutableListOf() + for (folder in folders) { + val packRoot = configPath(root, folder.name) + val containsManifest = try { + storage.list(packRoot).any { it.name == "manifest.json" && it.type == StorageEntryType.FILE } + } catch (e: Exception) { + val diagnostic = ResourcePackDiagnostic("manifest.json", message = "Unable to inspect pack: ${e.message}") + failures += ResourcePackFailure(folder.name, listOf(diagnostic)) + AppLogger.config.error("Skipping unreadable resource pack '${folder.name}': ${diagnostic.message}") + continue + } + if (!containsManifest) continue + try { + packs += parser.parse(StorageResourcePackSource(storage, packRoot)) + } catch (e: ResourcePackParseException) { + failures += ResourcePackFailure(folder.name, e.diagnostics) + AppLogger.config.error("Skipping invalid resource pack '${folder.name}': ${e.message}") + } + } + return ResourcePackCatalog(core, packs.toList(), failures.toList()) + } +} diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/parser.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/parser.kt new file mode 100644 index 000000000..ffd21df3a --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/parser.kt @@ -0,0 +1,76 @@ +package dev.slimevr.resourcepacks + +import com.github.erosb.jsonsKema.JsonParser +import com.github.erosb.jsonsKema.Validator +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.decodeFromJsonElement + +/** Validates trusted-schema JSON, then decodes a complete typed resource model. */ +class ResourcePackParser { + private val json = Json { + ignoreUnknownKeys = false + explicitNulls = true + } + + suspend fun parse(source: ResourcePackSource): ParsedResourcePack { + val entries = try { + source.entries() + } catch (e: Exception) { + throw ResourcePackParseException(listOf(ResourcePackDiagnostic("", message = "Unable to scan ${source.description}: ${e.message}"))) + } + val diagnostics = mutableListOf() + entries.groupBy { it.path }.filterValues { it.size > 1 }.keys.sorted().forEach { diagnostics += ResourcePackDiagnostic(it, message = "Duplicate resource path") } + val manifestEntry = entries.firstOrNull { it.path == "manifest.json" } + if (manifestEntry == null) diagnostics += ResourcePackDiagnostic("manifest.json", message = "Missing manifest") + + val bones = mutableListOf>() + val proportions = mutableListOf>() + val boneOverrides = mutableListOf>() + val proportionOverrides = mutableListOf>() + val languages = mutableListOf>() + var manifest: SourcedResource? = null + for (entry in entries) { + val kind = kindFor(entry.path) ?: continue + if (kind == ResourceKind.MISPLACED) { + diagnostics += ResourcePackDiagnostic(entry.path, message = "JSON document is not allowed at this pack path") + continue + } + val document = validate(entry, kind, diagnostics) ?: continue + try { + when (kind) { + ResourceKind.MANIFEST -> manifest = SourcedResource(entry.path, json.decodeFromJsonElement(document)) + ResourceKind.BONE -> bones += SourcedResource(entry.path, json.decodeFromJsonElement(document)) + ResourceKind.PROPORTION -> proportions += SourcedResource(entry.path, json.decodeFromJsonElement(document)) + ResourceKind.BONE_OVERRIDE -> boneOverrides += SourcedResource(entry.path, json.decodeFromJsonElement(document)) + ResourceKind.PROPORTION_OVERRIDE -> proportionOverrides += SourcedResource(entry.path, json.decodeFromJsonElement(document)) + ResourceKind.LANGUAGE -> languages += SourcedResource(entry.path, json.decodeFromJsonElement(document)) + } + } catch (e: Exception) { + diagnostics += ResourcePackDiagnostic(entry.path, message = "Schema/model drift while decoding: ${e.message}") + } + } + if (diagnostics.isNotEmpty()) throw ResourcePackParseException(diagnostics.sortedWith(compareBy { it.path }.thenBy { it.pointer })) + return ParsedResourcePack(source.description, requireNotNull(manifest), bones.toList(), proportions.toList(), boneOverrides.toList(), proportionOverrides.toList(), languages.toList()) + } + + private fun validate(entry: ResourcePackEntry, kind: ResourceKind, diagnostics: MutableList): JsonElement? { + val instance = try { + JsonParser(entry.contents).parse() + } catch (e: Exception) { + diagnostics += ResourcePackDiagnostic(entry.path, message = "Malformed JSON: ${e.message}") + return null + } + val failure = Validator.forSchema(PackSchemas.schema(kind)).validate(instance) + if (failure != null) { + diagnostics += ResourcePackDiagnostic(entry.path, message = "$kind schema: $failure") + return null + } + return try { + json.parseToJsonElement(entry.contents) + } catch (e: Exception) { + diagnostics += ResourcePackDiagnostic(entry.path, message = "Malformed JSON: ${e.message}") + null + } + } +} diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/resource-models.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/resource-models.kt new file mode 100644 index 000000000..abecfcf35 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/resource-models.kt @@ -0,0 +1,186 @@ +@file:OptIn(kotlinx.serialization.ExperimentalSerializationApi::class) + +package dev.slimevr.resourcepacks + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonClassDiscriminator + +@Serializable +data class Vector3(val x: Float, val y: Float, val z: Float) + +@Serializable +data class OffsetTerm(val proportion: String, val direction: Vector3) + +@Serializable +data class Offset(val base: Vector3? = null, val terms: List? = null) + +@Serializable +@JsonClassDiscriminator("type") +sealed interface RotationFallback { + val before: List? + val after: List? +} + +@Serializable +@SerialName("none") +data class NoRotationFallback(override val before: List? = null, override val after: List? = null) : RotationFallback + +@Serializable +@SerialName("copy") +data class CopyRotationFallback(val source: String, override val before: List? = null, override val after: List? = null) : RotationFallback + +@Serializable +@SerialName("firstActive") +data class FirstActiveRotationFallback(val sources: List, override val before: List? = null, override val after: List? = null) : RotationFallback + +@Serializable +@JsonClassDiscriminator("type") +sealed interface Constraint + +@Serializable +@SerialName("twistSwing") +data class TwistSwingConstraint(val twistDegrees: Float, val swingDegrees: Float, val allowedDeviationDegrees: Float? = null) : Constraint + +@Serializable +@SerialName("hinge") +data class HingeConstraint(val minDegrees: Float, val maxDegrees: Float, val axis: Vector3) : Constraint + +@Serializable +@SerialName("looseHinge") +data class LooseHingeConstraint(val minDegrees: Float, val maxDegrees: Float, val allowedDeviationDegrees: Float, val axis: Vector3) : Constraint + +@Serializable +@JsonClassDiscriminator("type") +sealed interface ProportionDefault { + val value: Float +} + +@Serializable +@SerialName("fixed") +data class FixedProportionDefault(override val value: Float) : ProportionDefault + +@Serializable +@SerialName("heightRatio") +data class HeightRatioProportionDefault(override val value: Float) : ProportionDefault + +@Serializable +data class DriverOutput(val supported: Boolean) + +@Serializable(with = VmcNamesSerializer::class) +data class VmcNames(val values: List) { + init { + require(values.isNotEmpty()) + } +} + +sealed interface VmcInputParent { + data object Omitted : VmcInputParent + data object ExplicitNull : VmcInputParent + data class Bone(val key: String) : VmcInputParent +} + +@Serializable +data class RestRotation(val axis: Vector3, val degrees: Float) + +@Serializable(with = VmcOutputSerializer::class) +data class VmcOutput( + val name: VmcNames, + val outputParent: String? = null, + val inputParent: VmcInputParent = VmcInputParent.Omitted, + val restRotation: List? = null, +) + +@Serializable +data class VrchatOutput(val required: Boolean? = null, val emit: Map) + +@Serializable +data class EmitEntry(val from: EmitSource, val relativeTo: String? = null, val value: List? = null) + +@Serializable +enum class EmitSource { + @SerialName("position") + POSITION, + + @SerialName("rotation") + ROTATION, +} + +@Serializable +data class PipelineStep( + val euler: EulerSpec? = null, + val scale: ScalarOrVector? = null, + val divide: ScalarOrVector? = null, + val offset: ScalarOrVector? = null, + val clamp: List? = null, + val greaterThan: Float? = null, + val lessThan: Float? = null, +) + +@Serializable(with = EulerSpecSerializer::class) +data class EulerSpec(val axis: Axis? = null, val order: EulerOrder? = null, val unit: EulerUnit? = null) + +@Serializable enum class Axis { + @SerialName("x") + X, + + @SerialName("y") + Y, + + @SerialName("z") + Z, +} + +@Serializable enum class EulerOrder { XYZ, XZY, YXZ, YZX, ZXY, ZYX } + +@Serializable enum class EulerUnit { + @SerialName("degrees") + DEGREES, + + @SerialName("radians") + RADIANS, +} + +@Serializable(with = ScalarOrVectorSerializer::class) +sealed interface ScalarOrVector { + data class Scalar(val value: Float) : ScalarOrVector + data class Vector(val value: PartialVector3) : ScalarOrVector +} + +@Serializable +data class PartialVector3(val x: Float? = null, val y: Float? = null, val z: Float? = null) + +@Serializable +data class BoneOutputs(val driver: DriverOutput? = null, val vmc: VmcOutput? = null, val vrchat: VrchatOutput? = null) + +@Serializable +data class VrchatInput(val address: String) + +@Serializable +data class BoneInputs(val vrchat: VrchatInput? = null) + +@Serializable +data class BoneOverrideSet( + val nameKey: String? = null, + val mirror: String? = null, + val batterySources: List? = null, + val candidateSources: List? = null, + val overridable: Boolean? = null, + val parent: String? = null, + val headOffset: Offset? = null, + val tailOffset: Offset? = null, + val rotationFallback: RotationFallback? = null, + val constraint: Constraint? = null, + val outputs: BoneOutputs? = null, + val inputs: BoneInputs? = null, +) + +@Serializable +data class ProportionOverrideSet( + val nameKey: String? = null, + val descriptionKey: String? = null, + val contributesToHeight: Boolean? = null, + val minimum: Float? = null, + val maximum: Float? = null, + val default: ProportionDefault? = null, +) diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/resource-packs.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/resource-packs.kt new file mode 100644 index 000000000..bfdebabc8 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/resource-packs.kt @@ -0,0 +1,104 @@ +package dev.slimevr.resourcepacks + +import dev.slimevr.config.ConfigStorage +import dev.slimevr.config.StorageEntryType +import dev.slimevr.config.configPath +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.IOException + +data class ResourcePackEntry(val path: String, val contents: String) + +interface ResourcePackSource { + val description: String + suspend fun entries(): List +} + +/** In memory source, mock for unit test **/ +class InMemoryResourcePackSource( + private val files: Map, + override val description: String = "in memory", +) : ResourcePackSource { + override suspend fun entries(): List = files.entries + .map { ResourcePackEntry(normalizePath(it.key), it.value) } + .sortedBy { it.path } +} + +/** Reads a local directory through ConfigStorage, never following symlinks. */ +class StorageResourcePackSource( + private val storage: ConfigStorage, + private val root: String, + override val description: String = storage.displayPath(root), +) : ResourcePackSource { + override suspend fun entries(): List { + val result = mutableListOf() + suspend fun visit(relative: String) { + val directory = if (relative.isEmpty()) root else configPath(root, relative) + for (entry in storage.list(directory).sortedBy { it.name }) { + if (entry.name.isEmpty() || entry.name.contains('/') || entry.name.contains('\\') || entry.name == "." || entry.name == "..") { + throw IOException("Invalid entry name '${entry.name}' in $directory") + } + val child = if (relative.isEmpty()) entry.name else "$relative/${entry.name}" + when (entry.type) { + StorageEntryType.SYMLINK -> throw IOException("Symbolic links are not permitted in resource packs ($child)") + + StorageEntryType.DIRECTORY -> visit(child) + + StorageEntryType.FILE -> { + val path = normalizePath(child) + val contents = storage.read(configPath(root, path)) + ?: throw IOException("Unable to read $path") + result += ResourcePackEntry(path, contents) + } + + StorageEntryType.OTHER -> throw IOException("Unsupported filesystem entry in resource pack: $child") + } + } + } + visit("") + return result.sortedBy { it.path } + } +} + +/** Discovers the single bundled core pack from a class loader. */ +class ClasspathResourcePackSource private constructor( + private val classLoader: ClassLoader, + override val description: String, +) : ResourcePackSource { + override suspend fun entries(): List = withContext(Dispatchers.IO) { + val indexPath = "$CORE_ROOT/index.txt" + val paths = classLoader.getResourceAsStream(indexPath)?.bufferedReader()?.use { reader -> + reader.lineSequence().filter { it.isNotBlank() }.map(::normalizePath).toList() + } ?: throw IOException("Bundled core resource-pack index is missing ($indexPath)") + paths.sorted().map { path -> + val resource = "$CORE_ROOT/$path" + val contents = classLoader.getResourceAsStream(resource)?.bufferedReader()?.use { it.readText() } + ?: throw IOException("Bundled core resource is missing ($resource)") + ResourcePackEntry(path, contents) + } + } + + companion object { + const val CORE_ROOT = "dev/slimevr/resourcepacks/core" + + fun core(classLoader: ClassLoader): ClasspathResourcePackSource { + val resource = "$CORE_ROOT/manifest.json" + val urls = classLoader.getResources(resource).toList() + require(urls.size == 1) { + when (urls.size) { + 0 -> "Bundled core resource pack is missing ($resource)" + else -> "Bundled core resource pack is duplicated: ${urls.joinToString()}" + } + } + return ClasspathResourcePackSource(classLoader, "bundled core pack (${urls.single()})") + } + } +} + +private fun normalizePath(path: String): String { + val normalized = path.replace('\\', '/') + require(normalized.isNotEmpty() && !normalized.startsWith('/') && normalized.split('/').none { it.isEmpty() || it == "." || it == ".." }) { + "Invalid resource-pack path: $path" + } + return normalized +} diff --git a/server/core/src/main/java/dev/slimevr/resourcepacks/schemas.kt b/server/core/src/main/java/dev/slimevr/resourcepacks/schemas.kt new file mode 100644 index 000000000..3fa35d1ba --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/resourcepacks/schemas.kt @@ -0,0 +1,51 @@ +package dev.slimevr.resourcepacks + +import com.github.erosb.jsonsKema.JsonParser +import com.github.erosb.jsonsKema.Schema +import com.github.erosb.jsonsKema.SchemaLoader +import java.net.URI +import java.nio.charset.StandardCharsets + +internal enum class ResourceKind { + MANIFEST, + BONE, + PROPORTION, + BONE_OVERRIDE, + PROPORTION_OVERRIDE, + LANGUAGE, + MISPLACED, +} + +internal fun kindFor(path: String): ResourceKind? = when { + path == "manifest.json" -> ResourceKind.MANIFEST + Regex("data/bones/[^/]+\\.json").matches(path) -> ResourceKind.BONE + Regex("data/proportions/[^/]+\\.json").matches(path) -> ResourceKind.PROPORTION + Regex("data/overrides/bones/[^/]+\\.json").matches(path) -> ResourceKind.BONE_OVERRIDE + Regex("data/overrides/proportions/[^/]+\\.json").matches(path) -> ResourceKind.PROPORTION_OVERRIDE + Regex("assets/lang/[^/]+\\.json").matches(path) -> ResourceKind.LANGUAGE + (path.startsWith("data/") || path.startsWith("assets/lang/")) && path.endsWith(".json") -> ResourceKind.MISPLACED + else -> null +} + +internal object PackSchemas { + private const val ROOT = ClasspathResourcePackSource.CORE_ROOT + "/schemas/v1" + private val names = ResourceKind.entries.filter { it != ResourceKind.MISPLACED }.associateWith { kind -> + when (kind) { + ResourceKind.MANIFEST -> "manifest.schema.json" + ResourceKind.BONE -> "bone.schema.json" + ResourceKind.PROPORTION -> "proportion.schema.json" + ResourceKind.BONE_OVERRIDE -> "bone-override.schema.json" + ResourceKind.PROPORTION_OVERRIDE -> "proportion-override.schema.json" + ResourceKind.LANGUAGE -> "language.schema.json" + ResourceKind.MISPLACED -> error("No schema") + } + } + private val base = URI("classpath:/$ROOT/") + private val documents = names.values.distinct().associateWith { name -> + PackSchemas::class.java.classLoader.getResourceAsStream("$ROOT/$name")?.bufferedReader(StandardCharsets.UTF_8)?.use { it.readText() } + ?: error("Bundled resource-pack schema is missing: $ROOT/$name") + } + private val config = com.github.erosb.jsonsKema.SchemaLoaderConfig.createDefaultConfig(documents.mapKeys { (name, _) -> base.resolve(name) }) + private val loaded = names.mapValues { (_, name) -> SchemaLoader(JsonParser(documents.getValue(name), base.resolve(name)).parse(), config.copy(initialBaseURI = base.resolve(name))).load() } + fun schema(kind: ResourceKind): Schema = loaded.getValue(kind) +} diff --git a/server/core/src/test/java/dev/slimevr/resourcepacks/ResourcePackParserTest.kt b/server/core/src/test/java/dev/slimevr/resourcepacks/ResourcePackParserTest.kt new file mode 100644 index 000000000..9283e5a4d --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/resourcepacks/ResourcePackParserTest.kt @@ -0,0 +1,211 @@ +package dev.slimevr.resourcepacks + +import com.github.erosb.jsonsKema.JsonParser +import com.github.erosb.jsonsKema.Validator +import dev.slimevr.config.ConfigStorage +import dev.slimevr.config.StorageEntry +import dev.slimevr.config.StorageEntryType +import dev.slimevr.config.TextFileHandle +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.KSerializer +import kotlinx.serialization.json.Json +import java.io.File +import java.net.URLClassLoader +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class ResourcePackParserTest { + @Test + fun `bundled core pack is packaged and parsed`() = runBlocking { + val core = ResourcePackParser().parse(ClasspathResourcePackSource.core(javaClass.classLoader)) + + assertEquals("slimevr:core", core.manifest.value.id) + assertEquals(61, core.bones.size) + assertEquals(18, core.proportions.size) + assertEquals(1, core.languages.size) + assertTrue(core.boneOverrides.isEmpty()) + assertTrue(core.proportionOverrides.isEmpty()) + + val head = core.bones.single { it.value.key == "slimevr:head" }.value + val fallback = assertIs(head.rotationFallback) + assertEquals("slimevr:neck", fallback.source) + assertIs(head.outputs!!.vrchat!!.emit.getValue("/tracking/trackers/head/position").value!!.single().scale) + assertIs(core.proportions.single { it.value.key == "slimevr:upper_chest" }.value.default) + } + + @Test + fun `parser aggregates malformed and misplaced resource diagnostics`() { + val error = assertFailsWith { + runBlocking { + ResourcePackParser().parse( + InMemoryResourcePackSource( + mapOf( + "manifest.json" to "{not json}", + "data/not-a-definition.json" to "{}", + ), + ), + ) + } + } + + assertEquals(listOf("data/not-a-definition.json", "manifest.json"), error.diagnostics.map { it.path }) + } + + @Test + fun `bundled pack loads from the built jar through its generated index`() = runBlocking { + val jar = File("build/libs/core-jvm.jar") + assertTrue(jar.isFile, "jvmJar must run before the test") + URLClassLoader(arrayOf(jar.toURI().toURL()), null).use { loader -> + val core = ResourcePackParser().parse(ClasspathResourcePackSource.core(loader)) + assertEquals(61, core.bones.size) + assertEquals(18, core.proportions.size) + } + } + + @Test + fun `manager orders valid user packs and isolates failures`() = runBlocking { + val storage = MemoryStorage( + files = mapOf( + "resourcepacks/20-custom/manifest.json" to manifest("example:custom"), + "resourcepacks/10-base/manifest.json" to manifest("example:base"), + "resourcepacks/30-invalid/manifest.json" to "{}", + "resourcepacks/40-no-manifest/data/bones/ignored.json" to "{}", + "resourcepacks/50-symlink/manifest.json" to manifest("example:symlink"), + ), + symlinks = setOf("resourcepacks/50-symlink/data/bones/linked.json"), + ) + + val catalog = ResourcePackManager.load(storage, javaClass.classLoader) + + assertEquals(listOf("example:base", "example:custom"), catalog.userPacks.map { it.manifest.value.id }) + assertEquals(listOf("30-invalid", "50-symlink"), catalog.failures.map { it.folder }) + assertTrue(storage.createdResourcePackDirectory) + } + + @Test + fun `manager falls back to core when resourcepack directory cannot be created`() = runBlocking { + val catalog = ResourcePackManager.load(MemoryStorage(emptyMap(), ensureDirectoryResult = false), javaClass.classLoader) + assertTrue(catalog.userPacks.isEmpty()) + assertTrue(catalog.failures.isEmpty()) + } + + @Test + fun `core typed documents round trip through their trusted schemas`() = runBlocking { + val core = ResourcePackParser().parse(ClasspathResourcePackSource.core(javaClass.classLoader)) + val json = Json { + encodeDefaults = false + explicitNulls = true + } + + assertRoundTrip(core.manifest, PackManifest.serializer(), ResourceKind.MANIFEST, json) + assertRoundTrips(core.bones, BoneDefinition.serializer(), ResourceKind.BONE, json) + assertRoundTrips(core.proportions, ProportionDefinition.serializer(), ResourceKind.PROPORTION, json) + assertRoundTrips(core.languages, LanguageResourceSerializer, ResourceKind.LANGUAGE, json) + } + + @Test + fun `overrides and all vmc input parent states decode`() = runBlocking { + val pack = ResourcePackParser().parse( + InMemoryResourcePackSource( + mapOf( + "manifest.json" to manifest("example:variants"), + "data/bones/omitted.json" to bone("example:omitted", "{\"name\":\"Omitted\"}"), + "data/bones/null.json" to bone("example:null", "{\"name\":\"Null\",\"inputParent\":null}"), + "data/bones/key.json" to bone("example:key", "{\"name\":\"Key\",\"inputParent\":\"example:parent\"}"), + "data/overrides/bones/one.json" to "{\"target\":\"example:omitted\",\"set\":{\"parent\":\"example:parent\"}}", + "data/overrides/proportions/one.json" to "{\"target\":\"example:height\",\"set\":{\"default\":{\"type\":\"fixed\",\"value\":1}}}", + ), + ), + ) + + assertEquals(VmcInputParent.Omitted, pack.bones.single { it.value.key == "example:omitted" }.value.outputs!!.vmc!!.inputParent) + assertEquals(VmcInputParent.ExplicitNull, pack.bones.single { it.value.key == "example:null" }.value.outputs!!.vmc!!.inputParent) + assertEquals(VmcInputParent.Bone("example:parent"), pack.bones.single { it.value.key == "example:key" }.value.outputs!!.vmc!!.inputParent) + assertEquals("example:parent", pack.boneOverrides.single().value.set!!.parent) + assertIs(pack.proportionOverrides.single().value.set!!.default) + } + + @Test + fun `typed fallback constraint and transform variants decode`() = runBlocking { + val pack = ResourcePackParser().parse( + InMemoryResourcePackSource( + mapOf( + "manifest.json" to manifest("example:branches"), + "data/bones/branch.json" to """ + {"key":"example:branch","nameKey":"example:name", + "rotationFallback":{"type":"firstActive","sources":["example:first","example:last"],"after":["example:after"]}, + "constraint":{"type":"hinge","minDegrees":-1,"maxDegrees":1,"axis":{"x":1,"y":0,"z":0}}, + "outputs":{"vrchat":{"emit":{"/example":{"from":"rotation","value":[ + {"euler":"x"},{"euler":{"order":"YXZ","unit":"radians"}},{"scale":2},{"divide":{"x":2}},{"offset":{"z":1}},{"clamp":[-1,1]},{"greaterThan":0},{"lessThan":2} + ]}}}}} + """.trimIndent(), + ), + ), + ) + val bone = pack.bones.single().value + assertIs(bone.rotationFallback) + assertIs(bone.constraint) + val steps = bone.outputs!!.vrchat!!.emit.getValue("/example").value!! + assertEquals(Axis.X, steps[0].euler!!.axis) + assertEquals(EulerOrder.YXZ, steps[1].euler!!.order) + assertIs(steps[2].scale) + assertIs(steps[3].divide) + assertEquals(listOf(-1f, 1f), steps[5].clamp) + assertEquals(0f, steps[6].greaterThan) + assertEquals(2f, steps[7].lessThan) + } +} + +private fun assertRoundTrips(resources: List>, serializer: KSerializer, kind: ResourceKind, json: Json) = resources.forEach { assertRoundTrip(it, serializer, kind, json) } + +private fun assertRoundTrip(resource: SourcedResource, serializer: KSerializer, kind: ResourceKind, json: Json) { + val encoded = json.encodeToString(serializer, resource.value) + assertNull(Validator.forSchema(PackSchemas.schema(kind)).validate(JsonParser(encoded).parse()), resource.path) + assertEquals(resource.value, json.decodeFromString(serializer, encoded), resource.path) +} + +private fun manifest(id: String) = """ + {"formatVersion":1,"id":"$id","nameKey":"example:name","descriptionKey":"example:description","version":[1,0,0],"authors":["Test"]} +""".trimIndent() + +private fun bone(key: String, vmc: String) = """ + {"key":"$key","nameKey":"example:name","outputs":{"vmc":$vmc}} +""".trimIndent() + +private class MemoryStorage( + private val files: Map, + private val symlinks: Set = emptySet(), + private val ensureDirectoryResult: Boolean = true, +) : ConfigStorage { + var createdResourcePackDirectory = false + + override suspend fun read(path: String): String? = files[path] + override suspend fun write(path: String, content: String) = Unit + override suspend fun backup(path: String) = Unit + override suspend fun exists(path: String): Boolean = path in files + override suspend fun ensureDirectory(path: String): Boolean { + if (path == "resourcepacks") createdResourcePackDirectory = ensureDirectoryResult + return ensureDirectoryResult + } + override suspend fun list(path: String): List { + val prefix = path.trimEnd('/') + "/" + val children = linkedMapOf() + for (entry in files.keys + symlinks) { + if (!entry.startsWith(prefix)) continue + val remainder = entry.removePrefix(prefix) + val name = remainder.substringBefore('/') + val type = when { + entry in symlinks && remainder == name -> StorageEntryType.SYMLINK + remainder == name -> StorageEntryType.FILE + else -> StorageEntryType.DIRECTORY + } + children[name] = type + } + return children.map { StorageEntry(it.key, it.value) }.sortedBy { it.name } + } + override suspend fun openTextFile(path: String): TextFileHandle = error("Not used") +} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt index aa96535a5..59d41533d 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -38,6 +38,7 @@ import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsManager import dev.slimevr.resolveConfigDirectory +import dev.slimevr.resourcepacks.ResourcePackManager import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.skeleton.Skeleton import dev.slimevr.solarxr.rpc.ServerInfos @@ -125,6 +126,8 @@ fun main(args: Array) = runBlocking(appCoroutineExceptionHandler + val configFolder = resolveConfigDirectory() ?: error("Unable to resolve config folder") val storage = DesktopConfigStorage(configFolder.toFile()) val config = AppConfig.create(this, storage = storage) + ResourcePackManager.load(storage, javaClass.classLoader) + val server = VRServer.create(this) val serialServer = createDesktopSerialServer(this) val bones = BoneRegistryManager.create(scope = this) diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt b/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt index 9318136a4..cf8ef115c 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/config/storage.kt @@ -1,12 +1,15 @@ package dev.slimevr.desktop.config import dev.slimevr.config.ConfigStorage +import dev.slimevr.config.StorageEntry +import dev.slimevr.config.StorageEntryType import dev.slimevr.config.TextFileHandle import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File import java.io.RandomAccessFile import java.nio.file.Files +import java.nio.file.LinkOption import java.nio.file.StandardCopyOption class DesktopConfigStorage( @@ -48,6 +51,22 @@ class DesktopConfigStorage( directory.isDirectory || directory.mkdirs() } + override suspend fun list(path: String): List = withContext(Dispatchers.IO) { + val directory = resolve(path).toPath() + if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) return@withContext emptyList() + Files.list(directory).use { stream -> + stream.map { child -> + val type = when { + Files.isSymbolicLink(child) -> StorageEntryType.SYMLINK + Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.DIRECTORY + Files.isRegularFile(child, LinkOption.NOFOLLOW_LINKS) -> StorageEntryType.FILE + else -> StorageEntryType.OTHER + } + StorageEntry(child.fileName.toString(), type) + }.sorted(compareBy { it.name }).toList() + } + } + override suspend fun openTextFile(path: String): TextFileHandle = withContext(Dispatchers.IO) { val file = resolve(path) file.parentFile?.mkdirs()