Search in sources :

Example 1 with MutableComponent

use of net.minecraft.network.chat.MutableComponent in project Denizen-For-Bukkit by DenizenScript.

the class SidebarImpl method setDisplayName.

@Override
protected void setDisplayName(String title) {
    if (this.obj1 != null) {
        MutableComponent chatComponentTitle = Handler.componentToNMS(FormattedTextHelper.parse(title, ChatColor.WHITE));
        this.obj1.setDisplayName(chatComponentTitle);
        this.obj2.setDisplayName(chatComponentTitle);
    }
}
Also used : MutableComponent(net.minecraft.network.chat.MutableComponent)

Example 2 with MutableComponent

use of net.minecraft.network.chat.MutableComponent in project SpongeCommon by SpongePowered.

the class MetadataPanel method newChatWithLinks.

/*
     * Credit: MinecraftForge
     * Changes: Set ichat to link if ichat is null
     */
public static Component newChatWithLinks(final String string, final boolean allowMissingHeader) {
    // Includes ipv4 and domain pattern
    // Matches an ip (xx.xxx.xx.xxx) or a domain (something.com) with or
    // without a protocol or path.
    MutableComponent ichat = null;
    final Matcher matcher = MetadataPanel.URL_PATTERN.matcher(string);
    int lastEnd = 0;
    // Find all urls
    while (matcher.find()) {
        final int start = matcher.start();
        final int end = matcher.end();
        // Append the previous left overs.
        final String part = string.substring(lastEnd, start);
        if (part.length() > 0) {
            if (ichat == null) {
                ichat = new TextComponent(part);
            } else {
                ichat.append(part);
            }
        }
        lastEnd = end;
        String url = string.substring(start, end);
        final MutableComponent link = new TextComponent(url);
        try {
            // Add schema so client doesn't crash.
            if ((new URI(url)).getScheme() == null) {
                if (!allowMissingHeader) {
                    if (ichat == null) {
                        ichat = new TextComponent(url);
                    } else {
                        ichat.append(url);
                    }
                    continue;
                }
                url = "http://" + url;
            }
        } catch (final URISyntaxException e) {
            // Bad syntax bail out!
            if (ichat == null) {
                ichat = new TextComponent(url);
            } else {
                ichat.append(url);
            }
            continue;
        }
        // Set the click event and append the link.
        final ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_URL, url);
        link.withStyle(style -> style.withClickEvent(click).withUnderlined(true).withColor(ChatFormatting.BLUE));
        ichat = ichat == null ? link : ichat.append(link);
    }
    // Append the rest of the message.
    final String end = string.substring(lastEnd);
    if (ichat == null) {
        ichat = new TextComponent(end);
    } else if (end.length() > 0) {
        ichat.append(string.substring(lastEnd));
    }
    return ichat;
}
Also used : TextComponent(net.minecraft.network.chat.TextComponent) MutableComponent(net.minecraft.network.chat.MutableComponent) Matcher(java.util.regex.Matcher) ClickEvent(net.minecraft.network.chat.ClickEvent) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 3 with MutableComponent

use of net.minecraft.network.chat.MutableComponent in project SpongeCommon by SpongePowered.

the class NativeComponentRenderer method renderTranslatable.

@NonNull
protected MutableComponent renderTranslatable(@NonNull final TranslatableComponent component, @NonNull final C context) {
    final MessageFormat /* @Nullable */
    format = this.translate(component.getKey(), context);
    if (format == null) {
        // we don't have a translation for this component, but the arguments or children
        // of this component might need additional rendering
        final Object[] args = component.getArgs();
        if (args.length > 0) {
            for (int i = 0, size = args.length; i < size; i++) {
                if (args[i] instanceof Component) {
                    args[i] = this.render(((Component) args[i]).copy(), context);
                }
            }
        }
        this.renderSiblings(component, context);
        return component;
    }
    final Object[] args = component.getArgs();
    final TextComponent result;
    // no arguments makes this render very simple
    if (args.length == 0) {
        result = new TextComponent(format.format(null, new StringBuffer(), null).toString());
    } else {
        result = new TextComponent("");
        final Object[] nulls = new Object[args.length];
        final StringBuffer sb = format.format(nulls, new StringBuffer(), null);
        final AttributedCharacterIterator it = format.formatToCharacterIterator(nulls);
        while (it.getIndex() < it.getEndIndex()) {
            final int end = it.getRunLimit();
            final Integer index = (Integer) it.getAttribute(MessageFormat.Field.ARGUMENT);
            if (index != null && args[index] instanceof Component) {
                result.append(this.render(((Component) args[index]).copy(), context));
            } else {
                result.append(new TextComponent(sb.substring(it.getIndex(), end)));
            }
            it.setIndex(end);
        }
    }
    result.setStyle(component.getStyle());
    this.renderSiblings(component, context, (idx, rendered) -> result.append(rendered));
    return result;
}
Also used : TextComponent(net.minecraft.network.chat.TextComponent) MessageFormat(java.text.MessageFormat) Component(net.minecraft.network.chat.Component) MutableComponent(net.minecraft.network.chat.MutableComponent) TextComponent(net.minecraft.network.chat.TextComponent) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) AttributedCharacterIterator(java.text.AttributedCharacterIterator) NonNull(org.checkerframework.checker.nullness.qual.NonNull)

Example 4 with MutableComponent

use of net.minecraft.network.chat.MutableComponent in project SpongeCommon by SpongePowered.

the class PlayerListMixin method impl$canPlayerLoginServer.

protected final CompletableFuture<net.minecraft.network.chat.Component> impl$canPlayerLoginServer(final SocketAddress param0, final com.mojang.authlib.GameProfile param1) {
    final SpongeGameProfile profile = SpongeGameProfile.basicOf(param1);
    return Sponge.server().serviceProvider().banService().find(profile).thenCompose(profileBanOpt -> {
        if (profileBanOpt.isPresent()) {
            final Ban.Profile var0 = profileBanOpt.get();
            final MutableComponent var1 = new TranslatableComponent("multiplayer.disconnect.banned.reason", var0.reason().orElse(Component.empty()));
            if (var0.expirationDate().isPresent()) {
                var1.append(new TranslatableComponent("multiplayer.disconnect.banned.expiration", BAN_DATE_FORMAT.format(var0.expirationDate().get())));
            }
            return CompletableFuture.completedFuture(var1);
        }
        if (param0 instanceof LocalAddress) {
            // don't bother looking up IP bans on local address
            return CompletableFuture.completedFuture(null);
        }
        final InetAddress address;
        try {
            address = InetAddress.getByName(NetworkUtil.getHostString(param0));
        } catch (final UnknownHostException ex) {
            // no
            return CompletableFuture.completedFuture(new TextComponent(ex.getMessage()));
        }
        return Sponge.server().serviceProvider().banService().find(address).thenCompose(ipBanOpt -> {
            if (ipBanOpt.isPresent()) {
                final Ban.IP var2 = ipBanOpt.get();
                final MutableComponent var3 = new TranslatableComponent("multiplayer.disconnect.banned_ip.reason", var2.reason().orElse(Component.empty()));
                if (var2.expirationDate().isPresent()) {
                    var3.append(new TranslatableComponent("multiplayer.disconnect.banned_ip.expiration", BAN_DATE_FORMAT.format(var2.expirationDate().get())));
                }
                return CompletableFuture.completedFuture(var3);
            }
            return CompletableFuture.supplyAsync(() -> {
                if (!Sponge.server().isWhitelistEnabled()) {
                    return true;
                }
                final PermissionService permissionService = Sponge.server().serviceProvider().permissionService();
                Subject subject = permissionService.userSubjects().subject(param1.getId().toString()).orElse(null);
                if (subject == null) {
                    subject = permissionService.defaults();
                }
                return subject.hasPermission(LoginPermissions.BYPASS_WHITELIST_PERMISSION);
            }, SpongeCommon.server()).thenCompose(w -> {
                if (w) {
                    return CompletableFuture.completedFuture(null);
                }
                return Sponge.server().serviceProvider().whitelistService().isWhitelisted(profile).<net.minecraft.network.chat.Component>thenApply(whitelisted -> {
                    if (!whitelisted) {
                        return new TranslatableComponent("multiplayer.disconnect.not_whitelisted");
                    }
                    return null;
                });
            });
        });
    }).thenApplyAsync(component -> {
        if (component != null) {
            return component;
        }
        if (this.players.size() >= this.maxPlayers && !this.shadow$canBypassPlayerLimit(param1)) {
            return new TranslatableComponent("multiplayer.disconnect.server_full");
        }
        return null;
    }, SpongeCommon.server());
}
Also used : ServerLevelBridge(org.spongepowered.common.bridge.server.level.ServerLevelBridge) ConnectionBridge(org.spongepowered.common.bridge.network.ConnectionBridge) SpongeUserBanList(org.spongepowered.common.service.server.ban.SpongeUserBanList) ServerSideConnectionEvent(org.spongepowered.api.event.network.ServerSideConnectionEvent) Inject(org.spongepowered.asm.mixin.injection.Inject) Connection(net.minecraft.network.Connection) SpongeAdventure(org.spongepowered.common.adventure.SpongeAdventure) PermissionService(org.spongepowered.api.service.permission.PermissionService) PlayerList(net.minecraft.server.players.PlayerList) LocalAddress(io.netty.channel.local.LocalAddress) InetAddress(java.net.InetAddress) MinecraftServer(net.minecraft.server.MinecraftServer) IntegratedPlayerListBridge(org.spongepowered.common.bridge.client.server.IntegratedPlayerListBridge) ClientboundPlayerInfoPacketAccessor(org.spongepowered.common.accessor.network.protocol.game.ClientboundPlayerInfoPacketAccessor) Mixin(org.spongepowered.asm.mixin.Mixin) Map(java.util.Map) GameProfile(org.spongepowered.api.profile.GameProfile) PlayerInventoryTransaction(org.spongepowered.common.event.tracking.context.transaction.inventory.PlayerInventoryTransaction) ServerPlayerBridge(org.spongepowered.common.bridge.server.level.ServerPlayerBridge) ServerScoreboardBridge(org.spongepowered.common.bridge.server.ServerScoreboardBridge) PlayerListBridge(org.spongepowered.common.bridge.server.players.PlayerListBridge) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) IpBanList(net.minecraft.server.players.IpBanList) ClientboundPlayerInfoPacket(net.minecraft.network.protocol.game.ClientboundPlayerInfoPacket) Set(java.util.Set) RegistryAccess(net.minecraft.core.RegistryAccess) TextComponent(net.minecraft.network.chat.TextComponent) Logger(org.apache.logging.log4j.Logger) BroadcastInventoryChangesEffect(org.spongepowered.common.event.tracking.context.transaction.effect.BroadcastInventoryChangesEffect) SpongeUserView(org.spongepowered.common.entity.player.SpongeUserView) Shadow(org.spongepowered.asm.mixin.Shadow) Packet(net.minecraft.network.protocol.Packet) GameType(net.minecraft.world.level.GameType) ServerLocation(org.spongepowered.api.world.server.ServerLocation) ServerSideConnection(org.spongepowered.api.network.ServerSideConnection) Ban(org.spongepowered.api.service.ban.Ban) SimpleDateFormat(java.text.SimpleDateFormat) PrimaryLevelDataBridge(org.spongepowered.common.bridge.world.level.storage.PrimaryLevelDataBridge) MutableComponent(net.minecraft.network.chat.MutableComponent) UserBanList(net.minecraft.server.players.UserBanList) ServerScoreboard(net.minecraft.server.ServerScoreboard) SpongeIPBanList(org.spongepowered.common.service.server.ban.SpongeIPBanList) PerWorldBorderListener(org.spongepowered.common.server.PerWorldBorderListener) Nullable(javax.annotation.Nullable) Opcodes(org.objectweb.asm.Opcodes) Identity(net.kyori.adventure.identity.Identity) Redirect(org.spongepowered.asm.mixin.injection.Redirect) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) PhaseTracker(org.spongepowered.common.event.tracking.PhaseTracker) UnknownHostException(java.net.UnknownHostException) Cause(org.spongepowered.api.event.Cause) Audience(net.kyori.adventure.audience.Audience) LoginPermissions(org.spongepowered.common.entity.player.LoginPermissions) VecHelper(org.spongepowered.common.util.VecHelper) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) SocketAddress(java.net.SocketAddress) SpongeServer(org.spongepowered.common.SpongeServer) RespawnPlayerEvent(org.spongepowered.api.event.entity.living.player.RespawnPlayerEvent) EffectTransactor(org.spongepowered.common.event.tracking.context.transaction.EffectTransactor) EventContext(org.spongepowered.api.event.EventContext) CallbackInfoReturnable(org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable) SpongeGameProfile(org.spongepowered.common.profile.SpongeGameProfile) CallbackInfo(org.spongepowered.asm.mixin.injection.callback.CallbackInfo) SpongeUserWhiteList(org.spongepowered.common.service.server.whitelist.SpongeUserWhiteList) TransactionalCaptureSupplier(org.spongepowered.common.event.tracking.context.transaction.TransactionalCaptureSupplier) Subject(org.spongepowered.api.service.permission.Subject) At(org.spongepowered.asm.mixin.injection.At) User(org.spongepowered.api.entity.living.player.User) NetworkUtil(org.spongepowered.common.util.NetworkUtil) Sponge(org.spongepowered.api.Sponge) ChatType(net.minecraft.network.chat.ChatType) UUID(java.util.UUID) Final(org.spongepowered.asm.mixin.Final) Instant(java.time.Instant) ClientboundDisconnectPacket(net.minecraft.network.protocol.game.ClientboundDisconnectPacket) List(java.util.List) CompoundTag(net.minecraft.nbt.CompoundTag) BlockPos(net.minecraft.core.BlockPos) PhaseContext(org.spongepowered.common.event.tracking.PhaseContext) Optional(java.util.Optional) ClientboundRespawnPacketAccessor(org.spongepowered.common.accessor.network.protocol.game.ClientboundRespawnPacketAccessor) Level(net.minecraft.world.level.Level) UserWhiteList(net.minecraft.server.players.UserWhiteList) Constants(org.spongepowered.common.util.Constants) CustomBossEvents(net.minecraft.server.bossevents.CustomBossEvents) CompletableFuture(java.util.concurrent.CompletableFuture) DimensionType(net.minecraft.world.level.dimension.DimensionType) ServerLevel(net.minecraft.server.level.ServerLevel) WorldBorder(net.minecraft.world.level.border.WorldBorder) Component(net.kyori.adventure.text.Component) BorderChangeListener(net.minecraft.world.level.border.BorderChangeListener) Audiences(org.spongepowered.api.adventure.Audiences) Mutable(org.spongepowered.asm.mixin.Mutable) VanishableBridge(org.spongepowered.common.bridge.data.VanishableBridge) SpongeCommon(org.spongepowered.common.SpongeCommon) ClientboundLoginPacket(net.minecraft.network.protocol.game.ClientboundLoginPacket) ResourceKey(net.minecraft.resources.ResourceKey) ServerGamePacketListenerImpl(net.minecraft.server.network.ServerGamePacketListenerImpl) Vector3d(org.spongepowered.math.vector.Vector3d) Slice(org.spongepowered.asm.mixin.injection.Slice) TextComponent(net.minecraft.network.chat.TextComponent) LocalAddress(io.netty.channel.local.LocalAddress) UnknownHostException(java.net.UnknownHostException) GameProfile(org.spongepowered.api.profile.GameProfile) SpongeGameProfile(org.spongepowered.common.profile.SpongeGameProfile) Subject(org.spongepowered.api.service.permission.Subject) PermissionService(org.spongepowered.api.service.permission.PermissionService) MutableComponent(net.minecraft.network.chat.MutableComponent) TranslatableComponent(net.minecraft.network.chat.TranslatableComponent) SpongeGameProfile(org.spongepowered.common.profile.SpongeGameProfile) InetAddress(java.net.InetAddress)

Example 5 with MutableComponent

use of net.minecraft.network.chat.MutableComponent in project SpongeCommon by SpongePowered.

the class ChatFormatter method format.

@Nullable
public static Component format(final String s) {
    final Matcher matcher = ChatFormatter.URL_PATTERN.matcher(s);
    if (!matcher.find()) {
        return null;
    }
    MutableComponent result = null;
    int pos = 0;
    do {
        final int start = matcher.start();
        final int end = matcher.end();
        final String displayUrl = s.substring(start, end);
        String url = displayUrl;
        try {
            if (new URI(url).getScheme() == null) {
                url = ChatFormatter.DEFAULT_SCHEME + url;
            }
        } catch (final URISyntaxException e) {
            // Invalid URL so just ignore it
            continue;
        }
        if (pos < start) {
            if (result == null) {
                result = new TextComponent(s.substring(pos, start));
            } else {
                result.append(s.substring(pos, start));
            }
        }
        pos = end;
        final MutableComponent link = new TextComponent(displayUrl);
        link.setStyle(link.getStyle().withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url)));
        if (result == null) {
            result = new TextComponent("");
        }
        result.append(link);
    } while (matcher.find());
    // If there is something left, append the rest
    if (pos < s.length()) {
        if (result == null) {
            result = new TextComponent(s.substring(pos));
        } else {
            result.append(s.substring(pos));
        }
    }
    return result;
}
Also used : TextComponent(net.minecraft.network.chat.TextComponent) MutableComponent(net.minecraft.network.chat.MutableComponent) Matcher(java.util.regex.Matcher) ClickEvent(net.minecraft.network.chat.ClickEvent) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Nullable(javax.annotation.Nullable)

Aggregations

MutableComponent (net.minecraft.network.chat.MutableComponent)6 TextComponent (net.minecraft.network.chat.TextComponent)4 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 Matcher (java.util.regex.Matcher)2 Nullable (javax.annotation.Nullable)2 ClickEvent (net.minecraft.network.chat.ClickEvent)2 TranslatableComponent (net.minecraft.network.chat.TranslatableComponent)2 LocalAddress (io.netty.channel.local.LocalAddress)1 InetAddress (java.net.InetAddress)1 SocketAddress (java.net.SocketAddress)1 UnknownHostException (java.net.UnknownHostException)1 AttributedCharacterIterator (java.text.AttributedCharacterIterator)1 MessageFormat (java.text.MessageFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Instant (java.time.Instant)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Set (java.util.Set)1