From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Riley Park Date: Fri, 29 Jan 2021 17:54:03 +0100 Subject: [PATCH] Adventure Co-authored-by: zml Co-authored-by: Jake Potrebic diff --git a/src/main/java/com/destroystokyo/paper/PaperConfig.java b/src/main/java/com/destroystokyo/paper/PaperConfig.java index 1d03a79e9010bc514b72a81ba0ad4a62aeff1bb7..429b74474ced04d8dd8f038b8590b8dfe178bf4d 100644 --- a/src/main/java/com/destroystokyo/paper/PaperConfig.java +++ b/src/main/java/com/destroystokyo/paper/PaperConfig.java @@ -217,4 +217,9 @@ public class PaperConfig { " - Length: " + timeSummary(Timings.getHistoryLength() / 20) + " - Server Name: " + timingsServerName); } + + public static boolean useDisplayNameInQuit = false; + private static void useDisplayNameInQuit() { + useDisplayNameInQuit = getBoolean("use-display-name-in-quit-message", useDisplayNameInQuit); + } } diff --git a/src/main/java/io/papermc/paper/adventure/AdventureComponent.java b/src/main/java/io/papermc/paper/adventure/AdventureComponent.java new file mode 100644 index 0000000000000000000000000000000000000000..4b4cec054ad0146773b722c7e3708f988aeeb76d --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/AdventureComponent.java @@ -0,0 +1,76 @@ +package io.papermc.paper.adventure; + +import com.google.gson.JsonElement; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import java.lang.reflect.Type; +import java.util.List; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; +import org.checkerframework.checker.nullness.qual.Nullable; + +public final class AdventureComponent implements net.minecraft.network.chat.Component { + final Component wrapped; + private @MonotonicNonNull net.minecraft.network.chat.Component converted; + + public AdventureComponent(final Component wrapped) { + this.wrapped = wrapped; + } + + public net.minecraft.network.chat.Component deepConverted() { + net.minecraft.network.chat.Component converted = this.converted; + if (converted == null) { + converted = PaperAdventure.WRAPPER_AWARE_SERIALIZER.serialize(this.wrapped); + this.converted = converted; + } + return converted; + } + + public @Nullable net.minecraft.network.chat.Component deepConvertedIfPresent() { + return this.converted; + } + + @Override + public Style getStyle() { + return this.deepConverted().getStyle(); + } + + @Override + public String getContents() { + if (this.wrapped instanceof TextComponent) { + return ((TextComponent) this.wrapped).content(); + } else { + return this.deepConverted().getContents(); + } + } + + @Override + public String getString() { + return PaperAdventure.PLAIN.serialize(this.wrapped); + } + + @Override + public List getSiblings() { + return this.deepConverted().getSiblings(); + } + + @Override + public MutableComponent plainCopy() { + return this.deepConverted().plainCopy(); + } + + @Override + public MutableComponent copy() { + return this.deepConverted().copy(); + } + + public static class Serializer implements JsonSerializer { + @Override + public JsonElement serialize(final AdventureComponent src, final Type type, final JsonSerializationContext context) { + return PaperAdventure.GSON.serializer().toJsonTree(src.wrapped, Component.class); + } + } +} diff --git a/src/main/java/io/papermc/paper/adventure/ChatProcessor.java b/src/main/java/io/papermc/paper/adventure/ChatProcessor.java new file mode 100644 index 0000000000000000000000000000000000000000..a29b6aaafd529e56a83dd96c32211f21e4aad348 --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/ChatProcessor.java @@ -0,0 +1,214 @@ +package io.papermc.paper.adventure; + +import io.papermc.paper.chat.ChatRenderer; +import io.papermc.paper.event.player.AbstractChatEvent; +import io.papermc.paper.event.player.AsyncChatEvent; +import io.papermc.paper.event.player.ChatEvent; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.function.Consumer; +import java.util.regex.Pattern; + +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.audience.MessageType; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextReplacementConfig; +import net.kyori.adventure.text.event.ClickEvent; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.craftbukkit.util.LazyPlayerSet; +import org.bukkit.craftbukkit.util.Waitable; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerChatEvent; + +public final class ChatProcessor { + // <-- copied from adventure-text-serializer-legacy + private static final Pattern DEFAULT_URL_PATTERN = Pattern.compile("(?:(https?)://)?([-\\w_.]+\\.\\w{2,})(/\\S*)?"); + private static final Pattern URL_SCHEME_PATTERN = Pattern.compile("^[a-z][a-z0-9+\\-.]*:"); + private static final TextReplacementConfig URL_REPLACEMENT_CONFIG = TextReplacementConfig.builder() + .match(DEFAULT_URL_PATTERN) + .replacement(url -> { + String clickUrl = url.content(); + if (!URL_SCHEME_PATTERN.matcher(clickUrl).find()) { + clickUrl = "http://" + clickUrl; + } + return url.clickEvent(ClickEvent.openUrl(clickUrl)); + }) + .build(); + // copied from adventure-text-serializer-legacy --> + final MinecraftServer server; + final ServerPlayer player; + final String message; + final boolean async; + final Component originalMessage; + + public ChatProcessor(final MinecraftServer server, final ServerPlayer player, final String message, final boolean async) { + this.server = server; + this.player = player; + this.message = message; + this.async = async; + this.originalMessage = Component.text(message); + } + + @SuppressWarnings({"CodeBlock2Expr", "deprecated"}) + public void process() { + this.processingLegacyFirst( + // continuing from AsyncPlayerChatEvent (without PlayerChatEvent) + event -> { + this.processModern( + legacyRenderer(event.getFormat()), + event.getRecipients(), + PaperAdventure.LEGACY_SECTION_UXRC.deserialize(event.getMessage()), + event.isCancelled() + ); + }, + // continuing from AsyncPlayerChatEvent and PlayerChatEvent + event -> { + this.processModern( + legacyRenderer(event.getFormat()), + event.getRecipients(), + PaperAdventure.LEGACY_SECTION_UXRC.deserialize(event.getMessage()), + event.isCancelled() + ); + }, + // no legacy events called, all nice and fresh! + () -> { + this.processModern( + ChatRenderer.defaultRenderer(), + new LazyPlayerSet(this.server), + Component.text(this.message).replaceText(URL_REPLACEMENT_CONFIG), + false + ); + } + ); + } + + @SuppressWarnings("deprecation") + private void processingLegacyFirst( + final Consumer continueAfterAsync, + final Consumer continueAfterAsyncAndSync, + final Runnable modernOnly + ) { + final boolean listenersOnAsyncEvent = anyListeners(AsyncPlayerChatEvent.getHandlerList()); + final boolean listenersOnSyncEvent = anyListeners(PlayerChatEvent.getHandlerList()); + if (listenersOnAsyncEvent || listenersOnSyncEvent) { + final CraftPlayer player = this.player.getBukkitEntity(); + final AsyncPlayerChatEvent ae = new AsyncPlayerChatEvent(this.async, player, this.message, new LazyPlayerSet(this.server)); + post(ae); + if (listenersOnSyncEvent) { + final PlayerChatEvent se = new PlayerChatEvent(player, ae.getMessage(), ae.getFormat(), ae.getRecipients()); + se.setCancelled(ae.isCancelled()); // propagate cancelled state + this.queueIfAsyncOrRunImmediately(new Waitable() { + @Override + protected Void evaluate() { + post(se); + return null; + } + }); + continueAfterAsyncAndSync.accept(se); + } else { + continueAfterAsync.accept(ae); + } + } else { + modernOnly.run(); + } + } + + private void processModern(final ChatRenderer renderer, final Set recipients, final Component message, final boolean cancelled) { + final AsyncChatEvent ae = this.createAsync(renderer, recipients, new LazyChatAudienceSet(), message); + ae.setCancelled(cancelled); // propagate cancelled state + post(ae); + final boolean listenersOnSyncEvent = anyListeners(ChatEvent.getHandlerList()); + if (listenersOnSyncEvent) { + this.continueWithSyncFromWhereAsyncLeftOff(ae); + } else { + this.complete(ae); + } + } + + private void continueWithSyncFromWhereAsyncLeftOff(final AsyncChatEvent ae) { + this.queueIfAsyncOrRunImmediately(new Waitable() { + @Override + protected Void evaluate() { + final ChatEvent se = ChatProcessor.this.createSync(ae.renderer(), ae.recipients(), ae.viewers(), ae.message()); + se.setCancelled(ae.isCancelled()); // propagate cancelled state + post(se); + ChatProcessor.this.complete(se); + return null; + } + }); + } + + private void complete(final AbstractChatEvent event) { + if (event.isCancelled()) { + return; + } + + final CraftPlayer player = this.player.getBukkitEntity(); + final Component displayName = displayName(player); + final Component message = event.message(); + final ChatRenderer renderer = event.renderer(); + + final Set viewers = event.viewers(); + final Set recipients = event.recipients(); + if (viewers instanceof LazyChatAudienceSet && recipients instanceof LazyPlayerSet && + (!((LazyChatAudienceSet) viewers).isLazy() || ((LazyPlayerSet) recipients).isLazy())) { + for (final Audience viewer : viewers) { + viewer.sendMessage(player, renderer.render(player, displayName, message, viewer), MessageType.CHAT); + } + } else { + this.server.console.sendMessage(player, renderer.render(player, displayName, message, this.server.console), MessageType.CHAT); + for (final Player recipient : recipients) { + recipient.sendMessage(player, renderer.render(player, displayName, message, recipient), MessageType.CHAT); + } + } + } + + private AsyncChatEvent createAsync(final ChatRenderer renderer, final Set recipients, final Set viewers, final Component message) { + return new AsyncChatEvent(this.async, this.player.getBukkitEntity(), recipients, viewers, renderer, message, this.originalMessage); + } + + private ChatEvent createSync(final ChatRenderer renderer, final Set recipients, final Set viewers, final Component message) { + return new ChatEvent(this.player.getBukkitEntity(), recipients, viewers, renderer, message, this.originalMessage); + } + + private static String legacyDisplayName(final CraftPlayer player) { + return player.getDisplayName(); + } + + private static Component displayName(final CraftPlayer player) { + return player.displayName(); + } + + private static ChatRenderer legacyRenderer(final String format) { + return (player, displayName, message, recipient) -> PaperAdventure.LEGACY_SECTION_UXRC.deserialize(String.format(format, legacyDisplayName((CraftPlayer) player), PaperAdventure.LEGACY_SECTION_UXRC.serialize(message))).replaceText(URL_REPLACEMENT_CONFIG); + } + + private void queueIfAsyncOrRunImmediately(final Waitable waitable) { + if (this.async) { + this.server.processQueue.add(waitable); + } else { + waitable.run(); + } + try { + waitable.get(); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); // tag, you're it + } catch (final ExecutionException e) { + throw new RuntimeException("Exception processing chat", e.getCause()); + } + } + + private static void post(final Event event) { + Bukkit.getPluginManager().callEvent(event); + } + + private static boolean anyListeners(final HandlerList handlers) { + return handlers.getRegisteredListeners().length > 0; + } +} diff --git a/src/main/java/io/papermc/paper/adventure/DisplayNames.java b/src/main/java/io/papermc/paper/adventure/DisplayNames.java new file mode 100644 index 0000000000000000000000000000000000000000..bfaf5d3c5aae8a587c2b11d90089c588b2a2aba0 --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/DisplayNames.java @@ -0,0 +1,22 @@ +package io.papermc.paper.adventure; + +import net.minecraft.server.level.ServerPlayer; +import org.bukkit.ChatColor; +import org.bukkit.craftbukkit.entity.CraftPlayer; + +public final class DisplayNames { + private DisplayNames() { + } + + public static String getLegacy(final CraftPlayer player) { + return getLegacy(player.getHandle()); + } + + public static String getLegacy(final ServerPlayer player) { + final String legacy = player.displayName; + if (legacy != null) { + return PaperAdventure.LEGACY_SECTION_UXRC.serialize(player.adventure$displayName) + ChatColor.getLastColors(player.displayName); + } + return PaperAdventure.LEGACY_SECTION_UXRC.serialize(player.adventure$displayName); + } +} diff --git a/src/main/java/io/papermc/paper/adventure/LazyChatAudienceSet.java b/src/main/java/io/papermc/paper/adventure/LazyChatAudienceSet.java new file mode 100644 index 0000000000000000000000000000000000000000..10f08e2b73610ab06928d1f63348920fef8e91fa --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/LazyChatAudienceSet.java @@ -0,0 +1,21 @@ +package io.papermc.paper.adventure; + +import net.kyori.adventure.audience.Audience; +import net.minecraft.server.MinecraftServer; +import org.bukkit.Bukkit; +import org.bukkit.craftbukkit.util.LazyHashSet; +import org.bukkit.craftbukkit.util.LazyPlayerSet; +import org.bukkit.entity.Player; + +import java.util.HashSet; +import java.util.Set; + +final class LazyChatAudienceSet extends LazyHashSet { + @Override + protected Set makeReference() { + final Set playerSet = LazyPlayerSet.makePlayerSet(MinecraftServer.getServer()); + final HashSet audiences = new HashSet<>(playerSet); + audiences.add(Bukkit.getConsoleSender()); + return audiences; + } +} diff --git a/src/main/java/io/papermc/paper/adventure/NBTLegacyHoverEventSerializer.java b/src/main/java/io/papermc/paper/adventure/NBTLegacyHoverEventSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..eeedc30a45d9637d68f04f185b3dd90dd711b9e0 --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/NBTLegacyHoverEventSerializer.java @@ -0,0 +1,88 @@ +package io.papermc.paper.adventure; + +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import java.io.IOException; +import java.util.UUID; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.nbt.api.BinaryTagHolder; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.serializer.gson.LegacyHoverEventSerializer; +import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer; +import net.kyori.adventure.util.Codec; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.Tag; +import net.minecraft.nbt.TagParser; + +final class NBTLegacyHoverEventSerializer implements LegacyHoverEventSerializer { + public static final NBTLegacyHoverEventSerializer INSTANCE = new NBTLegacyHoverEventSerializer(); + private static final Codec SNBT_CODEC = Codec.of(TagParser::parseTag, Tag::toString); + + static final String ITEM_TYPE = "id"; + static final String ITEM_COUNT = "Count"; + static final String ITEM_TAG = "tag"; + + static final String ENTITY_NAME = "name"; + static final String ENTITY_TYPE = "type"; + static final String ENTITY_ID = "id"; + + NBTLegacyHoverEventSerializer() { + } + + @Override + public HoverEvent.ShowItem deserializeShowItem(final Component input) throws IOException { + final String raw = PlainComponentSerializer.plain().serialize(input); + try { + final CompoundTag contents = SNBT_CODEC.decode(raw); + final CompoundTag tag = contents.getCompound(ITEM_TAG); + return HoverEvent.ShowItem.of( + Key.key(contents.getString(ITEM_TYPE)), + contents.contains(ITEM_COUNT) ? contents.getByte(ITEM_COUNT) : 1, + tag.isEmpty() ? null : BinaryTagHolder.encode(tag, SNBT_CODEC) + ); + } catch (final CommandSyntaxException ex) { + throw new IOException(ex); + } + } + + @Override + public HoverEvent.ShowEntity deserializeShowEntity(final Component input, final Codec.Decoder componentCodec) throws IOException { + final String raw = PlainComponentSerializer.plain().serialize(input); + try { + final CompoundTag contents = SNBT_CODEC.decode(raw); + return HoverEvent.ShowEntity.of( + Key.key(contents.getString(ENTITY_TYPE)), + UUID.fromString(contents.getString(ENTITY_ID)), + componentCodec.decode(contents.getString(ENTITY_NAME)) + ); + } catch (final CommandSyntaxException ex) { + throw new IOException(ex); + } + } + + @Override + public Component serializeShowItem(final HoverEvent.ShowItem input) throws IOException { + final CompoundTag tag = new CompoundTag(); + tag.putString(ITEM_TYPE, input.item().asString()); + tag.putByte(ITEM_COUNT, (byte) input.count()); + if (input.nbt() != null) { + try { + tag.put(ITEM_TAG, input.nbt().get(SNBT_CODEC)); + } catch (final CommandSyntaxException ex) { + throw new IOException(ex); + } + } + return Component.text(SNBT_CODEC.encode(tag)); + } + + @Override + public Component serializeShowEntity(final HoverEvent.ShowEntity input, final Codec.Encoder componentCodec) throws IOException { + final CompoundTag tag = new CompoundTag(); + tag.putString(ENTITY_ID, input.id().toString()); + tag.putString(ENTITY_TYPE, input.type().asString()); + if (input.name() != null) { + tag.putString(ENTITY_NAME, componentCodec.encode(input.name())); + } + return Component.text(SNBT_CODEC.encode(tag)); + } +} diff --git a/src/main/java/io/papermc/paper/adventure/PaperAdventure.java b/src/main/java/io/papermc/paper/adventure/PaperAdventure.java new file mode 100644 index 0000000000000000000000000000000000000000..696b7ad89af4e379d7b8f1961d1ab0cba1c3313f --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/PaperAdventure.java @@ -0,0 +1,342 @@ +package io.papermc.paper.adventure; + +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import io.netty.util.AttributeKey; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.inventory.Book; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.nbt.api.BinaryTagHolder; +import net.kyori.adventure.sound.Sound; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TranslatableComponent; +import net.kyori.adventure.text.flattener.ComponentFlattener; +import net.kyori.adventure.text.format.TextColor; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer; +import net.kyori.adventure.translation.GlobalTranslator; +import net.kyori.adventure.util.Codec; +import net.minecraft.ChatFormatting; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.StringTag; +import net.minecraft.nbt.TagParser; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.BossEvent; +import net.minecraft.world.item.ItemStack; +import org.bukkit.ChatColor; +import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; + +public final class PaperAdventure { + public static final AttributeKey LOCALE_ATTRIBUTE = AttributeKey.valueOf("adventure:locale"); + private static final Pattern LOCALIZATION_PATTERN = Pattern.compile("%(?:(\\d+)\\$)?s"); + public static final ComponentFlattener FLATTENER = ComponentFlattener.basic().toBuilder() + .complexMapper(TranslatableComponent.class, (translatable, consumer) -> { + final @NonNull String translated = LocaleLanguage.a().a(translatable.key()); + + final Matcher matcher = LOCALIZATION_PATTERN.matcher(translated); + final List args = translatable.args(); + int argPosition = 0; + int lastIdx = 0; + while (matcher.find()) { + // append prior + if (lastIdx < matcher.start()) { + consumer.accept(Component.text(translated.substring(lastIdx, matcher.start()))); + } + lastIdx = matcher.end(); + + final @Nullable String argIdx = matcher.group(1); + // calculate argument position + if (argIdx != null) { + try { + final int idx = Integer.parseInt(argIdx) - 1; + if (idx < args.size()) { + consumer.accept(args.get(idx)); + } + } catch (final NumberFormatException ex) { + // ignore, drop the format placeholder + } + } else { + final int idx = argPosition++; + if (idx < args.size()) { + consumer.accept(args.get(idx)); + } + } + } + + // append tail + if (lastIdx < translated.length()) { + consumer.accept(Component.text(translated.substring(lastIdx))); + } + }) + .build(); + public static final LegacyComponentSerializer LEGACY_SECTION_UXRC = LegacyComponentSerializer.builder().flattener(FLATTENER).hexColors().useUnusualXRepeatedCharacterHexFormat().build(); + public static final PlainComponentSerializer PLAIN = PlainComponentSerializer.builder().flattener(FLATTENER).build(); + public static final GsonComponentSerializer GSON = GsonComponentSerializer.builder() + .legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE) + .build(); + public static final GsonComponentSerializer COLOR_DOWNSAMPLING_GSON = GsonComponentSerializer.builder() + .legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE) + .downsampleColors() + .build(); + private static final Codec NBT_CODEC = new Codec() { + @Override + public @NonNull CompoundTag decode(final @NonNull String encoded) throws IOException { + try { + return TagParser.parseTag(encoded); + } catch (final CommandSyntaxException e) { + throw new IOException(e); + } + } + + @Override + public @NonNull String encode(final @NonNull CompoundTag decoded) { + return decoded.toString(); + } + }; + static final WrapperAwareSerializer WRAPPER_AWARE_SERIALIZER = new WrapperAwareSerializer(); + + private PaperAdventure() { + } + + // Key + + public static ResourceLocation asVanilla(final Key key) { + return new ResourceLocation(key.namespace(), key.value()); + } + + public static ResourceLocation asVanillaNullable(final Key key) { + if (key == null) { + return null; + } + return new ResourceLocation(key.namespace(), key.value()); + } + + // Component + + public static Component asAdventure(final net.minecraft.network.chat.Component component) { + return component == null ? Component.empty() : GSON.serializer().fromJson(net.minecraft.network.chat.Component.Serializer.toJsonTree(component), Component.class); + } + + public static ArrayList asAdventure(final List vanillas) { + final ArrayList adventures = new ArrayList<>(vanillas.size()); + for (final net.minecraft.network.chat.Component vanilla : vanillas) { + adventures.add(asAdventure(vanilla)); + } + return adventures; + } + + public static ArrayList asAdventureFromJson(final List jsonStrings) { + final ArrayList adventures = new ArrayList<>(jsonStrings.size()); + for (final String json : jsonStrings) { + adventures.add(GsonComponentSerializer.gson().deserialize(json)); + } + return adventures; + } + + public static List asJson(final List adventures) { + final List jsons = new ArrayList<>(adventures.size()); + for (final Component component : adventures) { + jsons.add(GsonComponentSerializer.gson().serialize(component)); + } + return jsons; + } + + public static net.minecraft.network.chat.Component asVanilla(final Component component) { + if (true) return new AdventureComponent(component); + return net.minecraft.network.chat.Component.Serializer.fromJsonTree(GSON.serializer().toJsonTree(component)); + } + + public static List asVanilla(final List adventures) { + final List vanillas = new ArrayList<>(adventures.size()); + for (final Component adventure : adventures) { + vanillas.add(asVanilla(adventure)); + } + return vanillas; + } + + public static String asJsonString(final Component component, final Locale locale) { + return GSON.serialize( + GlobalTranslator.render( + component, + // play it safe + locale != null + ? locale + : Locale.US + ) + ); + } + + public static String asJsonString(final net.minecraft.network.chat.Component component, final Locale locale) { + if (component instanceof AdventureComponent) { + return asJsonString(((AdventureComponent) component).wrapped, locale); + } + return net.minecraft.network.chat.Component.Serializer.componentToJson(component); + } + + // thank you for being worse than wet socks, Bukkit + public static String superHackyLegacyRepresentationOfComponent(final Component component, final String string) { + return LEGACY_SECTION_UXRC.serialize(component) + ChatColor.getLastColors(string); + } + + // BossBar + + public static BossEvent.BossBarColor asVanilla(final BossBar.Color color) { + if (color == BossBar.Color.PINK) { + return BossEvent.BossBarColor.PINK; + } else if (color == BossBar.Color.BLUE) { + return BossEvent.BossBarColor.BLUE; + } else if (color == BossBar.Color.RED) { + return BossEvent.BossBarColor.RED; + } else if (color == BossBar.Color.GREEN) { + return BossEvent.BossBarColor.GREEN; + } else if (color == BossBar.Color.YELLOW) { + return BossEvent.BossBarColor.YELLOW; + } else if (color == BossBar.Color.PURPLE) { + return BossEvent.BossBarColor.PURPLE; + } else if (color == BossBar.Color.WHITE) { + return BossEvent.BossBarColor.WHITE; + } + throw new IllegalArgumentException(color.name()); + } + + public static BossBar.Color asAdventure(final BossEvent.BossBarColor color) { + if(color == BossEvent.BossBarColor.PINK) { + return BossBar.Color.PINK; + } else if(color == BossEvent.BossBarColor.BLUE) { + return BossBar.Color.BLUE; + } else if(color == BossEvent.BossBarColor.RED) { + return BossBar.Color.RED; + } else if(color == BossEvent.BossBarColor.GREEN) { + return BossBar.Color.GREEN; + } else if(color == BossEvent.BossBarColor.YELLOW) { + return BossBar.Color.YELLOW; + } else if(color == BossEvent.BossBarColor.PURPLE) { + return BossBar.Color.PURPLE; + } else if(color == BossEvent.BossBarColor.WHITE) { + return BossBar.Color.WHITE; + } + throw new IllegalArgumentException(color.name()); + } + + public static BossEvent.BossBarOverlay asVanilla(final BossBar.Overlay overlay) { + if (overlay == BossBar.Overlay.PROGRESS) { + return BossEvent.BossBarOverlay.PROGRESS; + } else if (overlay == BossBar.Overlay.NOTCHED_6) { + return BossEvent.BossBarOverlay.NOTCHED_6; + } else if (overlay == BossBar.Overlay.NOTCHED_10) { + return BossEvent.BossBarOverlay.NOTCHED_10; + } else if (overlay == BossBar.Overlay.NOTCHED_12) { + return BossEvent.BossBarOverlay.NOTCHED_12; + } else if (overlay == BossBar.Overlay.NOTCHED_20) { + return BossEvent.BossBarOverlay.NOTCHED_20; + } + throw new IllegalArgumentException(overlay.name()); + } + + public static BossBar.Overlay asAdventure(final BossEvent.BossBarOverlay overlay) { + if (overlay == BossEvent.BossBarOverlay.PROGRESS) { + return BossBar.Overlay.PROGRESS; + } else if (overlay == BossEvent.BossBarOverlay.NOTCHED_6) { + return BossBar.Overlay.NOTCHED_6; + } else if (overlay == BossEvent.BossBarOverlay.NOTCHED_10) { + return BossBar.Overlay.NOTCHED_10; + } else if (overlay == BossEvent.BossBarOverlay.NOTCHED_12) { + return BossBar.Overlay.NOTCHED_12; + } else if (overlay == BossEvent.BossBarOverlay.NOTCHED_20) { + return BossBar.Overlay.NOTCHED_20; + } + throw new IllegalArgumentException(overlay.name()); + } + + public static void setFlag(final BossBar bar, final BossBar.Flag flag, final boolean value) { + if (value) { + bar.addFlag(flag); + } else { + bar.removeFlag(flag); + } + } + + // Book + + public static ItemStack asItemStack(final Book book, final Locale locale) { + final ItemStack item = new ItemStack(net.minecraft.world.item.Items.WRITTEN_BOOK, 1); + final CompoundTag tag = item.getOrCreateTag(); + tag.putString("title", asJsonString(book.title(), locale)); + tag.putString("author", asJsonString(book.author(), locale)); + final ListTag pages = new ListTag(); + for (final Component page : book.pages()) { + pages.add(StringTag.create(asJsonString(page, locale))); + } + tag.put("pages", pages); + return item; + } + + // Sounds + + public static SoundSource asVanilla(final Sound.Source source) { + if (source == Sound.Source.MASTER) { + return SoundSource.MASTER; + } else if (source == Sound.Source.MUSIC) { + return SoundSource.MUSIC; + } else if (source == Sound.Source.RECORD) { + return SoundSource.RECORDS; + } else if (source == Sound.Source.WEATHER) { + return SoundSource.WEATHER; + } else if (source == Sound.Source.BLOCK) { + return SoundSource.BLOCKS; + } else if (source == Sound.Source.HOSTILE) { + return SoundSource.HOSTILE; + } else if (source == Sound.Source.NEUTRAL) { + return SoundSource.NEUTRAL; + } else if (source == Sound.Source.PLAYER) { + return SoundSource.PLAYERS; + } else if (source == Sound.Source.AMBIENT) { + return SoundSource.AMBIENT; + } else if (source == Sound.Source.VOICE) { + return SoundSource.VOICE; + } + throw new IllegalArgumentException(source.name()); + } + + public static @Nullable SoundSource asVanillaNullable(final Sound.@Nullable Source source) { + if (source == null) { + return null; + } + return asVanilla(source); + } + + // NBT + + public static @Nullable BinaryTagHolder asBinaryTagHolder(final @Nullable CompoundTag tag) { + if (tag == null) { + return null; + } + try { + return BinaryTagHolder.encode(tag, NBT_CODEC); + } catch (final IOException e) { + return null; + } + } + + // Colors + + public static @NonNull TextColor asAdventure(ChatFormatting minecraftColor) { + if (minecraftColor.getColor() == null) { + throw new IllegalArgumentException("Not a valid color"); + } + return TextColor.color(minecraftColor.getColor()); + } + + public static @Nullable ChatFormatting asVanilla(TextColor color) { + return ChatFormatting.getByHexValue(color.value()); + } +} diff --git a/src/main/java/io/papermc/paper/adventure/VanillaBossBarListener.java b/src/main/java/io/papermc/paper/adventure/VanillaBossBarListener.java new file mode 100644 index 0000000000000000000000000000000000000000..ee6d9d5c072d68cace63068a8e2ed603ad475378 --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/VanillaBossBarListener.java @@ -0,0 +1,41 @@ +package io.papermc.paper.adventure; + +import java.util.Set; +import java.util.function.Consumer; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.text.Component; +import net.minecraft.network.protocol.game.ClientboundBossEventPacket; +import org.checkerframework.checker.nullness.qual.NonNull; + +public final class VanillaBossBarListener implements BossBar.Listener { + private final Consumer action; + + public VanillaBossBarListener(final Consumer action) { + this.action = action; + } + + @Override + public void bossBarNameChanged(final @NonNull BossBar bar, final @NonNull Component oldName, final @NonNull Component newName) { + this.action.accept(ClientboundBossEventPacket.Operation.UPDATE_NAME); + } + + @Override + public void bossBarProgressChanged(final @NonNull BossBar bar, final float oldProgress, final float newProgress) { + this.action.accept(ClientboundBossEventPacket.Operation.UPDATE_PCT); + } + + @Override + public void bossBarColorChanged(final @NonNull BossBar bar, final BossBar.@NonNull Color oldColor, final BossBar.@NonNull Color newColor) { + this.action.accept(ClientboundBossEventPacket.Operation.UPDATE_STYLE); + } + + @Override + public void bossBarOverlayChanged(final @NonNull BossBar bar, final BossBar.@NonNull Overlay oldOverlay, final BossBar.@NonNull Overlay newOverlay) { + this.action.accept(ClientboundBossEventPacket.Operation.UPDATE_STYLE); + } + + @Override + public void bossBarFlagsChanged(final @NonNull BossBar bar, final @NonNull Set flagsAdded, final @NonNull Set flagsRemoved) { + this.action.accept(ClientboundBossEventPacket.Operation.UPDATE_PROPERTIES); + } +} diff --git a/src/main/java/io/papermc/paper/adventure/WrapperAwareSerializer.java b/src/main/java/io/papermc/paper/adventure/WrapperAwareSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..2e93ac0eb74a89c020f3356f77320cf6459727fd --- /dev/null +++ b/src/main/java/io/papermc/paper/adventure/WrapperAwareSerializer.java @@ -0,0 +1,19 @@ +package io.papermc.paper.adventure; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.ComponentSerializer; + +final class WrapperAwareSerializer implements ComponentSerializer { + @Override + public Component deserialize(final net.minecraft.network.chat.Component input) { + if (input instanceof AdventureComponent) { + return ((AdventureComponent) input).wrapped; + } + return PaperAdventure.GSON.serializer().fromJson(net.minecraft.network.chat.Component.Serializer.toJsonTree(input), Component.class); + } + + @Override + public net.minecraft.network.chat.Component serialize(final Component component) { + return net.minecraft.network.chat.Component.Serializer.fromJsonTree(PaperAdventure.GSON.serializer().toJsonTree(component)); + } +} diff --git a/src/main/java/net/kyori/adventure/bossbar/HackyBossBarPlatformBridge.java b/src/main/java/net/kyori/adventure/bossbar/HackyBossBarPlatformBridge.java new file mode 100644 index 0000000000000000000000000000000000000000..2dc92d8d2764d3e9b621d5c7d5e30c30367b3117 --- /dev/null +++ b/src/main/java/net/kyori/adventure/bossbar/HackyBossBarPlatformBridge.java @@ -0,0 +1,36 @@ +package net.kyori.adventure.bossbar; + +import io.papermc.paper.adventure.PaperAdventure; +import io.papermc.paper.adventure.VanillaBossBarListener; +import net.minecraft.server.level.ServerBossEvent; +import org.bukkit.craftbukkit.entity.CraftPlayer; + +public abstract class HackyBossBarPlatformBridge { + public ServerBossEvent vanilla$bar; + private VanillaBossBarListener vanilla$listener; + + public final void paper$playerShow(final CraftPlayer player) { + if (this.vanilla$bar == null) { + final BossBar $this = (BossBar) this; + this.vanilla$bar = new ServerBossEvent( + PaperAdventure.asVanilla($this.name()), + PaperAdventure.asVanilla($this.color()), + PaperAdventure.asVanilla($this.overlay()) + ); + this.vanilla$bar.adventure = $this; + this.vanilla$listener = new VanillaBossBarListener(this.vanilla$bar::broadcast); + $this.addListener(this.vanilla$listener); + } + this.vanilla$bar.addPlayer(player.getHandle()); + } + + public final void paper$playerHide(final CraftPlayer player) { + if (this.vanilla$bar != null) { + this.vanilla$bar.removePlayer(player.getHandle()); + if (this.vanilla$bar.getPlayers().isEmpty()) { + ((BossBar) this).removeListener(this.vanilla$listener); + this.vanilla$bar = null; + } + } + } +} diff --git a/src/main/java/net/minecraft/ChatFormatting.java b/src/main/java/net/minecraft/ChatFormatting.java index e888a90226c30757b190a3b89a56c1a312f32850..1720eba650c959810c6e4a3522979e75e10a1bb8 100644 --- a/src/main/java/net/minecraft/ChatFormatting.java +++ b/src/main/java/net/minecraft/ChatFormatting.java @@ -61,6 +61,7 @@ public enum ChatFormatting { return !this.isFormat && this != ChatFormatting.RESET; } + @Nullable public Integer getHexValue() { return this.getColor(); } // Paper - OBFHELPER @Nullable public Integer getColor() { return this.color; @@ -84,6 +85,18 @@ public enum ChatFormatting { return name == null ? null : (ChatFormatting) ChatFormatting.FORMATTING_BY_NAME.get(cleanName(name)); } + // Paper start + @Nullable public static ChatFormatting getByHexValue(int i) { + for (ChatFormatting value : values()) { + if (value.getHexValue() != null && value.getHexValue() == i) { + return value; + } + } + + return null; + } + // Paper end + @Nullable public static ChatFormatting getById(int colorIndex) { if (colorIndex < 0) { diff --git a/src/main/java/net/minecraft/nbt/StringTag.java b/src/main/java/net/minecraft/nbt/StringTag.java index 620e10b5ba9e57ff4d0d7967bf4240fafadb2be7..dab8983fa65b97ecf0fe20fdc06cc8ec60d8fe95 100644 --- a/src/main/java/net/minecraft/nbt/StringTag.java +++ b/src/main/java/net/minecraft/nbt/StringTag.java @@ -43,6 +43,7 @@ public class StringTag implements Tag { this.data = value; } + public static StringTag create(final String value) { return valueOf(value); } // Paper - OBFHELPER public static StringTag valueOf(String value) { return value.isEmpty() ? StringTag.EMPTY : new StringTag(value); } diff --git a/src/main/java/net/minecraft/network/FriendlyByteBuf.java b/src/main/java/net/minecraft/network/FriendlyByteBuf.java index 50f14acb062c2f90266279dbd1945a3297396f0b..59788eaef0dae5ee01ceba1bf45e85cb07f88e53 100644 --- a/src/main/java/net/minecraft/network/FriendlyByteBuf.java +++ b/src/main/java/net/minecraft/network/FriendlyByteBuf.java @@ -10,6 +10,7 @@ import io.netty.buffer.ByteBufOutputStream; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.EncoderException; import io.netty.util.ByteProcessor; +import io.papermc.paper.adventure.PaperAdventure; // Paper import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; @@ -43,6 +44,7 @@ import org.bukkit.craftbukkit.inventory.CraftItemStack; // CraftBukkit public class FriendlyByteBuf extends ByteBuf { private final ByteBuf source; + public java.util.Locale adventure$locale; // Paper public FriendlyByteBuf(ByteBuf bytebuf) { this.source = bytebuf; @@ -164,8 +166,15 @@ public class FriendlyByteBuf extends ByteBuf { return Component.Serializer.fromJson(this.readUtf(262144)); } + // Paper start + public FriendlyByteBuf writeComponent(final net.kyori.adventure.text.Component component) { + return this.writeUtf(PaperAdventure.asJsonString(component, this.adventure$locale), 262144); + } + // Paper end + public FriendlyByteBuf writeComponent(Component text) { - return this.writeUtf(Component.Serializer.toJson(text), 262144); + //return this.a(IChatBaseComponent.ChatSerializer.a(ichatbasecomponent), 262144); // Paper - comment + return this.writeUtf(PaperAdventure.asJsonString(text, this.adventure$locale), 262144); // Paper } public > T readEnum(Class oclass) { @@ -348,6 +357,7 @@ public class FriendlyByteBuf extends ByteBuf { return this.writeUtf(s, 32767); } + public FriendlyByteBuf writeUtf(final String string, final int maxLength) { return this.writeUtf(string, maxLength); } // Paper - OBFHELPER public FriendlyByteBuf writeUtf(String s, int i) { byte[] abyte = s.getBytes(StandardCharsets.UTF_8); diff --git a/src/main/java/net/minecraft/network/PacketEncoder.java b/src/main/java/net/minecraft/network/PacketEncoder.java index 14fa1371e52b9af5a7550a9aa144fa406b754046..d36d0424bcd4811af892f5f76fdcefda2af1ad33 100644 --- a/src/main/java/net/minecraft/network/PacketEncoder.java +++ b/src/main/java/net/minecraft/network/PacketEncoder.java @@ -3,6 +3,7 @@ package net.minecraft.network; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; +import io.papermc.paper.adventure.PaperAdventure; // Paper import java.io.IOException; import net.minecraft.network.protocol.Packet; import net.minecraft.network.protocol.PacketFlow; @@ -37,6 +38,7 @@ public class PacketEncoder extends MessageToByteEncoder> { throw new IOException("Can't serialize unregistered packet"); } else { FriendlyByteBuf packetdataserializer = new FriendlyByteBuf(bytebuf); + packetdataserializer.adventure$locale = channelhandlercontext.channel().attr(PaperAdventure.LOCALE_ATTRIBUTE).get(); // Paper packetdataserializer.writeVarInt(integer); diff --git a/src/main/java/net/minecraft/network/chat/Component.java b/src/main/java/net/minecraft/network/chat/Component.java index 819ea90ea116dea396c225539fc0fbebd6176ba5..54d186a195aca6d0a4c412ed609d8c86dcc76072 100644 --- a/src/main/java/net/minecraft/network/chat/Component.java +++ b/src/main/java/net/minecraft/network/chat/Component.java @@ -1,5 +1,6 @@ package net.minecraft.network.chat; +import io.papermc.paper.adventure.AdventureComponent; // Paper import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -110,6 +111,7 @@ public interface Component extends Message, FormattedText, Iterable { GsonBuilder gsonbuilder = new GsonBuilder(); gsonbuilder.disableHtmlEscaping(); + gsonbuilder.registerTypeAdapter(AdventureComponent.class, new AdventureComponent.Serializer()); // Paper gsonbuilder.registerTypeHierarchyAdapter(Component.class, new Component.Serializer()); gsonbuilder.registerTypeHierarchyAdapter(Style.class, new Style.Serializer()); gsonbuilder.registerTypeAdapterFactory(new LowerCaseEnumTypeAdapterFactory()); @@ -262,6 +264,7 @@ public interface Component extends Message, FormattedText, Iterable { } public JsonElement serialize(Component ichatbasecomponent, Type type, JsonSerializationContext jsonserializationcontext) { + if (ichatbasecomponent instanceof AdventureComponent) return jsonserializationcontext.serialize(ichatbasecomponent); // Paper JsonObject jsonobject = new JsonObject(); if (!ichatbasecomponent.getStyle().isEmpty()) { @@ -350,10 +353,12 @@ public interface Component extends Message, FormattedText, Iterable { return jsonobject; } + public static String componentToJson(final Component component) { return toJson(component); } // Paper - OBFHELPER public static String toJson(Component text) { return Component.Serializer.GSON.toJson(text); } + public static JsonElement toJsonTree(final Component component) { return toJsonTree(component); } // Paper - OBFHELPER public static JsonElement toJsonTree(Component text) { return Component.Serializer.GSON.toJsonTree(text); } @@ -363,6 +368,7 @@ public interface Component extends Message, FormattedText, Iterable { return (MutableComponent) GsonHelper.fromJson(Component.Serializer.GSON, json, MutableComponent.class, false); } + public static @Nullable Component fromJsonTree(final JsonElement json) { return fromJson(json); } // Paper - OBFHELPER @Nullable public static MutableComponent fromJson(JsonElement json) { return (MutableComponent) Component.Serializer.GSON.fromJson(json, MutableComponent.class); diff --git a/src/main/java/net/minecraft/network/protocol/game/ClientboundChatPacket.java b/src/main/java/net/minecraft/network/protocol/game/ClientboundChatPacket.java index ce64931b5c363352f03baddbc747246469d56a84..e47102cadb40ed8a9c011386445f15fd30de7596 100644 --- a/src/main/java/net/minecraft/network/protocol/game/ClientboundChatPacket.java +++ b/src/main/java/net/minecraft/network/protocol/game/ClientboundChatPacket.java @@ -11,6 +11,7 @@ import net.minecraft.network.protocol.Packet; public class ClientboundChatPacket implements Packet { private Component message; + public net.kyori.adventure.text.Component adventure$message; // Paper public net.md_5.bungee.api.chat.BaseComponent[] components; // Spigot private ChatType type; private UUID sender; @@ -32,6 +33,11 @@ public class ClientboundChatPacket implements Packet { @Override public void write(FriendlyByteBuf buf) throws IOException { + // Paper start + if (this.adventure$message != null) { + buf.writeComponent(this.adventure$message); + } else + // Paper end // Spigot start if (components != null) { buf.writeByteArray(net.md_5.bungee.chat.ComponentSerializer.toString(components)); diff --git a/src/main/java/net/minecraft/network/protocol/game/ClientboundSetTitlesPacket.java b/src/main/java/net/minecraft/network/protocol/game/ClientboundSetTitlesPacket.java index 915120cc505c70153f7b70f07d8d42c13eb77ea7..69ff8df7340e60c476803256750a48f0b43414d3 100644 --- a/src/main/java/net/minecraft/network/protocol/game/ClientboundSetTitlesPacket.java +++ b/src/main/java/net/minecraft/network/protocol/game/ClientboundSetTitlesPacket.java @@ -10,6 +10,7 @@ public class ClientboundSetTitlesPacket implements Packet 0 && flag) { // TODO: allow plugins to override? - Component ichatbasecomponent; - if (deathMessage.equals(deathmessage)) { - ichatbasecomponent = this.getCombatTracker().getDeathMessage(); - } else { - ichatbasecomponent = org.bukkit.craftbukkit.util.CraftChatMessage.fromStringOrNull(deathMessage); - } + if (deathMessage != null && deathMessage != net.kyori.adventure.text.Component.empty() && flag) { // Paper - Adventure // TODO: allow plugins to override? + Component ichatbasecomponent = PaperAdventure.asVanilla(deathMessage); // Paper - Adventure this.connection.send((Packet) (new ClientboundPlayerCombatPacket(this.getCombatTracker(), ClientboundPlayerCombatPacket.Event.ENTITY_DIED, ichatbasecomponent)), (future) -> { if (!future.isSuccess()) { @@ -1666,6 +1663,7 @@ public class ServerPlayer extends Player implements ContainerListener { this.sendMessage(message, ChatType.SYSTEM, senderUuid); } + public void sendMessage(final Component message, final ChatType type, final UUID sender) { this.sendMessage(message, type, sender); } // Paper - OBFHELPER public void sendMessage(Component message, ChatType type, UUID senderUuid) { this.connection.send((Packet) (new ClientboundChatPacket(message, type, senderUuid)), (future) -> { if (!future.isSuccess() && (type == ChatType.GAME_INFO || type == ChatType.SYSTEM)) { @@ -1688,6 +1686,7 @@ public class ServerPlayer extends Player implements ContainerListener { } public String locale = "en_us"; // CraftBukkit - add, lowercase + public java.util.Locale adventure$locale = java.util.Locale.US; // Paper public void updateOptions(ServerboundClientInformationPacket packet) { // CraftBukkit start if (getMainArm() != packet.getMainHand()) { @@ -1699,6 +1698,10 @@ public class ServerPlayer extends Player implements ContainerListener { this.server.server.getPluginManager().callEvent(event); } this.locale = packet.language; + // Paper start + this.adventure$locale = net.kyori.adventure.translation.Translator.parseLocale(this.locale); + this.connection.connection.channel.attr(PaperAdventure.LOCALE_ATTRIBUTE).set(this.adventure$locale); + // Paper end this.clientViewDistance = packet.viewDistance; // CraftBukkit end this.chatVisibility = packet.getChatVisibility(); diff --git a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java index 466c4322803bedf1fa61be281b954bf94fb8ff02..016e91a6ca1c8457e3e367ac0597b73e81919b68 100644 --- a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java +++ b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java @@ -168,6 +168,8 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; // CraftBukkit start +import io.papermc.paper.adventure.ChatProcessor; // Paper +import io.papermc.paper.adventure.PaperAdventure; // Paper import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import org.bukkit.Location; @@ -388,21 +390,24 @@ public class ServerGamePacketListenerImpl implements ServerGamePacketListener { return this.server.isSingleplayerOwner(this.player.getGameProfile()); } - // CraftBukkit start - @Deprecated - public void disconnect(Component reason) { - disconnect(CraftChatMessage.fromComponent(reason)); + public void disconnect(String s) { + // Paper start + this.disconnect(PaperAdventure.LEGACY_SECTION_UXRC.deserialize(s)); } - // CraftBukkit end - public void disconnect(String s) { + public void disconnect(final Component reason) { + this.disconnect(PaperAdventure.asAdventure(reason)); + } + + public void disconnect(net.kyori.adventure.text.Component reason) { + // Paper end // CraftBukkit start - fire PlayerKickEvent if (this.processedDisconnect) { return; } - String leaveMessage = ChatFormatting.YELLOW + this.player.getScoreboardName() + " left the game."; + net.kyori.adventure.text.Component leaveMessage = net.kyori.adventure.text.Component.translatable("multiplayer.player.left", net.kyori.adventure.text.format.NamedTextColor.YELLOW, this.player.getBukkitEntity().displayName()); // Paper - Adventure - PlayerKickEvent event = new PlayerKickEvent(this.craftServer.getPlayer(this.player), s, leaveMessage); + PlayerKickEvent event = new PlayerKickEvent(this.craftServer.getPlayer(this.player), reason, leaveMessage); // Paper - Adventure if (this.craftServer.getServer().isRunning()) { this.craftServer.getPluginManager().callEvent(event); @@ -413,8 +418,7 @@ public class ServerGamePacketListenerImpl implements ServerGamePacketListener { return; } // Send the possibly modified leave message - s = event.getReason(); - final Component ichatbasecomponent = CraftChatMessage.fromString(s, true)[0]; + final Component ichatbasecomponent = PaperAdventure.asVanilla(event.reason()); // Paper - Adventure // CraftBukkit end this.connection.send(new ClientboundDisconnectPacket(ichatbasecomponent), (future) -> { @@ -1631,9 +1635,11 @@ public class ServerGamePacketListenerImpl implements ServerGamePacketListener { */ this.player.disconnect(); - String quitMessage = this.server.getPlayerList().disconnect(this.player); - if ((quitMessage != null) && (quitMessage.length() > 0)) { - this.server.getPlayerList().sendMessage(CraftChatMessage.fromString(quitMessage)); + // Paper start - Adventure + net.kyori.adventure.text.Component quitMessage = this.server.getPlayerList().disconnect(this.player); + if ((quitMessage != null) && !quitMessage.equals(net.kyori.adventure.text.Component.empty())) { + this.server.getPlayerList().sendMessage(PaperAdventure.asVanilla(quitMessage)); + // Paper end } // CraftBukkit end TextFilter itextfilter = this.player.getTextFilter(); @@ -1849,8 +1855,13 @@ public class ServerGamePacketListenerImpl implements ServerGamePacketListener { this.handleCommand(s); } else if (this.player.getChatVisibility() == ChatVisiblity.SYSTEM) { // Do nothing, this is coming from a plugin - } else { - Player player = this.getPlayer(); + // Paper start + } else if (true) { + final ChatProcessor cp = new ChatProcessor(this.server, this.player, s, async); + cp.process(); + // Paper end + } else if (false) { // Paper + Player player = this.getPlayer(); // Paper AsyncPlayerChatEvent event = new AsyncPlayerChatEvent(async, player, s, new LazyPlayerSet(server)); this.craftServer.getPluginManager().callEvent(event); @@ -2668,21 +2679,20 @@ public class ServerGamePacketListenerImpl implements ServerGamePacketListener { return; } - // CraftBukkit start - Player player = this.craftServer.getPlayer(this.player); - int x = packetplayinupdatesign.getPos().getX(); - int y = packetplayinupdatesign.getPos().getY(); - int z = packetplayinupdatesign.getPos().getZ(); - String[] lines = new String[4]; + // CraftBukkit start // Paper start - Adventure + List lines = new java.util.ArrayList<>(); for (int i = 0; i < list.size(); ++i) { - lines[i] = ChatFormatting.stripFormatting(new TextComponent(ChatFormatting.stripFormatting((String) list.get(i))).getString()); + lines.add(net.kyori.adventure.text.Component.text(list.get(i))); } - SignChangeEvent event = new SignChangeEvent((org.bukkit.craftbukkit.block.CraftBlock) player.getWorld().getBlockAt(x, y, z), this.craftServer.getPlayer(this.player), lines); + SignChangeEvent event = new SignChangeEvent(org.bukkit.craftbukkit.block.CraftBlock.at(worldserver, blockposition), this.getPlayer(), lines); this.craftServer.getPluginManager().callEvent(event); if (!event.isCancelled()) { - System.arraycopy(org.bukkit.craftbukkit.block.CraftSign.sanitizeLines(event.getLines()), 0, tileentitysign.messages, 0, 4); + for (int i = 0; i < 4; i++) { + tileentitysign.setMessage(i, PaperAdventure.asVanilla(event.line(i))); + } + // Paper end tileentitysign.isEditable = false; } // CraftBukkit end diff --git a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java index a1dd76f49c59ed0a0b7f2b68fbd1a9a70a89128b..9dbb3bb79ae2de6635f71e5ee5bebeb5e57b624e 100644 --- a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java +++ b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java @@ -35,6 +35,7 @@ import net.minecraft.world.entity.player.Player; import org.apache.commons.lang3.Validate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import io.papermc.paper.adventure.PaperAdventure; // Paper import org.bukkit.craftbukkit.util.Waitable; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.PlayerPreLoginEvent; @@ -299,7 +300,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener if (PlayerPreLoginEvent.getHandlerList().getRegisteredListeners().length != 0) { final PlayerPreLoginEvent event = new PlayerPreLoginEvent(playerName, address, uniqueId); if (asyncEvent.getResult() != PlayerPreLoginEvent.Result.ALLOWED) { - event.disallow(asyncEvent.getResult(), asyncEvent.getKickMessage()); + event.disallow(asyncEvent.getResult(), asyncEvent.kickMessage()); // Paper - Adventure } Waitable waitable = new Waitable() { @Override @@ -310,12 +311,12 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener ServerLoginPacketListenerImpl.this.server.processQueue.add(waitable); if (waitable.get() != PlayerPreLoginEvent.Result.ALLOWED) { - disconnect(event.getKickMessage()); + disconnect(PaperAdventure.asVanilla(event.kickMessage())); // Paper - Adventure return; } } else { if (asyncEvent.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) { - disconnect(asyncEvent.getKickMessage()); + disconnect(PaperAdventure.asVanilla(asyncEvent.kickMessage())); // Paper - Adventure return; } } diff --git a/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java index de19aa66e7b6ddde17e9acf65643b4a71573d759..223df8d27c2ff1cbff634bca3dbde5cc24de7f98 100644 --- a/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java +++ b/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java @@ -55,7 +55,7 @@ public class ServerStatusPacketListenerImpl implements ServerStatusPacketListene CraftIconCache icon = server.server.getServerIcon(); ServerListPingEvent() { - super(((InetSocketAddress) connection.getRemoteAddress()).getAddress(), server.getMotd(), server.getPlayerList().getMaxPlayers()); + super(((InetSocketAddress) connection.getRemoteAddress()).getAddress(), server.server.motd(), server.getPlayerList().getMaxPlayers()); // Paper - Adventure } @Override diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java index 88af57699d7f9e45ad1366243049e4f3565703ff..8cdecaf2f63c78196e0c5046fe2431b40e072c8a 100644 --- a/src/main/java/net/minecraft/server/players/PlayerList.java +++ b/src/main/java/net/minecraft/server/players/PlayerList.java @@ -8,6 +8,7 @@ import com.mojang.authlib.GameProfile; import com.mojang.serialization.DataResult; import com.mojang.serialization.Dynamic; import io.netty.buffer.Unpooled; +import io.papermc.paper.adventure.PaperAdventure; import java.io.File; import java.net.SocketAddress; import java.text.SimpleDateFormat; @@ -83,6 +84,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; // CraftBukkit start +import io.papermc.paper.adventure.PaperAdventure; // Paper import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import net.minecraft.server.dedicated.DedicatedServer; @@ -251,7 +253,7 @@ public abstract class PlayerList { } // CraftBukkit start chatmessage.withStyle(ChatFormatting.YELLOW); - String joinMessage = CraftChatMessage.fromComponent(chatmessage); + Component joinMessage = chatmessage; // Paper - Adventure playerconnection.teleport(player.getX(), player.getY(), player.getZ(), player.yRot, player.xRot); this.players.add(player); @@ -260,19 +262,18 @@ public abstract class PlayerList { // this.sendAll(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, new EntityPlayer[]{entityplayer})); // CraftBukkit - replaced with loop below // CraftBukkit start - PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(cserver.getPlayer(player), joinMessage); + PlayerJoinEvent playerJoinEvent = new org.bukkit.event.player.PlayerJoinEvent(cserver.getPlayer(player), PaperAdventure.asAdventure(chatmessage)); // Paper - Adventure cserver.getPluginManager().callEvent(playerJoinEvent); if (!player.connection.connection.isConnected()) { return; } - joinMessage = playerJoinEvent.getJoinMessage(); + final net.kyori.adventure.text.Component jm = playerJoinEvent.joinMessage(); - if (joinMessage != null && joinMessage.length() > 0) { - for (Component line : org.bukkit.craftbukkit.util.CraftChatMessage.fromString(joinMessage)) { - server.getPlayerList().broadcastAll(new ClientboundChatPacket(line, ChatType.SYSTEM, Util.NIL_UUID)); - } + if (jm != null && !jm.equals(net.kyori.adventure.text.Component.empty())) { // Paper - Adventure + joinMessage = PaperAdventure.asVanilla(jm); // Paper - Adventure + server.getPlayerList().broadcastAll(new ClientboundChatPacket(joinMessage, ChatType.SYSTEM, Util.NIL_UUID)); // Paper - Adventure } // CraftBukkit end @@ -469,7 +470,7 @@ public abstract class PlayerList { } - public String disconnect(ServerPlayer entityplayer) { // CraftBukkit - return string + public net.kyori.adventure.text.Component disconnect(ServerPlayer entityplayer) { // Paper - return Component ServerLevel worldserver = entityplayer.getLevel(); entityplayer.awardStat(Stats.LEAVE_GAME); @@ -480,7 +481,7 @@ public abstract class PlayerList { entityplayer.closeContainer(); } - PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(cserver.getPlayer(entityplayer), "\u00A7e" + entityplayer.getScoreboardName() + " left the game"); + PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(cserver.getPlayer(entityplayer), net.kyori.adventure.text.Component.translatable("multiplayer.player.left", net.kyori.adventure.text.format.NamedTextColor.YELLOW, com.destroystokyo.paper.PaperConfig.useDisplayNameInQuit ? entityplayer.getBukkitEntity().displayName() : net.kyori.adventure.text.Component.text(entityplayer.getScoreboardName()))); cserver.getPluginManager().callEvent(playerQuitEvent); entityplayer.getBukkitEntity().disconnect(playerQuitEvent.getQuitMessage()); @@ -541,7 +542,7 @@ public abstract class PlayerList { cserver.getScoreboardManager().removePlayer(entityplayer.getBukkitEntity()); // CraftBukkit end - return playerQuitEvent.getQuitMessage(); // CraftBukkit + return playerQuitEvent.quitMessage(); // Paper - Adventure } // CraftBukkit start - Whole method, SocketAddress to LoginListener, added hostname to signature, return EntityPlayer @@ -587,10 +588,10 @@ public abstract class PlayerList { } // return chatmessage; - if (!gameprofilebanentry.hasExpired()) event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); // Spigot + if (!gameprofilebanentry.hasExpired()) event.disallow(PlayerLoginEvent.Result.KICK_BANNED, PaperAdventure.asAdventure(chatmessage)); // Spigot // Paper - Adventure } else if (!this.isWhiteListed(gameprofile)) { chatmessage = new TranslatableComponent("multiplayer.disconnect.not_whitelisted"); - event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, org.spigotmc.SpigotConfig.whitelistMessage); // Spigot + event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, PaperAdventure.LEGACY_SECTION_UXRC.deserialize(org.spigotmc.SpigotConfig.whitelistMessage)); // Spigot // Paper - Adventure } else if (getIpBans().isBanned(socketaddress) && !getIpBans().get(socketaddress).hasExpired()) { IpBanListEntry ipbanentry = this.ipBans.get(socketaddress); @@ -600,17 +601,17 @@ public abstract class PlayerList { } // return chatmessage; - event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(chatmessage)); + event.disallow(PlayerLoginEvent.Result.KICK_BANNED, PaperAdventure.asAdventure(chatmessage)); // Paper - Adventure } else { // return this.players.size() >= this.maxPlayers && !this.f(gameprofile) ? new ChatMessage("multiplayer.disconnect.server_full") : null; if (this.players.size() >= this.maxPlayers && !this.canBypassPlayerLimit(gameprofile)) { - event.disallow(PlayerLoginEvent.Result.KICK_FULL, org.spigotmc.SpigotConfig.serverFullMessage); // Spigot + event.disallow(PlayerLoginEvent.Result.KICK_FULL, PaperAdventure.LEGACY_SECTION_UXRC.deserialize(org.spigotmc.SpigotConfig.serverFullMessage)); // Spigot // Paper - Adventure } } cserver.getPluginManager().callEvent(event); if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) { - loginlistener.disconnect(event.getKickMessage()); + loginlistener.disconnect(PaperAdventure.asVanilla(event.kickMessage())); // Paper - Adventure return null; } return entity; @@ -1131,7 +1132,7 @@ public abstract class PlayerList { public void removeAll() { // CraftBukkit start - disconnect safely for (ServerPlayer player : this.players) { - player.connection.disconnect(this.server.server.getShutdownMessage()); // CraftBukkit - add custom shutdown message + player.connection.disconnect(this.server.server.shutdownMessage()); // CraftBukkit - add custom shutdown message // Paper - Adventure } // CraftBukkit end diff --git a/src/main/java/net/minecraft/world/BossEvent.java b/src/main/java/net/minecraft/world/BossEvent.java index 8718449abc08ed7795ac70c2bef12d15b94d4127..adb7c8db8e173801a83e5ff1f4cad0dda2abeb82 100644 --- a/src/main/java/net/minecraft/world/BossEvent.java +++ b/src/main/java/net/minecraft/world/BossEvent.java @@ -1,5 +1,6 @@ package net.minecraft.world; +import io.papermc.paper.adventure.PaperAdventure; import java.util.UUID; import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; @@ -14,6 +15,7 @@ public abstract class BossEvent { protected boolean darkenScreen; protected boolean playBossMusic; protected boolean createWorldFog; + public net.kyori.adventure.bossbar.BossBar adventure; // Paper public BossEvent(UUID uuid, Component name, BossEvent.BossBarColor color, BossEvent.BossBarOverlay style) { this.id = uuid; diff --git a/src/main/java/net/minecraft/world/item/ItemStack.java b/src/main/java/net/minecraft/world/item/ItemStack.java index 2a6a6e291efbd7cc8fed6532f18321bd141e1306..3faf52e7ac5e7e22d09cfb73cfda6b9f622137d4 100644 --- a/src/main/java/net/minecraft/world/item/ItemStack.java +++ b/src/main/java/net/minecraft/world/item/ItemStack.java @@ -865,6 +865,7 @@ public final class ItemStack { } // CraftBukkit end + public Component displayName() { return this.getDisplayName(); } // Paper - OBFHELPER public Component getDisplayName() { MutableComponent ichatmutablecomponent = (new TextComponent("")).append(this.getHoverName()); diff --git a/src/main/java/net/minecraft/world/item/enchantment/Enchantment.java b/src/main/java/net/minecraft/world/item/enchantment/Enchantment.java index 72367311f79e3ef2868c05b38bae98c5a9fb129c..c23ec1b31950471905c65e46273ae105de853d9b 100644 --- a/src/main/java/net/minecraft/world/item/enchantment/Enchantment.java +++ b/src/main/java/net/minecraft/world/item/enchantment/Enchantment.java @@ -94,6 +94,7 @@ public abstract class Enchantment { return this.getOrCreateDescriptionId(); } + public final Component getTranslationComponentForLevel(int level) { return this.getFullname(level); } // Paper - OBFHELPER public Component getFullname(int level) { TranslatableComponent chatmessage = new TranslatableComponent(this.getDescriptionId()); diff --git a/src/main/java/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java b/src/main/java/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java index 2cccec66fbc7114c65336769e354fe6f756c9fca..d44505b3ee2a35422568e9bce0d868191e348fc0 100644 --- a/src/main/java/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java +++ b/src/main/java/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java @@ -32,6 +32,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; // CraftBukkit start +import io.papermc.paper.adventure.PaperAdventure; // Paper import java.util.UUID; import org.bukkit.craftbukkit.CraftServer; @@ -473,7 +474,7 @@ public class MapItemSavedData extends SavedData { for ( org.bukkit.map.MapCursor cursor : render.cursors) { if (cursor.isVisible()) { - icons.add(new MapDecoration(MapDecoration.Type.byIcon(cursor.getRawType()), cursor.getX(), cursor.getY(), cursor.getDirection(), CraftChatMessage.fromStringOrNull(cursor.getCaption()))); + icons.add(new MapDecoration(MapDecoration.Type.byIcon(cursor.getRawType()), cursor.getX(), cursor.getY(), cursor.getDirection(), PaperAdventure.asVanilla(cursor.caption()))); // Paper - Adventure } } diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java index c4cf1394fe4c2782b1fea8b3653a817157d857eb..f7f5457d20586e0ba72368e64ff6025f6755e61e 100644 --- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java +++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java @@ -561,8 +561,10 @@ public final class CraftServer implements Server { } @Override + @Deprecated // Paper start public int broadcastMessage(String message) { - return broadcast(message, BROADCAST_CHANNEL_USERS); + return this.broadcast(message, BROADCAST_CHANNEL_USERS); + // Paper end } public Player getPlayer(final ServerPlayer entity) { @@ -1306,7 +1308,15 @@ public final class CraftServer implements Server { return configuration.getInt("settings.spawn-radius", -1); } + // Paper start @Override + public net.kyori.adventure.text.Component shutdownMessage() { + String msg = getShutdownMessage(); + return msg != null ? io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(msg) : null; + } + // Paper end + @Override + @Deprecated // Paper public String getShutdownMessage() { return configuration.getString("settings.shutdown-message"); } @@ -1422,7 +1432,20 @@ public final class CraftServer implements Server { } @Override + @Deprecated // Paper public int broadcast(String message, String permission) { + // Paper start - Adventure + return this.broadcast(io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(message), permission); + } + + @Override + public int broadcast(net.kyori.adventure.text.Component message) { + return this.broadcast(message, BROADCAST_CHANNEL_USERS); + } + + @Override + public int broadcast(net.kyori.adventure.text.Component message, String permission) { + // Paper end Set recipients = new HashSet<>(); for (Permissible permissible : getPluginManager().getPermissionSubscriptions(permission)) { if (permissible instanceof CommandSender && permissible.hasPermission(permission)) { @@ -1430,14 +1453,14 @@ public final class CraftServer implements Server { } } - BroadcastMessageEvent broadcastMessageEvent = new BroadcastMessageEvent(!Bukkit.isPrimaryThread(), message, recipients); + BroadcastMessageEvent broadcastMessageEvent = new BroadcastMessageEvent(!Bukkit.isPrimaryThread(), message, recipients); // Paper - Adventure getPluginManager().callEvent(broadcastMessageEvent); if (broadcastMessageEvent.isCancelled()) { return 0; } - message = broadcastMessageEvent.getMessage(); + message = broadcastMessageEvent.message(); // Paper - Adventure for (CommandSender recipient : recipients) { recipient.sendMessage(message); @@ -1663,6 +1686,14 @@ public final class CraftServer implements Server { return CraftInventoryCreator.INSTANCE.createInventory(owner, type); } + // Paper start + @Override + public Inventory createInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) { + Validate.isTrue(type.isCreatable(), "Cannot open an inventory of type ", type); + return CraftInventoryCreator.INSTANCE.createInventory(owner, type, title); + } + // Paper end + @Override public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { Validate.isTrue(type.isCreatable(), "Cannot open an inventory of type ", type); @@ -1675,13 +1706,28 @@ public final class CraftServer implements Server { return CraftInventoryCreator.INSTANCE.createInventory(owner, size); } + // Paper start + @Override + public Inventory createInventory(InventoryHolder owner, int size, net.kyori.adventure.text.Component title) throws IllegalArgumentException { + Validate.isTrue(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got " + size + ")"); + return CraftInventoryCreator.INSTANCE.createInventory(owner, size, title); + } + // Paper end + @Override public Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException { Validate.isTrue(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got " + size + ")"); return CraftInventoryCreator.INSTANCE.createInventory(owner, size, title); } + // Paper start + @Override + public Merchant createMerchant(net.kyori.adventure.text.Component title) { + return new org.bukkit.craftbukkit.inventory.CraftMerchantCustom(title == null ? InventoryType.MERCHANT.defaultTitle() : title); + } + // Paper end @Override + @Deprecated // Paper public Merchant createMerchant(String title) { return new CraftMerchantCustom(title == null ? InventoryType.MERCHANT.getDefaultTitle() : title); } @@ -1725,6 +1771,12 @@ public final class CraftServer implements Server { return Thread.currentThread().equals(console.serverThread) || console.hasStopped() || !org.spigotmc.AsyncCatcher.enabled; // All bets are off if we have shut down (e.g. due to watchdog) } + // Paper start + @Override + public net.kyori.adventure.text.Component motd() { + return io.papermc.paper.adventure.PaperAdventure.asAdventure(new net.minecraft.network.chat.TextComponent(console.getMotd())); + } + // Paper end @Override public String getMotd() { return console.getMotd(); @@ -2153,5 +2205,15 @@ public final class CraftServer implements Server { return null; } } + + // Paper start + private Iterable adventure$audiences; + @Override + public Iterable audiences() { + if (this.adventure$audiences == null) { + this.adventure$audiences = com.google.common.collect.Iterables.concat(java.util.Collections.singleton(this.getConsoleSender()), this.getOnlinePlayers()); + } + return this.adventure$audiences; + } // Paper end } diff --git a/src/main/java/org/bukkit/craftbukkit/Main.java b/src/main/java/org/bukkit/craftbukkit/Main.java index 05aedca561919a12ced1925c5cc9af585bb04523..ce9f10f890a5866ab6208c7253b15b09fe323a81 100644 --- a/src/main/java/org/bukkit/craftbukkit/Main.java +++ b/src/main/java/org/bukkit/craftbukkit/Main.java @@ -19,6 +19,12 @@ public class Main { public static boolean useConsole = true; public static void main(String[] args) { + // Paper start + final String warnWhenLegacyFormattingDetected = String.join(".", "net", "kyori", "adventure", "text", "warnWhenLegacyFormattingDetected"); + if (false && System.getProperty(warnWhenLegacyFormattingDetected) == null) { + System.setProperty(warnWhenLegacyFormattingDetected, String.valueOf(true)); + } + // Paper end // Todo: Installation script OptionParser parser = new OptionParser() { { diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java b/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java index 639577ab8b6467302a243c99ba5a4eede3aed655..940fef58f14e06213c7f305f67dcb8918976c03d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java @@ -70,6 +70,19 @@ public class CraftBeacon extends CraftBlockEntityState implem this.getSnapshot().secondaryPower = (effect != null) ? MobEffect.byId(effect.getId()) : null; } + // Paper start + @Override + public net.kyori.adventure.text.Component customName() { + final BeaconBlockEntity be = this.getSnapshot(); + return be.name != null ? io.papermc.paper.adventure.PaperAdventure.asAdventure(be.name) : null; + } + + @Override + public void customName(final net.kyori.adventure.text.Component customName) { + this.getSnapshot().setCustomName(customName != null ? io.papermc.paper.adventure.PaperAdventure.asVanilla(customName) : null); + } + // Paper end + @Override public String getCustomName() { BeaconBlockEntity beacon = this.getSnapshot(); diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java index 16a0f6e390a7415635e3573c1f79f7d78e5ef859..b1edc96d7e0444e72b79f190982de1d1bb5987f3 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java @@ -32,6 +32,19 @@ public abstract class CraftContainer extends this.getSnapshot().lockKey = (key == null) ? LockCode.NO_LOCK : new LockCode(key); } + // Paper start + @Override + public net.kyori.adventure.text.Component customName() { + final T be = this.getSnapshot(); + return be.hasCustomName() ? io.papermc.paper.adventure.PaperAdventure.asAdventure(be.getCustomName()) : null; + } + + @Override + public void customName(final net.kyori.adventure.text.Component customName) { + this.getSnapshot().setCustomName(customName != null ? io.papermc.paper.adventure.PaperAdventure.asVanilla(customName) : null); + } + // Paper end + @Override public String getCustomName() { T container = this.getSnapshot(); diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java b/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java index add5b68d5fbd887e3fc2d226eff9ab00ed01ce73..2c3d6ba06d876df168aae4cc09b7b4400e2fa33d 100644 --- a/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java +++ b/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java @@ -16,6 +16,19 @@ public class CraftEnchantingTable extends CraftBlockEntityState implements Sign { // Lazily initialized only if requested: - private String[] originalLines = null; - private String[] lines = null; + // Paper start + private java.util.ArrayList originalLines = null; // ArrayList for RandomAccess + private java.util.ArrayList lines = null; // ArrayList for RandomAccess + // Paper end public CraftSign(final Block block) { super(block, SignBlockEntity.class); @@ -23,27 +25,52 @@ public class CraftSign extends CraftBlockEntityState implements super(material, te); } + // Paper start @Override - public String[] getLines() { - if (lines == null) { - // Lazy initialization: - SignBlockEntity sign = this.getSnapshot(); - lines = new String[sign.messages.length]; - System.arraycopy(revertComponents(sign.messages), 0, lines, 0, lines.length); - originalLines = new String[lines.length]; - System.arraycopy(lines, 0, originalLines, 0, originalLines.length); + public java.util.List lines() { + this.loadLines(); + return this.lines; + } + + @Override + public net.kyori.adventure.text.Component line(int index) { + this.loadLines(); + return this.lines.get(index); + } + + @Override + public void line(int index, net.kyori.adventure.text.Component line) { + this.loadLines(); + this.lines.set(index, line); + } + + private void loadLines() { + if (lines != null) { + return; } - return lines; + + // Lazy initialization: + SignBlockEntity sign = this.getSnapshot(); + lines = io.papermc.paper.adventure.PaperAdventure.asAdventure(com.google.common.collect.Lists.newArrayList(sign.messages)); + originalLines = new java.util.ArrayList<>(lines); + } + // Paper end + @Override + public String[] getLines() { + this.loadLines(); + return this.lines.stream().map(io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC::serialize).toArray(String[]::new); // Paper } @Override public String getLine(int index) throws IndexOutOfBoundsException { - return getLines()[index]; + this.loadLines(); + return io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(this.lines.get(index)); // Paper } @Override public void setLine(int index, String line) throws IndexOutOfBoundsException { - getLines()[index] = line; + this.loadLines(); + this.lines.set(index, line != null ? io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(line) : net.kyori.adventure.text.Component.empty()); // Paper } @Override @@ -71,16 +98,32 @@ public class CraftSign extends CraftBlockEntityState implements super.applyTo(sign); if (lines != null) { - for (int i = 0; i < lines.length; i++) { - String line = (lines[i] == null) ? "" : lines[i]; - if (line.equals(originalLines[i])) { + // Paper start + for (int i = 0; i < this.lines.size(); ++i) { + net.kyori.adventure.text.Component component = this.lines.get(i); + net.kyori.adventure.text.Component origComp = this.originalLines.get(i); + if (component.equals(origComp)) { continue; // The line contents are still the same, skip. } - sign.messages[i] = CraftChatMessage.fromString(line)[0]; + sign.messages[i] = io.papermc.paper.adventure.PaperAdventure.asVanilla(component); } + // Paper end } } + // Paper start + public static Component[] sanitizeLines(java.util.List lines) { + Component[] components = new Component[4]; + for (int i = 0; i < 4; i++) { + if (i < lines.size() && lines.get(i) != null) { + components[i] = io.papermc.paper.adventure.PaperAdventure.asVanilla(lines.get(i)); + } else { + components[i] = new TextComponent(""); + } + } + return components; + } + // Paper end public static Component[] sanitizeLines(String[] lines) { Component[] components = new Component[4]; diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java index 089fe4a3458ed3106fa214f89a7004a5d3c6bb95..af986adfdb547cb61fbd52f0f89858f1a9e52cc3 100644 --- a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java +++ b/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java @@ -80,4 +80,11 @@ public class CraftConsoleCommandSender extends ServerCommandSender implements Co public boolean isConversing() { return conversationTracker.isConversing(); } + + // Paper start + @Override + public void sendMessage(final net.kyori.adventure.identity.Identity identity, final net.kyori.adventure.text.Component message, final net.kyori.adventure.audience.MessageType type) { + this.sendRawMessage(org.bukkit.craftbukkit.util.CraftChatMessage.fromComponent(io.papermc.paper.adventure.PaperAdventure.asVanilla(message))); + } + // Paper end } diff --git a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java b/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java index fd473d213f4050f420bd7d729fe0df757d5398bc..b1ffe6c7a5915f00a476e88f3a38349b740b4910 100644 --- a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java +++ b/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java @@ -187,6 +187,12 @@ public class CraftEnchantment extends Enchantment { CraftEnchantment ench = (CraftEnchantment) other; return !target.isCompatibleWith(ench.target); } + // Paper start + @Override + public net.kyori.adventure.text.Component displayName(int level) { + return io.papermc.paper.adventure.PaperAdventure.asAdventure(getHandle().getTranslationComponentForLevel(level)); + } + // Paper end public net.minecraft.world.item.enchantment.Enchantment getHandle() { return target; diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java index eb61c803cf74c5ca2c51d5027a02ed3db6b53096..53c231925ef1b17e48c5863570e3c54124874621 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java @@ -768,6 +768,19 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity { return getHandle().getVehicle().getBukkitEntity(); } + // Paper start + @Override + public net.kyori.adventure.text.Component customName() { + final Component name = this.getHandle().getCustomName(); + return name != null ? io.papermc.paper.adventure.PaperAdventure.asAdventure(name) : null; + } + + @Override + public void customName(final net.kyori.adventure.text.Component customName) { + this.getHandle().setCustomName(customName != null ? io.papermc.paper.adventure.PaperAdventure.asVanilla(customName) : null); + } + // Paper end + @Override public void setCustomName(String name) { // sane limit for name length diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java index 7c200e43bdc170ecf8b8fbfadd7bb38c66133443..b5c0f3d91cf451a972f0cf293db03a306073c493 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java @@ -317,9 +317,12 @@ public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity { container = CraftEventFactory.callInventoryOpenEvent(player, container); if (container == null) return; - String title = container.getBukkitView().getTitle(); + //String title = container.getBukkitView().getTitle(); // Paper - comment + net.kyori.adventure.text.Component adventure$title = container.getBukkitView().title(); // Paper + if (adventure$title == null) adventure$title = io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(container.getBukkitView().getTitle()); // Paper - player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); + //player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, windowType, CraftChatMessage.fromString(title)[0])); // Paper // Paper - comment + player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, io.papermc.paper.adventure.PaperAdventure.asVanilla(adventure$title))); // Paper getHandle().containerMenu = container; getHandle().containerMenu.addSlotListener(player); } @@ -388,8 +391,12 @@ public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity { // Now open the window MenuType windowType = CraftContainer.getNotchInventoryType(inventory.getTopInventory()); - String title = inventory.getTitle(); - player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); + + //String title = inventory.getTitle(); // Paper - comment + net.kyori.adventure.text.Component adventure$title = inventory.title(); // Paper + if (adventure$title == null) adventure$title = io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(inventory.getTitle()); // Paper + //player.playerConnection.sendPacket(new PacketPlayOutOpenWindow(container.windowId, windowType, CraftChatMessage.fromString(title)[0])); // Paper - comment + player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, io.papermc.paper.adventure.PaperAdventure.asVanilla(adventure$title))); // Paper player.containerMenu = container; player.containerMenu.addSlotListener(player); } diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java index 61e2d92471d1498eb97d42dc642605a2e00e6089..50d11611702e3d1f0e980fb8f2280b05b891167b 100644 --- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java +++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java @@ -238,14 +238,39 @@ public class CraftPlayer extends CraftHumanEntity implements Player { @Override public String getDisplayName() { + if(true) return io.papermc.paper.adventure.DisplayNames.getLegacy(this); // Paper return getHandle().displayName; } @Override public void setDisplayName(final String name) { + this.getHandle().adventure$displayName = name != null ? io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(name) : net.kyori.adventure.text.Component.text(this.getName()); // Paper getHandle().displayName = name == null ? getName() : name; } + // Paper start + @Override + public void playerListName(net.kyori.adventure.text.Component name) { + getHandle().listName = name == null ? null : io.papermc.paper.adventure.PaperAdventure.asVanilla(name); + for (ServerPlayer player : server.getHandle().players) { + if (player.getBukkitEntity().canSee(this)) { + player.connection.send(new ClientboundPlayerInfoPacket(ClientboundPlayerInfoPacket.Action.UPDATE_DISPLAY_NAME, getHandle())); + } + } + } + @Override + public net.kyori.adventure.text.Component playerListName() { + return getHandle().listName == null ? net.kyori.adventure.text.Component.text(getName()) : io.papermc.paper.adventure.PaperAdventure.asAdventure(getHandle().listName); + } + @Override + public net.kyori.adventure.text.Component playerListHeader() { + return playerListHeader; + } + @Override + public net.kyori.adventure.text.Component playerListFooter() { + return playerListFooter; + } + // Paper end @Override public String getPlayerListName() { return getHandle().listName == null ? getName() : CraftChatMessage.fromComponent(getHandle().listName); @@ -264,35 +289,35 @@ public class CraftPlayer extends CraftHumanEntity implements Player { } } - private Component playerListHeader; - private Component playerListFooter; + private net.kyori.adventure.text.Component playerListHeader; // Paper - Adventure + private net.kyori.adventure.text.Component playerListFooter; // Paper - Adventure @Override public String getPlayerListHeader() { - return (playerListHeader == null) ? null : CraftChatMessage.fromComponent(playerListHeader); + return (playerListHeader == null) ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(playerListHeader); // Paper - Adventure } @Override public String getPlayerListFooter() { - return (playerListFooter == null) ? null : CraftChatMessage.fromComponent(playerListFooter); + return (playerListFooter == null) ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(playerListFooter); // Paper - Adventure } @Override public void setPlayerListHeader(String header) { - this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true); + this.playerListHeader = header == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(header); // Paper - Adventure updatePlayerListHeaderFooter(); } @Override public void setPlayerListFooter(String footer) { - this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true); + this.playerListFooter = footer == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(footer); // Paper - Adventure updatePlayerListHeaderFooter(); } @Override public void setPlayerListHeaderFooter(String header, String footer) { - this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true); - this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true); + this.playerListHeader = header == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(header); // Paper - Adventure + this.playerListFooter = footer == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(footer); // Paper - Adventure updatePlayerListHeaderFooter(); } @@ -300,8 +325,8 @@ public class CraftPlayer extends CraftHumanEntity implements Player { if (getHandle().connection == null) return; ClientboundTabListPacket packet = new ClientboundTabListPacket(); - packet.header = (this.playerListHeader == null) ? new TextComponent("") : this.playerListHeader; - packet.footer = (this.playerListFooter == null) ? new TextComponent("") : this.playerListFooter; + packet.header = (this.playerListHeader == null) ? new TextComponent("") : io.papermc.paper.adventure.PaperAdventure.asVanilla(this.playerListHeader); // Paper - Adventure + packet.footer = (this.playerListFooter == null) ? new TextComponent("") : io.papermc.paper.adventure.PaperAdventure.asVanilla(this.playerListFooter); // Paper - Adventure getHandle().connection.send(packet); } @@ -333,6 +358,17 @@ public class CraftPlayer extends CraftHumanEntity implements Player { getHandle().connection.disconnect(message == null ? "" : message); } + // Paper start + @Override + public void kick(final net.kyori.adventure.text.Component message) { + org.spigotmc.AsyncCatcher.catchOp("player kick"); + final ServerGamePacketListenerImpl connection = this.getHandle().connection; + if (connection != null) { + connection.disconnect(message == null ? net.kyori.adventure.text.Component.empty() : message); + } + } + // Paper end + @Override public void setCompassTarget(Location loc) { if (getHandle().connection == null) return; @@ -559,6 +595,37 @@ public class CraftPlayer extends CraftHumanEntity implements Player { getHandle().connection.send(packet); } + // Paper start + @Override + public void sendSignChange(Location loc, List lines) { + this.sendSignChange(loc, lines, org.bukkit.DyeColor.BLACK); + } + @Override + public void sendSignChange(Location loc, List lines, DyeColor dyeColor) { + if (getHandle().connection == null) { + return; + } + if (lines == null) { + lines = new java.util.ArrayList<>(4); + } + Validate.notNull(loc, "Location cannot be null"); + Validate.notNull(dyeColor, "DyeColor cannot be null"); + if (lines.size() < 4) { + throw new IllegalArgumentException("Must have at least 4 lines"); + } + Component[] components = CraftSign.sanitizeLines(lines); + this.sendSignChange0(components, loc, dyeColor); + } + + private void sendSignChange0(Component[] components, Location loc, DyeColor dyeColor) { + SignBlockEntity sign = new SignBlockEntity(); + sign.setPosition(new BlockPos(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + sign.setColor(net.minecraft.world.item.DyeColor.byId(dyeColor.getWoolData())); + System.arraycopy(components, 0, sign.messages, 0, sign.messages.length); + + getHandle().connection.send(sign.getUpdatePacket()); + } + // Paper end @Override public void sendSignChange(Location loc, String[] lines) { sendSignChange(loc, lines, DyeColor.BLACK); @@ -581,12 +648,13 @@ public class CraftPlayer extends CraftHumanEntity implements Player { } Component[] components = CraftSign.sanitizeLines(lines); - SignBlockEntity sign = new SignBlockEntity(); - sign.setPosition(new BlockPos(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - sign.setColor(net.minecraft.world.item.DyeColor.byId(dyeColor.getWoolData())); - System.arraycopy(components, 0, sign.messages, 0, sign.messages.length); + /*TileEntitySign sign = new TileEntitySign(); // Paper + sign.setPosition(new BlockPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + sign.setColor(EnumColor.fromColorIndex(dyeColor.getWoolData())); + System.arraycopy(components, 0, sign.lines, 0, sign.lines.length); - getHandle().connection.send(sign.getUpdatePacket()); + getHandle().playerConnection.sendPacket(sign.getUpdatePacket());*/ // Paper + this.sendSignChange0(components, loc, dyeColor); // Paper } @Override @@ -1686,6 +1754,12 @@ public class CraftPlayer extends CraftHumanEntity implements Player { return (getHandle().clientViewDistance == null) ? Bukkit.getViewDistance() : getHandle().clientViewDistance; } + // Paper start + @Override + public java.util.Locale locale() { + return getHandle().adventure$locale; + } + // Paper end @Override public int getPing() { return getHandle().latency; @@ -1714,6 +1788,138 @@ public class CraftPlayer extends CraftHumanEntity implements Player { getInventory().setItemInMainHand(hand); } + // Paper start + @Override + public net.kyori.adventure.text.Component displayName() { + return this.getHandle().adventure$displayName; + } + + @Override + public void displayName(final net.kyori.adventure.text.Component displayName) { + this.getHandle().adventure$displayName = displayName != null ? displayName : net.kyori.adventure.text.Component.text(this.getName()); + this.getHandle().displayName = null; + } + + @Override + public void sendMessage(final net.kyori.adventure.identity.Identity identity, final net.kyori.adventure.text.Component message, final net.kyori.adventure.audience.MessageType type) { + final ClientboundChatPacket packet = new ClientboundChatPacket(null, type == net.kyori.adventure.audience.MessageType.CHAT ? net.minecraft.network.chat.ChatType.CHAT : net.minecraft.network.chat.ChatType.SYSTEM, identity.uuid()); + packet.adventure$message = message; + this.getHandle().connection.send(packet); + } + + @Override + public void sendActionBar(final net.kyori.adventure.text.Component message) { + final ClientboundSetTitlesPacket packet = new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.ACTIONBAR, null); + packet.adventure$text = message; + this.getHandle().connection.send(packet); + } + + @Override + public void sendPlayerListHeader(final net.kyori.adventure.text.Component header) { + this.playerListHeader = header; + this.adventure$sendPlayerListHeaderAndFooter(); + } + + @Override + public void sendPlayerListFooter(final net.kyori.adventure.text.Component footer) { + this.playerListFooter = footer; + this.adventure$sendPlayerListHeaderAndFooter(); + } + + @Override + public void sendPlayerListHeaderAndFooter(final net.kyori.adventure.text.Component header, final net.kyori.adventure.text.Component footer) { + this.playerListHeader = header; + this.playerListFooter = footer; + this.adventure$sendPlayerListHeaderAndFooter(); + } + + private void adventure$sendPlayerListHeaderAndFooter() { + final ServerGamePacketListenerImpl connection = this.getHandle().connection; + if (connection == null) return; + final ClientboundTabListPacket packet = new ClientboundTabListPacket(); + packet.adventure$header = (this.playerListHeader == null) ? net.kyori.adventure.text.Component.empty() : this.playerListHeader; + packet.adventure$footer = (this.playerListFooter == null) ? net.kyori.adventure.text.Component.empty() : this.playerListFooter; + connection.send(packet); + } + + @Override + public void showTitle(final net.kyori.adventure.title.Title title) { + final ServerGamePacketListenerImpl connection = this.getHandle().connection; + final net.kyori.adventure.title.Title.Times times = title.times(); + if (times != null) { + connection.send(new ClientboundSetTitlesPacket(ticks(times.fadeIn()), ticks(times.stay()), ticks(times.fadeOut()))); + } + final ClientboundSetTitlesPacket sp = new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.SUBTITLE, null); + sp.adventure$text = title.subtitle(); + connection.send(sp); + final ClientboundSetTitlesPacket tp = new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.TITLE, null); + tp.adventure$text = title.title(); + connection.send(tp); + } + + private static int ticks(final java.time.Duration duration) { + if (duration == null) { + return -1; + } + return (int) (duration.toMillis() / 50L); + } + + @Override + public void clearTitle() { + this.getHandle().connection.send(new ClientboundSetTitlesPacket(ClientboundSetTitlesPacket.Type.CLEAR, null)); + } + + // resetTitle implemented above + + @Override + public void showBossBar(final net.kyori.adventure.bossbar.BossBar bar) { + ((net.kyori.adventure.bossbar.HackyBossBarPlatformBridge) bar).paper$playerShow(this); + } + + @Override + public void hideBossBar(final net.kyori.adventure.bossbar.BossBar bar) { + ((net.kyori.adventure.bossbar.HackyBossBarPlatformBridge) bar).paper$playerHide(this); + } + + @Override + public void playSound(final net.kyori.adventure.sound.Sound sound) { + final Vec3 pos = this.getHandle().position(); + this.playSound(sound, pos.x, pos.y, pos.z); + } + + @Override + public void playSound(final net.kyori.adventure.sound.Sound sound, final double x, final double y, final double z) { + final ResourceLocation name = io.papermc.paper.adventure.PaperAdventure.asVanilla(sound.name()); + final java.util.Optional event = net.minecraft.core.Registry.SOUND_EVENT.getOptional(name); + if (event.isPresent()) { + this.getHandle().connection.send(new ClientboundSoundPacket(event.get(), io.papermc.paper.adventure.PaperAdventure.asVanilla(sound.source()), x, y, z, sound.volume(), sound.pitch())); + } else { + this.getHandle().connection.send(new ClientboundCustomSoundPacket(name, io.papermc.paper.adventure.PaperAdventure.asVanilla(sound.source()), new Vec3(x, y, z), sound.volume(), sound.pitch())); + } + } + + @Override + public void stopSound(final net.kyori.adventure.sound.SoundStop stop) { + this.getHandle().connection.send(new ClientboundStopSoundPacket( + io.papermc.paper.adventure.PaperAdventure.asVanillaNullable(stop.sound()), + io.papermc.paper.adventure.PaperAdventure.asVanillaNullable(stop.source()) + )); + } + + @Override + public void openBook(final net.kyori.adventure.inventory.Book book) { + final java.util.Locale locale = this.getHandle().adventure$locale; + final net.minecraft.world.item.ItemStack item = io.papermc.paper.adventure.PaperAdventure.asItemStack(book, locale); + final ServerPlayer player = this.getHandle(); + final ServerGamePacketListenerImpl connection = player.connection; + final net.minecraft.world.entity.player.Inventory inventory = player.inventory; + final int slot = inventory.items.size() + inventory.selected; + connection.send(new net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket(0, slot, item)); + connection.send(new net.minecraft.network.protocol.game.ClientboundOpenBookPacket(net.minecraft.world.InteractionHand.MAIN_HAND)); + connection.send(new net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket(0, slot, inventory.getSelected())); + } + // Paper end + // Spigot start private final Player.Spigot spigot = new Player.Spigot() { diff --git a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java b/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java index abd65693aca1964b65d091e633a36c97513c1d69..7fde1bb7587e567270e3f936381c6d361870211f 100644 --- a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java +++ b/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java @@ -776,9 +776,9 @@ public class CraftEventFactory { return event; } - public static PlayerDeathEvent callPlayerDeathEvent(ServerPlayer victim, List drops, String deathMessage, boolean keepInventory) { + public static PlayerDeathEvent callPlayerDeathEvent(ServerPlayer victim, List drops, net.kyori.adventure.text.Component deathMessage, String stringDeathMessage, boolean keepInventory) { // Paper - Adventure CraftPlayer entity = victim.getBukkitEntity(); - PlayerDeathEvent event = new PlayerDeathEvent(entity, drops, victim.getExpReward(), 0, deathMessage); + PlayerDeathEvent event = new PlayerDeathEvent(entity, drops, victim.getExpReward(), 0, deathMessage, stringDeathMessage); // Paper - Adventure event.setKeepInventory(keepInventory); org.bukkit.World world = entity.getWorld(); Bukkit.getServer().getPluginManager().callEvent(event); @@ -802,7 +802,7 @@ public class CraftEventFactory { * Server methods */ public static ServerListPingEvent callServerListPingEvent(Server craftServer, InetAddress address, String motd, int numPlayers, int maxPlayers) { - ServerListPingEvent event = new ServerListPingEvent(address, motd, numPlayers, maxPlayers); + ServerListPingEvent event = new ServerListPingEvent(address, craftServer.motd(), numPlayers, maxPlayers); // Paper - Adventure craftServer.getPluginManager().callEvent(event); return event; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java index a393bdae6ef588289c8814a1896146a993c92e71..680c7818a7097355158eb76662ecebbae6dd6637 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java @@ -1,6 +1,5 @@ package org.bukkit.craftbukkit.inventory; -import net.minecraft.network.chat.TextComponent; import net.minecraft.network.protocol.game.ClientboundOpenScreenPacket; import net.minecraft.world.Container; import net.minecraft.world.entity.player.Player; @@ -38,6 +37,7 @@ public class CraftContainer extends AbstractContainerMenu { private final InventoryView view; private InventoryType cachedType; + private net.kyori.adventure.text.Component adventure$title; // Paper private String cachedTitle; private AbstractContainerMenu delegate; private final int cachedSize; @@ -49,7 +49,9 @@ public class CraftContainer extends AbstractContainerMenu { Container top = ((CraftInventory) view.getTopInventory()).getInventory(); net.minecraft.world.entity.player.Inventory bottom = (net.minecraft.world.entity.player.Inventory) ((CraftInventory) view.getBottomInventory()).getInventory(); cachedType = view.getType(); - cachedTitle = view.getTitle(); + this.adventure$title = view.title(); // Paper + if (this.adventure$title == null) this.adventure$title = io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(view.getTitle()); // Paper + //cachedTitle = view.getTitle(); // Paper - comment cachedSize = getSize(); setupSlots(top, bottom, player); } @@ -76,6 +78,13 @@ public class CraftContainer extends AbstractContainerMenu { return inventory.getType(); } + // Paper start + @Override + public net.kyori.adventure.text.Component title() { + return inventory instanceof CraftInventoryCustom ? ((CraftInventoryCustom.MinecraftInventory) ((CraftInventory) inventory).getInventory()).title() : net.kyori.adventure.text.Component.text(inventory.getType().getDefaultTitle()); + } + // Paper end + @Override public String getTitle() { return inventory instanceof CraftInventoryCustom ? ((CraftInventoryCustom.MinecraftInventory) ((CraftInventory) inventory).getInventory()).getTitle() : inventory.getType().getDefaultTitle(); @@ -94,7 +103,8 @@ public class CraftContainer extends AbstractContainerMenu { @Override public boolean isSynched(Player player) { - if (cachedType == view.getType() && cachedSize == getSize() && cachedTitle.equals(view.getTitle())) { + if (cachedType == view.getType() && cachedSize == getSize() && this.adventure$title.equals(view.title())) { // Paper + //if (cachedType == view.getType() && cachedSize == getSize() && cachedTitle.equals(view.getTitle())) { // Paper - comment return true; } // If the window type has changed for some reason, update the player @@ -102,7 +112,9 @@ public class CraftContainer extends AbstractContainerMenu { // as good a place as any to put something like this. boolean typeChanged = (cachedType != view.getType()); cachedType = view.getType(); - cachedTitle = view.getTitle(); + this.adventure$title = view.title(); // Paper + if (this.adventure$title == null) this.adventure$title = io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(view.getTitle()); // Paper + //cachedTitle = view.getTitle(); // Paper - comment if (view.getPlayer() instanceof CraftPlayer) { CraftPlayer player1 = (CraftPlayer) view.getPlayer(); MenuType type = getNotchInventoryType(view.getTopInventory()); @@ -114,7 +126,8 @@ public class CraftContainer extends AbstractContainerMenu { setupSlots(top, bottom, player1.getHandle()); } int size = getSize(); - player1.getHandle().connection.send(new ClientboundOpenScreenPacket(this.containerId, type, new TextComponent(cachedTitle))); + player1.getHandle().connection.send(new ClientboundOpenScreenPacket(this.containerId, type, io.papermc.paper.adventure.PaperAdventure.asVanilla(this.adventure$title))); // Paper + //player.getHandle().playerConnection.sendPacket(new PacketPlayOutOpenWindow(this.windowId, type, new ChatComponentText(cachedTitle))); // Paper - comment player1.updateInventory(); } return true; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java index 397cd9651381a8a0ddb4ca173690e9b80428b182..46805a25c0273b76c19a3bbd40078d78c5379f43 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java @@ -19,6 +19,12 @@ public class CraftInventoryCustom extends CraftInventory { super(new MinecraftInventory(owner, type)); } + // Paper start + public CraftInventoryCustom(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) { + super(new MinecraftInventory(owner, type, title)); + } + // Paper end + public CraftInventoryCustom(InventoryHolder owner, InventoryType type, String title) { super(new MinecraftInventory(owner, type, title)); } @@ -27,6 +33,12 @@ public class CraftInventoryCustom extends CraftInventory { super(new MinecraftInventory(owner, size)); } + // Paper start + public CraftInventoryCustom(InventoryHolder owner, int size, net.kyori.adventure.text.Component title) { + super(new MinecraftInventory(owner, size, title)); + } + // Paper end + public CraftInventoryCustom(InventoryHolder owner, int size, String title) { super(new MinecraftInventory(owner, size, title)); } @@ -36,9 +48,17 @@ public class CraftInventoryCustom extends CraftInventory { private int maxStack = MAX_STACK; private final List viewers; private final String title; + private final net.kyori.adventure.text.Component adventure$title; // Paper private InventoryType type; private final InventoryHolder owner; + // Paper start + public MinecraftInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) { + this(owner, type.getDefaultSize(), title); + this.type = type; + } + // Paper end + public MinecraftInventory(InventoryHolder owner, InventoryType type) { this(owner, type.getDefaultSize(), type.getDefaultTitle()); this.type = type; @@ -57,11 +77,24 @@ public class CraftInventoryCustom extends CraftInventory { Validate.notNull(title, "Title cannot be null"); this.items = NonNullList.a(size, ItemStack.EMPTY); this.title = title; + this.adventure$title = io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(title); this.viewers = new ArrayList(); this.owner = owner; this.type = InventoryType.CHEST; } + // Paper start + public MinecraftInventory(final InventoryHolder owner, final int size, final net.kyori.adventure.text.Component title) { + Validate.notNull(title, "Title cannot be null"); + this.items = NonNullList.a(size, ItemStack.EMPTY); + this.title = io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(title); + this.adventure$title = title; + this.viewers = new ArrayList(); + this.owner = owner; + this.type = InventoryType.CHEST; + } + // Paper end + @Override public int getContainerSize() { return items.size(); @@ -183,6 +216,12 @@ public class CraftInventoryCustom extends CraftInventory { return null; } + // Paper start + public net.kyori.adventure.text.Component title() { + return this.adventure$title; + } + // Paper end + public String getTitle() { return title; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java index 326e8eb49e67ccfbf8f9b23bd6f03ea3576b9d35..945a80ca026c12e16a7ac5bebe56f846a437f847 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java @@ -64,6 +64,13 @@ public class CraftInventoryView extends InventoryView { return CraftItemStack.asCraftMirror(container.getSlot(slot).getItem()); } + // Paper start + @Override + public net.kyori.adventure.text.Component title() { + return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.container.getTitle()); + } + // Paper end + @Override public String getTitle() { return CraftChatMessage.fromComponent(container.getTitle()); diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java index 89a3617068421bb86baf4e8bfd9df2d0626adff7..32fa5ca0df07466e40817341d85d359b282f3078 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java @@ -334,4 +334,17 @@ public final class CraftItemFactory implements ItemFactory { public Material updateMaterial(ItemMeta meta, Material material) throws IllegalArgumentException { return ((CraftMetaItem) meta).updateMaterial(material); } + + // Paper start + @Override + public net.kyori.adventure.text.event.HoverEvent asHoverEvent(final ItemStack item, final java.util.function.UnaryOperator op) { + final net.minecraft.nbt.CompoundTag tag = CraftItemStack.asNMSCopy(item).getTag(); + return net.kyori.adventure.text.event.HoverEvent.showItem(op.apply(net.kyori.adventure.text.event.HoverEvent.ShowItem.of(item.getType().getKey(), item.getAmount(), io.papermc.paper.adventure.PaperAdventure.asBinaryTagHolder(tag)))); + } + + @Override + public net.kyori.adventure.text.@org.jetbrains.annotations.NotNull Component displayName(@org.jetbrains.annotations.NotNull ItemStack itemStack) { + return io.papermc.paper.adventure.PaperAdventure.asAdventure(CraftItemStack.asNMSCopy(itemStack).displayName()); + } + // Paper end } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java index 71136bb009d6c8c92595f957ee7680a771ea9a63..306c6483708ae1b41bd16f122d36beec1916a776 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java @@ -14,10 +14,17 @@ import org.apache.commons.lang.Validate; public class CraftMerchantCustom extends CraftMerchant { + @Deprecated // Paper - Adventure public CraftMerchantCustom(String title) { super(new MinecraftMerchant(title)); getMerchant().craftMerchant = this; } + // Paper start + public CraftMerchantCustom(net.kyori.adventure.text.Component title) { + super(new MinecraftMerchant(title)); + getMerchant().craftMerchant = this; + } + // Paper end @Override public String toString() { @@ -37,10 +44,17 @@ public class CraftMerchantCustom extends CraftMerchant { private Level tradingWorld; protected CraftMerchant craftMerchant; + @Deprecated // Paper - Adventure public MinecraftMerchant(String title) { Validate.notNull(title, "Title cannot be null"); this.title = new TextComponent(title); } + // Paper start + public MinecraftMerchant(net.kyori.adventure.text.Component title) { + Validate.notNull(title, "Title cannot be null"); + this.title = io.papermc.paper.adventure.PaperAdventure.asVanilla(title); + } + // Paper end @Override public CraftMerchant getCraftMerchant() { diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java index 6dba12c4f58a462c8d466461eb8b804dd045766d..a592d4a286a775a61192dde2a4d21a0681090415 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java @@ -1,8 +1,9 @@ package org.bukkit.craftbukkit.inventory; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Lists; + +import com.google.common.collect.ImmutableMap; // Paper import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -17,9 +18,12 @@ import org.bukkit.craftbukkit.util.CraftChatMessage; import org.bukkit.craftbukkit.util.CraftMagicNumbers; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.BookMeta.Generation; +import org.checkerframework.checker.nullness.qual.NonNull; // Spigot start import static org.spigotmc.ValidateUtils.*; + +import BookMetaBuilder; import java.util.AbstractList; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.chat.ComponentSerializer; @@ -269,6 +273,141 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta { this.generation = (generation == null) ? null : generation.ordinal(); } + // Paper start + @Override + public net.kyori.adventure.text.Component title() { + return this.title == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(this.title); + } + + @Override + public org.bukkit.inventory.meta.BookMeta title(net.kyori.adventure.text.Component title) { + this.setTitle(title == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(title)); + return this; + } + + @Override + public net.kyori.adventure.text.Component author() { + return this.author == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(this.author); + } + + @Override + public org.bukkit.inventory.meta.BookMeta author(net.kyori.adventure.text.Component author) { + this.setAuthor(author == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(author)); + return this; + } + + @Override + public net.kyori.adventure.text.Component page(final int page) { + Validate.isTrue(isValidPage(page), "Invalid page number"); + return this instanceof CraftMetaBookSigned ? net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson().deserialize(pages.get(page - 1)) : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(pages.get(page - 1)); + } + + @Override + public void page(final int page, net.kyori.adventure.text.Component data) { + if (!isValidPage(page)) { + throw new IllegalArgumentException("Invalid page number " + page + "/" + pages.size()); + } + if (data == null) { + data = net.kyori.adventure.text.Component.empty(); + } + pages.set(page - 1, this instanceof CraftMetaBookSigned ? net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson().serialize(data) : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(data)); + } + + @Override + public List pages() { + if (this.pages == null) return ImmutableList.of(); + if (this instanceof CraftMetaBookSigned) + return pages.stream().map(net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson()::deserialize).collect(ImmutableList.toImmutableList()); + else + return pages.stream().map(io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC::deserialize).collect(ImmutableList.toImmutableList()); + } + + @Override + public BookMeta pages(List pages) { + if (this.pages != null) this.pages.clear(); + for (net.kyori.adventure.text.Component page : pages) { + addPages(page); + } + return this; + } + + @Override + public BookMeta pages(net.kyori.adventure.text.Component... pages) { + if (this.pages != null) this.pages.clear(); + addPages(pages); + return this; + } + + @Override + public void addPages(net.kyori.adventure.text.Component... pages) { + if (this.pages == null) this.pages = new ArrayList<>(); + for (net.kyori.adventure.text.Component page : pages) { + if (this.pages.size() >= MAX_PAGES) { + return; + } + + if (page == null) { + page = net.kyori.adventure.text.Component.empty(); + } + + this.pages.add(this instanceof CraftMetaBookSigned ? net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson().serialize(page) : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(page)); + } + } + + private CraftMetaBook(net.kyori.adventure.text.Component title, net.kyori.adventure.text.Component author, List pages) { + super((org.bukkit.craftbukkit.inventory.CraftMetaItem) org.bukkit.Bukkit.getItemFactory().getItemMeta(org.bukkit.Material.WRITABLE_BOOK)); + this.title = title == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(title); + this.author = author == null ? null : io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.serialize(author); + this.pages = pages.subList(0, Math.min(MAX_PAGES, pages.size())).stream().map(io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC::serialize).collect(java.util.stream.Collectors.toList()); + } + + static final class CraftMetaBookBuilder implements BookMetaBuilder { + private net.kyori.adventure.text.Component title = null; + private net.kyori.adventure.text.Component author = null; + private final List pages = new java.util.ArrayList<>(); + + @Override + public BookMetaBuilder title(net.kyori.adventure.text.Component title) { + this.title = title; + return this; + } + + @Override + public BookMetaBuilder author(net.kyori.adventure.text.Component author) { + this.author = author; + return this; + } + + @Override + public BookMetaBuilder addPage(net.kyori.adventure.text.Component page) { + this.pages.add(page); + return this; + } + + @Override + public BookMetaBuilder pages(net.kyori.adventure.text.Component... pages) { + java.util.Collections.addAll(this.pages, pages); + return this; + } + + @Override + public BookMetaBuilder pages(java.util.Collection pages) { + this.pages.addAll(pages); + return this; + } + + @Override + public BookMeta build() { + return new CraftMetaBook(title, author, pages); + } + } + + @Override + public BookMetaBuilder toBuilder() { + return new CraftMetaBookBuilder(); + } + + // Paper end @Override public String getPage(final int page) { Validate.isTrue(isValidPage(page), "Invalid page number"); @@ -413,7 +552,7 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta { } @Override - Builder serialize(Builder builder) { + ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); if (hasTitle()) { diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java index 00445fc7373c70f4cecc4114f9bcfb4b6f27c0e8..0cf60eb9b6ba1a79c9b603c4349debd478101f9a 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java @@ -1,6 +1,6 @@ package org.bukkit.craftbukkit.inventory; -import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.ImmutableMap; // Paper import java.util.Map; import net.minecraft.nbt.CompoundTag; import org.bukkit.Material; @@ -84,7 +84,7 @@ class CraftMetaBookSigned extends CraftMetaBook implements BookMeta { } @Override - Builder serialize(Builder builder) { + ImmutableMap.Builder serialize(ImmutableMap.Builder builder) { super.serialize(builder); return builder; } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java index 2e819849e83967d751f7b0612a7cf4edb5a7264b..cca04daf84e506382365c0ba945cb024bd4d4475 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java @@ -744,6 +744,18 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { return !(hasDisplayName() || hasLocalizedName() || hasEnchants() || (lore != null) || hasCustomModelData() || hasBlockData() || hasRepairCost() || !unhandledTags.isEmpty() || !persistentDataContainer.isEmpty() || hideFlag != 0 || isUnbreakable() || hasDamage() || hasAttributeModifiers()); } + // Paper start + @Override + public net.kyori.adventure.text.Component displayName() { + return displayName == null ? null : net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson().deserialize(displayName); + } + + @Override + public void displayName(final net.kyori.adventure.text.Component displayName) { + this.displayName = displayName == null ? null : net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson().serialize(displayName); + } + // Paper end + @Override public String getDisplayName() { return CraftChatMessage.fromJSONComponent(displayName); @@ -779,6 +791,18 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta { return this.lore != null && !this.lore.isEmpty(); } + // Paper start + @Override + public List lore() { + return this.lore != null ? io.papermc.paper.adventure.PaperAdventure.asAdventureFromJson(this.lore) : null; + } + + @Override + public void lore(final List lore) { + this.lore = lore != null ? io.papermc.paper.adventure.PaperAdventure.asJson(lore) : null; + } + // Paper end + @Override public boolean hasRepairCost() { return repairCost > 0; diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftCustomInventoryConverter.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftCustomInventoryConverter.java index ed4415f6dd588c08c922efd5beebb3b124beb9d6..78a7ac47f20e84ccd67ff44d0bc7a2f2faa0d476 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftCustomInventoryConverter.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftCustomInventoryConverter.java @@ -12,6 +12,13 @@ public class CraftCustomInventoryConverter implements CraftInventoryCreator.Inve return new CraftInventoryCustom(holder, type); } + // Paper start + @Override + public Inventory createInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) { + return new CraftInventoryCustom(owner, type, title); + } + // Paper end + @Override public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { return new CraftInventoryCustom(owner, type, title); @@ -21,6 +28,12 @@ public class CraftCustomInventoryConverter implements CraftInventoryCreator.Inve return new CraftInventoryCustom(owner, size); } + // Paper start + public Inventory createInventory(InventoryHolder owner, int size, net.kyori.adventure.text.Component title) { + return new CraftInventoryCustom(owner, size, title); + } + // Paper end + public Inventory createInventory(InventoryHolder owner, int size, String title) { return new CraftInventoryCustom(owner, size, title); } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java index b51321c8dd70a90ab149f456c7ffb4587c4fbd34..94d807c5d09f165c6eedd0a1c4026c2b833806a0 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java @@ -43,6 +43,17 @@ public final class CraftInventoryCreator { return converterMap.get(type).createInventory(holder, type); } + // Paper start + public Inventory createInventory(InventoryHolder holder, InventoryType type, net.kyori.adventure.text.Component title) { + // Paper start + if (holder != null) { + return DEFAULT_CONVERTER.createInventory(holder, type, title); + } + //noinspection ConstantConditions // Paper end + return converterMap.get(type).createInventory(holder, type, title); + } + // Paper end + public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { return converterMap.get(type).createInventory(holder, type, title); } @@ -51,6 +62,12 @@ public final class CraftInventoryCreator { return DEFAULT_CONVERTER.createInventory(holder, size); } + // Paper start + public Inventory createInventory(InventoryHolder holder, int size, net.kyori.adventure.text.Component title) { + return DEFAULT_CONVERTER.createInventory(holder, size, title); + } + // Paper end + public Inventory createInventory(InventoryHolder holder, int size, String title) { return DEFAULT_CONVERTER.createInventory(holder, size, title); } @@ -59,6 +76,10 @@ public final class CraftInventoryCreator { Inventory createInventory(InventoryHolder holder, InventoryType type); + // Paper start + Inventory createInventory(InventoryHolder holder, InventoryType type, net.kyori.adventure.text.Component title); + // Paper end + Inventory createInventory(InventoryHolder holder, InventoryType type, String title); } } diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java index 0395a6235d62126540e370d6ef77e6966c50ca1d..3ef9742a68084d159ea8ed5709298f9863e04a67 100644 --- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java +++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java @@ -31,6 +31,18 @@ public abstract class CraftTileInventoryConverter implements CraftInventoryCreat return getInventory(getTileEntity()); } + // Paper start + @Override + public Inventory createInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) { + Container te = getTileEntity(); + if (te instanceof RandomizableContainerBlockEntity) { + ((RandomizableContainerBlockEntity) te).setCustomName(io.papermc.paper.adventure.PaperAdventure.asVanilla(title)); + } + + return getInventory(te); + } + // Paper end + @Override public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { Container te = getTileEntity(); @@ -54,6 +66,15 @@ public abstract class CraftTileInventoryConverter implements CraftInventoryCreat return furnace; } + // Paper start + @Override + public Inventory createInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) { + Container tileEntity = getTileEntity(); + ((AbstractFurnaceBlockEntity) tileEntity).setCustomName(io.papermc.paper.adventure.PaperAdventure.asVanilla(title)); + return getInventory(tileEntity); + } + // Paper end + @Override public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) { Container tileEntity = getTileEntity(); @@ -74,6 +95,18 @@ public abstract class CraftTileInventoryConverter implements CraftInventoryCreat return new BrewingStandBlockEntity(); } + // Paper start + @Override + public Inventory createInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) { + // BrewingStand does not extend TileEntityLootable + Container tileEntity = getTileEntity(); + if (tileEntity instanceof BrewingStandBlockEntity) { + ((BrewingStandBlockEntity) tileEntity).setCustomName(io.papermc.paper.adventure.PaperAdventure.asVanilla(title)); + } + return getInventory(tileEntity); + } + // Paper end + @Override public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) { // BrewingStand does not extend TileEntityLootable diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java index d5ebb11447a8effa41138a13874fd3e5246dfe71..96ba508c87336d012c1ed5aa982588f55782a2fe 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java @@ -30,6 +30,21 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective return objective.getName(); } + // Paper start + @Override + public net.kyori.adventure.text.Component displayName() throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + return io.papermc.paper.adventure.PaperAdventure.asAdventure(objective.getDisplayName()); + } + @Override + public void displayName(net.kyori.adventure.text.Component displayName) throws IllegalStateException, IllegalArgumentException { + if (displayName == null) { + displayName = net.kyori.adventure.text.Component.empty(); + } + CraftScoreboard scoreboard = checkState(); + objective.setDisplayName(io.papermc.paper.adventure.PaperAdventure.asVanilla(displayName)); + } + // Paper end @Override public String getDisplayName() throws IllegalStateException { CraftScoreboard scoreboard = checkState(); diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java index af160d3bdb82f07c6c836a438b8ab37b803c29e2..4c93be31fd95d731327479519ecb34a08785c1ca 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java @@ -27,6 +27,27 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { public CraftObjective registerNewObjective(String name, String criteria) throws IllegalArgumentException { return registerNewObjective(name, criteria, name); } + // Paper start + @Override + public CraftObjective registerNewObjective(String name, String criteria, net.kyori.adventure.text.Component displayName) { + return registerNewObjective(name, criteria, displayName, org.bukkit.scoreboard.RenderType.INTEGER); + } + @Override + public CraftObjective registerNewObjective(String name, String criteria, net.kyori.adventure.text.Component displayName, RenderType renderType) { + if (displayName == null) { + displayName = net.kyori.adventure.text.Component.empty(); + } + Validate.notNull(name, "Objective name cannot be null"); + Validate.notNull(criteria, "Criteria cannot be null"); + Validate.notNull(displayName, "Display name cannot be null"); + Validate.notNull(renderType, "RenderType cannot be null"); + Validate.isTrue(name.length() <= 16, "The name '" + name + "' is longer than the limit of 16 characters"); + Validate.isTrue(board.getObjective(name) == null, "An objective of name '" + name + "' already exists"); + CraftCriteria craftCriteria = CraftCriteria.getFromBukkit(criteria); + net.minecraft.world.scores.Objective objective = board.registerObjective(name, craftCriteria.criteria, io.papermc.paper.adventure.PaperAdventure.asVanilla(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType)); + return new CraftObjective(this, objective); + } + // Paper end @Override public CraftObjective registerNewObjective(String name, String criteria, String displayName) throws IllegalArgumentException { @@ -35,7 +56,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { @Override public CraftObjective registerNewObjective(String name, String criteria, String displayName, RenderType renderType) throws IllegalArgumentException { - Validate.notNull(name, "Objective name cannot be null"); + /*Validate.notNull(name, "Objective name cannot be null"); // Paper Validate.notNull(criteria, "Criteria cannot be null"); Validate.notNull(displayName, "Display name cannot be null"); Validate.notNull(renderType, "RenderType cannot be null"); @@ -44,8 +65,9 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard { Validate.isTrue(board.getObjective(name) == null, "An objective of name '" + name + "' already exists"); CraftCriteria craftCriteria = CraftCriteria.getFromBukkit(criteria); - net.minecraft.world.scores.Objective objective = board.registerObjective(name, craftCriteria.criteria, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType)); - return new CraftObjective(this, objective); + ScoreboardObjective objective = board.registerObjective(name, craftCriteria.criteria, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType)); + return new CraftObjective(this, objective);*/ // Paper + return registerNewObjective(name, criteria, io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC.deserialize(displayName), renderType); // Paper } @Override diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java index f5237ff19d8b26be0b762659ad0ea6887205b3f9..7ebcba4ada42f5599d56cfdeb75dbf62f2a09b78 100644 --- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java +++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java @@ -28,6 +28,55 @@ final class CraftTeam extends CraftScoreboardComponent implements Team { return team.getName(); } + // Paper start + @Override + public net.kyori.adventure.text.Component displayName() throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + return io.papermc.paper.adventure.PaperAdventure.asAdventure(team.getDisplayName()); + } + @Override + public void displayName(net.kyori.adventure.text.Component displayName) throws IllegalStateException, IllegalArgumentException { + if (displayName == null) displayName = net.kyori.adventure.text.Component.empty(); + CraftScoreboard scoreboard = checkState(); + team.setDisplayName(io.papermc.paper.adventure.PaperAdventure.asVanilla(displayName)); + } + @Override + public net.kyori.adventure.text.Component prefix() throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + return io.papermc.paper.adventure.PaperAdventure.asAdventure(team.getPlayerPrefix()); + } + @Override + public void prefix(net.kyori.adventure.text.Component prefix) throws IllegalStateException, IllegalArgumentException { + if (prefix == null) prefix = net.kyori.adventure.text.Component.empty(); + CraftScoreboard scoreboard = checkState(); + team.setPlayerPrefix(io.papermc.paper.adventure.PaperAdventure.asVanilla(prefix)); + } + @Override + public net.kyori.adventure.text.Component suffix() throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + return io.papermc.paper.adventure.PaperAdventure.asAdventure(team.getPlayerSuffix()); + } + @Override + public void suffix(net.kyori.adventure.text.Component suffix) throws IllegalStateException, IllegalArgumentException { + if (suffix == null) suffix = net.kyori.adventure.text.Component.empty(); + CraftScoreboard scoreboard = checkState(); + team.setPlayerSuffix(io.papermc.paper.adventure.PaperAdventure.asVanilla(suffix)); + } + @Override + public net.kyori.adventure.text.format.TextColor color() throws IllegalStateException { + CraftScoreboard scoreboard = checkState(); + if (team.getColor().getHexValue() == null) throw new IllegalStateException("Team colors must have hex values"); + net.kyori.adventure.text.format.TextColor color = net.kyori.adventure.text.format.TextColor.color(team.getColor().getHexValue()); + if (!(color instanceof net.kyori.adventure.text.format.NamedTextColor)) throw new IllegalStateException("Team doesn't have a NamedTextColor"); + return (net.kyori.adventure.text.format.NamedTextColor) color; + } + @Override + public void color(net.kyori.adventure.text.format.NamedTextColor color) { + if (color == null) color = net.kyori.adventure.text.format.NamedTextColor.WHITE; + CraftScoreboard scoreboard = checkState(); + team.setColor(io.papermc.paper.adventure.PaperAdventure.asVanilla(color)); + } + // Paper end @Override public String getDisplayName() throws IllegalStateException { diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java index 35e6ce5f33b3d6b86c3654e6a207e26aa44badb5..b27af66795d902a2e95d692fa0ff18eccbef8a75 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java @@ -290,6 +290,7 @@ public final class CraftChatMessage { public static String fromComponent(Component component) { if (component == null) return ""; + if (component instanceof io.papermc.paper.adventure.AdventureComponent) component = ((io.papermc.paper.adventure.AdventureComponent) component).deepConverted(); StringBuilder out = new StringBuilder(); boolean hadFormat = false; diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java index ef7715774fbdc4c42b217d8192784e09a43fe66f..2d4faef5a2b9c4fe8b65ff4f1346b8375e0e02c8 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java +++ b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java @@ -57,6 +57,33 @@ public final class CraftMagicNumbers implements UnsafeValues { private CraftMagicNumbers() {} + // Paper start + @Override + public net.kyori.adventure.text.flattener.ComponentFlattener componentFlattener() { + return io.papermc.paper.adventure.PaperAdventure.FLATTENER; + } + + @Override + public net.kyori.adventure.text.serializer.gson.GsonComponentSerializer colorDownsamplingGsonComponentSerializer() { + return io.papermc.paper.adventure.PaperAdventure.COLOR_DOWNSAMPLING_GSON; + } + + @Override + public net.kyori.adventure.text.serializer.gson.GsonComponentSerializer gsonComponentSerializer() { + return io.papermc.paper.adventure.PaperAdventure.GSON; + } + + @Override + public net.kyori.adventure.text.serializer.plain.PlainComponentSerializer plainComponentSerializer() { + return io.papermc.paper.adventure.PaperAdventure.PLAIN; + } + + @Override + public net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer legacyComponentSerializer() { + return io.papermc.paper.adventure.PaperAdventure.LEGACY_SECTION_UXRC; + } + // Paper end + public static BlockState getBlock(MaterialData material) { return getBlock(material.getItemType(), material.getData()); } diff --git a/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java index f194cf2663919ea18309a0501ddfab5e2ed639dd..4b110d6c6f22ff7c2fa0fd4b459820797066199d 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java +++ b/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java @@ -80,7 +80,7 @@ public abstract class LazyHashSet implements Set { return this.reference = makeReference(); } - abstract Set makeReference(); + protected abstract Set makeReference(); // Paper - protected public boolean isLazy() { return reference == null; diff --git a/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java index 103c1407b2946e9cae2271646178e5f243c8abb1..b22b7603f3f66e1b64f413106e7989b30475110b 100644 --- a/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java +++ b/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java @@ -15,10 +15,15 @@ public class LazyPlayerSet extends LazyHashSet { } @Override - HashSet makeReference() { + protected HashSet makeReference() { // Paper - protected if (reference != null) { throw new IllegalStateException("Reference already created!"); } + // Paper start + return makePlayerSet(this.server); + } + public static HashSet makePlayerSet(final MinecraftServer server) { + // Paper end List players = server.getPlayerList().players; HashSet reference = new HashSet(players.size()); for (ServerPlayer player : players) {