2021-06-11 14:02:28 +02:00
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
2023-03-23 17:49:24 +01:00
From: Riley Park <rileysebastianpark@gmail.com>
2021-06-11 14:02:28 +02:00
Date: Fri, 29 Jan 2021 17:54:03 +0100
Subject: [PATCH] Adventure
2023-12-12 07:02:06 +01:00
== AT ==
public net.minecraft.network.chat.HoverEvent$ItemStackInfo item
public net.minecraft.network.chat.HoverEvent$ItemStackInfo count
2024-04-25 05:14:51 +02:00
public net.minecraft.network.chat.HoverEvent$ItemStackInfo components
2023-12-12 07:02:06 +01:00
public net.minecraft.network.chat.contents.TranslatableContents filterAllowedArguments(Ljava/lang/Object;)Lcom/mojang/serialization/DataResult;
2021-06-11 14:02:28 +02:00
Co-authored-by: zml <zml@stellardrift.ca>
Co-authored-by: Jake Potrebic <jake.m.potrebic@gmail.com>
2023-12-12 07:02:06 +01:00
diff --git a/src/main/java/io/papermc/paper/adventure/AdventureCodecs.java b/src/main/java/io/papermc/paper/adventure/AdventureCodecs.java
new file mode 100644
2024-04-26 18:22:55 +02:00
index 0000000000000000000000000000000000000000..8dcedc5f4d4453fd942787dbcb9c757274ec7715
2023-12-12 07:02:06 +01:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/AdventureCodecs.java
2024-04-25 05:14:51 +02:00
@@ -0,0 +1,446 @@
2023-12-12 07:02:06 +01:00
+package io.papermc.paper.adventure;
+
2024-04-23 20:32:19 +02:00
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
2023-12-12 07:02:06 +01:00
+import com.mojang.brigadier.exceptions.CommandSyntaxException;
+import com.mojang.datafixers.util.Either;
2024-04-23 20:32:19 +02:00
+import com.mojang.datafixers.util.Pair;
2023-12-12 07:02:06 +01:00
+import com.mojang.serialization.Codec;
+import com.mojang.serialization.DataResult;
2024-04-23 20:32:19 +02:00
+import com.mojang.serialization.DynamicOps;
+import com.mojang.serialization.JsonOps;
2023-12-12 07:02:06 +01:00
+import com.mojang.serialization.MapCodec;
+import com.mojang.serialization.codecs.RecordCodecBuilder;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
2024-04-25 05:14:51 +02:00
+import java.util.Map;
2023-12-12 07:02:06 +01:00
+import java.util.Optional;
+import java.util.UUID;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import net.kyori.adventure.key.Key;
+import net.kyori.adventure.text.BlockNBTComponent;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.EntityNBTComponent;
+import net.kyori.adventure.text.KeybindComponent;
+import net.kyori.adventure.text.NBTComponent;
+import net.kyori.adventure.text.NBTComponentBuilder;
+import net.kyori.adventure.text.ScoreComponent;
+import net.kyori.adventure.text.SelectorComponent;
+import net.kyori.adventure.text.StorageNBTComponent;
+import net.kyori.adventure.text.TextComponent;
+import net.kyori.adventure.text.TranslatableComponent;
2023-12-25 11:51:44 +01:00
+import net.kyori.adventure.text.TranslationArgument;
2023-12-12 07:02:06 +01:00
+import net.kyori.adventure.text.event.ClickEvent;
2024-04-25 05:14:51 +02:00
+import net.kyori.adventure.text.event.DataComponentValue;
2023-12-12 07:02:06 +01:00
+import net.kyori.adventure.text.event.HoverEvent;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.Style;
+import net.kyori.adventure.text.format.TextColor;
+import net.kyori.adventure.text.format.TextDecoration;
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
+import net.minecraft.core.UUIDUtil;
+import net.minecraft.core.registries.BuiltInRegistries;
+import net.minecraft.nbt.CompoundTag;
2024-04-23 20:32:19 +02:00
+import net.minecraft.nbt.NbtOps;
+import net.minecraft.nbt.Tag;
2023-12-12 07:02:06 +01:00
+import net.minecraft.nbt.TagParser;
2024-04-23 20:32:19 +02:00
+import net.minecraft.network.RegistryFriendlyByteBuf;
2023-12-12 07:02:06 +01:00
+import net.minecraft.network.chat.ComponentSerialization;
+import net.minecraft.network.chat.contents.KeybindContents;
+import net.minecraft.network.chat.contents.ScoreContents;
+import net.minecraft.network.chat.contents.TranslatableContents;
2024-04-23 20:32:19 +02:00
+import net.minecraft.network.codec.ByteBufCodecs;
+import net.minecraft.network.codec.StreamCodec;
+import net.minecraft.resources.RegistryOps;
2023-12-12 07:02:06 +01:00
+import net.minecraft.util.ExtraCodecs;
+import net.minecraft.util.StringRepresentable;
+import net.minecraft.world.item.Item;
+import net.minecraft.world.item.ItemStack;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.checkerframework.framework.qual.DefaultQualifier;
+import org.intellij.lang.annotations.Subst;
+
2024-04-25 05:14:51 +02:00
+import static com.mojang.serialization.Codec.recursive;
2023-12-12 07:02:06 +01:00
+import static com.mojang.serialization.codecs.RecordCodecBuilder.mapCodec;
+import static java.util.function.Function.identity;
+import static net.kyori.adventure.text.Component.text;
2023-12-25 11:51:44 +01:00
+import static net.kyori.adventure.text.TranslationArgument.bool;
+import static net.kyori.adventure.text.TranslationArgument.component;
+import static net.kyori.adventure.text.TranslationArgument.numeric;
2023-12-12 07:02:06 +01:00
+
+@DefaultQualifier(NonNull.class)
+public final class AdventureCodecs {
+
+ public static final Codec<Component> COMPONENT_CODEC = recursive("adventure Component", AdventureCodecs::createCodec);
2024-04-23 20:32:19 +02:00
+ public static final StreamCodec<RegistryFriendlyByteBuf, Component> STREAM_COMPONENT_CODEC = ByteBufCodecs.fromCodecWithRegistriesTrusted(COMPONENT_CODEC);
2023-12-12 07:02:06 +01:00
+
+ static final Codec<TextColor> TEXT_COLOR_CODEC = Codec.STRING.comapFlatMap(s -> {
+ if (s.startsWith("#")) {
+ @Nullable TextColor value = TextColor.fromHexString(s);
+ return value != null ? DataResult.success(value) : DataResult.error(() -> "Cannot convert " + s + " to adventure TextColor");
+ } else {
+ final @Nullable NamedTextColor value = NamedTextColor.NAMES.value(s);
+ return value != null ? DataResult.success(value) : DataResult.error(() -> "Cannot convert " + s + " to adventure NamedTextColor");
+ }
+ }, textColor -> {
+ if (textColor instanceof NamedTextColor named) {
+ return NamedTextColor.NAMES.keyOrThrow(named);
+ } else {
+ return textColor.asHexString();
+ }
+ });
+
+ static final Codec<Key> KEY_CODEC = Codec.STRING.comapFlatMap(s -> {
+ return Key.parseable(s) ? DataResult.success(Key.key(s)) : DataResult.error(() -> "Cannot convert " + s + " to adventure Key");
+ }, Key::asString);
+
+ static final Codec<ClickEvent.Action> CLICK_EVENT_ACTION_CODEC = Codec.STRING.comapFlatMap(s -> {
+ final ClickEvent.@Nullable Action value = ClickEvent.Action.NAMES.value(s);
+ return value != null ? DataResult.success(value) : DataResult.error(() -> "Cannot convert " + s + " to adventure ClickEvent$Action");
+ }, ClickEvent.Action.NAMES::keyOrThrow);
+ static final Codec<ClickEvent> CLICK_EVENT_CODEC = RecordCodecBuilder.create((instance) -> {
+ return instance.group(
+ CLICK_EVENT_ACTION_CODEC.fieldOf("action").forGetter(ClickEvent::action),
+ Codec.STRING.fieldOf("value").forGetter(ClickEvent::value)
+ ).apply(instance, ClickEvent::clickEvent);
+ });
+
+ static Codec<HoverEvent.ShowEntity> showEntityCodec(final Codec<Component> componentCodec) {
+ return RecordCodecBuilder.create((instance) -> {
+ return instance.group(
+ KEY_CODEC.fieldOf("type").forGetter(HoverEvent.ShowEntity::type),
+ UUIDUtil.LENIENT_CODEC.fieldOf("id").forGetter(HoverEvent.ShowEntity::id),
2024-04-23 20:32:19 +02:00
+ componentCodec.lenientOptionalFieldOf("name").forGetter(he -> Optional.ofNullable(he.name()))
2023-12-12 07:02:06 +01:00
+ ).apply(instance, (key, uuid, component) -> {
+ return HoverEvent.ShowEntity.showEntity(key, uuid, component.orElse(null));
+ });
+ });
+ }
+
+ static Codec<HoverEvent.ShowItem> showItemCodec(final Codec<Component> componentCodec) {
+ return net.minecraft.network.chat.HoverEvent.ItemStackInfo.CODEC.xmap(isi -> {
2024-04-26 18:22:55 +02:00
+ @Subst("key") final String typeKey = isi.item.unwrapKey().orElseThrow().location().toString();
2024-04-25 05:14:51 +02:00
+ return HoverEvent.ShowItem.showItem(Key.key(typeKey), isi.count, PaperAdventure.asAdventure(isi.getItemStack().getComponentsPatch()));
2023-12-12 07:02:06 +01:00
+ }, si -> {
+ final Item itemType = BuiltInRegistries.ITEM.get(PaperAdventure.asVanilla(si.item()));
2024-04-25 05:14:51 +02:00
+ final Map<Key, DataComponentValue> dataComponentsMap = si.dataComponents();
+ final ItemStack stack = new ItemStack(BuiltInRegistries.ITEM.wrapAsHolder(itemType), si.count(), PaperAdventure.asVanilla(dataComponentsMap));
2023-12-12 07:02:06 +01:00
+ return new net.minecraft.network.chat.HoverEvent.ItemStackInfo(stack);
+ });
+ }
+
+ static final HoverEventType<HoverEvent.ShowEntity> SHOW_ENTITY_HOVER_EVENT_TYPE = new HoverEventType<>(AdventureCodecs::showEntityCodec, HoverEvent.Action.SHOW_ENTITY, "show_entity", AdventureCodecs::legacyDeserializeEntity);
+ static final HoverEventType<HoverEvent.ShowItem> SHOW_ITEM_HOVER_EVENT_TYPE = new HoverEventType<>(AdventureCodecs::showItemCodec, HoverEvent.Action.SHOW_ITEM, "show_item", AdventureCodecs::legacyDeserializeItem);
2024-04-25 03:10:18 +02:00
+ static final HoverEventType<Component> SHOW_TEXT_HOVER_EVENT_TYPE = new HoverEventType<>(identity(), HoverEvent.Action.SHOW_TEXT, "show_text", (component, registryOps, codec) -> DataResult.success(component));
2023-12-12 07:02:06 +01:00
+ static final Codec<HoverEventType<?>> HOVER_EVENT_TYPE_CODEC = StringRepresentable.fromValues(() -> new HoverEventType<?>[]{ SHOW_ENTITY_HOVER_EVENT_TYPE, SHOW_ITEM_HOVER_EVENT_TYPE, SHOW_TEXT_HOVER_EVENT_TYPE });
+
2024-04-23 20:32:19 +02:00
+ static DataResult<HoverEvent.ShowEntity> legacyDeserializeEntity(final Component component, final @Nullable RegistryOps<?> ops, final Codec<Component> componentCodec) {
2023-12-12 07:02:06 +01:00
+ try {
2024-04-23 20:32:19 +02:00
+ final CompoundTag tag = TagParser.parseTag(PlainTextComponentSerializer.plainText().serialize(component));
+ final DynamicOps<JsonElement> dynamicOps = ops != null ? ops.withParent(JsonOps.INSTANCE) : JsonOps.INSTANCE;
+ final DataResult<Component> entityNameResult = componentCodec.parse(dynamicOps, JsonParser.parseString(tag.getString("name")));
2023-12-12 07:02:06 +01:00
+ @Subst("key") final String keyString = tag.getString("type");
+ final UUID entityUUID = UUID.fromString(tag.getString("id"));
2024-04-23 20:32:19 +02:00
+ return entityNameResult.map(name -> HoverEvent.ShowEntity.showEntity(Key.key(keyString), entityUUID, name));
2023-12-12 07:02:06 +01:00
+ } catch (final Exception ex) {
+ return DataResult.error(() -> "Failed to parse tooltip: " + ex.getMessage());
+ }
+ }
+
2024-04-23 20:32:19 +02:00
+ static DataResult<HoverEvent.ShowItem> legacyDeserializeItem(final Component component, final @Nullable RegistryOps<?> ops, final Codec<Component> componentCodec) {
2023-12-12 07:02:06 +01:00
+ try {
2024-04-23 20:32:19 +02:00
+ final CompoundTag tag = TagParser.parseTag(PlainTextComponentSerializer.plainText().serialize(component));
+ final DynamicOps<Tag> dynamicOps = ops != null ? ops.withParent(NbtOps.INSTANCE) : NbtOps.INSTANCE;
2024-04-25 03:10:18 +02:00
+ final DataResult<ItemStack> stackResult = ItemStack.CODEC.parse(dynamicOps, tag);
2024-04-23 20:32:19 +02:00
+ return stackResult.map(stack -> {
2024-04-25 05:14:51 +02:00
+ @Subst("key:value") final String location = stack.getItemHolder().unwrapKey().orElseThrow().location().toString();
+ return HoverEvent.ShowItem.showItem(Key.key(location), stack.getCount(), PaperAdventure.asAdventure(stack.getComponentsPatch()));
2024-04-23 20:32:19 +02:00
+ });
2024-04-25 03:10:18 +02:00
+ } catch (final CommandSyntaxException ex) {
2023-12-12 07:02:06 +01:00
+ return DataResult.error(() -> "Failed to parse item tag: " + ex.getMessage());
+ }
+ }
+
2024-04-23 20:32:19 +02:00
+ @FunctionalInterface
+ interface LegacyDeserializer<T> {
+ DataResult<T> apply(Component component, @Nullable RegistryOps<?> ops, Codec<Component> componentCodec);
+ }
+
+ record HoverEventType<V>(Function<Codec<Component>, MapCodec<HoverEvent<V>>> codec, String id, Function<Codec<Component>, MapCodec<HoverEvent<V>>> legacyCodec) implements StringRepresentable {
+ HoverEventType(final Function<Codec<Component>, Codec<V>> contentCodec, final HoverEvent.Action<V> action, final String id, final LegacyDeserializer<V> legacyDeserializer) {
+ this(cc -> contentCodec.apply(cc).xmap(v -> HoverEvent.hoverEvent(action, v), HoverEvent::value).fieldOf("contents"),
2023-12-12 07:02:06 +01:00
+ id,
2024-04-23 20:32:19 +02:00
+ codec -> (new Codec<HoverEvent<V>>() {
+ public <D> DataResult<Pair<HoverEvent<V>, D>> decode(final DynamicOps<D> dynamicOps, final D object) {
+ return codec.decode(dynamicOps, object).flatMap(pair -> {
+ final DataResult<V> dataResult;
+ if (dynamicOps instanceof final RegistryOps<D> registryOps) {
+ dataResult = legacyDeserializer.apply(pair.getFirst(), registryOps, codec);
+ } else {
+ dataResult = legacyDeserializer.apply(pair.getFirst(), null, codec);
+ }
+
+ return dataResult.map(value -> Pair.of(HoverEvent.hoverEvent(action, value), pair.getSecond()));
+ });
+ }
+
+ public <D> DataResult<D> encode(final HoverEvent<V> hoverEvent, final DynamicOps<D> dynamicOps, final D object) {
+ return DataResult.error(() -> "Can't encode in legacy format");
+ }
+ }).fieldOf("value")
2023-12-12 07:02:06 +01:00
+ );
+ }
+ @Override
+ public String getSerializedName() {
+ return this.id;
+ }
+ }
+
+ private static final Function<HoverEvent<?>, HoverEventType<?>> GET_HOVER_EVENT_TYPE = he -> {
+ if (he.action() == HoverEvent.Action.SHOW_ENTITY) {
+ return SHOW_ENTITY_HOVER_EVENT_TYPE;
+ } else if (he.action() == HoverEvent.Action.SHOW_ITEM) {
+ return SHOW_ITEM_HOVER_EVENT_TYPE;
+ } else if (he.action() == HoverEvent.Action.SHOW_TEXT) {
+ return SHOW_TEXT_HOVER_EVENT_TYPE;
+ } else {
+ throw new IllegalStateException();
+ }
+ };
2024-04-23 20:32:19 +02:00
+ static final Codec<HoverEvent<?>> HOVER_EVENT_CODEC = Codec.withAlternative(
2023-12-12 07:02:06 +01:00
+ HOVER_EVENT_TYPE_CODEC.<HoverEvent<?>>dispatchMap("action", GET_HOVER_EVENT_TYPE, het -> het.codec.apply(COMPONENT_CODEC)).codec(),
+ HOVER_EVENT_TYPE_CODEC.<HoverEvent<?>>dispatchMap("action", GET_HOVER_EVENT_TYPE, het -> het.legacyCodec.apply(COMPONENT_CODEC)).codec()
2024-04-23 20:32:19 +02:00
+ );
2023-12-12 07:02:06 +01:00
+
+ public static final MapCodec<Style> STYLE_MAP_CODEC = mapCodec((instance) -> {
+ return instance.group(
2024-04-23 20:32:19 +02:00
+ TEXT_COLOR_CODEC.optionalFieldOf("color").forGetter(nullableGetter(Style::color)),
+ Codec.BOOL.optionalFieldOf("bold").forGetter(decorationGetter(TextDecoration.BOLD)),
+ Codec.BOOL.optionalFieldOf("italic").forGetter(decorationGetter(TextDecoration.ITALIC)),
+ Codec.BOOL.optionalFieldOf("underlined").forGetter(decorationGetter(TextDecoration.UNDERLINED)),
+ Codec.BOOL.optionalFieldOf("strikethrough").forGetter(decorationGetter(TextDecoration.STRIKETHROUGH)),
+ Codec.BOOL.optionalFieldOf("obfuscated").forGetter(decorationGetter(TextDecoration.OBFUSCATED)),
+ CLICK_EVENT_CODEC.optionalFieldOf("clickEvent").forGetter(nullableGetter(Style::clickEvent)),
+ HOVER_EVENT_CODEC.optionalFieldOf("hoverEvent").forGetter(nullableGetter(Style::hoverEvent)),
+ Codec.STRING.optionalFieldOf("insertion").forGetter(nullableGetter(Style::insertion)),
+ KEY_CODEC.optionalFieldOf("font").forGetter(nullableGetter(Style::font))
2023-12-12 07:02:06 +01:00
+ ).apply(instance, (textColor, bold, italic, underlined, strikethrough, obfuscated, clickEvent, hoverEvent, insertion, font) -> {
+ return Style.style(builder -> {
+ textColor.ifPresent(builder::color);
+ bold.ifPresent(styleBooleanConsumer(builder, TextDecoration.BOLD));
+ italic.ifPresent(styleBooleanConsumer(builder, TextDecoration.ITALIC));
+ underlined.ifPresent(styleBooleanConsumer(builder, TextDecoration.UNDERLINED));
+ strikethrough.ifPresent(styleBooleanConsumer(builder, TextDecoration.STRIKETHROUGH));
+ obfuscated.ifPresent(styleBooleanConsumer(builder, TextDecoration.OBFUSCATED));
+ clickEvent.ifPresent(builder::clickEvent);
+ hoverEvent.ifPresent(builder::hoverEvent);
+ insertion.ifPresent(builder::insertion);
+ font.ifPresent(builder::font);
+ });
+ });
+ });
+ static Consumer<Boolean> styleBooleanConsumer(final Style.Builder builder, final TextDecoration decoration) {
+ return b -> builder.decoration(decoration, b);
+ }
+
+ static Function<Style, Optional<Boolean>> decorationGetter(final TextDecoration decoration) {
+ return style -> Optional.ofNullable(style.decoration(decoration) == TextDecoration.State.NOT_SET ? null : style.decoration(decoration) == TextDecoration.State.TRUE);
+ }
+
+ static <R, T> Function<R, Optional<T>> nullableGetter(final Function<R, @Nullable T> getter) {
+ return style -> Optional.ofNullable(getter.apply(style));
+ }
+
+ static final MapCodec<TextComponent> TEXT_COMPONENT_MAP_CODEC = mapCodec((instance) -> {
+ return instance.group(Codec.STRING.fieldOf("text").forGetter(TextComponent::content)).apply(instance, Component::text);
+ });
2024-04-23 20:32:19 +02:00
+ static final Codec<Object> PRIMITIVE_ARG_CODEC = ExtraCodecs.JAVA.validate(TranslatableContents::filterAllowedArguments);
2023-12-25 11:51:44 +01:00
+ static final Codec<TranslationArgument> ARG_CODEC = Codec.either(PRIMITIVE_ARG_CODEC, COMPONENT_CODEC).flatXmap((primitiveOrComponent) -> {
+ return primitiveOrComponent.map(o -> {
+ final TranslationArgument arg;
+ if (o instanceof String s) {
+ arg = component(text(s));
+ } else if (o instanceof Boolean bool) {
+ arg = bool(bool);
+ } else if (o instanceof Number num) {
+ arg = numeric(num);
+ } else {
+ return DataResult.error(() -> o + " is not a valid translation argument primitive");
+ }
+ return DataResult.success(arg);
+ }, component -> DataResult.success(component(component)));
+ }, translationArgument -> {
+ if (translationArgument.value() instanceof Number || translationArgument.value() instanceof Boolean) {
+ return DataResult.success(Either.left(translationArgument.value()));
+ }
+ final Component component = translationArgument.asComponent();
+ final @Nullable String collapsed = tryCollapseToString(component);
+ if (collapsed != null) {
+ return DataResult.success(Either.left(collapsed)); // attempt to collapse all text components to strings
+ }
+ return DataResult.success(Either.right(component));
+ });
2023-12-12 07:02:06 +01:00
+ static final MapCodec<TranslatableComponent> TRANSLATABLE_COMPONENT_MAP_CODEC = mapCodec((instance) -> {
+ return instance.group(
+ Codec.STRING.fieldOf("translate").forGetter(TranslatableComponent::key),
2024-04-23 20:32:19 +02:00
+ Codec.STRING.lenientOptionalFieldOf("fallback").forGetter(nullableGetter(TranslatableComponent::fallback)),
+ ARG_CODEC.listOf().optionalFieldOf("with").forGetter(c -> c.arguments().isEmpty() ? Optional.empty() : Optional.of(c.arguments()))
2023-12-12 07:02:06 +01:00
+ ).apply(instance, (key, fallback, components) -> {
+ return Component.translatable(key, components.orElse(Collections.emptyList())).fallback(fallback.orElse(null));
+ });
+ });
+
+ static final MapCodec<KeybindComponent> KEYBIND_COMPONENT_MAP_CODEC = KeybindContents.CODEC.xmap(k -> Component.keybind(k.getName()), k -> new KeybindContents(k.keybind()));
+ static final MapCodec<ScoreComponent> SCORE_COMPONENT_INNER_MAP_CODEC = ScoreContents.INNER_CODEC.xmap(s -> Component.score(s.getName(), s.getObjective()), s -> new ScoreContents(s.name(), s.objective()));
+ static final MapCodec<ScoreComponent> SCORE_COMPONENT_MAP_CODEC = SCORE_COMPONENT_INNER_MAP_CODEC.fieldOf("score");
+ static final MapCodec<SelectorComponent> SELECTOR_COMPONENT_MAP_CODEC = mapCodec((instance) -> {
+ return instance.group(
+ Codec.STRING.fieldOf("selector").forGetter(SelectorComponent::pattern),
2024-04-23 20:32:19 +02:00
+ COMPONENT_CODEC.optionalFieldOf("separator").forGetter(nullableGetter(SelectorComponent::separator))
2023-12-12 07:02:06 +01:00
+ ).apply(instance, (selector, component) -> Component.selector(selector, component.orElse(null)));
+ });
+
+ interface NbtComponentDataSource {
+ NBTComponentBuilder<?, ?> builder();
+
+ DataSourceType<?> type();
+ }
+
+ record StorageDataSource(Key storage) implements NbtComponentDataSource {
+ @Override
+ public NBTComponentBuilder<?, ?> builder() {
+ return Component.storageNBT().storage(this.storage());
+ }
+
+ @Override
+ public DataSourceType<?> type() {
+ return STORAGE_DATA_SOURCE_TYPE;
+ }
+ }
+
+ record BlockDataSource(String posPattern) implements NbtComponentDataSource {
+ @Override
+ public NBTComponentBuilder<?, ?> builder() {
+ return Component.blockNBT().pos(BlockNBTComponent.Pos.fromString(this.posPattern));
+ }
+
+ @Override
+ public DataSourceType<?> type() {
+ return BLOCK_DATA_SOURCE_TYPE;
+ }
+ }
+
+ record EntityDataSource(String selectorPattern) implements NbtComponentDataSource {
+ @Override
+ public NBTComponentBuilder<?, ?> builder() {
+ return Component.entityNBT().selector(this.selectorPattern());
+ }
+
+ @Override
+ public DataSourceType<?> type() {
+ return ENTITY_DATA_SOURCE_TYPE;
+ }
+ }
+
+ static final DataSourceType<StorageDataSource> STORAGE_DATA_SOURCE_TYPE = new DataSourceType<>(mapCodec((instance) -> instance.group(KEY_CODEC.fieldOf("storage").forGetter(StorageDataSource::storage)).apply(instance, StorageDataSource::new)), "storage");
+ static final DataSourceType<BlockDataSource> BLOCK_DATA_SOURCE_TYPE = new DataSourceType<>(mapCodec((instance) -> instance.group(Codec.STRING.fieldOf("block").forGetter(BlockDataSource::posPattern)).apply(instance, BlockDataSource::new)), "block");
+ static final DataSourceType<EntityDataSource> ENTITY_DATA_SOURCE_TYPE = new DataSourceType<>(mapCodec((instance) -> instance.group(Codec.STRING.fieldOf("entity").forGetter(EntityDataSource::selectorPattern)).apply(instance, EntityDataSource::new)), "entity");
+
+ static final MapCodec<NbtComponentDataSource> NBT_COMPONENT_DATA_SOURCE_CODEC = ComponentSerialization.createLegacyComponentMatcher(new DataSourceType<?>[]{ENTITY_DATA_SOURCE_TYPE, BLOCK_DATA_SOURCE_TYPE, STORAGE_DATA_SOURCE_TYPE}, DataSourceType::codec, NbtComponentDataSource::type, "source");
+
+ record DataSourceType<D extends NbtComponentDataSource>(MapCodec<D> codec, String id) implements StringRepresentable {
+ @Override
+ public String getSerializedName() {
+ return this.id();
+ }
+ }
+
+ static final MapCodec<NBTComponent<?, ?>> NBT_COMPONENT_MAP_CODEC = mapCodec((instance) -> {
+ return instance.group(
+ Codec.STRING.fieldOf("nbt").forGetter(NBTComponent::nbtPath),
2024-04-23 20:32:19 +02:00
+ Codec.BOOL.lenientOptionalFieldOf("interpret", false).forGetter(NBTComponent::interpret),
+ COMPONENT_CODEC.lenientOptionalFieldOf("separator").forGetter(nullableGetter(NBTComponent::separator)),
2023-12-12 07:02:06 +01:00
+ NBT_COMPONENT_DATA_SOURCE_CODEC.forGetter(nbtComponent -> {
+ if (nbtComponent instanceof final EntityNBTComponent entityNBTComponent) {
+ return new EntityDataSource(entityNBTComponent.selector());
+ } else if (nbtComponent instanceof final BlockNBTComponent blockNBTComponent) {
+ return new BlockDataSource(blockNBTComponent.pos().asString());
+ } else if (nbtComponent instanceof final StorageNBTComponent storageNBTComponent) {
+ return new StorageDataSource(storageNBTComponent.storage());
+ } else {
+ throw new IllegalArgumentException(nbtComponent + " isn't a valid nbt component");
+ }
+ })
+ ).apply(instance, (nbtPath, interpret, separator, dataSource) -> {
+ return dataSource.builder().nbtPath(nbtPath).interpret(interpret).separator(separator.orElse(null)).build();
+ });
+ });
+
+ @SuppressWarnings("NonExtendableApiUsage")
+ record ComponentType<C extends Component>(MapCodec<C> codec, Predicate<Component> test, String id) implements StringRepresentable {
+ @Override
+ public String getSerializedName() {
+ return this.id;
+ }
+ }
+
+ static final ComponentType<TextComponent> PLAIN = new ComponentType<>(TEXT_COMPONENT_MAP_CODEC, TextComponent.class::isInstance, "text");
+ static final ComponentType<TranslatableComponent> TRANSLATABLE = new ComponentType<>(TRANSLATABLE_COMPONENT_MAP_CODEC, TranslatableComponent.class::isInstance, "translatable");
+ static final ComponentType<KeybindComponent> KEYBIND = new ComponentType<>(KEYBIND_COMPONENT_MAP_CODEC, KeybindComponent.class::isInstance, "keybind");
+ static final ComponentType<ScoreComponent> SCORE = new ComponentType<>(SCORE_COMPONENT_MAP_CODEC, ScoreComponent.class::isInstance, "score");
+ static final ComponentType<SelectorComponent> SELECTOR = new ComponentType<>(SELECTOR_COMPONENT_MAP_CODEC, SelectorComponent.class::isInstance, "selector");
+ static final ComponentType<NBTComponent<?, ?>> NBT = new ComponentType<>(NBT_COMPONENT_MAP_CODEC, NBTComponent.class::isInstance, "nbt");
+
+ static Codec<Component> createCodec(final Codec<Component> selfCodec) {
+ final ComponentType<?>[] types = new ComponentType<?>[]{PLAIN, TRANSLATABLE, KEYBIND, SCORE, SELECTOR, NBT};
+ final MapCodec<Component> legacyCodec = ComponentSerialization.createLegacyComponentMatcher(types, ComponentType::codec, component -> {
+ for (final ComponentType<?> type : types) {
+ if (type.test().test(component)) {
+ return type;
+ }
+ }
+ throw new IllegalStateException("Unexpected component type " + component);
+ }, "type");
+
+ final Codec<Component> directCodec = RecordCodecBuilder.create((instance) -> {
+ return instance.group(
+ legacyCodec.forGetter(identity()),
2024-04-23 20:32:19 +02:00
+ ExtraCodecs.nonEmptyList(selfCodec.listOf()).optionalFieldOf("extra", List.of()).forGetter(Component::children),
2023-12-12 07:02:06 +01:00
+ STYLE_MAP_CODEC.forGetter(Component::style)
+ ).apply(instance, (component, children, style) -> {
+ return component.style(style).children(children);
+ });
+ });
+
+ return Codec.either(Codec.either(Codec.STRING, ExtraCodecs.nonEmptyList(selfCodec.listOf())), directCodec).xmap((stringOrListOrComponent) -> {
+ return stringOrListOrComponent.map((stringOrList) -> stringOrList.map(Component::text, AdventureCodecs::createFromList), identity());
+ }, (text) -> {
+ final @Nullable String string = tryCollapseToString(text);
+ return string != null ? Either.left(Either.left(string)) : Either.right(text);
+ });
+ }
+
2024-04-19 21:47:24 +02:00
+ public static @Nullable String tryCollapseToString(final Component component) {
2023-12-12 07:02:06 +01:00
+ if (component instanceof final TextComponent textComponent) {
+ if (component.children().isEmpty() && component.style().isEmpty()) {
+ return textComponent.content();
+ }
+ }
+ return null;
+ }
+
+ static Component createFromList(final List<? extends Component> components) {
+ Component component = components.get(0);
+ for (int i = 1; i < components.size(); i++) {
+ component = component.append(components.get(i));
+ }
+ return component;
+ }
+
+ private AdventureCodecs() {
+ }
+}
2021-06-11 14:02:28 +02:00
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
2024-04-27 00:25:20 +02:00
index 0000000000000000000000000000000000000000..c9d787f4e66f152b557229fdb1d9a3ac83a7d71f
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/AdventureComponent.java
2024-04-27 00:25:20 +02:00
@@ -0,0 +1,88 @@
2021-06-11 14:02:28 +02:00
+package io.papermc.paper.adventure;
+
+import java.util.List;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.TextComponent;
2022-05-26 21:12:14 +02:00
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
2022-06-08 16:24:55 +02:00
+import net.minecraft.network.chat.ComponentContents;
2021-06-11 14:02:28 +02:00
+import net.minecraft.network.chat.MutableComponent;
+import net.minecraft.network.chat.Style;
2023-12-06 19:07:47 +01:00
+import net.minecraft.network.chat.contents.PlainTextContents;
2021-06-12 00:37:16 +02:00
+import net.minecraft.util.FormattedCharSequence;
2021-06-11 14:02:28 +02:00
+import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
2021-12-22 08:07:17 +01:00
+import org.jetbrains.annotations.Nullable;
2021-06-11 14:02:28 +02:00
+
+public final class AdventureComponent implements net.minecraft.network.chat.Component {
2021-12-22 08:07:17 +01:00
+ final Component adventure;
+ private net.minecraft.network.chat.@MonotonicNonNull Component vanilla;
2021-06-11 14:02:28 +02:00
+
2021-12-22 08:07:17 +01:00
+ public AdventureComponent(final Component adventure) {
+ this.adventure = adventure;
2021-06-11 14:02:28 +02:00
+ }
+
+ public net.minecraft.network.chat.Component deepConverted() {
2021-12-22 08:07:17 +01:00
+ net.minecraft.network.chat.Component vanilla = this.vanilla;
+ if (vanilla == null) {
+ vanilla = PaperAdventure.WRAPPER_AWARE_SERIALIZER.serialize(this.adventure);
+ this.vanilla = vanilla;
2021-06-11 14:02:28 +02:00
+ }
2021-12-22 08:07:17 +01:00
+ return vanilla;
2021-06-11 14:02:28 +02:00
+ }
+
2021-06-12 00:37:16 +02:00
+ public net.minecraft.network.chat.@Nullable Component deepConvertedIfPresent() {
2021-12-22 08:07:17 +01:00
+ return this.vanilla;
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public Style getStyle() {
+ return this.deepConverted().getStyle();
+ }
+
+ @Override
2022-06-08 16:24:55 +02:00
+ public ComponentContents getContents() {
2021-12-22 08:07:17 +01:00
+ if (this.adventure instanceof TextComponent) {
2023-12-06 19:07:47 +01:00
+ return PlainTextContents.create(((TextComponent) this.adventure).content());
2021-06-11 14:02:28 +02:00
+ } else {
+ return this.deepConverted().getContents();
+ }
+ }
+
+ @Override
+ public String getString() {
2022-05-26 21:12:14 +02:00
+ return PlainTextComponentSerializer.plainText().serialize(this.adventure);
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public List<net.minecraft.network.chat.Component> getSiblings() {
+ return this.deepConverted().getSiblings();
+ }
+
+ @Override
+ public MutableComponent plainCopy() {
+ return this.deepConverted().plainCopy();
+ }
+
+ @Override
+ public MutableComponent copy() {
+ return this.deepConverted().copy();
+ }
+
2021-06-12 00:37:16 +02:00
+ @Override
+ public FormattedCharSequence getVisualOrderText() {
+ return this.deepConverted().getVisualOrderText();
+ }
+
2023-03-14 21:27:18 +01:00
+ public Component adventure$component() {
+ return this.adventure;
+ }
2024-04-27 00:25:20 +02:00
+
+ @Override
+ public int hashCode() {
+ return this.deepConverted().hashCode();
+ }
+
+ @Override
+ public boolean equals(final Object obj) {
+ return this.deepConverted().equals(obj);
+ }
2021-06-11 14:02:28 +02:00
+}
2023-06-12 23:43:39 +02:00
diff --git a/src/main/java/io/papermc/paper/adventure/BossBarImplementationImpl.java b/src/main/java/io/papermc/paper/adventure/BossBarImplementationImpl.java
new file mode 100644
2023-12-25 11:51:44 +01:00
index 0000000000000000000000000000000000000000..23bd6d2d8fed5a3491e856f8b875456dd29f8aaf
2023-06-12 23:43:39 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/BossBarImplementationImpl.java
2023-12-25 11:51:44 +01:00
@@ -0,0 +1,85 @@
2023-06-12 23:43:39 +02:00
+package io.papermc.paper.adventure;
+
+import com.google.common.collect.Collections2;
+import java.util.Set;
+import java.util.function.Function;
+import net.kyori.adventure.bossbar.BossBar;
+import net.kyori.adventure.bossbar.BossBarImplementation;
+import net.kyori.adventure.bossbar.BossBarViewer;
+import net.kyori.adventure.text.Component;
+import net.minecraft.network.protocol.game.ClientboundBossEventPacket;
+import net.minecraft.server.level.ServerBossEvent;
+import net.minecraft.server.level.ServerPlayer;
+import net.minecraft.world.BossEvent;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.jetbrains.annotations.NotNull;
+
2023-12-25 11:51:44 +01:00
+@SuppressWarnings("UnstableApiUsage")
2023-06-12 23:43:39 +02:00
+public final class BossBarImplementationImpl implements BossBar.Listener, BossBarImplementation {
+ private final BossBar bar;
+ private ServerBossEvent vanilla;
+
+ public BossBarImplementationImpl(final BossBar bar) {
+ this.bar = bar;
+ }
+
+ public void playerShow(final CraftPlayer player) {
+ if (this.vanilla == null) {
+ this.vanilla = new ServerBossEvent(
+ PaperAdventure.asVanilla(this.bar.name()),
+ PaperAdventure.asVanilla(this.bar.color()),
+ PaperAdventure.asVanilla(this.bar.overlay())
+ );
+ this.vanilla.adventure = this.bar;
+ this.bar.addListener(this);
+ }
+ this.vanilla.addPlayer(player.getHandle());
+ }
+
+ public void playerHide(final CraftPlayer player) {
+ if (this.vanilla != null) {
+ this.vanilla.removePlayer(player.getHandle());
+ if (this.vanilla.getPlayers().isEmpty()) {
+ this.bar.removeListener(this);
+ this.vanilla = null;
+ }
+ }
+ }
+
+ @Override
+ public void bossBarNameChanged(final @NonNull BossBar bar, final @NonNull Component oldName, final @NonNull Component newName) {
+ this.maybeBroadcast(ClientboundBossEventPacket::createUpdateNamePacket);
+ }
+
+ @Override
+ public void bossBarProgressChanged(final @NonNull BossBar bar, final float oldProgress, final float newProgress) {
+ this.maybeBroadcast(ClientboundBossEventPacket::createUpdateProgressPacket);
+ }
+
+ @Override
+ public void bossBarColorChanged(final @NonNull BossBar bar, final BossBar.@NonNull Color oldColor, final BossBar.@NonNull Color newColor) {
+ this.maybeBroadcast(ClientboundBossEventPacket::createUpdateStylePacket);
+ }
+
+ @Override
+ public void bossBarOverlayChanged(final @NonNull BossBar bar, final BossBar.@NonNull Overlay oldOverlay, final BossBar.@NonNull Overlay newOverlay) {
+ this.maybeBroadcast(ClientboundBossEventPacket::createUpdateStylePacket);
+ }
+
+ @Override
+ public void bossBarFlagsChanged(final @NonNull BossBar bar, final @NonNull Set<BossBar.Flag> flagsAdded, final @NonNull Set<BossBar.Flag> flagsRemoved) {
+ this.maybeBroadcast(ClientboundBossEventPacket::createUpdatePropertiesPacket);
+ }
+
+ @Override
+ public @NotNull Iterable<? extends BossBarViewer> viewers() {
+ return this.vanilla == null ? Set.of() : Collections2.transform(this.vanilla.getPlayers(), ServerPlayer::getBukkitEntity);
+ }
+
+ private void maybeBroadcast(final Function<BossEvent, ClientboundBossEventPacket> fn) {
+ if (this.vanilla != null) {
+ this.vanilla.broadcast(fn);
+ }
+ }
+}
2021-06-11 14:02:28 +02:00
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
2024-06-14 14:28:06 +02:00
index 0000000000000000000000000000000000000000..b9a64a40dbb025e34a3de81df1208de45df3cfcc
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/ChatProcessor.java
2024-04-19 21:47:24 +02:00
@@ -0,0 +1,376 @@
2021-06-11 14:02:28 +02:00
+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;
2022-12-17 07:05:48 +01:00
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
2022-08-01 21:34:55 +02:00
+import java.util.BitSet;
+import java.util.Collection;
2022-12-17 07:05:48 +01:00
+import java.util.HashMap;
2021-06-19 00:47:40 +02:00
+import java.util.HashSet;
2022-12-17 07:05:48 +01:00
+import java.util.Map;
+import java.util.Objects;
2021-06-11 14:02:28 +02:00
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
2022-08-01 21:34:55 +02:00
+import java.util.function.Function;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.audience.Audience;
2022-12-17 07:05:48 +01:00
+import net.kyori.adventure.audience.ForwardingAudience;
+import net.kyori.adventure.key.Key;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.text.Component;
2024-04-19 21:47:24 +02:00
+import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
2023-03-15 00:10:18 +01:00
+import net.minecraft.Optionull;
2022-08-01 21:34:55 +02:00
+import net.minecraft.Util;
2022-12-17 07:05:48 +01:00
+import net.minecraft.core.registries.Registries;
2022-08-01 21:34:55 +02:00
+import net.minecraft.network.chat.ChatType;
2022-12-08 17:32:29 +01:00
+import net.minecraft.network.chat.OutgoingChatMessage;
2022-08-01 21:34:55 +02:00
+import net.minecraft.network.chat.PlayerChatMessage;
+import net.minecraft.resources.ResourceKey;
2023-09-15 20:03:42 +02:00
+import net.minecraft.resources.ResourceLocation;
2021-06-11 14:02:28 +02:00
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.server.level.ServerPlayer;
2022-08-01 21:34:55 +02:00
+import org.bukkit.command.ConsoleCommandSender;
2021-06-11 14:02:28 +02:00
+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;
2022-08-01 21:34:55 +02:00
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.checkerframework.framework.qual.DefaultQualifier;
2024-04-19 21:47:24 +02:00
+import org.intellij.lang.annotations.Subst;
2022-08-01 21:34:55 +02:00
+
+import static net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection;
2021-06-11 14:02:28 +02:00
+
2022-08-01 21:34:55 +02:00
+@DefaultQualifier(NonNull.class)
2021-06-11 14:02:28 +02:00
+public final class ChatProcessor {
2024-06-14 14:28:06 +02:00
+ static final ResourceKey<ChatType> PAPER_RAW = ResourceKey.create(Registries.CHAT_TYPE, ResourceLocation.fromNamespaceAndPath(ResourceLocation.PAPER_NAMESPACE, "raw"));
2022-08-01 21:34:55 +02:00
+ static final String DEFAULT_LEGACY_FORMAT = "<%1$s> %2$s"; // copied from PlayerChatEvent/AsyncPlayerChatEvent
2021-06-11 14:02:28 +02:00
+ final MinecraftServer server;
+ final ServerPlayer player;
2022-08-01 21:34:55 +02:00
+ final PlayerChatMessage message;
2021-06-11 14:02:28 +02:00
+ final boolean async;
2022-08-01 21:34:55 +02:00
+ final String craftbukkit$originalMessage;
+ final Component paper$originalMessage;
2022-12-08 17:32:29 +01:00
+ final OutgoingChatMessage outgoing;
2021-06-11 14:02:28 +02:00
+
2022-08-01 21:34:55 +02:00
+ static final int MESSAGE_CHANGED = 1;
+ static final int FORMAT_CHANGED = 2;
+ static final int SENDER_CHANGED = 3; // Not used
+ private final BitSet flags = new BitSet(3);
+
+ public ChatProcessor(final MinecraftServer server, final ServerPlayer player, final PlayerChatMessage message, final boolean async) {
2021-06-11 14:02:28 +02:00
+ this.server = server;
+ this.player = player;
+ this.message = message;
+ this.async = async;
2024-04-19 21:47:24 +02:00
+ this.craftbukkit$originalMessage = message.unsignedContent() != null ? LegacyComponentSerializer.legacySection().serialize(PaperAdventure.asAdventure(message.unsignedContent())) : message.signedContent();
+ this.paper$originalMessage = PaperAdventure.asAdventure(this.message.decoratedContent());
2022-12-08 17:32:29 +01:00
+ this.outgoing = OutgoingChatMessage.create(this.message);
2021-06-11 14:02:28 +02:00
+ }
+
2022-02-28 22:38:23 +01:00
+ @SuppressWarnings("deprecated")
2021-06-11 14:02:28 +02:00
+ public void process() {
2022-02-28 22:38:23 +01:00
+ final boolean listenersOnAsyncEvent = canYouHearMe(AsyncPlayerChatEvent.getHandlerList());
+ final boolean listenersOnSyncEvent = canYouHearMe(PlayerChatEvent.getHandlerList());
2021-06-11 14:02:28 +02:00
+ if (listenersOnAsyncEvent || listenersOnSyncEvent) {
+ final CraftPlayer player = this.player.getBukkitEntity();
2022-08-01 21:34:55 +02:00
+ final AsyncPlayerChatEvent ae = new AsyncPlayerChatEvent(this.async, player, this.craftbukkit$originalMessage, new LazyPlayerSet(this.server));
2022-02-28 22:38:23 +01:00
+ this.post(ae);
2021-06-11 14:02:28 +02:00
+ 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<Void>() {
+ @Override
+ protected Void evaluate() {
2022-02-28 22:38:23 +01:00
+ ChatProcessor.this.post(se);
2021-06-11 14:02:28 +02:00
+ return null;
+ }
+ });
2022-08-01 21:34:55 +02:00
+ this.readLegacyModifications(se.getMessage(), se.getFormat(), se.getPlayer());
2022-02-28 22:38:23 +01:00
+ this.processModern(
2022-08-01 21:34:55 +02:00
+ this.modernRenderer(se.getFormat()),
2022-02-28 22:38:23 +01:00
+ this.viewersFromLegacy(se.getRecipients()),
2022-08-01 21:34:55 +02:00
+ this.modernMessage(se.getMessage()),
+ se.getPlayer(),
2022-02-28 22:38:23 +01:00
+ se.isCancelled()
+ );
2021-06-11 14:02:28 +02:00
+ } else {
2022-08-01 21:34:55 +02:00
+ this.readLegacyModifications(ae.getMessage(), ae.getFormat(), ae.getPlayer());
2022-02-28 22:38:23 +01:00
+ this.processModern(
2022-08-01 21:34:55 +02:00
+ this.modernRenderer(ae.getFormat()),
2022-02-28 22:38:23 +01:00
+ this.viewersFromLegacy(ae.getRecipients()),
2022-08-01 21:34:55 +02:00
+ this.modernMessage(ae.getMessage()),
+ ae.getPlayer(),
2022-02-28 22:38:23 +01:00
+ ae.isCancelled()
+ );
2021-06-11 14:02:28 +02:00
+ }
+ } else {
2022-02-28 22:38:23 +01:00
+ this.processModern(
2022-08-01 21:34:55 +02:00
+ defaultRenderer(),
2022-02-28 22:38:23 +01:00
+ new LazyChatAudienceSet(this.server),
2022-08-01 21:34:55 +02:00
+ this.paper$originalMessage,
+ this.player.getBukkitEntity(),
2022-02-28 22:38:23 +01:00
+ false
+ );
2021-06-11 14:02:28 +02:00
+ }
+ }
+
2022-08-01 21:34:55 +02:00
+ private ChatRenderer modernRenderer(final String format) {
+ if (this.flags.get(FORMAT_CHANGED)) {
+ return legacyRenderer(format);
+ } else {
+ return defaultRenderer();
+ }
+ }
+
+ private Component modernMessage(final String legacyMessage) {
+ if (this.flags.get(MESSAGE_CHANGED)) {
+ return legacySection().deserialize(legacyMessage);
+ } else {
+ return this.paper$originalMessage;
+ }
+ }
+
+ private void readLegacyModifications(final String message, final String format, final Player playerSender) {
2024-04-19 21:47:24 +02:00
+ this.flags.set(MESSAGE_CHANGED, !message.equals(this.craftbukkit$originalMessage));
+ this.flags.set(FORMAT_CHANGED, !format.equals(DEFAULT_LEGACY_FORMAT));
2022-08-01 21:34:55 +02:00
+ this.flags.set(SENDER_CHANGED, playerSender != this.player.getBukkitEntity());
+ }
+
+ private void processModern(final ChatRenderer renderer, final Set<Audience> viewers, final Component message, final Player player, final boolean cancelled) {
2022-12-23 16:54:04 +01:00
+ final PlayerChatMessage.AdventureView signedMessage = this.message.adventureView();
+ final AsyncChatEvent ae = new AsyncChatEvent(this.async, player, viewers, renderer, message, this.paper$originalMessage, signedMessage);
2021-06-11 14:02:28 +02:00
+ ae.setCancelled(cancelled); // propagate cancelled state
2022-02-28 22:38:23 +01:00
+ this.post(ae);
+ final boolean listenersOnSyncEvent = canYouHearMe(ChatEvent.getHandlerList());
2021-06-11 14:02:28 +02:00
+ if (listenersOnSyncEvent) {
2022-02-28 22:38:23 +01:00
+ this.queueIfAsyncOrRunImmediately(new Waitable<Void>() {
+ @Override
+ protected Void evaluate() {
2022-12-23 16:54:04 +01:00
+ final ChatEvent se = new ChatEvent(player, ae.viewers(), ae.renderer(), ae.message(), ChatProcessor.this.paper$originalMessage/*, ae.usePreviewComponent()*/, signedMessage);
2022-02-28 22:38:23 +01:00
+ se.setCancelled(ae.isCancelled()); // propagate cancelled state
+ ChatProcessor.this.post(se);
2022-08-01 21:34:55 +02:00
+ ChatProcessor.this.readModernModifications(se, renderer);
2022-02-28 22:38:23 +01:00
+ ChatProcessor.this.complete(se);
+ return null;
+ }
+ });
2021-06-11 14:02:28 +02:00
+ } else {
2022-08-01 21:34:55 +02:00
+ this.readModernModifications(ae, renderer);
2021-06-11 14:02:28 +02:00
+ this.complete(ae);
+ }
+ }
+
2022-08-01 21:34:55 +02:00
+ private void readModernModifications(final AbstractChatEvent chatEvent, final ChatRenderer originalRenderer) {
2024-04-19 21:47:24 +02:00
+ this.flags.set(MESSAGE_CHANGED, !chatEvent.message().equals(this.paper$originalMessage));
2022-08-01 21:34:55 +02:00
+ if (originalRenderer != chatEvent.renderer()) { // don't set to false if it hasn't changed
+ this.flags.set(FORMAT_CHANGED, true);
+ }
+ }
+
2021-06-11 14:02:28 +02:00
+ private void complete(final AbstractChatEvent event) {
+ if (event.isCancelled()) {
+ return;
+ }
+
2022-08-01 21:34:55 +02:00
+ final CraftPlayer player = ((CraftPlayer) event.getPlayer());
2021-06-11 14:02:28 +02:00
+ final Component displayName = displayName(player);
+ final Component message = event.message();
+ final ChatRenderer renderer = event.renderer();
+
+ final Set<Audience> viewers = event.viewers();
2023-09-15 20:03:42 +02:00
+ final ResourceKey<ChatType> chatTypeKey = renderer instanceof ChatRenderer.Default ? ChatType.CHAT : PAPER_RAW;
2023-06-08 22:56:13 +02:00
+ final ChatType.Bound chatType = ChatType.bind(chatTypeKey, this.player.level().registryAccess(), PaperAdventure.asVanilla(displayName(player)));
2022-08-01 21:34:55 +02:00
+
+ OutgoingChat outgoingChat = viewers instanceof LazyChatAudienceSet lazyAudienceSet && lazyAudienceSet.isLazy() ? new ServerOutgoingChat() : new ViewersOutgoingChat();
+ if (this.flags.get(FORMAT_CHANGED)) {
+ if (renderer instanceof ChatRenderer.ViewerUnaware unaware) {
+ outgoingChat.sendFormatChangedViewerUnaware(player, PaperAdventure.asVanilla(unaware.render(player, displayName, message)), viewers, chatType);
+ } else {
+ outgoingChat.sendFormatChangedViewerAware(player, displayName, message, renderer, viewers, chatType);
2021-06-11 14:02:28 +02:00
+ }
2022-08-01 21:34:55 +02:00
+ } else if (this.flags.get(MESSAGE_CHANGED)) {
+ if (!(renderer instanceof ChatRenderer.ViewerUnaware unaware)) {
2024-04-19 21:47:24 +02:00
+ throw new IllegalStateException("BUG: This should be a ViewerUnaware renderer at this point");
2022-08-01 21:34:55 +02:00
+ }
+ final Component renderedComponent = chatTypeKey == ChatType.CHAT ? message : unaware.render(player, displayName, message);
+ outgoingChat.sendMessageChanged(player, PaperAdventure.asVanilla(renderedComponent), viewers, chatType);
2021-06-11 14:02:28 +02:00
+ } else {
2022-08-01 21:34:55 +02:00
+ outgoingChat.sendOriginal(player, viewers, chatType);
+ }
+ }
+
+ interface OutgoingChat {
+ default void sendFormatChangedViewerUnaware(CraftPlayer player, net.minecraft.network.chat.Component renderedMessage, Set<Audience> viewers, ChatType.Bound chatType) {
+ this.sendMessageChanged(player, renderedMessage, viewers, chatType);
+ }
+
+ void sendFormatChangedViewerAware(CraftPlayer player, Component displayName, Component message, ChatRenderer renderer, Set<Audience> viewers, ChatType.Bound chatType);
+
+ void sendMessageChanged(CraftPlayer player, net.minecraft.network.chat.Component renderedMessage, Set<Audience> viewers, ChatType.Bound chatType);
+
+ void sendOriginal(CraftPlayer player, Set<Audience> viewers, ChatType.Bound chatType);
+ }
+
+ final class ServerOutgoingChat implements OutgoingChat {
+ @Override
+ public void sendFormatChangedViewerAware(CraftPlayer player, Component displayName, Component message, ChatRenderer renderer, Set<Audience> viewers, ChatType.Bound chatType) {
+ ChatProcessor.this.server.getPlayerList().broadcastChatMessage(ChatProcessor.this.message, ChatProcessor.this.player, chatType, viewer -> PaperAdventure.asVanilla(renderer.render(player, displayName, message, viewer)));
+ }
+
+ @Override
+ public void sendMessageChanged(CraftPlayer player, net.minecraft.network.chat.Component renderedMessage, Set<Audience> viewers, ChatType.Bound chatType) {
+ ChatProcessor.this.server.getPlayerList().broadcastChatMessage(ChatProcessor.this.message.withUnsignedContent(renderedMessage), ChatProcessor.this.player, chatType);
+ }
+
+ @Override
+ public void sendOriginal(CraftPlayer player, Set<Audience> viewers, ChatType.Bound chatType) {
+ ChatProcessor.this.server.getPlayerList().broadcastChatMessage(ChatProcessor.this.message, ChatProcessor.this.player, chatType);
+ }
+ }
+
+ final class ViewersOutgoingChat implements OutgoingChat {
+ @Override
+ public void sendFormatChangedViewerAware(CraftPlayer player, Component displayName, Component message, ChatRenderer renderer, Set<Audience> viewers, ChatType.Bound chatType) {
2022-12-17 07:05:48 +01:00
+ this.broadcastToViewers(viewers, chatType, v -> PaperAdventure.asVanilla(renderer.render(player, displayName, message, v)));
2022-08-01 21:34:55 +02:00
+ }
+
+ @Override
+ public void sendMessageChanged(CraftPlayer player, net.minecraft.network.chat.Component renderedMessage, Set<Audience> viewers, ChatType.Bound chatType) {
2022-12-17 07:05:48 +01:00
+ this.broadcastToViewers(viewers, chatType, $ -> renderedMessage);
2022-08-01 21:34:55 +02:00
+ }
+
+ @Override
+ public void sendOriginal(CraftPlayer player, Set<Audience> viewers, ChatType.Bound chatType) {
2022-12-17 07:05:48 +01:00
+ this.broadcastToViewers(viewers, chatType, null);
2022-08-01 21:34:55 +02:00
+ }
+
2022-12-17 07:05:48 +01:00
+ private void broadcastToViewers(Collection<Audience> viewers, final ChatType.Bound chatType, final @Nullable Function<Audience, net.minecraft.network.chat.Component> msgFunction) {
2022-08-01 21:34:55 +02:00
+ for (Audience viewer : viewers) {
2022-12-17 07:05:48 +01:00
+ if (acceptsNative(viewer)) {
+ this.sendNative(viewer, chatType, msgFunction);
2022-08-01 21:34:55 +02:00
+ } else {
2023-03-15 00:10:18 +01:00
+ final net.minecraft.network.chat.@Nullable Component unsigned = Optionull.map(msgFunction, f -> f.apply(viewer));
2022-12-17 07:05:48 +01:00
+ final PlayerChatMessage msg = unsigned == null ? ChatProcessor.this.message : ChatProcessor.this.message.withUnsignedContent(unsigned);
+ viewer.sendMessage(msg.adventureView(), this.adventure(chatType));
2022-08-01 21:34:55 +02:00
+ }
+ }
+ }
+
2022-12-17 07:05:48 +01:00
+ private static final Map<String, net.kyori.adventure.chat.ChatType> BUILT_IN_CHAT_TYPES = Util.make(() -> {
+ final Map<String, net.kyori.adventure.chat.ChatType> map = new HashMap<>();
+ for (final Field declaredField : net.kyori.adventure.chat.ChatType.class.getDeclaredFields()) {
+ if (Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType().equals(ChatType.class)) {
+ try {
+ final net.kyori.adventure.chat.ChatType type = (net.kyori.adventure.chat.ChatType) declaredField.get(null);
+ map.put(type.key().asString(), type);
+ } catch (final ReflectiveOperationException ignore) {
+ }
+ }
+ }
+ return map;
+ });
+
+ private net.kyori.adventure.chat.ChatType.Bound adventure(ChatType.Bound chatType) {
2024-04-19 21:47:24 +02:00
+ @Subst("key:value") final String stringKey = Objects.requireNonNull(
2024-04-26 04:54:07 +02:00
+ chatType.chatType().unwrapKey().orElseThrow().location(),
2022-12-17 07:05:48 +01:00
+ () -> "No key for '%s' in CHAT_TYPE registry.".formatted(chatType)
+ ).toString();
+ net.kyori.adventure.chat.@Nullable ChatType adventure = BUILT_IN_CHAT_TYPES.get(stringKey);
+ if (adventure == null) {
+ adventure = net.kyori.adventure.chat.ChatType.chatType(Key.key(stringKey));
+ }
+ return adventure.bind(
+ PaperAdventure.asAdventure(chatType.name()),
2024-04-26 04:54:07 +02:00
+ chatType.targetName().map(PaperAdventure::asAdventure).orElse(null)
2022-12-17 07:05:48 +01:00
+ );
+ }
+
+ private static boolean acceptsNative(final Audience viewer) {
+ if (viewer instanceof Player || viewer instanceof ConsoleCommandSender) {
+ return true;
+ }
+ if (viewer instanceof ForwardingAudience.Single single) {
+ return acceptsNative(single.audience());
+ }
+ return false;
+ }
+
+ private void sendNative(final Audience viewer, final ChatType.Bound chatType, final @Nullable Function<Audience, net.minecraft.network.chat.Component> msgFunction) {
2022-08-01 21:34:55 +02:00
+ if (viewer instanceof ConsoleCommandSender) {
+ this.sendToServer(chatType, msgFunction);
+ } else if (viewer instanceof CraftPlayer craftPlayer) {
2023-03-15 00:10:18 +01:00
+ craftPlayer.getHandle().sendChatMessage(ChatProcessor.this.outgoing, ChatProcessor.this.player.shouldFilterMessageTo(craftPlayer.getHandle()), chatType, Optionull.map(msgFunction, f -> f.apply(viewer)));
2022-12-17 07:05:48 +01:00
+ } else if (viewer instanceof ForwardingAudience.Single single) {
+ this.sendNative(single.audience(), chatType, msgFunction);
2022-08-01 21:34:55 +02:00
+ } else {
2022-12-17 07:05:48 +01:00
+ throw new IllegalStateException("Should only be a Player or Console or ForwardingAudience.Single pointing to one!");
2022-08-01 21:34:55 +02:00
+ }
+ }
+
+ private void sendToServer(final ChatType.Bound chatType, final @Nullable Function<Audience, net.minecraft.network.chat.Component> msgFunction) {
+ final PlayerChatMessage toConsoleMessage = msgFunction == null ? ChatProcessor.this.message : ChatProcessor.this.message.withUnsignedContent(msgFunction.apply(ChatProcessor.this.server.console));
2022-12-08 17:32:29 +01:00
+ ChatProcessor.this.server.logChatMessage(toConsoleMessage.decoratedContent(), chatType, ChatProcessor.this.server.getPlayerList().verifyChatTrusted(toConsoleMessage) ? null : "Not Secure");
2022-08-01 21:34:55 +02:00
+ }
2021-06-11 14:02:28 +02:00
+ }
+
2022-02-28 22:38:23 +01:00
+ private Set<Audience> viewersFromLegacy(final Set<Player> recipients) {
+ if (recipients instanceof LazyPlayerSet lazyPlayerSet && lazyPlayerSet.isLazy()) {
+ return new LazyChatAudienceSet(this.server);
+ }
+ final HashSet<Audience> viewers = new HashSet<>(recipients);
+ viewers.add(this.server.console);
+ return viewers;
2021-06-11 14:02:28 +02:00
+ }
+
2022-08-01 21:34:55 +02:00
+ static String legacyDisplayName(final CraftPlayer player) {
2021-06-11 14:02:28 +02:00
+ return player.getDisplayName();
+ }
+
2022-08-01 21:34:55 +02:00
+ static Component displayName(final CraftPlayer player) {
2021-06-11 14:02:28 +02:00
+ return player.displayName();
+ }
+
2022-08-01 21:34:55 +02:00
+ private static ChatRenderer.Default defaultRenderer() {
+ return (ChatRenderer.Default) ChatRenderer.defaultRenderer();
+ }
+
2021-06-11 14:02:28 +02:00
+ private static ChatRenderer legacyRenderer(final String format) {
2021-10-13 11:00:40 +02:00
+ if (DEFAULT_LEGACY_FORMAT.equals(format)) {
2022-08-01 21:34:55 +02:00
+ return defaultRenderer();
2021-10-13 11:00:40 +02:00
+ }
2022-08-01 21:34:55 +02:00
+ return ChatRenderer.viewerUnaware((player, sourceDisplayName, message) -> legacySection().deserialize(legacyFormat(format, player, legacySection().serialize(message))));
+ }
+
+ static String legacyFormat(final String format, Player player, String message) {
+ return String.format(format, legacyDisplayName((CraftPlayer) player), message);
2021-06-11 14:02:28 +02:00
+ }
+
+ private void queueIfAsyncOrRunImmediately(final Waitable<Void> 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());
+ }
+ }
+
2022-02-28 22:38:23 +01:00
+ private void post(final Event event) {
+ this.server.server.getPluginManager().callEvent(event);
2021-06-11 14:02:28 +02:00
+ }
+
2022-08-01 21:34:55 +02:00
+ static boolean canYouHearMe(final HandlerList handlers) {
2021-06-11 14:02:28 +02:00
+ 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
2023-04-02 20:53:29 +02:00
index 0000000000000000000000000000000000000000..d496a9a6ad229e42f1c44e31eafa6974b9faced5
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/DisplayNames.java
2023-04-02 20:53:29 +02:00
@@ -0,0 +1,25 @@
2021-06-11 14:02:28 +02:00
+package io.papermc.paper.adventure;
+
2022-05-26 21:12:14 +02:00
+import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
2021-06-11 14:02:28 +02:00
+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());
+ }
+
2023-04-02 20:53:29 +02:00
+ @SuppressWarnings("deprecation") // Valid suppress due to supporting legacy display name formatting
2021-06-11 14:02:28 +02:00
+ public static String getLegacy(final ServerPlayer player) {
+ final String legacy = player.displayName;
+ if (legacy != null) {
2022-02-28 22:38:23 +01:00
+ // thank you for being worse than wet socks, Bukkit
2022-05-26 21:12:14 +02:00
+ return LegacyComponentSerializer.legacySection().serialize(player.adventure$displayName) + ChatColor.getLastColors(player.displayName);
2021-06-11 14:02:28 +02:00
+ }
2022-05-26 21:12:14 +02:00
+ return LegacyComponentSerializer.legacySection().serialize(player.adventure$displayName);
2021-06-11 14:02:28 +02:00
+ }
+}
2024-04-19 21:47:24 +02:00
diff --git a/src/main/java/io/papermc/paper/adventure/ImprovedChatDecorator.java b/src/main/java/io/papermc/paper/adventure/ImprovedChatDecorator.java
new file mode 100644
index 0000000000000000000000000000000000000000..0848ad9c7a6d386f0219b75df1ae4d08ba23aa59
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/ImprovedChatDecorator.java
@@ -0,0 +1,55 @@
+package io.papermc.paper.adventure;
+
+import io.papermc.paper.event.player.AsyncChatCommandDecorateEvent;
+import io.papermc.paper.event.player.AsyncChatDecorateEvent;
+import java.util.concurrent.CompletableFuture;
+import net.minecraft.commands.CommandSourceStack;
+import net.minecraft.network.chat.ChatDecorator;
+import net.minecraft.network.chat.Component;
+import net.minecraft.server.MinecraftServer;
+import net.minecraft.server.level.ServerPlayer;
+import org.bukkit.craftbukkit.entity.CraftPlayer;
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.checkerframework.framework.qual.DefaultQualifier;
+
+@DefaultQualifier(NonNull.class)
+public final class ImprovedChatDecorator implements ChatDecorator {
+ private final MinecraftServer server;
+
+ public ImprovedChatDecorator(final MinecraftServer server) {
+ this.server = server;
+ }
+
+ @Override
+ public CompletableFuture<Component> decorate(final @Nullable ServerPlayer sender, final Component message) {
+ return decorate(this.server, sender, null, message);
+ }
+
+ @Override
+ public CompletableFuture<Component> decorate(final @Nullable ServerPlayer sender, final @Nullable CommandSourceStack commandSourceStack, final Component message) {
+ return decorate(this.server, sender, commandSourceStack, message);
+ }
+
+ private static CompletableFuture<Component> decorate(final MinecraftServer server, final @Nullable ServerPlayer player, final @Nullable CommandSourceStack commandSourceStack, final Component originalMessage) {
+ return CompletableFuture.supplyAsync(() -> {
+ final net.kyori.adventure.text.Component initialResult = PaperAdventure.asAdventure(originalMessage);
+
+ final @Nullable CraftPlayer craftPlayer = player == null ? null : player.getBukkitEntity();
+
+ final AsyncChatDecorateEvent event;
+ if (commandSourceStack != null) {
+ // TODO more command decorate context
+ event = new AsyncChatCommandDecorateEvent(craftPlayer, initialResult);
+ } else {
+ event = new AsyncChatDecorateEvent(craftPlayer, initialResult);
+ }
+
+ if (event.callEvent()) {
+ return PaperAdventure.asVanilla(event.result());
+ }
+
+ return originalMessage;
+ }, server.chatExecutor);
+ }
+}
2021-06-11 14:02:28 +02:00
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
2021-06-19 00:47:40 +02:00
index 0000000000000000000000000000000000000000..2fd6c3e65354071af71c7d8ebb97b559b6e105ce
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/LazyChatAudienceSet.java
2021-06-19 00:47:40 +02:00
@@ -0,0 +1,26 @@
2021-06-11 14:02:28 +02:00
+package io.papermc.paper.adventure;
+
2021-06-19 00:47:40 +02:00
+import java.util.HashSet;
+import java.util.Set;
2021-06-11 14:02:28 +02:00
+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;
+
+final class LazyChatAudienceSet extends LazyHashSet<Audience> {
2021-06-19 00:47:40 +02:00
+ private final MinecraftServer server;
+
+ public LazyChatAudienceSet(final MinecraftServer server) {
+ this.server = server;
+ }
+
2021-06-11 14:02:28 +02:00
+ @Override
+ protected Set<Audience> makeReference() {
2021-06-19 00:47:40 +02:00
+ final Set<Player> playerSet = LazyPlayerSet.makePlayerSet(this.server);
2021-06-11 14:02:28 +02:00
+ final HashSet<Audience> audiences = new HashSet<>(playerSet);
+ audiences.add(Bukkit.getConsoleSender());
+ return audiences;
+ }
+}
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
2024-06-16 21:39:59 +02:00
index 0000000000000000000000000000000000000000..dc4837c577676115f0653acc35f55962a432e425
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/PaperAdventure.java
2024-06-16 21:39:59 +02:00
@@ -0,0 +1,479 @@
2021-06-11 14:02:28 +02:00
+package io.papermc.paper.adventure;
+
2024-04-25 05:14:51 +02:00
+import com.mojang.brigadier.StringReader;
2021-06-11 14:02:28 +02:00
+import com.mojang.brigadier.exceptions.CommandSyntaxException;
2024-04-25 05:14:51 +02:00
+import com.mojang.serialization.JavaOps;
2024-06-16 21:39:59 +02:00
+import com.mojang.serialization.JsonOps;
2021-06-11 14:02:28 +02:00
+import io.netty.util.AttributeKey;
+import java.io.IOException;
+import java.util.ArrayList;
2024-04-25 05:14:51 +02:00
+import java.util.Collections;
2024-04-25 03:10:18 +02:00
+import java.util.HashMap;
2021-06-11 14:02:28 +02:00
+import java.util.List;
+import java.util.Locale;
2023-12-12 07:02:06 +01:00
+import java.util.Map;
2023-05-31 03:36:16 +02:00
+import java.util.Optional;
2023-12-12 07:02:06 +01:00
+import java.util.concurrent.ConcurrentHashMap;
2023-05-31 03:36:16 +02:00
+import java.util.function.BiConsumer;
2021-06-11 14:02:28 +02:00
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
2023-12-25 11:51:44 +01:00
+import java.util.stream.StreamSupport;
2021-06-11 14:02:28 +02:00
+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;
2023-12-25 11:51:44 +01:00
+import net.kyori.adventure.text.TranslationArgument;
2024-04-25 03:10:18 +02:00
+import net.kyori.adventure.text.event.DataComponentValue;
2024-04-25 05:14:51 +02:00
+import net.kyori.adventure.text.event.DataComponentValueConverterRegistry;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.text.flattener.ComponentFlattener;
2024-02-17 21:22:00 +01:00
+import net.kyori.adventure.text.format.Style;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.text.format.TextColor;
2022-08-01 21:34:55 +02:00
+import net.kyori.adventure.text.serializer.ComponentSerializer;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
2021-12-22 23:56:37 +01:00
+import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
2021-12-22 08:07:17 +01:00
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.translation.GlobalTranslator;
2021-09-03 19:01:05 +02:00
+import net.kyori.adventure.translation.TranslationRegistry;
+import net.kyori.adventure.translation.Translator;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.util.Codec;
+import net.minecraft.ChatFormatting;
2022-11-23 05:53:50 +01:00
+import net.minecraft.commands.CommandSourceStack;
2023-05-31 03:36:16 +02:00
+import net.minecraft.core.Holder;
2024-04-25 05:14:51 +02:00
+import net.minecraft.core.component.DataComponentPatch;
+import net.minecraft.core.component.DataComponentType;
+import net.minecraft.core.component.DataComponents;
2023-05-31 03:36:16 +02:00
+import net.minecraft.core.registries.BuiltInRegistries;
2021-09-01 23:03:00 +02:00
+import net.minecraft.locale.Language;
2021-06-11 14:02:28 +02:00
+import net.minecraft.nbt.CompoundTag;
2024-04-25 03:10:18 +02:00
+import net.minecraft.nbt.NbtOps;
+import net.minecraft.nbt.Tag;
2021-06-11 14:02:28 +02:00
+import net.minecraft.nbt.TagParser;
2022-11-23 05:53:50 +01:00
+import net.minecraft.network.chat.ComponentUtils;
2023-05-31 03:36:16 +02:00
+import net.minecraft.network.protocol.Packet;
+import net.minecraft.network.protocol.game.ClientboundSoundEntityPacket;
+import net.minecraft.network.protocol.game.ClientboundSoundPacket;
2024-04-27 03:16:31 +02:00
+import net.minecraft.resources.RegistryOps;
2021-06-11 14:02:28 +02:00
+import net.minecraft.resources.ResourceLocation;
2024-04-25 05:14:51 +02:00
+import net.minecraft.server.network.Filterable;
2023-05-31 03:36:16 +02:00
+import net.minecraft.sounds.SoundEvent;
2021-06-11 14:02:28 +02:00
+import net.minecraft.sounds.SoundSource;
+import net.minecraft.world.BossEvent;
2023-05-31 03:36:16 +02:00
+import net.minecraft.world.entity.Entity;
2021-06-11 14:02:28 +02:00
+import net.minecraft.world.item.ItemStack;
2024-04-25 05:14:51 +02:00
+import net.minecraft.world.item.component.WrittenBookContent;
2022-11-23 05:53:50 +01:00
+import org.bukkit.command.CommandSender;
2024-04-27 03:16:31 +02:00
+import org.bukkit.craftbukkit.CraftRegistry;
2022-11-23 05:53:50 +01:00
+import org.bukkit.craftbukkit.command.VanillaCommandWrapper;
+import org.bukkit.craftbukkit.entity.CraftEntity;
2024-04-25 05:14:51 +02:00
+import org.intellij.lang.annotations.Subst;
2024-04-26 01:24:08 +02:00
+import org.jetbrains.annotations.Contract;
2021-12-22 08:07:17 +01:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2021-06-11 14:02:28 +02:00
+
2024-04-25 05:14:51 +02:00
+import static java.util.Objects.requireNonNull;
+
2021-06-11 14:02:28 +02:00
+public final class PaperAdventure {
+ private static final Pattern LOCALIZATION_PATTERN = Pattern.compile("%(?:(\\d+)\\$)?s");
+ public static final ComponentFlattener FLATTENER = ComponentFlattener.basic().toBuilder()
+ .complexMapper(TranslatableComponent.class, (translatable, consumer) -> {
2021-09-01 23:03:00 +02:00
+ if (!Language.getInstance().has(translatable.key())) {
2022-02-28 22:38:23 +01:00
+ for (final Translator source : GlobalTranslator.translator().sources()) {
2021-09-03 19:01:05 +02:00
+ if (source instanceof TranslationRegistry registry && registry.contains(translatable.key())) {
+ consumer.accept(GlobalTranslator.render(translatable, Locale.US));
+ return;
+ }
+ }
2021-09-01 23:03:00 +02:00
+ }
2023-04-20 09:05:41 +02:00
+ final @Nullable String fallback = translatable.fallback();
+ final @NotNull String translated = Language.getInstance().getOrDefault(translatable.key(), fallback != null ? fallback : translatable.key());
2021-06-11 14:02:28 +02:00
+
+ final Matcher matcher = LOCALIZATION_PATTERN.matcher(translated);
2023-12-25 11:51:44 +01:00
+ final List<TranslationArgument> args = translatable.arguments();
2021-06-11 14:02:28 +02:00
+ 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()) {
2023-12-25 11:51:44 +01:00
+ consumer.accept(args.get(idx).asComponent());
2021-06-11 14:02:28 +02:00
+ }
+ } catch (final NumberFormatException ex) {
+ // ignore, drop the format placeholder
+ }
+ } else {
+ final int idx = argPosition++;
+ if (idx < args.size()) {
2023-12-25 11:51:44 +01:00
+ consumer.accept(args.get(idx).asComponent());
2021-06-11 14:02:28 +02:00
+ }
+ }
+ }
+
+ // append tail
+ if (lastIdx < translated.length()) {
+ consumer.accept(Component.text(translated.substring(lastIdx)));
+ }
+ })
+ .build();
2022-10-12 05:05:28 +02:00
+ public static final AttributeKey<Locale> LOCALE_ATTRIBUTE = AttributeKey.valueOf("adventure:locale"); // init after FLATTENER because classloading triggered here might create a logger
2023-05-31 03:36:16 +02:00
+ @Deprecated
+ public static final PlainComponentSerializer PLAIN = PlainComponentSerializer.builder().flattener(FLATTENER).build();
2024-04-25 05:14:51 +02:00
+ public static final Codec<Tag, String, CommandSyntaxException, RuntimeException> NBT_CODEC = new Codec<>() {
2021-06-11 14:02:28 +02:00
+ @Override
2024-04-25 05:14:51 +02:00
+ public @NotNull Tag decode(final @NotNull String encoded) throws CommandSyntaxException {
+ return new TagParser(new StringReader(encoded)).readValue();
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
2024-04-25 05:14:51 +02:00
+ public @NotNull String encode(final @NotNull Tag decoded) {
2021-06-11 14:02:28 +02:00
+ return decoded.toString();
+ }
+ };
2024-06-16 21:39:59 +02:00
+ public static final ComponentSerializer<Component, Component, net.minecraft.network.chat.Component> WRAPPER_AWARE_SERIALIZER = new WrapperAwareSerializer(() -> CraftRegistry.getMinecraftRegistry().createSerializationContext(JavaOps.INSTANCE));
2021-06-11 14:02:28 +02:00
+
+ private PaperAdventure() {
+ }
+
+ // Key
+
+ public static ResourceLocation asVanilla(final Key key) {
2024-06-14 14:28:06 +02:00
+ return ResourceLocation.fromNamespaceAndPath(key.namespace(), key.value());
2021-06-11 14:02:28 +02:00
+ }
+
+ public static ResourceLocation asVanillaNullable(final Key key) {
+ if (key == null) {
+ return null;
+ }
2022-02-28 22:38:23 +01:00
+ return asVanilla(key);
2021-06-11 14:02:28 +02:00
+ }
+
+ // Component
+
2024-04-19 21:47:24 +02:00
+ public static @NotNull Component asAdventure(@Nullable final net.minecraft.network.chat.Component component) {
2023-12-12 07:02:06 +01:00
+ return component == null ? Component.empty() : WRAPPER_AWARE_SERIALIZER.deserialize(component);
2021-06-11 14:02:28 +02:00
+ }
+
2023-12-25 11:51:44 +01:00
+ public static ArrayList<Component> asAdventure(final List<? extends net.minecraft.network.chat.Component> vanillas) {
2021-06-11 14:02:28 +02:00
+ final ArrayList<Component> adventures = new ArrayList<>(vanillas.size());
+ for (final net.minecraft.network.chat.Component vanilla : vanillas) {
+ adventures.add(asAdventure(vanilla));
+ }
+ return adventures;
+ }
+
+ public static ArrayList<Component> asAdventureFromJson(final List<String> jsonStrings) {
+ final ArrayList<Component> adventures = new ArrayList<>(jsonStrings.size());
+ for (final String json : jsonStrings) {
+ adventures.add(GsonComponentSerializer.gson().deserialize(json));
+ }
+ return adventures;
+ }
+
2023-03-20 09:18:06 +01:00
+ public static List<String> asJson(final List<? extends Component> adventures) {
2021-06-11 14:02:28 +02:00
+ final List<String> jsons = new ArrayList<>(adventures.size());
+ for (final Component component : adventures) {
+ jsons.add(GsonComponentSerializer.gson().serialize(component));
+ }
+ return jsons;
+ }
+
2024-04-26 01:24:08 +02:00
+ public static net.minecraft.network.chat.@NotNull Component asVanillaNullToEmpty(final @Nullable Component component) {
+ if (component == null) return net.minecraft.network.chat.CommonComponents.EMPTY;
+ return asVanilla(component);
+ }
+
+ @Contract("null -> null; !null -> !null")
+ public static net.minecraft.network.chat.Component asVanilla(final @Nullable Component component) {
2021-12-22 08:07:17 +01:00
+ if (component == null) return null;
2021-06-11 14:02:28 +02:00
+ if (true) return new AdventureComponent(component);
2023-12-12 07:02:06 +01:00
+ return WRAPPER_AWARE_SERIALIZER.serialize(component);
2021-06-11 14:02:28 +02:00
+ }
+
2023-12-25 11:51:44 +01:00
+ public static List<net.minecraft.network.chat.Component> asVanilla(final List<? extends Component> adventures) {
2021-06-11 14:02:28 +02:00
+ final List<net.minecraft.network.chat.Component> 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) {
2022-05-26 21:12:14 +02:00
+ return GsonComponentSerializer.gson().serialize(translated(component, locale));
2021-06-11 14:02:28 +02:00
+ }
+
2023-12-25 11:51:44 +01:00
+ public static boolean hasAnyTranslations() {
+ return StreamSupport.stream(GlobalTranslator.translator().sources().spliterator(), false)
+ .anyMatch(t -> t.hasAnyTranslations().toBooleanOrElse(true));
+ }
+
2023-12-12 07:02:06 +01:00
+ private static final Map<Locale, com.mojang.serialization.Codec<Component>> LOCALIZED_CODECS = new ConcurrentHashMap<>();
+
2023-12-12 22:40:33 +01:00
+ public static com.mojang.serialization.Codec<Component> localizedCodec(final @Nullable Locale l) {
+ if (l == null) {
+ return AdventureCodecs.COMPONENT_CODEC;
+ }
2023-12-12 07:02:06 +01:00
+ return LOCALIZED_CODECS.computeIfAbsent(l, locale -> AdventureCodecs.COMPONENT_CODEC.xmap(
+ component -> component, // decode
+ component -> translated(component, locale) // encode
+ ));
2021-06-11 14:02:28 +02:00
+ }
+
2021-07-20 01:11:06 +02:00
+ public static String asPlain(final Component component, final Locale locale) {
2022-05-26 21:12:14 +02:00
+ return PlainTextComponentSerializer.plainText().serialize(translated(component, locale));
2021-07-20 01:11:06 +02:00
+ }
+
2022-02-28 22:38:23 +01:00
+ private static Component translated(final Component component, final Locale locale) {
2023-12-25 11:51:44 +01:00
+ //noinspection ConstantValue
2022-02-28 22:38:23 +01:00
+ return GlobalTranslator.render(
+ component,
+ // play it safe
+ locale != null
+ ? locale
+ : Locale.US
+ );
2021-06-11 14:02:28 +02:00
+ }
+
2023-05-31 03:36:16 +02:00
+ public static Component resolveWithContext(final @NotNull Component component, final @Nullable CommandSender context, final @Nullable org.bukkit.entity.Entity scoreboardSubject, final boolean bypassPermissions) throws IOException {
2022-11-23 05:53:50 +01:00
+ final CommandSourceStack css = context != null ? VanillaCommandWrapper.getListener(context) : null;
+ Boolean previous = null;
+ if (css != null && bypassPermissions) {
+ previous = css.bypassSelectorPermissions;
+ css.bypassSelectorPermissions = true;
+ }
+ try {
+ return asAdventure(ComponentUtils.updateForEntity(css, asVanilla(component), scoreboardSubject == null ? null : ((CraftEntity) scoreboardSubject).getHandle(), 0));
2023-12-25 11:51:44 +01:00
+ } catch (final CommandSyntaxException e) {
2022-11-23 05:53:50 +01:00
+ throw new IOException(e);
+ } finally {
+ if (css != null && previous != null) {
+ css.bypassSelectorPermissions = previous;
+ }
+ }
+ }
+
2021-06-11 14:02:28 +02:00
+ // BossBar
+
+ public static BossEvent.BossBarColor asVanilla(final BossBar.Color color) {
2021-12-22 08:07:17 +01:00
+ return switch (color) {
+ case PINK -> BossEvent.BossBarColor.PINK;
+ case BLUE -> BossEvent.BossBarColor.BLUE;
+ case RED -> BossEvent.BossBarColor.RED;
+ case GREEN -> BossEvent.BossBarColor.GREEN;
+ case YELLOW -> BossEvent.BossBarColor.YELLOW;
+ case PURPLE -> BossEvent.BossBarColor.PURPLE;
+ case WHITE -> BossEvent.BossBarColor.WHITE;
+ };
2021-06-11 14:02:28 +02:00
+ }
+
+ public static BossBar.Color asAdventure(final BossEvent.BossBarColor color) {
2021-12-22 08:07:17 +01:00
+ return switch (color) {
+ case PINK -> BossBar.Color.PINK;
+ case BLUE -> BossBar.Color.BLUE;
+ case RED -> BossBar.Color.RED;
+ case GREEN -> BossBar.Color.GREEN;
+ case YELLOW -> BossBar.Color.YELLOW;
+ case PURPLE -> BossBar.Color.PURPLE;
+ case WHITE -> BossBar.Color.WHITE;
+ };
2021-06-11 14:02:28 +02:00
+ }
+
+ public static BossEvent.BossBarOverlay asVanilla(final BossBar.Overlay overlay) {
2021-12-22 08:07:17 +01:00
+ return switch (overlay) {
+ case PROGRESS -> BossEvent.BossBarOverlay.PROGRESS;
+ case NOTCHED_6 -> BossEvent.BossBarOverlay.NOTCHED_6;
+ case NOTCHED_10 -> BossEvent.BossBarOverlay.NOTCHED_10;
+ case NOTCHED_12 -> BossEvent.BossBarOverlay.NOTCHED_12;
+ case NOTCHED_20 -> BossEvent.BossBarOverlay.NOTCHED_20;
+ };
2021-06-11 14:02:28 +02:00
+ }
+
+ public static BossBar.Overlay asAdventure(final BossEvent.BossBarOverlay overlay) {
2021-12-22 08:07:17 +01:00
+ return switch (overlay) {
+ case PROGRESS -> BossBar.Overlay.PROGRESS;
+ case NOTCHED_6 -> BossBar.Overlay.NOTCHED_6;
+ case NOTCHED_10 -> BossBar.Overlay.NOTCHED_10;
+ case NOTCHED_12 -> BossBar.Overlay.NOTCHED_12;
+ case NOTCHED_20 -> BossBar.Overlay.NOTCHED_20;
+ };
2021-06-11 14:02:28 +02:00
+ }
+
+ 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);
2024-04-25 05:14:51 +02:00
+ item.set(DataComponents.WRITTEN_BOOK_CONTENT, new WrittenBookContent(
+ Filterable.passThrough(validateField(asPlain(book.title(), locale), WrittenBookContent.TITLE_MAX_LENGTH, "title")),
+ asPlain(book.author(), locale),
+ 0,
+ book.pages().stream().map(c -> Filterable.passThrough(PaperAdventure.asVanilla(c))).toList(), // TODO should we validate legnth?
+ false
+ ));
2021-06-11 14:02:28 +02:00
+ return item;
+ }
+
2021-07-20 01:11:06 +02:00
+ private static String validateField(final String content, final int length, final String name) {
+ final int actual = content.length();
+ if (actual > length) {
+ throw new IllegalArgumentException("Field '" + name + "' has a maximum length of " + length + " but was passed '" + content + "', which was " + actual + " characters long.");
+ }
+ return content;
+ }
+
2021-06-11 14:02:28 +02:00
+ // Sounds
+
+ public static SoundSource asVanilla(final Sound.Source source) {
2022-02-28 22:38:23 +01:00
+ return switch (source) {
+ case MASTER -> SoundSource.MASTER;
+ case MUSIC -> SoundSource.MUSIC;
+ case RECORD -> SoundSource.RECORDS;
+ case WEATHER -> SoundSource.WEATHER;
+ case BLOCK -> SoundSource.BLOCKS;
+ case HOSTILE -> SoundSource.HOSTILE;
+ case NEUTRAL -> SoundSource.NEUTRAL;
+ case PLAYER -> SoundSource.PLAYERS;
+ case AMBIENT -> SoundSource.AMBIENT;
+ case VOICE -> SoundSource.VOICE;
+ };
2021-06-11 14:02:28 +02:00
+ }
+
+ public static @Nullable SoundSource asVanillaNullable(final Sound.@Nullable Source source) {
+ if (source == null) {
+ return null;
+ }
+ return asVanilla(source);
+ }
+
2023-05-31 03:36:16 +02:00
+ public static Packet<?> asSoundPacket(final Sound sound, final double x, final double y, final double z, final long seed, @Nullable BiConsumer<Packet<?>, Float> packetConsumer) {
+ final ResourceLocation name = asVanilla(sound.name());
+ final Optional<SoundEvent> soundEvent = BuiltInRegistries.SOUND_EVENT.getOptional(name);
+ final SoundSource source = asVanilla(sound.source());
+
+ final Holder<SoundEvent> soundEventHolder = soundEvent.map(BuiltInRegistries.SOUND_EVENT::wrapAsHolder).orElseGet(() -> Holder.direct(SoundEvent.createVariableRangeEvent(name)));
+ final Packet<?> packet = new ClientboundSoundPacket(soundEventHolder, source, x, y, z, sound.volume(), sound.pitch(), seed);
+ if (packetConsumer != null) {
+ packetConsumer.accept(packet, soundEventHolder.value().getRange(sound.volume()));
+ }
+ return packet;
+ }
+
+ public static Packet<?> asSoundPacket(final Sound sound, final Entity emitter, final long seed, @Nullable BiConsumer<Packet<?>, Float> packetConsumer) {
+ final ResourceLocation name = asVanilla(sound.name());
+ final Optional<SoundEvent> soundEvent = BuiltInRegistries.SOUND_EVENT.getOptional(name);
+ final SoundSource source = asVanilla(sound.source());
+
+ final Holder<SoundEvent> soundEventHolder = soundEvent.map(BuiltInRegistries.SOUND_EVENT::wrapAsHolder).orElseGet(() -> Holder.direct(SoundEvent.createVariableRangeEvent(name)));
+ final Packet<?> packet = new ClientboundSoundEntityPacket(soundEventHolder, source, emitter, sound.volume(), sound.pitch(), seed);
+ if (packetConsumer != null) {
+ packetConsumer.accept(packet, soundEventHolder.value().getRange(sound.volume()));
+ }
+ return packet;
+ }
+
2021-06-11 14:02:28 +02:00
+ // NBT
+
2024-04-25 05:14:51 +02:00
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public static Map<Key, ? extends DataComponentValue> asAdventure(
+ final DataComponentPatch patch
2024-04-25 03:10:18 +02:00
+ ) {
2024-04-25 05:14:51 +02:00
+ if (patch.isEmpty()) {
+ return Collections.emptyMap();
+ }
2024-04-25 03:10:18 +02:00
+ final Map<Key, DataComponentValue> map = new HashMap<>();
2024-04-25 05:14:51 +02:00
+ for (final Map.Entry<DataComponentType<?>, Optional<?>> entry : patch.entrySet()) {
+ if (entry.getKey().isTransient()) continue;
+ @Subst("key:value") final String typeKey = requireNonNull(BuiltInRegistries.DATA_COMPONENT_TYPE.getKey(entry.getKey())).toString();
+ if (entry.getValue().isEmpty()) {
+ map.put(Key.key(typeKey), DataComponentValue.removed());
+ } else {
+ map.put(Key.key(typeKey), new DataComponentValueImpl(entry.getKey().codec(), entry.getValue().get()));
+ }
2024-04-25 03:10:18 +02:00
+ }
+ return map;
+ }
+
2024-04-25 05:14:51 +02:00
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public static DataComponentPatch asVanilla(final Map<? extends Key, ? extends DataComponentValue> map) {
+ if (map.isEmpty()) {
+ return DataComponentPatch.EMPTY;
+ }
+ final DataComponentPatch.Builder builder = DataComponentPatch.builder();
+ map.forEach((key, dataComponentValue) -> {
+ final DataComponentType<?> type = requireNonNull(BuiltInRegistries.DATA_COMPONENT_TYPE.get(asVanilla(key)));
+ if (dataComponentValue instanceof DataComponentValue.Removed) {
+ builder.remove(type);
+ return;
+ }
+ final DataComponentValueImpl<?> converted = DataComponentValueConverterRegistry.convert(DataComponentValueImpl.class, key, dataComponentValue);
+ builder.set((DataComponentType) type, (Object) converted.value());
+ });
+ return builder.build();
+ }
+
+ public record DataComponentValueImpl<T>(com.mojang.serialization.Codec<T> codec, T value) implements DataComponentValue.TagSerializable {
+
+ @Override
+ public @NotNull BinaryTagHolder asBinaryTag() {
2024-06-03 00:19:17 +02:00
+ return BinaryTagHolder.encode(this.codec.encodeStart(CraftRegistry.getMinecraftRegistry().createSerializationContext(NbtOps.INSTANCE), this.value).getOrThrow(IllegalArgumentException::new), NBT_CODEC);
2024-04-25 05:14:51 +02:00
+ }
+ }
+
2021-06-11 14:02:28 +02:00
+ public static @Nullable BinaryTagHolder asBinaryTagHolder(final @Nullable CompoundTag tag) {
+ if (tag == null) {
+ return null;
+ }
2024-04-25 05:14:51 +02:00
+ return BinaryTagHolder.encode(tag, NBT_CODEC);
2021-06-11 14:02:28 +02:00
+ }
+
+ // Colors
+
2021-12-22 08:07:17 +01:00
+ public static @NotNull TextColor asAdventure(final ChatFormatting formatting) {
+ final Integer color = formatting.getColor();
+ if (color == null) {
2021-06-11 14:02:28 +02:00
+ throw new IllegalArgumentException("Not a valid color");
+ }
2021-12-22 08:07:17 +01:00
+ return TextColor.color(color);
2021-06-11 14:02:28 +02:00
+ }
+
2021-12-22 08:07:17 +01:00
+ public static @Nullable ChatFormatting asVanilla(final TextColor color) {
2021-06-11 14:02:28 +02:00
+ return ChatFormatting.getByHexValue(color.value());
+ }
2024-02-17 21:22:00 +01:00
+
+ // Style
+
2024-04-25 05:14:51 +02:00
+ public static net.minecraft.network.chat.Style asVanilla(final Style style) {
2024-06-03 00:19:17 +02:00
+ final RegistryOps<Object> ops = CraftRegistry.getMinecraftRegistry().createSerializationContext(JavaOps.INSTANCE);
2024-04-25 05:14:51 +02:00
+ final Object encoded = AdventureCodecs.STYLE_MAP_CODEC.codec()
2024-04-28 05:32:11 +02:00
+ .encodeStart(ops, style).getOrThrow(IllegalStateException::new);
2024-02-17 21:22:00 +01:00
+
2024-04-25 05:14:51 +02:00
+ return net.minecraft.network.chat.Style.Serializer.CODEC
2024-04-27 03:16:31 +02:00
+ .parse(ops, encoded).getOrThrow(IllegalStateException::new);
2024-02-17 21:22:00 +01:00
+ }
+
2024-04-25 05:14:51 +02:00
+ public static Style asAdventure(final net.minecraft.network.chat.Style style) {
2024-06-03 00:19:17 +02:00
+ final RegistryOps<Object> ops = CraftRegistry.getMinecraftRegistry().createSerializationContext(JavaOps.INSTANCE);
2024-04-25 05:14:51 +02:00
+ final Object encoded = net.minecraft.network.chat.Style.Serializer.CODEC
2024-04-28 05:32:11 +02:00
+ .encodeStart(ops, style).getOrThrow(IllegalStateException::new);
2024-02-17 21:22:00 +01:00
+
2024-04-25 05:14:51 +02:00
+ return AdventureCodecs.STYLE_MAP_CODEC.codec()
2024-04-27 03:16:31 +02:00
+ .parse(ops, encoded).getOrThrow(IllegalStateException::new);
2024-02-17 21:22:00 +01:00
+ }
2021-06-11 14:02:28 +02:00
+}
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
2024-06-16 21:39:59 +02:00
index 0000000000000000000000000000000000000000..a16344476abbb4f3e8aac26d4add9da53b7fc7df
2021-06-11 14:02:28 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/WrapperAwareSerializer.java
2024-06-16 21:39:59 +02:00
@@ -0,0 +1,43 @@
2021-06-11 14:02:28 +02:00
+package io.papermc.paper.adventure;
+
2024-06-16 21:39:59 +02:00
+import com.google.common.base.Suppliers;
2023-12-12 07:02:06 +01:00
+import com.mojang.datafixers.util.Pair;
2024-04-25 21:16:00 +02:00
+import com.mojang.serialization.JavaOps;
2024-06-16 21:39:59 +02:00
+import java.util.function.Supplier;
2021-06-11 14:02:28 +02:00
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.serializer.ComponentSerializer;
2023-12-12 07:02:06 +01:00
+import net.minecraft.network.chat.ComponentSerialization;
2024-04-27 03:16:31 +02:00
+import net.minecraft.resources.RegistryOps;
+import org.bukkit.craftbukkit.CraftRegistry;
2021-06-11 14:02:28 +02:00
+
2024-06-16 21:39:59 +02:00
+public final class WrapperAwareSerializer implements ComponentSerializer<Component, Component, net.minecraft.network.chat.Component> {
+
+ private final Supplier<RegistryOps<Object>> javaOps;
+
+ public WrapperAwareSerializer(final Supplier<RegistryOps<Object>> javaOps) {
+ this.javaOps = Suppliers.memoize(javaOps::get);
+ }
+
2021-06-11 14:02:28 +02:00
+ @Override
+ public Component deserialize(final net.minecraft.network.chat.Component input) {
+ if (input instanceof AdventureComponent) {
2021-12-22 08:07:17 +01:00
+ return ((AdventureComponent) input).adventure;
2021-06-11 14:02:28 +02:00
+ }
2024-06-16 21:39:59 +02:00
+ final RegistryOps<Object> ops = this.javaOps.get();
2024-04-27 03:16:31 +02:00
+ final Object obj = ComponentSerialization.CODEC.encodeStart(ops, input)
2024-04-25 21:16:00 +02:00
+ .getOrThrow(s -> new RuntimeException("Failed to encode Minecraft Component: " + input + "; " + s));
2024-04-27 03:16:31 +02:00
+ final Pair<Component, Object> converted = AdventureCodecs.COMPONENT_CODEC.decode(ops, obj)
2024-04-25 21:16:00 +02:00
+ .getOrThrow(s -> new RuntimeException("Failed to decode to adventure Component: " + obj + "; " + s));
2023-12-12 07:02:06 +01:00
+ return converted.getFirst();
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public net.minecraft.network.chat.Component serialize(final Component component) {
2024-06-16 21:39:59 +02:00
+ final RegistryOps<Object> ops = this.javaOps.get();
2024-04-27 03:16:31 +02:00
+ final Object obj = AdventureCodecs.COMPONENT_CODEC.encodeStart(ops, component)
2024-04-25 21:16:00 +02:00
+ .getOrThrow(s -> new RuntimeException("Failed to encode adventure Component: " + component + "; " + s));
2024-04-27 03:16:31 +02:00
+ final Pair<net.minecraft.network.chat.Component, Object> converted = ComponentSerialization.CODEC.decode(ops, obj)
2024-04-25 21:16:00 +02:00
+ .getOrThrow(s -> new RuntimeException("Failed to decode to Minecraft Component: " + obj + "; " + s));
2023-12-12 07:02:06 +01:00
+ return converted.getFirst();
2022-05-26 21:12:14 +02:00
+ }
+}
2023-06-12 23:43:39 +02:00
diff --git a/src/main/java/io/papermc/paper/adventure/providers/BossBarImplementationProvider.java b/src/main/java/io/papermc/paper/adventure/providers/BossBarImplementationProvider.java
new file mode 100644
index 0000000000000000000000000000000000000000..2ee72fe7cb56e70404b8c86f0c9578750a45af03
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/BossBarImplementationProvider.java
@@ -0,0 +1,14 @@
+package io.papermc.paper.adventure.providers;
+
+import io.papermc.paper.adventure.BossBarImplementationImpl;
+import net.kyori.adventure.bossbar.BossBar;
+import net.kyori.adventure.bossbar.BossBarImplementation;
+import org.jetbrains.annotations.NotNull;
+
+@SuppressWarnings("UnstableApiUsage") // permitted provider
+public class BossBarImplementationProvider implements BossBarImplementation.Provider {
+ @Override
+ public @NotNull BossBarImplementation create(final @NotNull BossBar bar) {
+ return new BossBarImplementationImpl(bar);
+ }
+}
2023-03-15 13:19:54 +01:00
diff --git a/src/main/java/io/papermc/paper/adventure/providers/ClickCallbackProviderImpl.java b/src/main/java/io/papermc/paper/adventure/providers/ClickCallbackProviderImpl.java
new file mode 100644
2023-08-28 13:21:13 +02:00
index 0000000000000000000000000000000000000000..23432eea862c6df716d7726a32da3a0612a3fb77
2023-03-15 13:19:54 +01:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/ClickCallbackProviderImpl.java
2023-03-19 19:25:45 +01:00
@@ -0,0 +1,96 @@
2023-03-15 13:19:54 +01:00
+package io.papermc.paper.adventure.providers;
+
2023-03-19 19:25:45 +01:00
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
2023-03-15 13:19:54 +01:00
+import net.kyori.adventure.audience.Audience;
+import net.kyori.adventure.text.event.ClickCallback;
+import net.kyori.adventure.text.event.ClickEvent;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+@SuppressWarnings("UnstableApiUsage") // permitted provider
+public class ClickCallbackProviderImpl implements ClickCallback.Provider {
+
+ public static final CallbackManager CALLBACK_MANAGER = new CallbackManager();
+
+ @Override
+ public @NotNull ClickEvent create(final @NotNull ClickCallback<Audience> callback, final ClickCallback.@NotNull Options options) {
2023-08-28 13:21:13 +02:00
+ return ClickEvent.runCommand("/paper:callback " + CALLBACK_MANAGER.addCallback(callback, options));
2023-03-15 13:19:54 +01:00
+ }
+
+ public static final class CallbackManager {
+
2023-03-19 19:25:45 +01:00
+ private final Map<UUID, StoredCallback> callbacks = new HashMap<>();
2023-03-15 13:19:54 +01:00
+ private final Queue<StoredCallback> queue = new ConcurrentLinkedQueue<>();
+
+ private CallbackManager() {
+ }
+
2023-03-19 19:25:45 +01:00
+ public UUID addCallback(final @NotNull ClickCallback<Audience> callback, final ClickCallback.@NotNull Options options) {
+ final UUID id = UUID.randomUUID();
2023-03-15 13:19:54 +01:00
+ this.queue.add(new StoredCallback(callback, options, id));
+ return id;
+ }
+
+ public void handleQueue(final int currentTick) {
+ // Evict expired entries
+ if (currentTick % 100 == 0) {
+ this.callbacks.values().removeIf(callback -> !callback.valid());
+ }
+
+ // Add entries from queue
+ StoredCallback callback;
+ while ((callback = this.queue.poll()) != null) {
+ this.callbacks.put(callback.id(), callback);
+ }
+ }
+
2023-03-19 19:25:45 +01:00
+ public void runCallback(final @NotNull Audience audience, final UUID id) {
2023-03-15 13:19:54 +01:00
+ final StoredCallback callback = this.callbacks.get(id);
+ if (callback != null && callback.valid()) { //TODO Message if expired/invalid?
+ callback.takeUse();
+ callback.callback.accept(audience);
+ }
+ }
+ }
+
+ private static final class StoredCallback {
+ private final long startedAt = System.nanoTime();
+ private final ClickCallback<Audience> callback;
+ private final long lifetime;
2023-03-19 19:25:45 +01:00
+ private final UUID id;
2023-03-15 13:19:54 +01:00
+ private int remainingUses;
+
2023-03-19 19:25:45 +01:00
+ private StoredCallback(final @NotNull ClickCallback<Audience> callback, final ClickCallback.@NotNull Options options, final UUID id) {
2023-03-15 13:19:54 +01:00
+ this.callback = callback;
+ this.lifetime = options.lifetime().toNanos();
+ this.remainingUses = options.uses();
+ this.id = id;
+ }
+
+ public void takeUse() {
+ if (this.remainingUses != ClickCallback.UNLIMITED_USES) {
+ this.remainingUses--;
+ }
+ }
+
+ public boolean hasRemainingUses() {
+ return this.remainingUses == ClickCallback.UNLIMITED_USES || this.remainingUses > 0;
+ }
+
+ public boolean expired() {
+ return System.nanoTime() - this.startedAt >= this.lifetime;
+ }
+
+ public boolean valid() {
+ return hasRemainingUses() && !expired();
+ }
+
2023-03-19 19:25:45 +01:00
+ public UUID id() {
2023-03-15 13:19:54 +01:00
+ return this.id;
+ }
+ }
+}
2022-06-12 23:07:40 +02:00
diff --git a/src/main/java/io/papermc/paper/adventure/providers/ComponentLoggerProviderImpl.java b/src/main/java/io/papermc/paper/adventure/providers/ComponentLoggerProviderImpl.java
new file mode 100644
2023-12-25 11:51:44 +01:00
index 0000000000000000000000000000000000000000..8323f135d6bf2e1f12525e05094ffa3f2420e7e1
2022-06-12 23:07:40 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/ComponentLoggerProviderImpl.java
2023-12-25 11:51:44 +01:00
@@ -0,0 +1,20 @@
2022-06-12 23:07:40 +02:00
+package io.papermc.paper.adventure.providers;
+
+import io.papermc.paper.adventure.PaperAdventure;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import net.kyori.adventure.text.logger.slf4j.ComponentLoggerProvider;
+import org.jetbrains.annotations.NotNull;
+import org.slf4j.LoggerFactory;
+
2023-12-25 11:51:44 +01:00
+@SuppressWarnings("UnstableApiUsage")
2022-06-12 23:07:40 +02:00
+public class ComponentLoggerProviderImpl implements ComponentLoggerProvider {
+ @Override
+ public @NotNull ComponentLogger logger(@NotNull LoggerHelper helper, @NotNull String name) {
+ return helper.delegating(LoggerFactory.getLogger(name), this::serialize);
+ }
+
+ private String serialize(final Component message) {
+ return PaperAdventure.asPlain(message, null);
+ }
+}
2024-04-25 05:14:51 +02:00
diff --git a/src/main/java/io/papermc/paper/adventure/providers/DataComponentValueConverterProviderImpl.java b/src/main/java/io/papermc/paper/adventure/providers/DataComponentValueConverterProviderImpl.java
new file mode 100644
2024-06-03 00:19:17 +02:00
index 0000000000000000000000000000000000000000..6b37c0ebda4a0cfcf9c3b2c3483ffababe622555
2024-04-25 05:14:51 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/DataComponentValueConverterProviderImpl.java
2024-06-03 00:19:17 +02:00
@@ -0,0 +1,82 @@
2024-04-25 05:14:51 +02:00
+package io.papermc.paper.adventure.providers;
+
+import com.google.gson.JsonElement;
+import com.mojang.brigadier.exceptions.CommandSyntaxException;
2024-06-03 00:19:17 +02:00
+import com.mojang.serialization.DynamicOps;
2024-04-25 05:14:51 +02:00
+import com.mojang.serialization.JsonOps;
+import io.papermc.paper.adventure.PaperAdventure;
+import java.util.List;
+import net.kyori.adventure.key.Key;
+import net.kyori.adventure.nbt.api.BinaryTagHolder;
+import net.kyori.adventure.text.event.DataComponentValue;
+import net.kyori.adventure.text.event.DataComponentValueConverterRegistry;
+import net.kyori.adventure.text.serializer.gson.GsonDataComponentValue;
+import net.minecraft.core.component.DataComponentType;
+import net.minecraft.core.registries.BuiltInRegistries;
+import net.minecraft.nbt.NbtOps;
+import net.minecraft.nbt.Tag;
2024-06-03 00:19:17 +02:00
+import net.minecraft.resources.RegistryOps;
+import org.bukkit.craftbukkit.CraftRegistry;
2024-04-25 05:14:51 +02:00
+import org.checkerframework.checker.nullness.qual.NonNull;
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.checkerframework.framework.qual.DefaultQualifier;
+
2024-04-25 21:40:53 +02:00
+import static net.kyori.adventure.text.serializer.gson.GsonDataComponentValue.gsonDataComponentValue;
2024-04-25 05:14:51 +02:00
+
+@DefaultQualifier(NonNull.class)
+public class DataComponentValueConverterProviderImpl implements DataComponentValueConverterRegistry.Provider {
+
+ static final Key ID = Key.key("adventure", "platform/paper");
+
+ @Override
+ public Key id() {
+ return ID;
+ }
+
2024-06-03 00:19:17 +02:00
+ private static <T> RegistryOps<T> createOps(final DynamicOps<T> delegate) {
+ return CraftRegistry.getMinecraftRegistry().createSerializationContext(delegate);
+ }
+
2024-04-25 05:14:51 +02:00
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ @Override
+ public Iterable<DataComponentValueConverterRegistry.Conversion<?, ?>> conversions() {
+ return List.of(
+ DataComponentValueConverterRegistry.Conversion.convert(
+ PaperAdventure.DataComponentValueImpl.class,
+ GsonDataComponentValue.class,
2024-06-03 00:19:17 +02:00
+ (key, dataComponentValue) -> gsonDataComponentValue((JsonElement) dataComponentValue.codec().encodeStart(createOps(JsonOps.INSTANCE), dataComponentValue.value()).getOrThrow())
2024-04-25 05:14:51 +02:00
+ ),
+ DataComponentValueConverterRegistry.Conversion.convert(
+ GsonDataComponentValue.class,
+ PaperAdventure.DataComponentValueImpl.class,
+ (key, dataComponentValue) -> {
+ final @Nullable DataComponentType<?> type = BuiltInRegistries.DATA_COMPONENT_TYPE.get(PaperAdventure.asVanilla(key));
+ if (type == null) {
+ throw new IllegalArgumentException("Unknown data component type: " + key);
+ }
2024-06-03 00:19:17 +02:00
+ return new PaperAdventure.DataComponentValueImpl(type.codecOrThrow(), type.codecOrThrow().parse(createOps(JsonOps.INSTANCE), dataComponentValue.element()).getOrThrow(IllegalArgumentException::new));
2024-04-25 05:14:51 +02:00
+ }
+ ),
+ DataComponentValueConverterRegistry.Conversion.convert(
+ PaperAdventure.DataComponentValueImpl.class,
+ DataComponentValue.TagSerializable.class,
2024-06-03 00:19:17 +02:00
+ (key, dataComponentValue) -> BinaryTagHolder.encode((Tag) dataComponentValue.codec().encodeStart(createOps(NbtOps.INSTANCE), dataComponentValue.value()).getOrThrow(), PaperAdventure.NBT_CODEC)
2024-04-25 05:14:51 +02:00
+ ),
+ DataComponentValueConverterRegistry.Conversion.convert(
+ DataComponentValue.TagSerializable.class,
+ PaperAdventure.DataComponentValueImpl.class,
+ (key, tagSerializable) -> {
+ final @Nullable DataComponentType<?> type = BuiltInRegistries.DATA_COMPONENT_TYPE.get(PaperAdventure.asVanilla(key));
+ if (type == null) {
+ throw new IllegalArgumentException("Unknown data component type: " + key);
+ }
+ try {
2024-06-03 00:19:17 +02:00
+ return new PaperAdventure.DataComponentValueImpl(type.codecOrThrow(), type.codecOrThrow().parse(createOps(NbtOps.INSTANCE), tagSerializable.asBinaryTag().get(PaperAdventure.NBT_CODEC)).getOrThrow(IllegalArgumentException::new));
2024-04-25 05:14:51 +02:00
+ } catch (final CommandSyntaxException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+ )
+ );
+ }
+}
2022-05-26 21:12:14 +02:00
diff --git a/src/main/java/io/papermc/paper/adventure/providers/GsonComponentSerializerProviderImpl.java b/src/main/java/io/papermc/paper/adventure/providers/GsonComponentSerializerProviderImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..c620d5aa2b0208b769dbe9563f0e99edc9a91047
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/GsonComponentSerializerProviderImpl.java
@@ -0,0 +1,30 @@
+package io.papermc.paper.adventure.providers;
+
+import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.function.Consumer;
+
+@SuppressWarnings("UnstableApiUsage") // permitted provider
+public class GsonComponentSerializerProviderImpl implements GsonComponentSerializer.Provider {
+
+ @Override
+ public @NotNull GsonComponentSerializer gson() {
+ return GsonComponentSerializer.builder()
+ .legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE)
+ .build();
+ }
+
+ @Override
+ public @NotNull GsonComponentSerializer gsonLegacy() {
+ return GsonComponentSerializer.builder()
+ .legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE)
+ .downsampleColors()
+ .build();
+ }
+
+ @Override
+ public @NotNull Consumer<GsonComponentSerializer.Builder> builder() {
+ return builder -> builder.legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.INSTANCE);
+ }
+}
diff --git a/src/main/java/io/papermc/paper/adventure/providers/LegacyComponentSerializerProviderImpl.java b/src/main/java/io/papermc/paper/adventure/providers/LegacyComponentSerializerProviderImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..03723dbe32b7eb95253e8ff6e72dbf8d2300a059
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/LegacyComponentSerializerProviderImpl.java
@@ -0,0 +1,36 @@
+package io.papermc.paper.adventure.providers;
+
+import io.papermc.paper.adventure.PaperAdventure;
+import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.function.Consumer;
+
+@SuppressWarnings("UnstableApiUsage") // permitted provider
+public class LegacyComponentSerializerProviderImpl implements LegacyComponentSerializer.Provider {
+
+ @Override
+ public @NotNull LegacyComponentSerializer legacyAmpersand() {
+ return LegacyComponentSerializer.builder()
+ .flattener(PaperAdventure.FLATTENER)
+ .character(LegacyComponentSerializer.AMPERSAND_CHAR)
+ .hexColors()
+ .useUnusualXRepeatedCharacterHexFormat()
+ .build();
+ }
+
+ @Override
+ public @NotNull LegacyComponentSerializer legacySection() {
+ return LegacyComponentSerializer.builder()
+ .flattener(PaperAdventure.FLATTENER)
+ .character(LegacyComponentSerializer.SECTION_CHAR)
+ .hexColors()
+ .useUnusualXRepeatedCharacterHexFormat()
+ .build();
+ }
+
+ @Override
+ public @NotNull Consumer<LegacyComponentSerializer.Builder> legacy() {
+ return builder -> builder.flattener(PaperAdventure.FLATTENER);
+ }
+}
diff --git a/src/main/java/io/papermc/paper/adventure/providers/MiniMessageProviderImpl.java b/src/main/java/io/papermc/paper/adventure/providers/MiniMessageProviderImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..25fd6992c869c841b1b1b3240f4d524948487614
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/MiniMessageProviderImpl.java
@@ -0,0 +1,20 @@
+package io.papermc.paper.adventure.providers;
+
+import net.kyori.adventure.text.minimessage.MiniMessage;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.function.Consumer;
+
+@SuppressWarnings("UnstableApiUsage") // permitted provider
+public class MiniMessageProviderImpl implements MiniMessage.Provider {
+
+ @Override
+ public @NotNull MiniMessage miniMessage() {
+ return MiniMessage.builder().build();
+ }
+
+ @Override
+ public @NotNull Consumer<MiniMessage.Builder> builder() {
+ return builder -> {};
+ }
+}
diff --git a/src/main/java/io/papermc/paper/adventure/providers/NBTLegacyHoverEventSerializer.java b/src/main/java/io/papermc/paper/adventure/providers/NBTLegacyHoverEventSerializer.java
new file mode 100644
2023-12-25 11:51:44 +01:00
index 0000000000000000000000000000000000000000..202b964e7e67717904cd3f00b6af6ad7f2a5c90e
2022-05-26 21:12:14 +02:00
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/NBTLegacyHoverEventSerializer.java
2023-12-25 11:51:44 +01:00
@@ -0,0 +1,91 @@
2022-05-26 21:12:14 +02:00
+package io.papermc.paper.adventure.providers;
+
+import com.mojang.brigadier.exceptions.CommandSyntaxException;
2023-12-25 11:51:44 +01:00
+import java.io.IOException;
+import java.util.UUID;
2022-05-26 21:12:14 +02:00
+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;
2023-12-25 11:51:44 +01:00
+import net.kyori.adventure.text.serializer.json.LegacyHoverEventSerializer;
2022-05-26 21:12:14 +02:00
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
+import net.kyori.adventure.util.Codec;
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.nbt.Tag;
+import net.minecraft.nbt.TagParser;
2023-12-25 11:51:44 +01:00
+import org.intellij.lang.annotations.Subst;
2022-05-26 21:12:14 +02:00
+
+final class NBTLegacyHoverEventSerializer implements LegacyHoverEventSerializer {
+ public static final NBTLegacyHoverEventSerializer INSTANCE = new NBTLegacyHoverEventSerializer();
+ private static final Codec<CompoundTag, String, CommandSyntaxException, RuntimeException> SNBT_CODEC = Codec.codec(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 = PlainTextComponentSerializer.plainText().serialize(input);
+ try {
+ final CompoundTag contents = SNBT_CODEC.decode(raw);
+ final CompoundTag tag = contents.getCompound(ITEM_TAG);
2023-12-25 11:51:44 +01:00
+ @Subst("key") final String keyString = contents.getString(ITEM_TYPE);
+ return HoverEvent.ShowItem.showItem(
+ Key.key(keyString),
2022-05-26 21:12:14 +02:00
+ 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<Component, String, ? extends RuntimeException> componentCodec) throws IOException {
+ final String raw = PlainTextComponentSerializer.plainText().serialize(input);
+ try {
+ final CompoundTag contents = SNBT_CODEC.decode(raw);
2023-12-25 11:51:44 +01:00
+ @Subst("key") final String keyString = contents.getString(ENTITY_TYPE);
+ return HoverEvent.ShowEntity.showEntity(
+ Key.key(keyString),
2022-05-26 21:12:14 +02:00
+ 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
2023-12-25 11:51:44 +01:00
+ public Component serializeShowEntity(final HoverEvent.ShowEntity input, final Codec.Encoder<Component, String, ? extends RuntimeException> componentCodec) {
2022-05-26 21:12:14 +02:00
+ 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/providers/PlainTextComponentSerializerProviderImpl.java b/src/main/java/io/papermc/paper/adventure/providers/PlainTextComponentSerializerProviderImpl.java
new file mode 100644
index 0000000000000000000000000000000000000000..c0701d4f93a4d77a8177d2dd8d5076f9f781873d
--- /dev/null
+++ b/src/main/java/io/papermc/paper/adventure/providers/PlainTextComponentSerializerProviderImpl.java
@@ -0,0 +1,23 @@
+package io.papermc.paper.adventure.providers;
+
+import io.papermc.paper.adventure.PaperAdventure;
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.function.Consumer;
+
+@SuppressWarnings("UnstableApiUsage") // permitted provider
+public class PlainTextComponentSerializerProviderImpl implements PlainTextComponentSerializer.Provider {
+
+ @Override
+ public @NotNull PlainTextComponentSerializer plainTextSimple() {
+ return PlainTextComponentSerializer.builder()
+ .flattener(PaperAdventure.FLATTENER)
+ .build();
+ }
+
+ @Override
+ public @NotNull Consumer<PlainTextComponentSerializer.Builder> plainText() {
+ return builder -> builder.flattener(PaperAdventure.FLATTENER);
2021-06-11 14:02:28 +02:00
+ }
+}
diff --git a/src/main/java/net/minecraft/ChatFormatting.java b/src/main/java/net/minecraft/ChatFormatting.java
2024-06-13 19:12:48 +02:00
index 08dcd817bfe1ba0121d4ce701825e4aee384db85..d5f63d06d921d731b4e64b38228377712fe9c75b 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/ChatFormatting.java
+++ b/src/main/java/net/minecraft/ChatFormatting.java
2024-06-13 19:12:48 +02:00
@@ -112,6 +112,18 @@ public enum ChatFormatting implements StringRepresentable {
2021-06-11 21:23:46 +02:00
return name == null ? null : FORMATTING_BY_NAME.get(cleanName(name));
2021-06-11 14:02:28 +02:00
}
2024-01-13 21:31:02 +01:00
+ // Paper start - add method to get by hex value
2021-06-11 14:02:28 +02:00
+ @Nullable public static ChatFormatting getByHexValue(int i) {
+ for (ChatFormatting value : values()) {
2021-06-16 19:48:25 +02:00
+ if (value.getColor() != null && value.getColor() == i) {
2021-06-11 14:02:28 +02:00
+ return value;
+ }
+ }
+
+ return null;
+ }
2024-01-13 21:31:02 +01:00
+ // Paper end - add method to get by hex value
2021-06-11 14:02:28 +02:00
+
@Nullable
public static ChatFormatting getById(int colorIndex) {
if (colorIndex < 0) {
2022-11-23 05:53:50 +01:00
diff --git a/src/main/java/net/minecraft/commands/CommandSourceStack.java b/src/main/java/net/minecraft/commands/CommandSourceStack.java
2024-04-23 20:32:19 +02:00
index f30cdfa5fd294479e35680b2f758b3295f659b74..ec34e402104d7a696ea95e0b11ee70189b678ab9 100644
2022-11-23 05:53:50 +01:00
--- a/src/main/java/net/minecraft/commands/CommandSourceStack.java
+++ b/src/main/java/net/minecraft/commands/CommandSourceStack.java
2023-12-05 19:38:29 +01:00
@@ -65,6 +65,7 @@ public class CommandSourceStack implements ExecutionCommandSource<CommandSourceS
private final CommandSigningContext signingContext;
2022-11-23 05:53:50 +01:00
private final TaskChainer chatMessageChainer;
public volatile CommandNode currentCommand; // CraftBukkit
2024-01-13 21:31:02 +01:00
+ public boolean bypassSelectorPermissions = false; // Paper - add bypass for selector permissions
2022-11-23 05:53:50 +01:00
public CommandSourceStack(CommandSource output, Vec3 pos, Vec2 rot, ServerLevel world, int level, String name, Component displayName, MinecraftServer server, @Nullable Entity entity) {
2023-12-05 19:38:29 +01:00
this(output, pos, rot, world, level, name, displayName, server, entity, false, CommandResultCallback.EMPTY, EntityAnchorArgument.Anchor.FEET, CommandSigningContext.ANONYMOUS, TaskChainer.immediate(server));
2022-12-08 18:06:14 +01:00
diff --git a/src/main/java/net/minecraft/commands/arguments/MessageArgument.java b/src/main/java/net/minecraft/commands/arguments/MessageArgument.java
2024-08-10 12:24:38 +02:00
index 8f03eed020a99b96189f4f5d42d806d06f4d6b5e..55484826fc5ddd04ae024e25a0251796d7fa9c28 100644
2022-12-08 18:06:14 +01:00
--- a/src/main/java/net/minecraft/commands/arguments/MessageArgument.java
+++ b/src/main/java/net/minecraft/commands/arguments/MessageArgument.java
2024-08-10 12:24:38 +02:00
@@ -54,17 +54,21 @@ public class MessageArgument implements SignedArgument<MessageArgument.Message>
2022-12-08 18:06:14 +01:00
private static void resolveSignedMessage(Consumer<PlayerChatMessage> callback, CommandSourceStack source, PlayerChatMessage message) {
MinecraftServer minecraftServer = source.getServer();
CompletableFuture<FilteredText> completableFuture = filterPlainText(source, message);
2023-09-21 21:00:11 +02:00
- Component component = minecraftServer.getChatDecorator().decorate(source.getPlayer(), message.decoratedContent());
2024-04-12 21:14:06 +02:00
- source.getChatMessageChainer().append(completableFuture, filtered -> {
2023-12-05 19:38:29 +01:00
- PlayerChatMessage playerChatMessage2 = message.withUnsignedContent(component).filter(filtered.mask());
2024-01-13 21:31:02 +01:00
+ // Paper start - support asynchronous chat decoration
2024-04-19 21:47:24 +02:00
+ CompletableFuture<Component> componentFuture = minecraftServer.getChatDecorator().decorate(source.getPlayer(), source, message.decoratedContent());
2024-04-12 21:14:06 +02:00
+ source.getChatMessageChainer().append(CompletableFuture.allOf(completableFuture, componentFuture), filtered -> {
2024-04-19 21:47:24 +02:00
+ PlayerChatMessage playerChatMessage2 = message.withUnsignedContent(componentFuture.join()).filter(completableFuture.join().mask());
2024-01-13 21:31:02 +01:00
+ // Paper end - support asynchronous chat decoration
2023-12-05 19:38:29 +01:00
callback.accept(playerChatMessage2);
2022-12-08 18:06:14 +01:00
});
2023-12-05 19:38:29 +01:00
}
2022-12-08 18:06:14 +01:00
private static void resolveDisguisedMessage(Consumer<PlayerChatMessage> callback, CommandSourceStack source, PlayerChatMessage message) {
2023-09-21 21:00:11 +02:00
ChatDecorator chatDecorator = source.getServer().getChatDecorator();
- Component component = chatDecorator.decorate(source.getPlayer(), message.decoratedContent());
- callback.accept(message.withUnsignedContent(component));
2024-01-13 21:31:02 +01:00
+ // Paper start - support asynchronous chat decoration
2024-04-19 21:47:24 +02:00
+ CompletableFuture<Component> componentFuture = chatDecorator.decorate(source.getPlayer(), source, message.decoratedContent());
+ source.getChatMessageChainer().append(componentFuture, (result) -> callback.accept(message.withUnsignedContent(result)));
2024-01-13 21:31:02 +01:00
+ // Paper end - support asynchronous chat decoration
2022-12-08 18:06:14 +01:00
}
2023-09-21 21:00:11 +02:00
private static CompletableFuture<FilteredText> filterPlainText(CommandSourceStack source, PlayerChatMessage message) {
2022-11-23 05:53:50 +01:00
diff --git a/src/main/java/net/minecraft/commands/arguments/selector/EntitySelector.java b/src/main/java/net/minecraft/commands/arguments/selector/EntitySelector.java
2024-06-13 19:12:48 +02:00
index dd66979bcae33096d72001678e8e55569bea6f53..c8d39e6e1c570c9219f6066da273dc0130920519 100644
2022-11-23 05:53:50 +01:00
--- a/src/main/java/net/minecraft/commands/arguments/selector/EntitySelector.java
+++ b/src/main/java/net/minecraft/commands/arguments/selector/EntitySelector.java
2024-06-13 19:12:48 +02:00
@@ -93,7 +93,7 @@ public class EntitySelector {
2022-11-23 05:53:50 +01:00
}
private void checkPermissions(CommandSourceStack source) throws CommandSyntaxException {
- if (this.usesSelector && !source.hasPermission(2, "minecraft.command.selector")) { // CraftBukkit
2024-06-01 16:26:11 +02:00
+ if (!source.bypassSelectorPermissions && (this.usesSelector && !source.hasPermission(2, "minecraft.command.selector"))) { // CraftBukkit // Paper - add bypass for selector perms
2022-11-23 05:53:50 +01:00
throw EntityArgument.ERROR_SELECTORS_NOT_ALLOWED.create();
}
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/net/minecraft/network/FriendlyByteBuf.java b/src/main/java/net/minecraft/network/FriendlyByteBuf.java
2024-06-13 19:12:48 +02:00
index 6d7545a925156aef6badcfa2bc40dbdad18c4ac0..0cd6a50837efce87ca052a0e1e24db2b75761196 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/network/FriendlyByteBuf.java
+++ b/src/main/java/net/minecraft/network/FriendlyByteBuf.java
2024-04-23 20:32:19 +02:00
@@ -72,6 +72,7 @@ public class FriendlyByteBuf extends ByteBuf {
2023-09-21 21:00:11 +02:00
2022-12-07 18:53:34 +01:00
public static final int DEFAULT_NBT_QUOTA = 2097152;
2021-06-11 14:02:28 +02:00
private final ByteBuf source;
2024-04-27 00:08:35 +02:00
+ @Nullable public final java.util.Locale adventure$locale; // Paper - track player's locale for server-side translations
2024-04-23 20:32:19 +02:00
public static final short MAX_STRING_LENGTH = Short.MAX_VALUE;
2021-06-11 21:23:46 +02:00
public static final int MAX_COMPONENT_STRING_LENGTH = 262144;
2022-06-07 20:12:34 +02:00
private static final int PUBLIC_KEY_SIZE = 256;
2024-04-27 00:08:35 +02:00
@@ -80,6 +81,7 @@ public class FriendlyByteBuf extends ByteBuf {
private static final Gson GSON = new Gson();
public FriendlyByteBuf(ByteBuf parent) {
+ this.adventure$locale = PacketEncoder.ADVENTURE_LOCALE.get(); // Paper - track player's locale for server-side translations
this.source = parent;
}
@@ -120,11 +122,16 @@ public class FriendlyByteBuf extends ByteBuf {
2023-12-29 20:51:52 +01:00
}
public <T> void writeJsonWithCodec(Codec<T> codec, T value) {
2024-01-13 21:31:02 +01:00
+ // Paper start - Adventure; add max length parameter
2023-12-29 20:51:52 +01:00
+ this.writeJsonWithCodec(codec, value, MAX_STRING_LENGTH);
+ }
+ public <T> void writeJsonWithCodec(Codec<T> codec, T value, int maxLength) {
2024-01-13 21:31:02 +01:00
+ // Paper end - Adventure; add max length parameter
2023-12-29 20:51:52 +01:00
DataResult<JsonElement> dataresult = codec.encodeStart(JsonOps.INSTANCE, value);
2024-04-23 20:32:19 +02:00
this.writeUtf(FriendlyByteBuf.GSON.toJson((JsonElement) dataresult.getOrThrow((s) -> {
return new EncoderException("Failed to encode: " + s + " " + String.valueOf(value));
2023-12-29 20:51:52 +01:00
- })));
2024-01-13 21:31:02 +01:00
+ })), maxLength); // Paper - Adventure; add max length parameter
2023-12-29 20:51:52 +01:00
}
2024-04-23 20:32:19 +02:00
public static <T> IntFunction<T> limitValue(IntFunction<T> applier, int max) {
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/net/minecraft/network/PacketEncoder.java b/src/main/java/net/minecraft/network/PacketEncoder.java
2024-04-27 00:08:35 +02:00
index a58f67973b4ed986065860263c7a42214640520d..046bfc212b640de174b300e7a05cc30bb3cac93e 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/network/PacketEncoder.java
+++ b/src/main/java/net/minecraft/network/PacketEncoder.java
2024-04-27 00:08:35 +02:00
@@ -17,10 +17,12 @@ public class PacketEncoder<T extends PacketListener> extends MessageToByteEncode
this.protocolInfo = state;
}
+ static final ThreadLocal<java.util.Locale> ADVENTURE_LOCALE = ThreadLocal.withInitial(() -> null); // Paper - adventure; set player's locale
2024-04-23 20:32:19 +02:00
protected void encode(ChannelHandlerContext channelHandlerContext, Packet<T> packet, ByteBuf byteBuf) throws Exception {
PacketType<? extends Packet<? super T>> packetType = packet.type();
try {
2024-04-27 00:08:35 +02:00
+ ADVENTURE_LOCALE.set(channelHandlerContext.channel().attr(io.papermc.paper.adventure.PaperAdventure.LOCALE_ATTRIBUTE).get()); // Paper - adventure; set player's locale
2024-04-23 20:32:19 +02:00
this.protocolInfo.codec().encode(byteBuf, packet);
int i = byteBuf.readableBytes();
2024-04-27 00:08:35 +02:00
if (LOGGER.isDebugEnabled()) {
2022-08-01 21:34:55 +02:00
diff --git a/src/main/java/net/minecraft/network/chat/ChatDecorator.java b/src/main/java/net/minecraft/network/chat/ChatDecorator.java
2024-04-19 21:47:24 +02:00
index e4624d696dcf0ddb6d42a80701dfc47ec6877540..6b8dc1eb490098cc14673c9ab0aa16fe3471325b 100644
2022-08-01 21:34:55 +02:00
--- a/src/main/java/net/minecraft/network/chat/ChatDecorator.java
+++ b/src/main/java/net/minecraft/network/chat/ChatDecorator.java
2024-04-19 21:47:24 +02:00
@@ -2,10 +2,18 @@ package net.minecraft.network.chat;
2023-09-21 21:00:11 +02:00
import javax.annotation.Nullable;
import net.minecraft.server.level.ServerPlayer;
+import java.util.concurrent.CompletableFuture; // Paper
@FunctionalInterface
public interface ChatDecorator {
2024-04-12 21:14:06 +02:00
- ChatDecorator PLAIN = (sender, message) -> message;
2024-04-19 21:47:24 +02:00
+ ChatDecorator PLAIN = (sender, message) -> CompletableFuture.completedFuture(message); // Paper - adventure; support async chat decoration events
2022-08-01 21:34:55 +02:00
2023-09-21 21:00:11 +02:00
- Component decorate(@Nullable ServerPlayer sender, Component message);
2024-04-19 21:47:24 +02:00
+ @io.papermc.paper.annotation.DoNotUse @Deprecated // Paper - adventure; support chat decoration events (callers should use the overload with CommandSourceStack)
2024-01-13 21:31:02 +01:00
+ CompletableFuture<Component> decorate(@Nullable ServerPlayer sender, Component message); // Paper - adventure; support async chat decoration events
2022-12-07 18:53:34 +01:00
+
2024-01-13 21:31:02 +01:00
+ // Paper start - adventure; support async chat decoration events
2024-04-19 21:47:24 +02:00
+ default CompletableFuture<Component> decorate(@Nullable ServerPlayer sender, @Nullable net.minecraft.commands.CommandSourceStack commandSourceStack, Component message) {
2022-08-01 21:34:55 +02:00
+ throw new UnsupportedOperationException("Must override this implementation");
+ }
2024-01-13 21:31:02 +01:00
+ // Paper end - adventure; support async chat decoration events
2022-12-07 18:53:34 +01:00
}
2023-12-12 07:02:06 +01:00
diff --git a/src/main/java/net/minecraft/network/chat/ComponentSerialization.java b/src/main/java/net/minecraft/network/chat/ComponentSerialization.java
2024-04-25 05:14:51 +02:00
index ec99dc00d83e2369e66ba5e93bf482555aab7b06..22c6a324dedeb315eac2d3d3f55d2f3a9eebb0ad 100644
2023-12-12 07:02:06 +01:00
--- a/src/main/java/net/minecraft/network/chat/ComponentSerialization.java
+++ b/src/main/java/net/minecraft/network/chat/ComponentSerialization.java
2024-04-25 05:14:51 +02:00
@@ -37,9 +37,31 @@ import net.minecraft.util.StringRepresentable;
public class ComponentSerialization {
2024-04-23 20:32:19 +02:00
public static final Codec<Component> CODEC = Codec.recursive("Component", ComponentSerialization::createCodec);
2024-04-25 05:14:51 +02:00
- public static final StreamCodec<RegistryFriendlyByteBuf, Component> STREAM_CODEC = ByteBufCodecs.fromCodecWithRegistries(CODEC);
+ public static final StreamCodec<RegistryFriendlyByteBuf, Component> STREAM_CODEC = createTranslationAware(() -> net.minecraft.nbt.NbtAccounter.create(net.minecraft.network.FriendlyByteBuf.DEFAULT_NBT_QUOTA)); // Paper - adventure
2024-04-23 20:32:19 +02:00
public static final StreamCodec<RegistryFriendlyByteBuf, Optional<Component>> OPTIONAL_STREAM_CODEC = STREAM_CODEC.apply(ByteBufCodecs::optional);
- public static final StreamCodec<RegistryFriendlyByteBuf, Component> TRUSTED_STREAM_CODEC = ByteBufCodecs.fromCodecWithRegistriesTrusted(CODEC);
+ // Paper start - adventure; use locale from bytebuf for translation
2024-04-25 05:14:51 +02:00
+ public static final ThreadLocal<Boolean> DONT_RENDER_TRANSLATABLES = ThreadLocal.withInitial(() -> false);
+ public static final StreamCodec<RegistryFriendlyByteBuf, Component> TRUSTED_STREAM_CODEC = createTranslationAware(net.minecraft.nbt.NbtAccounter::unlimitedHeap);
+ private static StreamCodec<RegistryFriendlyByteBuf, Component> createTranslationAware(final Supplier<net.minecraft.nbt.NbtAccounter> sizeTracker) {
+ return new StreamCodec<>() {
+ final StreamCodec<ByteBuf, net.minecraft.nbt.Tag> streamCodec = ByteBufCodecs.tagCodec(sizeTracker);
+ @Override
+ public Component decode(RegistryFriendlyByteBuf registryFriendlyByteBuf) {
+ net.minecraft.nbt.Tag tag = this.streamCodec.decode(registryFriendlyByteBuf);
+ RegistryOps<net.minecraft.nbt.Tag> registryOps = registryFriendlyByteBuf.registryAccess().createSerializationContext(net.minecraft.nbt.NbtOps.INSTANCE);
+ return CODEC.parse(registryOps, tag).getOrThrow(error -> new io.netty.handler.codec.DecoderException("Failed to decode: " + error + " " + tag));
+ }
2024-04-23 20:32:19 +02:00
+
2024-04-25 05:14:51 +02:00
+ @Override
+ public void encode(RegistryFriendlyByteBuf registryFriendlyByteBuf, Component object) {
+ RegistryOps<net.minecraft.nbt.Tag> registryOps = registryFriendlyByteBuf.registryAccess().createSerializationContext(net.minecraft.nbt.NbtOps.INSTANCE);
+ net.minecraft.nbt.Tag tag = (DONT_RENDER_TRANSLATABLES.get() ? CODEC : ComponentSerialization.localizedCodec(registryFriendlyByteBuf.adventure$locale))
+ .encodeStart(registryOps, object).getOrThrow(error -> new io.netty.handler.codec.EncoderException("Failed to encode: " + error + " " + object));
+ this.streamCodec.encode(registryFriendlyByteBuf, tag);
+ }
+ };
+ }
2024-04-23 20:32:19 +02:00
+ // Paper end - adventure; use locale from bytebuf for translation
public static final StreamCodec<RegistryFriendlyByteBuf, Optional<Component>> TRUSTED_OPTIONAL_STREAM_CODEC = TRUSTED_STREAM_CODEC.apply(
ByteBufCodecs::optional
);
2024-04-25 05:14:51 +02:00
@@ -100,7 +122,27 @@ public class ComponentSerialization {
2023-12-12 22:40:33 +01:00
return ExtraCodecs.orCompressed(mapCodec3, mapCodec2);
}
2024-01-13 21:31:02 +01:00
+ // Paper start - adventure; create separate codec for each locale
2023-12-12 22:40:33 +01:00
+ private static final java.util.Map<java.util.Locale, Codec<Component>> LOCALIZED_CODECS = new java.util.concurrent.ConcurrentHashMap<>();
+
+ public static Codec<Component> localizedCodec(final java.util.@org.checkerframework.checker.nullness.qual.Nullable Locale locale) {
+ if (locale == null) {
+ return CODEC;
+ }
+ return LOCALIZED_CODECS.computeIfAbsent(locale,
2024-04-23 20:32:19 +02:00
+ loc -> Codec.recursive("Component", selfCodec -> createCodec(selfCodec, loc)));
2023-12-12 22:40:33 +01:00
+ }
2024-04-23 20:32:19 +02:00
+
+
2024-01-13 21:31:02 +01:00
+ // Paper end - adventure; create separate codec for each locale
2023-12-12 22:40:33 +01:00
+
private static Codec<Component> createCodec(Codec<Component> selfCodec) {
2024-01-13 21:31:02 +01:00
+ // Paper start - adventure; create separate codec for each locale
2023-12-12 22:40:33 +01:00
+ return createCodec(selfCodec, null);
+ }
+
+ private static Codec<Component> createCodec(Codec<Component> selfCodec, @javax.annotation.Nullable java.util.Locale locale) {
2024-01-13 21:31:02 +01:00
+ // Paper end - adventure; create separate codec for each locale
2024-04-12 21:14:06 +02:00
ComponentContents.Type<?>[] types = new ComponentContents.Type[]{
PlainTextContents.TYPE, TranslatableContents.TYPE, KeybindContents.TYPE, ScoreContents.TYPE, SelectorContents.TYPE, NbtContents.TYPE
};
2024-04-25 05:14:51 +02:00
@@ -113,6 +155,34 @@ public class ComponentSerialization {
2024-04-12 21:14:06 +02:00
)
.apply(instance, MutableComponent::new)
);
2024-01-13 21:31:02 +01:00
+ // Paper start - adventure; create separate codec for each locale
2023-12-12 07:02:06 +01:00
+ final Codec<Component> origCodec = codec;
+ codec = new Codec<>() {
+ @Override
+ public <T> DataResult<com.mojang.datafixers.util.Pair<Component, T>> decode(final DynamicOps<T> ops, final T input) {
+ return origCodec.decode(ops, input);
+ }
+
+ @Override
+ public <T> DataResult<T> encode(final Component input, final DynamicOps<T> ops, final T prefix) {
2023-12-12 22:40:33 +01:00
+ final net.kyori.adventure.text.Component adventureComponent;
2023-12-12 07:02:06 +01:00
+ if (input instanceof io.papermc.paper.adventure.AdventureComponent adv) {
2023-12-12 22:40:33 +01:00
+ adventureComponent = adv.adventure$component();
2023-12-25 11:51:44 +01:00
+ } else if (locale != null && input.getContents() instanceof TranslatableContents && io.papermc.paper.adventure.PaperAdventure.hasAnyTranslations()) {
2023-12-12 22:40:33 +01:00
+ adventureComponent = io.papermc.paper.adventure.PaperAdventure.asAdventure(input);
+ } else {
+ return origCodec.encode(input, ops, prefix);
2023-12-12 07:02:06 +01:00
+ }
2023-12-12 22:40:33 +01:00
+ return io.papermc.paper.adventure.PaperAdventure.localizedCodec(locale)
+ .encode(adventureComponent, ops, prefix);
2023-12-12 07:02:06 +01:00
+ }
+
+ @Override
+ public String toString() {
+ return origCodec.toString() + "[AdventureComponentAware]";
+ }
+ };
2024-01-13 21:31:02 +01:00
+ // Paper end - adventure; create separate codec for each locale
2024-04-12 21:14:06 +02:00
return Codec.either(Codec.either(Codec.STRING, ExtraCodecs.nonEmptyList(selfCodec.listOf())), codec)
.xmap(either -> either.map(either2 -> either2.map(Component::literal, ComponentSerialization::createFromList), text -> (Component)text), text -> {
String string = text.tryCollapseToString();
2022-11-23 05:53:50 +01:00
diff --git a/src/main/java/net/minecraft/network/chat/ComponentUtils.java b/src/main/java/net/minecraft/network/chat/ComponentUtils.java
2024-04-12 21:14:06 +02:00
index 0030c0c91e989fcdc5b7ce6490836a0e8dd3b5d5..3365aed2b67ae0e4dd0410f5190ba474f146139b 100644
2022-11-23 05:53:50 +01:00
--- a/src/main/java/net/minecraft/network/chat/ComponentUtils.java
+++ b/src/main/java/net/minecraft/network/chat/ComponentUtils.java
2023-09-21 21:00:11 +02:00
@@ -41,6 +41,11 @@ public class ComponentUtils {
2022-11-23 05:53:50 +01:00
if (depth > 100) {
return text.copy();
} else {
2024-01-13 21:31:02 +01:00
+ // Paper start - adventure; pass actual vanilla component
2022-11-23 05:53:50 +01:00
+ if (text instanceof io.papermc.paper.adventure.AdventureComponent adventureComponent) {
+ text = adventureComponent.deepConverted();
+ }
2024-01-13 21:31:02 +01:00
+ // Paper end - adventure; pass actual vanilla component
2022-11-23 05:53:50 +01:00
MutableComponent mutableComponent = text.getContents().resolve(source, sender, depth + 1);
2024-04-12 21:14:06 +02:00
for (Component component : text.getSiblings()) {
2022-12-17 07:05:48 +01:00
diff --git a/src/main/java/net/minecraft/network/chat/MessageSignature.java b/src/main/java/net/minecraft/network/chat/MessageSignature.java
2024-04-12 21:14:06 +02:00
index 739ef5fb6f4fa37382153ba6a308ca3b451e6b05..7c3154af5d7732037c0ee965f6f8b89424461abd 100644
2022-12-17 07:05:48 +01:00
--- a/src/main/java/net/minecraft/network/chat/MessageSignature.java
+++ b/src/main/java/net/minecraft/network/chat/MessageSignature.java
2024-04-12 21:14:06 +02:00
@@ -13,6 +13,7 @@ import net.minecraft.util.SignatureUpdater;
2022-12-17 07:05:48 +01:00
import net.minecraft.util.SignatureValidator;
2022-12-17 08:46:46 +01:00
public record MessageSignature(byte[] bytes) {
2024-01-13 21:31:02 +01:00
+ public net.kyori.adventure.chat.SignedMessage.Signature adventure() { return () -> this.bytes; } // Paper - adventure; support signed messages
2022-12-17 07:05:48 +01:00
public static final Codec<MessageSignature> CODEC = ExtraCodecs.BASE64_STRING.xmap(MessageSignature::new, MessageSignature::bytes);
public static final int BYTES = 256;
2024-04-27 00:25:20 +02:00
diff --git a/src/main/java/net/minecraft/network/chat/MutableComponent.java b/src/main/java/net/minecraft/network/chat/MutableComponent.java
2024-06-13 19:12:48 +02:00
index 0a70fb7df0d4532edbc2468b13520c34ae1500e9..e34a8a66411b7571813117ce47d9dec08e567978 100644
2024-04-27 00:25:20 +02:00
--- a/src/main/java/net/minecraft/network/chat/MutableComponent.java
+++ b/src/main/java/net/minecraft/network/chat/MutableComponent.java
@@ -94,6 +94,11 @@ public class MutableComponent implements Component {
@Override
public boolean equals(Object object) {
+ // Paper start - make AdventureComponent equivalent
+ if (object instanceof io.papermc.paper.adventure.AdventureComponent adventureComponent) {
+ object = adventureComponent.deepConverted();
+ }
+ // Paper end - make AdventureComponent equivalent
return this == object
|| object instanceof MutableComponent mutableComponent
&& this.contents.equals(mutableComponent.contents)
2022-12-07 18:53:34 +01:00
diff --git a/src/main/java/net/minecraft/network/chat/OutgoingChatMessage.java b/src/main/java/net/minecraft/network/chat/OutgoingChatMessage.java
2024-04-12 21:14:06 +02:00
index e2def0ca552343143e495736d533b3334686fd62..c87b708c368713a23a10ad97704575ee4df27891 100644
2022-12-07 18:53:34 +01:00
--- a/src/main/java/net/minecraft/network/chat/OutgoingChatMessage.java
+++ b/src/main/java/net/minecraft/network/chat/OutgoingChatMessage.java
@@ -7,6 +7,12 @@ public interface OutgoingChatMessage {
2022-08-06 00:58:34 +02:00
void sendToPlayer(ServerPlayer sender, boolean filterMaskEnabled, ChatType.Bound params);
2022-08-01 21:34:55 +02:00
+ // Paper start
2022-08-06 00:58:34 +02:00
+ default void sendToPlayer(ServerPlayer sender, boolean filterMaskEnabled, ChatType.Bound params, @javax.annotation.Nullable Component unsigned) {
+ this.sendToPlayer(sender, filterMaskEnabled, params);
2022-08-01 21:34:55 +02:00
+ }
+ // Paper end
2022-08-06 00:58:34 +02:00
+
2022-12-07 18:53:34 +01:00
static OutgoingChatMessage create(PlayerChatMessage message) {
2024-04-12 21:14:06 +02:00
return (OutgoingChatMessage)(message.isSystem()
? new OutgoingChatMessage.Disguised(message.decoratedContent())
@@ -16,7 +22,12 @@ public interface OutgoingChatMessage {
public static record Disguised(@Override Component content) implements OutgoingChatMessage {
2022-08-01 21:34:55 +02:00
@Override
2022-08-06 00:58:34 +02:00
public void sendToPlayer(ServerPlayer sender, boolean filterMaskEnabled, ChatType.Bound params) {
2022-12-07 18:53:34 +01:00
- sender.connection.sendDisguisedChatMessage(this.content, params);
+ // Paper start
2022-08-06 00:58:34 +02:00
+ this.sendToPlayer(sender, filterMaskEnabled, params, null);
2022-08-01 21:34:55 +02:00
+ }
2022-08-06 00:58:34 +02:00
+ public void sendToPlayer(ServerPlayer sender, boolean filterMaskEnabled, ChatType.Bound params, @javax.annotation.Nullable Component unsigned) {
2022-12-07 18:53:34 +01:00
+ sender.connection.sendDisguisedChatMessage(unsigned != null ? unsigned : this.content, params);
2022-08-01 21:34:55 +02:00
+ // Paper end
2022-12-07 18:53:34 +01:00
}
}
2024-04-12 21:14:06 +02:00
@@ -28,7 +39,13 @@ public interface OutgoingChatMessage {
2022-08-01 21:34:55 +02:00
@Override
2022-08-06 00:58:34 +02:00
public void sendToPlayer(ServerPlayer sender, boolean filterMaskEnabled, ChatType.Bound params) {
2022-08-01 21:34:55 +02:00
+ // Paper start
2022-08-06 00:58:34 +02:00
+ this.sendToPlayer(sender, filterMaskEnabled, params, null);
2022-08-01 21:34:55 +02:00
+ }
2022-08-06 00:58:34 +02:00
+ public void sendToPlayer(ServerPlayer sender, boolean filterMaskEnabled, ChatType.Bound params, @javax.annotation.Nullable Component unsigned) {
2022-08-01 21:34:55 +02:00
+ // Paper end
2022-08-06 00:58:34 +02:00
PlayerChatMessage playerChatMessage = this.message.filter(filterMaskEnabled);
2022-08-01 21:34:55 +02:00
+ playerChatMessage = unsigned != null ? playerChatMessage.withUnsignedContent(unsigned) : playerChatMessage; // Paper
if (!playerChatMessage.isFullyFiltered()) {
2022-12-07 18:53:34 +01:00
sender.connection.sendPlayerChatMessage(playerChatMessage, params);
}
2022-12-08 17:32:29 +01:00
diff --git a/src/main/java/net/minecraft/network/chat/PlayerChatMessage.java b/src/main/java/net/minecraft/network/chat/PlayerChatMessage.java
2024-04-19 21:47:24 +02:00
index d89049328641faa889b7c567123ab3a2c63b8df0..76b304560c2b631a18f20e656a65ac75af7b4e63 100644
2022-12-08 17:32:29 +01:00
--- a/src/main/java/net/minecraft/network/chat/PlayerChatMessage.java
+++ b/src/main/java/net/minecraft/network/chat/PlayerChatMessage.java
2024-04-19 21:47:24 +02:00
@@ -17,6 +17,42 @@ import net.minecraft.util.SignatureValidator;
2024-04-12 21:14:06 +02:00
public record PlayerChatMessage(
2024-04-19 21:47:24 +02:00
SignedMessageLink link, @Nullable MessageSignature signature, SignedMessageBody signedBody, @Nullable Component unsignedContent, FilterMask filterMask
2024-04-12 21:14:06 +02:00
) {
+ // Paper start - adventure; support signed messages
2022-12-17 07:05:48 +01:00
+ public final class AdventureView implements net.kyori.adventure.chat.SignedMessage {
+ private AdventureView() {
+ }
+ @Override
+ public @org.jetbrains.annotations.NotNull Instant timestamp() {
+ return PlayerChatMessage.this.timeStamp();
+ }
+ @Override
+ public long salt() {
+ return PlayerChatMessage.this.salt();
+ }
+ @Override
+ public @org.jetbrains.annotations.Nullable Signature signature() {
2022-12-17 08:46:46 +01:00
+ return PlayerChatMessage.this.signature == null ? null : PlayerChatMessage.this.signature.adventure();
2022-12-17 07:05:48 +01:00
+ }
+ @Override
+ public net.kyori.adventure.text.@org.jetbrains.annotations.Nullable Component unsignedContent() {
+ return PlayerChatMessage.this.unsignedContent() == null ? null : io.papermc.paper.adventure.PaperAdventure.asAdventure(PlayerChatMessage.this.unsignedContent());
+ }
+ @Override
+ public @org.jetbrains.annotations.NotNull String message() {
+ return PlayerChatMessage.this.signedContent();
+ }
+ @Override
+ public @org.jetbrains.annotations.NotNull net.kyori.adventure.identity.Identity identity() {
+ return net.kyori.adventure.identity.Identity.identity(PlayerChatMessage.this.sender());
+ }
+ public PlayerChatMessage playerChatMessage() {
+ return PlayerChatMessage.this;
+ }
+ }
+ public AdventureView adventureView() {
+ return new AdventureView();
+ }
2024-01-13 21:31:02 +01:00
+ // Paper end - adventure; support signed messages
2024-04-12 21:14:06 +02:00
public static final MapCodec<PlayerChatMessage> MAP_CODEC = RecordCodecBuilder.mapCodec(
instance -> instance.group(
SignedMessageLink.CODEC.fieldOf("link").forGetter(PlayerChatMessage::link),
2024-04-19 21:47:24 +02:00
@@ -47,7 +83,14 @@ public record PlayerChatMessage(
2022-12-08 18:06:14 +01:00
}
public PlayerChatMessage withUnsignedContent(Component unsignedContent) {
- Component component = !unsignedContent.equals(Component.literal(this.signedContent())) ? unsignedContent : null;
2024-04-19 21:47:24 +02:00
+ // Paper start - adventure
+ final Component component;
+ if (unsignedContent instanceof io.papermc.paper.adventure.AdventureComponent advComponent) {
+ component = this.signedContent().equals(io.papermc.paper.adventure.AdventureCodecs.tryCollapseToString(advComponent.adventure$component())) ? null : unsignedContent;
+ } else {
+ component = !unsignedContent.equals(Component.literal(this.signedContent())) ? unsignedContent : null;
+ }
+ // Paper end - adventure
2022-12-08 18:06:14 +01:00
return new PlayerChatMessage(this.link, this.signature, this.signedBody, component, this.filterMask);
}
2022-06-07 20:12:34 +02:00
diff --git a/src/main/java/net/minecraft/network/protocol/game/ClientboundSystemChatPacket.java b/src/main/java/net/minecraft/network/protocol/game/ClientboundSystemChatPacket.java
2024-04-23 20:32:19 +02:00
index c5ba5e30cd74ca2cfc3f952c7b992df239a53a34..fdb75db02603ef97b624219211a0db22cd447dea 100644
2022-06-07 20:12:34 +02:00
--- a/src/main/java/net/minecraft/network/protocol/game/ClientboundSystemChatPacket.java
+++ b/src/main/java/net/minecraft/network/protocol/game/ClientboundSystemChatPacket.java
2024-04-23 20:32:19 +02:00
@@ -18,6 +18,11 @@ public record ClientboundSystemChatPacket(Component content, boolean overlay) im
this(org.bukkit.craftbukkit.util.CraftChatMessage.fromJSON(net.md_5.bungee.chat.ComponentSerializer.toString(content)), overlay);
2022-06-07 20:12:34 +02:00
}
// Spigot end
2022-06-08 01:49:14 +02:00
+ // Paper start
2022-07-27 21:18:51 +02:00
+ public ClientboundSystemChatPacket(net.kyori.adventure.text.Component content, boolean overlay) {
2023-12-05 19:38:29 +01:00
+ this(io.papermc.paper.adventure.PaperAdventure.asVanilla(content), overlay);
2022-06-08 01:49:14 +02:00
+ }
2022-06-07 20:12:34 +02:00
+ // Paper end
2021-06-11 14:02:28 +02:00
@Override
2024-04-23 20:32:19 +02:00
public PacketType<ClientboundSystemChatPacket> type() {
2023-12-29 20:51:52 +01:00
diff --git a/src/main/java/net/minecraft/network/protocol/login/ClientboundLoginDisconnectPacket.java b/src/main/java/net/minecraft/network/protocol/login/ClientboundLoginDisconnectPacket.java
2024-08-05 21:02:19 +02:00
index bb97fdb9aa6167083442a928276ebe4225a586ef..eeaa40e8121643c6c1d951e76e7361e29210ba48 100644
2023-12-29 20:51:52 +01:00
--- a/src/main/java/net/minecraft/network/protocol/login/ClientboundLoginDisconnectPacket.java
+++ b/src/main/java/net/minecraft/network/protocol/login/ClientboundLoginDisconnectPacket.java
2024-08-05 21:02:19 +02:00
@@ -18,11 +18,16 @@ public class ClientboundLoginDisconnectPacket implements Packet<ClientLoginPacke
2023-12-29 20:51:52 +01:00
}
2024-04-23 20:32:19 +02:00
private ClientboundLoginDisconnectPacket(FriendlyByteBuf buf) {
- this.reason = Component.Serializer.fromJsonLenient(buf.readUtf(262144), RegistryAccess.EMPTY);
+ this.reason = Component.Serializer.fromJsonLenient(buf.readUtf(FriendlyByteBuf.MAX_COMPONENT_STRING_LENGTH), RegistryAccess.EMPTY); // Paper - diff on change
2023-12-29 20:51:52 +01:00
}
2024-04-23 20:32:19 +02:00
private void write(FriendlyByteBuf buf) {
- buf.writeUtf(Component.Serializer.toJson(this.reason, RegistryAccess.EMPTY));
2023-12-29 20:51:52 +01:00
+ // Paper start - Adventure
2024-04-23 20:32:19 +02:00
+ // buf.writeUtf(Component.Serializer.toJson(this.reason, RegistryAccess.EMPTY));
2024-08-05 21:02:19 +02:00
+ // In the login phase, buf.adventure$locale field is most likely null, but plugins may use internals to set it via the channel attribute
+ java.util.Locale bufLocale = buf.adventure$locale;
+ buf.writeJsonWithCodec(net.minecraft.network.chat.ComponentSerialization.localizedCodec(bufLocale == null ? java.util.Locale.US : bufLocale), this.reason, FriendlyByteBuf.MAX_COMPONENT_STRING_LENGTH);
2023-12-29 20:51:52 +01:00
+ // Paper end - Adventure
}
@Override
2022-07-23 03:56:50 +02:00
diff --git a/src/main/java/net/minecraft/server/MinecraftServer.java b/src/main/java/net/minecraft/server/MinecraftServer.java
2024-07-17 19:24:53 +02:00
index cef1761cdaf3e456695f2de61f4295fb99361914..e0b2d474e8d6f2d573d2c1f63e68ba931ecf4eb6 100644
2022-07-23 03:56:50 +02:00
--- a/src/main/java/net/minecraft/server/MinecraftServer.java
+++ b/src/main/java/net/minecraft/server/MinecraftServer.java
2024-06-13 19:12:48 +02:00
@@ -201,6 +201,7 @@ import org.bukkit.craftbukkit.SpigotTimings; // Spigot
public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTask> implements ServerInfo, ChunkIOErrorReporter, CommandSource, AutoCloseable {
2023-03-27 19:19:23 +02:00
public static final Logger LOGGER = LogUtils.getLogger();
+ public static final net.kyori.adventure.text.logger.slf4j.ComponentLogger COMPONENT_LOGGER = net.kyori.adventure.text.logger.slf4j.ComponentLogger.logger(LOGGER.getName()); // Paper
public static final String VANILLA_BRAND = "vanilla";
private static final float AVERAGE_TICK_TIME_SMOOTHING = 0.8F;
private static final int TICK_STATS_SPAN = 100;
2024-06-13 19:12:48 +02:00
@@ -251,8 +252,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
2023-06-13 01:51:45 +02:00
private boolean preventProxyConnections;
private boolean pvp;
2022-07-23 03:56:50 +02:00
private boolean allowFlight;
2023-06-13 01:51:45 +02:00
- @Nullable
- private String motd;
+ private net.kyori.adventure.text.Component motd; // Paper - Adventure
2022-07-23 03:56:50 +02:00
private int playerIdleTimeout;
2023-12-05 19:38:29 +01:00
private final long[] tickTimesNanos;
private long aggregatedTickTimesNanos;
2024-07-17 19:24:53 +02:00
@@ -1396,7 +1396,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
2023-06-13 01:51:45 +02:00
private ServerStatus buildServerStatus() {
ServerStatus.Players serverping_serverpingplayersample = this.buildPlayerStatus();
- return new ServerStatus(Component.nullToEmpty(this.motd), Optional.of(serverping_serverpingplayersample), Optional.of(ServerStatus.Version.current()), Optional.ofNullable(this.statusIcon), this.enforceSecureProfile());
+ return new ServerStatus(io.papermc.paper.adventure.PaperAdventure.asVanilla(this.motd), Optional.of(serverping_serverpingplayersample), Optional.of(ServerStatus.Version.current()), Optional.ofNullable(this.statusIcon), this.enforceSecureProfile()); // Paper - Adventure
}
private ServerStatus.Players buildPlayerStatus() {
2024-07-17 19:24:53 +02:00
@@ -1428,6 +1428,7 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
2023-03-15 13:19:54 +01:00
SpigotTimings.schedulerTimer.startTiming(); // Spigot
this.server.getScheduler().mainThreadHeartbeat(this.tickCount); // CraftBukkit
SpigotTimings.schedulerTimer.stopTiming(); // Spigot
+ io.papermc.paper.adventure.providers.ClickCallbackProviderImpl.CALLBACK_MANAGER.handleQueue(this.tickCount); // Paper
this.profiler.push("commandFunctions");
SpigotTimings.commandFunctionsTimer.startTiming(); // Spigot
this.getFunctions().tick();
2024-07-17 19:24:53 +02:00
@@ -1799,10 +1800,20 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
2023-06-13 01:51:45 +02:00
2023-09-21 21:00:11 +02:00
@Override
2023-06-13 01:51:45 +02:00
public String getMotd() {
- return this.motd;
+ return net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(this.motd); // Paper - Adventure
2022-07-23 03:56:50 +02:00
}
2023-06-13 01:51:45 +02:00
public void setMotd(String motd) {
+ // Paper start - Adventure
+ this.motd = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserializeOr(motd, net.kyori.adventure.text.Component.empty());
+ }
2022-07-23 03:56:50 +02:00
+
2023-06-13 01:51:45 +02:00
+ public net.kyori.adventure.text.Component motd() {
+ return this.motd;
2022-07-23 03:56:50 +02:00
+ }
+
2023-06-13 01:51:45 +02:00
+ public void motd(net.kyori.adventure.text.Component motd) {
+ // Paper end - Adventure
2022-07-23 03:56:50 +02:00
this.motd = motd;
}
2024-07-17 19:24:53 +02:00
@@ -2564,23 +2575,24 @@ public abstract class MinecraftServer extends ReentrantBlockableEventLoop<TickTa
2023-03-27 19:19:23 +02:00
}
public void logChatMessage(Component message, ChatType.Bound params, @Nullable String prefix) {
- String s1 = params.decorate(message).getString();
+ // Paper start
+ net.kyori.adventure.text.Component s1 = io.papermc.paper.adventure.PaperAdventure.asAdventure(params.decorate(message));
if (prefix != null) {
- MinecraftServer.LOGGER.info("[{}] {}", prefix, s1);
+ MinecraftServer.COMPONENT_LOGGER.info("[{}] {}", prefix, s1);
} else {
- MinecraftServer.LOGGER.info("{}", s1);
+ MinecraftServer.COMPONENT_LOGGER.info("{}", s1);
+ // Paper end
}
}
2022-08-01 21:34:55 +02:00
2023-09-21 21:00:11 +02:00
- // CraftBukkit start
2022-08-01 21:34:55 +02:00
public final java.util.concurrent.ExecutorService chatExecutor = java.util.concurrent.Executors.newCachedThreadPool(
- new com.google.common.util.concurrent.ThreadFactoryBuilder().setDaemon(true).setNameFormat("Async Chat Thread - #%d").build());
2023-09-21 21:00:11 +02:00
- // CraftBukkit end
2022-08-01 21:34:55 +02:00
+ new com.google.common.util.concurrent.ThreadFactoryBuilder().setDaemon(true).setNameFormat("Async Chat Thread - #%d").setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER)).build()); // Paper
2024-04-19 21:47:24 +02:00
+ public final ChatDecorator improvedChatDecorator = new io.papermc.paper.adventure.ImprovedChatDecorator(this); // Paper - adventure
2022-08-01 21:34:55 +02:00
public ChatDecorator getChatDecorator() {
2023-09-21 21:00:11 +02:00
- return ChatDecorator.PLAIN;
2024-04-19 21:47:24 +02:00
+ return this.improvedChatDecorator; // Paper - support async chat decoration events
2022-08-01 21:34:55 +02:00
}
2023-09-22 00:01:00 +02:00
public boolean logIPs() {
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/net/minecraft/server/level/ServerPlayer.java b/src/main/java/net/minecraft/server/level/ServerPlayer.java
2024-07-18 10:13:20 +02:00
index cb136a30287a17947ed018cdc48e6f91ed904072..ee5188f3aa2ff71306f5af8046e8ddf919c8601b 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/server/level/ServerPlayer.java
+++ b/src/main/java/net/minecraft/server/level/ServerPlayer.java
2024-07-18 10:13:20 +02:00
@@ -172,6 +172,7 @@ import net.minecraft.world.item.trading.MerchantOffers;
2021-06-11 14:02:28 +02:00
import net.minecraft.world.scores.Scoreboard;
import net.minecraft.world.scores.Team;
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
+import io.papermc.paper.adventure.PaperAdventure; // Paper
import org.bukkit.Bukkit;
import org.bukkit.Location;
2021-11-23 12:27:39 +01:00
import org.bukkit.WeatherType;
2024-07-18 10:13:20 +02:00
@@ -237,6 +238,7 @@ public class ServerPlayer extends net.minecraft.world.entity.player.Player {
2023-09-21 21:00:11 +02:00
private boolean disconnected;
private int requestedViewDistance;
public String language = "en_us"; // CraftBukkit - default
+ public java.util.Locale adventure$locale = java.util.Locale.US; // Paper
@Nullable
private Vec3 startingToFallPosition;
@Nullable
2024-07-18 10:13:20 +02:00
@@ -270,6 +272,7 @@ public class ServerPlayer extends net.minecraft.world.entity.player.Player {
2021-06-11 14:02:28 +02:00
// CraftBukkit start
2024-04-23 20:32:19 +02:00
public CraftPlayer.TransferCookieConnection transferCookieConnection;
2021-06-11 14:02:28 +02:00
public String displayName;
+ public net.kyori.adventure.text.Component adventure$displayName; // Paper
public Component listName;
public org.bukkit.Location compassTarget;
public int newExp = 0;
2024-07-18 10:13:20 +02:00
@@ -353,6 +356,7 @@ public class ServerPlayer extends net.minecraft.world.entity.player.Player {
2021-06-11 14:02:28 +02:00
// CraftBukkit start
this.displayName = this.getScoreboardName();
+ this.adventure$displayName = net.kyori.adventure.text.Component.text(this.getScoreboardName()); // Paper
2021-06-11 21:23:46 +02:00
this.bukkitPickUpLoot = true;
2021-06-11 14:02:28 +02:00
this.maxHealthCache = this.getMaxHealth();
}
2024-07-18 10:13:20 +02:00
@@ -910,22 +914,17 @@ public class ServerPlayer extends net.minecraft.world.entity.player.Player {
2021-06-11 14:02:28 +02:00
2021-08-13 19:08:34 +02:00
String deathmessage = defaultMessage.getString();
this.keepLevel = keepInventory; // SPIGOT-2222: pre-set keepLevel
2024-05-11 23:48:37 +02:00
- org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, damageSource, loot, deathmessage, keepInventory);
+ org.bukkit.event.entity.PlayerDeathEvent event = CraftEventFactory.callPlayerDeathEvent(this, damageSource, loot, PaperAdventure.asAdventure(defaultMessage), keepInventory); // Paper - Adventure
2021-06-11 14:02:28 +02:00
// SPIGOT-943 - only call if they have an inventory open
if (this.containerMenu != this.inventoryMenu) {
this.closeContainer();
}
- String deathMessage = event.getDeathMessage();
+ net.kyori.adventure.text.Component deathMessage = event.deathMessage() != null ? event.deathMessage() : net.kyori.adventure.text.Component.empty(); // Paper - Adventure
- if (deathMessage != null && deathMessage.length() > 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
2023-06-07 19:18:05 +02:00
this.connection.send(new ClientboundPlayerCombatKillPacket(this.getId(), ichatbasecomponent), PacketSendListener.exceptionallySend(() -> {
2022-07-27 21:18:51 +02:00
boolean flag1 = true;
2024-07-18 10:13:20 +02:00
@@ -2025,8 +2024,13 @@ public class ServerPlayer extends net.minecraft.world.entity.player.Player {
2022-08-01 21:34:55 +02:00
}
2022-12-07 18:53:34 +01:00
public void sendChatMessage(OutgoingChatMessage message, boolean filterMaskEnabled, ChatType.Bound params) {
2022-08-01 21:34:55 +02:00
+ // Paper start
2022-08-06 00:58:34 +02:00
+ this.sendChatMessage(message, filterMaskEnabled, params, null);
2022-08-01 21:34:55 +02:00
+ }
2022-12-07 18:53:34 +01:00
+ public void sendChatMessage(OutgoingChatMessage message, boolean filterMaskEnabled, ChatType.Bound params, @Nullable Component unsigned) {
2022-08-01 21:34:55 +02:00
+ // Paper end
if (this.acceptsChatMessages()) {
2022-08-06 00:58:34 +02:00
- message.sendToPlayer(this, filterMaskEnabled, params);
+ message.sendToPlayer(this, filterMaskEnabled, params, unsigned); // Paper
2022-08-01 21:34:55 +02:00
}
}
2024-07-18 10:13:20 +02:00
@@ -2053,6 +2057,7 @@ public class ServerPlayer extends net.minecraft.world.entity.player.Player {
2021-06-11 14:02:28 +02:00
}
2023-09-21 21:00:11 +02:00
// CraftBukkit end
this.language = clientOptions.language();
2024-02-09 21:30:50 +01:00
+ this.adventure$locale = java.util.Objects.requireNonNullElse(net.kyori.adventure.translation.Translator.parseLocale(this.language), java.util.Locale.US); // Paper
2023-09-21 21:00:11 +02:00
this.requestedViewDistance = clientOptions.viewDistance();
this.chatVisibility = clientOptions.chatVisibility();
this.canChatColor = clientOptions.chatColors();
diff --git a/src/main/java/net/minecraft/server/network/ServerCommonPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerCommonPacketListenerImpl.java
2024-06-14 01:32:45 +02:00
index 677ee8dfa0d2f5bcb23ee870a76bcee63e557813..678f12679985c6fa9effe8beec306d95d5e0bdac 100644
2023-09-21 21:00:11 +02:00
--- a/src/main/java/net/minecraft/server/network/ServerCommonPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerCommonPacketListenerImpl.java
2024-06-13 19:12:48 +02:00
@@ -67,7 +67,7 @@ public abstract class ServerCommonPacketListenerImpl implements ServerCommonPack
2023-09-21 21:00:11 +02:00
private static final Component TIMEOUT_DISCONNECTION_MESSAGE = Component.translatable("disconnect.timeout");
2024-04-23 20:32:19 +02:00
static final Component DISCONNECT_UNEXPECTED_QUERY = Component.translatable("multiplayer.disconnect.unexpected_query_response");
2023-09-21 21:00:11 +02:00
protected final MinecraftServer server;
- protected final Connection connection;
2023-03-14 20:24:52 +01:00
+ public final Connection connection; // Paper
2024-04-23 20:32:19 +02:00
private final boolean transferred;
2023-09-21 21:00:11 +02:00
private long keepAliveTime;
private boolean keepAlivePending;
2024-06-13 19:12:48 +02:00
@@ -76,6 +76,7 @@ public abstract class ServerCommonPacketListenerImpl implements ServerCommonPack
2024-04-23 20:32:19 +02:00
private boolean closed = false;
2023-12-25 11:51:44 +01:00
private int latency;
private volatile boolean suspendFlushingOnServerThread = false;
+ public final java.util.Map<java.util.UUID, net.kyori.adventure.resource.ResourcePackCallback> packCallbacks = new java.util.concurrent.ConcurrentHashMap<>(); // Paper - adventure resource pack callbacks
public ServerCommonPacketListenerImpl(MinecraftServer minecraftserver, Connection networkmanager, CommonListenerCookie commonlistenercookie, ServerPlayer player) { // CraftBukkit
this.server = minecraftserver;
2024-06-13 19:12:48 +02:00
@@ -189,6 +190,18 @@ public abstract class ServerCommonPacketListenerImpl implements ServerCommonPack
2023-12-25 11:51:44 +01:00
ServerCommonPacketListenerImpl.LOGGER.info("Disconnecting {} due to resource pack {} rejection", this.playerProfile().getName(), packet.id());
2024-06-13 19:12:48 +02:00
this.disconnect((Component) Component.translatable("multiplayer.requiredTexturePrompt.disconnect"));
2023-12-25 11:51:44 +01:00
}
+ // Paper start - adventure pack callbacks
+ // call the callbacks before the previously-existing event so the event has final say
+ final net.kyori.adventure.resource.ResourcePackCallback callback;
+ if (packet.action().isTerminal()) {
+ callback = this.packCallbacks.remove(packet.id());
+ } else {
+ callback = this.packCallbacks.get(packet.id());
+ }
+ if (callback != null) {
+ callback.packEventReceived(packet.id(), net.kyori.adventure.resource.ResourcePackStatus.valueOf(packet.action().name()), this.getCraftPlayer());
+ }
+ // Paper end
this.cserver.getPluginManager().callEvent(new PlayerResourcePackStatusEvent(this.getCraftPlayer(), packet.id(), PlayerResourcePackStatusEvent.Status.values()[packet.action().ordinal()])); // CraftBukkit
}
2024-06-13 19:12:48 +02:00
@@ -275,6 +288,12 @@ public abstract class ServerCommonPacketListenerImpl implements ServerCommonPack
}
2023-03-23 22:57:03 +01:00
}
2024-06-13 19:12:48 +02:00
+ // Paper start - adventure
2024-06-14 01:32:45 +02:00
+ public void disconnect(final net.kyori.adventure.text.Component reason) {
2024-06-13 19:12:48 +02:00
+ this.disconnect(io.papermc.paper.adventure.PaperAdventure.asVanilla(reason));
2021-06-11 14:02:28 +02:00
+ }
2024-06-13 19:12:48 +02:00
+ // Paper end - adventure
2021-06-11 14:02:28 +02:00
+
2024-06-13 19:12:48 +02:00
public void disconnect(Component reason) {
this.disconnect(new DisconnectionDetails(reason));
}
@@ -305,9 +324,9 @@ public abstract class ServerCommonPacketListenerImpl implements ServerCommonPack
2022-07-27 21:18:51 +02:00
return;
2021-06-11 14:02:28 +02:00
}
2022-07-27 21:18:51 +02:00
2021-06-11 14:02:28 +02:00
- String leaveMessage = ChatFormatting.YELLOW + this.player.getScoreboardName() + " left the game.";
2022-06-09 10:51:45 +02:00
+ net.kyori.adventure.text.Component leaveMessage = net.kyori.adventure.text.Component.translatable("multiplayer.player.left", net.kyori.adventure.text.format.NamedTextColor.YELLOW, io.papermc.paper.configuration.GlobalConfiguration.get().messages.useDisplayNameInQuitMessage ? this.player.getBukkitEntity().displayName() : net.kyori.adventure.text.Component.text(this.player.getScoreboardName())); // Paper - Adventure
2021-06-11 14:02:28 +02:00
2024-06-13 19:12:48 +02:00
- PlayerKickEvent event = new PlayerKickEvent(this.player.getBukkitEntity(), CraftChatMessage.fromComponent(disconnectionInfo.reason()), leaveMessage);
+ PlayerKickEvent event = new PlayerKickEvent(this.player.getBukkitEntity(), io.papermc.paper.adventure.PaperAdventure.asAdventure(disconnectionInfo.reason()), leaveMessage); // Paper - adventure
2021-06-11 14:02:28 +02:00
2021-06-11 21:23:46 +02:00
if (this.cserver.getServer().isRunning()) {
this.cserver.getPluginManager().callEvent(event);
2024-06-13 19:12:48 +02:00
@@ -319,7 +338,7 @@ public abstract class ServerCommonPacketListenerImpl implements ServerCommonPack
2021-06-11 14:02:28 +02:00
}
2022-03-16 16:57:51 +01:00
this.player.kickLeaveMessage = event.getLeaveMessage(); // CraftBukkit - SPIGOT-3034: Forward leave message to PlayerQuitEvent
2021-06-11 14:02:28 +02:00
// Send the possibly modified leave message
2024-06-13 19:12:48 +02:00
- this.disconnect0(new DisconnectionDetails(CraftChatMessage.fromString(event.getReason(), true)[0], disconnectionInfo.report(), disconnectionInfo.bugReportLink()));
+ this.disconnect0(new DisconnectionDetails(io.papermc.paper.adventure.PaperAdventure.asVanilla(event.reason()), disconnectionInfo.report(), disconnectionInfo.bugReportLink())); // Paper - Adventure
}
2021-06-11 14:02:28 +02:00
2024-06-13 19:12:48 +02:00
private void disconnect0(DisconnectionDetails disconnectiondetails) {
2023-09-23 01:42:59 +02:00
diff --git a/src/main/java/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
2024-06-13 19:12:48 +02:00
index e7c407039fef88ef01ba9b6be9ae5bcc3edc026f..5457358bc76889153036818fdfd70a043ec4e40f 100644
2023-09-23 01:42:59 +02:00
--- a/src/main/java/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerConfigurationPacketListenerImpl.java
2024-06-13 19:12:48 +02:00
@@ -120,6 +120,7 @@ public class ServerConfigurationPacketListenerImpl extends ServerCommonPacketLis
2023-09-23 01:42:59 +02:00
@Override
public void handleClientInformation(ServerboundClientInformationPacket packet) {
this.clientInformation = packet.information();
+ this.connection.channel.attr(io.papermc.paper.adventure.PaperAdventure.LOCALE_ATTRIBUTE).set(net.kyori.adventure.translation.Translator.parseLocale(packet.information().language())); // Paper
}
@Override
2023-09-21 21:00:11 +02:00
diff --git a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
2024-06-16 17:21:14 +02:00
index e244ac9f51a08603a7877e7e655fda26cd396772..556d8f23ee2de77cea71abcc0e56718e60b20b05 100644
2023-09-21 21:00:11 +02:00
--- a/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerGamePacketListenerImpl.java
2024-06-13 19:12:48 +02:00
@@ -45,6 +45,7 @@ import net.minecraft.nbt.CompoundTag;
2023-09-21 21:00:11 +02:00
import net.minecraft.network.Connection;
2024-06-13 19:12:48 +02:00
import net.minecraft.network.DisconnectionDetails;
2023-09-21 21:00:11 +02:00
import net.minecraft.network.TickablePacketListener;
+import net.minecraft.network.chat.ChatDecorator;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.LastSeenMessages;
2024-04-25 23:21:18 +02:00
@@ -195,6 +196,8 @@ import net.minecraft.world.phys.shapes.VoxelShape;
2023-09-21 21:00:11 +02:00
import org.slf4j.Logger;
// CraftBukkit start
+import io.papermc.paper.adventure.ChatProcessor; // Paper
+import io.papermc.paper.adventure.PaperAdventure; // Paper
import com.mojang.datafixers.util.Pair;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
2024-06-13 19:12:48 +02:00
@@ -1728,9 +1731,11 @@ public class ServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl
2021-06-11 14:02:28 +02:00
*/
this.player.disconnect();
2021-11-23 12:27:39 +01:00
- String quitMessage = this.server.getPlayerList().remove(this.player);
2021-06-11 14:02:28 +02:00
- if ((quitMessage != null) && (quitMessage.length() > 0)) {
2021-11-23 12:27:39 +01:00
- this.server.getPlayerList().broadcastMessage(CraftChatMessage.fromString(quitMessage));
2021-06-11 14:02:28 +02:00
+ // Paper start - Adventure
2021-11-23 12:27:39 +01:00
+ net.kyori.adventure.text.Component quitMessage = this.server.getPlayerList().remove(this.player);
2021-06-11 14:02:28 +02:00
+ if ((quitMessage != null) && !quitMessage.equals(net.kyori.adventure.text.Component.empty())) {
2022-07-27 21:18:51 +02:00
+ this.server.getPlayerList().broadcastSystemMessage(PaperAdventure.asVanilla(quitMessage), false);
2021-06-11 14:02:28 +02:00
+ // Paper end
}
// CraftBukkit end
2021-06-11 21:23:46 +02:00
this.player.getTextFilter().leave();
2024-06-13 19:12:48 +02:00
@@ -1791,10 +1796,10 @@ public class ServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl
2024-04-23 20:32:19 +02:00
}
2022-12-07 18:53:34 +01:00
2024-04-23 20:32:19 +02:00
CompletableFuture<FilteredText> completablefuture = this.filterTextPacket(playerchatmessage.signedContent()).thenApplyAsync(Function.identity(), this.server.chatExecutor); // CraftBukkit - async chat
- Component ichatbasecomponent = this.server.getChatDecorator().decorate(this.player, playerchatmessage.decoratedContent());
+ CompletableFuture<Component> componentFuture = this.server.getChatDecorator().decorate(this.player, null, playerchatmessage.decoratedContent()); // Paper - Adventure
2023-09-22 00:26:51 +02:00
2024-04-23 20:32:19 +02:00
- this.chatMessageChain.append(completablefuture, (filteredtext) -> {
- PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(ichatbasecomponent).filter(filteredtext.mask());
+ this.chatMessageChain.append(CompletableFuture.allOf(completablefuture, componentFuture), (filteredtext) -> { // Paper - Adventure
+ PlayerChatMessage playerchatmessage1 = playerchatmessage.withUnsignedContent(componentFuture.join()).filter(completablefuture.join().mask()); // Paper - Adventure
2023-03-14 19:05:23 +01:00
2024-04-23 20:32:19 +02:00
this.broadcastChatMessage(playerchatmessage1);
});
2024-06-13 19:12:48 +02:00
@@ -2014,7 +2019,15 @@ public class ServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl
2021-06-11 14:02:28 +02:00
this.handleCommand(s);
} else if (this.player.getChatVisibility() == ChatVisiblity.SYSTEM) {
// Do nothing, this is coming from a plugin
- } else {
+ // Paper start
+ } else if (true) {
2023-12-29 01:50:06 +01:00
+ if (!async && !org.bukkit.Bukkit.isPrimaryThread()) {
+ org.spigotmc.AsyncCatcher.catchOp("Asynchronous player chat is not allowed here");
+ }
2022-08-01 21:34:55 +02:00
+ final ChatProcessor cp = new ChatProcessor(this.server, this.player, original, async);
2021-06-11 14:02:28 +02:00
+ cp.process();
2021-06-11 21:23:46 +02:00
+ // Paper end
2021-06-11 14:02:28 +02:00
+ } else if (false) { // Paper
2021-06-11 21:23:46 +02:00
Player player = this.getCraftPlayer();
2023-10-27 01:34:58 +02:00
AsyncPlayerChatEvent event = new AsyncPlayerChatEvent(async, player, s, new LazyPlayerSet(this.server));
2022-07-27 21:18:51 +02:00
String originalFormat = event.getFormat(), originalMessage = event.getMessage();
2024-06-13 19:12:48 +02:00
@@ -3011,6 +3024,7 @@ public class ServerGamePacketListenerImpl extends ServerCommonPacketListenerImpl
2023-09-23 01:42:59 +02:00
public void handleClientInformation(ServerboundClientInformationPacket packet) {
PacketUtils.ensureRunningOnSameThread(packet, this, this.player.serverLevel());
this.player.updateOptions(packet.information());
+ this.connection.channel.attr(io.papermc.paper.adventure.PaperAdventure.LOCALE_ATTRIBUTE).set(net.kyori.adventure.translation.Translator.parseLocale(packet.information().language())); // Paper
}
@Override
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
2024-06-13 19:12:48 +02:00
index 8e715261b99bcc19b6f4b9787987c59aa19ba70e..851e4bdf1739736fd193786a6541ffb341525dcb 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
2024-06-13 19:12:48 +02:00
@@ -333,7 +333,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
2024-01-14 10:46:04 +01:00
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<PlayerPreLoginEvent.Result> waitable = new Waitable<PlayerPreLoginEvent.Result>() {
@Override
2024-06-13 19:12:48 +02:00
@@ -345,12 +345,12 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
2024-01-14 10:46:04 +01:00
ServerLoginPacketListenerImpl.this.server.processQueue.add(waitable);
if (waitable.get() != PlayerPreLoginEvent.Result.ALLOWED) {
- this.disconnect(event.getKickMessage());
+ this.disconnect(io.papermc.paper.adventure.PaperAdventure.asVanilla(event.kickMessage())); // Paper - Adventure
return;
}
} else {
if (asyncEvent.getLoginResult() != AsyncPlayerPreLoginEvent.Result.ALLOWED) {
- this.disconnect(asyncEvent.getKickMessage());
+ this.disconnect(io.papermc.paper.adventure.PaperAdventure.asVanilla(asyncEvent.kickMessage())); // Paper - Adventure
return;
}
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java
2024-07-06 21:19:14 +02:00
index 3848cc836785829c5aa82bdb5d37d36a97f94a04..f08700abb005f487aca95c0457c09cefa9a81be2 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerStatusPacketListenerImpl.java
2024-06-13 19:12:48 +02:00
@@ -58,7 +58,7 @@ public class ServerStatusPacketListenerImpl implements ServerStatusPacketListene
2021-06-11 14:02:28 +02:00
CraftIconCache icon = server.server.getServerIcon();
ServerListPingEvent() {
2023-10-27 01:34:58 +02:00
- super(ServerStatusPacketListenerImpl.this.connection.hostname, ((InetSocketAddress) ServerStatusPacketListenerImpl.this.connection.getRemoteAddress()).getAddress(), server.getMotd(), server.getPlayerList().getMaxPlayers());
+ super(ServerStatusPacketListenerImpl.this.connection.hostname, ((InetSocketAddress) ServerStatusPacketListenerImpl.this.connection.getRemoteAddress()).getAddress(), server.server.motd(), server.getPlayerList().getMaxPlayers()); // Paper - Adventure
2021-06-11 14:02:28 +02:00
}
@Override
diff --git a/src/main/java/net/minecraft/server/players/PlayerList.java b/src/main/java/net/minecraft/server/players/PlayerList.java
2024-06-14 01:32:45 +02:00
index 6abe921099ff00ecfaf0f423ef27d708420f6f48..e9109526880159e2341cc97b53939ba2bcfaeaf9 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/server/players/PlayerList.java
+++ b/src/main/java/net/minecraft/server/players/PlayerList.java
2024-04-23 20:32:19 +02:00
@@ -271,7 +271,7 @@ public abstract class PlayerList {
2021-06-11 14:02:28 +02:00
}
// CraftBukkit start
2022-06-07 20:12:34 +02:00
ichatmutablecomponent.withStyle(ChatFormatting.YELLOW);
- String joinMessage = CraftChatMessage.fromComponent(ichatmutablecomponent);
+ Component joinMessage = ichatmutablecomponent; // Paper - Adventure
2021-06-11 14:02:28 +02:00
2021-06-11 21:23:46 +02:00
playerconnection.teleport(player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot());
2023-03-14 19:05:23 +01:00
ServerStatus serverping = this.server.getStatus();
2024-04-23 20:32:19 +02:00
@@ -292,19 +292,18 @@ public abstract class PlayerList {
2021-06-20 21:25:59 +02:00
// Ensure that player inventory is populated with its viewer
player.containerMenu.transferTo(player.containerMenu, bukkitPlayer);
2021-06-11 14:02:28 +02:00
2021-06-20 21:25:59 +02:00
- PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(bukkitPlayer, joinMessage);
2023-09-21 21:00:11 +02:00
+ PlayerJoinEvent playerJoinEvent = new PlayerJoinEvent(bukkitPlayer, io.papermc.paper.adventure.PaperAdventure.asAdventure(ichatmutablecomponent)); // Paper - Adventure
2021-06-11 21:23:46 +02:00
this.cserver.getPluginManager().callEvent(playerJoinEvent);
2021-06-11 14:02:28 +02:00
2023-03-14 19:05:23 +01:00
if (!player.connection.isAcceptingMessages()) {
2021-06-11 14:02:28 +02:00
return;
}
- joinMessage = playerJoinEvent.getJoinMessage();
+ final net.kyori.adventure.text.Component jm = playerJoinEvent.joinMessage();
- if (joinMessage != null && joinMessage.length() > 0) {
2022-07-28 00:10:27 +02:00
- for (Component line : org.bukkit.craftbukkit.util.CraftChatMessage.fromString(joinMessage)) {
- this.server.getPlayerList().broadcastSystemMessage(line, false);
- }
2021-06-11 14:02:28 +02:00
+ if (jm != null && !jm.equals(net.kyori.adventure.text.Component.empty())) { // Paper - Adventure
2023-09-21 21:00:11 +02:00
+ joinMessage = io.papermc.paper.adventure.PaperAdventure.asVanilla(jm); // Paper - Adventure
2022-07-27 21:18:51 +02:00
+ this.server.getPlayerList().broadcastSystemMessage(joinMessage, false); // Paper - Adventure
2022-07-28 00:10:27 +02:00
}
// CraftBukkit end
2024-06-13 19:12:48 +02:00
@@ -492,7 +491,7 @@ public abstract class PlayerList {
2023-06-07 20:03:53 +02:00
}
- public String remove(ServerPlayer entityplayer) { // CraftBukkit - return string
+ public net.kyori.adventure.text.Component remove(ServerPlayer entityplayer) { // CraftBukkit - return string // Paper - return Component
ServerLevel worldserver = entityplayer.serverLevel();
entityplayer.awardStat(Stats.LEAVE_GAME);
2024-06-13 19:12:48 +02:00
@@ -503,7 +502,7 @@ public abstract class PlayerList {
2021-06-11 14:02:28 +02:00
entityplayer.closeContainer();
}
2022-03-16 16:57:51 +01:00
- PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(entityplayer.getBukkitEntity(), entityplayer.kickLeaveMessage != null ? entityplayer.kickLeaveMessage : "\u00A7e" + entityplayer.getScoreboardName() + " left the game");
2023-09-21 21:00:11 +02:00
+ PlayerQuitEvent playerQuitEvent = new PlayerQuitEvent(entityplayer.getBukkitEntity(), net.kyori.adventure.text.Component.translatable("multiplayer.player.left", net.kyori.adventure.text.format.NamedTextColor.YELLOW, io.papermc.paper.configuration.GlobalConfiguration.get().messages.useDisplayNameInQuitMessage ? entityplayer.getBukkitEntity().displayName() : io.papermc.paper.adventure.PaperAdventure.asAdventure(entityplayer.getDisplayName()))); // Paper - Adventure
2021-06-11 21:23:46 +02:00
this.cserver.getPluginManager().callEvent(playerQuitEvent);
2021-06-11 14:02:28 +02:00
entityplayer.getBukkitEntity().disconnect(playerQuitEvent.getQuitMessage());
2024-06-13 19:12:48 +02:00
@@ -556,7 +555,7 @@ public abstract class PlayerList {
2021-06-11 21:23:46 +02:00
this.cserver.getScoreboardManager().removePlayer(entityplayer.getBukkitEntity());
2021-06-11 14:02:28 +02:00
// CraftBukkit end
- return playerQuitEvent.getQuitMessage(); // CraftBukkit
+ return playerQuitEvent.quitMessage(); // Paper - Adventure
}
// CraftBukkit start - Whole method, SocketAddress to LoginListener, added hostname to signature, return EntityPlayer
2024-06-13 19:12:48 +02:00
@@ -603,11 +602,11 @@ public abstract class PlayerList {
2021-06-11 14:02:28 +02:00
}
// return chatmessage;
2022-06-07 20:12:34 +02:00
- event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(ichatmutablecomponent));
2023-09-21 21:00:11 +02:00
+ event.disallow(PlayerLoginEvent.Result.KICK_BANNED, io.papermc.paper.adventure.PaperAdventure.asAdventure(ichatmutablecomponent)); // Paper - Adventure
2021-06-11 14:02:28 +02:00
} else if (!this.isWhiteListed(gameprofile)) {
2022-06-07 20:12:34 +02:00
ichatmutablecomponent = Component.translatable("multiplayer.disconnect.not_whitelisted");
2021-06-11 14:02:28 +02:00
- event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, org.spigotmc.SpigotConfig.whitelistMessage); // Spigot
Updated Upstream (Bukkit/CraftBukkit/Spigot) (#10277)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
9a80d38c SPIGOT-336, SPIGOT-3366, SPIGOT-5768, SPIGOT-6409, SPIGOT-6861, PR-722: Add EntityRemoveEvent
258086d9 SPIGOT-7417, PR-967: Add Sign#getTargetSide and Sign#getAllowedEditor
ffaba051 SPIGOT-7584: Add missing Tag.ITEMS_NON_FLAMMABLE_WOOD
CraftBukkit Changes:
98b6c1ac7 SPIGOT-7589 Fix NullPointerException when bans expire
a2736ddb0 SPIGOT-336, SPIGOT-3366, SPIGOT-5768, SPIGOT-6409, SPIGOT-6861, PR-1008: Add EntityRemoveEvent
5bf12cb89 SPIGOT-7565: Throw a more descriptive error message when a developer tries to spawn an entity from a CraftBukkit class
76d95fe7e SPIGOT-7417, PR-1343: Add Sign#getTargetSide and Sign#getAllowedEditor
Spigot Changes:
e9ec5485 Rebuild patches
f1b62e0c Rebuild patches
2024-02-23 14:37:33 +01:00
- } else if (this.ipBans.isBanned(socketaddress)) {
2022-05-26 21:12:14 +02:00
+ event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(org.spigotmc.SpigotConfig.whitelistMessage)); // Spigot // Paper - Adventure
Updated Upstream (Bukkit/CraftBukkit/Spigot) (#10277)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
9a80d38c SPIGOT-336, SPIGOT-3366, SPIGOT-5768, SPIGOT-6409, SPIGOT-6861, PR-722: Add EntityRemoveEvent
258086d9 SPIGOT-7417, PR-967: Add Sign#getTargetSide and Sign#getAllowedEditor
ffaba051 SPIGOT-7584: Add missing Tag.ITEMS_NON_FLAMMABLE_WOOD
CraftBukkit Changes:
98b6c1ac7 SPIGOT-7589 Fix NullPointerException when bans expire
a2736ddb0 SPIGOT-336, SPIGOT-3366, SPIGOT-5768, SPIGOT-6409, SPIGOT-6861, PR-1008: Add EntityRemoveEvent
5bf12cb89 SPIGOT-7565: Throw a more descriptive error message when a developer tries to spawn an entity from a CraftBukkit class
76d95fe7e SPIGOT-7417, PR-1343: Add Sign#getTargetSide and Sign#getAllowedEditor
Spigot Changes:
e9ec5485 Rebuild patches
f1b62e0c Rebuild patches
2024-02-23 14:37:33 +01:00
+ } else if (this.getIpBans().isBanned(socketaddress) && !this.getIpBans().get(socketaddress).hasExpired()) {
2021-06-11 14:02:28 +02:00
IpBanListEntry ipbanentry = this.ipBans.get(socketaddress);
Updated Upstream (Bukkit/CraftBukkit/Spigot) (#10277)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
9a80d38c SPIGOT-336, SPIGOT-3366, SPIGOT-5768, SPIGOT-6409, SPIGOT-6861, PR-722: Add EntityRemoveEvent
258086d9 SPIGOT-7417, PR-967: Add Sign#getTargetSide and Sign#getAllowedEditor
ffaba051 SPIGOT-7584: Add missing Tag.ITEMS_NON_FLAMMABLE_WOOD
CraftBukkit Changes:
98b6c1ac7 SPIGOT-7589 Fix NullPointerException when bans expire
a2736ddb0 SPIGOT-336, SPIGOT-3366, SPIGOT-5768, SPIGOT-6409, SPIGOT-6861, PR-1008: Add EntityRemoveEvent
5bf12cb89 SPIGOT-7565: Throw a more descriptive error message when a developer tries to spawn an entity from a CraftBukkit class
76d95fe7e SPIGOT-7417, PR-1343: Add Sign#getTargetSide and Sign#getAllowedEditor
Spigot Changes:
e9ec5485 Rebuild patches
f1b62e0c Rebuild patches
2024-02-23 14:37:33 +01:00
ichatmutablecomponent = Component.translatable("multiplayer.disconnect.banned_ip.reason", ipbanentry.getReason());
2024-06-13 19:12:48 +02:00
@@ -616,17 +615,17 @@ public abstract class PlayerList {
2021-06-11 14:02:28 +02:00
}
// return chatmessage;
2022-06-07 20:12:34 +02:00
- event.disallow(PlayerLoginEvent.Result.KICK_BANNED, CraftChatMessage.fromComponent(ichatmutablecomponent));
2023-09-21 21:00:11 +02:00
+ event.disallow(PlayerLoginEvent.Result.KICK_BANNED, io.papermc.paper.adventure.PaperAdventure.asAdventure(ichatmutablecomponent)); // Paper - Adventure
2021-06-11 14:02:28 +02:00
} else {
2022-06-07 20:12:34 +02:00
// return this.players.size() >= this.maxPlayers && !this.canBypassPlayerLimit(gameprofile) ? IChatBaseComponent.translatable("multiplayer.disconnect.server_full") : null;
2021-06-11 14:02:28 +02:00
if (this.players.size() >= this.maxPlayers && !this.canBypassPlayerLimit(gameprofile)) {
- event.disallow(PlayerLoginEvent.Result.KICK_FULL, org.spigotmc.SpigotConfig.serverFullMessage); // Spigot
2022-05-26 21:12:14 +02:00
+ event.disallow(PlayerLoginEvent.Result.KICK_FULL, net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(org.spigotmc.SpigotConfig.serverFullMessage)); // Spigot // Paper - Adventure
2021-06-11 14:02:28 +02:00
}
}
2021-06-11 21:23:46 +02:00
this.cserver.getPluginManager().callEvent(event);
2021-06-11 14:02:28 +02:00
if (event.getResult() != PlayerLoginEvent.Result.ALLOWED) {
- loginlistener.disconnect(event.getKickMessage());
2023-09-21 21:00:11 +02:00
+ loginlistener.disconnect(io.papermc.paper.adventure.PaperAdventure.asVanilla(event.kickMessage())); // Paper - Adventure
2021-06-11 14:02:28 +02:00
return null;
}
return entity;
2024-06-13 19:12:48 +02:00
@@ -1122,7 +1121,7 @@ public abstract class PlayerList {
2021-06-11 14:02:28 +02:00
public void removeAll() {
// CraftBukkit start - disconnect safely
for (ServerPlayer player : this.players) {
2024-06-13 19:12:48 +02:00
- player.connection.disconnect(CraftChatMessage.fromStringOrEmpty(this.server.server.getShutdownMessage())); // CraftBukkit - add custom shutdown message
2024-06-14 01:32:45 +02:00
+ player.connection.disconnect(java.util.Objects.requireNonNullElseGet(this.server.server.shutdownMessage(), net.kyori.adventure.text.Component::empty)); // CraftBukkit - add custom shutdown message // Paper - Adventure
2021-06-11 14:02:28 +02:00
}
// CraftBukkit end
2024-06-13 19:12:48 +02:00
@@ -1163,24 +1162,43 @@ public abstract class PlayerList {
2022-08-01 21:34:55 +02:00
}
2022-08-06 00:58:34 +02:00
public void broadcastChatMessage(PlayerChatMessage message, ServerPlayer sender, ChatType.Bound params) {
2022-08-01 21:34:55 +02:00
+ // Paper start
2022-08-06 00:58:34 +02:00
+ this.broadcastChatMessage(message, sender, params, null);
2022-08-01 21:34:55 +02:00
+ }
2022-08-06 00:58:34 +02:00
+ public void broadcastChatMessage(PlayerChatMessage message, ServerPlayer sender, ChatType.Bound params, @Nullable Function<net.kyori.adventure.audience.Audience, Component> unsignedFunction) {
2022-08-01 21:34:55 +02:00
+ // Paper end
Objects.requireNonNull(sender);
2022-12-07 18:53:34 +01:00
- this.broadcastChatMessage(message, sender::shouldFilterMessageTo, sender, params);
+ this.broadcastChatMessage(message, sender::shouldFilterMessageTo, sender, params, unsignedFunction); // Paper
2022-08-01 21:34:55 +02:00
}
2022-12-07 18:53:34 +01:00
private void broadcastChatMessage(PlayerChatMessage message, Predicate<ServerPlayer> shouldSendFiltered, @Nullable ServerPlayer sender, ChatType.Bound params) {
2022-08-01 21:34:55 +02:00
+ // Paper start
2022-12-07 18:53:34 +01:00
+ this.broadcastChatMessage(message, shouldSendFiltered, sender, params, null);
2022-08-01 21:34:55 +02:00
+ }
2022-12-07 18:53:34 +01:00
+ public void broadcastChatMessage(PlayerChatMessage message, Predicate<ServerPlayer> shouldSendFiltered, @Nullable ServerPlayer sender, ChatType.Bound params, @Nullable Function<net.kyori.adventure.audience.Audience, Component> unsignedFunction) {
2022-08-01 21:34:55 +02:00
+ // Paper end
2022-12-07 18:53:34 +01:00
boolean flag = this.verifyChatTrusted(message);
- this.server.logChatMessage(message.decoratedContent(), params, flag ? null : "Not Secure");
2023-02-23 10:37:18 +01:00
+ this.server.logChatMessage((unsignedFunction == null ? message.decoratedContent() : unsignedFunction.apply(this.server.console)), params, flag ? null : "Not Secure"); // Paper
2022-12-07 18:53:34 +01:00
OutgoingChatMessage outgoingchatmessage = OutgoingChatMessage.create(message);
boolean flag1 = false;
2023-01-10 14:01:42 +01:00
boolean flag2;
2024-04-25 22:34:46 +02:00
+ Packet<?> disguised = sender != null && unsignedFunction == null ? new net.minecraft.network.protocol.game.ClientboundDisguisedChatPacket(outgoingchatmessage.content(), params) : null; // Paper - don't send player chat packets from vanished players
2023-01-10 14:01:42 +01:00
for (Iterator iterator = this.players.iterator(); iterator.hasNext(); flag1 |= flag2 && message.isFullyFiltered()) {
2022-08-01 21:34:55 +02:00
ServerPlayer entityplayer1 = (ServerPlayer) iterator.next();
2022-12-07 18:53:34 +01:00
flag2 = shouldSendFiltered.test(entityplayer1);
- entityplayer1.sendChatMessage(outgoingchatmessage, flag2, params);
2023-01-10 14:01:42 +01:00
+ // Paper start - don't send player chat packets from vanished players
+ if (sender != null && !entityplayer1.getBukkitEntity().canSee(sender.getBukkitEntity())) {
+ entityplayer1.connection.send(unsignedFunction != null
2024-04-25 22:34:46 +02:00
+ ? new net.minecraft.network.protocol.game.ClientboundDisguisedChatPacket(unsignedFunction.apply(entityplayer1.getBukkitEntity()), params)
2023-01-10 14:01:42 +01:00
+ : disguised);
+ continue;
+ }
+ // Paper end
2022-12-07 18:53:34 +01:00
+ entityplayer1.sendChatMessage(outgoingchatmessage, flag2, params, unsignedFunction == null ? null : unsignedFunction.apply(entityplayer1.getBukkitEntity())); // Paper
}
if (flag1 && sender != null) {
2024-06-13 19:12:48 +02:00
@@ -1189,7 +1207,7 @@ public abstract class PlayerList {
2022-08-01 21:34:55 +02:00
}
2022-12-07 18:53:34 +01:00
- private boolean verifyChatTrusted(PlayerChatMessage message) {
+ public boolean verifyChatTrusted(PlayerChatMessage message) { // Paper - private -> public
return message.hasSignature() && !message.hasExpiredServer(Instant.now());
2022-08-01 21:34:55 +02:00
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/net/minecraft/world/BossEvent.java b/src/main/java/net/minecraft/world/BossEvent.java
2024-04-23 20:32:19 +02:00
index ed54c81a3269360acce674aa4e1d54ccb2461841..c9c849534c3998cfcab7ddcb12a71ccb1fdb3e1a 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/world/BossEvent.java
+++ b/src/main/java/net/minecraft/world/BossEvent.java
2021-07-04 01:26:13 +02:00
@@ -13,6 +13,7 @@ public abstract class BossEvent {
2021-06-11 14:02:28 +02:00
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;
2021-07-04 01:26:13 +02:00
@@ -27,61 +28,75 @@ public abstract class BossEvent {
}
public Component getName() {
+ if (this.adventure != null) return io.papermc.paper.adventure.PaperAdventure.asVanilla(this.adventure.name()); // Paper
return this.name;
}
public void setName(Component name) {
+ if (this.adventure != null) this.adventure.name(io.papermc.paper.adventure.PaperAdventure.asAdventure(name)); // Paper
this.name = name;
}
public float getProgress() {
+ if (this.adventure != null) return this.adventure.progress(); // Paper
return this.progress;
}
2022-03-01 06:43:03 +01:00
public void setProgress(float percent) {
+ if (this.adventure != null) this.adventure.progress(percent); // Paper
this.progress = percent;
2021-07-04 01:26:13 +02:00
}
public BossEvent.BossBarColor getColor() {
+ if (this.adventure != null) return io.papermc.paper.adventure.PaperAdventure.asVanilla(this.adventure.color()); // Paper
return this.color;
}
public void setColor(BossEvent.BossBarColor color) {
+ if (this.adventure != null) this.adventure.color(io.papermc.paper.adventure.PaperAdventure.asAdventure(color)); // Paper
this.color = color;
}
public BossEvent.BossBarOverlay getOverlay() {
+ if (this.adventure != null) return io.papermc.paper.adventure.PaperAdventure.asVanilla(this.adventure.overlay()); // Paper
return this.overlay;
}
public void setOverlay(BossEvent.BossBarOverlay style) {
+ if (this.adventure != null) this.adventure.overlay(io.papermc.paper.adventure.PaperAdventure.asAdventure(style)); // Paper
this.overlay = style;
}
public boolean shouldDarkenScreen() {
+ if (this.adventure != null) return this.adventure.hasFlag(net.kyori.adventure.bossbar.BossBar.Flag.DARKEN_SCREEN); // Paper
return this.darkenScreen;
}
public BossEvent setDarkenScreen(boolean darkenSky) {
+ if (this.adventure != null) io.papermc.paper.adventure.PaperAdventure.setFlag(this.adventure, net.kyori.adventure.bossbar.BossBar.Flag.DARKEN_SCREEN, darkenSky); // Paper
this.darkenScreen = darkenSky;
return this;
}
public boolean shouldPlayBossMusic() {
+ if (this.adventure != null) return this.adventure.hasFlag(net.kyori.adventure.bossbar.BossBar.Flag.PLAY_BOSS_MUSIC); // Paper
return this.playBossMusic;
}
public BossEvent setPlayBossMusic(boolean dragonMusic) {
+ if (this.adventure != null) io.papermc.paper.adventure.PaperAdventure.setFlag(this.adventure, net.kyori.adventure.bossbar.BossBar.Flag.PLAY_BOSS_MUSIC, dragonMusic); // Paper
this.playBossMusic = dragonMusic;
return this;
}
public BossEvent setCreateWorldFog(boolean thickenFog) {
+ if (this.adventure != null) io.papermc.paper.adventure.PaperAdventure.setFlag(this.adventure, net.kyori.adventure.bossbar.BossBar.Flag.CREATE_WORLD_FOG, thickenFog); // Paper
this.createWorldFog = thickenFog;
return this;
}
public boolean shouldCreateWorldFog() {
+ if (this.adventure != null) return this.adventure.hasFlag(net.kyori.adventure.bossbar.BossBar.Flag.CREATE_WORLD_FOG); // Paper
return this.createWorldFog;
}
2024-04-25 05:14:51 +02:00
diff --git a/src/main/java/net/minecraft/world/item/ItemStack.java b/src/main/java/net/minecraft/world/item/ItemStack.java
2024-08-09 22:05:50 +02:00
index 3457e1c9791b294b5e4dab478d90cdd1a1cf7fef..1138d238caa18171b6562cc748c92cec03bfbb97 100644
2024-04-25 05:14:51 +02:00
--- a/src/main/java/net/minecraft/world/item/ItemStack.java
+++ b/src/main/java/net/minecraft/world/item/ItemStack.java
2024-06-13 19:12:48 +02:00
@@ -183,7 +183,15 @@ public final class ItemStack implements DataComponentHolder {
2024-04-27 00:08:35 +02:00
CraftItemStack.setItemMeta(itemstack, CraftItemStack.getItemMeta(itemstack));
// Spigot end
ITEM_STREAM_CODEC.encode(registryfriendlybytebuf, itemstack.getItemHolder()); // CraftBukkit - decompile error
2024-04-25 05:14:51 +02:00
+ // Paper start - adventure; conditionally render translatable components
+ boolean prev = net.minecraft.network.chat.ComponentSerialization.DONT_RENDER_TRANSLATABLES.get();
+ try {
2024-04-27 00:08:35 +02:00
+ net.minecraft.network.chat.ComponentSerialization.DONT_RENDER_TRANSLATABLES.set(true);
DataComponentPatch.STREAM_CODEC.encode(registryfriendlybytebuf, itemstack.components.asPatch());
2024-04-25 05:14:51 +02:00
+ } finally {
+ net.minecraft.network.chat.ComponentSerialization.DONT_RENDER_TRANSLATABLES.set(prev);
+ }
+ // Paper end - adventure; conditionally render translatable components
2024-04-27 00:08:35 +02:00
}
}
};
2023-06-07 19:18:05 +02:00
diff --git a/src/main/java/net/minecraft/world/level/block/entity/SignBlockEntity.java b/src/main/java/net/minecraft/world/level/block/entity/SignBlockEntity.java
2024-04-23 20:32:19 +02:00
index 8ec376f453ac1f4c9423483f5ae1625b295858c7..e535fb3b5194b8412c0c26c0799340916c7542eb 100644
2023-06-07 19:18:05 +02:00
--- a/src/main/java/net/minecraft/world/level/block/entity/SignBlockEntity.java
+++ b/src/main/java/net/minecraft/world/level/block/entity/SignBlockEntity.java
2024-04-23 20:32:19 +02:00
@@ -210,22 +210,22 @@ public class SignBlockEntity extends BlockEntity implements CommandSource { // C
2023-06-07 20:03:53 +02:00
2023-06-08 15:25:35 +02:00
// CraftBukkit start
Player player = ((ServerPlayer) entityhuman).getBukkitEntity();
- String[] lines = new String[4];
+ List<net.kyori.adventure.text.Component> lines = new java.util.ArrayList<>(); // Paper - adventure
2023-06-07 20:03:53 +02:00
2023-06-16 12:28:31 +02:00
for (int i = 0; i < list.size(); ++i) {
- lines[i] = CraftChatMessage.fromComponent(signtext.getMessage(i, entityhuman.isTextFilteringEnabled()));
+ lines.add(io.papermc.paper.adventure.PaperAdventure.asAdventure(signtext.getMessage(i, entityhuman.isTextFilteringEnabled()))); // Paper - Adventure
2023-06-08 15:25:35 +02:00
}
2023-06-07 20:03:53 +02:00
2023-06-16 12:28:31 +02:00
- SignChangeEvent event = new SignChangeEvent(CraftBlock.at(this.level, this.worldPosition), player, lines.clone(), (front) ? Side.FRONT : Side.BACK);
+ SignChangeEvent event = new SignChangeEvent(CraftBlock.at(this.level, this.worldPosition), player, new java.util.ArrayList<>(lines), (front) ? Side.FRONT : Side.BACK); // Paper - Adventure
2023-06-08 15:25:35 +02:00
entityhuman.level().getCraftServer().getPluginManager().callEvent(event);
2023-06-16 12:28:31 +02:00
if (event.isCancelled()) {
return originalText;
}
- Component[] components = org.bukkit.craftbukkit.block.CraftSign.sanitizeLines(event.getLines());
+ Component[] components = org.bukkit.craftbukkit.block.CraftSign.sanitizeLines(event.lines()); // Paper - Adventure
for (int i = 0; i < components.length; i++) {
- if (!Objects.equals(lines[i], event.getLine(i))) {
+ if (!Objects.equals(lines.get(i), event.line(i))) { // Paper - Adventure
signtext = signtext.setMessage(i, components[i]);
2023-06-07 20:03:53 +02:00
}
2023-06-16 12:28:31 +02:00
}
2021-06-11 14:02:28 +02:00
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
2024-06-13 19:12:48 +02:00
index 6acee03278c8005a06d9cd2577761f2f5355a7ec..5e469bd4d9ca428abdd9d758993164635dc86f27 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java
+++ b/src/main/java/net/minecraft/world/level/saveddata/maps/MapItemSavedData.java
2024-04-23 20:32:19 +02:00
@@ -45,6 +45,7 @@ import net.minecraft.world.level.saveddata.SavedData;
2022-03-01 06:43:03 +01:00
import org.slf4j.Logger;
2021-06-11 14:02:28 +02:00
// CraftBukkit start
+import io.papermc.paper.adventure.PaperAdventure; // Paper
import java.util.UUID;
2021-06-11 21:23:46 +02:00
import org.bukkit.Bukkit;
2021-11-23 12:27:39 +01:00
import org.bukkit.craftbukkit.CraftServer;
2024-06-13 19:12:48 +02:00
@@ -615,7 +616,7 @@ public class MapItemSavedData extends SavedData {
2021-06-11 14:02:28 +02:00
2021-06-11 21:23:46 +02:00
for (org.bukkit.map.MapCursor cursor : render.cursors) {
if (cursor.isVisible()) {
2024-04-23 20:32:19 +02:00
- icons.add(new MapDecoration(CraftMapCursor.CraftType.bukkitToMinecraftHolder(cursor.getType()), cursor.getX(), cursor.getY(), cursor.getDirection(), CraftChatMessage.fromStringOrOptional(cursor.getCaption())));
+ icons.add(new MapDecoration(CraftMapCursor.CraftType.bukkitToMinecraftHolder(cursor.getType()), cursor.getX(), cursor.getY(), cursor.getDirection(), Optional.ofNullable(PaperAdventure.asVanilla(cursor.caption()))));
2021-06-11 21:23:46 +02:00
}
2021-06-11 14:02:28 +02:00
}
2021-06-11 21:23:46 +02:00
collection = icons;
2024-06-20 17:57:56 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java b/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java
index 49c037e961c5ca5ba8d6a870cb32ffe8719adc91..2772c19f58a35713d61aab24f6f0d6f5070153c6 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftJukeboxSong.java
@@ -59,6 +59,7 @@ public class CraftJukeboxSong implements JukeboxSong, Handleable<net.minecraft.w
@NotNull
@Override
public String getTranslationKey() {
+ if (!(this.handle.description().getContents() instanceof TranslatableContents)) throw new UnsupportedOperationException("Description isn't translatable!"); // Paper
return ((TranslatableContents) this.handle.description().getContents()).getKey();
}
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
2024-08-10 12:24:38 +02:00
index 2ea3ad9ab43dec0555d6716bebefbc3bb6553f1a..be068650a568fc1d0d3b9c5acd040adafb2344e1 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
2024-07-18 10:13:20 +02:00
@@ -644,8 +644,10 @@ public final class CraftServer implements Server {
2021-06-11 14:02:28 +02:00
}
@Override
+ @Deprecated // Paper start
public int broadcastMessage(String message) {
2021-06-11 21:23:46 +02:00
return this.broadcast(message, BROADCAST_CHANNEL_USERS);
2021-06-11 14:02:28 +02:00
+ // Paper end
}
2021-06-20 21:25:59 +02:00
@Override
2024-07-18 10:13:20 +02:00
@@ -1621,7 +1623,15 @@ public final class CraftServer implements Server {
2021-06-11 21:23:46 +02:00
return this.configuration.getInt("settings.spawn-radius", -1);
2021-06-11 14:02:28 +02:00
}
+ // Paper start
2023-03-23 22:57:03 +01:00
+ @Override
2021-06-11 14:02:28 +02:00
+ public net.kyori.adventure.text.Component shutdownMessage() {
+ String msg = getShutdownMessage();
2022-05-26 21:12:14 +02:00
+ return msg != null ? net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(msg) : null;
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
2023-03-23 22:57:03 +01:00
@Override
2021-06-11 14:02:28 +02:00
+ @Deprecated // Paper
public String getShutdownMessage() {
2021-06-11 21:23:46 +02:00
return this.configuration.getString("settings.shutdown-message");
2021-06-11 14:02:28 +02:00
}
2024-07-18 10:13:20 +02:00
@@ -1795,7 +1805,20 @@ public final class CraftServer implements Server {
2021-06-11 14:02:28 +02:00
}
@Override
+ @Deprecated // Paper
public int broadcast(String message, String permission) {
+ // Paper start - Adventure
2022-05-26 21:12:14 +02:00
+ return this.broadcast(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(message), permission);
2021-06-11 14:02:28 +02:00
+ }
+
+ @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<CommandSender> recipients = new HashSet<>();
2021-06-11 21:23:46 +02:00
for (Permissible permissible : this.getPluginManager().getPermissionSubscriptions(permission)) {
2021-06-11 14:02:28 +02:00
if (permissible instanceof CommandSender && permissible.hasPermission(permission)) {
2024-07-18 10:13:20 +02:00
@@ -1803,14 +1826,14 @@ public final class CraftServer implements Server {
2021-06-11 14:02:28 +02:00
}
}
- BroadcastMessageEvent broadcastMessageEvent = new BroadcastMessageEvent(!Bukkit.isPrimaryThread(), message, recipients);
+ BroadcastMessageEvent broadcastMessageEvent = new BroadcastMessageEvent(!Bukkit.isPrimaryThread(), message, recipients); // Paper - Adventure
2021-06-11 21:23:46 +02:00
this.getPluginManager().callEvent(broadcastMessageEvent);
2021-06-11 14:02:28 +02:00
if (broadcastMessageEvent.isCancelled()) {
return 0;
}
- message = broadcastMessageEvent.getMessage();
+ message = broadcastMessageEvent.message(); // Paper - Adventure
for (CommandSender recipient : recipients) {
recipient.sendMessage(message);
2024-07-18 10:13:20 +02:00
@@ -2072,6 +2095,14 @@ public final class CraftServer implements Server {
2021-06-11 14:02:28 +02:00
return CraftInventoryCreator.INSTANCE.createInventory(owner, type);
}
+ // Paper start
+ @Override
+ public Inventory createInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) {
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(type.isCreatable(), "Cannot open an inventory of type ", type);
2021-06-11 14:02:28 +02:00
+ return CraftInventoryCreator.INSTANCE.createInventory(owner, type, title);
+ }
+ // Paper end
+
@Override
public Inventory createInventory(InventoryHolder owner, InventoryType type, String title) {
2023-06-13 01:51:45 +02:00
Preconditions.checkArgument(type != null, "InventoryType cannot be null");
2024-07-18 10:13:20 +02:00
@@ -2086,13 +2117,28 @@ public final class CraftServer implements Server {
2021-06-11 14:02:28 +02:00
return CraftInventoryCreator.INSTANCE.createInventory(owner, size);
}
+ // Paper start
+ @Override
+ public Inventory createInventory(InventoryHolder owner, int size, net.kyori.adventure.text.Component title) throws IllegalArgumentException {
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got " + size + ")");
2021-06-11 14:02:28 +02:00
+ return CraftInventoryCreator.INSTANCE.createInventory(owner, size, title);
+ }
+ // Paper end
+
@Override
public Inventory createInventory(InventoryHolder owner, int size, String title) throws IllegalArgumentException {
2023-06-13 01:51:45 +02:00
Preconditions.checkArgument(9 <= size && size <= 54 && size % 9 == 0, "Size for custom inventory must be a multiple of 9 between 9 and 54 slots (got %s)", size);
2021-06-11 14:02:28 +02:00
return CraftInventoryCreator.INSTANCE.createInventory(owner, size, title);
}
+ // Paper start
2023-03-23 22:57:03 +01:00
+ @Override
2021-06-11 14:02:28 +02:00
+ public Merchant createMerchant(net.kyori.adventure.text.Component title) {
+ return new org.bukkit.craftbukkit.inventory.CraftMerchantCustom(title == null ? InventoryType.MERCHANT.defaultTitle() : title);
+ }
+ // Paper end
2023-03-23 22:57:03 +01:00
@Override
2021-06-11 14:02:28 +02:00
+ @Deprecated // Paper
public Merchant createMerchant(String title) {
return new CraftMerchantCustom(title == null ? InventoryType.MERCHANT.getDefaultTitle() : title);
}
2024-07-18 10:13:20 +02:00
@@ -2157,6 +2203,17 @@ public final class CraftServer implements Server {
2023-10-27 01:34:58 +02:00
return Thread.currentThread().equals(this.console.serverThread) || this.console.hasStopped() || !org.spigotmc.AsyncCatcher.enabled; // All bets are off if we have shut down (e.g. due to watchdog)
2021-06-11 14:02:28 +02:00
}
2023-06-13 01:51:45 +02:00
+ // Paper start - Adventure
2021-06-11 14:02:28 +02:00
+ @Override
+ public net.kyori.adventure.text.Component motd() {
2023-06-13 01:51:45 +02:00
+ return this.console.motd();
+ }
+ @Override
+ public void motd(final net.kyori.adventure.text.Component motd) {
+ this.console.motd(motd);
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
2023-06-13 01:51:45 +02:00
+
2021-06-11 14:02:28 +02:00
@Override
public String getMotd() {
2021-06-11 21:23:46 +02:00
return this.console.getMotd();
2024-07-18 10:13:20 +02:00
@@ -2606,4 +2663,57 @@ public final class CraftServer implements Server {
2024-01-24 22:13:08 +01:00
public double[] getTPS() {
return new double[]{0, 0, 0}; // TODO
2021-06-11 14:02:28 +02:00
}
+
2023-05-31 03:36:16 +02:00
+ // Paper start - adventure sounds
+ @Override
+ public void playSound(final net.kyori.adventure.sound.Sound sound) {
2023-12-26 21:00:21 +01:00
+ if (sound.seed().isEmpty()) org.spigotmc.AsyncCatcher.catchOp("play sound; cannot generate seed with world random"); // Paper
2023-05-31 03:36:16 +02:00
+ final long seed = sound.seed().orElseGet(this.console.overworld().getRandom()::nextLong);
+ for (ServerPlayer player : this.playerList.getPlayers()) {
+ player.connection.send(io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, player.getX(), player.getY(), player.getZ(), seed, null));
+ }
+ }
+
+ @Override
+ public void playSound(final net.kyori.adventure.sound.Sound sound, final double x, final double y, final double z) {
2023-12-26 21:00:21 +01:00
+ org.spigotmc.AsyncCatcher.catchOp("play sound"); // Paper
2023-05-31 03:36:16 +02:00
+ io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, x, y, z, sound.seed().orElseGet(this.console.overworld().getRandom()::nextLong), this.playSound0(x, y, z, this.console.getAllLevels()));
+ }
+
+ @Override
+ public void playSound(final net.kyori.adventure.sound.Sound sound, final net.kyori.adventure.sound.Sound.Emitter emitter) {
2023-12-26 21:00:21 +01:00
+ if (sound.seed().isEmpty()) org.spigotmc.AsyncCatcher.catchOp("play sound; cannot generate seed with world random"); // Paper
2023-05-31 03:36:16 +02:00
+ final long seed = sound.seed().orElseGet(this.console.overworld().getRandom()::nextLong);
+ if (emitter == net.kyori.adventure.sound.Sound.Emitter.self()) {
+ for (ServerPlayer player : this.playerList.getPlayers()) {
+ player.connection.send(io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, player, seed, null));
+ }
+ } else if (emitter instanceof org.bukkit.craftbukkit.entity.CraftEntity craftEntity) {
2023-12-26 21:00:21 +01:00
+ org.spigotmc.AsyncCatcher.catchOp("play sound; cannot use entity emitter"); // Paper
2023-05-31 03:36:16 +02:00
+ final net.minecraft.world.entity.Entity entity = craftEntity.getHandle();
2023-06-08 00:12:41 +02:00
+ io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, entity, seed, this.playSound0(entity.getX(), entity.getY(), entity.getZ(), List.of((ServerLevel) entity.level())));
2023-05-31 03:36:16 +02:00
+ } else {
+ throw new IllegalArgumentException("Sound emitter must be an Entity or self(), but was: " + emitter);
+ }
+ }
+
+ private java.util.function.BiConsumer<net.minecraft.network.protocol.Packet<?>, Float> playSound0(final double x, final double y, final double z, final Iterable<ServerLevel> levels) {
+ return (packet, distance) -> {
+ for (final ServerLevel level : levels) {
+ level.getServer().getPlayerList().broadcast(null, x, y, z, distance, level.dimension(), packet);
+ }
+ };
+ }
+ // Paper end
+
2021-06-11 14:02:28 +02:00
+ // Paper start
+ private Iterable<? extends net.kyori.adventure.audience.Audience> adventure$audiences;
+ @Override
+ public Iterable<? extends net.kyori.adventure.audience.Audience> 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;
+ }
2022-06-09 10:51:45 +02:00
+ // Paper end
2021-06-11 14:02:28 +02:00
}
2024-06-16 13:54:38 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServerLinks.java b/src/main/java/org/bukkit/craftbukkit/CraftServerLinks.java
index cbdb1a56a97150c164515a4ce6d3ba06428bf321..b214e7b302abbfe1641485a05f1371ac65ffb517 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServerLinks.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServerLinks.java
@@ -61,6 +61,19 @@ public class CraftServerLinks implements ServerLinks {
return link;
}
+ // Paper start - Adventure
+ @Override
+ public ServerLink addLink(net.kyori.adventure.text.Component displayName, URI url) {
+ Preconditions.checkArgument(displayName != null, "displayName cannot be null");
+ Preconditions.checkArgument(url != null, "url cannot be null");
+
+ CraftServerLink link = new CraftServerLink(net.minecraft.server.ServerLinks.Entry.custom(io.papermc.paper.adventure.PaperAdventure.asVanilla(displayName), url));
+ this.addLink(link);
+
+ return link;
+ }
+ // Paper end - Adventure
+
@Override
public ServerLink addLink(String displayName, URI url) {
Preconditions.checkArgument(displayName != null, "displayName cannot be null");
@@ -134,6 +147,13 @@ public class CraftServerLinks implements ServerLinks {
return CraftChatMessage.fromComponent(this.handle.displayName());
}
+ // Paper start - Adventure
+ @Override
+ public net.kyori.adventure.text.Component displayName() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.handle.displayName());
+ }
+ // Paper end - Adventure
+
@Override
public URI getUrl() {
return this.handle.link();
2021-09-23 23:07:44 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
2024-07-17 19:24:53 +02:00
index 69c62699e3412f2730e3db65f196099d77698980..4878a1b085a83dd4a8ffdc86250b8fb4fbac5192 100644
2021-09-23 23:07:44 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftWorld.java
2024-04-06 21:53:39 +02:00
@@ -162,6 +162,7 @@ public class CraftWorld extends CraftRegionAccessor implements World {
2022-02-12 14:20:33 +01:00
private final BlockMetadataStore blockMetadata = new BlockMetadataStore(this);
private final Object2IntOpenHashMap<SpawnCategory> spawnCategoryLimit = new Object2IntOpenHashMap<>();
2022-02-15 11:30:58 +01:00
private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(CraftWorld.DATA_TYPE_REGISTRY);
2021-09-23 23:07:44 +02:00
+ private net.kyori.adventure.pointer.Pointers adventure$pointers; // Paper - implement pointers
private static final Random rand = new Random();
2024-06-13 16:45:27 +02:00
@@ -1709,6 +1710,42 @@ public class CraftWorld extends CraftRegionAccessor implements World {
2023-05-31 03:36:16 +02:00
entityTracker.broadcastAndSend(packet);
}
}
+ // Paper start - Adventure
+ @Override
+ public void playSound(final net.kyori.adventure.sound.Sound sound) {
2023-12-26 21:00:21 +01:00
+ org.spigotmc.AsyncCatcher.catchOp("play sound"); // Paper
2023-05-31 03:36:16 +02:00
+ final long seed = sound.seed().orElseGet(this.world.getRandom()::nextLong);
+ for (ServerPlayer player : this.getHandle().players()) {
+ player.connection.send(io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, player.getX(), player.getY(), player.getZ(), seed, null));
+ }
+ }
+
+ @Override
+ public void playSound(final net.kyori.adventure.sound.Sound sound, final double x, final double y, final double z) {
2023-12-26 21:00:21 +01:00
+ org.spigotmc.AsyncCatcher.catchOp("play sound"); // Paper
2023-05-31 03:36:16 +02:00
+ io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, x, y, z, sound.seed().orElseGet(this.world.getRandom()::nextLong), this.playSound0(x, y, z));
+ }
+
+ @Override
+ public void playSound(final net.kyori.adventure.sound.Sound sound, final net.kyori.adventure.sound.Sound.Emitter emitter) {
2023-12-26 21:00:21 +01:00
+ org.spigotmc.AsyncCatcher.catchOp("play sound"); // Paper
2023-05-31 03:36:16 +02:00
+ final long seed = sound.seed().orElseGet(this.getHandle().getRandom()::nextLong);
+ if (emitter == net.kyori.adventure.sound.Sound.Emitter.self()) {
+ for (ServerPlayer player : this.getHandle().players()) {
+ player.connection.send(io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, player, seed, null));
+ }
+ } else if (emitter instanceof CraftEntity craftEntity) {
+ final net.minecraft.world.entity.Entity entity = craftEntity.getHandle();
+ io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, entity, seed, this.playSound0(entity.getX(), entity.getY(), entity.getZ()));
+ } else {
+ throw new IllegalArgumentException("Sound emitter must be an Entity or self(), but was: " + emitter);
+ }
+ }
+
+ private java.util.function.BiConsumer<net.minecraft.network.protocol.Packet<?>, Float> playSound0(final double x, final double y, final double z) {
+ return (packet, distance) -> this.world.getServer().getPlayerList().broadcast(null, x, y, z, distance, this.world.dimension(), packet);
+ }
+ // Paper end
private static Map<String, GameRules.Key<?>> gamerules;
public static synchronized Map<String, GameRules.Key<?>> getGameRulesNMS() {
2024-06-13 16:45:27 +02:00
@@ -2150,5 +2187,18 @@ public class CraftWorld extends CraftRegionAccessor implements World {
2024-01-24 22:13:08 +01:00
public void setSendViewDistance(final int viewDistance) {
throw new UnsupportedOperationException("Not implemented yet");
2021-09-23 23:07:44 +02:00
}
+
+ // Paper start - implement pointers
+ @Override
+ public net.kyori.adventure.pointer.Pointers pointers() {
+ if (this.adventure$pointers == null) {
+ this.adventure$pointers = net.kyori.adventure.pointer.Pointers.builder()
+ .withDynamic(net.kyori.adventure.identity.Identity.NAME, this::getName)
+ .withDynamic(net.kyori.adventure.identity.Identity.UUID, this::getUID)
+ .build();
+ }
+
+ return this.adventure$pointers;
+ }
2022-09-01 18:51:59 +02:00
// Paper end
2021-09-23 23:07:44 +02:00
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/Main.java b/src/main/java/org/bukkit/craftbukkit/Main.java
2024-08-09 22:05:50 +02:00
index 42a1a0588e2b506082499ac9791d039089a64631..9c1fab8db74757e1fb57d4f47099ba6e1536cd6d 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/Main.java
+++ b/src/main/java/org/bukkit/craftbukkit/Main.java
2023-03-14 19:05:23 +01:00
@@ -20,6 +20,12 @@ public class Main {
2021-12-10 15:24:07 +01:00
public static boolean useConsole = true;
2021-12-09 21:59:59 +01:00
2021-12-10 15:24:07 +01:00
public static void main(String[] args) {
2021-06-11 14:02:28 +02:00
+ // 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
2024-04-23 20:32:19 +02:00
index 9ef8b0327e377817faaf58b82a8fdfa5e801eac8..2dfbe061a064b0c79b96f644a1c3639bb900eca4 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java
+++ b/src/main/java/org/bukkit/craftbukkit/block/CraftBeacon.java
2024-04-23 20:32:19 +02:00
@@ -72,6 +72,19 @@ public class CraftBeacon extends CraftBlockEntityState<BeaconBlockEntity> implem
this.getSnapshot().secondaryPower = (effect != null) ? CraftPotionEffectType.bukkitToMinecraftHolder(effect) : null;
2021-06-11 14:02:28 +02:00
}
+ // 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();
2021-09-30 23:28:02 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java b/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java
2024-04-26 04:54:07 +02:00
index f9b89a7c6ac9f7fdbd29567a5b6550398dbc7345..f5b0bec4c1164fe7ef6da1f19a6ce9bb3d6864d0 100644
2021-09-30 23:28:02 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java
+++ b/src/main/java/org/bukkit/craftbukkit/block/CraftCommandBlock.java
2024-04-23 20:32:19 +02:00
@@ -45,4 +45,16 @@ public class CraftCommandBlock extends CraftBlockEntityState<CommandBlockEntity>
public CraftCommandBlock copy(Location location) {
return new CraftCommandBlock(this, location);
2021-09-30 23:28:02 +02:00
}
+
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component name() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(getSnapshot().getCommandBlock().getName());
+ }
+
+ @Override
+ public void name(net.kyori.adventure.text.Component name) {
2024-04-26 04:54:07 +02:00
+ getSnapshot().getCommandBlock().setCustomName(name == null ? net.minecraft.network.chat.Component.literal("@") : io.papermc.paper.adventure.PaperAdventure.asVanilla(name));
2021-09-30 23:28:02 +02:00
+ }
+ // Paper end
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java
2024-04-26 03:51:28 +02:00
index 007b6d66dd837ca6352c0fba5c2399139f6b5425..513402b61e6b8388b7bc163d98e54ffae0e18254 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java
+++ b/src/main/java/org/bukkit/craftbukkit/block/CraftContainer.java
2024-04-23 20:32:19 +02:00
@@ -32,6 +32,19 @@ public abstract class CraftContainer<T extends BaseContainerBlockEntity> extends
2021-06-11 14:02:28 +02:00
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) {
2024-04-26 03:51:28 +02:00
+ this.getSnapshot().name = (customName != null ? io.papermc.paper.adventure.PaperAdventure.asVanilla(customName) : null);
2021-06-11 14:02:28 +02:00
+ }
+ // 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
2024-04-26 03:51:28 +02:00
index 690dd79b82108322a290c00de63b1f038f617c84..a01691f98a378a818b8bf12176c7270e15c316d8 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java
+++ b/src/main/java/org/bukkit/craftbukkit/block/CraftEnchantingTable.java
2024-04-23 20:32:19 +02:00
@@ -16,6 +16,19 @@ public class CraftEnchantingTable extends CraftBlockEntityState<EnchantingTableB
super(state, location);
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component customName() {
2024-04-26 03:51:28 +02:00
+ final EnchantingTableBlockEntity be = this.getSnapshot();
2021-06-11 14:02:28 +02:00
+ 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() {
2024-04-23 20:32:19 +02:00
EnchantingTableBlockEntity enchant = this.getSnapshot();
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java b/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java
2024-04-23 20:32:19 +02:00
index 0641d17d8095e7700c651e90472ae53d6f7dbbb2..a12702cdf36c75572e661b5b5758270f5058c181 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java
+++ b/src/main/java/org/bukkit/craftbukkit/block/CraftSign.java
2024-04-23 20:32:19 +02:00
@@ -36,6 +36,23 @@ public class CraftSign<T extends SignBlockEntity> extends CraftBlockEntityState<
2023-06-07 19:18:05 +02:00
this.back = new CraftSignSide(this.getSnapshot().getBackText());
2023-06-01 01:36:57 +02:00
}
+ // Paper start
+ @Override
+ public java.util.@NotNull List<net.kyori.adventure.text.Component> lines() {
+ return this.front.lines();
+ }
+
+ @Override
+ public net.kyori.adventure.text.@NotNull Component line(int index) {
+ return this.front.line(index);
+ }
+
+ @Override
+ public void line(int index, net.kyori.adventure.text.@NotNull Component line) {
+ this.front.line(index, line);
+ }
+ // Paper end
+
@Override
public String[] getLines() {
return this.front.getLines();
2024-04-23 20:32:19 +02:00
@@ -161,6 +178,20 @@ public class CraftSign<T extends SignBlockEntity> extends CraftBlockEntityState<
2023-06-08 15:25:35 +02:00
((CraftPlayer) player).getHandle().openTextEdit(handle, Side.FRONT == side);
2023-06-01 01:36:57 +02:00
}
+ // Paper start
+ public static Component[] sanitizeLines(java.util.List<? extends net.kyori.adventure.text.Component> 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] = net.minecraft.network.chat.Component.literal("");
+ }
+ }
+ return components;
+ }
+ // Paper end
+
public static Component[] sanitizeLines(String[] lines) {
Component[] components = new Component[4];
diff --git a/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java b/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java
2023-10-27 01:34:58 +02:00
index d4724c812f8b7322ad59dc0695d01ceb47772dc4..4747d77fd5fd12116ef40d897a08c7baca60a399 100644
2023-06-01 01:36:57 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java
+++ b/src/main/java/org/bukkit/craftbukkit/block/sign/CraftSignSide.java
2023-09-16 23:18:51 +02:00
@@ -12,37 +12,70 @@ import org.jetbrains.annotations.Nullable;
2023-06-01 01:36:57 +02:00
public class CraftSignSide implements SignSide {
2021-06-11 14:02:28 +02:00
// Lazily initialized only if requested:
- private String[] originalLines = null;
- private String[] lines = null;
+ // Paper start
+ private java.util.ArrayList<net.kyori.adventure.text.Component> originalLines = null; // ArrayList for RandomAccess
+ private java.util.ArrayList<net.kyori.adventure.text.Component> lines = null; // ArrayList for RandomAccess
+ // Paper end
2023-06-08 15:25:35 +02:00
private SignText signText;
2021-06-11 14:02:28 +02:00
2023-06-07 19:18:05 +02:00
public CraftSignSide(SignText signText) {
2023-06-01 01:36:57 +02:00
this.signText = signText;
2021-06-11 14:02:28 +02:00
}
+ // Paper start
2023-06-01 01:36:57 +02:00
+ @Override
+ public java.util.@NotNull List<net.kyori.adventure.text.Component> lines() {
2021-06-11 14:02:28 +02:00
+ this.loadLines();
2023-06-01 01:36:57 +02:00
+ return this.lines;
+ }
+
2021-06-11 14:02:28 +02:00
+ @Override
2023-06-01 01:36:57 +02:00
+ public net.kyori.adventure.text.@NotNull Component line(final int index) throws IndexOutOfBoundsException {
2021-06-11 14:02:28 +02:00
+ this.loadLines();
+ return this.lines.get(index);
+ }
+
+ @Override
2023-06-01 01:36:57 +02:00
+ public void line(final int index, final net.kyori.adventure.text.@NotNull Component line) throws IndexOutOfBoundsException {
2023-09-16 23:18:51 +02:00
+ com.google.common.base.Preconditions.checkArgument(line != null, "Line cannot be null");
2021-06-11 14:02:28 +02:00
+ this.loadLines();
+ this.lines.set(index, line);
+ }
+
+ private void loadLines() {
2023-06-01 01:36:57 +02:00
+ if (this.lines != null) {
2021-06-11 14:02:28 +02:00
+ return;
2021-06-11 21:23:46 +02:00
+ }
2021-06-11 14:02:28 +02:00
+ // Lazy initialization:
2023-06-07 19:18:05 +02:00
+ this.lines = io.papermc.paper.adventure.PaperAdventure.asAdventure(com.google.common.collect.Lists.newArrayList(this.signText.getMessages(false)));
2023-06-01 01:36:57 +02:00
+ this.originalLines = new java.util.ArrayList<>(this.lines);
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
2023-06-01 01:36:57 +02:00
+
@NotNull
@Override
public String[] getLines() {
- if (this.lines == null) {
- // Lazy initialization:
2023-06-07 19:18:05 +02:00
- Component[] messages = this.signText.getMessages(false);
- this.lines = new String[messages.length];
2023-10-27 01:34:58 +02:00
- System.arraycopy(CraftSign.revertComponents(messages), 0, this.lines, 0, this.lines.length);
- this.originalLines = new String[this.lines.length];
- System.arraycopy(this.lines, 0, this.originalLines, 0, this.originalLines.length);
2023-06-01 01:36:57 +02:00
- }
- return this.lines;
+ // Paper start
2021-06-11 14:02:28 +02:00
+ this.loadLines();
2022-05-26 21:12:14 +02:00
+ return this.lines.stream().map(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection()::serialize).toArray(String[]::new); // Paper
2023-06-01 01:36:57 +02:00
+ // Paper end
}
@NotNull
2021-06-11 14:02:28 +02:00
@Override
public String getLine(int index) throws IndexOutOfBoundsException {
2021-06-11 21:23:46 +02:00
- return this.getLines()[index];
2023-06-01 01:36:57 +02:00
+ // Paper start
2021-06-11 14:02:28 +02:00
+ this.loadLines();
2023-06-01 01:36:57 +02:00
+ return net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(this.lines.get(index));
+ // Paper end
2021-06-11 14:02:28 +02:00
}
@Override
2023-06-01 01:36:57 +02:00
public void setLine(int index, @NotNull String line) throws IndexOutOfBoundsException {
2021-06-11 21:23:46 +02:00
- this.getLines()[index] = line;
2023-06-01 01:36:57 +02:00
+ // Paper start
2021-06-11 14:02:28 +02:00
+ this.loadLines();
2023-06-01 01:36:57 +02:00
+ this.lines.set(index, line != null ? net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(line) : net.kyori.adventure.text.Component.empty());
+ // Paper end
2021-06-11 14:02:28 +02:00
}
@Override
2023-09-16 23:18:51 +02:00
@@ -68,13 +101,16 @@ public class CraftSignSide implements SignSide {
2021-06-11 14:02:28 +02:00
2023-06-08 15:25:35 +02:00
public SignText applyLegacyStringToSignSide() {
2021-06-11 21:23:46 +02:00
if (this.lines != null) {
2023-10-27 01:34:58 +02:00
- for (int i = 0; i < this.lines.length; i++) {
2021-06-11 21:23:46 +02:00
- String line = (this.lines[i] == null) ? "" : this.lines[i];
- if (line.equals(this.originalLines[i])) {
2021-06-11 14:02:28 +02:00
+ // 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.
}
2023-06-08 15:25:35 +02:00
- this.signText = this.signText.setMessage(i, CraftChatMessage.fromString(line)[0]);
+ this.signText = this.signText.setMessage(i, io.papermc.paper.adventure.PaperAdventure.asVanilla(component));
2021-06-11 14:02:28 +02:00
}
+ // Paper end
}
2023-06-08 15:25:35 +02:00
return this.signText;
2021-09-22 20:34:40 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java
2023-12-25 23:51:56 +01:00
index f2e8b63d787754c0a92441dcc9eb39dffdc1e280..9feae61fe02cbc624581ef0bd4c60af636407367 100644
2021-09-22 20:34:40 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java
+++ b/src/main/java/org/bukkit/craftbukkit/command/CraftBlockCommandSender.java
2023-12-25 23:51:56 +01:00
@@ -61,6 +61,18 @@ public class CraftBlockCommandSender extends ServerCommandSender implements Bloc
2021-09-22 20:34:40 +02:00
return this.block.getTextName();
}
+ // Paper start
+ @Override
2022-06-17 00:03:02 +02:00
+ public void sendMessage(net.kyori.adventure.identity.Identity identity, net.kyori.adventure.text.Component message, net.kyori.adventure.audience.MessageType type) {
+ block.source.sendSystemMessage(io.papermc.paper.adventure.PaperAdventure.asVanilla(message));
+ }
+
+ @Override
2021-09-22 20:34:40 +02:00
+ public net.kyori.adventure.text.Component name() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.block.getDisplayName());
+ }
+ // Paper end
+
@Override
public boolean isOp() {
2023-12-25 23:51:56 +01:00
return CraftBlockCommandSender.SHARED_PERM.isOp();
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java
2022-05-26 21:12:14 +02:00
index f3cb4102ab223f379f60dac317df7da1fab812a8..324e6d1a4fadd3e557e4ba05f04e6a5891cc54df 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java
+++ b/src/main/java/org/bukkit/craftbukkit/command/CraftConsoleCommandSender.java
2021-09-22 20:34:40 +02:00
@@ -46,6 +46,13 @@ public class CraftConsoleCommandSender extends ServerCommandSender implements Co
return "CONSOLE";
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component name() {
+ return net.kyori.adventure.text.Component.text(this.getName());
+ }
+ // Paper end
+
@Override
public boolean isOp() {
return true;
@@ -80,4 +87,11 @@ public class CraftConsoleCommandSender extends ServerCommandSender implements Co
2021-06-11 14:02:28 +02:00
public boolean isConversing() {
2021-06-11 21:23:46 +02:00
return this.conversationTracker.isConversing();
2021-06-11 14:02:28 +02:00
}
+
+ // 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) {
2022-05-26 21:12:14 +02:00
+ this.sendRawMessage(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(message));
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
}
2021-09-22 20:34:40 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java
2023-10-27 01:34:58 +02:00
index e3c7fa50fad3077a297d2412de9d26d53371808c..5b7d230103f421fb939072e1526854f715430e51 100644
2021-09-22 20:34:40 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java
+++ b/src/main/java/org/bukkit/craftbukkit/command/CraftRemoteConsoleCommandSender.java
2023-08-28 13:05:48 +02:00
@@ -39,6 +39,13 @@ public class CraftRemoteConsoleCommandSender extends ServerCommandSender impleme
2021-09-22 20:34:40 +02:00
return "Rcon";
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component name() {
+ return net.kyori.adventure.text.Component.text(this.getName());
+ }
+ // Paper end
+
@Override
public boolean isOp() {
return true;
diff --git a/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java
index 53d6950ad270ba901de5226b9daecb683248ad05..3e7d14564f11a3ed0b0766444e9d681804597e9a 100644
--- a/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java
+++ b/src/main/java/org/bukkit/craftbukkit/command/ProxiedNativeCommandSender.java
@@ -67,6 +67,13 @@ public class ProxiedNativeCommandSender implements ProxiedCommandSender {
return this.getCallee().getName();
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component name() {
+ return this.getCallee().name();
+ }
+ // Paper end
+
@Override
public boolean isPermissionSet(String name) {
return this.getCaller().isPermissionSet(name);
2021-09-23 23:07:44 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java b/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java
2023-12-25 23:51:56 +01:00
index 1e82312c24cb752d63b165926861fc178cd7849b..7f22950ae61436e91a59cd29a345809c42bbe739 100644
2021-09-23 23:07:44 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java
+++ b/src/main/java/org/bukkit/craftbukkit/command/ServerCommandSender.java
2023-12-25 23:51:56 +01:00
@@ -13,6 +13,7 @@ import org.bukkit.plugin.Plugin;
2021-09-23 23:07:44 +02:00
public abstract class ServerCommandSender implements CommandSender {
private final PermissibleBase perm;
+ private net.kyori.adventure.pointer.Pointers adventure$pointers; // Paper - implement pointers
2023-12-25 23:51:56 +01:00
protected ServerCommandSender() {
this.perm = new PermissibleBase(this);
@@ -130,4 +131,18 @@ public abstract class ServerCommandSender implements CommandSender {
2021-09-23 23:07:44 +02:00
return this.spigot;
}
// Spigot end
+
+ // Paper start - implement pointers
+ @Override
+ public net.kyori.adventure.pointer.Pointers pointers() {
+ if (this.adventure$pointers == null) {
+ this.adventure$pointers = net.kyori.adventure.pointer.Pointers.builder()
+ .withDynamic(net.kyori.adventure.identity.Identity.DISPLAY_NAME, this::name)
+ .withStatic(net.kyori.adventure.permission.PermissionChecker.POINTER, this::permissionValue)
+ .build();
+ }
+
+ return this.adventure$pointers;
+ }
+ // Paper end
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java b/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java
2024-07-06 21:19:14 +02:00
index 2d0c82ca240e371a756d71f28e2e04d1aa8e6ad2..f73017bff613bd62b86c974b29576e241c24c927 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java
+++ b/src/main/java/org/bukkit/craftbukkit/enchantments/CraftEnchantment.java
2024-07-06 21:19:14 +02:00
@@ -145,6 +145,12 @@ public class CraftEnchantment extends Enchantment implements Handleable<net.mine
2021-06-11 14:02:28 +02:00
CraftEnchantment ench = (CraftEnchantment) other;
2024-06-13 19:12:48 +02:00
return !net.minecraft.world.item.enchantment.Enchantment.areCompatible(this.handle, ench.handle);
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component displayName(int level) {
2021-06-17 21:37:37 +02:00
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(getHandle().getFullname(level));
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
2023-12-05 19:38:29 +01:00
@Override
2024-04-06 21:53:39 +02:00
public String getTranslationKey() {
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
2024-06-13 19:12:48 +02:00
index d09102fe44dffa61dff883488f47715effaa8211..269326e7689eba91bcfd3475006e8cbf8f5694ef 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftEntity.java
2024-06-13 19:12:48 +02:00
@@ -69,6 +69,7 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
2023-08-14 01:32:51 +02:00
private final EntityType entityType;
2021-09-23 23:07:44 +02:00
private EntityDamageEvent lastDamageEvent;
private final CraftPersistentDataContainer persistentDataContainer = new CraftPersistentDataContainer(CraftEntity.DATA_TYPE_REGISTRY);
+ protected net.kyori.adventure.pointer.Pointers adventure$pointers; // Paper - implement pointers
public CraftEntity(final CraftServer server, final Entity entity) {
this.server = server;
2024-06-13 19:12:48 +02:00
@@ -525,6 +526,32 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
2021-06-11 21:23:46 +02:00
return this.getHandle().getVehicle().getBukkitEntity();
2021-06-11 14:02:28 +02:00
}
+ // 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);
+ }
2021-09-23 23:07:44 +02:00
+
+ @Override
+ public net.kyori.adventure.pointer.Pointers pointers() {
+ if (this.adventure$pointers == null) {
+ this.adventure$pointers = net.kyori.adventure.pointer.Pointers.builder()
+ .withDynamic(net.kyori.adventure.identity.Identity.DISPLAY_NAME, this::name)
+ .withDynamic(net.kyori.adventure.identity.Identity.UUID, this::getUniqueId)
+ .withStatic(net.kyori.adventure.permission.PermissionChecker.POINTER, this::permissionValue)
+ .build();
+ }
+
+ return this.adventure$pointers;
+ }
2021-06-11 14:02:28 +02:00
+ // Paper end
+
@Override
public void setCustomName(String name) {
// sane limit for name length
2024-06-13 19:12:48 +02:00
@@ -621,6 +648,17 @@ public abstract class CraftEntity implements org.bukkit.entity.Entity {
2021-09-22 20:34:40 +02:00
public String getName() {
return CraftChatMessage.fromComponent(this.getHandle().getName());
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.@org.jetbrains.annotations.NotNull Component name() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.getHandle().getName());
+ }
+
+ @Override
+ public net.kyori.adventure.text.@org.jetbrains.annotations.NotNull Component teamDisplayName() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.getHandle().getDisplayName());
+ }
+ // Paper end
@Override
public boolean isPermissionSet(String name) {
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java
2024-07-06 21:19:14 +02:00
index 59107e11f29e2c6dd213966b3000c79eabdbd39b..0c94a1094a3af0232bb2957708fa997933db621b 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftHumanEntity.java
2024-04-23 20:32:19 +02:00
@@ -321,9 +321,12 @@ public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity {
2021-06-11 14:02:28 +02:00
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
2022-05-26 21:12:14 +02:00
+ if (adventure$title == null) adventure$title = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(container.getBukkitView().getTitle()); // Paper
2021-06-11 14:02:28 +02:00
- player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, CraftChatMessage.fromString(title)[0]));
2022-06-11 11:02:09 +02:00
+ //player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); // Paper - comment
2021-06-11 14:02:28 +02:00
+ player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, io.papermc.paper.adventure.PaperAdventure.asVanilla(adventure$title))); // Paper
2021-06-11 21:23:46 +02:00
player.containerMenu = container;
player.initMenu(container);
2021-06-11 14:02:28 +02:00
}
2024-07-06 21:19:14 +02:00
@@ -393,8 +396,12 @@ public class CraftHumanEntity extends CraftLivingEntity implements HumanEntity {
2021-06-11 14:02:28 +02:00
// 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
2022-05-26 21:12:14 +02:00
+ if (adventure$title == null) adventure$title = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(inventory.getTitle()); // Paper
2022-06-11 11:02:09 +02:00
+ //player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, CraftChatMessage.fromString(title)[0])); // Paper - comment
2021-06-11 14:02:28 +02:00
+ player.connection.send(new ClientboundOpenScreenPacket(container.containerId, windowType, io.papermc.paper.adventure.PaperAdventure.asVanilla(adventure$title))); // Paper
player.containerMenu = container;
2021-06-11 21:23:46 +02:00
player.initMenu(container);
2021-06-11 14:02:28 +02:00
}
2021-09-22 20:34:40 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java
2024-04-23 20:32:19 +02:00
index 55945b83a5426b352bad9507cc9e94afb1278032..9ea1537408ff2d790747b6e5a681d9171a4233ae 100644
2021-09-22 20:34:40 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftMinecartCommand.java
2023-08-14 01:32:51 +02:00
@@ -59,6 +59,13 @@ public class CraftMinecartCommand extends CraftMinecart implements CommandMineca
2021-09-22 20:34:40 +02:00
return CraftChatMessage.fromComponent(this.getHandle().getCommandBlock().getName());
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.@org.jetbrains.annotations.NotNull Component name() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.getHandle().getCommandBlock().getName());
+ }
+ // Paper end
+
@Override
public boolean isOp() {
return true;
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
2024-07-18 10:13:20 +02:00
index 9ca244b69995552df63fb5d4e3d6961b585bcc47..807184636a99c17fe6ed8dd1cd07e1872d613657 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftPlayer.java
2024-06-13 19:12:48 +02:00
@@ -388,14 +388,40 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2021-06-11 14:02:28 +02:00
@Override
public String getDisplayName() {
+ if(true) return io.papermc.paper.adventure.DisplayNames.getLegacy(this); // Paper
2021-06-11 21:23:46 +02:00
return this.getHandle().displayName;
2021-06-11 14:02:28 +02:00
}
@Override
public void setDisplayName(final String name) {
2022-05-26 21:12:14 +02:00
+ this.getHandle().adventure$displayName = name != null ? net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(name) : net.kyori.adventure.text.Component.text(this.getName()); // Paper
2023-10-27 01:34:58 +02:00
this.getHandle().displayName = name == null ? this.getName() : name;
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
+ public void playerListName(net.kyori.adventure.text.Component name) {
+ getHandle().listName = name == null ? null : io.papermc.paper.adventure.PaperAdventure.asVanilla(name);
2024-04-20 15:24:42 +02:00
+ if (getHandle().connection == null) return; // Updates are possible before the player has fully joined
2021-06-11 14:02:28 +02:00
+ for (ServerPlayer player : server.getHandle().players) {
+ if (player.getBukkitEntity().canSee(this)) {
2022-12-07 22:36:56 +01:00
+ player.connection.send(new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, getHandle()));
2021-06-11 14:02:28 +02:00
+ }
+ }
+ }
+ @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() {
2023-10-27 01:34:58 +02:00
return this.getHandle().listName == null ? this.getName() : CraftChatMessage.fromComponent(this.getHandle().listName);
2024-06-13 19:12:48 +02:00
@@ -407,6 +433,7 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2024-04-20 15:24:42 +02:00
name = this.getName();
}
this.getHandle().listName = name.equals(this.getName()) ? null : CraftChatMessage.fromStringOrNull(name);
+ if (this.getHandle().connection == null) return; // Paper - Updates are possible before the player has fully joined
for (ServerPlayer player : (List<ServerPlayer>) this.server.getHandle().players) {
if (player.getBukkitEntity().canSee(this)) {
player.connection.send(new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_DISPLAY_NAME, this.getHandle()));
2024-06-13 19:12:48 +02:00
@@ -414,42 +441,42 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2021-06-11 14:02:28 +02:00
}
}
- 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() {
2023-10-27 01:34:58 +02:00
- return (this.playerListHeader == null) ? null : CraftChatMessage.fromComponent(this.playerListHeader);
+ return (this.playerListHeader == null) ? null : net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(this.playerListHeader);
2021-06-11 14:02:28 +02:00
}
@Override
public String getPlayerListFooter() {
2023-10-27 01:34:58 +02:00
- return (this.playerListFooter == null) ? null : CraftChatMessage.fromComponent(this.playerListFooter);
+ return (this.playerListFooter == null) ? null : net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(this.playerListFooter); // Paper - Adventure
2021-06-11 14:02:28 +02:00
}
@Override
public void setPlayerListHeader(String header) {
- this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true);
2022-05-26 21:12:14 +02:00
+ this.playerListHeader = header == null ? null : net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(header); // Paper - Adventure
2021-06-11 21:23:46 +02:00
this.updatePlayerListHeaderFooter();
2021-06-11 14:02:28 +02:00
}
@Override
public void setPlayerListFooter(String footer) {
- this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true);
2022-05-26 21:12:14 +02:00
+ this.playerListFooter = footer == null ? null : net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(footer); // Paper - Adventure
2021-06-11 21:23:46 +02:00
this.updatePlayerListHeaderFooter();
2021-06-11 14:02:28 +02:00
}
@Override
public void setPlayerListHeaderFooter(String header, String footer) {
- this.playerListHeader = CraftChatMessage.fromStringOrNull(header, true);
- this.playerListFooter = CraftChatMessage.fromStringOrNull(footer, true);
2022-05-26 21:12:14 +02:00
+ this.playerListHeader = header == null ? null : net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(header); // Paper - Adventure
+ this.playerListFooter = footer == null ? null : net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(footer); // Paper - Adventure
2021-06-11 21:23:46 +02:00
this.updatePlayerListHeaderFooter();
2021-06-11 14:02:28 +02:00
}
2021-06-11 21:23:46 +02:00
private void updatePlayerListHeaderFooter() {
if (this.getHandle().connection == null) return;
2021-06-11 14:02:28 +02:00
2022-06-07 20:12:34 +02:00
- ClientboundTabListPacket packet = new ClientboundTabListPacket((this.playerListHeader == null) ? Component.empty() : this.playerListHeader, (this.playerListFooter == null) ? Component.empty() : this.playerListFooter);
2024-04-26 01:24:08 +02:00
+ ClientboundTabListPacket packet = new ClientboundTabListPacket(io.papermc.paper.adventure.PaperAdventure.asVanillaNullToEmpty(this.playerListHeader), io.papermc.paper.adventure.PaperAdventure.asVanillaNullToEmpty(this.playerListFooter)); // Paper - adventure
2021-06-11 21:23:46 +02:00
this.getHandle().connection.send(packet);
2021-06-11 14:02:28 +02:00
}
2024-06-13 19:12:48 +02:00
@@ -481,6 +508,23 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2024-07-06 21:19:14 +02:00
this.getHandle().connection.disconnect(CraftChatMessage.fromStringOrEmpty(message, true));
2021-06-11 14:02:28 +02:00
}
+ // Paper start
2022-06-01 08:20:12 +02:00
+ private static final net.kyori.adventure.text.Component DEFAULT_KICK_COMPONENT = net.kyori.adventure.text.Component.translatable("multiplayer.disconnect.kicked");
+ @Override
+ public void kick() {
+ this.kick(DEFAULT_KICK_COMPONENT);
+ }
+
2021-06-11 14:02:28 +02:00
+ @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) {
2023-06-13 01:51:45 +02:00
Preconditions.checkArgument(loc != null, "Location cannot be null");
2024-06-13 19:12:48 +02:00
@@ -777,6 +821,24 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2021-06-11 21:23:46 +02:00
this.getHandle().connection.send(packet);
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
2023-03-20 09:18:06 +01:00
+ public void sendSignChange(Location loc, @Nullable List<? extends net.kyori.adventure.text.Component> lines, DyeColor dyeColor, boolean hasGlowingText) {
2021-06-11 14:02:28 +02:00
+ if (getHandle().connection == null) {
+ return;
+ }
+ if (lines == null) {
+ lines = new java.util.ArrayList<>(4);
+ }
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(loc != null, "Location cannot be null");
+ Preconditions.checkArgument(dyeColor != null, "DyeColor cannot be null");
2021-06-11 14:02:28 +02:00
+ if (lines.size() < 4) {
+ throw new IllegalArgumentException("Must have at least 4 lines");
+ }
+ Component[] components = CraftSign.sanitizeLines(lines);
2021-08-05 21:53:50 +02:00
+ this.sendSignChange0(components, loc, dyeColor, hasGlowingText);
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
@Override
public void sendSignChange(Location loc, String[] lines) {
2021-08-05 21:53:50 +02:00
this.sendSignChange(loc, lines, DyeColor.BLACK);
2024-06-13 19:12:48 +02:00
@@ -800,6 +862,12 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2023-06-13 01:51:45 +02:00
if (this.getHandle().connection == null) return;
2021-06-11 14:02:28 +02:00
Component[] components = CraftSign.sanitizeLines(lines);
2023-05-12 13:10:08 +02:00
+ // Paper start - adventure
+ this.sendSignChange0(components, loc, dyeColor, hasGlowingText);
+ }
+
+ private void sendSignChange0(Component[] components, Location loc, DyeColor dyeColor, boolean hasGlowingText) {
2024-04-25 23:21:18 +02:00
+ // Paper end
2023-05-12 13:10:08 +02:00
SignBlockEntity sign = new SignBlockEntity(CraftLocation.toBlockPosition(loc), Blocks.OAK_SIGN.defaultBlockState());
2023-06-07 19:18:05 +02:00
SignText text = sign.getFrontText();
2024-04-25 23:21:18 +02:00
text = text.setColor(net.minecraft.world.item.DyeColor.byId(dyeColor.getWoolData()));
2024-07-06 21:19:14 +02:00
@@ -1816,7 +1884,7 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2021-12-22 08:07:17 +01:00
@Override
public void setResourcePack(String url) {
- this.setResourcePack(url, null);
+ this.setResourcePack(url, (byte[]) null);
}
@Override
2024-07-06 21:19:14 +02:00
@@ -1831,7 +1899,7 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2021-12-22 08:07:17 +01:00
@Override
public void setResourcePack(String url, byte[] hash, boolean force) {
- this.setResourcePack(url, hash, null, force);
+ this.setResourcePack(url, hash, (String) null, force);
}
@Override
2024-07-06 21:19:14 +02:00
@@ -1868,6 +1936,59 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2024-04-23 20:32:19 +02:00
this.handlePushResourcePack(new ClientboundResourcePackPushPacket(id, url, hashStr, force, CraftChatMessage.fromStringOrOptional(prompt, true)), false);
2021-12-22 08:07:17 +01:00
}
2023-12-09 00:13:02 +01:00
+ // Paper start - adventure
2021-12-22 08:07:17 +01:00
+ @Override
2023-12-09 00:13:02 +01:00
+ public void setResourcePack(final UUID uuid, final String url, final byte[] hashBytes, final net.kyori.adventure.text.Component prompt, final boolean force) {
+ Preconditions.checkArgument(uuid != null, "Resource pack UUID cannot be null");
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(url != null, "Resource pack URL cannot be null");
2021-12-22 08:07:17 +01:00
+ final String hash;
+ if (hashBytes != null) {
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(hashBytes.length == 20, "Resource pack hash should be 20 bytes long but was " + hashBytes.length);
2021-12-22 08:07:17 +01:00
+ hash = BaseEncoding.base16().lowerCase().encode(hashBytes);
+ } else {
+ hash = "";
+ }
Updated Upstream (Bukkit/CraftBukkit) (#10034)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
f29cb801 Separate checkstyle-suppressions file is not required
86f99bbe SPIGOT-7540, PR-946: Add ServerTickManager API
d4119585 SPIGOT-6903, PR-945: Add BlockData#getMapColor
b7a2ed41 SPIGOT-7530, PR-947: Add Player#removeResourcePack
9dd56255 SPIGOT-7527, PR-944: Add WindCharge#explode()
994a6163 Attempt upgrade of resolver libraries
CraftBukkit Changes:
b3b43a6ad Add Checkstyle check for unused imports
13fb3358e SPIGOT-7544: Scoreboard#getEntries() doesn't get entries but class names
3dda99c06 SPIGOT-7540, PR-1312: Add ServerTickManager API
2ab4508c0 SPIGOT-6903, PR-1311: Add BlockData#getMapColor
1dbdbbed4 PR-1238: Remove unnecessary sign ticking
659728d2a MC-264285, SPIGOT-7439, PR-1237: Fix unbreakable flint and steel is completely consumed while igniting creeper
e37e29ce0 Increase outdated build delay
c00438b39 SPIGOT-7530, PR-1313: Add Player#removeResourcePack
492dd80ce SPIGOT-7527, PR-1310: Add WindCharge#explode()
e11fbb9d7 Upgrade MySQL driver
9f3a0bd2a Attempt upgrade of resolver libraries
60d16d7ca PR-1306: Centralize Bukkit and Minecraft entity conversion
Spigot Changes:
06d602e7 Rebuild patches
2023-12-17 03:09:28 +01:00
+ this.getHandle().connection.send(new ClientboundResourcePackPopPacket(Optional.empty()));
2024-04-25 07:29:18 +02:00
+ this.getHandle().connection.send(new ClientboundResourcePackPushPacket(uuid, url, hash, force, Optional.ofNullable(prompt).map(io.papermc.paper.adventure.PaperAdventure::asVanilla)));
2021-12-22 08:07:17 +01:00
+ }
2023-12-25 11:51:44 +01:00
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ void sendBundle(final List<? extends net.minecraft.network.protocol.Packet<? extends net.minecraft.network.protocol.common.ClientCommonPacketListener>> packet) {
+ this.getHandle().connection.send(new net.minecraft.network.protocol.game.ClientboundBundlePacket((List) packet));
+ }
+
+ @Override
+ public void sendResourcePacks(final net.kyori.adventure.resource.ResourcePackRequest request) {
+ if (this.getHandle().connection == null) return;
+ final List<ClientboundResourcePackPushPacket> packs = new java.util.ArrayList<>(request.packs().size());
+ if (request.replace()) {
+ this.clearResourcePacks();
+ }
+ final Component prompt = io.papermc.paper.adventure.PaperAdventure.asVanilla(request.prompt());
+ for (final java.util.Iterator<net.kyori.adventure.resource.ResourcePackInfo> iter = request.packs().iterator(); iter.hasNext();) {
+ final net.kyori.adventure.resource.ResourcePackInfo pack = iter.next();
2024-05-17 23:22:45 +02:00
+ packs.add(new ClientboundResourcePackPushPacket(pack.id(), pack.uri().toASCIIString(), pack.hash(), request.required(), iter.hasNext() ? Optional.empty() : Optional.ofNullable(prompt)));
2023-12-25 11:51:44 +01:00
+ if (request.callback() != net.kyori.adventure.resource.ResourcePackCallback.noOp()) {
+ this.getHandle().connection.packCallbacks.put(pack.id(), request.callback()); // just override if there is a previously existing callback
+ }
+ }
+ this.sendBundle(packs);
+ super.sendResourcePacks(request);
+ }
+
+ @Override
+ public void removeResourcePacks(final UUID id, final UUID ... others) {
+ if (this.getHandle().connection == null) return;
+ this.sendBundle(net.kyori.adventure.util.MonkeyBars.nonEmptyArrayToList(pack -> new ClientboundResourcePackPopPacket(Optional.of(pack)), id, others));
+ }
+
+ @Override
+ public void clearResourcePacks() {
+ if (this.getHandle().connection == null) return;
+ this.getHandle().connection.send(new ClientboundResourcePackPopPacket(Optional.empty()));
+ }
2023-12-09 00:13:02 +01:00
+ // Paper end - adventure
2021-12-22 08:07:17 +01:00
+
Updated Upstream (Bukkit/CraftBukkit) (#10034)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
f29cb801 Separate checkstyle-suppressions file is not required
86f99bbe SPIGOT-7540, PR-946: Add ServerTickManager API
d4119585 SPIGOT-6903, PR-945: Add BlockData#getMapColor
b7a2ed41 SPIGOT-7530, PR-947: Add Player#removeResourcePack
9dd56255 SPIGOT-7527, PR-944: Add WindCharge#explode()
994a6163 Attempt upgrade of resolver libraries
CraftBukkit Changes:
b3b43a6ad Add Checkstyle check for unused imports
13fb3358e SPIGOT-7544: Scoreboard#getEntries() doesn't get entries but class names
3dda99c06 SPIGOT-7540, PR-1312: Add ServerTickManager API
2ab4508c0 SPIGOT-6903, PR-1311: Add BlockData#getMapColor
1dbdbbed4 PR-1238: Remove unnecessary sign ticking
659728d2a MC-264285, SPIGOT-7439, PR-1237: Fix unbreakable flint and steel is completely consumed while igniting creeper
e37e29ce0 Increase outdated build delay
c00438b39 SPIGOT-7530, PR-1313: Add Player#removeResourcePack
492dd80ce SPIGOT-7527, PR-1310: Add WindCharge#explode()
e11fbb9d7 Upgrade MySQL driver
9f3a0bd2a Attempt upgrade of resolver libraries
60d16d7ca PR-1306: Centralize Bukkit and Minecraft entity conversion
Spigot Changes:
06d602e7 Rebuild patches
2023-12-17 03:09:28 +01:00
@Override
public void removeResourcePack(UUID id) {
Preconditions.checkArgument(id != null, "Resource pack id cannot be null");
2024-07-06 21:19:14 +02:00
@@ -2288,6 +2409,12 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2023-09-21 21:00:11 +02:00
return (this.getHandle().requestedViewDistance() == 0) ? Bukkit.getViewDistance() : this.getHandle().requestedViewDistance();
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
+ public java.util.Locale locale() {
+ return getHandle().adventure$locale;
+ }
+ // Paper end
@Override
public int getPing() {
2023-09-21 21:00:11 +02:00
return this.getHandle().connection.latency();
2024-07-06 21:19:14 +02:00
@@ -2338,6 +2465,248 @@ public class CraftPlayer extends CraftHumanEntity implements Player {
2021-11-23 12:27:39 +01:00
return this.getHandle().allowsListing();
2021-06-11 14:02:28 +02:00
}
+ // 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
2022-12-09 10:11:28 +01:00
+ public void deleteMessage(net.kyori.adventure.chat.SignedMessage.Signature signature) {
+ if (getHandle().connection == null) return;
+ net.minecraft.network.chat.MessageSignature sig = new net.minecraft.network.chat.MessageSignature(signature.bytes());
+
+ this.getHandle().connection.send(new net.minecraft.network.protocol.game.ClientboundDeleteChatPacket(new net.minecraft.network.chat.MessageSignature.Packed(sig)));
+ }
+
+ private net.minecraft.network.chat.ChatType.Bound toHandle(net.kyori.adventure.chat.ChatType.Bound boundChatType) {
2023-06-08 00:12:41 +02:00
+ net.minecraft.core.Registry<net.minecraft.network.chat.ChatType> chatTypeRegistry = this.getHandle().level().registryAccess().registryOrThrow(net.minecraft.core.registries.Registries.CHAT_TYPE);
2022-12-09 10:11:28 +01:00
+
+ return new net.minecraft.network.chat.ChatType.Bound(
2024-04-26 03:51:28 +02:00
+ chatTypeRegistry.getHolderOrThrow(net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.CHAT_TYPE, io.papermc.paper.adventure.PaperAdventure.asVanilla(boundChatType.type().key()))),
2022-12-09 10:11:28 +01:00
+ io.papermc.paper.adventure.PaperAdventure.asVanilla(boundChatType.name()),
2024-04-26 03:51:28 +02:00
+ Optional.ofNullable(io.papermc.paper.adventure.PaperAdventure.asVanilla(boundChatType.target()))
2022-12-09 10:11:28 +01:00
+ );
+ }
+
+ @Override
+ public void sendMessage(net.kyori.adventure.text.Component message, net.kyori.adventure.chat.ChatType.Bound boundChatType) {
+ if (getHandle().connection == null) return;
+
+ net.minecraft.network.chat.Component component = io.papermc.paper.adventure.PaperAdventure.asVanilla(message);
+ this.getHandle().sendChatMessage(new net.minecraft.network.chat.OutgoingChatMessage.Disguised(component), this.getHandle().isTextFilteringEnabled(), this.toHandle(boundChatType));
+ }
+
+ @Override
+ public void sendMessage(net.kyori.adventure.chat.SignedMessage signedMessage, net.kyori.adventure.chat.ChatType.Bound boundChatType) {
+ if (getHandle().connection == null) return;
+
2022-12-17 07:05:48 +01:00
+ if (signedMessage instanceof PlayerChatMessage.AdventureView view) {
+ this.getHandle().sendChatMessage(net.minecraft.network.chat.OutgoingChatMessage.create(view.playerChatMessage()), this.getHandle().isTextFilteringEnabled(), this.toHandle(boundChatType));
+ return;
+ }
2022-12-09 10:11:28 +01:00
+ net.kyori.adventure.text.Component message = signedMessage.unsignedContent() == null ? net.kyori.adventure.text.Component.text(signedMessage.message()) : signedMessage.unsignedContent();
+ if (signedMessage.isSystem()) {
+ this.sendMessage(message, boundChatType);
+ } else {
+ super.sendMessage(signedMessage, boundChatType);
+ }
+// net.minecraft.network.chat.PlayerChatMessage playerChatMessage = new net.minecraft.network.chat.PlayerChatMessage(
+// null, // TODO:
+// new net.minecraft.network.chat.MessageSignature(signedMessage.signature().bytes()),
+// null, // TODO
+// io.papermc.paper.adventure.PaperAdventure.asVanilla(signedMessage.unsignedContent()),
+// net.minecraft.network.chat.FilterMask.PASS_THROUGH
+// );
+//
+// this.getHandle().sendChatMessage(net.minecraft.network.chat.OutgoingChatMessage.create(playerChatMessage), this.getHandle().isTextFilteringEnabled(), this.toHandle(boundChatType));
+ }
+
+ @Deprecated(forRemoval = true)
+ @Override
2021-06-11 14:02:28 +02:00
+ public void sendMessage(final net.kyori.adventure.identity.Identity identity, final net.kyori.adventure.text.Component message, final net.kyori.adventure.audience.MessageType type) {
2021-06-29 23:21:42 +02:00
+ if (getHandle().connection == null) return;
2023-06-08 00:12:41 +02:00
+ final net.minecraft.core.Registry<net.minecraft.network.chat.ChatType> chatTypeRegistry = this.getHandle().level().registryAccess().registryOrThrow(net.minecraft.core.registries.Registries.CHAT_TYPE);
2022-07-28 00:38:37 +02:00
+ this.getHandle().connection.send(new net.minecraft.network.protocol.game.ClientboundSystemChatPacket(message, false));
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public void sendActionBar(final net.kyori.adventure.text.Component message) {
2024-04-26 03:51:28 +02:00
+ final net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket packet = new net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket(io.papermc.paper.adventure.PaperAdventure.asVanillaNullToEmpty(message));
2021-06-11 14:02:28 +02:00
+ 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;
2024-04-25 07:29:18 +02:00
+ final ClientboundTabListPacket packet = new ClientboundTabListPacket(
2024-04-26 01:24:08 +02:00
+ io.papermc.paper.adventure.PaperAdventure.asVanillaNullToEmpty(this.playerListHeader),
+ io.papermc.paper.adventure.PaperAdventure.asVanillaNullToEmpty(this.playerListFooter)
2024-04-25 07:29:18 +02:00
+ );
2021-06-11 14:02:28 +02:00
+ 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) {
2021-06-11 21:23:46 +02:00
+ connection.send(new ClientboundSetTitlesAnimationPacket(ticks(times.fadeIn()), ticks(times.stay()), ticks(times.fadeOut())));
2021-06-11 14:02:28 +02:00
+ }
2024-04-25 07:29:18 +02:00
+ final ClientboundSetSubtitleTextPacket sp = new ClientboundSetSubtitleTextPacket(io.papermc.paper.adventure.PaperAdventure.asVanilla(title.subtitle()));
2021-06-11 14:02:28 +02:00
+ connection.send(sp);
2024-04-25 07:29:18 +02:00
+ final ClientboundSetTitleTextPacket tp = new ClientboundSetTitleTextPacket(io.papermc.paper.adventure.PaperAdventure.asVanilla(title.title()));
2021-06-11 14:02:28 +02:00
+ connection.send(tp);
+ }
+
2021-09-23 23:07:44 +02:00
+ @Override
+ public <T> void sendTitlePart(final net.kyori.adventure.title.TitlePart<T> part, T value) {
+ java.util.Objects.requireNonNull(part, "part");
+ java.util.Objects.requireNonNull(value, "value");
+ if (part == net.kyori.adventure.title.TitlePart.TITLE) {
2024-04-25 07:29:18 +02:00
+ final ClientboundSetTitleTextPacket tp = new ClientboundSetTitleTextPacket(io.papermc.paper.adventure.PaperAdventure.asVanilla((net.kyori.adventure.text.Component)value));
2021-09-23 23:07:44 +02:00
+ this.getHandle().connection.send(tp);
+ } else if (part == net.kyori.adventure.title.TitlePart.SUBTITLE) {
2024-04-25 07:29:18 +02:00
+ final ClientboundSetSubtitleTextPacket sp = new ClientboundSetSubtitleTextPacket(io.papermc.paper.adventure.PaperAdventure.asVanilla((net.kyori.adventure.text.Component)value));
2021-09-23 23:07:44 +02:00
+ this.getHandle().connection.send(sp);
+ } else if (part == net.kyori.adventure.title.TitlePart.TIMES) {
+ final net.kyori.adventure.title.Title.Times times = (net.kyori.adventure.title.Title.Times) value;
+ this.getHandle().connection.send(new ClientboundSetTitlesAnimationPacket(ticks(times.fadeIn()), ticks(times.stay()), ticks(times.fadeOut())));
+ } else {
+ throw new IllegalArgumentException("Unknown TitlePart");
+ }
+ }
+
2021-06-11 14:02:28 +02:00
+ private static int ticks(final java.time.Duration duration) {
+ if (duration == null) {
+ return -1;
+ }
+ return (int) (duration.toMillis() / 50L);
+ }
+
+ @Override
+ public void clearTitle() {
2021-06-11 21:23:46 +02:00
+ this.getHandle().connection.send(new net.minecraft.network.protocol.game.ClientboundClearTitlesPacket(false));
2021-06-11 14:02:28 +02:00
+ }
+
+ // resetTitle implemented above
+
2023-06-12 23:43:39 +02:00
+ private @Nullable Set<net.kyori.adventure.bossbar.BossBar> activeBossBars;
+
+ @Override
+ public @NotNull Iterable<? extends net.kyori.adventure.bossbar.BossBar> activeBossBars() {
+ if (this.activeBossBars != null) {
+ return java.util.Collections.unmodifiableSet(this.activeBossBars);
+ }
+ return Set.of();
+ }
+
2021-06-11 14:02:28 +02:00
+ @Override
+ public void showBossBar(final net.kyori.adventure.bossbar.BossBar bar) {
2023-06-12 23:43:39 +02:00
+ net.kyori.adventure.bossbar.BossBarImplementation.get(bar, io.papermc.paper.adventure.BossBarImplementationImpl.class).playerShow(this);
+ if (this.activeBossBars == null) {
+ this.activeBossBars = new HashSet<>();
+ }
+ this.activeBossBars.add(bar);
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public void hideBossBar(final net.kyori.adventure.bossbar.BossBar bar) {
2023-06-12 23:43:39 +02:00
+ net.kyori.adventure.bossbar.BossBarImplementation.get(bar, io.papermc.paper.adventure.BossBarImplementationImpl.class).playerHide(this);
+ if (this.activeBossBars != null) {
+ this.activeBossBars.remove(bar);
+ if (this.activeBossBars.isEmpty()) {
+ this.activeBossBars = null;
+ }
+ }
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public void playSound(final net.kyori.adventure.sound.Sound sound) {
2024-06-14 14:11:52 +02:00
+ final net.minecraft.world.phys.Vec3 pos = this.getHandle().position();
2021-06-11 14:02:28 +02:00
+ 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) {
2023-05-31 03:36:16 +02:00
+ this.getHandle().connection.send(io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, x, y, z, sound.seed().orElseGet(this.getHandle().getRandom()::nextLong), null));
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
2021-06-17 00:57:49 +02:00
+ public void playSound(final net.kyori.adventure.sound.Sound sound, final net.kyori.adventure.sound.Sound.Emitter emitter) {
+ final Entity entity;
+ if (emitter == net.kyori.adventure.sound.Sound.Emitter.self()) {
+ entity = this.getHandle();
2023-05-31 03:36:16 +02:00
+ } else if (emitter instanceof CraftEntity craftEntity) {
+ entity = craftEntity.getHandle();
2021-06-17 00:57:49 +02:00
+ } else {
+ throw new IllegalArgumentException("Sound emitter must be an Entity or self(), but was: " + emitter);
+ }
2023-05-31 03:36:16 +02:00
+ this.getHandle().connection.send(io.papermc.paper.adventure.PaperAdventure.asSoundPacket(sound, entity, sound.seed().orElseGet(this.getHandle().getRandom()::nextLong), null));
2021-06-17 00:57:49 +02:00
+ }
+
+ @Override
2021-06-11 14:02:28 +02:00
+ 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;
2021-06-11 21:23:46 +02:00
+ final net.minecraft.world.entity.player.Inventory inventory = player.getInventory();
2021-06-11 14:02:28 +02:00
+ final int slot = inventory.items.size() + inventory.selected;
2021-07-07 08:52:40 +02:00
+ final int stateId = getHandle().containerMenu.getStateId();
+ connection.send(new net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket(0, stateId, slot, item));
2021-06-11 14:02:28 +02:00
+ connection.send(new net.minecraft.network.protocol.game.ClientboundOpenBookPacket(net.minecraft.world.InteractionHand.MAIN_HAND));
2021-07-07 08:52:40 +02:00
+ connection.send(new net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket(0, stateId, slot, inventory.getSelected()));
2021-06-11 14:02:28 +02:00
+ }
2021-09-23 23:07:44 +02:00
+
+ @Override
+ public net.kyori.adventure.pointer.Pointers pointers() {
+ if (this.adventure$pointers == null) {
+ this.adventure$pointers = net.kyori.adventure.pointer.Pointers.builder()
+ .withDynamic(net.kyori.adventure.identity.Identity.DISPLAY_NAME, this::displayName)
+ .withDynamic(net.kyori.adventure.identity.Identity.NAME, this::getName)
+ .withDynamic(net.kyori.adventure.identity.Identity.UUID, this::getUniqueId)
+ .withStatic(net.kyori.adventure.permission.PermissionChecker.POINTER, this::permissionValue)
+ .withDynamic(net.kyori.adventure.identity.Identity.LOCALE, this::locale)
+ .build();
+ }
+
+ return this.adventure$pointers;
+ }
2021-06-11 14:02:28 +02:00
+ // Paper end
// Spigot start
private final Player.Spigot spigot = new Player.Spigot()
{
2023-03-15 00:52:28 +01:00
diff --git a/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java b/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java
2023-08-14 01:32:51 +02:00
index 5725b0281ac53a2354b233223259d6784353bc6e..9ef939b76d06874b856e0c850addb364146f5a00 100644
2023-03-15 00:52:28 +01:00
--- a/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java
+++ b/src/main/java/org/bukkit/craftbukkit/entity/CraftTextDisplay.java
2023-08-14 01:32:51 +02:00
@@ -32,6 +32,17 @@ public class CraftTextDisplay extends CraftDisplay implements TextDisplay {
2023-03-15 00:52:28 +01:00
public void setText(String text) {
this.getHandle().setText(CraftChatMessage.fromString(text, true)[0]);
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component text() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.getHandle().getText());
+ }
+
+ @Override
+ public void text(net.kyori.adventure.text.Component text) {
+ this.getHandle().setText(text == null ? net.minecraft.network.chat.Component.empty() : io.papermc.paper.adventure.PaperAdventure.asVanilla(text));
+ }
+ // Paper end
@Override
public int getLineWidth() {
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java b/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java
2024-08-09 22:05:50 +02:00
index 938a7ee49a727d5929d1d049c61d2881cf24ff9c..78f4bb474c85e32448a385e108707d92082bfe02 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java
+++ b/src/main/java/org/bukkit/craftbukkit/event/CraftEventFactory.java
2024-08-09 22:05:50 +02:00
@@ -915,7 +915,7 @@ public class CraftEventFactory {
2021-06-11 14:02:28 +02:00
return event;
}
2024-05-11 23:48:37 +02:00
- public static PlayerDeathEvent callPlayerDeathEvent(ServerPlayer victim, DamageSource damageSource, List<org.bukkit.inventory.ItemStack> drops, String deathMessage, boolean keepInventory) {
+ public static PlayerDeathEvent callPlayerDeathEvent(ServerPlayer victim, DamageSource damageSource, List<org.bukkit.inventory.ItemStack> drops, net.kyori.adventure.text.Component deathMessage, boolean keepInventory) { // Paper - Adventure
2021-06-11 14:02:28 +02:00
CraftPlayer entity = victim.getBukkitEntity();
2024-05-11 23:48:37 +02:00
CraftDamageSource bukkitDamageSource = new CraftDamageSource(damageSource);
2024-06-13 19:12:48 +02:00
PlayerDeathEvent event = new PlayerDeathEvent(entity, bukkitDamageSource, drops, victim.getExpReward(damageSource.getEntity()), 0, deathMessage);
2024-08-09 22:05:50 +02:00
@@ -948,7 +948,7 @@ public class CraftEventFactory {
2021-06-11 14:02:28 +02:00
* Server methods
*/
2023-09-21 21:00:11 +02:00
public static ServerListPingEvent callServerListPingEvent(SocketAddress address, String motd, int numPlayers, int maxPlayers) {
- ServerListPingEvent event = new ServerListPingEvent("", ((InetSocketAddress) address).getAddress(), motd, numPlayers, maxPlayers);
+ ServerListPingEvent event = new ServerListPingEvent("", ((InetSocketAddress) address).getAddress(), Bukkit.getServer().motd(), numPlayers, maxPlayers);
Bukkit.getServer().getPluginManager().callEvent(event);
2021-06-11 14:02:28 +02:00
return event;
}
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java
2024-06-16 17:21:14 +02:00
index 42c888af154a133e118a9ff9fef587e345c13e19..867091ff253541ec45b6ae7f1fb3acc83a5c4966 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftContainer.java
2024-06-15 18:28:18 +02:00
@@ -72,6 +72,13 @@ public class CraftContainer extends AbstractContainerMenu {
2021-06-11 14:02:28 +02:00
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() {
2023-10-27 01:34:58 +02:00
return this.title;
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryCustom.java
2023-06-13 01:51:45 +02:00
index c9cc23757a9fcc58d30b2915d4c5cfbc7d1c767a..fc0e1212022d1aa3506699b60ef338196eb54eba 100644
2021-06-11 14:02:28 +02:00
--- 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<HumanEntity> 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 {
2023-06-13 01:51:45 +02:00
Preconditions.checkArgument(title != null, "title cannot be null");
2021-06-11 21:23:46 +02:00
this.items = NonNullList.withSize(size, ItemStack.EMPTY);
2021-06-11 14:02:28 +02:00
this.title = title;
2022-05-26 21:12:14 +02:00
+ this.adventure$title = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(title);
2021-06-11 14:02:28 +02:00
this.viewers = new ArrayList<HumanEntity>();
this.owner = owner;
this.type = InventoryType.CHEST;
}
+ // Paper start
+ public MinecraftInventory(final InventoryHolder owner, final int size, final net.kyori.adventure.text.Component title) {
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(title != null, "Title cannot be null");
2021-06-12 00:37:16 +02:00
+ this.items = NonNullList.withSize(size, ItemStack.EMPTY);
2022-05-26 21:12:14 +02:00
+ this.title = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(title);
2021-06-11 14:02:28 +02:00
+ this.adventure$title = title;
+ this.viewers = new ArrayList<HumanEntity>();
+ this.owner = owner;
+ this.type = InventoryType.CHEST;
+ }
+ // Paper end
+
@Override
public int getContainerSize() {
2021-06-11 21:23:46 +02:00
return this.items.size();
2021-06-11 14:02:28 +02:00
@@ -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() {
2021-06-11 21:23:46 +02:00
return this.title;
2021-06-11 14:02:28 +02:00
}
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java
2024-08-09 22:05:50 +02:00
index 07d406de7123593dc470af2723f2a9a2dc2157b0..01fbd8a55866af3e371c8a2eef23ef6e9ca3226d 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftInventoryView.java
2024-08-09 22:05:50 +02:00
@@ -73,6 +73,13 @@ public class CraftInventoryView<T extends AbstractContainerMenu> extends CraftAb
2021-06-11 21:23:46 +02:00
return CraftItemStack.asCraftMirror(this.container.getSlot(slot).getItem());
2021-06-11 14:02:28 +02:00
}
+ // 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() {
2023-05-12 13:10:08 +02:00
return this.title;
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java
2024-06-15 18:28:18 +02:00
index 500bfe5dd745327f953a314e863f7318953bf3bc..e2daeeba1bacbb5c5ca2aa922fa67b02cd050755 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemFactory.java
2024-06-15 18:28:18 +02:00
@@ -206,4 +206,21 @@ public final class CraftItemFactory implements ItemFactory {
2024-06-13 19:12:48 +02:00
Optional<HolderSet.Named<Enchantment>> optional = (allowTreasures) ? Optional.empty() : registry.registryOrThrow(Registries.ENCHANTMENT).getTag(EnchantmentTags.IN_ENCHANTING_TABLE);
return CraftItemStack.asCraftMirror(EnchantmentHelper.enchantItem(source, craft.handle, level, registry, optional));
2021-06-11 14:02:28 +02:00
}
+
2023-08-06 02:21:59 +02:00
+ // Paper start - Adventure
2021-06-11 14:02:28 +02:00
+ @Override
+ public net.kyori.adventure.text.event.HoverEvent<net.kyori.adventure.text.event.HoverEvent.ShowItem> asHoverEvent(final ItemStack item, final java.util.function.UnaryOperator<net.kyori.adventure.text.event.HoverEvent.ShowItem> op) {
2024-04-26 01:24:08 +02:00
+ return net.kyori.adventure.text.event.HoverEvent.showItem(op.apply(
+ net.kyori.adventure.text.event.HoverEvent.ShowItem.showItem(
+ item.getType().getKey(),
+ item.getAmount(),
+ io.papermc.paper.adventure.PaperAdventure.asAdventure(CraftItemStack.unwrap(item).getComponentsPatch())) // unwrap is fine here because the components patch will be safely copied
+ ));
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public net.kyori.adventure.text.@org.jetbrains.annotations.NotNull Component displayName(@org.jetbrains.annotations.NotNull ItemStack itemStack) {
2021-06-16 19:48:25 +02:00
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(CraftItemStack.asNMSCopy(itemStack).getDisplayName());
2021-06-11 14:02:28 +02:00
+ }
2023-08-06 02:21:59 +02:00
+ // Paper end - Adventure
2021-06-11 14:02:28 +02:00
}
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java
2023-06-13 01:51:45 +02:00
index 9e05a8515c5f6f340182e91150fcad8bbf80a22b..adf22ce4f0bcd3bd57dc2030c6c92d3df96566e3 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMerchantCustom.java
2022-07-25 18:44:24 +02:00
@@ -13,10 +13,17 @@ import org.bukkit.craftbukkit.util.CraftChatMessage;
2021-06-11 14:02:28 +02:00
public class CraftMerchantCustom extends CraftMerchant {
+ @Deprecated // Paper - Adventure
public CraftMerchantCustom(String title) {
super(new MinecraftMerchant(title));
2021-06-11 21:23:46 +02:00
this.getMerchant().craftMerchant = this;
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ public CraftMerchantCustom(net.kyori.adventure.text.Component title) {
+ super(new MinecraftMerchant(title));
+ getMerchant().craftMerchant = this;
+ }
+ // Paper end
@Override
public String toString() {
2022-07-25 18:44:24 +02:00
@@ -35,10 +42,17 @@ public class CraftMerchantCustom extends CraftMerchant {
private Player tradingPlayer;
2021-06-11 14:02:28 +02:00
protected CraftMerchant craftMerchant;
+ @Deprecated // Paper - Adventure
public MinecraftMerchant(String title) {
2023-06-13 01:51:45 +02:00
Preconditions.checkArgument(title != null, "Title cannot be null");
2022-07-25 18:44:24 +02:00
this.title = CraftChatMessage.fromString(title)[0];
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ public MinecraftMerchant(net.kyori.adventure.text.Component title) {
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(title != null, "Title cannot be null");
2021-06-11 14:02:28 +02:00
+ 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
2024-07-23 10:11:00 +02:00
index 3ab6b212001c2b92cac42c0ff97e59c3d08b3e49..32e5188442551b3e72e1d4826d836d622d0e438a 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBook.java
2023-06-13 01:51:45 +02:00
@@ -2,8 +2,9 @@ package org.bukkit.craftbukkit.inventory;
2021-06-11 14:02:28 +02:00
2023-06-13 01:51:45 +02:00
import com.google.common.base.Preconditions;
2021-06-11 14:02:28 +02:00
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;
2024-07-23 10:11:00 +02:00
@@ -170,6 +171,128 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBo
2024-04-23 20:32:19 +02:00
public void setGeneration(Generation generation) {
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component title() {
2024-04-26 02:46:17 +02:00
+ return null;
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public org.bukkit.inventory.meta.BookMeta title(net.kyori.adventure.text.Component title) {
+ return this;
+ }
+
+ @Override
+ public net.kyori.adventure.text.Component author() {
2024-04-26 02:46:17 +02:00
+ return null;
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public org.bukkit.inventory.meta.BookMeta author(net.kyori.adventure.text.Component author) {
+ return this;
+ }
+
+ @Override
+ public net.kyori.adventure.text.Component page(final int page) {
2024-07-23 10:11:00 +02:00
+ Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s/%s)", page, this.getPageCount());
2024-04-26 02:46:17 +02:00
+ return net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(this.pages.get(page - 1));
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public void page(final int page, net.kyori.adventure.text.Component data) {
2024-07-23 10:11:00 +02:00
+ Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s/%s)", page, this.getPageCount());
2021-06-11 14:02:28 +02:00
+ if (data == null) {
+ data = net.kyori.adventure.text.Component.empty();
+ }
2024-04-26 02:46:17 +02:00
+ this.pages.set(page - 1, net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(data));
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public List<net.kyori.adventure.text.Component> pages() {
+ if (this.pages == null) return ImmutableList.of();
2024-04-26 02:46:17 +02:00
+ return this.pages.stream().map(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection()::deserialize).collect(ImmutableList.toImmutableList());
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public BookMeta pages(List<net.kyori.adventure.text.Component> pages) {
+ if (this.pages != null) this.pages.clear();
+ for (net.kyori.adventure.text.Component page : pages) {
2024-04-26 02:46:17 +02:00
+ this.addPages(page);
2021-06-11 14:02:28 +02:00
+ }
+ return this;
+ }
+
+ @Override
+ public BookMeta pages(net.kyori.adventure.text.Component... pages) {
+ if (this.pages != null) this.pages.clear();
2024-04-26 02:46:17 +02:00
+ this.addPages(pages);
2021-06-11 14:02:28 +02:00
+ 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();
+ }
+
2024-04-26 02:46:17 +02:00
+ this.pages.add(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().serialize(page));
2021-06-11 14:02:28 +02:00
+ }
+ }
+
2024-04-26 02:46:17 +02:00
+ private CraftMetaBook(List<net.kyori.adventure.text.Component> pages) {
2021-06-11 14:02:28 +02:00
+ super((org.bukkit.craftbukkit.inventory.CraftMetaItem) org.bukkit.Bukkit.getItemFactory().getItemMeta(org.bukkit.Material.WRITABLE_BOOK));
2022-05-26 21:12:14 +02:00
+ this.pages = pages.subList(0, Math.min(MAX_PAGES, pages.size())).stream().map(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection()::serialize).collect(java.util.stream.Collectors.toList());
2021-06-11 14:02:28 +02:00
+ }
+
2021-08-09 00:57:20 +02:00
+ static class CraftMetaBookBuilder implements BookMetaBuilder {
2024-04-26 02:46:17 +02:00
+ protected final List<net.kyori.adventure.text.Component> pages = new java.util.ArrayList<>();
2021-06-11 14:02:28 +02:00
+
+ @Override
+ public BookMetaBuilder title(net.kyori.adventure.text.Component title) {
+ return this;
+ }
+
+ @Override
+ public BookMetaBuilder author(net.kyori.adventure.text.Component 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<net.kyori.adventure.text.Component> pages) {
+ this.pages.addAll(pages);
+ return this;
+ }
+
+ @Override
+ public BookMeta build() {
2024-04-26 02:46:17 +02:00
+ return new CraftMetaBook(this.pages);
2021-06-11 14:02:28 +02:00
+ }
+ }
+
+ @Override
+ public BookMetaBuilder toBuilder() {
+ return new CraftMetaBookBuilder();
+ }
+
+ // Paper end
@Override
public String getPage(final int page) {
2023-06-13 01:51:45 +02:00
Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s)", page);
2024-07-23 10:11:00 +02:00
@@ -286,7 +409,7 @@ public class CraftMetaBook extends CraftMetaItem implements BookMeta, WritableBo
2021-06-11 14:02:28 +02:00
}
@Override
- Builder<String, Object> serialize(Builder<String, Object> builder) {
+ ImmutableMap.Builder<String, Object> serialize(ImmutableMap.Builder<String, Object> builder) {
super.serialize(builder);
2024-04-23 20:32:19 +02:00
if (this.pages != null) {
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java
2024-07-23 10:11:00 +02:00
index c71a4971f127fdfc753306019313ce1a31201120..fd3b12477c30d1eabdbe57ea779027931e9dd957 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaBookSigned.java
2024-04-25 23:21:18 +02:00
@@ -346,7 +346,7 @@ public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta {
2021-06-11 14:02:28 +02:00
}
@Override
- Builder<String, Object> serialize(Builder<String, Object> builder) {
2024-07-06 21:19:14 +02:00
+ com.google.common.collect.ImmutableMap.Builder<String, Object> serialize(com.google.common.collect.ImmutableMap.Builder<String, Object> builder) { // Paper - adventure - fqn as it conflicts with adventure book builder
2021-06-11 14:02:28 +02:00
super.serialize(builder);
2024-04-23 20:32:19 +02:00
if (this.hasTitle()) {
2024-07-23 10:11:00 +02:00
@@ -459,4 +459,111 @@ public class CraftMetaBookSigned extends CraftMetaItem implements BookMeta {
2024-04-23 20:32:19 +02:00
return this.spigot;
2021-06-11 14:02:28 +02:00
}
2024-04-23 20:32:19 +02:00
// Spigot end
2021-08-09 00:57:20 +02:00
+
+ // Paper start - adventure
2024-04-26 02:46:17 +02:00
+ public static final net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer LEGACY_DOWNSAMPLING_COMPONENT_SERIALIZER = net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.builder()
+ .character(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.SECTION_CHAR)
+ .build();
2021-08-09 00:57:20 +02:00
+ private CraftMetaBookSigned(net.kyori.adventure.text.Component title, net.kyori.adventure.text.Component author, java.util.List<net.kyori.adventure.text.Component> pages) {
+ super((org.bukkit.craftbukkit.inventory.CraftMetaItem) org.bukkit.Bukkit.getItemFactory().getItemMeta(Material.WRITABLE_BOOK));
2024-04-26 02:46:17 +02:00
+ this.title = title == null ? null : LEGACY_DOWNSAMPLING_COMPONENT_SERIALIZER.serialize(title);
+ this.author = author == null ? null : LEGACY_DOWNSAMPLING_COMPONENT_SERIALIZER.serialize(author);
2024-04-23 20:32:19 +02:00
+ this.pages = io.papermc.paper.adventure.PaperAdventure.asVanilla(pages.subList(0, Math.min(MAX_PAGES, pages.size())));
2021-08-09 00:57:20 +02:00
+ }
+
2024-04-23 20:32:19 +02:00
+ static final class CraftMetaBookSignedBuilder extends CraftMetaBook.CraftMetaBookBuilder {
2024-04-26 02:46:17 +02:00
+ private net.kyori.adventure.text.Component title;
+ private net.kyori.adventure.text.Component author;
+
+ @Override
+ public org.bukkit.inventory.meta.BookMeta.BookMetaBuilder title(final net.kyori.adventure.text.Component title) {
+ this.title = title;
+ return this;
+ }
+
+ @Override
+ public org.bukkit.inventory.meta.BookMeta.BookMetaBuilder author(final net.kyori.adventure.text.Component author) {
+ this.author = author;
+ return this;
+ }
+
2021-08-09 00:57:20 +02:00
+ @Override
2024-04-26 02:46:17 +02:00
+ public org.bukkit.inventory.meta.BookMeta build() {
+ return new CraftMetaBookSigned(this.title, this.author, this.pages);
2021-08-09 00:57:20 +02:00
+ }
+ }
+
+ @Override
+ public BookMetaBuilder toBuilder() {
+ return new CraftMetaBookSignedBuilder();
+ }
2024-04-26 02:46:17 +02:00
+
+ @Override
+ public net.kyori.adventure.text.Component title() {
+ return this.title == null ? null : LEGACY_DOWNSAMPLING_COMPONENT_SERIALIZER.deserialize(this.title);
+ }
+
+ @Override
+ public org.bukkit.inventory.meta.BookMeta title(net.kyori.adventure.text.Component title) {
+ this.setTitle(title == null ? null : LEGACY_DOWNSAMPLING_COMPONENT_SERIALIZER.serialize(title));
+ return this;
+ }
+
+ @Override
+ public net.kyori.adventure.text.Component author() {
+ return this.author == null ? null : LEGACY_DOWNSAMPLING_COMPONENT_SERIALIZER.deserialize(this.author);
+ }
+
+ @Override
+ public org.bukkit.inventory.meta.BookMeta author(net.kyori.adventure.text.Component author) {
+ this.setAuthor(author == null ? null : LEGACY_DOWNSAMPLING_COMPONENT_SERIALIZER.serialize(author));
+ return this;
+ }
+
+ @Override
+ public net.kyori.adventure.text.Component page(final int page) {
2024-07-23 10:11:00 +02:00
+ Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s/%s)", page, this.getPageCount());
2024-04-26 02:46:17 +02:00
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.pages.get(page - 1));
+ }
+
+ @Override
+ public void page(final int page, net.kyori.adventure.text.Component data) {
2024-07-23 10:11:00 +02:00
+ Preconditions.checkArgument(this.isValidPage(page), "Invalid page number (%s/%s)", page, this.getPageCount());
2024-04-26 02:46:17 +02:00
+ this.pages.set(page - 1, io.papermc.paper.adventure.PaperAdventure.asVanillaNullToEmpty(data));
+ }
+
+ @Override
+ public List<net.kyori.adventure.text.Component> pages() {
+ if (this.pages == null) return ImmutableList.of();
+ return this.pages.stream().map(io.papermc.paper.adventure.PaperAdventure::asAdventure).collect(ImmutableList.toImmutableList());
+ }
+
+ @Override
+ public BookMeta pages(List<net.kyori.adventure.text.Component> pages) {
+ if (this.pages != null) this.pages.clear();
+ for (net.kyori.adventure.text.Component page : pages) {
+ this.addPages(page);
+ }
+ return this;
+ }
+
+ @Override
+ public BookMeta pages(net.kyori.adventure.text.Component... pages) {
+ if (this.pages != null) this.pages.clear();
+ this.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;
+ }
+
+ this.pages.add(io.papermc.paper.adventure.PaperAdventure.asVanillaNullToEmpty(page));
+ }
+ }
2021-08-09 00:57:20 +02:00
+ // Paper end
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java
2024-08-09 22:05:50 +02:00
index 1c5d63fb6a9ed5cc40d735793cf5889e189feadf..568d6fab743039b20715d8181555f52baa05f0f3 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/CraftMetaItem.java
2024-08-09 22:05:50 +02:00
@@ -959,6 +959,18 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
2024-06-15 18:28:18 +02:00
return !(this.hasDisplayName() || this.hasItemName() || this.hasLocalizedName() || this.hasEnchants() || (this.lore != null) || this.hasCustomModelData() || this.hasBlockData() || this.hasRepairCost() || !this.unhandledTags.build().isEmpty() || !this.removedTags.isEmpty() || !this.persistentDataContainer.isEmpty() || this.hideFlag != 0 || this.isHideTooltip() || this.isUnbreakable() || this.hasEnchantmentGlintOverride() || this.isFireResistant() || this.hasMaxStackSize() || this.hasRarity() || this.hasFood() || this.hasTool() || this.hasDamage() || this.hasMaxDamage() || this.hasAttributeModifiers() || this.customTag != null);
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
+ public net.kyori.adventure.text.Component displayName() {
2024-04-25 06:38:28 +02:00
+ return displayName == null ? null : io.papermc.paper.adventure.PaperAdventure.asAdventure(displayName);
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public void displayName(final net.kyori.adventure.text.Component displayName) {
2024-04-25 06:38:28 +02:00
+ this.displayName = displayName == null ? null : io.papermc.paper.adventure.PaperAdventure.asVanilla(displayName);
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
+
@Override
public String getDisplayName() {
2024-04-23 20:32:19 +02:00
return CraftChatMessage.fromComponent(this.displayName);
2024-08-09 22:05:50 +02:00
@@ -989,6 +1001,18 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
2024-04-28 19:08:59 +02:00
return this.itemName != null;
}
+ // Paper start - Adventure
+ @Override
+ public net.kyori.adventure.text.Component itemName() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.itemName);
+ }
+
+ @Override
+ public void itemName(final net.kyori.adventure.text.Component name) {
+ this.itemName = io.papermc.paper.adventure.PaperAdventure.asVanilla(name);
+ }
+ // Paper end - Adventure
+
@Override
public String getLocalizedName() {
return this.getDisplayName();
2024-08-09 22:05:50 +02:00
@@ -1008,6 +1032,18 @@ class CraftMetaItem implements ItemMeta, Damageable, Repairable, BlockDataMeta {
2021-06-11 14:02:28 +02:00
return this.lore != null && !this.lore.isEmpty();
}
+ // Paper start
+ @Override
+ public List<net.kyori.adventure.text.Component> lore() {
2024-04-25 06:38:28 +02:00
+ return this.lore != null ? io.papermc.paper.adventure.PaperAdventure.asAdventure(this.lore) : null;
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
2023-03-20 09:18:06 +01:00
+ public void lore(final List<? extends net.kyori.adventure.text.Component> lore) {
2024-04-25 06:38:28 +02:00
+ this.lore = lore != null ? io.papermc.paper.adventure.PaperAdventure.asVanilla(lore) : null;
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
+
@Override
public boolean hasRepairCost() {
2021-06-11 21:23:46 +02:00
return this.repairCost > 0;
2024-04-06 21:53:39 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java
2024-04-23 20:32:19 +02:00
index 8952e5526cfe90ad16a7af28b0a8d9c65b159f90..cd3e35867075e65f46051fb88d8a2460a8bb4b53 100644
2024-04-06 21:53:39 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimMaterial.java
2024-04-23 20:32:19 +02:00
@@ -60,6 +60,14 @@ public class CraftTrimMaterial implements TrimMaterial, Handleable<net.minecraft
2024-04-06 21:53:39 +02:00
@NotNull
@Override
public String getTranslationKey() {
+ if (!(this.handle.description().getContents() instanceof TranslatableContents)) throw new UnsupportedOperationException("Description isn't translatable!"); // Paper
return ((TranslatableContents) this.handle.description().getContents()).getKey();
}
+
+ // Paper start - adventure
+ @Override
+ public net.kyori.adventure.text.Component description() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.handle.description());
+ }
+ // Paper end - adventure
}
diff --git a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java
2024-04-23 20:32:19 +02:00
index 0a6df5fdaf6724bb1cf777d527f032e2ae74fbbd..364f8d7a7106259401154d91b1b79869d014a469 100644
2024-04-06 21:53:39 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/trim/CraftTrimPattern.java
2024-04-23 20:32:19 +02:00
@@ -60,6 +60,14 @@ public class CraftTrimPattern implements TrimPattern, Handleable<net.minecraft.w
2024-04-06 21:53:39 +02:00
@NotNull
@Override
public String getTranslationKey() {
+ if (!(this.handle.description().getContents() instanceof TranslatableContents)) throw new UnsupportedOperationException("Description isn't translatable!"); // Paper
return ((TranslatableContents) this.handle.description().getContents()).getKey();
}
+
+ // Paper start - adventure
+ @Override
+ public net.kyori.adventure.text.Component description() {
+ return io.papermc.paper.adventure.PaperAdventure.asAdventure(this.handle.description());
+ }
+ // Paper end - adventure
}
2021-06-11 14:02:28 +02:00
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
2023-12-05 19:38:29 +01:00
index ec8ef47ed7cc627fef2c71b2b281119245e88b97..53cbc743b1e722d029021f9d63ffbf7d0fddd04e 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftInventoryCreator.java
2023-12-05 19:38:29 +01:00
@@ -45,6 +45,12 @@ public final class CraftInventoryCreator {
2021-06-11 21:23:46 +02:00
return this.converterMap.get(type).createInventory(holder, type);
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ public Inventory createInventory(InventoryHolder holder, InventoryType type, net.kyori.adventure.text.Component title) {
+ return converterMap.get(type).createInventory(holder, type, title);
+ }
+ // Paper end
+
public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) {
2021-06-11 21:23:46 +02:00
return this.converterMap.get(type).createInventory(holder, type, title);
2021-06-11 14:02:28 +02:00
}
2023-12-05 19:38:29 +01:00
@@ -53,6 +59,12 @@ public final class CraftInventoryCreator {
2021-06-11 21:23:46 +02:00
return this.DEFAULT_CONVERTER.createInventory(holder, size);
2021-06-11 14:02:28 +02:00
}
+ // 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) {
2021-06-11 21:23:46 +02:00
return this.DEFAULT_CONVERTER.createInventory(holder, size, title);
2021-06-11 14:02:28 +02:00
}
2023-12-05 19:38:29 +01:00
@@ -61,6 +73,10 @@ public final class CraftInventoryCreator {
2021-06-11 14:02:28 +02:00
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
2024-04-26 06:27:19 +02:00
index 11d23b3a9a0c99ede04f2cd64d8022b2b0b737df..7bc082d08a3d577481046818f0d58133413fc723 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java
+++ b/src/main/java/org/bukkit/craftbukkit/inventory/util/CraftTileInventoryConverter.java
Updated Upstream (Bukkit/CraftBukkit) (#10034)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
f29cb801 Separate checkstyle-suppressions file is not required
86f99bbe SPIGOT-7540, PR-946: Add ServerTickManager API
d4119585 SPIGOT-6903, PR-945: Add BlockData#getMapColor
b7a2ed41 SPIGOT-7530, PR-947: Add Player#removeResourcePack
9dd56255 SPIGOT-7527, PR-944: Add WindCharge#explode()
994a6163 Attempt upgrade of resolver libraries
CraftBukkit Changes:
b3b43a6ad Add Checkstyle check for unused imports
13fb3358e SPIGOT-7544: Scoreboard#getEntries() doesn't get entries but class names
3dda99c06 SPIGOT-7540, PR-1312: Add ServerTickManager API
2ab4508c0 SPIGOT-6903, PR-1311: Add BlockData#getMapColor
1dbdbbed4 PR-1238: Remove unnecessary sign ticking
659728d2a MC-264285, SPIGOT-7439, PR-1237: Fix unbreakable flint and steel is completely consumed while igniting creeper
e37e29ce0 Increase outdated build delay
c00438b39 SPIGOT-7530, PR-1313: Add Player#removeResourcePack
492dd80ce SPIGOT-7527, PR-1310: Add WindCharge#explode()
e11fbb9d7 Upgrade MySQL driver
9f3a0bd2a Attempt upgrade of resolver libraries
60d16d7ca PR-1306: Centralize Bukkit and Minecraft entity conversion
Spigot Changes:
06d602e7 Rebuild patches
2023-12-17 03:09:28 +01:00
@@ -31,6 +31,18 @@ public abstract class CraftTileInventoryConverter implements CraftInventoryCreat
2021-06-11 21:23:46 +02:00
return this.getInventory(this.getTileEntity());
2021-06-11 14:02:28 +02:00
}
+ // Paper start
+ @Override
+ public Inventory createInventory(InventoryHolder owner, InventoryType type, net.kyori.adventure.text.Component title) {
+ Container te = getTileEntity();
+ if (te instanceof RandomizableContainerBlockEntity) {
2024-04-26 06:27:19 +02:00
+ ((RandomizableContainerBlockEntity) te).name = io.papermc.paper.adventure.PaperAdventure.asVanilla(title);
2021-06-11 14:02:28 +02:00
+ }
+
+ return getInventory(te);
+ }
+ // Paper end
+
@Override
public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) {
2021-06-11 21:23:46 +02:00
Container te = this.getTileEntity();
Updated Upstream (Bukkit/CraftBukkit) (#10034)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
f29cb801 Separate checkstyle-suppressions file is not required
86f99bbe SPIGOT-7540, PR-946: Add ServerTickManager API
d4119585 SPIGOT-6903, PR-945: Add BlockData#getMapColor
b7a2ed41 SPIGOT-7530, PR-947: Add Player#removeResourcePack
9dd56255 SPIGOT-7527, PR-944: Add WindCharge#explode()
994a6163 Attempt upgrade of resolver libraries
CraftBukkit Changes:
b3b43a6ad Add Checkstyle check for unused imports
13fb3358e SPIGOT-7544: Scoreboard#getEntries() doesn't get entries but class names
3dda99c06 SPIGOT-7540, PR-1312: Add ServerTickManager API
2ab4508c0 SPIGOT-6903, PR-1311: Add BlockData#getMapColor
1dbdbbed4 PR-1238: Remove unnecessary sign ticking
659728d2a MC-264285, SPIGOT-7439, PR-1237: Fix unbreakable flint and steel is completely consumed while igniting creeper
e37e29ce0 Increase outdated build delay
c00438b39 SPIGOT-7530, PR-1313: Add Player#removeResourcePack
492dd80ce SPIGOT-7527, PR-1310: Add WindCharge#explode()
e11fbb9d7 Upgrade MySQL driver
9f3a0bd2a Attempt upgrade of resolver libraries
60d16d7ca PR-1306: Centralize Bukkit and Minecraft entity conversion
Spigot Changes:
06d602e7 Rebuild patches
2023-12-17 03:09:28 +01:00
@@ -53,6 +65,15 @@ public abstract class CraftTileInventoryConverter implements CraftInventoryCreat
2021-06-11 14:02:28 +02:00
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) {
2021-06-11 21:23:46 +02:00
Container tileEntity = this.getTileEntity();
Updated Upstream (Bukkit/CraftBukkit) (#10034)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
f29cb801 Separate checkstyle-suppressions file is not required
86f99bbe SPIGOT-7540, PR-946: Add ServerTickManager API
d4119585 SPIGOT-6903, PR-945: Add BlockData#getMapColor
b7a2ed41 SPIGOT-7530, PR-947: Add Player#removeResourcePack
9dd56255 SPIGOT-7527, PR-944: Add WindCharge#explode()
994a6163 Attempt upgrade of resolver libraries
CraftBukkit Changes:
b3b43a6ad Add Checkstyle check for unused imports
13fb3358e SPIGOT-7544: Scoreboard#getEntries() doesn't get entries but class names
3dda99c06 SPIGOT-7540, PR-1312: Add ServerTickManager API
2ab4508c0 SPIGOT-6903, PR-1311: Add BlockData#getMapColor
1dbdbbed4 PR-1238: Remove unnecessary sign ticking
659728d2a MC-264285, SPIGOT-7439, PR-1237: Fix unbreakable flint and steel is completely consumed while igniting creeper
e37e29ce0 Increase outdated build delay
c00438b39 SPIGOT-7530, PR-1313: Add Player#removeResourcePack
492dd80ce SPIGOT-7527, PR-1310: Add WindCharge#explode()
e11fbb9d7 Upgrade MySQL driver
9f3a0bd2a Attempt upgrade of resolver libraries
60d16d7ca PR-1306: Centralize Bukkit and Minecraft entity conversion
Spigot Changes:
06d602e7 Rebuild patches
2023-12-17 03:09:28 +01:00
@@ -73,6 +94,18 @@ public abstract class CraftTileInventoryConverter implements CraftInventoryCreat
2021-06-11 21:23:46 +02:00
return new BrewingStandBlockEntity(BlockPos.ZERO, Blocks.BREWING_STAND.defaultBlockState());
2021-06-11 14:02:28 +02:00
}
+ // 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) {
2024-04-26 06:27:19 +02:00
+ ((BrewingStandBlockEntity) tileEntity).name = io.papermc.paper.adventure.PaperAdventure.asVanilla(title);
2021-06-11 14:02:28 +02:00
+ }
+ return getInventory(tileEntity);
+ }
+ // Paper end
+
@Override
public Inventory createInventory(InventoryHolder holder, InventoryType type, String title) {
// BrewingStand does not extend TileEntityLootable
2022-08-11 10:40:19 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java b/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java
2024-04-23 20:32:19 +02:00
index 9efd33cc208af7068be6cf4040dd398f2506c709..0cbbd915631904fe8c6effefb92895422b33eff6 100644
2022-08-11 10:40:19 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java
+++ b/src/main/java/org/bukkit/craftbukkit/map/CraftMapRenderer.java
2024-04-23 20:32:19 +02:00
@@ -43,7 +43,7 @@ public class CraftMapRenderer extends MapRenderer {
2022-08-11 10:40:19 +02:00
}
2023-10-27 01:34:58 +02:00
MapDecoration decoration = this.worldMap.decorations.get(key);
2024-04-23 20:32:19 +02:00
- cursors.addCursor(new MapCursor(decoration.x(), decoration.y(), (byte) (decoration.rot() & 15), CraftMapCursor.CraftType.minecraftHolderToBukkit(decoration.type()), true, CraftChatMessage.fromComponent(decoration.name().orElse(null))));
+ cursors.addCursor(new MapCursor(decoration.x(), decoration.y(), (byte) (decoration.rot() & 15), CraftMapCursor.CraftType.minecraftHolderToBukkit(decoration.type()), true, decoration.name().isEmpty() ? null : io.papermc.paper.adventure.PaperAdventure.asAdventure(decoration.name().get()))); // Paper
2022-08-11 10:40:19 +02:00
}
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java
2023-12-05 19:38:29 +01:00
index 5c987c7d9e43bb481800935cbc918a43a3656524..da1e4496d78a2c1b258ff8bb316414cb8a662ba2 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java
+++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftObjective.java
2022-08-09 09:18:08 +02:00
@@ -31,6 +31,21 @@ final class CraftObjective extends CraftScoreboardComponent implements Objective
2021-06-11 21:23:46 +02:00
return this.objective.getName();
2021-06-11 14:02:28 +02:00
}
+ // 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
2023-08-06 02:21:59 +02:00
public String getDisplayName() {
2023-06-13 01:51:45 +02:00
this.checkState();
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java
Updated Upstream (Bukkit/CraftBukkit) (#10034)
Upstream has released updates that appear to apply and compile correctly.
This update has not been tested by PaperMC and as with ANY update, please do your own testing
Bukkit Changes:
f29cb801 Separate checkstyle-suppressions file is not required
86f99bbe SPIGOT-7540, PR-946: Add ServerTickManager API
d4119585 SPIGOT-6903, PR-945: Add BlockData#getMapColor
b7a2ed41 SPIGOT-7530, PR-947: Add Player#removeResourcePack
9dd56255 SPIGOT-7527, PR-944: Add WindCharge#explode()
994a6163 Attempt upgrade of resolver libraries
CraftBukkit Changes:
b3b43a6ad Add Checkstyle check for unused imports
13fb3358e SPIGOT-7544: Scoreboard#getEntries() doesn't get entries but class names
3dda99c06 SPIGOT-7540, PR-1312: Add ServerTickManager API
2ab4508c0 SPIGOT-6903, PR-1311: Add BlockData#getMapColor
1dbdbbed4 PR-1238: Remove unnecessary sign ticking
659728d2a MC-264285, SPIGOT-7439, PR-1237: Fix unbreakable flint and steel is completely consumed while igniting creeper
e37e29ce0 Increase outdated build delay
c00438b39 SPIGOT-7530, PR-1313: Add Player#removeResourcePack
492dd80ce SPIGOT-7527, PR-1310: Add WindCharge#explode()
e11fbb9d7 Upgrade MySQL driver
9f3a0bd2a Attempt upgrade of resolver libraries
60d16d7ca PR-1306: Centralize Bukkit and Minecraft entity conversion
Spigot Changes:
06d602e7 Rebuild patches
2023-12-17 03:09:28 +01:00
index d9f8a0c894a2a70b3dc2cef4feb87363627ec73a..5681630159bb52628e6cc391db324bbafe333414 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java
+++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftScoreboard.java
2023-12-05 19:38:29 +01:00
@@ -29,6 +29,33 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
2023-08-06 02:21:59 +02:00
public CraftObjective registerNewObjective(String name, String criteria) {
2021-06-11 21:23:46 +02:00
return this.registerNewObjective(name, criteria, name);
2021-06-11 14:02:28 +02:00
}
2023-08-06 02:21:59 +02:00
+ // Paper start - Adventure
2021-06-11 14:02:28 +02:00
+ @Override
+ public CraftObjective registerNewObjective(String name, String criteria, net.kyori.adventure.text.Component displayName) {
2023-08-06 02:21:59 +02:00
+ return this.registerNewObjective(name, CraftCriteria.getFromBukkit(criteria), displayName, RenderType.INTEGER);
2021-06-11 14:02:28 +02:00
+ }
+ @Override
+ public CraftObjective registerNewObjective(String name, String criteria, net.kyori.adventure.text.Component displayName, RenderType renderType) {
2023-08-06 02:21:59 +02:00
+ return this.registerNewObjective(name, CraftCriteria.getFromBukkit(criteria), displayName, renderType);
2022-08-09 09:18:08 +02:00
+ }
+ @Override
+ public CraftObjective registerNewObjective(String name, Criteria criteria, net.kyori.adventure.text.Component displayName) throws IllegalArgumentException {
2023-08-06 02:21:59 +02:00
+ return this.registerNewObjective(name, criteria, displayName, RenderType.INTEGER);
2022-08-09 09:18:08 +02:00
+ }
+ @Override
+ public CraftObjective registerNewObjective(String name, Criteria criteria, net.kyori.adventure.text.Component displayName, RenderType renderType) throws IllegalArgumentException {
2021-06-11 14:02:28 +02:00
+ if (displayName == null) {
+ displayName = net.kyori.adventure.text.Component.empty();
+ }
2023-06-13 01:51:45 +02:00
+ Preconditions.checkArgument(name != null, "Objective name cannot be null");
+ Preconditions.checkArgument(criteria != null, "Criteria cannot be null");
+ Preconditions.checkArgument(renderType != null, "RenderType cannot be null");
+ Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "The name '%s' is longer than the limit of 32767 characters (%s)", name, name.length());
+ Preconditions.checkArgument(this.board.getObjective(name) == null, "An objective of name '%s' already exists", name);
2023-12-05 19:38:29 +01:00
+ net.minecraft.world.scores.Objective objective = this.board.addObjective(name, ((CraftCriteria) criteria).criteria, io.papermc.paper.adventure.PaperAdventure.asVanilla(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType), true, null);
2021-06-11 14:02:28 +02:00
+ return new CraftObjective(this, objective);
+ }
2023-08-06 02:21:59 +02:00
+ // Paper end - Adventure
2021-06-11 14:02:28 +02:00
@Override
2023-08-06 02:21:59 +02:00
public CraftObjective registerNewObjective(String name, String criteria, String displayName) {
2023-12-05 19:38:29 +01:00
@@ -47,15 +74,7 @@ public final class CraftScoreboard implements org.bukkit.scoreboard.Scoreboard {
2021-06-11 14:02:28 +02:00
@Override
2023-08-06 02:21:59 +02:00
public CraftObjective registerNewObjective(String name, Criteria criteria, String displayName, RenderType renderType) {
2023-06-13 01:51:45 +02:00
- Preconditions.checkArgument(name != null, "Objective name cannot be null");
- Preconditions.checkArgument(criteria != null, "Criteria cannot be null");
- Preconditions.checkArgument(displayName != null, "Display name cannot be null");
- Preconditions.checkArgument(renderType != null, "RenderType cannot be null");
- Preconditions.checkArgument(name.length() <= Short.MAX_VALUE, "The name '%s' is longer than the limit of 32767 characters (%s)", name, name.length());
- Preconditions.checkArgument(this.board.getObjective(name) == null, "An objective of name '%s' already exists", name);
2022-08-09 09:18:08 +02:00
-
2023-12-05 19:38:29 +01:00
- net.minecraft.world.scores.Objective objective = this.board.addObjective(name, ((CraftCriteria) criteria).criteria, CraftChatMessage.fromStringOrNull(displayName), CraftScoreboardTranslations.fromBukkitRender(renderType), true, null);
2021-06-11 14:02:28 +02:00
- return new CraftObjective(this, objective);
2023-08-06 02:21:59 +02:00
+ return this.registerNewObjective(name, criteria, net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection().deserialize(displayName), renderType); // Paper - Adventure
2021-06-11 14:02:28 +02:00
}
@Override
diff --git a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java
2023-11-04 21:50:56 +01:00
index 4d586e1375ed8782939c9d480479e0dd981f8cbc..7900adb0b158bc17dd792dd082c338547bc1aa0a 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java
+++ b/src/main/java/org/bukkit/craftbukkit/scoreboard/CraftTeam.java
2023-06-13 01:51:45 +02:00
@@ -26,6 +26,63 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
2021-06-11 14:02:28 +02:00
2021-06-11 21:23:46 +02:00
return this.team.getName();
2021-06-11 14:02:28 +02:00
}
+ // 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
2022-04-24 03:37:10 +02:00
+ public boolean hasColor() {
+ CraftScoreboard scoreboard = checkState();
+ return this.team.getColor().getColor() != null;
+ }
+ @Override
2021-06-11 14:02:28 +02:00
+ public net.kyori.adventure.text.format.TextColor color() throws IllegalStateException {
+ CraftScoreboard scoreboard = checkState();
2021-06-16 19:48:25 +02:00
+ if (team.getColor().getColor() == 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().getColor());
2021-06-11 14:02:28 +02:00
+ 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) {
+ CraftScoreboard scoreboard = checkState();
2022-04-24 03:37:10 +02:00
+ if (color == null) {
+ this.team.setColor(net.minecraft.ChatFormatting.RESET);
2022-05-21 11:27:12 +02:00
+ } else {
+ this.team.setColor(io.papermc.paper.adventure.PaperAdventure.asVanilla(color));
2022-04-24 03:37:10 +02:00
+ }
2021-06-11 14:02:28 +02:00
+ }
+ // Paper end
@Override
2023-08-06 02:21:59 +02:00
public String getDisplayName() {
2023-11-04 21:50:56 +01:00
@@ -303,4 +360,20 @@ final class CraftTeam extends CraftScoreboardComponent implements Team {
return !(this.team != other.team && (this.team == null || !this.team.equals(other.team)));
}
+ // Paper start - make Team extend ForwardingAudience
+ @Override
+ public @org.jetbrains.annotations.NotNull Iterable<? extends net.kyori.adventure.audience.Audience> audiences() {
+ this.checkState();
+ java.util.List<net.kyori.adventure.audience.Audience> audiences = new java.util.ArrayList<>();
+ for (String playerName : this.team.getPlayers()) {
+ org.bukkit.entity.Player player = Bukkit.getPlayerExact(playerName);
+ if (player != null) {
+ audiences.add(player);
+ }
+ }
+
+ return audiences;
+ }
+ // Paper end - make Team extend ForwardingAudience
+
}
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java
2024-07-06 21:19:14 +02:00
index ff040613083c015d9c52c0995591b64305fd5018..1b552b3f05ac7fc44450de4b1ec78907a0f62424 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/CraftChatMessage.java
2024-07-06 21:19:14 +02:00
@@ -264,6 +264,7 @@ public final class CraftChatMessage {
2021-06-11 14:02:28 +02:00
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
2024-08-10 12:24:38 +02:00
index eeffc4be4ae7168c9f69edbbff6642fd4c214b3d..b64be3f292d88fa60746a3fe542740ef8ad2b41c 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/CraftMagicNumbers.java
2024-07-06 21:19:14 +02:00
@@ -77,6 +77,43 @@ public final class CraftMagicNumbers implements UnsafeValues {
2021-06-11 14:02:28 +02:00
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() {
2022-05-26 21:12:14 +02:00
+ return net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.colorDownsamplingGson();
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public net.kyori.adventure.text.serializer.gson.GsonComponentSerializer gsonComponentSerializer() {
2022-05-26 21:12:14 +02:00
+ return net.kyori.adventure.text.serializer.gson.GsonComponentSerializer.gson();
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
2021-12-22 23:56:37 +01:00
+ public net.kyori.adventure.text.serializer.plain.PlainComponentSerializer plainComponentSerializer() {
2022-05-26 21:12:14 +02:00
+ return io.papermc.paper.adventure.PaperAdventure.PLAIN;
2021-12-22 23:56:37 +01:00
+ }
+
+ @Override
+ public net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer plainTextSerializer() {
2022-05-26 21:12:14 +02:00
+ return net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText();
2021-06-11 14:02:28 +02:00
+ }
+
+ @Override
+ public net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer legacyComponentSerializer() {
2022-05-26 21:12:14 +02:00
+ return net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer.legacySection();
2021-06-11 14:02:28 +02:00
+ }
2022-11-23 05:53:50 +01:00
+
+ @Override
+ public net.kyori.adventure.text.Component resolveWithContext(final net.kyori.adventure.text.Component component, final org.bukkit.command.CommandSender context, final org.bukkit.entity.Entity scoreboardSubject, final boolean bypassPermissions) throws IOException {
+ return io.papermc.paper.adventure.PaperAdventure.resolveWithContext(component, context, scoreboardSubject, bypassPermissions);
+ }
2021-06-11 14:02:28 +02:00
+ // Paper end
+
public static BlockState getBlock(MaterialData material) {
2021-06-11 21:23:46 +02:00
return CraftMagicNumbers.getBlock(material.getItemType(), material.getData());
2021-06-11 14:02:28 +02:00
}
diff --git a/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyHashSet.java
2021-06-11 21:23:46 +02:00
index 62c66e3179b9557cdba46242df0fb15bce7e7710..73a37638abacdffbff8274291a64ea6cd0be7a5e 100644
2021-06-11 14:02:28 +02:00
--- 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<E> implements Set<E> {
2021-06-11 21:23:46 +02:00
return this.reference = this.makeReference();
2021-06-11 14:02:28 +02:00
}
- abstract Set<E> makeReference();
+ protected abstract Set<E> makeReference(); // Paper - protected
public boolean isLazy() {
2021-06-11 21:23:46 +02:00
return this.reference == null;
2021-06-11 14:02:28 +02:00
diff --git a/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java b/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java
2023-10-27 01:34:58 +02:00
index 0ab4c7eaffe69b314423732dd529aaeafc476e08..8a44e7260518bda87c6d0eeade98d5b81a04c3b6 100644
2021-06-11 14:02:28 +02:00
--- a/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java
+++ b/src/main/java/org/bukkit/craftbukkit/util/LazyPlayerSet.java
2023-10-27 01:34:58 +02:00
@@ -16,9 +16,14 @@ public class LazyPlayerSet extends LazyHashSet<Player> {
2021-06-11 14:02:28 +02:00
}
@Override
- HashSet<Player> makeReference() {
+ protected HashSet<Player> makeReference() { // Paper - protected
2023-10-27 01:34:58 +02:00
Preconditions.checkState(this.reference == null, "Reference already created!");
- List<ServerPlayer> players = this.server.getPlayerList().players;
2021-06-11 14:02:28 +02:00
+ // Paper start
+ return makePlayerSet(this.server);
+ }
+ public static HashSet<Player> makePlayerSet(final MinecraftServer server) {
2021-06-11 21:23:46 +02:00
+ List<ServerPlayer> players = server.getPlayerList().players;
2023-10-27 01:34:58 +02:00
+ // Paper end
2021-06-11 14:02:28 +02:00
HashSet<Player> reference = new HashSet<Player>(players.size());
for (ServerPlayer player : players) {
2021-06-11 21:23:46 +02:00
reference.add(player.getBukkitEntity());
2023-06-12 23:43:39 +02:00
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.bossbar.BossBarImplementation$Provider b/src/main/resources/META-INF/services/net.kyori.adventure.bossbar.BossBarImplementation$Provider
new file mode 100644
index 0000000000000000000000000000000000000000..9b7119d0b88bf7f9d25fab37a15340cabc0c9b7b
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.bossbar.BossBarImplementation$Provider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.BossBarImplementationProvider
2023-03-15 13:19:54 +01:00
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.text.event.ClickCallback$Provider b/src/main/resources/META-INF/services/net.kyori.adventure.text.event.ClickCallback$Provider
new file mode 100644
index 0000000000000000000000000000000000000000..845711e03c41c6b6a03d541f1c43d37b24c11733
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.text.event.ClickCallback$Provider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.ClickCallbackProviderImpl
2024-04-25 05:14:51 +02:00
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.text.event.DataComponentValueConverterRegistry$Provider b/src/main/resources/META-INF/services/net.kyori.adventure.text.event.DataComponentValueConverterRegistry$Provider
new file mode 100644
index 0000000000000000000000000000000000000000..714cb03596627badb6ad7f23b17f2e686761a9b5
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.text.event.DataComponentValueConverterRegistry$Provider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.DataComponentValueConverterProviderImpl
2022-06-12 23:07:40 +02:00
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.text.logger.slf4j.ComponentLoggerProvider b/src/main/resources/META-INF/services/net.kyori.adventure.text.logger.slf4j.ComponentLoggerProvider
new file mode 100644
index 0000000000000000000000000000000000000000..399bde6e57cd82b50d3ebe0f51a3958fa2d52d43
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.text.logger.slf4j.ComponentLoggerProvider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.ComponentLoggerProviderImpl
2022-05-26 21:12:14 +02:00
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.text.minimessage.MiniMessage$Provider b/src/main/resources/META-INF/services/net.kyori.adventure.text.minimessage.MiniMessage$Provider
new file mode 100644
index 0000000000000000000000000000000000000000..6ce632b6c9dc5e4b3b978331df51c0ffd1526471
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.text.minimessage.MiniMessage$Provider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.MiniMessageProviderImpl
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.gson.GsonComponentSerializer$Provider b/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.gson.GsonComponentSerializer$Provider
new file mode 100644
index 0000000000000000000000000000000000000000..bc9f7398a0fe158af05b562a8ded9e74a22eae9b
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.gson.GsonComponentSerializer$Provider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.GsonComponentSerializerProviderImpl
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer$Provider b/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer$Provider
new file mode 100644
index 0000000000000000000000000000000000000000..820f381981a91754b7f0c5106f93b773d885e321
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer$Provider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.LegacyComponentSerializerProviderImpl
diff --git a/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer$Provider b/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer$Provider
new file mode 100644
index 0000000000000000000000000000000000000000..28d777610b52ba74f808bf3245d73b8333d01fa7
--- /dev/null
+++ b/src/main/resources/META-INF/services/net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer$Provider
@@ -0,0 +1 @@
+io.papermc.paper.adventure.providers.PlainTextComponentSerializerProviderImpl
2024-04-26 17:33:00 +02:00
diff --git a/src/main/resources/data/minecraft/datapacks/paper/data/paper/chat_type/raw.json b/src/main/resources/data/minecraft/datapacks/paper/data/paper/chat_type/raw.json
2023-09-15 20:03:42 +02:00
new file mode 100644
index 0000000000000000000000000000000000000000..3aedd0bbc97edacc1ebf71264b310e55aaaa5cb3
--- /dev/null
2024-04-26 17:33:00 +02:00
+++ b/src/main/resources/data/minecraft/datapacks/paper/data/paper/chat_type/raw.json
2023-09-15 20:03:42 +02:00
@@ -0,0 +1,14 @@
+{
+ "chat": {
+ "parameters": [
+ "content"
+ ],
+ "translation_key": "%s"
+ },
+ "narration": {
+ "parameters": [
+ "content"
+ ],
+ "translation_key": "%s"
+ }
+}
2023-12-12 07:02:06 +01:00
diff --git a/src/test/java/io/papermc/paper/adventure/AdventureCodecsTest.java b/src/test/java/io/papermc/paper/adventure/AdventureCodecsTest.java
new file mode 100644
2024-06-03 00:19:17 +02:00
index 0000000000000000000000000000000000000000..69b3aa957161e75d6344e437a8b4a4533ef00523
2023-12-12 07:02:06 +01:00
--- /dev/null
+++ b/src/test/java/io/papermc/paper/adventure/AdventureCodecsTest.java
2024-04-27 03:16:31 +02:00
@@ -0,0 +1,403 @@
2023-12-12 07:02:06 +01:00
+package io.papermc.paper.adventure;
+
+import com.mojang.datafixers.util.Pair;
+import com.mojang.serialization.Codec;
+import com.mojang.serialization.DataResult;
2024-02-17 22:58:56 +01:00
+import com.mojang.serialization.DynamicOps;
2024-04-25 05:14:51 +02:00
+import com.mojang.serialization.JavaOps;
2024-02-17 22:58:56 +01:00
+import com.mojang.serialization.JsonOps;
+import io.papermc.paper.util.MethodParameterSource;
2023-12-12 07:02:06 +01:00
+import java.io.IOException;
2024-02-17 22:58:56 +01:00
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
2023-12-12 07:02:06 +01:00
+import java.util.List;
+import java.util.UUID;
+import java.util.function.Function;
2024-04-27 03:16:31 +02:00
+import java.util.stream.Stream;
2023-12-12 07:02:06 +01:00
+import net.kyori.adventure.key.Key;
+import net.kyori.adventure.text.BlockNBTComponent;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.event.ClickEvent;
+import net.kyori.adventure.text.event.HoverEvent;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.Style;
+import net.kyori.adventure.text.format.TextColor;
+import net.kyori.adventure.text.format.TextDecoration;
2024-04-25 05:14:51 +02:00
+import net.minecraft.core.component.DataComponents;
2023-12-12 07:02:06 +01:00
+import net.minecraft.core.registries.BuiltInRegistries;
+import net.minecraft.nbt.ByteTag;
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.nbt.IntTag;
+import net.minecraft.nbt.ListTag;
+import net.minecraft.nbt.NbtOps;
+import net.minecraft.nbt.Tag;
+import net.minecraft.network.chat.ComponentSerialization;
2024-04-27 03:16:31 +02:00
+import net.minecraft.resources.RegistryOps;
2023-12-12 07:02:06 +01:00
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.item.ItemStack;
+import net.minecraft.world.item.Items;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.bukkit.support.AbstractTestingBase;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
2024-02-17 22:58:56 +01:00
+import org.junitpioneer.jupiter.cartesian.CartesianTest;
2023-12-12 07:02:06 +01:00
+
+import static io.papermc.paper.adventure.AdventureCodecs.CLICK_EVENT_CODEC;
+import static io.papermc.paper.adventure.AdventureCodecs.COMPONENT_CODEC;
+import static io.papermc.paper.adventure.AdventureCodecs.HOVER_EVENT_CODEC;
+import static io.papermc.paper.adventure.AdventureCodecs.KEY_CODEC;
+import static io.papermc.paper.adventure.AdventureCodecs.STYLE_MAP_CODEC;
+import static io.papermc.paper.adventure.AdventureCodecs.TEXT_COLOR_CODEC;
+import static java.util.Objects.requireNonNull;
+import static net.kyori.adventure.key.Key.key;
+import static net.kyori.adventure.text.Component.blockNBT;
+import static net.kyori.adventure.text.Component.entityNBT;
+import static net.kyori.adventure.text.Component.keybind;
+import static net.kyori.adventure.text.Component.score;
+import static net.kyori.adventure.text.Component.selector;
+import static net.kyori.adventure.text.Component.storageNBT;
+import static net.kyori.adventure.text.Component.text;
+import static net.kyori.adventure.text.Component.translatable;
2023-12-25 11:51:44 +01:00
+import static net.kyori.adventure.text.TranslationArgument.numeric;
2023-12-12 07:02:06 +01:00
+import static net.kyori.adventure.text.event.ClickEvent.openUrl;
+import static net.kyori.adventure.text.event.ClickEvent.suggestCommand;
+import static net.kyori.adventure.text.event.HoverEvent.showEntity;
+import static net.kyori.adventure.text.format.Style.style;
+import static net.kyori.adventure.text.format.TextColor.color;
+import static net.kyori.adventure.text.minimessage.MiniMessage.miniMessage;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class AdventureCodecsTest extends AbstractTestingBase {
+
2024-02-17 22:58:56 +01:00
+ static final String PARAMETERIZED_NAME = "[{index}] {displayName}: {arguments}";
+
2023-12-12 07:02:06 +01:00
+ @Test
+ void testTextColor() {
+ final TextColor color = color(0x1d38df);
+ final Tag result = TEXT_COLOR_CODEC.encodeStart(NbtOps.INSTANCE, color).result().orElseThrow();
+ assertEquals(color.asHexString(), result.getAsString());
+ final net.minecraft.network.chat.TextColor nms = net.minecraft.network.chat.TextColor.CODEC.decode(NbtOps.INSTANCE, result).result().orElseThrow().getFirst();
+ assertEquals(color.value(), nms.getValue());
+ }
+
+ @Test
+ void testNamedTextColor() {
+ final NamedTextColor color = NamedTextColor.BLUE;
+ final Tag result = TEXT_COLOR_CODEC.encodeStart(NbtOps.INSTANCE, color).result().orElseThrow();
+ assertEquals(NamedTextColor.NAMES.keyOrThrow(color), result.getAsString());
+ final net.minecraft.network.chat.TextColor nms = net.minecraft.network.chat.TextColor.CODEC.decode(NbtOps.INSTANCE, result).result().orElseThrow().getFirst();
+ assertEquals(color.value(), nms.getValue());
+ }
+
+ @Test
+ void testKey() {
+ final Key key = key("hello", "there");
+ final Tag result = KEY_CODEC.encodeStart(NbtOps.INSTANCE, key).result().orElseThrow();
+ assertEquals(key.asString(), result.getAsString());
+ final ResourceLocation location = ResourceLocation.CODEC.decode(NbtOps.INSTANCE, result).result().orElseThrow().getFirst();
+ assertEquals(key.asString(), location.toString());
+ }
+
2024-02-17 22:58:56 +01:00
+ @ParameterizedTest(name = PARAMETERIZED_NAME)
2023-12-12 07:02:06 +01:00
+ @EnumSource(value = ClickEvent.Action.class, mode = EnumSource.Mode.EXCLUDE, names = {"OPEN_FILE"})
+ void testClickEvent(final ClickEvent.Action action) {
+ final ClickEvent event = ClickEvent.clickEvent(action, RandomStringUtils.randomAlphanumeric(20));
+ final Tag result = CLICK_EVENT_CODEC.encodeStart(NbtOps.INSTANCE, event).result().orElseThrow();
+ final net.minecraft.network.chat.ClickEvent nms = net.minecraft.network.chat.ClickEvent.CODEC.decode(NbtOps.INSTANCE, result).result().orElseThrow().getFirst();
+ assertEquals(event.action().toString(), nms.getAction().getSerializedName());
+ assertEquals(event.value(), nms.getValue());
+ }
+
+ @Test
+ void testShowTextHoverEvent() {
+ final HoverEvent<Component> hoverEvent = HoverEvent.hoverEvent(HoverEvent.Action.SHOW_TEXT, text("hello"));
+ final Tag result = HOVER_EVENT_CODEC.encodeStart(NbtOps.INSTANCE, hoverEvent).result().orElseThrow();
+ final net.minecraft.network.chat.HoverEvent nms = net.minecraft.network.chat.HoverEvent.CODEC.decode(NbtOps.INSTANCE, result).result().orElseThrow().getFirst();
+ assertEquals(hoverEvent.action().toString(), nms.getAction().getSerializedName());
+ assertNotNull(nms.getValue(net.minecraft.network.chat.HoverEvent.Action.SHOW_TEXT));
+ }
+
+ @Test
+ void testShowItemHoverEvent() throws IOException {
+ final ItemStack stack = new ItemStack(Items.PUMPKIN, 3);
2024-04-25 05:14:51 +02:00
+ stack.set(DataComponents.CUSTOM_NAME, net.minecraft.network.chat.Component.literal("NAME"));
+ final HoverEvent<HoverEvent.ShowItem> hoverEvent = HoverEvent.showItem(key("minecraft:pumpkin"), 3, PaperAdventure.asAdventure(stack.getComponentsPatch()));
2023-12-12 07:02:06 +01:00
+ final Tag result = HOVER_EVENT_CODEC.encodeStart(NbtOps.INSTANCE, hoverEvent).result().orElseThrow();
+ final DataResult<Pair<net.minecraft.network.chat.HoverEvent, Tag>> dataResult = net.minecraft.network.chat.HoverEvent.CODEC.decode(NbtOps.INSTANCE, result);
+ assertTrue(dataResult.result().isPresent(), () -> dataResult + " result is not present");
+ final net.minecraft.network.chat.HoverEvent nms = dataResult.result().orElseThrow().getFirst();
+ assertEquals(hoverEvent.action().toString(), nms.getAction().getSerializedName());
+ final net.minecraft.network.chat.HoverEvent.ItemStackInfo value = nms.getValue(net.minecraft.network.chat.HoverEvent.Action.SHOW_ITEM);
+ assertNotNull(value);
+ assertEquals(hoverEvent.value().count(), value.count);
2024-04-25 05:14:51 +02:00
+ assertEquals(hoverEvent.value().item().asString(), value.item.unwrapKey().orElseThrow().location().toString());
+ assertEquals(stack.getComponentsPatch(), value.components);
2023-12-12 07:02:06 +01:00
+ }
+
+ @Test
+ void testShowEntityHoverEvent() {
+ UUID uuid = UUID.randomUUID();
+ final HoverEvent<HoverEvent.ShowEntity> hoverEvent = showEntity(key("minecraft:wolf"), uuid, text("NAME"));
+ final Tag result = HOVER_EVENT_CODEC.encodeStart(NbtOps.INSTANCE, hoverEvent).result().orElseThrow();
+ final DataResult<Pair<net.minecraft.network.chat.HoverEvent, Tag>> dataResult = net.minecraft.network.chat.HoverEvent.CODEC.decode(NbtOps.INSTANCE, result);
+ assertTrue(dataResult.result().isPresent(), () -> dataResult + " result is not present");
+ final net.minecraft.network.chat.HoverEvent nms = dataResult.result().orElseThrow().getFirst();
+ assertEquals(hoverEvent.action().toString(), nms.getAction().getSerializedName());
+ final net.minecraft.network.chat.HoverEvent.EntityTooltipInfo value = nms.getValue(net.minecraft.network.chat.HoverEvent.Action.SHOW_ENTITY);
+ assertNotNull(value);
+ assertEquals(hoverEvent.value().type().asString(), BuiltInRegistries.ENTITY_TYPE.getKey(value.type).toString());
+ assertEquals(hoverEvent.value().id(), value.id);
+ assertEquals("NAME", value.name.orElseThrow().getString());
+ }
+
+ @Test
+ void testSimpleStyle() {
+ final Style style = style().decorate(TextDecoration.BOLD).color(NamedTextColor.RED).build();
+ final Tag result = STYLE_MAP_CODEC.codec().encodeStart(NbtOps.INSTANCE, style).result().orElseThrow();
+ final DataResult<Pair<net.minecraft.network.chat.Style, Tag>> dataResult = net.minecraft.network.chat.Style.Serializer.CODEC.decode(NbtOps.INSTANCE, result);
+ assertTrue(dataResult.result().isPresent(), () -> dataResult + " result is not present");
+ final net.minecraft.network.chat.Style nms = dataResult.result().get().getFirst();
+ assertTrue(nms.isBold());
+ assertEquals(requireNonNull(style.color()).value(), requireNonNull(nms.getColor()).getValue());
+ }
+
2024-02-17 22:58:56 +01:00
+ @CartesianTest(name = PARAMETERIZED_NAME)
+ void testDirectRoundTripStyle(
+ @MethodParameterSource("dynamicOps") final DynamicOps<?> dynamicOps,
+ @MethodParameterSource("testStyles") final Style style
+ ) {
+ testDirectRoundTrip(dynamicOps, STYLE_MAP_CODEC.codec(), style);
2023-12-12 07:02:06 +01:00
+ }
+
2024-02-17 22:58:56 +01:00
+ @CartesianTest(name = PARAMETERIZED_NAME)
+ void testMinecraftRoundTripStyle(
+ @MethodParameterSource("dynamicOps") final DynamicOps<?> dynamicOps,
+ @MethodParameterSource("testStyles") final Style style
+ ) {
+ testMinecraftRoundTrip(dynamicOps, STYLE_MAP_CODEC.codec(), net.minecraft.network.chat.Style.Serializer.CODEC, style);
2023-12-12 07:02:06 +01:00
+ }
+
2024-02-17 22:58:56 +01:00
+ @CartesianTest(name = PARAMETERIZED_NAME)
+ void testDirectRoundTripComponent(
+ @MethodParameterSource("dynamicOps") final DynamicOps<?> dynamicOps,
+ @TestComponents final Component component
+ ) {
+ testDirectRoundTrip(dynamicOps, COMPONENT_CODEC, component);
2023-12-12 07:02:06 +01:00
+ }
+
2024-02-17 22:58:56 +01:00
+ @CartesianTest(name = PARAMETERIZED_NAME)
+ void testMinecraftRoundTripComponent(
+ @MethodParameterSource("dynamicOps") final DynamicOps<?> dynamicOps,
+ @TestComponents final Component component
+ ) {
+ testMinecraftRoundTrip(dynamicOps, COMPONENT_CODEC, ComponentSerialization.CODEC, component);
2023-12-12 07:02:06 +01:00
+ }
+
2024-04-27 03:16:31 +02:00
+ static List<? extends DynamicOps<?>> dynamicOps() {
+ return Stream.of(
2024-02-17 22:58:56 +01:00
+ NbtOps.INSTANCE,
+ JavaOps.INSTANCE,
+ JsonOps.INSTANCE
2024-04-27 03:16:31 +02:00
+ )
2024-06-03 00:19:17 +02:00
+ .map(ops -> AbstractTestingBase.REGISTRY_CUSTOM.createSerializationContext(ops))
2024-04-27 03:16:31 +02:00
+ .toList();
2024-02-17 22:58:56 +01:00
+ }
+
+ @ParameterizedTest(name = PARAMETERIZED_NAME)
2023-12-12 07:02:06 +01:00
+ @MethodSource({"invalidData"})
+ void invalidThrows(final Tag input) {
+ assertThrows(RuntimeException.class, () -> {
+ require(
+ COMPONENT_CODEC.decode(NbtOps.INSTANCE, input),
+ msg -> "Failed to decode " + input + ": " + msg
+ );
+ });
+ }
+
2024-02-17 22:58:56 +01:00
+ static <A, O> void testDirectRoundTrip(final DynamicOps<O> ops, final Codec<A> codec, final A adventure) {
+ final O encoded = require(
+ codec.encodeStart(ops, adventure),
2023-12-12 07:02:06 +01:00
+ msg -> "Failed to encode " + adventure + ": " + msg
+ );
2024-02-17 22:58:56 +01:00
+ final Pair<A, O> roundTripResult = require(
+ codec.decode(ops, encoded),
2023-12-12 07:02:06 +01:00
+ msg -> "Failed to decode " + encoded + ": " + msg
+ );
+ assertEquals(adventure, roundTripResult.getFirst());
+ }
+
2024-02-17 22:58:56 +01:00
+ static <A, M, O> void testMinecraftRoundTrip(final DynamicOps<O> ops, final Codec<A> adventureCodec, final Codec<M> minecraftCodec, final A adventure) {
+ final O encoded = require(
+ adventureCodec.encodeStart(ops, adventure),
2023-12-12 07:02:06 +01:00
+ msg -> "Failed to encode " + adventure + ": " + msg
+ );
+ final M minecraftResult = require(
2024-02-17 22:58:56 +01:00
+ minecraftCodec.decode(ops, encoded),
2023-12-12 07:02:06 +01:00
+ msg -> "Failed to decode to Minecraft: " + encoded + "; " + msg
+ ).getFirst();
2024-02-17 22:58:56 +01:00
+ final O minecraftReEncoded = require(
+ minecraftCodec.encodeStart(ops, minecraftResult),
2023-12-12 07:02:06 +01:00
+ msg -> "Failed to re-encode Minecraft: " + minecraftResult + "; " + msg
+ );
2024-02-17 22:58:56 +01:00
+ final Pair<A, O> roundTripResult = require(
+ adventureCodec.decode(ops, minecraftReEncoded),
2023-12-12 07:02:06 +01:00
+ msg -> "Failed to decode " + minecraftReEncoded + ": " + msg
+ );
+ assertEquals(adventure, roundTripResult.getFirst());
+ }
+
+ static <R> R require(final DataResult<R> result, final Function<String, String> errorMessage) {
2024-04-25 21:16:00 +02:00
+ return result.getOrThrow(s -> new RuntimeException(errorMessage.apply(s)));
2023-12-12 07:02:06 +01:00
+ }
+
+ static List<Tag> invalidData() {
+ return List.of(
+ IntTag.valueOf(-1),
+ ByteTag.ZERO,
+ new CompoundTag(),
+ new ListTag()
+ );
+ }
+
+ static List<Style> testStyles() {
+ return List.of(
+ Style.empty(),
+ style(color(0x0a1ab9)),
+ style(NamedTextColor.LIGHT_PURPLE),
+ style(TextDecoration.BOLD),
+ style(TextDecoration.BOLD.withState(false)),
+ style(TextDecoration.BOLD.withState(TextDecoration.State.NOT_SET)),
+ style()
+ .font(key("kyori", "kittens"))
+ .color(NamedTextColor.RED)
+ .decoration(TextDecoration.BOLD, true)
+ .clickEvent(openUrl("https://github.com"))
+ .build(),
+ style()
+ .hoverEvent(HoverEvent.showEntity(HoverEvent.ShowEntity.showEntity(
+ Key.key(Key.MINECRAFT_NAMESPACE, "pig"),
+ UUID.randomUUID(),
+ Component.text("Dolores", TextColor.color(0x0a1ab9))
+ )))
+ .build()
+ );
+ }
+
2024-02-17 22:58:56 +01:00
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target({ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
+ @MethodParameterSource({
+ "testTexts", "testTranslatables", "testKeybinds", "testScores",
+ "testSelectors", "testBlockNbts", "testEntityNbts", "testStorageNbts"
+ })
+ @interface TestComponents {
+ }
+
2023-12-12 07:02:06 +01:00
+ static List<Component> testTexts() {
+ return List.of(
+ Component.empty(),
+ text("Hello, world."),
+ text().content("c")
+ .color(NamedTextColor.GOLD)
+ .append(text("o", NamedTextColor.DARK_AQUA))
+ .append(text("l", NamedTextColor.LIGHT_PURPLE))
+ .append(text("o", NamedTextColor.DARK_PURPLE))
+ .append(text("u", NamedTextColor.BLUE))
+ .append(text("r", NamedTextColor.DARK_GREEN))
+ .append(text("s", NamedTextColor.RED))
+ .build(),
+ text().content("This is a test.")
+ .color(NamedTextColor.DARK_PURPLE)
+ .hoverEvent(HoverEvent.showText(text("A test.")))
+ .append(text(" "))
+ .append(text("A what?", NamedTextColor.DARK_AQUA))
+ .build(),
+ text().append(text("Hello")).build(),
+ miniMessage().deserialize("<rainbow>|||||||||||||||||||||||<bold>|||||||||||||</bold>|||||||||")
+ );
+ }
+
+ static List<Component> testTranslatables() {
+ final String key = "multiplayer.player.left";
+ final UUID id = UUID.fromString("eb121687-8b1a-4944-bd4d-e0a818d9dfe2");
+ final String name = "kashike";
+ final String command = String.format("/msg %s ", name);
+
+ return List.of(
+ translatable(key),
+ translatable()
+ .key("thisIsA")
+ .fallback("This is a test.")
+ .build(),
2024-02-17 22:58:56 +01:00
+ translatable(key, numeric(Integer.MAX_VALUE), text("HEY")), // boolean doesn't work in vanilla, can't test here
2023-12-12 07:02:06 +01:00
+ translatable(
+ key,
+ text().content(name)
+ .clickEvent(suggestCommand(command))
+ .hoverEvent(showEntity(HoverEvent.ShowEntity.showEntity(
+ key("minecraft", "player"),
+ id,
+ text(name)
+ )))
+ .build()
+ ).color(NamedTextColor.YELLOW)
+ );
+ }
+
+ static List<Component> testKeybinds() {
+ return List.of(keybind("key.jump"));
+ }
+
+ static List<Component> testScores() {
+ final String name = "abc";
+ final String objective = "def";
+
+ return List.of(score(name, objective));
+ }
+
+ static List<Component> testSelectors() {
+ final String selector = "@p";
+
+ return List.of(
+ selector(selector),
+ selector(selector, text(','))
+ );
+ }
+
+ static List<Component> testBlockNbts() {
+ return List.of(
+ blockNBT().nbtPath("abc").localPos(1.23d, 2.0d, 3.89d).build(),
+ blockNBT().nbtPath("xyz").absoluteWorldPos(4, 5, 6).interpret(true).build(),
+ blockNBT().nbtPath("eeee").relativeWorldPos(7, 83, 900)
+ .separator(text(';'))
+ .build(),
+ blockNBT().nbtPath("qwert").worldPos(
+ BlockNBTComponent.WorldPos.Coordinate.absolute(12),
+ BlockNBTComponent.WorldPos.Coordinate.relative(3),
+ BlockNBTComponent.WorldPos.Coordinate.absolute(1200)
+ ).build()
+ );
+ }
+
+ static List<Component> testEntityNbts() {
+ return List.of(
+ entityNBT().nbtPath("abc").selector("test").build(),
+ entityNBT().nbtPath("abc").selector("test").separator(text(',')).build(),
+ entityNBT().nbtPath("abc").selector("test").interpret(true).build()
+ );
+ }
+
+ static List<Component> testStorageNbts() {
+ return List.of(
+ storageNBT().nbtPath("abc").storage(key("doom:apple")).build(),
+ storageNBT().nbtPath("abc").storage(key("doom:apple")).separator(text(", ")).build(),
+ storageNBT().nbtPath("abc").storage(key("doom:apple")).interpret(true).build()
+ );
+ }
+}
2022-05-26 21:12:14 +02:00
diff --git a/src/test/java/io/papermc/paper/adventure/ComponentServicesTest.java b/src/test/java/io/papermc/paper/adventure/ComponentServicesTest.java
new file mode 100644
2023-09-24 09:16:58 +02:00
index 0000000000000000000000000000000000000000..98114b8fdc441f2a1642abf230457c2b5208bb5c
2022-05-26 21:12:14 +02:00
--- /dev/null
+++ b/src/test/java/io/papermc/paper/adventure/ComponentServicesTest.java
@@ -0,0 +1,23 @@
+package io.papermc.paper.adventure;
+
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
2023-09-24 09:16:58 +02:00
+import org.junit.jupiter.api.Test;
2022-05-26 21:12:14 +02:00
+
2023-09-24 09:16:58 +02:00
+import static org.junit.jupiter.api.Assertions.assertEquals;
2022-05-26 21:12:14 +02:00
+
+public class ComponentServicesTest {
+
+ @Test
+ public void testPlainTextComponentSerializerProvider() {
+ assertEquals("Done", PlainTextComponentSerializer.plainText().serialize(Component.translatable("narrator.loading.done")));
+ }
+
+ @Test
+ public void testLegacyComponentSerializerProvider() {
+ assertEquals("§cDone", LegacyComponentSerializer.legacySection().serialize(Component.translatable("narrator.loading.done", NamedTextColor.RED)));
+ assertEquals("&cDone", LegacyComponentSerializer.legacyAmpersand().serialize(Component.translatable("narrator.loading.done", NamedTextColor.RED)));
+ }
+}
2024-04-27 03:16:31 +02:00
diff --git a/src/test/java/io/papermc/paper/util/MethodParameterSource.java b/src/test/java/io/papermc/paper/util/MethodParameterSource.java
index 6cbf11c898439834cffb99ef84e5df1494356809..381668df2f58df82ac6da85796752934e92d0796 100644
--- a/src/test/java/io/papermc/paper/util/MethodParameterSource.java
+++ b/src/test/java/io/papermc/paper/util/MethodParameterSource.java
@@ -4,11 +4,13 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
+import org.intellij.lang.annotations.Language;
import org.junitpioneer.jupiter.cartesian.CartesianArgumentsSource;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@CartesianArgumentsSource(MethodParameterProvider.class)
public @interface MethodParameterSource {
+ @Language("jvm-method-name")
String[] value() default {};
}