MessageRenderer.java

/* ========================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyright 2009-2024, Arnaud Roques
 *
 * Project Info:  https://plantuml.com
 * 
 * If you like this project or if you find it useful, you can support us at:
 * 
 * https://plantuml.com/patreon (only 1$ per month!)
 * https://plantuml.com/paypal
 * 
 * This file is part of PlantUML.
 *
 * PlantUML is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PlantUML distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 *
 * Original Author:  Arnaud Roques
 *
 */
package net.sourceforge.plantuml.error.messages;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.atmp.PixelImage;
import net.sourceforge.plantuml.flashcode.FlashCodeFactory;
import net.sourceforge.plantuml.klimt.AffineTransformType;
import net.sourceforge.plantuml.klimt.awt.PortableImage;
import net.sourceforge.plantuml.klimt.awt.XColor;
import net.sourceforge.plantuml.klimt.color.HColor;
import net.sourceforge.plantuml.klimt.color.HColorSet;
import net.sourceforge.plantuml.klimt.color.HColorSimple;
import net.sourceforge.plantuml.klimt.color.HColors;
import net.sourceforge.plantuml.klimt.creole.Display;
import net.sourceforge.plantuml.klimt.font.FontConfiguration;
import net.sourceforge.plantuml.klimt.font.UFont;
import net.sourceforge.plantuml.klimt.font.UFontFactory;
import net.sourceforge.plantuml.klimt.geom.HorizontalAlignment;
import net.sourceforge.plantuml.klimt.geom.VerticalAlignment;
import net.sourceforge.plantuml.klimt.shape.TextBlock;
import net.sourceforge.plantuml.klimt.shape.TextBlockUtils;
import net.sourceforge.plantuml.klimt.shape.UImage;
import net.sourceforge.plantuml.klimt.sprite.SpriteContainerEmpty;
import net.sourceforge.plantuml.security.SImageIO;
import net.sourceforge.plantuml.utils.Log;

/**
 * Draws a message of messages.yaml and places it around the error diagram.
 *
 * Layout: the image is placed next to the text as {@code image-position} says,
 * the QR code is always on the right of both, vertically centered. Without
 * {@code background}, a message with an image takes the color of its top left
 * pixel, as the banners used to.
 */
public final class MessageRenderer {

	private MessageRenderer() {
	}

	/**
	 * The error diagram with the message of this rule around it, or the diagram
	 * unchanged when nothing can be drawn.
	 */
	public static TextBlock decorate(TextBlock diagram, MessageRule rule) {
		final TextBlock message = render(rule.getMessage());
		if (message == null)
			return diagram;

		switch (rule.getPosition()) {
		case TOP:
			return TextBlockUtils.mergeTB(message, diagram, HorizontalAlignment.LEFT);
		case BOTTOM:
			return TextBlockUtils.mergeTB(diagram, message, HorizontalAlignment.LEFT);
		case TOP_BOTTOM:
			return TextBlockUtils.mergeTB(TextBlockUtils.mergeTB(message, diagram, HorizontalAlignment.LEFT), message,
					HorizontalAlignment.LEFT);
		case RIGHT:
			return TextBlockUtils.mergeLR(diagram, message, VerticalAlignment.TOP);
		}
		throw new IllegalStateException();
	}

	/** The message alone, or null when none of its parts can be drawn. */
	static TextBlock render(MessageDefinition message) {
		final PortableImage image = readImage(message);
		final HColor background = getBackground(message, image);

		final TextBlock text = message.getText() == null ? null : createText(message);
		final TextBlock picture = image == null ? null
				: new UImage(new PixelImage(image, AffineTransformType.TYPE_BILINEAR));

		TextBlock result = arrange(text, picture, message.getImagePosition());

		final TextBlock qrcode = createQrcode(message, background);
		if (qrcode != null)
			result = result == null ? qrcode : TextBlockUtils.mergeLR(result, qrcode, VerticalAlignment.CENTER);

		if (result == null)
			return null;

		result = TextBlockUtils.withMargin(result, 1, 1);
		if (background != null)
			result = TextBlockUtils.addBackcolor(result, background);

		return result;
	}

	private static TextBlock arrange(TextBlock text, TextBlock picture, ImagePosition imagePosition) {
		if (text == null)
			return picture;

		if (picture == null)
			return text;

		switch (imagePosition) {
		case LEFT:
			return TextBlockUtils.mergeLR(picture, text, VerticalAlignment.CENTER);
		case RIGHT:
			return TextBlockUtils.mergeLR(text, picture, VerticalAlignment.CENTER);
		case TOP:
			return TextBlockUtils.mergeTB(picture, text, HorizontalAlignment.LEFT);
		case BOTTOM:
			return TextBlockUtils.mergeTB(text, picture, HorizontalAlignment.LEFT);
		}
		throw new IllegalStateException();
	}

	private static TextBlock createText(MessageDefinition message) {
		final List<String> lines = new ArrayList<>();
		for (String line : message.getText().split("\n", -1))
			// An empty line would be dropped: a space keeps the blank line
			lines.add(line.length() == 0 ? " " : line);

		final UFont font = UFontFactory.sansSerif(message.getFontSize());
		final FontConfiguration fc = FontConfiguration.create(font, HColors.BLACK, HColors.BLACK, null);
		final TextBlock text = Display.create(lines).create(fc, HorizontalAlignment.LEFT, new SpriteContainerEmpty());
		return TextBlockUtils.withMargin(text, 10, 0);
	}

	private static PortableImage readImage(MessageDefinition message) {
		final byte[] data = message.getImage();
		if (data == null)
			return null;

		try {
			return SImageIO.read(data);
		} catch (IOException | RuntimeException e) {
			Log.info(() -> "messages.yaml: cannot read the image of message '" + message.getId() + "': " + e);
			return null;
		}
	}

	private static HColor getBackground(MessageDefinition message, PortableImage image) {
		if (message.getBackground() != null)
			return HColorSet.instance().getColorOrNull(message.getBackground());

		if (image != null && image.getWidth() > 0 && image.getHeight() > 0)
			return HColors.simple(XColor.from(image.getRGB(0, 0)));

		return null;
	}

	private static TextBlock createQrcode(MessageDefinition message, HColor background) {
		if (message.getQrcode() == null)
			return null;

		XColor back = XColor.WHITE;
		if (background instanceof HColorSimple && message.getBackground() != null)
			back = ((HColorSimple) background).getAwtColor();

		final PortableImage qrcode = withoutBorder(
				FlashCodeFactory.getFlashCodeUtils().exportFlashcode(message.getQrcode(), XColor.BLACK, back));
		if (qrcode == null)
			return null;

		return new UImage(new PixelImage(qrcode, AffineTransformType.TYPE_NEAREST_NEIGHBOR))
				.scale(message.getQrcodeScale());
	}

	// The QR code comes with a one pixel border that the background already gives
	private static PortableImage withoutBorder(PortableImage image) {
		if (image == null || image.getWidth() <= 2 || image.getHeight() <= 2)
			return image;

		return image.getSubimage(1, 1, image.getWidth() - 2, image.getHeight() - 2);
	}

}