Skip to content

Commit

Permalink
Fixed argument processing + placeholders api wrapper
Browse files Browse the repository at this point in the history
TODO still need to fix options/flags and finally suggestion invocations
  • Loading branch information
Matt-MX committed Jul 7, 2024
1 parent 53f9e85 commit 382da33
Show file tree
Hide file tree
Showing 16 changed files with 143 additions and 132 deletions.
2 changes: 1 addition & 1 deletion api/.gradle/caches/paperweight/taskCache/reobfJar.log
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Command: C:\Program Files\Java\jdk-17\bin\java.exe -Xmx1G -classpath C:\Users\Mangr\.gradle\caches\modules-2\files-2.1\net.fabricmc\tiny-remapper\0.10.1\c293b2384ae12af74f407fa3aaa553bba4ac6763\tiny-remapper-0.10.1-fat.jar net.fabricmc.tinyremapper.Main D:\PC\Projects\KtBukkitGui\api\build\libs\ktgui-2.4.1-dev-all.jar D:\PC\Projects\KtBukkitGui\api\build\libs\api-2.4.1.jar C:\Users\Mangr\.gradle\caches\paperweight-userdev\ff775525efc29c3503a07d1006e63e5695a742b7505cf63e157d49d32419c69f\module\io.papermc.paper\dev-bundle\1.20.4-R0.1-SNAPSHOT\paperweight\setupCache\extractDevBundle.dir\data\mojang+yarn-spigot-reobf.tiny mojang+yarn spigot C:\Users\Mangr\.gradle\caches\paperweight-userdev\ff775525efc29c3503a07d1006e63e5695a742b7505cf63e157d49d32419c69f\module\io.papermc.paper\dev-bundle\1.20.4-R0.1-SNAPSHOT\paperweight\setupCache\applyMojangMappedPaperclipPatch.jar --threads=1
Finished after 2525.50 ms.
Finished after 2839.29 ms.
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ class ChainCommandBuilder(val name: String) {
subcommands.addAll(command)
}

inline infix fun <reified S : CommandSender> runs(noinline block: RunnableCommandContext<S>.() -> Unit) =
build().runs(block)

fun build() = build(DeclarativeCommandBuilder(name))

fun <T : DeclarativeCommandBuilder> build(existing: T) = existing.apply {
Expand All @@ -31,6 +28,9 @@ class ChainCommandBuilder(val name: String) {
}
}

inline infix fun <reified S : CommandSender> ChainCommandBuilder.runs(noinline block: RunnableCommandContext<S>.() -> Unit) =
build().runs(block)

inline operator fun ChainCommandBuilder.invoke(block: DeclarativeCommandBuilder.() -> Unit) =
build().apply(block)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import org.bukkit.permissions.PermissionDefault
import java.time.Duration
import java.util.*
import java.util.function.Consumer
import kotlin.math.exp

open class DeclarativeCommandBuilder(
val name: String
Expand Down Expand Up @@ -152,6 +151,12 @@ open class DeclarativeCommandBuilder(
inline operator fun ChainCommandBuilder.invoke(block: DeclarativeSubCommandBuilder.() -> Unit) =
subcommand(this, block)

inline infix fun <reified S : CommandSender> ChainCommandBuilder.runs(noinline block: RunnableCommandContext<S>.() -> Unit) =
build().runs(block).let {
this@DeclarativeCommandBuilder.subcommands += it
it
}

inline operator fun String.invoke(block: DeclarativeSubCommandBuilder.() -> Unit) =
fromString(this).let {
val subCommand = DeclarativeSubCommandBuilder(it.name)
Expand Down Expand Up @@ -334,15 +339,19 @@ open class DeclarativeCommandBuilder(

val processorClone = argumentProcessor.clone()
val result = arg.consumer.consume(processorClone)
val actualValue = arg.getValueOfString(this, context, result.stringValue)
val actualValue = arg.getValueOfString(
this,
context,
result.args
)

if (actualValue != null || arg.isOptional()) {
argumentValues[arg.name()] = arg.createContext(result.stringValue, actualValue)
argumentValues[arg.name()] = arg.createContext(result.argsAsStringValue, actualValue)
argumentProcessor.pointer = processorClone.pointer
argumentProcessor.optionsAndFlagsValues = processorClone.optionsAndFlagsValues
} else {
val invalidArgumentContext =
InvalidArgContext(context.sender, context.alias, context.rawArgs, arg, result.stringValue)
InvalidArgContext(context.sender, context.alias, context.rawArgs, arg, result.argsAsStringValue)

if (arg.invokeInvalid(invalidArgumentContext)) {
return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,9 @@ open class Argument<T : Any>(
open fun getValueOfString(
cmd: DeclarativeCommandBuilder?,
context: BaseCommandContext<*>?,
split: List<String>
split: List<String>?
): T? {
return getValueOfString(cmd, context, split.joinToString(" "))
return getValueOfString(cmd, context, split?.joinToString(" "))
}

open fun getValueOfString(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,36 @@ fun interface ArgumentConsumer {
fun consume(processor: ArgumentProcessor): Result

class Result(
val stringValue: String?,
val consumed: List<Int>
val args: List<String>?
) {
fun isEmpty() = stringValue == null
constructor(single: String?) : this(single?.let { listOf(it) })

override fun toString() = "Result('$stringValue', [${consumed.joinToString(", ")}])"
val argsAsStringValue = args?.joinToString(" ")

fun isEmpty() = args.isNullOrEmpty()

override fun toString() = "Result($args)"

companion object {
private val EMPTY = Result(null, emptyList())
private val EMPTY = Result(emptyList())
fun empty() = EMPTY
}

}

companion object {
private val NONE = ArgumentConsumer { _ -> Result.empty() }
private val SINGLE = ArgumentConsumer { processor -> Result(processor.next(), listOf(processor.pointer)) }
private val SINGLE = ArgumentConsumer { processor -> ArgumentConsumer.Result(processor.next()) }

@JvmStatic
fun none() = NONE
@JvmStatic
fun single() = SINGLE

@JvmStatic
infix fun untilFalse(predicate: (ArgumentProcessor, String) -> Boolean) = ArgumentConsumer { processor ->
infix fun untilFalse(predicate: (ArgumentProcessor, List<String>) -> Boolean) = ArgumentConsumer { processor ->
var current: String? = ""
val startIndex = processor.pointer + 1
var fullString = ""
val consumed = arrayListOf<String>()

while (current != null) {
current = processor.next()
Expand All @@ -41,40 +43,37 @@ fun interface ArgumentConsumer {
return@ArgumentConsumer Result.empty()
}

fullString += "$current "
fullString = fullString.trim()
consumed += current

if (!predicate(processor, fullString)) {
return@ArgumentConsumer Result(fullString, (startIndex..processor.pointer).toList())
if (!predicate(processor, consumed)) {
return@ArgumentConsumer Result(consumed)
}
}
Result.empty()
}

@JvmStatic
infix fun until(predicate: (ArgumentProcessor, String) -> Boolean) = untilFalse { p, s -> !predicate(p, s) }
infix fun until(predicate: (ArgumentProcessor, List<String>) -> Boolean) = untilFalse { p, s -> !predicate(p, s) }

@JvmStatic
infix fun untilFalsePartial(predicate: (ArgumentProcessor, String) -> Boolean) = ArgumentConsumer { processor ->
var current: String? = null
val startIndex = processor.pointer + 1
var fullString = ""
val consumed = arrayListOf<String>()

while (current != null) {
current = processor.next()

if (current == null) {
return@ArgumentConsumer Result(fullString, (startIndex..processor.pointer).toList())
return@ArgumentConsumer Result(consumed)
}

fullString += "$current "
fullString = fullString.trim()
consumed += current

if (!predicate(processor, current)) {
return@ArgumentConsumer Result(fullString, (startIndex..processor.pointer).toList())
return@ArgumentConsumer Result(consumed)
}
}
Result(fullString, (startIndex..processor.pointer).toList())
Result(consumed)
}

@JvmStatic
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class FlagArgument(
override fun getValueOfString(
cmd: DeclarativeCommandBuilder?,
context: BaseCommandContext<*>?,
split: List<String>
split: List<String>?
): Boolean {
// todo context should contain included flags/options
return false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class MultiChoiceArgument<T : Any>(
init {
this.consumes(
ArgumentConsumer.until { argumentProcessor, s ->
choices().containsKey(s)
choices().containsKey(s.joinToString(" "))
}
)
suggests { choices().keys.toList() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ class RelativeCoordinateArgument(
override fun getValueOfString(
cmd: DeclarativeCommandBuilder?,
context: BaseCommandContext<*>?,
split: List<String>
split: List<String>?
): Location? {
if (split.size != 3) return null
if (split?.size != 3) return null

val entity = (context?.sender as Entity?)
?: return null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ fun <T : Any> multiChoiceArgument(choices: HashMap<String, T>) =
fun <T : Any> multiChoiceArgument(choiceSupplier: () -> HashMap<String, T>) =
delegateArgument(MultiChoiceArgument(DELEGATED_ARG_NAME) { choiceSupplier() })

fun multiChoiceStringArgument(choiceSupplier: List<String>) =
delegateArgument(MultiChoiceArgument(DELEGATED_ARG_NAME) { choiceSupplier.associateWithTo(HashMap()) { it } })

fun multiChoiceStringArgument(vararg choiceSupplier: String) =
delegateArgument(MultiChoiceArgument(DELEGATED_ARG_NAME) { choiceSupplier.associateWithTo(HashMap()) { it } })

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,23 +83,23 @@ class PlaceholderExpansionWrapper(
for (expArg in placeholder.match.arguments) {
if (invalid) continue

val stringValue = expArg.consume(argumentParser)
val consumeResult = expArg.consume(argumentParser)

if (expArg.isRequired() && stringValue.isEmpty()) {
if (expArg.isRequired() && consumeResult.isEmpty()) {
invalid = true
if (isDebug) {
owner.logger.warning(
"Placeholder(${
identifier
}) Failed parsing for arg $expArg in placeholder $name - $stringValue"
}) Failed parsing for arg $expArg in placeholder $name - $consumeResult"
)
}
continue
} else {
args[expArg.name()] = expArg.createContext(
emptyCommand,
baseContext,
stringValue.stringValue?.split("_", " ") ?: emptyList()
consumeResult.args ?: emptyList()
)
}
}
Expand Down
4 changes: 3 additions & 1 deletion api/src/main/kotlin/com/mattmx/ktgui/utils/color.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ fun Component.json() = gsonSerializer.serialize(this)
fun Component.legacy() = legacySerializer.serialize(this)
fun String.jsonToComponent() = gsonSerializer.deserialize(this)
fun JsonElement.component() = gsonSerializer.deserializeFromTree(this)
fun String.component() = serializer.deserialize(this)
fun String.component() = component(null)
infix fun String.component(player: OfflinePlayer?) = serializer.deserialize(this.placeholders(null))
val String.component: Component
get() = component()
fun String.legacyToComponent() = legacySerializer.deserialize(this)
Expand All @@ -53,6 +54,7 @@ operator fun Component.plus(component: Component) = this.append(component)
infix fun Component.clickEvent(event: ClickEvent) = clickEvent(event)
infix fun <T> Component.hoverEvent(event: HoverEvent<T>) = hoverEvent(event)
operator fun String.not() = component()
operator fun String.minus(player: OfflinePlayer?) = component(player)

val String.translatable
get() = Component.translatable(this)
2 changes: 1 addition & 1 deletion plugin/.gradle/caches/paperweight/taskCache/reobfJar.log
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
Command: C:\Program Files\Java\jdk-17\bin\java.exe -Xmx1G -classpath C:\Users\Mangr\.gradle\caches\modules-2\files-2.1\net.fabricmc\tiny-remapper\0.10.1\c293b2384ae12af74f407fa3aaa553bba4ac6763\tiny-remapper-0.10.1-fat.jar net.fabricmc.tinyremapper.Main D:\PC\Projects\KtBukkitGui\plugin\build\libs\ktgui-plugin-2.4.1-dev-all.jar D:\PC\Projects\KtBukkitGui\plugin\build\libs\plugin-unspecified.jar C:\Users\Mangr\.gradle\caches\paperweight-userdev\ff775525efc29c3503a07d1006e63e5695a742b7505cf63e157d49d32419c69f\module\io.papermc.paper\dev-bundle\1.20.4-R0.1-SNAPSHOT\paperweight\setupCache\extractDevBundle.dir\data\mojang+yarn-spigot-reobf.tiny mojang+yarn spigot C:\Users\Mangr\.gradle\caches\paperweight-userdev\ff775525efc29c3503a07d1006e63e5695a742b7505cf63e157d49d32419c69f\module\io.papermc.paper\dev-bundle\1.20.4-R0.1-SNAPSHOT\paperweight\setupCache\applyMojangMappedPaperclipPatch.jar --threads=1
Finished after 1601.92 ms.
Finished after 1655.39 ms.
92 changes: 6 additions & 86 deletions plugin/src/main/kotlin/com/mattmx/ktgui/KotlinGui.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import com.mattmx.ktgui.commands.declarative.arg.suggestsTopLevel
import com.mattmx.ktgui.commands.declarative.arg.withArgs
import com.mattmx.ktgui.commands.declarative.div
import com.mattmx.ktgui.commands.declarative.invoke
import com.mattmx.ktgui.commands.declarative.runs
import com.mattmx.ktgui.commands.rawCommand
import com.mattmx.ktgui.commands.usage.CommandUsageOptions
import com.mattmx.ktgui.components.screen.GuiScreen
import com.mattmx.ktgui.cooldown.ActionCoolDown
import com.mattmx.ktgui.designer.DesignerManager
import com.mattmx.ktgui.designer.GuiDesigner
import com.mattmx.ktgui.examples.*
import com.mattmx.ktgui.papi.placeholder
Expand Down Expand Up @@ -108,7 +110,8 @@ class KotlinGui : JavaPlugin() {
}

placeholder("font-ph" / fontType / stringToConvert) {
val string = PlaceholderAPI.setPlaceholders(requestedBy, stringToConvert())
val formatted = "%${stringToConvert().replace(" ", "_")}%"
val string = PlaceholderAPI.setPlaceholders(requestedBy, formatted)
fontType()(string)
}

Expand Down Expand Up @@ -138,7 +141,6 @@ class KotlinGui : JavaPlugin() {
} permission "ktgui.command.font" register this

sync {
val cachedDesigners = hashMapOf<String, GuiDesigner>()
rawCommand("ktgui") {
permission = "ktgui.command"
playerOnly = true
Expand Down Expand Up @@ -190,90 +192,6 @@ class KotlinGui : JavaPlugin() {
}
}.register(false)

"designer" {
buildAutomaticPermissions("ktgui.command")
withDefaultUsageSubCommand(defaultUsageOptions)

val typeOrRowArgMessage = !"&cYou must provide an InventoryType or an amount of rows."
val typeOrRowArg by argument<String>("type_or_row")
val id by argument<String>("unique_id")

typeOrRowArg suggestsTopLevel { InventoryType.values().map { it.name.lowercase() } }
typeOrRowArg invalid { reply(typeOrRowArgMessage) }
id missing { reply(!"&cMissing argument 'id'. Need an identifier for the designer UI.") }

val create = ("create" / typeOrRowArg / id) {
runs<Player> {
val type = runCatching {
InventoryType.valueOf(typeOrRowArg().uppercase())
}.getOrNull()
val rows = typeOrRowArg().toIntOrNull()

if (type == null && rows == null) {
reply(typeOrRowArgMessage)
return@runs
}

if (cachedDesigners.containsKey(id())) {
return@runs reply("&cThere is already a designer by that name.")
}

val designer =
cachedDesigners.getOrPut(id()) { GuiDesigner(id(), type = type, rows = rows ?: 1) }
designer.open(sender)
}
}

("open" / id) {

id suggests { cachedDesigners.keys.toList() }

runs<Player> {
val designer = cachedDesigners[id()]
?: return@runs reply(
!"&cInvalid id, create one using &7/&fdesigner ${
create.getUsage(
defaultUsageOptions,
false
)
}"
)
designer.open(sender)
}
}

val newTitle by argument<String>("string")
("set-title" / id / newTitle) {

id suggests { cachedDesigners.keys.toList() }

runs<CommandSender> {
val designer = cachedDesigners[id()]
?: return@runs reply(
!"&cInvalid id, create one using &7/&fdesigner ${
create.getUsage(
defaultUsageOptions,
false
)
}"
)
designer.exportTitle = newTitle()
reply(!"&aSet title of ${id()} to ${newTitle()}")
}
}

subcommand("export" / id) {

id suggests { cachedDesigners.keys.toList() }

runs<CommandSender> {
val designer = cachedDesigners.getOrPut(id()) { GuiDesigner(id()) }
val file = designer.save(this@KotlinGui)
reply(!"&aSaved to /plugins/KtGUI/designer/${file.name}")
}
}
} register this@KotlinGui

"ktgui-cmd-examples" {
buildAutomaticPermissions("ktgui.examples.command")

Expand Down Expand Up @@ -464,6 +382,8 @@ class KotlinGui : JavaPlugin() {
reply(!getUsage(defaultUsageOptions))
}
} register this@KotlinGui

DesignerManager(this@KotlinGui)
}
}

Expand Down
Loading

0 comments on commit 382da33

Please sign in to comment.