-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(4.13): Implement callback click event
- Loading branch information
Showing
8 changed files
with
329 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
158 changes: 158 additions & 0 deletions
158
src/main/java/net/kyori/adventure/platform/fabric/impl/ClickCallbackRegistry.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,158 @@ | ||
/* | ||
* This file is part of adventure-platform-fabric, licensed under the MIT License. | ||
* | ||
* Copyright (c) 2023 KyoriPowered | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in all | ||
* copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
* SOFTWARE. | ||
*/ | ||
package net.kyori.adventure.platform.fabric.impl; | ||
|
||
import com.google.common.cache.Cache; | ||
import com.google.common.cache.CacheBuilder; | ||
import com.google.common.cache.RemovalListener; | ||
import com.mojang.brigadier.Command; | ||
import com.mojang.brigadier.CommandDispatcher; | ||
import com.mojang.logging.LogUtils; | ||
import java.time.Instant; | ||
import java.util.HashSet; | ||
import java.util.Set; | ||
import java.util.UUID; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
import net.kyori.adventure.audience.Audience; | ||
import net.kyori.adventure.text.Component; | ||
import net.kyori.adventure.text.event.ClickCallback; | ||
import net.kyori.adventure.text.format.NamedTextColor; | ||
import net.minecraft.commands.CommandSourceStack; | ||
import net.minecraft.commands.Commands; | ||
import net.minecraft.commands.arguments.UuidArgument; | ||
import org.jetbrains.annotations.Nullable; | ||
import org.slf4j.Logger; | ||
|
||
public final class ClickCallbackRegistry { | ||
private static final Logger LOGGER = LogUtils.getLogger(); | ||
|
||
public static final ClickCallbackRegistry INSTANCE = new ClickCallbackRegistry(); | ||
|
||
public static final int CLEAN_UP_RATE = 30 /* seconds */; | ||
|
||
private static final String UUID_ARG = "uuid"; | ||
private static final String COMMAND_NAME = "adventure_callback"; | ||
private static final Component FAILURE_MESSAGE = Component.text("No callback with that ID could be found! You may have used it too many times, or it may have expired.", NamedTextColor.RED); | ||
|
||
private final Cache<UUID, CallbackRegistration> registrations = CacheBuilder.newBuilder() | ||
.expireAfterWrite(24, TimeUnit.HOURS) | ||
.maximumSize(1024) // to avoid unbounded growth | ||
.removalListener((RemovalListener<UUID, CallbackRegistration>) notification -> LOGGER.debug("Removing callback {} from cache for reason {}", notification.getKey(), notification.getCause())) | ||
.build(); | ||
|
||
private ClickCallbackRegistry() { | ||
} | ||
|
||
/** | ||
* Register a callback, returning the command to be attached to a click event. | ||
* | ||
* @param callback the callback to register | ||
* @param options options | ||
* @return a new callback handler command | ||
* @since 5.7.0 | ||
*/ | ||
public String register(final ClickCallback<Audience> callback, final ClickCallback.Options options) { | ||
final UUID id = UUID.randomUUID(); | ||
final CallbackRegistration reg = new CallbackRegistration( | ||
options, | ||
callback, | ||
Instant.now().plus(options.lifetime()), | ||
new AtomicInteger() | ||
); | ||
|
||
this.registrations.put(id, reg); | ||
|
||
return "/" + COMMAND_NAME + " " + id; | ||
} | ||
|
||
public void registerToDispatcher(final CommandDispatcher<CommandSourceStack> dispatcher) { | ||
dispatcher.register(Commands.literal(COMMAND_NAME) | ||
.requires(HiddenRequirement.alwaysAllowed()) // hide from client tab completion | ||
.then(Commands.argument(UUID_ARG, UuidArgument.uuid()) | ||
.executes(ctx -> { | ||
final UUID callbackId = UuidArgument.getUuid(ctx, UUID_ARG); | ||
final @Nullable CallbackRegistration reg = this.registrations.getIfPresent(callbackId); | ||
|
||
if (reg == null) { | ||
ctx.getSource().sendFailure(FAILURE_MESSAGE); | ||
return 0; // unsuccessful | ||
} | ||
|
||
// check use count | ||
boolean expire = false; | ||
boolean allowUse = true; | ||
final int allowedUses = reg.options.uses(); | ||
if (allowedUses != ClickCallback.UNLIMITED_USES) { | ||
final int useCount = reg.useCount().incrementAndGet(); | ||
if (useCount >= allowedUses) { | ||
expire = true; | ||
allowUse = !(useCount > allowedUses); | ||
// allowUse: determine | ||
} | ||
} | ||
|
||
// check duration expiry | ||
final Instant now = Instant.now(); | ||
if (now.isAfter(reg.expiryTime())) { | ||
expire = true; | ||
allowUse = false; | ||
} | ||
|
||
if (expire) { | ||
this.registrations.invalidate(callbackId); | ||
} | ||
if (allowUse) { | ||
reg.callback().accept(ctx.getSource()); // pass the CommandSourceStack to the callback action | ||
} else { | ||
ctx.getSource().sendFailure(FAILURE_MESSAGE); | ||
} | ||
return Command.SINGLE_SUCCESS; | ||
}))); | ||
} | ||
|
||
/** | ||
* Perform a periodic cleanup of callbacks. | ||
*/ | ||
public void cleanUp() { | ||
final Instant now = Instant.now(); | ||
|
||
final Set<UUID> uuidsToClean = new HashSet<>(); | ||
for (final var entry : this.registrations.asMap().entrySet()) { | ||
final var reg = entry.getValue(); | ||
final int allowedUses = reg.options().uses(); | ||
if (allowedUses != ClickCallback.UNLIMITED_USES && reg.useCount().get() >= allowedUses) { | ||
uuidsToClean.add(entry.getKey()); | ||
} else if (now.isAfter(reg.expiryTime())) { | ||
uuidsToClean.add(entry.getKey()); | ||
} | ||
} | ||
|
||
for (final UUID id : uuidsToClean) { | ||
this.registrations.invalidate(id); | ||
} | ||
} | ||
|
||
private record CallbackRegistration(ClickCallback.Options options, ClickCallback<Audience> callback, Instant expiryTime, AtomicInteger useCount) {} | ||
} |
66 changes: 66 additions & 0 deletions
66
src/main/java/net/kyori/adventure/platform/fabric/impl/HiddenRequirement.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
/* | ||
* This file is part of adventure-platform-fabric, licensed under the MIT License. | ||
* | ||
* Copyright (c) 2023 KyoriPowered | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in all | ||
* copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
* SOFTWARE. | ||
*/ | ||
package net.kyori.adventure.platform.fabric.impl; | ||
|
||
import java.util.Objects; | ||
import java.util.function.Predicate; | ||
import org.jetbrains.annotations.NotNull; | ||
|
||
/** | ||
* A requirement for commands that prevents them from being synced to the client. | ||
* | ||
* <p>Not yet implemented for client commands.</p> | ||
* | ||
* @param base the base predicate | ||
* @param <V> value type | ||
*/ | ||
public record HiddenRequirement<V>(Predicate<V> base) implements Predicate<V> { | ||
public static <T> HiddenRequirement<T> alwaysAllowed() { | ||
return new HiddenRequirement<>(t -> true); | ||
} | ||
|
||
@Override | ||
public boolean test(final V v) { | ||
return this.base.test(v); | ||
} | ||
|
||
@Override | ||
public @NotNull Predicate<V> and(final @NotNull Predicate<? super V> other) { | ||
return new HiddenRequirement<>(this.base.and(unwrap(Objects.requireNonNull(other, "other")))); | ||
} | ||
|
||
@Override | ||
public @NotNull Predicate<V> negate() { | ||
return new HiddenRequirement<>(this.base.negate()); | ||
} | ||
|
||
@Override | ||
public @NotNull Predicate<V> or(final @NotNull Predicate<? super V> other) { | ||
return new HiddenRequirement<>(this.base.or(unwrap(Objects.requireNonNull(other, "other")))); | ||
} | ||
|
||
private static <T> @NotNull Predicate<T> unwrap(final @NotNull Predicate<T> pred) { | ||
return pred instanceof HiddenRequirement<T> req ? req.base : pred; | ||
} | ||
} |
39 changes: 39 additions & 0 deletions
39
...ava/net/kyori/adventure/platform/fabric/impl/service/FabricClickCallbackProviderImpl.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
/* | ||
* This file is part of adventure-platform-fabric, licensed under the MIT License. | ||
* | ||
* Copyright (c) 2023 KyoriPowered | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in all | ||
* copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
* SOFTWARE. | ||
*/ | ||
package net.kyori.adventure.platform.fabric.impl.service; | ||
|
||
import com.google.auto.service.AutoService; | ||
import net.kyori.adventure.audience.Audience; | ||
import net.kyori.adventure.platform.fabric.impl.ClickCallbackRegistry; | ||
import net.kyori.adventure.text.event.ClickCallback; | ||
import net.kyori.adventure.text.event.ClickEvent; | ||
import org.jetbrains.annotations.NotNull; | ||
|
||
@AutoService(ClickCallback.Provider.class) | ||
public final class FabricClickCallbackProviderImpl implements ClickCallback.Provider { | ||
@Override | ||
public @NotNull ClickEvent create(final @NotNull ClickCallback<Audience> callback, final ClickCallback.@NotNull Options options) { | ||
return ClickEvent.runCommand(ClickCallbackRegistry.INSTANCE.register(callback, options)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.