Search in sources :

Example 6 with ClickEvent

use of net.minecraft.text.ClickEvent in project Client by MatHax.

the class BookBot method onTick.

@EventHandler
private void onTick(TickEvent.Post event) {
    FindItemResult writableBook = InvUtils.find(Items.WRITABLE_BOOK);
    // Check if there is a book to write
    if (!writableBook.found()) {
        toggle();
        return;
    }
    // Move the book into hand
    if (!writableBook.isMainHand()) {
        InvUtils.move().from(writableBook.slot()).toHotbar(mc.player.getInventory().selectedSlot);
        return;
    }
    // If somehow it failed, just dont do anything until it tries again
    FindItemResult finalBook = InvUtils.findInHotbar(Items.WRITABLE_BOOK);
    if (!finalBook.isMainHand())
        return;
    // Check delay
    if (delayTimer > 0) {
        delayTimer--;
        return;
    }
    // Reset delay
    delayTimer = delay.get();
    if (mode.get() == Mode.Random) {
        int origin = onlyAscii.get() ? 0x21 : 0x0800;
        int bound = onlyAscii.get() ? 0x7E : 0x10FFFF;
        writeBook(// Generate a random load of ints to use as random characters
        random.ints(origin, bound).filter(i -> !Character.isWhitespace(i) && i != '\r' && i != '\n').iterator());
    } else if (mode.get() == Mode.File) {
        // Ignore if somehow the file got deleted
        if ((file == null || !file.exists()) && mode.get() == Mode.File) {
            info("No file selected, please select a file in the GUI.");
            toggle();
            return;
        }
        // Handle the file being empty
        if (file.length() == 0) {
            MutableText message = new LiteralText("");
            message.append(new LiteralText("The bookbot file is empty! ").formatted(Formatting.RED));
            message.append(new LiteralText("Click here to edit it.").setStyle(Style.EMPTY.withFormatting(Formatting.UNDERLINE, Formatting.RED).withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, file.getAbsolutePath()))));
            info(message);
            toggle();
            return;
        }
        // Read each line of the file and construct a string with the needed line breaks
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder file = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                file.append(line).append('\n');
            }
            reader.close();
            // Write the file string to a book
            writeBook(file.toString().chars().iterator());
        } catch (IOException ignored) {
            error("Failed to read the file.");
        }
    }
}
Also used : MutableText(net.minecraft.text.MutableText) ClickEvent(net.minecraft.text.ClickEvent) FindItemResult(mathax.client.utils.player.FindItemResult) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) NbtString(net.minecraft.nbt.NbtString) IOException(java.io.IOException) LiteralText(net.minecraft.text.LiteralText) EventHandler(mathax.client.eventbus.EventHandler)

Example 7 with ClickEvent

use of net.minecraft.text.ClickEvent in project Client by MatHax.

the class CommandsCommand method getCommandText.

private BaseText getCommandText(Command command) {
    // Hover tooltip
    BaseText tooltip = new LiteralText("");
    tooltip.append(new LiteralText(Utils.nameToTitle(command.getName())).formatted(Formatting.BLUE, Formatting.BOLD)).append("\n");
    BaseText aliases = new LiteralText(Config.get().prefix + command.getName());
    if (command.getAliases().size() > 0) {
        aliases.append(", ");
        for (String alias : command.getAliases()) {
            if (alias.isEmpty())
                continue;
            aliases.append(Config.get().prefix + alias);
            if (!alias.equals(command.getAliases().get(command.getAliases().size() - 1)))
                aliases.append(", ");
        }
    }
    tooltip.append(aliases.formatted(Formatting.GRAY)).append("\n\n");
    tooltip.append(new LiteralText(command.getDescription()).formatted(Formatting.WHITE));
    // Text
    BaseText text = new LiteralText(Utils.nameToTitle(command.getName()));
    if (command != Commands.get().getAll().get(Commands.get().getAll().size() - 1))
        text.append(new LiteralText(", ").formatted(Formatting.GRAY));
    text.setStyle(text.getStyle().withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, tooltip)).withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, Config.get().prefix + command.getName())));
    return text;
}
Also used : BaseText(net.minecraft.text.BaseText) HoverEvent(net.minecraft.text.HoverEvent) ClickEvent(net.minecraft.text.ClickEvent) LiteralText(net.minecraft.text.LiteralText)

Example 8 with ClickEvent

use of net.minecraft.text.ClickEvent in project mclogs-fabric by aternosorg.

the class CommandMclogsList method register.

static void register(CommandDispatcher<ServerCommandSource> dispatcher) {
    dispatcher.register(literal("mclogs").then(literal("list").requires(source -> source.hasPermissionLevel(2)).executes((context) -> {
        ServerCommandSource source = context.getSource();
        try {
            String[] logs = MclogsFabricLoader.getLogs(context);
            if (logs.length == 0) {
                source.sendFeedback(new LiteralText("No logs available!"), false);
                return 0;
            }
            LiteralText feedback = new LiteralText("Available Logs:");
            for (String log : logs) {
                Style s = Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/mclogs share " + log));
                LiteralText tempText = new LiteralText("\n" + log);
                tempText.setStyle(s);
                feedback.append(tempText);
            }
            source.sendFeedback(feedback, false);
            return logs.length;
        } catch (Exception e) {
            MclogsFabricLoader.logger.error("An error occurred when listing your logs.");
            MclogsFabricLoader.logger.error(e);
            LiteralText error = new LiteralText("An error occurred. Check your log for more details.");
            source.sendError(error);
            return -1;
        }
    })));
}
Also used : LiteralText(net.minecraft.text.LiteralText) Style(net.minecraft.text.Style) CommandDispatcher(com.mojang.brigadier.CommandDispatcher) ServerCommandSource(net.minecraft.server.command.ServerCommandSource) ClickEvent(net.minecraft.text.ClickEvent) CommandManager.literal(net.minecraft.server.command.CommandManager.literal) ClickEvent(net.minecraft.text.ClickEvent) Style(net.minecraft.text.Style) ServerCommandSource(net.minecraft.server.command.ServerCommandSource) LiteralText(net.minecraft.text.LiteralText)

Example 9 with ClickEvent

use of net.minecraft.text.ClickEvent in project mclogs-fabric by aternosorg.

the class MclogsFabricLoader method share.

public static int share(ServerCommandSource source, String filename) {
    MclogsAPI.mcversion = source.getMinecraftServer().getVersion();
    logger.log(Level.INFO, "Sharing " + filename);
    source.sendFeedback(new LiteralText("Sharing " + filename), false);
    try {
        Path logs = source.getMinecraftServer().getFile("logs/").toPath();
        Path log = logs.resolve(filename);
        if (!log.getParent().equals(logs)) {
            throw new FileNotFoundException();
        }
        APIResponse response = MclogsAPI.share(log);
        if (response.success) {
            LiteralText feedback = new LiteralText("Your log has been uploaded: ");
            feedback.setStyle(Style.EMPTY.withColor(Formatting.GREEN));
            LiteralText link = new LiteralText(response.url);
            Style linkStyle = Style.EMPTY.withColor(Formatting.BLUE);
            linkStyle = linkStyle.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, response.url));
            link.setStyle(linkStyle);
            source.sendFeedback(feedback.append(link), true);
            return 1;
        } else {
            logger.error("An error occurred when uploading your log: ");
            logger.error(response.error);
            LiteralText error = new LiteralText("An error occurred. Check your log for more details");
            source.sendError(error);
            return 0;
        }
    } catch (FileNotFoundException | IllegalArgumentException e) {
        LiteralText error = new LiteralText("The log file " + filename + " doesn't exist. Use '/mclogs list' to list all logs.");
        source.sendError(error);
        return -1;
    } catch (IOException e) {
        source.sendError(new LiteralText("An error occurred. Check your log for more details"));
        logger.error("Could not get log file!");
        logger.error(e);
        return 0;
    }
}
Also used : Path(java.nio.file.Path) APIResponse(gs.mclo.java.APIResponse) ClickEvent(net.minecraft.text.ClickEvent) FileNotFoundException(java.io.FileNotFoundException) Style(net.minecraft.text.Style) IOException(java.io.IOException) LiteralText(net.minecraft.text.LiteralText)

Example 10 with ClickEvent

use of net.minecraft.text.ClickEvent in project Carrier by GabrielOlvH.

the class Carrier method onInitialize.

@Override
public void onInitialize() {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    File file = new File(FabricLoader.getInstance().getConfigDir().toFile(), "carrier.json");
    if (!file.exists()) {
        try {
            if (!file.createNewFile())
                throw new IOException("Failed to create file");
            FileUtils.write(file, gson.toJson(CONFIG), StandardCharsets.UTF_8);
        } catch (IOException e) {
            LogManager.getLogger("Carrier").error("Failed to create carrier config");
            throw new RuntimeException(e);
        }
    } else {
        try {
            String lines = String.join("\n", FileUtils.readLines(file, StandardCharsets.UTF_8));
            CONFIG = gson.fromJson(lines, Config.class);
        } catch (IOException e) {
            LogManager.getLogger("Carrier").error("Failed to read config");
            throw new RuntimeException(e);
        }
    }
    ServerTickEvents.END_WORLD_TICK.register(new ServerWorldTickCallback());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_cow"), new CarriableCow());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_chicken"), new CarriableChicken());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_parrot"), new CarriableParrot());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_pig"), new CarriablePig());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_rabbit"), new CarriableRabbit());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_sheep"), new CarriableSheep());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_turtle"), new CarriableTurtle());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_wolf"), new CarriableWolf());
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_spawner"), new CarriableSpawner(new Identifier(MOD_ID, "minecraft_spawner")));
    CarriableRegistry.INSTANCE.register(new Identifier(MOD_ID, "minecraft_enchanting_table"), new CarriableEnchantingTable(new Identifier(MOD_ID, "minecraft_enchanting_table")));
    Registry.BLOCK.forEach((block) -> {
        Identifier id = Registry.BLOCK.getId(block);
        Identifier type = new Identifier("carrier", id.getNamespace() + "_" + id.getPath());
        registerGenericCarriable(block, type);
    });
    RegistryEntryAddedCallback.event(Registry.BLOCK).register((rawId, id, block) -> {
        Identifier type = new Identifier("carrier", id.getNamespace() + "_" + id.getPath());
        registerGenericCarriable(block, type);
    });
    Registry.register(Registry.ITEM, new Identifier(MOD_ID, "glove"), ITEM_GLOVE);
    if (CONFIG.doGlovesExist()) {
        RuntimeResourcePack resourcePack = RuntimeResourcePack.create(MOD_ID + ":gloves");
        resourcePack.addRecipe(new Identifier(MOD_ID, "gloves"), JRecipe.shaped(JPattern.pattern("L  ", "LL "), JKeys.keys().key("L", JIngredient.ingredient().item("minecraft:leather")), JResult.item(ITEM_GLOVE)));
        RRPCallback.EVENT.register(packs -> packs.add(resourcePack));
    }
    ServerSidePacketRegistry.INSTANCE.register(SET_CAN_CARRY_PACKET, (ctx, buf) -> {
        boolean canCarry = buf.readBoolean();
        ctx.getTaskQueue().execute(() -> ((CarrierPlayerExtension) ctx.getPlayer()).setCanCarry(canCarry));
    });
    CommandRegistrationCallback.EVENT.register((commandDispatcher, b) -> commandDispatcher.register(CommandManager.literal("carrierinfo").executes((ctx) -> {
        ServerPlayerEntity player = ctx.getSource().getPlayer();
        NbtCompound tag = new NbtCompound();
        HOLDER.get(player).writeToNbt(tag);
        ctx.getSource().sendFeedback(new LiteralText(tag.toString()), false);
        return 1;
    })));
    CommandRegistrationCallback.EVENT.register((commandDispatcher, b) -> commandDispatcher.register(CommandManager.literal("carrierdelete").executes((ctx) -> {
        ServerPlayerEntity player = ctx.getSource().getPlayer();
        CarrierComponent component = HOLDER.get(player);
        NbtCompound tag = new NbtCompound();
        component.writeToNbt(tag);
        component.setCarryingData(null);
        ctx.getSource().sendFeedback(new LiteralText("Deleted ").append(new LiteralText(tag.toString()).setStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, tag.toString())))), false);
        return 1;
    })));
    CommandRegistrationCallback.EVENT.register((commandDispatcher, b) -> commandDispatcher.register(CommandManager.literal("carrierplace").executes((ctx) -> {
        ServerPlayerEntity player = ctx.getSource().getPlayer();
        CarrierComponent component = HOLDER.get(player);
        Carriable<Object> carriable = CarriableRegistry.INSTANCE.get(component.getCarryingData().getType());
        BlockPos pos = player.getBlockPos().offset(player.getHorizontalFacing());
        ServerWorld world = ctx.getSource().getWorld();
        if (!world.getBlockState(pos).getMaterial().isReplaceable()) {
            ctx.getSource().sendFeedback(new LiteralText("Could not place! Make sure you have empty space in front of you."), false);
            return 1;
        }
        CarriablePlacementContext placementCtx = new CarriablePlacementContext(component, carriable, pos, player.getHorizontalFacing().getOpposite(), player.getHorizontalFacing());
        carriable.tryPlace(component, world, placementCtx);
        component.setCarryingData(null);
        return 1;
    })));
}
Also used : NbtCompound(net.minecraft.nbt.NbtCompound) ClickEvent(net.minecraft.text.ClickEvent) Gson(com.google.gson.Gson) RuntimeResourcePack(net.devtech.arrp.api.RuntimeResourcePack) ServerWorld(net.minecraft.server.world.ServerWorld) Identifier(net.minecraft.util.Identifier) BlockPos(net.minecraft.util.math.BlockPos) LiteralText(net.minecraft.text.LiteralText) GsonBuilder(com.google.gson.GsonBuilder) ServerPlayerEntity(net.minecraft.server.network.ServerPlayerEntity) IOException(java.io.IOException) File(java.io.File)

Aggregations

ClickEvent (net.minecraft.text.ClickEvent)23 LiteralText (net.minecraft.text.LiteralText)23 HoverEvent (net.minecraft.text.HoverEvent)16 MutableText (net.minecraft.text.MutableText)8 BaseText (net.minecraft.text.BaseText)6 ItemStack (net.minecraft.item.ItemStack)5 NbtCompound (net.minecraft.nbt.NbtCompound)5 Formatting (net.minecraft.util.Formatting)5 IntegerArgumentType (com.mojang.brigadier.arguments.IntegerArgumentType)4 IOException (java.io.IOException)4 CommandSource (net.minecraft.command.CommandSource)4 ServerPlayerEntity (net.minecraft.server.network.ServerPlayerEntity)4 Style (net.minecraft.text.Style)4 CommandDispatcher (com.mojang.brigadier.CommandDispatcher)3 LiteralArgumentBuilder (com.mojang.brigadier.builder.LiteralArgumentBuilder)3 CommandContext (com.mojang.brigadier.context.CommandContext)3 NbtPathArgumentType (net.minecraft.command.argument.NbtPathArgumentType)3 CreativeInventoryActionC2SPacket (net.minecraft.network.packet.c2s.play.CreativeInventoryActionC2SPacket)3 CommandManager.literal (net.minecraft.server.command.CommandManager.literal)3 ServerCommandSource (net.minecraft.server.command.ServerCommandSource)3