net.minecraft.util.text.ITextComponent Java Examples

The following examples show how to use net.minecraft.util.text.ITextComponent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiblockWithDisplayBase.java    From GregTech with GNU Lesser General Public License v3.0 7 votes vote down vote up
/**
 * Called serverside to obtain text displayed in GUI
 * each element of list is displayed on new line
 * to use translation, use TextComponentTranslation
 */
protected void addDisplayText(List<ITextComponent> textList) {
    if (!isStructureFormed()) {
        ITextComponent tooltip = new TextComponentTranslation("gregtech.multiblock.invalid_structure.tooltip");
        tooltip.setStyle(new Style().setColor(TextFormatting.GRAY));
        textList.add(new TextComponentTranslation("gregtech.multiblock.invalid_structure")
            .setStyle(new Style().setColor(TextFormatting.RED)
                .setHoverEvent(new HoverEvent(Action.SHOW_TEXT, tooltip))));
    }
}
 
Example #2
Source File: GuiCustomizeWorld.java    From YUNoMakeGoodMap with Apache License 2.0 6 votes vote down vote up
private List<ITextComponent> resizeContent(List<String> lines)
{
    List<ITextComponent> ret = new ArrayList<ITextComponent>();
    for (String line : lines)
    {
        if (line == null)
        {
            ret.add(null);
            continue;
        }

        ITextComponent chat = ForgeHooks.newChatWithLinks(line, false);
        ret.addAll(GuiUtilRenderComponents.splitText(chat, this.listWidth-8, GuiCustomizeWorld.this.fontRenderer, false, true));
    }
    return ret;
}
 
Example #3
Source File: AutoReconnectMod.java    From ForgeHax with MIT License 6 votes vote down vote up
public GuiDisconnectedOverride(
    GuiScreen screen,
    String reasonLocalizationKey,
    ITextComponent chatComp,
    String reason,
    double delay) {
  super(screen, reasonLocalizationKey, chatComp);
  parent = screen;
  message = chatComp;
  reconnectTime = System.currentTimeMillis() + (long) (delay * 1000);
  // set variable 'reason' to the previous classes value
  try {
    ReflectionHelper.setPrivateValue(
        GuiDisconnected.class,
        this,
        reason,
        "reason",
        "field_146306_a",
        "a"); // TODO: Find obbed mapping name
  } catch (Exception e) {
    Helper.printStackTrace(e);
  }
  // parse server return text and find queue pos
}
 
Example #4
Source File: ClientPacketHandler.java    From CodeChickenLib with GNU Lesser General Public License v2.1 6 votes vote down vote up
@SuppressWarnings ("unchecked")
private void handleOpenContainer(PacketCustom packet, Minecraft mc) {
    ContainerType<?> rawType = packet.readRegistryIdUnsafe(ForgeRegistries.CONTAINERS);
    int windowId = packet.readVarInt();
    ITextComponent name = packet.readTextComponent();
    if (rawType instanceof ICCLContainerType<?>) {
        ICCLContainerType<?> type = (ICCLContainerType<?>) rawType;
        ScreenManager.getScreenFactory(rawType, mc, windowId, name)//
                .map(e -> (ScreenManager.IScreenFactory<Container, ?>) e)//
                .ifPresent(screenFactory -> {
                    Container container = type.create(windowId, Minecraft.getInstance().player.inventory, packet);
                    Screen screen = screenFactory.create(container, mc.player.inventory, name);
                    mc.player.openContainer = ((IHasContainer<?>) screen).getContainer();
                    mc.displayGuiScreen(screen);
                });

    }
}
 
Example #5
Source File: MetaTileEntityLargeBoiler.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void addDisplayText(List<ITextComponent> textList) {
    super.addDisplayText(textList);
    if (isStructureFormed()) {
        textList.add(new TextComponentTranslation("gregtech.multiblock.large_boiler.temperature", currentTemperature, boilerType.maxTemperature));
        textList.add(new TextComponentTranslation("gregtech.multiblock.large_boiler.steam_output", lastTickSteamOutput, boilerType.baseSteamOutput));

        ITextComponent heatEffText = new TextComponentTranslation("gregtech.multiblock.large_boiler.heat_efficiency", (int) (getHeatEfficiencyMultiplier() * 100));
        withHoverTextTranslate(heatEffText, "gregtech.multiblock.large_boiler.heat_efficiency.tooltip");
        textList.add(heatEffText);

        ITextComponent throttleText = new TextComponentTranslation("gregtech.multiblock.large_boiler.throttle", throttlePercentage, (int)(getThrottleEfficiency() * 100));
        withHoverTextTranslate(throttleText, "gregtech.multiblock.large_boiler.throttle.tooltip");
        textList.add(throttleText);

        ITextComponent buttonText = new TextComponentTranslation("gregtech.multiblock.large_boiler.throttle_modify");
        buttonText.appendText(" ");
        buttonText.appendSibling(withButton(new TextComponentString("[-]"), "sub"));
        buttonText.appendText(" ");
        buttonText.appendSibling(withButton(new TextComponentString("[+]"), "add"));
        textList.add(buttonText);
    }
}
 
Example #6
Source File: MetaTileEntityLargeTurbine.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void addDisplayText(List<ITextComponent> textList) {
    if (isStructureFormed()) {
        MetaTileEntityRotorHolder rotorHolder = getAbilities(ABILITY_ROTOR_HOLDER).get(0);
        FluidStack fuelStack = ((LargeTurbineWorkableHandler) workableHandler).getFuelStack();
        int fuelAmount = fuelStack == null ? 0 : fuelStack.amount;

        ITextComponent fuelName = new TextComponentTranslation(fuelAmount == 0 ? "gregtech.fluid.empty" : fuelStack.getUnlocalizedName());
        textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.fuel_amount", fuelAmount, fuelName));

        if (rotorHolder.getRotorEfficiency() > 0.0) {
            textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.rotor_speed", rotorHolder.getCurrentRotorSpeed(), rotorHolder.getMaxRotorSpeed()));
            textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.rotor_efficiency", (int) (rotorHolder.getRotorEfficiency() * 100)));
            int rotorDurability = (int) (rotorHolder.getRotorDurability() * 100);
            if (rotorDurability > MIN_DURABILITY_TO_WARN) {
                textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.rotor_durability", rotorDurability));
            } else {
                textList.add(new TextComponentTranslation("gregtech.multiblock.turbine.low_rotor_durability",
                    MIN_DURABILITY_TO_WARN, rotorDurability).setStyle(new Style().setColor(TextFormatting.RED)));
            }
        }
    }
    super.addDisplayText(textList);
}
 
Example #7
Source File: ScrapingDisabledWarning.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SubscribeEvent
public static void addInformation(ItemTooltipEvent ev)
{
    if (!ConfigManager.SERVER.enableScraping.get() && EnchantmentHelper.getEnchantmentLevel(SurvivalistMod.SCRAPING.get(), ev.getItemStack()) > 0)
    {
        List<ITextComponent> list = ev.getToolTip();
        /*int lastScraping = -1;
        for (int i = 0; i < list.size(); i++)
        {
            if (list.get(i).getFormattedText().startsWith(I18n.format("enchantment.survivalist.scraping")))
            {
                lastScraping = i;
            }
        }
        if (lastScraping >= 0)
        {
            list.add(lastScraping + 1, "" + TextFormatting.DARK_GRAY + TextFormatting.ITALIC + I18n.format("tooltip.survivalist.scraping.disabled"));
        }*/
        list.add(new TranslationTextComponent("tooltip.survivalist.scraping.disabled").func_240701_a_(TextFormatting.DARK_GRAY, TextFormatting.ITALIC));
    }
}
 
Example #8
Source File: BookBase.java    From minecraft-roguelike with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ItemStack get(){
	ItemStack book = new ItemStack(Items.WRITTEN_BOOK, 1);
	
	NBTTagList nbtPages = new NBTTagList();
	
	for(String page : this.pages){
		ITextComponent text = new TextComponentString(page);
		String json = ITextComponent.Serializer.componentToJson(text);
		NBTTagString nbtPage = new NBTTagString(json);
		nbtPages.appendTag(nbtPage);
	}
	
	book.setTagInfo("pages", nbtPages);
	book.setTagInfo("author", new NBTTagString(this.author == null ? "Anonymous" : this.author));
	book.setTagInfo("title", new NBTTagString(this.title == null ? "Book" : this.title));
	
	
	return book;
}
 
Example #9
Source File: CraftEventFactory.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
public static void handleEditBookEvent(EntityPlayerMP player, ItemStack newBookItem) {
    int itemInHandIndex = player.inventory.currentItem;

    PlayerEditBookEvent editBookEvent = new PlayerEditBookEvent(player.getBukkitEntity(), player.inventory.currentItem, (BookMeta) CraftItemStack.getItemMeta(player.inventory.getCurrentItem()), (BookMeta) CraftItemStack.getItemMeta(newBookItem), newBookItem.getItem() == Items.WRITTEN_BOOK);
    player.world.getServer().getPluginManager().callEvent(editBookEvent);
    ItemStack itemInHand = player.inventory.getStackInSlot(itemInHandIndex);

    // If they've got the same item in their hand, it'll need to be updated.
    if (itemInHand != null && itemInHand.getItem() == Items.WRITABLE_BOOK) {
        if (!editBookEvent.isCancelled()) {
            if (editBookEvent.isSigning()) {
                itemInHand.setItem(Items.WRITTEN_BOOK);
            }
            CraftMetaBook meta = (CraftMetaBook) editBookEvent.getNewBookMeta();
            List<ITextComponent> pages = meta.pages;
            for (int i = 0; i < pages.size(); i++) {
                pages.set(i, stripEvents(pages.get(i)));
            }
            CraftItemStack.setItemMeta(itemInHand, meta);
        }

        // Client will have updated its idea of the book item; we need to overwrite that
        Slot slot = player.openContainer.getSlotFromInventory(player.inventory, itemInHandIndex);
        player.connection.sendPacket(new SPacketSetSlot(player.openContainer.windowId, slot.slotNumber, itemInHand));
    }
}
 
Example #10
Source File: CraftMetaBook.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@Override
Builder<String, Object> serialize(Builder<String, Object> builder) {
    super.serialize(builder);

    if (hasTitle()) {
        builder.put(BOOK_TITLE.BUKKIT, title);
    }

    if (hasAuthor()) {
        builder.put(BOOK_AUTHOR.BUKKIT, author);
    }

    if (hasPages()) {
        List<String> pagesString = new ArrayList<String>();
        for (ITextComponent comp : pages) {
            pagesString.add(CraftChatMessage.fromComponent(comp));
        }
        builder.put(BOOK_PAGES.BUKKIT, pagesString);
    }

    if (generation != null) {
        builder.put(GENERATION.BUKKIT, generation);
    }

    return builder;
}
 
Example #11
Source File: CraftMetaBook.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<BaseComponent[]> getPages() {
    final List<ITextComponent> copy = ImmutableList.copyOf(CraftMetaBook.this.pages);
    return new AbstractList<BaseComponent[]>() {

        @Override
        public BaseComponent[] get(int index) {
            return ComponentSerializer.parse(ITextComponent.Serializer.componentToJson(copy.get(index)));
        }

        @Override
        public int size() {
            return copy.size();
        }
    };
}
 
Example #12
Source File: GuiCustomizeWorld.java    From YUNoMakeGoodMap with Apache License 2.0 5 votes vote down vote up
protected void drawHeader(int entryRight, int relativeY, Tessellator tess)
{
    int top = relativeY;

    if (logoPath != null)
    {
        GlStateManager.enableBlend();
        GuiCustomizeWorld.this.mc.renderEngine.bindTexture(logoPath);
        BufferBuilder wr = tess.getBuffer();
        int offset = (this.left + this.listWidth/2) - (logoDims.width / 2);
        wr.begin(7, DefaultVertexFormats.POSITION_TEX);
        wr.pos(offset,                  top + logoDims.height, zLevel).tex(0, 1).endVertex();
        wr.pos(offset + logoDims.width, top + logoDims.height, zLevel).tex(1, 1).endVertex();
        wr.pos(offset + logoDims.width, top,                   zLevel).tex(1, 0).endVertex();
        wr.pos(offset,                  top,                   zLevel).tex(0, 0).endVertex();
        tess.draw();
        GlStateManager.disableBlend();
        top += logoDims.height + 10;
    }

    for (ITextComponent line : lines)
    {
        if (line != null)
        {
            GlStateManager.enableBlend();
            GuiCustomizeWorld.this.fontRenderer.drawStringWithShadow(line.getFormattedText(), this.left + 4, top, 0xFFFFFF);
            GlStateManager.disableAlpha();
            GlStateManager.disableBlend();
        }
        top += 10;
    }
}
 
Example #13
Source File: EntityFugitive.java    From ToroQuest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the formatted ChatComponent that will be used for the sender's
 * username in chat
 */
public ITextComponent getDisplayName() {
	TextComponentTranslation textcomponenttranslation = new TextComponentTranslation("entity.toroquest.fugitive.name", new Object[0]);
	textcomponenttranslation.getStyle().setHoverEvent(this.getHoverEvent());
	textcomponenttranslation.getStyle().setInsertion(this.getCachedUniqueIdString());
	return textcomponenttranslation;
}
 
Example #14
Source File: UpgradeCard.java    From MiningGadgets with MIT License 5 votes vote down vote up
@Override
public void addInformation(ItemStack stack, @Nullable World world, List<ITextComponent> tooltip, ITooltipFlag flag) {
    super.addInformation(stack, world, tooltip, flag);
    if (stack.getItem() instanceof UpgradeCard) {
        Upgrade upgrade = ((UpgradeCard) stack.getItem()).upgrade;
        int cost = upgrade.getCostPerBlock();
        if (cost > 0)
            tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.upgrade_cost", cost).applyTextStyle(TextFormatting.AQUA));

        cost = 0;
        if (upgrade == Upgrade.LIGHT_PLACER)
            cost = Config.UPGRADECOST_LIGHT.get();
        if (upgrade == Upgrade.FREEZING)
            cost = Config.UPGRADECOST_FREEZE.get();
        if (cost > 0)
            tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.use_cost", cost).applyTextStyle(TextFormatting.AQUA));

        if( upgrade.getBaseName().equals(Upgrade.BATTERY_1.getBaseName()) ) {
            UpgradeBatteryLevels.getBatteryByLevel(upgrade.getTier()).ifPresent(e -> {
                tooltip.add(new TranslationTextComponent("mininggadgets.tooltip.item.battery_boost", MagicHelpers.tidyValue(e.getPower())).applyTextStyle(TextFormatting.AQUA));
            });
        }

        tooltip.add(new TranslationTextComponent(this.upgrade.getTooltop()).applyTextStyle(TextFormatting.GRAY));
    }

}
 
Example #15
Source File: EnderItemStorage.java    From EnderStorage with MIT License 5 votes vote down vote up
public void openContainer(ServerPlayerEntity player, ITextComponent title) {
    ServerUtils.openContainer(player, new SimpleNamedContainerProvider((id, inv, p) -> new ContainerEnderItemStorage(id, inv, EnderItemStorage.this), title),//
            packet -> {
                freq.writeToPacket(packet);
                packet.writeByte(size);
            });
}
 
Example #16
Source File: Helper.java    From ForgeHax with MIT License 5 votes vote down vote up
private static ITextComponent getFormattedText(String text, TextFormatting color,
    boolean bold, boolean italic) {
  return new TextComponentString(text.replaceAll("\r", ""))
      .setStyle(new Style()
          .setColor(color)
          .setBold(bold)
          .setItalic(italic)
      );
}
 
Example #17
Source File: IGWSupportNotifier.java    From IGW-mod with GNU General Public License v2.0 5 votes vote down vote up
@SubscribeEvent
public void onPlayerJoin(TickEvent.PlayerTickEvent event){
    if(event.player.world.isRemote && event.player == FMLClientHandler.instance().getClientPlayerEntity()) {
        event.player.sendMessage(ITextComponent.Serializer.jsonToComponent("[\"" + TextFormatting.GOLD + "The mod " + supportingMod + " is supporting In-Game Wiki mod. " + TextFormatting.GOLD + "However, In-Game Wiki isn't installed! " + "[\"," + "{\"text\":\"Download Latest\",\"color\":\"green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/igwmod_download\"}}," + "\"]\"]"));
        FMLCommonHandler.instance().bus().unregister(this);
    }
}
 
Example #18
Source File: GenericInventory.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
public ITextComponent getDisplayName() {
	final String name = getName();
	return hasCustomName()
			? new TextComponentString(name)
			: new TextComponentTranslation(name);
}
 
Example #19
Source File: CraftMetaBook.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void addPage(final BaseComponent[]... pages) {
    for (BaseComponent[] page : pages) {
        if (CraftMetaBook.this.pages.size() >= MAX_PAGES) {
            return;
        }

        if (page == null) {
            page = new BaseComponent[0];
        }

        CraftMetaBook.this.pages.add(ITextComponent.Serializer.jsonToComponent(ComponentSerializer.toString(page)));
    }
}
 
Example #20
Source File: NoLagModule.java    From seppuku with GNU General Public License v3.0 5 votes vote down vote up
@Listener
public void renderWorld(EventRender3D event) {
    final Minecraft mc = Minecraft.getMinecraft();
    if (this.signs.getValue()) {
        for (TileEntity te : mc.world.loadedTileEntityList) {
            if (te instanceof TileEntitySign) {
                final TileEntitySign sign = (TileEntitySign) te;
                sign.signText = new ITextComponent[]{new TextComponentString(""), new TextComponentString(""), new TextComponentString(""), new TextComponentString("")};
            }
        }
    }
}
 
Example #21
Source File: BlockSurfaceRockDeprecated.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<ITextComponent> getMagnifyResults(IBlockAccess world, BlockPos pos, IBlockState blockState, EntityPlayer player) {
    ArrayList<ITextComponent> result = new ArrayList<>();
    ITextComponent materialComponent = new TextComponentTranslation(getStoneMaterial(world, pos, blockState).getUnlocalizedName());
    materialComponent.getStyle().setColor(TextFormatting.GREEN);
    result.add(new TextComponentTranslation("gregtech.block.surface_rock.material", materialComponent));
    return result;
}
 
Example #22
Source File: ScannerBehavior.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ItemStack onItemUseFinish(ItemStack stack, EntityPlayer player) {
    if (!player.world.isRemote) {
        Pair<BlockPos, IBlockState> hitBlock = getHitBlock(player);
        if (hitBlock != null && checkCanUseScanner(stack, player, false).getLeft() == null) {
            ITextComponent component = new TextComponentTranslation("behavior.scanner.analyzing_complete");
            component.getStyle().setColor(TextFormatting.GOLD);
            player.sendStatusMessage(component, true);
            IScannableBlock magnifiableBlock = ((IScannableBlock) hitBlock.getRight().getBlock());
            List<ITextComponent> text = magnifiableBlock.getMagnifyResults(player.world, hitBlock.getLeft(), hitBlock.getRight(), player);
            text.forEach(player::sendMessage);
        }
    }
    return stack;
}
 
Example #23
Source File: ModeSwitchBehavior.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
    ItemStack itemStack = player.getHeldItem(hand);
    if(player.isSneaking()) {
        T currentMode = getModeFromItemStack(itemStack);
        int currentModeIndex = ArrayUtils.indexOf(enumConstants, currentMode);
        T nextMode = enumConstants[(currentModeIndex + 1) % enumConstants.length];
        setModeForItemStack(itemStack, nextMode);
        ITextComponent newModeComponent = new TextComponentTranslation(nextMode.getUnlocalizedName());
        ITextComponent textComponent = new TextComponentTranslation("metaitem.behavior.mode_switch.mode_switched", newModeComponent);
        player.sendStatusMessage(textComponent, true);
        return ActionResult.newResult(EnumActionResult.SUCCESS, itemStack);
    }
    return ActionResult.newResult(EnumActionResult.PASS, itemStack);
}
 
Example #24
Source File: CraftSign.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public static ITextComponent[] sanitizeLines(String[] lines) {
    ITextComponent[] components = new ITextComponent[4];

    for (int i = 0; i < 4; i++) {
        if (i < lines.length && lines[i] != null) {
            components[i] = CraftChatMessage.fromString(lines[i])[0];
        } else {
            components[i] = new TextComponentString("");
        }
    }

    return components;
}
 
Example #25
Source File: CraftSign.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
public static String[] revertComponents(ITextComponent[] components) {
    String[] lines = new String[components.length];
    for (int i = 0; i < lines.length; i++) {
        lines[i] = revertComponent(components[i]);
    }
    return lines;
}
 
Example #26
Source File: CraftMetaBookSigned.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
void applyToItem(NBTTagCompound itemData) {
    super.applyToItem(itemData, false);

    if (hasTitle()) {
        itemData.setString(BOOK_TITLE.NBT, this.title);
    } else {
        itemData.setString(BOOK_TITLE.NBT, " ");
    }

    if (hasAuthor()) {
        itemData.setString(BOOK_AUTHOR.NBT, this.author);
    } else {
        itemData.setString(BOOK_AUTHOR.NBT, " ");
    }

    if (hasPages()) {
        NBTTagList list = new NBTTagList();
        for (ITextComponent page : pages) {
            list.appendTag(new NBTTagString(
                    ITextComponent.Serializer.componentToJson(page)
            ));
        }
        itemData.setTag(BOOK_PAGES.NBT, list);
    }
    itemData.setBoolean(RESOLVED.NBT, true);

    if (generation != null) {
        itemData.setInteger(GENERATION.NBT, generation);
    } else {
        itemData.setInteger(GENERATION.NBT, 0);
    }
}
 
Example #27
Source File: Frequency.java    From EnderStorage with MIT License 5 votes vote down vote up
protected CompoundNBT write_internal(CompoundNBT tagCompound) {
    tagCompound.putInt("left", left.getWoolMeta());
    tagCompound.putInt("middle", middle.getWoolMeta());
    tagCompound.putInt("right", right.getWoolMeta());
    if (owner != null) {
        tagCompound.putUniqueId("owner", owner);
    }
    if (ownerName != null) {
        tagCompound.putString("owner_name", ITextComponent.Serializer.toJson(ownerName));
    }
    return tagCompound;
}
 
Example #28
Source File: CraftMetaBook.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
CraftMetaBook(NBTTagCompound tag, boolean handlePages) {
    super(tag);

    if (tag.hasKey(BOOK_TITLE.NBT)) {
        this.title = tag.getString(BOOK_TITLE.NBT);
    }

    if (tag.hasKey(BOOK_AUTHOR.NBT)) {
        this.author = tag.getString(BOOK_AUTHOR.NBT);
    }

    boolean resolved = false;
    if (tag.hasKey(RESOLVED.NBT)) {
        resolved = tag.getBoolean(RESOLVED.NBT);
    }

    if (tag.hasKey(GENERATION.NBT)) {
        generation = tag.getInteger(GENERATION.NBT);
    }

    if (tag.hasKey(BOOK_PAGES.NBT) && handlePages) {
        NBTTagList pages = tag.getTagList(BOOK_PAGES.NBT, CraftMagicNumbers.NBT.TAG_STRING);

        for (int i = 0; i < Math.min(pages.tagCount(), MAX_PAGES); i++) {
            String page = pages.getStringTagAt(i);
            if (resolved) {
                try {
                    this.pages.add(ITextComponent.Serializer.jsonToComponent(page));
                    continue;
                } catch (Exception e) {
                    // Ignore and treat as an old book
                }
            }
            addPage(page);
        }
    }
}
 
Example #29
Source File: CraftMetaBook.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
void applyToItem(NBTTagCompound itemData, boolean handlePages) {
    super.applyToItem(itemData);

    if (hasTitle()) {
        itemData.setString(BOOK_TITLE.NBT, this.title);
    }

    if (hasAuthor()) {
        itemData.setString(BOOK_AUTHOR.NBT, this.author);
    }

    if (handlePages) {
        if (hasPages()) {
            NBTTagList list = new NBTTagList();
            for (ITextComponent page : pages) {
                list.appendTag(new NBTTagString(CraftChatMessage.fromComponent(page)));
            }
            itemData.setTag(BOOK_PAGES.NBT, list);
        }

        itemData.removeTag(RESOLVED.NBT);
    }

    if (generation != null) {
        itemData.setInteger(GENERATION.NBT, generation);
    }
}
 
Example #30
Source File: CraftMetaBook.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setPage(final int page, final BaseComponent... text) {
    if (!isValidPage(page)) {
        throw new IllegalArgumentException("Invalid page number " + page + "/" + pages.size());
    }

    BaseComponent[] newText = text == null ? new BaseComponent[0] : text;
    CraftMetaBook.this.pages.set(page - 1, ITextComponent.Serializer.jsonToComponent(ComponentSerializer.toString(newText)));
}