Skip to content

Commit

Permalink
- random
Browse files Browse the repository at this point in the history
  • Loading branch information
ToberoCat committed Sep 17, 2023
1 parent 9854277 commit d31adaa
Show file tree
Hide file tree
Showing 20 changed files with 237 additions and 151 deletions.
2 changes: 1 addition & 1 deletion .run/Build GuiEngine.run.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<option name="goals">
<list>
<option value="install" />
<option value="-Dserver.location=$PROJECT_DIR$/../../JumpAndRun/server/plugins" />
<option value="-Dserver.location=./server/plugins" />
</list>
</option>
<option name="pomFileName" value="pom.xml" />
Expand Down
31 changes: 14 additions & 17 deletions src/main/kotlin/io/github/toberocat/guiengine/GuiEngineApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import io.github.toberocat.guiengine.interpreter.InterpreterManager
import io.github.toberocat.guiengine.utils.FileUtils
import io.github.toberocat.guiengine.utils.VirtualInventory
import io.github.toberocat.guiengine.utils.VirtualPlayer
import io.github.toberocat.guiengine.utils.logger.GuiLogger
import io.github.toberocat.guiengine.view.DefaultGuiViewManager
import io.github.toberocat.guiengine.xml.GuiComponentDeserializer
import io.github.toberocat.guiengine.xml.GuiComponentSerializer
Expand All @@ -32,7 +33,6 @@ import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.logging.Level
import java.util.regex.Pattern
import java.util.stream.Collectors
import kotlin.math.sqrt
Expand Down Expand Up @@ -110,14 +110,14 @@ class GuiEngineApi(
* @throws GuiIORuntimeException If there is an I/O error while loading or validating GUIs.
*/
@Throws(GuiIORuntimeException::class)
fun reload() {
fun reload(logger: GuiLogger) {
availableGuis =
listGuis(guiFolder).stream().map { file: File -> guiIdFromFile(file) }.collect(Collectors.toSet())

val totals = LongArray(availableGuis.size)
val guisCopy = ArrayList(availableGuis)

for (i in guisCopy.indices) totals[i] = validateGui(guisCopy[i])
for (i in guisCopy.indices) totals[i] = validateGui(logger, guisCopy[i])

val avg = Arrays.stream(totals).average().orElse(Double.NaN)
val sumSquaredDifferences =
Expand Down Expand Up @@ -226,24 +226,23 @@ class GuiEngineApi(
}

@Throws(GuiIORuntimeException::class)
private fun validateGui(gui: String): Long {
private fun validateGui(logger: GuiLogger, gui: String): Long {
var total: Long = 0
var delta: Long
val logger = GuiEngineApiPlugin.plugin.logger
try {
logger.log(Level.FINE, "Validating $gui.gui")
logger.debug("Validating $gui.gui")
val virtualPlayer = VirtualPlayer()
var now = System.currentTimeMillis()
val xmlGui = loadXmlGui(getGuiPlaceholders(virtualPlayer), gui)
delta = System.currentTimeMillis() - now
logger.log(Level.FINE, "Took %dms parsing %s", arrayOf<Any>(delta, gui))
logger.debug("Took ${delta}ms parsing $gui")
total += delta
now = System.currentTimeMillis()
val interpreter = plugin.getInterpreterManager().getInterpreter(xmlGui.interpreter)
?: throw GuiIORuntimeException("No interpreter found for " + xmlGui.interpreter)
val context = interpreter.loadContent(this, virtualPlayer, xmlGui)
delta = System.currentTimeMillis() - now
logger.log(Level.FINE, "Took %dms creating a context for %s", arrayOf<Any>(delta, gui))
logger.debug("Took ${delta}ms creating a context for $gui")
total += delta
now = System.currentTimeMillis()
val renderTask = CompletableFuture.supplyAsync<Exception?> {
Expand All @@ -263,30 +262,28 @@ class GuiEngineApi(
val exception = renderTask[1, TimeUnit.SECONDS]
if (null != exception) throw exception
delta = System.currentTimeMillis() - now
logger.log(Level.FINE, "Took %dms rendering to a virtual player %s", arrayOf<Any>(delta, gui))
logger.debug("Took ${delta}ms rendering to a virtual player $gui")
} catch (e: TimeoutException) {
renderTask.cancel(true)
plugin.logger.severe("Stopped rendering gui to virtual " + "player. The render process is very likely to render an infinite long period")
logger.error("Stopped rendering gui to virtual " + "player. The render process is very likely to render an infinite long period")
throw e
} catch (e: StackOverflowError) {
renderTask.cancel(true)
plugin.logger.severe("Stopped rendering gui to virtual " + "player. The render process is very likely to render an infinite long period")
logger.error("Stopped rendering gui to virtual " + "player. The render process is very likely to render an infinite long period")
throw e
}
total += delta
logger.log(
Level.FINE, "§aTook in total %dms§a to get %s displayed to the virtual player", arrayOf<Any>(delta, gui)
)
logger.debug("§aTook in total ${delta}ms§a to get $gui displayed to the virtual player")
} catch (e: InvalidGuiComponentException) {
availableGuis.remove(gui)
plugin.logger.severe(String.format("%s.gui has a invalid component. %s", gui, e.message))
logger.error(String.format("%s.gui has a invalid component. %s", gui, e.message))
} catch (e: InvalidGuiFileException) {
availableGuis.remove(gui)
plugin.logger.severe(e.message)
logger.error(e.message)
} catch (e: Throwable) {
availableGuis.remove(gui)
e.printStackTrace()
plugin.logger.severe("The gui couldn't get rendered to an " + "virtual player. Please take a look at it")
logger.error("The gui couldn't get rendered to an " + "virtual player. Please take a look at it")
throw GuiIORuntimeException(e)
}
return total
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import io.github.toberocat.guiengine.components.provided.paged.PagedComponent
import io.github.toberocat.guiengine.components.provided.paged.PagedComponentBuilder
import io.github.toberocat.guiengine.components.provided.toggle.ToggleItemComponent
import io.github.toberocat.guiengine.components.provided.toggle.ToggleItemComponentBuilder
import io.github.toberocat.guiengine.exception.GuiIORuntimeException
import io.github.toberocat.guiengine.function.FunctionProcessor
import io.github.toberocat.guiengine.function.call.*
import io.github.toberocat.guiengine.function.call.input.InputFunction
Expand All @@ -25,6 +24,7 @@ import io.github.toberocat.guiengine.listeners.ItemClickListener
import io.github.toberocat.guiengine.listeners.PlayerJoinListener
import io.github.toberocat.guiengine.utils.BStatsCollector
import io.github.toberocat.guiengine.utils.Utils
import io.github.toberocat.guiengine.utils.logger.PluginLogger
import io.github.toberocat.guiengine.view.DefaultGuiViewManager
import io.github.toberocat.toberocore.action.ActionCore
import org.bukkit.Bukkit
Expand Down Expand Up @@ -183,9 +183,11 @@ class GuiEngineApiPlugin : JavaPlugin() {
FunctionProcessor.registerFunction(AddComponentsFunction.TYPE, AddComponentsFunction.Deserializer())
FunctionProcessor.registerFunction(EditComponentFunction.TYPE, EditComponentFunction.Deserializer())
FunctionProcessor.registerFunction(RemoveComponentFunction.TYPE, RemoveComponentFunction.Deserializer())
FunctionProcessor.registerFunction(RandomFunction.TYPE, RandomFunction.Deserializer())
FunctionProcessor.registerFunction(ActionFunction.TYPE, ActionFunction.Deserializer())
FunctionProcessor.registerFunction(DelayFunction.TYPE, DelayFunction.Deserializer())
FunctionProcessor.registerFunction(InputFunction.TYPE, InputFunction.Deserializer())

FunctionProcessor.registerComputeFunction(GuiComponentPropertyFunction())
FunctionProcessor.registerComputeFunction(HasPermissionFunction())
FunctionProcessor.registerComputeFunction(HasNotPermissionFunction())
Expand All @@ -212,11 +214,7 @@ class GuiEngineApiPlugin : JavaPlugin() {
*/
private fun addDefaultApi() {
guiApi = GuiEngineApi("default", File(dataFolder, "guis"))
try {
guiApi!!.reload()
} catch (ignored: GuiIORuntimeException) {
// Ignored if an exception occurs while reloading the API.
}
guiApi!!.reload(PluginLogger(logger))
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ class NextPageAction(private val pagedComponent: PagedComponent) : GuiEngineActi
*
* @return The label of this action.
*/
override fun label(): String = pagedComponent.id + ":next"
override fun label() = pagedComponent.id + ":next"

init {
println(pagedComponent.id + ":next")
}

/**
* Performs the action of navigating to the next page of the associated `PagedComponent`
Expand All @@ -31,6 +35,8 @@ class NextPageAction(private val pagedComponent: PagedComponent) : GuiEngineActi
*/
override fun run(player: Player) {
val value = pagedComponent.page + 1
println(value)
println(pagedComponent.availablePages)
if (value >= pagedComponent.availablePages) return
pagedComponent.page = value
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package io.github.toberocat.guiengine.commands

import io.github.toberocat.guiengine.GuiEngineApi
import io.github.toberocat.guiengine.exception.GuiIORuntimeException
import io.github.toberocat.guiengine.exception.GuiNotFoundRuntimeException
import io.github.toberocat.toberocore.command.PlayerSubCommand
import io.github.toberocat.toberocore.command.arguments.Argument
import io.github.toberocat.toberocore.command.exceptions.CommandException
Expand Down Expand Up @@ -49,9 +47,7 @@ open class OpenCommand
return false
}
api.openGui(player, guiId)
} catch (e: GuiNotFoundRuntimeException) {
throw CommandException(e.message, HashMap())
} catch (e: GuiIORuntimeException) {
} catch (e: Exception) {
throw CommandException(e.message, HashMap())
}
return true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package io.github.toberocat.guiengine.commands

import io.github.toberocat.guiengine.GuiEngineApi
import io.github.toberocat.guiengine.GuiEngineApiPlugin.Companion.plugin
import io.github.toberocat.guiengine.exception.GuiIORuntimeException
import io.github.toberocat.guiengine.utils.logger.CommandSenderLogger
import io.github.toberocat.toberocore.command.SubCommand
import io.github.toberocat.toberocore.command.arguments.Argument
import io.github.toberocat.toberocore.command.exceptions.CommandException
Expand All @@ -18,9 +18,10 @@ class ReloadCommand : SubCommand("reload") {
override fun handleCommand(sender: CommandSender, strings: Array<String>): Boolean {
try {
plugin.reloadConfig()
for (api in GuiEngineApi.APIS.values) api.reload()
val logger = CommandSenderLogger(sender)
for (api in GuiEngineApi.APIS.values) api.reload(logger)
sender.sendMessage("§aReloaded GUI APIs.")
} catch (e: GuiIORuntimeException) {
} catch (e: Exception) {
sender.sendMessage(e.message)
}
return true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,4 @@ open class EmbeddedGuiComponentBuilder<B : EmbeddedGuiComponentBuilder<B>> : Abs
}
})
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import io.github.toberocat.guiengine.xml.parsing.ParserContext
import io.github.toberocat.toberocore.action.Action
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import kotlin.math.max
import kotlin.math.min

/**
Expand Down Expand Up @@ -91,8 +92,7 @@ open class PagedComponent(
override fun createEmptyPage() = pageParser?.createEmptyPage()

override fun addComponent(component: GuiComponent) {
if (pages.last().insert(component))
return
if (pages.last().insert(component)) return
createEmptyPage()?.let { pages.add(it) }
}

Expand Down Expand Up @@ -133,8 +133,7 @@ open class PagedComponent(
context?.let { context ->
context.viewer()?.let {
PageParser(
api,
context, it, width(), height(), pattern
api, context, it, width(), height(), pattern
)
}
}
Expand Down Expand Up @@ -165,61 +164,53 @@ class PageParser(
private val pattern: IntArray
) {
fun parse(node: ParserContext): MutableList<PatternPage> {
val pages = mutableListOf(createEmptyPage())
parseNode(node).forEach {
if (pages.last().insert(it))
return@forEach
pages.add(createEmptyPage())
val pages = mutableListOf<PatternPage>()
node.fieldList("page").optional(emptyList()).forEach {
val (page, preferredPosition) = parsePage(it)
pages.add(preferredPosition ?: (max(pages.size - 1, 0)), page)
}
if (pages.isEmpty()) pages.add(createEmptyPage())


node.fieldList("page")
.optional(emptyList())
.forEach {
val (page, preferredPosition) = parsePage(it)
pages.add(preferredPosition ?: (pages.size - 1), page)
}
parseNode(node).forEach { (_, component) ->
if (pages.last().insert(component)) return@forEach
pages.add(createEmptyPage())
}
return pages
//embedded = this.pages[showedPage]
}

fun createEmptyPage(): PatternPage = PatternPage(api, pattern, context
.interpreter()
.createContext(
api, viewer, XmlGui(
context.interpreter().interpreterId, emptyArray(), mapOf(
"width" to IntNode(width), "height" to IntNode(height)
)
fun createEmptyPage(): PatternPage = PatternPage(api, pattern, context.interpreter().createContext(
api, viewer, XmlGui(
context.interpreter().interpreterId, emptyArray(), mapOf(
"width" to IntNode(width), "height" to IntNode(height)
)
).also {
it.setInventory(context.inventory())
it.setViewer(viewer)
it.domEvents.onRender.addAll(context.domEvents.onRender)
it.computableFunctionProcessor.copy(context.computableFunctionProcessor)
})

private fun parseNode(node: ParserContext): List<GuiComponent> {
)
).also {
it.setInventory(context.inventory())
it.setViewer(viewer)
it.domEvents.onRender.addAll(context.domEvents.onRender)
it.computableFunctionProcessor.copy(context.computableFunctionProcessor)
})

private fun parseNode(node: ParserContext): List<Pair<Boolean, GuiComponent>> {
val interpreter = context.interpreter()
return node.fieldList("component")
.optional(ArrayList())
.map {
return@map interpreter.createComponent(
interpreter.xmlComponent(it.node, api),
api,
context
)
}
return node.fieldList("component").optional(ArrayList()).map {
return@map (it.node("x").present() || it.node("y").present()) to interpreter.createComponent(
interpreter.xmlComponent(it.node, api), api, context
)
}
}

private fun parsePage(node: ParserContext): Pair<PatternPage, Int?> =
createEmptyPage().also { page -> parseNode(node).forEach { page.insert(it) } } to
node.int("position").nullable(null)
private fun parsePage(node: ParserContext): Pair<PatternPage, Int?> = createEmptyPage().also { page ->
parseNode(node).forEach { (positioned, component) ->
if (positioned) page.pageContext.add(component) else page.insert(
component
)
}
} to node.int("position").nullable(null)
}

class PatternPage(
val api: GuiEngineApi,
val pattern: IntArray,
override val pageContext: GuiContext
val api: GuiEngineApi, private val pattern: IntArray, override val pageContext: GuiContext
) : Page {
private var current: Int = 0
override fun insert(component: GuiComponent): Boolean {
Expand All @@ -232,4 +223,10 @@ class PatternPage(
pageContext.add(component)
return true
}

override fun toString(): String {
return "PatternPage(pageContext=$pageContext, current=$current)"
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,5 @@ package io.github.toberocat.guiengine.exception
*/
class MissingRequiredParamException(id: String, clazz: Class<*>, parameterName: String) :
InvalidGuiComponentException(
String.format(
"Element %s, being generated with %s is missing the required argument '%s'",
id,
clazz.getSimpleName(),
parameterName
)
"Element $id, being generated with ${clazz.simpleName} is missing the required argument $parameterName"
)
Loading

0 comments on commit d31adaa

Please sign in to comment.