diff --git a/api/build.gradle.kts b/api/build.gradle.kts index 35d26bf..64e366d 100644 --- a/api/build.gradle.kts +++ b/api/build.gradle.kts @@ -11,8 +11,6 @@ tasks.withType().configureEach compilerOptions.jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_21) } -group = "net.hudkit" -version = "0.1.0-ALPHA.2" repositories { mavenCentral() diff --git a/api/src/main/kotlin/Constants.kt b/api/src/main/kotlin/Constants.kt index cb7a2a5..f82affc 100644 --- a/api/src/main/kotlin/Constants.kt +++ b/api/src/main/kotlin/Constants.kt @@ -7,7 +7,6 @@ object Constants { val SPACE_FONT_NAME = "space" val SPACE_FONT = Key.key(NAMESPACE, SPACE_FONT_NAME) - val GLOBAL_Y_SYNC = 9 val ASSETS_DIRECTORY = "assets" val FONTS_DIRECTORY = "font" @@ -15,8 +14,8 @@ object Constants { val BOSSBAR_TEXTURE_PATH = "minecraft/textures/gui/sprites/boss_bar/yellow_background.png" fun getYOffsetFromIndex(index: Int): Int { - val base = 1000 - val increment = 200 + val base = 2000 + val increment = 500 return (base + index * increment) * -1 } } \ No newline at end of file diff --git a/api/src/main/kotlin/HudManager.kt b/api/src/main/kotlin/HudManager.kt index 855e127..915ac98 100644 --- a/api/src/main/kotlin/HudManager.kt +++ b/api/src/main/kotlin/HudManager.kt @@ -195,7 +195,7 @@ class HudManager( fun loadDefinition(): HudDefinition { val project = studioAPI.getProject() val document = project.parseXml() - return HudDefinition(document) + return HudDefinition(document) { name -> studioAPI.getAsset(name) } } /** @@ -298,6 +298,15 @@ class HudManager( huds.remove(audience) } + /** + * Hides and removes all active HUDs. + * Call this before destroying the HudManager. + */ + fun removeAllHuds() { + huds.values.forEach { it.hideHud() } + huds.clear() + } + /** * Re-renders all active HUDs with the current definition. * diff --git a/api/src/main/kotlin/defenition/HudDefinition.kt b/api/src/main/kotlin/defenition/HudDefinition.kt index 0932d63..5d2e874 100644 --- a/api/src/main/kotlin/defenition/HudDefinition.kt +++ b/api/src/main/kotlin/defenition/HudDefinition.kt @@ -5,11 +5,11 @@ import net.hudkit.api.preprocess.HUDPreprocessor import net.hudkit.api.util.CharacterWidthCalculator -open class HudDefinition(override val document: Document) : AbstractHudDefinition() { +open class HudDefinition(override val document: Document, val getAsset: (name: String) -> ByteArray) : AbstractHudDefinition() { override val characterWidthCalculator = CharacterWidthCalculator(mapOf()) fun process(): ProcessedHudDefinition { - val preprocessor = HUDPreprocessor(document) + val preprocessor = HUDPreprocessor(document, getAsset) preprocessor.preprocess() return ProcessedHudDefinition(preprocessor.document, preprocessor) } diff --git a/api/src/main/kotlin/document/HudLayout.kt b/api/src/main/kotlin/document/HudLayout.kt index ac3926e..9b01afd 100644 --- a/api/src/main/kotlin/document/HudLayout.kt +++ b/api/src/main/kotlin/document/HudLayout.kt @@ -94,10 +94,12 @@ class HudLayout(layout: Element, val expandY = background.attributes.get("expandY", expand.toString()).toInt() val widthWithExpand = width + expandX * 2 - val height = 14 + expandY * 2 + val metrics = getContentMetrics(element) + val height = metrics.height + expandY * 2 + val yOffset = 2 - expandY + (metrics.height - 14) / 2 + metrics.ascent val font = Key.key(Constants.NAMESPACE, background.attributes.get("isolate","")) c = c.append(createArbitrarySpace(expandX * -1)) - c = c.append(createBackground(font, widthWithExpand, height, 2)) + c = c.append(createBackground(font, widthWithExpand, height, yOffset)) c = c.append(createArbitrarySpace(expandX)) } @@ -146,6 +148,57 @@ class HudLayout(layout: Element, return null } + private data class ContentMetrics(val height: Int, val ascent: Int) + + private fun getContentMetrics(element: Element): ContentMetrics { + var maxHeight = 14 // Default text height + var maxAscent = 0 + + for (i in 0 until element.childNodes.length) { + val item = element.childNodes.item(i) + if (item is Element && !isHidden(item)) { + val itemHeight: Int + val itemAscent: Int + when (item.tagName) { + "text" -> { + itemHeight = item.attributes.get("size", "14").toInt() + itemAscent = 0 + } + "image" -> { + itemHeight = item.attributes.get("size", "14").toInt() + itemAscent = item.attributes.get("ascent", "0").toInt() + } + "rectangle" -> { + val expand = item.attributes.get("expand", "0").toInt() + itemHeight = item.getAttribute("height").toIntOrNull() + ?: (item.attributes.get("expandY", expand.toString()).toInt() * 2) + itemAscent = 0 + } + "background" -> { + if (item.attributes.get("type", "") == "fill") { + itemHeight = 0 + itemAscent = 0 + } else { + val expand = item.attributes.get("expand", "0").toInt() + itemHeight = item.getAttribute("height").toIntOrNull() + ?: (item.attributes.get("expandY", expand.toString()).toInt() * 2) + itemAscent = 0 + } + } + else -> { + itemHeight = 0 + itemAscent = 0 + } + } + if (itemHeight > maxHeight) { + maxHeight = itemHeight + maxAscent = itemAscent + } + } + } + return ContentMetrics(maxHeight, maxAscent) + } + private fun handleComponentItem(item: Element): Component { val font = Key.key(Constants.NAMESPACE, item.attributes.get("isolate","")) when (item.tagName) { @@ -153,6 +206,24 @@ class HudLayout(layout: Element, val text = item.getInnerXml() return resolvePlaceholders(text, font) } + "image" -> { + var component = Component.text("\uE300") + if (item.getAttribute("shadow") == "false") { + component = component.shadowColor(ShadowColor.shadowColor(0x00000000)) + } + return component.font(font) + } + "rectangle", "background" -> { + if (item.tagName == "background" && item.attributes.get("type", "") == "fill") { + return Component.empty() + } + val expand = item.attributes.get("expand", "0").toInt() + val widthAttr = item.getAttribute("width").toIntOrNull() + val heightAttr = item.getAttribute("height").toIntOrNull() + val width = widthAttr ?: (item.attributes.get("expandX", expand.toString()).toInt() * 2) + val height = heightAttr ?: (item.attributes.get("expandY", expand.toString()).toInt() * 2) + return createBackground(font, width, height, 0).append(createArbitrarySpace(width)) + } } return Component.empty() } @@ -164,13 +235,11 @@ class HudLayout(layout: Element, var lastEnd = 0 for (match in placeholderPattern.findAll(text)) { - // Add text before the placeholder if (match.range.first > lastEnd) { val beforeText = text.substring(lastEnd, match.range.first) result = result.append(applyFontRecursively(mm.deserialize(beforeText), font)) } - // Resolve the placeholder val placeholderKey = match.groupValues[1] val resolved = placeholderResolver.resolve(placeholderKey, audience) result = result.append(applyFontRecursively(resolved, font)) @@ -178,13 +247,11 @@ class HudLayout(layout: Element, lastEnd = match.range.last + 1 } - // Add any remaining text after the last placeholder if (lastEnd < text.length) { val remainingText = text.substring(lastEnd) result = result.append(applyFontRecursively(mm.deserialize(remainingText), font)) } - // If no placeholders found, just parse the whole text if (lastEnd == 0) { return applyFontRecursively(mm.deserialize(text), font) } diff --git a/api/src/main/kotlin/preprocess/HUDPreprocessor.kt b/api/src/main/kotlin/preprocess/HUDPreprocessor.kt index 982c9e0..788a7ab 100644 --- a/api/src/main/kotlin/preprocess/HUDPreprocessor.kt +++ b/api/src/main/kotlin/preprocess/HUDPreprocessor.kt @@ -4,17 +4,18 @@ import net.kyori.adventure.key.Key import org.w3c.dom.Document import org.w3c.dom.Element import net.hudkit.api.text.info.CharacterInfoStore +import net.hudkit.api.text.info.SpaceCharacterInfoStore import net.hudkit.api.Constants import java.io.ByteArrayOutputStream import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream -class HUDPreprocessor(val document: Document) { +class HUDPreprocessor(val document: Document, val getAsset: (name: String) -> ByteArray) { fun preprocess() { treverseNodes(document.documentElement) } - val isolateManager = IsolateManager(this) + val isolateManager = IsolateManager(this, getAsset) private fun parseColor(value: String): Int { val hex = value.removePrefix("#") @@ -24,7 +25,8 @@ class HUDPreprocessor(val document: Document) { fun treverseNodes(element: Element, isolate: Isolate = isolateManager.rootIsolate) { val type: IsolateType? = when (element.tagName) { "text" -> IsolateType.TEXT - "background" -> IsolateType.RECTANGLE + "background", "rectangle" -> IsolateType.RECTANGLE + "image" -> IsolateType.IMAGE else -> null } @@ -37,6 +39,8 @@ class HUDPreprocessor(val document: Document) { type = type, rounding = element.getAttribute("rounding").toIntOrNull(), color = element.getAttribute("color").takeIf { it.isNotEmpty() }?.let { parseColor(it) }, + src = element.getAttribute("src"), + ascent = element.getAttribute("ascent").toIntOrNull(), inheritedFrom = isolate ) element.setAttribute("isolate", isolate.getIsolateString()) @@ -103,10 +107,13 @@ class HUDPreprocessor(val document: Document) { fun getFontInfoStores(): Map { val map = mutableMapOf() + // Register all isolate fonts isolateManager.isolates.forEach { isolate -> val key = isolate.getIsolateKey() map[key] = isolate.getCharacterInfoStore() } + // Register the space font for arbitrary spacing calculations + map[Constants.SPACE_FONT] = SpaceCharacterInfoStore() return map } } \ No newline at end of file diff --git a/api/src/main/kotlin/preprocess/Isolate.kt b/api/src/main/kotlin/preprocess/Isolate.kt index 92e9460..5556bee 100644 --- a/api/src/main/kotlin/preprocess/Isolate.kt +++ b/api/src/main/kotlin/preprocess/Isolate.kt @@ -43,7 +43,7 @@ enum class IsolateType { RECTANGLE } -class IsolateManager(val hudPreprocessor: HUDPreprocessor) { +class IsolateManager(val hudPreprocessor: HUDPreprocessor, val getAsset: (name: String) -> ByteArray) { val isolates = mutableListOf( TextIsolate(0, 0, Anchor.TOP_LEFT, 0, hudPreprocessor) ) @@ -59,9 +59,11 @@ class IsolateManager(val hudPreprocessor: HUDPreprocessor) { type: IsolateType? = null, rounding: Int? = null, color: Int? = null, + src: String? = null, + ascent: Int? = null, inheritedFrom: Isolate = rootIsolate ): Isolate { - if (y == null && anchor == null && size == null && type == null && rounding == null && color == null) { + if (y == null && anchor == null && size == null && type == null && rounding == null && color == null && src == null && ascent == null) { return inheritedFrom } @@ -73,10 +75,12 @@ class IsolateManager(val hudPreprocessor: HUDPreprocessor) { val resolvedType = type ?: inheritedFrom.type val resolvedRounding = rounding ?: (inheritedFrom as? RectangleIsolate)?.rounding ?: 0 val resolvedColor = color ?: (inheritedFrom as? RectangleIsolate)?.color ?: 0x0000007F + val resolvedAscent = ascent ?: (inheritedFrom as? ImageIsolate)?.userAscent ?: 0 + val src = src ?: "" val isolate = when (resolvedType) { IsolateType.TEXT -> TextIsolate(index, resolvedY, resolvedAnchor, resolvedSize, hudPreprocessor) - IsolateType.IMAGE -> ImageIsolate(index, resolvedY, resolvedAnchor, resolvedSize, hudPreprocessor) + IsolateType.IMAGE -> ImageIsolate(index, resolvedY, resolvedAnchor, resolvedSize, hudPreprocessor, src, getAsset, resolvedAscent) IsolateType.RECTANGLE -> RectangleIsolate(index, resolvedY, resolvedAnchor, resolvedSize, hudPreprocessor, resolvedRounding, resolvedColor) } @@ -155,13 +159,68 @@ class ImageIsolate( y: Int, anchor: Anchor, size: Int, - hudPreprocessor: HUDPreprocessor + hudPreprocessor: HUDPreprocessor, + val src: String, + val getAsset: (name: String) -> ByteArray, + val userAscent: Int = 0 ) : Isolate(index, y, anchor, size, hudPreprocessor) { - override val type = IsolateType.IMAGE + private var assetData: ByteArray? = null + private var imageWidth: Int = 0 + private var imageHeight: Int = 0 + + fun downloadAsset() { + val split = src.split("://") + if (split.size != 2) { + throw IllegalArgumentException("src string contains invalid format") + } + val protocol = split[0] + val path = split[1] + when (protocol) { + "project" -> { + assetData = getAsset(path) + // Read image dimensions + val inputStream = java.io.ByteArrayInputStream(assetData) + val image = javax.imageio.ImageIO.read(inputStream) + imageWidth = image.width + imageHeight = image.height + } + else -> throw RuntimeException("Unsupported asset source protocol: $protocol") + } + } + + override fun register() { + downloadAsset() + + val texturePath = "${Constants.ASSETS_DIRECTORY}/${Constants.NAMESPACE}/textures/${getIsolateString()}.png" + hudPreprocessor.addFile(texturePath, assetData!!) + super.register() + } + + override fun getFontJson(): String { + val font = Font(arrayOf( + BitmapFontProvider( + chars = arrayOf("\uE300"), + file = "${Constants.NAMESPACE}:${getIsolateString()}.png", + ascent = size + userAscent + yOffset, + height = size + ) + )) + return font.toJsonString() + } + + override fun getIsolateString(): String { + return "hud_${type.name.lowercase()}_${anchor.name.lowercase()}_${y}_${size}_${userAscent}_${src.split("//")[1]}" + } + + fun getWidth(): Int { + if (imageHeight == 0) return 0 + // Calculate width based on aspect ratio: width = originalWidth * (size / originalHeight) + return (imageWidth.toFloat() * size.toFloat() / imageHeight.toFloat()).toInt() + } override fun getCharacterInfoStore(): CharacterInfoStore { - throw UnsupportedOperationException("Image isolates are not yet supported") + return StaticCharacterInfoStore(getWidth()) } } @@ -178,7 +237,11 @@ class RectangleIsolate( override val type = IsolateType.RECTANGLE override fun getCharacterInfoStore(): CharacterInfoStore { - return StaticCharacterInfoStore(1) + // Return 0 because CharacterWidthCalculator adds +1 for inter-char spacing. + // The createBackground function adds createArbitrarySpace(-1) after the marker + // to cancel out the 1-pixel advance, making the net advance 0. + // The actual rectangle width is added separately via createArbitrarySpace(width). + return StaticCharacterInfoStore(0) } override fun getIsolateString(): String { diff --git a/api/src/main/kotlin/preprocess/ShaderGenerator.kt b/api/src/main/kotlin/preprocess/ShaderGenerator.kt index c21364e..6e5e3c9 100644 --- a/api/src/main/kotlin/preprocess/ShaderGenerator.kt +++ b/api/src/main/kotlin/preprocess/ShaderGenerator.kt @@ -32,6 +32,7 @@ class ShaderGenerator(val hudPreprocessor: HUDPreprocessor) { pos.x += Color.r * 128; pos.y -= (corner.y - 0.5) * (Color.g * 255); pos.y -= (Color.b * 255) - 128; + vertexColor = vec4(1.0, 1.0, 1.0, 1.0); """.trim() private fun ifStatement(s: String, y: Int, positionOffset: Int, glXoffset: Int, glYoffset: Int, isBackground: Boolean): String { diff --git a/api/src/main/kotlin/studio/HudkitStudioAPI.kt b/api/src/main/kotlin/studio/HudkitStudioAPI.kt index 02a6dbd..db8f389 100644 --- a/api/src/main/kotlin/studio/HudkitStudioAPI.kt +++ b/api/src/main/kotlin/studio/HudkitStudioAPI.kt @@ -1,18 +1,47 @@ package net.hudkit.api.studio import com.google.gson.Gson -import com.google.gson.JsonObject import okhttp3.* import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import net.hudkit.api.studio.license.License +import net.hudkit.api.studio.setup.SetupCallback +import net.hudkit.api.studio.setup.SetupResult +import net.hudkit.api.studio.setup.SetupSession +import net.hudkit.api.studio.setup.StudioSetup -class HudkitStudioAPI(val url: String, val key: String) : StudioAPI { +class HudkitStudioAPI @JvmOverloads constructor( + override val url: String, + override var key: String? = null +) : StudioAPI { private val client = OkHttpClient() private val gson = Gson() private val mediaType = "application/zip".toMediaType() + override fun startSetup(callback: SetupCallback): StudioSetup { + val setup = StudioSetup(url) + setup.startSetup(object : SetupCallback { + override fun onSessionCreated(session: SetupSession) { + callback.onSessionCreated(session) + } + + override fun onSetupComplete(result: SetupResult) { + key = result.key + callback.onSetupComplete(result) + } + + override fun onSetupError(error: String) { + callback.onSetupError(error) + } + }) + return setup + } + + private fun requireKey(): String { + return key ?: throw IllegalStateException("API key not set. Call startSetup() first or provide a key.") + } + override fun getLicense(): License { return makeRequest("/api/v1/license") } @@ -33,7 +62,7 @@ class HudkitStudioAPI(val url: String, val key: String) : StudioAPI { val request = Request.Builder() .url("$url/api/v1/resourcepack") - .addHeader("Authorization", "Bearer $key") + .addHeader("Authorization", "Bearer ${requireKey()}") .addHeader("Origin", url) .post(requestBody) .build() @@ -45,10 +74,22 @@ class HudkitStudioAPI(val url: String, val key: String) : StudioAPI { } } + override fun getAsset(name: String): ByteArray { + val request = Request.Builder() + .url("$url/api/v1/asset/$name") + .addHeader("Authorization", "Bearer ${requireKey()}") + .build() + + client.newCall(request).execute().use { response -> + if (!response.isSuccessful) throw Exception("API Error: ${response.code}") + return response.body?.bytes() ?: throw Exception("Empty response") + } + } + private inline fun makeRequest(endpoint: String): T { val request = Request.Builder() .url("$url$endpoint") - .addHeader("Authorization", "Bearer $key") + .addHeader("Authorization", "Bearer ${requireKey()}") .build() client.newCall(request).execute().use { response -> diff --git a/api/src/main/kotlin/studio/OfflineStudioAPI.kt b/api/src/main/kotlin/studio/OfflineStudioAPI.kt index c035e73..68be5dd 100644 --- a/api/src/main/kotlin/studio/OfflineStudioAPI.kt +++ b/api/src/main/kotlin/studio/OfflineStudioAPI.kt @@ -1,5 +1,8 @@ package net.hudkit.api.studio +import net.hudkit.api.studio.setup.SetupCallback +import net.hudkit.api.studio.setup.StudioSetup + /** * An offline "implementation"(-ish) of the StudioAPI. * Used for running Hudkit in offline mode. @@ -7,10 +10,18 @@ package net.hudkit.api.studio * Limitations: * - Always returns a FREE license. * - Project XML must be set manually. + * - Setup is not available. * * @param xml The XML string representing the project. */ class OfflineStudioAPI(var xml: String) : StudioAPI { + override val url: String = "offline" + override var key: String? = "offline" + + override fun startSetup(callback: SetupCallback): StudioSetup { + throw UnsupportedOperationException("Setup is not available in offline mode") + } + override fun getLicense(): net.hudkit.api.studio.license.License { return net.hudkit.api.studio.license.License( licenseType = net.hudkit.api.studio.license.License.Type.FREE, @@ -28,4 +39,8 @@ class OfflineStudioAPI(var xml: String) : StudioAPI { override fun uploadResourcepack(resourcepack: ByteArray): ResourcepackUploadResponse { throw UnsupportedOperationException("Resourcepack upload is not available in offline mode") } + + override fun getAsset(name: String): ByteArray { + throw UnsupportedOperationException("Asset fetching is not available in offline mode") + } } \ No newline at end of file diff --git a/api/src/main/kotlin/studio/StudioAPI.kt b/api/src/main/kotlin/studio/StudioAPI.kt index 83bec32..d1a1de0 100644 --- a/api/src/main/kotlin/studio/StudioAPI.kt +++ b/api/src/main/kotlin/studio/StudioAPI.kt @@ -1,9 +1,24 @@ package net.hudkit.api.studio import net.hudkit.api.studio.license.License +import net.hudkit.api.studio.setup.SetupCallback +import net.hudkit.api.studio.setup.StudioSetup interface StudioAPI { + val url: String + var key: String? + + /** + * Starts the setup process to connect a server to Hudkit Studio. + * Once complete, the key will be set on this instance. + * + * @param callback The callback to receive setup events + * @return A StudioSetup instance that can be used to cancel the setup + */ + fun startSetup(callback: SetupCallback): StudioSetup + fun getLicense(): License fun getProject(): StudioProject fun uploadResourcepack(resourcepack: ByteArray): ResourcepackUploadResponse + fun getAsset(name: String): ByteArray } \ No newline at end of file diff --git a/api/src/main/kotlin/studio/setup/SetupCallback.kt b/api/src/main/kotlin/studio/setup/SetupCallback.kt new file mode 100644 index 0000000..ee01f21 --- /dev/null +++ b/api/src/main/kotlin/studio/setup/SetupCallback.kt @@ -0,0 +1,27 @@ +package net.hudkit.api.studio.setup + +/** + * Callback interface for setup events. + */ +interface SetupCallback { + /** + * Called when the setup session is created and ready for the user to open in their browser. + * + * @param session The setup session containing the browser URL + */ + fun onSessionCreated(session: SetupSession) + + /** + * Called when the setup is completed successfully. + * + * @param result The result containing the API key + */ + fun onSetupComplete(result: SetupResult) + + /** + * Called when the setup fails or times out. + * + * @param error The error message + */ + fun onSetupError(error: String) +} diff --git a/api/src/main/kotlin/studio/setup/SetupResult.kt b/api/src/main/kotlin/studio/setup/SetupResult.kt new file mode 100644 index 0000000..7aa5622 --- /dev/null +++ b/api/src/main/kotlin/studio/setup/SetupResult.kt @@ -0,0 +1,12 @@ +package net.hudkit.api.studio.setup + +/** + * The result of a completed setup session. + * + * @property key The API key for the connected project + * @property projectId The ID of the project that was connected (if available) + */ +data class SetupResult( + val key: String, + val projectId: String? = null +) diff --git a/api/src/main/kotlin/studio/setup/SetupSession.kt b/api/src/main/kotlin/studio/setup/SetupSession.kt new file mode 100644 index 0000000..21d09ef --- /dev/null +++ b/api/src/main/kotlin/studio/setup/SetupSession.kt @@ -0,0 +1,16 @@ +package net.hudkit.api.studio.setup + +/** + * Represents a setup session for connecting a server to Hudkit Studio. + * + * @property id The unique identifier for this setup session + * @property browserUrl The URL the user should open in their browser to complete setup + * @property pocketbaseUrl The PocketBase URL for realtime subscription + * @property expires ISO 8601 timestamp when this setup session expires + */ +data class SetupSession( + val id: String, + val browserUrl: String, + val pocketbaseUrl: String, + val expires: String +) diff --git a/api/src/main/kotlin/studio/setup/StudioSetup.kt b/api/src/main/kotlin/studio/setup/StudioSetup.kt new file mode 100644 index 0000000..15a3bae --- /dev/null +++ b/api/src/main/kotlin/studio/setup/StudioSetup.kt @@ -0,0 +1,200 @@ +package net.hudkit.api.studio.setup + +import com.google.gson.Gson +import com.google.gson.JsonObject +import okhttp3.* +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.RequestBody.Companion.toRequestBody +import java.util.concurrent.TimeUnit + +/** + * Handles the setup process for connecting a server to Hudkit Studio. + * + * Usage: + * ```kotlin + * val setup = StudioSetup("https://studio.hudkit.net") + * setup.startSetup(object : SetupCallback { + * override fun onSessionCreated(session: SetupSession) { + * println("Open this URL: ${session.browserUrl}") + * } + * override fun onSetupComplete(result: SetupResult) { + * println("Setup complete! Key: ${result.key}") + * } + * override fun onSetupError(error: String) { + * println("Setup failed: $error") + * } + * }) + * ``` + */ +class StudioSetup(private val studioUrl: String) { + private val client = OkHttpClient.Builder() + .readTimeout(0, TimeUnit.MILLISECONDS) // No timeout for SSE + .build() + private val gson = Gson() + private var currentCall: Call? = null + private var sseCall: Call? = null + + /** + * Starts the setup process. + * + * @param callback The callback to receive setup events + */ + fun startSetup(callback: SetupCallback) { + // Create the setup session + val request = Request.Builder() + .url("$studioUrl/api/v1/setup") + .post(ByteArray(0).toRequestBody()) + .build() + + currentCall = client.newCall(request) + currentCall?.enqueue(object : Callback { + override fun onFailure(call: Call, e: java.io.IOException) { + callback.onSetupError("Failed to create setup session: ${e.message}") + } + + override fun onResponse(call: Call, response: Response) { + response.use { + if (!it.isSuccessful) { + callback.onSetupError("Failed to create setup session: HTTP ${it.code}") + return + } + + val json = it.body?.string() + if (json == null) { + callback.onSetupError("Empty response from server") + return + } + + val session = gson.fromJson(json, SetupSession::class.java) + callback.onSessionCreated(session) + + // Subscribe to setup record updates via SSE + subscribeToUpdates(session, callback) + } + } + }) + } + + private fun subscribeToUpdates(session: SetupSession, callback: SetupCallback) { + // PocketBase realtime uses Server-Sent Events + // First, we need to establish an SSE connection + val sseUrl = "${session.pocketbaseUrl}/api/realtime" + + val request = Request.Builder() + .url(sseUrl) + .header("Accept", "text/event-stream") + .header("Cache-Control", "no-cache") + .build() + + sseCall = client.newCall(request) + sseCall?.enqueue(object : Callback { + override fun onFailure(call: Call, e: java.io.IOException) { + callback.onSetupError("Failed to connect to realtime: ${e.message}") + } + + override fun onResponse(call: Call, response: Response) { + if (!response.isSuccessful) { + callback.onSetupError("Failed to connect to realtime: HTTP ${response.code}") + return + } + + val source = response.body?.source() + if (source == null) { + callback.onSetupError("No response body from realtime") + return + } + + var clientId: String? = null + val buffer = StringBuilder() + + try { + while (!source.exhausted()) { + val line = source.readUtf8Line() ?: continue + + if (line.startsWith("data:")) { + buffer.append(line.substring(5).trim()) + } else if (line.isEmpty() && buffer.isNotEmpty()) { + // End of event, process the data + val data = buffer.toString() + buffer.clear() + + try { + val eventJson = gson.fromJson(data, JsonObject::class.java) + + // Check if this is the initial connection event with clientId + if (eventJson.has("clientId") && clientId == null) { + clientId = eventJson.get("clientId").asString + // Subscribe to the setup record + sendSubscription(session.pocketbaseUrl, clientId, session.id, callback) + } + + // Check for record updates + if (eventJson.has("action") && eventJson.has("record")) { + val action = eventJson.get("action").asString + val record = eventJson.getAsJsonObject("record") + + if (action == "update" || action == "create") { + val status = record.get("status")?.asString + val key = record.get("key")?.asString + + if (status == "completed" && !key.isNullOrEmpty()) { + val result = SetupResult(key = key) + callback.onSetupComplete(result) + cancel() + return + } else if (status == "expired") { + callback.onSetupError("Setup session expired") + cancel() + return + } + } + } + } catch (e: Exception) { + // Ignore parse errors for non-JSON events + } + } + } + } catch (e: Exception) { + if (!call.isCanceled()) { + callback.onSetupError("Connection lost: ${e.message}") + } + } + } + }) + } + + private fun sendSubscription(pocketbaseUrl: String, clientId: String, setupId: String, callback: SetupCallback) { + val subscribeBody = gson.toJson(mapOf( + "clientId" to clientId, + "subscriptions" to listOf("setup/$setupId") + )) + + val request = Request.Builder() + .url("$pocketbaseUrl/api/realtime") + .post(subscribeBody.toRequestBody("application/json".toMediaType())) + .build() + + client.newCall(request).enqueue(object : Callback { + override fun onFailure(call: Call, e: java.io.IOException) { + callback.onSetupError("Failed to subscribe: ${e.message}") + } + + override fun onResponse(call: Call, response: Response) { + response.close() + if (!response.isSuccessful) { + callback.onSetupError("Failed to subscribe: HTTP ${response.code}") + } + // Subscription successful, continue listening on SSE + } + }) + } + + /** + * Cancels the ongoing setup process. + */ + fun cancel() { + currentCall?.cancel() + sseCall?.cancel() + } + +} diff --git a/api/src/main/kotlin/text/info/SpaceCharacterInfoStore.kt b/api/src/main/kotlin/text/info/SpaceCharacterInfoStore.kt new file mode 100644 index 0000000..a7892fa --- /dev/null +++ b/api/src/main/kotlin/text/info/SpaceCharacterInfoStore.kt @@ -0,0 +1,41 @@ +package net.hudkit.api.text.info + +/** + * CharacterInfoStore for the space font. + * + * Space font characters have direct advance values without inter-character spacing. + * Since CharacterWidthCalculator adds +1 for spacing, we return (advance - 1) + * so the final calculation gives the correct advance. + */ +class SpaceCharacterInfoStore : CharacterInfoStore() { + private val advances = mapOf( + '\uE100' to -1, + '\uE101' to -2, + '\uE102' to -4, + '\uE103' to -8, + '\uE104' to -16, + '\uE105' to -32, + '\uE106' to -64, + '\uE107' to -128, + '\uE108' to -256, + '\uE109' to -512, + '\uE200' to 1, + '\uE201' to 2, + '\uE202' to 4, + '\uE203' to 8, + '\uE204' to 16, + '\uE205' to 32, + '\uE206' to 64, + '\uE207' to 128, + '\uE208' to 256, + '\uE209' to 512 + ) + + override fun getCharacterInfo(char: Char): CharacterInfo? { + val advance = advances[char] ?: return null + // Return (advance - 1) because CharacterWidthCalculator adds +1 for spacing + // This way: (advance - 1) + 1 = advance + val width = advance - 1 + return CharacterInfo(char, width, width) + } +} diff --git a/build.gradle.kts b/build.gradle.kts index bec96d3..311914f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,6 +5,9 @@ plugins { subprojects { apply(plugin = "org.jetbrains.kotlin.jvm") + group = "net.hudkit" + version = property("hudkitVersion") as String + repositories { mavenCentral() } diff --git a/gradle.properties b/gradle.properties index 7fc6f1f..4b9e73b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,2 @@ kotlin.code.style=official +hudkitVersion=0.1.0-ALPHA.2 diff --git a/minestom/build.gradle.kts b/minestom/build.gradle.kts index 885a130..29baeda 100644 --- a/minestom/build.gradle.kts +++ b/minestom/build.gradle.kts @@ -22,7 +22,6 @@ tasks.withType().configureEach } group = "net.hudkit.minestom-viewer" -version = "0.1.0-ALPHA.2" repositories { mavenCentral() diff --git a/paper/build.gradle.kts b/paper/build.gradle.kts index 1f03d7f..881e1bf 100644 --- a/paper/build.gradle.kts +++ b/paper/build.gradle.kts @@ -18,7 +18,6 @@ tasks.withType().configureEach } group = "net.hudkit.paper" -version = "0.1.0-ALPHA.2" repositories { mavenCentral() diff --git a/paper/src/main/kotlin/net/hudkit/paper/HudkitPlugin.kt b/paper/src/main/kotlin/net/hudkit/paper/HudkitPlugin.kt index 4c616c3..6699150 100644 --- a/paper/src/main/kotlin/net/hudkit/paper/HudkitPlugin.kt +++ b/paper/src/main/kotlin/net/hudkit/paper/HudkitPlugin.kt @@ -1,5 +1,7 @@ package net.hudkit.paper +import io.papermc.paper.event.connection.PlayerConnectionValidateLoginEvent +import io.papermc.paper.event.connection.configuration.AsyncPlayerConnectionConfigureEvent import net.hudkit.api.HudManager import net.hudkit.api.RenderOptions import net.hudkit.api.StudioOptions @@ -7,12 +9,14 @@ import net.hudkit.paper.command.HudkitCommands import net.hudkit.paper.config.ConfigLoader import net.hudkit.paper.config.HudkitConfig import net.hudkit.paper.placeholder.PlaceholderAPIResolver +import net.hudkit.paper.setup.Setup import net.kyori.adventure.text.minimessage.MiniMessage import org.bukkit.Bukkit import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerJoinEvent +import org.bukkit.event.player.PlayerLoginEvent import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.plugin.java.JavaPlugin import java.nio.file.Files @@ -123,20 +127,9 @@ class HudkitPlugin : JavaPlugin(), Listener { fun reload(): Result { return try { stopRefreshLoop() + hudManager?.removeAllHuds() loadConfiguration() - - val manager = hudManager - if (manager == null) { - initializeHudManager() - } else { - val definition = manager.loadDefinition().process() - manager.definition = definition - - manager.uploadResourcepack(definition.resourcepack) - logger.info("Resource pack uploaded successfully.") - - logger.info("HUD definition reloaded successfully.") - } + initializeHudManager() Bukkit.getOnlinePlayers().forEach { player -> hudManager?.showHud(player) @@ -157,20 +150,25 @@ class HudkitPlugin : JavaPlugin(), Listener { return miniMessage.deserialize(prefixed) } + @EventHandler + fun onPlayerConfigure(event: AsyncPlayerConnectionConfigureEvent) { + val player = event.connection.audience + + if (config.hud.sendResourcepackOnJoin) { + hudManager?.sendResourcepack(player) + } + } + @EventHandler fun onPlayerJoin(event: PlayerJoinEvent) { val player = event.player - if (config.hud.showOnJoin) { - Bukkit.getScheduler().runTaskLater(this, Runnable { - hudManager?.showHud(player) - }, 20L) + if (player.hasPermission("hudkit.setup") && config.studio.apiKey == "DEMO") { + Setup(player, this).start() } - if (config.hud.sendResourcepackOnJoin) { - Bukkit.getScheduler().runTaskLater(this, Runnable { - hudManager?.sendResourcepack(player) - }, 40L) + if (config.hud.showOnJoin) { + hudManager?.showHud(player) } } @@ -185,4 +183,26 @@ class HudkitPlugin : JavaPlugin(), Listener { fun rerenderAllHuds() { hudManager?.rerenderAllHuds() } + + fun saveApiKey(apiKey: String): Result { + return try { + val configPath = dataFolder.toPath().resolve("config.toml") + val content = if (configPath.exists()) { + Files.readString(configPath) + } else { + ConfigLoader.getDefaultConfig() + } + + // Replace the apiKey line in the config + val updatedContent = content.replace( + Regex("""apiKey\s*=\s*"[^"]*""""), + """apiKey = "$apiKey"""" + ) + + Files.writeString(configPath, updatedContent) + Result.success(Unit) + } catch (e: Exception) { + Result.failure(e) + } + } } diff --git a/paper/src/main/kotlin/net/hudkit/paper/command/HudkitCommands.kt b/paper/src/main/kotlin/net/hudkit/paper/command/HudkitCommands.kt index 270cd3c..e8fe578 100644 --- a/paper/src/main/kotlin/net/hudkit/paper/command/HudkitCommands.kt +++ b/paper/src/main/kotlin/net/hudkit/paper/command/HudkitCommands.kt @@ -7,7 +7,13 @@ import io.papermc.paper.command.brigadier.CommandSourceStack import io.papermc.paper.command.brigadier.Commands import io.papermc.paper.plugin.lifecycle.event.LifecycleEventManager import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents +import net.hudkit.api.studio.HudkitStudioAPI +import net.hudkit.api.studio.setup.SetupCallback +import net.hudkit.api.studio.setup.SetupResult +import net.hudkit.api.studio.setup.SetupSession import net.hudkit.paper.HudkitPlugin +import net.hudkit.paper.setup.Setup +import org.bukkit.Bukkit import org.bukkit.entity.Player import org.bukkit.plugin.Plugin @@ -21,6 +27,11 @@ object HudkitCommands { commands.register( Commands.literal("hudkit") + .then( + Commands.literal("setup") + .requires { it.sender.hasPermission("hudkit.setup") } + .executes { ctx -> handleSetup(ctx, plugin) } + ) .then( Commands.literal("reload") .requires { it.sender.hasPermission("hudkit.reload") } @@ -58,6 +69,9 @@ object HudkitCommands { private fun handleHelp(ctx: CommandContext, plugin: HudkitPlugin): Int { val sender = ctx.source.sender sender.sendMessage(plugin.formatMessage("Hudkit Commands:")) + if (sender.hasPermission("hudkit.setup")) { + sender.sendMessage(plugin.formatMessage("/hudkit setup - Connect to Hudkit Studio")) + } if (sender.hasPermission("hudkit.reload")) { sender.sendMessage(plugin.formatMessage("/hudkit reload - Reload configuration")) } @@ -71,6 +85,19 @@ object HudkitCommands { return Command.SINGLE_SUCCESS } + private fun handleSetup(ctx: CommandContext, plugin: HudkitPlugin): Int { + val sender = ctx.source.sender + sender.sendMessage(plugin.formatMessage("Starting setup...")) + + if (sender !is Player) { + sender.sendMessage(plugin.formatMessage("Only players can use this command")) + } + + Setup(sender as Player, plugin).start() + + return Command.SINGLE_SUCCESS + } + private fun handleReload(ctx: CommandContext, plugin: HudkitPlugin): Int { val sender = ctx.source.sender val result = plugin.reload() diff --git a/paper/src/main/kotlin/net/hudkit/paper/setup/Setup.kt b/paper/src/main/kotlin/net/hudkit/paper/setup/Setup.kt new file mode 100644 index 0000000..8195e16 --- /dev/null +++ b/paper/src/main/kotlin/net/hudkit/paper/setup/Setup.kt @@ -0,0 +1,99 @@ +package net.hudkit.paper.setup + +import io.papermc.paper.dialog.Dialog +import io.papermc.paper.registry.data.dialog.ActionButton +import io.papermc.paper.registry.data.dialog.DialogBase +import io.papermc.paper.registry.data.dialog.action.DialogAction +import io.papermc.paper.registry.data.dialog.body.DialogBody +import io.papermc.paper.registry.data.dialog.type.DialogType +import net.hudkit.api.studio.HudkitStudioAPI +import net.hudkit.api.studio.setup.SetupCallback +import net.hudkit.api.studio.setup.SetupResult +import net.hudkit.api.studio.setup.SetupSession +import net.hudkit.paper.HudkitPlugin +import net.kyori.adventure.text.Component +import net.kyori.adventure.text.event.ClickEvent +import net.kyori.adventure.text.format.TextDecoration +import org.bukkit.Bukkit +import org.bukkit.entity.Player + + +class Setup(val player: Player, val plugin: HudkitPlugin) : SetupCallback { + fun createDialog(url: String): Dialog { + return Dialog.create({ builder -> + builder.empty() + .base( + DialogBase.builder(Component.text(" ".repeat(999))) + .body( + listOf( + DialogBody.plainMessage(Component.text("\n".repeat(3)), 1), + DialogBody.plainMessage( + Component.text("Welcome to Hudkit!").decoration(TextDecoration.BOLD, true) + ), + DialogBody.plainMessage( + Component.text("Hudkit comes with a minimal HUD to show you the basics of what it can do. Continue to Hudkit Studio to create your own!"), + 500 + ), + DialogBody.plainMessage(Component.text("\n".repeat(5)), 1), + ) + ) + + .build() + ) + .type( + DialogType.multiAction( + listOf( + ActionButton.create( + Component.text("Setup"), + null, + 100, + DialogAction.staticAction( + ClickEvent.openUrl(url) + ) + ), + + ActionButton.create( + Component.text("I'll do it later."), + null, + 100, + DialogAction.staticAction(ClickEvent.callback { + player.closeDialog() + } + ) + ) + )).build()) + }) + } + + fun start() { + val api = HudkitStudioAPI(plugin.config.studio.apiUrl) + api.startSetup(this) + } + + override fun onSessionCreated(session: SetupSession) { + player.showDialog(createDialog(session.browserUrl)) + } + + override fun onSetupComplete(result: SetupResult) { + player.closeDialog() + Bukkit.getScheduler().runTask(plugin, Runnable { + val saveResult = plugin.saveApiKey(result.key) + if (saveResult.isSuccess) { + val reloadResult = plugin.reload() + if (reloadResult.isSuccess) { + player.sendMessage(plugin.formatMessage("Hudkit is now connected and ready!")) + } else { + player.sendMessage(plugin.formatMessage("Failed to reload: ${reloadResult.exceptionOrNull()?.message}")) + } + } else { + player.sendMessage(plugin.formatMessage("Failed to save API key: ${saveResult.exceptionOrNull()?.message}")) + } + }) + } + + override fun onSetupError(error: String) { + Bukkit.getScheduler().runTask(plugin, Runnable { + player.sendMessage(plugin.formatMessage("Setup failed: $error")) + }) + } +} \ No newline at end of file diff --git a/studio/pb_migrations/1768500000_created_media.js b/studio/pb_migrations/1768500000_created_media.js new file mode 100644 index 0000000..ea909aa --- /dev/null +++ b/studio/pb_migrations/1768500000_created_media.js @@ -0,0 +1,154 @@ +/// +migrate((app) => { + const collection = new Collection({ + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "cascadeDelete": true, + "collectionId": "pbc_484305853", + "hidden": false, + "id": "relation_media_project", + "maxSelect": 1, + "minSelect": 0, + "name": "project", + "presentable": false, + "required": true, + "system": false, + "type": "relation" + }, + { + "autogeneratePattern": "", + "hidden": false, + "id": "text_media_type", + "max": 50, + "min": 0, + "name": "type", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "hidden": false, + "id": "file_media_file", + "maxSelect": 1, + "maxSize": 5242880, + "mimeTypes": [ + "image/png", + "image/jpeg", + "image/webp" + ], + "name": "file", + "presentable": false, + "protected": false, + "required": true, + "system": false, + "thumbs": ["100x100", "256x256"], + "type": "file" + }, + { + "autogeneratePattern": "", + "hidden": false, + "id": "text_media_name", + "max": 255, + "min": 0, + "name": "name", + "pattern": "", + "presentable": true, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "hidden": false, + "id": "number_media_width", + "max": null, + "min": 0, + "name": "width", + "onlyInt": true, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "hidden": false, + "id": "number_media_height", + "max": null, + "min": 0, + "name": "height", + "onlyInt": true, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "hidden": false, + "id": "number_media_duration", + "max": null, + "min": 0, + "name": "duration", + "onlyInt": false, + "presentable": false, + "required": false, + "system": false, + "type": "number" + }, + { + "hidden": false, + "id": "autodate_media_created", + "name": "created", + "onCreate": true, + "onUpdate": false, + "presentable": false, + "system": false, + "type": "autodate" + }, + { + "hidden": false, + "id": "autodate_media_updated", + "name": "updated", + "onCreate": true, + "onUpdate": true, + "presentable": false, + "system": false, + "type": "autodate" + } + ], + "id": "pbc_media", + "indexes": [ + "CREATE INDEX idx_media_project ON media (project)" + ], + "listRule": "", + "name": "media", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": "" + }); + + return app.save(collection); +}, (app) => { + const collection = app.findCollectionByNameOrId("pbc_media"); + + return app.delete(collection); +}) diff --git a/studio/pb_migrations/1768600000_updated_projects_storage.js b/studio/pb_migrations/1768600000_updated_projects_storage.js new file mode 100644 index 0000000..3fa94a4 --- /dev/null +++ b/studio/pb_migrations/1768600000_updated_projects_storage.js @@ -0,0 +1,60 @@ +/// +migrate((app) => { + const collection = app.findCollectionByNameOrId("pbc_484305853") + + // add storage_used field (bytes) + collection.fields.addAt(collection.fields.length, new Field({ + "hidden": false, + "id": "number_storage_used", + "max": null, + "min": 0, + "name": "storage_used", + "onlyInt": true, + "presentable": false, + "required": false, + "system": false, + "type": "number" + })) + + // add storage_limit field (bytes) - default 50MB + collection.fields.addAt(collection.fields.length, new Field({ + "hidden": false, + "id": "number_storage_limit", + "max": null, + "min": 0, + "name": "storage_limit", + "onlyInt": true, + "presentable": false, + "required": false, + "system": false, + "type": "number" + })) + + // update rules to prevent users from modifying storage fields + unmarshal({ + "listRule": "owner = @request.auth.id || collaborators.id ?= @request.auth.id", + "viewRule": "owner = @request.auth.id || collaborators.id ?= @request.auth.id", + "createRule": "owner = @request.auth.id", + "updateRule": "owner = @request.auth.id || (collaborators.id ?= @request.auth.id && @request.body.owner:isset = false && @request.body.collaborators:isset = false && @request.body.storage_used:isset = false && @request.body.storage_limit:isset = false)", + "deleteRule": "owner = @request.auth.id" + }, collection) + + return app.save(collection) +}, (app) => { + const collection = app.findCollectionByNameOrId("pbc_484305853") + + // remove fields + collection.fields.removeById("number_storage_used") + collection.fields.removeById("number_storage_limit") + + // revert rules + unmarshal({ + "listRule": "owner = @request.auth.id || collaborators.id ?= @request.auth.id", + "viewRule": "owner = @request.auth.id || collaborators.id ?= @request.auth.id", + "createRule": "owner = @request.auth.id", + "updateRule": "owner = @request.auth.id || (collaborators.id ?= @request.auth.id && @request.body.owner:isset = false && @request.body.collaborators:isset = false)", + "deleteRule": "owner = @request.auth.id" + }, collection) + + return app.save(collection) +}) diff --git a/studio/pb_migrations/1768600001_updated_media_size.js b/studio/pb_migrations/1768600001_updated_media_size.js new file mode 100644 index 0000000..1d472df --- /dev/null +++ b/studio/pb_migrations/1768600001_updated_media_size.js @@ -0,0 +1,27 @@ +/// +migrate((app) => { + const collection = app.findCollectionByNameOrId("pbc_media") + + // add size field (bytes) + collection.fields.addAt(collection.fields.length, new Field({ + "hidden": false, + "id": "number_media_size", + "max": null, + "min": 0, + "name": "size", + "onlyInt": true, + "presentable": false, + "required": false, + "system": false, + "type": "number" + })) + + return app.save(collection) +}, (app) => { + const collection = app.findCollectionByNameOrId("pbc_media") + + // remove field + collection.fields.removeById("number_media_size") + + return app.save(collection) +}) diff --git a/studio/pb_migrations/1768696297_updated_setup.js b/studio/pb_migrations/1768696297_updated_setup.js new file mode 100644 index 0000000..3d34f11 --- /dev/null +++ b/studio/pb_migrations/1768696297_updated_setup.js @@ -0,0 +1,20 @@ +/// +migrate((app) => { + const collection = app.findCollectionByNameOrId("pbc_setup_collection") + + // update collection data + unmarshal({ + "updateRule": "" + }, collection) + + return app.save(collection) +}, (app) => { + const collection = app.findCollectionByNameOrId("pbc_setup_collection") + + // update collection data + unmarshal({ + "updateRule": null + }, collection) + + return app.save(collection) +}) diff --git a/studio/pb_migrations/1768800000_created_setup.js b/studio/pb_migrations/1768800000_created_setup.js new file mode 100644 index 0000000..b7ca663 --- /dev/null +++ b/studio/pb_migrations/1768800000_created_setup.js @@ -0,0 +1,97 @@ +/// +migrate((app) => { + const collection = new Collection({ + "createRule": null, + "deleteRule": null, + "fields": [ + { + "autogeneratePattern": "[a-z0-9]{15}", + "hidden": false, + "id": "text3208210256", + "max": 15, + "min": 15, + "name": "id", + "pattern": "^[a-z0-9]+$", + "presentable": false, + "primaryKey": true, + "required": true, + "system": true, + "type": "text" + }, + { + "autogeneratePattern": "", + "hidden": false, + "id": "text_pocketbase_url", + "max": 500, + "min": 0, + "name": "pocketbase_url", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": true, + "system": false, + "type": "text" + }, + { + "autogeneratePattern": "", + "hidden": false, + "id": "text_key", + "max": 50, + "min": 0, + "name": "key", + "pattern": "", + "presentable": false, + "primaryKey": false, + "required": false, + "system": false, + "type": "text" + }, + { + "hidden": false, + "id": "select_status", + "maxSelect": 1, + "name": "status", + "presentable": false, + "required": true, + "system": false, + "type": "select", + "values": ["pending", "completed", "expired"] + }, + { + "hidden": false, + "id": "autodate2990389176", + "name": "created", + "onCreate": true, + "onUpdate": false, + "presentable": false, + "system": false, + "type": "autodate" + }, + { + "hidden": false, + "id": "date_expires", + "max": "", + "min": "", + "name": "expires", + "presentable": false, + "required": true, + "system": false, + "type": "date" + } + ], + "id": "pbc_setup_collection", + "indexes": [], + "listRule": null, + "name": "setup", + "system": false, + "type": "base", + "updateRule": null, + "viewRule": "" + }); + + return app.save(collection); +}, (app) => { + const collection = app.findCollectionByNameOrId("pbc_setup_collection"); + + return app.delete(collection); +}) diff --git a/studio/ui/src/lib/components/canvas-element.svelte b/studio/ui/src/lib/components/canvas-element.svelte index 0b181ac..f3b86b4 100644 --- a/studio/ui/src/lib/components/canvas-element.svelte +++ b/studio/ui/src/lib/components/canvas-element.svelte @@ -1,4 +1,3 @@ - @@ -338,40 +318,48 @@
- {#if hasBackground} + {@const colorHex = backgroundColor.slice(0, 7)} + {@const alphaHex = backgroundColor.length === 9 ? backgroundColor.slice(7, 9) : 'FF'} + {@const opacity = parseInt(alphaHex, 16) / 255}
{/if} - {#each visibleChildren as node (node)} - + {#if node.tagName.toLowerCase() === 'image'} + + {:else if node.tagName.toLowerCase() === 'rectangle'} + + {:else} + + {/if} {/each}
diff --git a/studio/ui/src/lib/components/canvas-media.svelte b/studio/ui/src/lib/components/canvas-media.svelte new file mode 100644 index 0000000..09607b0 --- /dev/null +++ b/studio/ui/src/lib/components/canvas-media.svelte @@ -0,0 +1,200 @@ + + + diff --git a/studio/ui/src/lib/components/canvas-rectangle.svelte b/studio/ui/src/lib/components/canvas-rectangle.svelte new file mode 100644 index 0000000..49c2272 --- /dev/null +++ b/studio/ui/src/lib/components/canvas-rectangle.svelte @@ -0,0 +1,201 @@ + + + diff --git a/studio/ui/src/lib/components/color-picker.svelte b/studio/ui/src/lib/components/color-picker.svelte new file mode 100644 index 0000000..35efa53 --- /dev/null +++ b/studio/ui/src/lib/components/color-picker.svelte @@ -0,0 +1,307 @@ + + + + + + + +
+ +
+ +
+
+ + +
+
+
+ + + {#if showOpacity} +
+
+
+ {/if} + + +
+
+ + {#if showOpacity} + { + const val = Math.max(0, Math.min(100, Number((e.target as HTMLInputElement).value))); + onchange(toHexWithAlpha(rgbValue, val / 100)); + }} + min={0} + max={100} + class="h-8 w-16 text-xs" + /> + {/if} +
+
+
+
diff --git a/studio/ui/src/lib/components/draggable-number.svelte b/studio/ui/src/lib/components/draggable-number.svelte new file mode 100644 index 0000000..be08b46 --- /dev/null +++ b/studio/ui/src/lib/components/draggable-number.svelte @@ -0,0 +1,108 @@ + + +
+ + {label} + + { + isEditing = true; + setTimeout(() => inputElement?.select(), 0); + }} + onchange={handleInputChange} + onblur={handleInputBlur} + onkeydown={handleInputKeydown} + /> +
diff --git a/studio/ui/src/lib/components/element-icon.svelte b/studio/ui/src/lib/components/element-icon.svelte index d257f7c..f2e5c5d 100644 --- a/studio/ui/src/lib/components/element-icon.svelte +++ b/studio/ui/src/lib/components/element-icon.svelte @@ -5,14 +5,17 @@ import ComponentIcon from '@lucide/svelte/icons/component'; import ImageIcon from '@lucide/svelte/icons/image'; import FolderIcon from '@lucide/svelte/icons/folder'; + import SquareIcon from '@lucide/svelte/icons/square'; {#if element.tagName === 'element'} {:else if element.tagName === 'text'} -{:else if element.tagName === 'glyph'} +{:else if element.tagName === 'image' || element.tagName === 'glyph'} +{:else if element.tagName === 'rectangle'} + {:else} {/if} diff --git a/studio/ui/src/lib/components/file-tree.svelte b/studio/ui/src/lib/components/file-tree.svelte index 8e6ce06..c97ce7f 100644 --- a/studio/ui/src/lib/components/file-tree.svelte +++ b/studio/ui/src/lib/components/file-tree.svelte @@ -6,6 +6,23 @@ import PlusIcon from '@lucide/svelte/icons/plus'; import EditableKey from './editable-key.svelte'; import ElementIcon from './element-icon.svelte'; + import MediaPickerDialog from './media-picker-dialog.svelte'; + + let showMediaDialog = $state(false); + let mediaDialogParent: Element | null = $state(null); + + function openMediaDialog(parent: Element) { + mediaDialogParent = parent; + showMediaDialog = true; + } + + function handleMediaSelected(mediaId: string) { + if (mediaDialogParent) { + project.createImage(mediaDialogParent, mediaId); + } + showMediaDialog = false; + mediaDialogParent = null; + } let draggedElement: Element | null = $state(null); let dropTarget: Element | null = $state(null); @@ -17,7 +34,7 @@ const draggedTag = draggedElement.tagName; const targetTag = target.tagName; - if (draggedTag === 'text' || draggedTag === 'image') { + if (draggedTag === 'text' || draggedTag === 'image' || draggedTag === 'rectangle') { return targetTag === 'element'; } @@ -26,7 +43,7 @@ } if (targetTag === 'element') { - return draggedTag === 'text' || draggedTag === 'image'; + return draggedTag === 'text' || draggedTag === 'image' || draggedTag === 'rectangle'; } return false; @@ -340,7 +357,8 @@ {/each} {#if element.tagName === 'element'} {@render TreeAdd('Add text', () => project.createText(element))} - {@render TreeAdd('Add image', () => {})} + {@render TreeAdd('Add image', () => openMediaDialog(element))} + {@render TreeAdd('Add rectangle', () => project.createRectangle(element))} {:else} {@render TreeAdd('Add element', () => project.createElement(element))} {@render TreeAdd('Add group', () => project.createGroup(element))} @@ -351,3 +369,5 @@ {/if} {/snippet} + + diff --git a/studio/ui/src/lib/components/inspect.svelte b/studio/ui/src/lib/components/inspect.svelte index ae3ed25..5beed79 100644 --- a/studio/ui/src/lib/components/inspect.svelte +++ b/studio/ui/src/lib/components/inspect.svelte @@ -5,6 +5,8 @@ import Button from './ui/button/button.svelte'; import Input from './ui/input/input.svelte'; import MiniMessageEditor from './minimessage/editor.svelte'; + import MediaPickerDialog from './media-picker-dialog.svelte'; + import DraggableNumber from './draggable-number.svelte'; import AlignStartIcon from '@lucide/svelte/icons/align-start-vertical'; import AlignCenterIcon from '@lucide/svelte/icons/align-center-vertical'; @@ -22,7 +24,13 @@ import ArrowDownIcon from '@lucide/svelte/icons/arrow-down'; import ArrowDownRightIcon from '@lucide/svelte/icons/arrow-down-right'; + import LinkIcon from '@lucide/svelte/icons/link'; + import ImageIcon from '@lucide/svelte/icons/image'; + import Switch from './ui/switch/switch.svelte'; + import ColorPicker from './color-picker.svelte'; + + let showMediaPicker = $state(false); const ANCHORING_OPTIONS = { 'top-left': ArrowUpLeftIcon, @@ -38,7 +46,6 @@ const ALIGNMENTS = ['left', 'center', 'right'] as const; - // Derived state that syncs with selection AND version changes let keyInput = $derived.by(() => { void project.version; return project.selected?.getAttribute('key') ?? ''; @@ -66,10 +73,9 @@ let currentAlignment = $derived.by(() => { void project.version; - return project.selected?.getAttribute('align') ?? 'left'; + return project.selected?.getAttribute('align') ?? 'center'; }); - // Background state let backgroundElement = $derived.by(() => { void project.version; if (!project.selected) return null; @@ -91,6 +97,87 @@ return Number(backgroundElement?.getAttribute('expandY')) || 0; }); + let backgroundColor = $derived.by(() => { + void project.version; + return backgroundElement?.getAttribute('color') || '#0000007F'; + }); + + let imageSrc = $derived.by(() => { + void project.version; + return project.selected?.getAttribute('src') || ''; + }); + + let imageSize = $derived.by(() => { + void project.version; + return Number(project.selected?.getAttribute('size')) || 16; + }); + + let imageAscent = $derived.by(() => { + void project.version; + return Number(project.selected?.getAttribute('ascent')) || 0; + }); + + let imageShadow = $derived.by(() => { + void project.version; + return project.selected?.getAttribute('shadow') === 'true'; + }); + + let selectedMedia = $derived.by(() => { + if (!imageSrc.startsWith('project://')) return null; + const mediaId = imageSrc.replace('project://', ''); + return project.media.get(mediaId) || null; + }); + + let isExternalUrl = $derived( + imageSrc.startsWith('http://') || imageSrc.startsWith('https://') + ); + + let rectangleWidth = $derived.by(() => { + void project.version; + return Number(project.selected?.getAttribute('width')) || 16; + }); + + let rectangleHeight = $derived.by(() => { + void project.version; + return Number(project.selected?.getAttribute('height')) || 16; + }); + + let rectangleColor = $derived.by(() => { + void project.version; + return project.selected?.getAttribute('color') || '#ffffffff'; + }); + + function updateRectangleDimension(attr: 'width' | 'height', value: number) { + project.selected?.setAttribute(attr, value.toString()); + project.notifyChange(); + } + + function updateRectangleColor(color: string) { + project.selected?.setAttribute('color', color); + project.notifyChange(); + } + + function updateImageSrc(src: string) { + project.selected?.setAttribute('src', src); + project.notifyChange(); + } + + function updateImageDimension(axis: 'size' | 'ascent', value: number) { + project.selected?.setAttribute(axis, value.toString()); + project.notifyChange(); + } + + async function handleImageChange(mediaId: string) { + if (!project.selected) return; + project.selected.setAttribute('src', `project://${mediaId}`); + + const media = project.media.get(mediaId); + if (media) { + project.selected.setAttribute('size', String(media.height || 16)); + } + project.notifyChange(); + } + function capitalize(str: string): string { return str.charAt(0).toUpperCase() + str.slice(1); } @@ -125,17 +212,16 @@ if (!project.selected) return; if (enabled) { - // Create background element if it doesn't exist if (!backgroundElement) { const bg = document.createElement('background'); bg.setAttribute('type', 'fill'); bg.setAttribute('expandX', '0'); bg.setAttribute('expandY', '0'); + bg.setAttribute('color', '#0000007F'); // Insert at the beginning so it renders behind other content project.selected.insertBefore(bg, project.selected.firstChild); } } else { - // Remove background element if it exists if (backgroundElement) { backgroundElement.remove(); } @@ -150,6 +236,13 @@ } } + function updateBackgroundColor(color: string) { + if (backgroundElement) { + backgroundElement.setAttribute('color', color); + project.notifyChange(); + } + } + function handleKeyInputKeydown(event: KeyboardEvent) { if (event.key === 'Escape' || event.key === 'Enter') { (event.target as HTMLInputElement).blur(); @@ -159,7 +252,6 @@ let textContentElm: HTMLInputElement | null = $state(null); function onKeyDown(event: KeyboardEvent) { - // Undo/redo shortcuts (work regardless of focus) if (event.ctrlKey || event.metaKey) { if (event.key === 'z' && !event.shiftKey) { event.preventDefault(); @@ -204,13 +296,11 @@ {#if project.selected} -
{capitalize(project.selected.tagName)}
-
{/if} + {#if project.selected.tagName === 'image'} +
+ Image Source + + {#if selectedMedia} +
+ {selectedMedia.name} +
+

{selectedMedia.name}

+

+ {selectedMedia.width} x {selectedMedia.height} +

+
+
+ {:else if isExternalUrl} +
+ External image +
+

External URL

+
+
+ {:else if !imageSrc} +

No image selected

+ {/if} + + + +
+ + { + const url = (e.target as HTMLInputElement).value; + if (url) updateImageSrc(url); + }} + class="h-8" + /> +
+
+ +
+ Dimensions + updateImageDimension('size', v)} + min={1} + max={255} + /> + updateImageDimension('ascent', v)} + min={-128} + max={128} + /> +
+ +
+ Visual +
+ Shadow + { + project.selected?.setAttribute('shadow', checked ? 'true' : 'false'); + project.notifyChange(); + }} + /> +
+
+ {/if} + + {#if project.selected.tagName === 'rectangle'} +
+ Dimensions + updateRectangleDimension('width', v)} + min={1} + /> + updateRectangleDimension('height', v)} + min={1} + max={255} + /> +
+ +
+ Appearance +
+ Color + +
+
+ {/if} + {#if project.selected.tagName === 'element'}
Position
-
Anchor
@@ -252,33 +462,15 @@
-
- - + updatePosition('x', v)} /> + updatePosition('y', v)} />
Alignment - {#each ALIGNMENTS as alignment (alignment)}
{/if} {/if} + + handleImageChange(mediaId)} +/> diff --git a/studio/ui/src/lib/components/media-picker-dialog.svelte b/studio/ui/src/lib/components/media-picker-dialog.svelte new file mode 100644 index 0000000..7396900 --- /dev/null +++ b/studio/ui/src/lib/components/media-picker-dialog.svelte @@ -0,0 +1,152 @@ + + + !isOpen && handleClose()}> + + + Select {type === 'image' ? 'Image' : 'Media'} + + +
+ +
+ + + {#if uploadError} +

{uploadError}

+ {/if} +
+ + + {#if filteredMedia.length === 0} +
+ +

No {type}s in this project

+
+ {:else} +
+ {#each filteredMedia as media (media.id)} +
(selectedId = media.id)} + onkeydown={(e) => e.key === 'Enter' && (selectedId = media.id)} + > + {media.name} + {#if selectedId === media.id} +
+ +
+ {/if} + +
+ {media.name} +
+
+ {/each} +
+ {/if} +
+ + + + + +
+
diff --git a/studio/ui/src/lib/components/minimessage/advanced-editor.svelte b/studio/ui/src/lib/components/minimessage/advanced-editor.svelte index 2d384ba..450e1ec 100644 --- a/studio/ui/src/lib/components/minimessage/advanced-editor.svelte +++ b/studio/ui/src/lib/components/minimessage/advanced-editor.svelte @@ -14,21 +14,13 @@ const renderer = new MiniMessageRenderer(); - // Generate highlighted HTML that shows tags dimmed but applies actual colors/styles let highlightedHtml = $derived.by(() => { if (!value) return ''; try { - // Use the parsed AST to properly render with all effects including gradients - // We'll interleave the tags (dimmed) with the rendered content - let result = ''; let charIndex = 0; - - // First, let's get the fully rendered HTML to extract styled content const renderedHtml = parseResult.renderedHtml || ''; - - // For simpler approach: parse through manually and detect special tags let pos = 0; let inTag = false; let tagBuffer = ''; @@ -43,7 +35,6 @@ while (pos < value.length) { const char = value[pos]; - // Handle escape sequences if (char === '\\' && pos + 1 < value.length) { const nextChar = value[pos + 1]; if (nextChar === '<' || nextChar === '>') { @@ -57,12 +48,9 @@ } } - // Start of tag if (char === '<' && !inTag) { - // Flush any text buffer with current styles if (textBuffer) { if (inGradient && gradientColors.length > 0) { - // Apply gradient to each character const chars = Array.from(textBuffer); chars.forEach((ch, i) => { const progress = chars.length === 1 ? 0 : i / (chars.length - 1); @@ -70,7 +58,6 @@ result += `${escapeHtml(ch)}`; }); } else if (inRainbow) { - // Apply rainbow to each character const chars = Array.from(textBuffer); chars.forEach((ch, i) => { const hue = (rainbowPhase + i * 15) % 360; @@ -90,14 +77,9 @@ continue; } - // End of tag if (char === '>' && inTag) { tagBuffer += char; - - // Show the tag dimmed result += `${escapeHtml(tagBuffer)}`; - - // Parse the tag to extract styling info const tagMatch = tagBuffer.match(/<\/?([a-zA-Z0-9_#]+)(?::([^>]+))?>/); if (tagMatch) { const isClosing = tagBuffer.startsWith('${escapeHtml(tagBuffer)}`; } @@ -183,7 +159,6 @@ } }); - // Helper to interpolate gradient colors function interpolateColor(colors: string[], position: number): string { if (colors.length === 0) return '#FFFFFF'; if (colors.length === 1) return colors[0]; @@ -211,9 +186,7 @@ return { r, g, b }; } - // Helper to get CSS styles for a tag function getStylesForTag(tagName: string, args?: string): string | null { - // Named colors const namedColors: Record = { black: '#000000', dark_blue: '#0000AA', @@ -235,17 +208,14 @@ white: '#FFFFFF' }; - // Check for named colors if (namedColors[tagName]) { return `color: ${namedColors[tagName]}`; } - // Check for hex color in tag name if (tagName.startsWith('#')) { return `color: ${tagName}`; } - // Verbose color syntax if (tagName === 'color' || tagName === 'c' || tagName === 'colour') { if (args) { const color = args.startsWith('#') ? args : namedColors[args] || args; @@ -253,7 +223,6 @@ } } - // Decorations if (tagName === 'bold' || tagName === 'b') { return 'font-weight: bold'; } @@ -281,7 +250,6 @@ let textareaRef: HTMLTextAreaElement | null = $state(null); - // Sync scroll between highlight layer and textarea function handleScroll() { const highlightLayer = textareaRef?.previousElementSibling as HTMLElement; if (highlightLayer && textareaRef) { @@ -293,12 +261,10 @@
- -