HtmlBlock.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.ngdot.html;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sourceforge.plantuml.klimt.UStroke;
import net.sourceforge.plantuml.klimt.UTranslate;
import net.sourceforge.plantuml.klimt.color.HColor;
import net.sourceforge.plantuml.klimt.color.HColorSet;
import net.sourceforge.plantuml.klimt.color.HColors;
import net.sourceforge.plantuml.klimt.drawing.UGraphic;
import net.sourceforge.plantuml.klimt.font.FontConfiguration;
import net.sourceforge.plantuml.klimt.font.FontStyle;
import net.sourceforge.plantuml.klimt.font.StringBounder;
import net.sourceforge.plantuml.klimt.geom.XDimension2D;
import net.sourceforge.plantuml.klimt.shape.TextBlock;
import net.sourceforge.plantuml.klimt.shape.ULine;
import net.sourceforge.plantuml.klimt.shape.URectangle;
import net.sourceforge.plantuml.klimt.shape.UText;
import net.sourceforge.plantuml.ngdot.attr.DotColors;

/**
 * Sizes and draws an HTML-like label, as {@code htmltable.c} of Graphviz 2.38:
 * {@code size_html_txt}, {@code size_html_cell}, {@code size_html_tbl} (with
 * {@code processTbl} and {@code sizeLinearArray}), {@code pos_html_tbl},
 * {@code pos_html_cell}, then {@code emit_html_tbl} and {@code doBorder}.
 * <p>
 * The coordinates are relative to the top left corner of the label, with Y
 * going down.
 */
public final class HtmlBlock implements TextBlock {

	/** Graphviz DEFAULT_BORDER, DEFAULT_CELLPADDING and DEFAULT_CELLSPACING. */
	private static final double DEFAULT_BORDER = 1;
	private static final double DEFAULT_CELLPADDING = 2;
	private static final double DEFAULT_CELLSPACING = 2;

	/** The radius of the rounded corners of a table or a cell. */
	private static final double ROUND = 12;

	private final HtmlLabel label;
	private final FontConfiguration font;
	private final HColorSet colorSet;
	private final HColor pencolor;

	private XDimension2D dimension;

	/**
	 * @param font     the font of the label ({@code fontname}, {@code fontsize},
	 *                 {@code fontcolor} of the element)
	 * @param pencolor the color of the borders without a {@code COLOR}
	 */
	public HtmlBlock(HtmlLabel label, FontConfiguration font, HColorSet colorSet, HColor pencolor) {
		this.label = label;
		this.font = font;
		this.colorSet = colorSet;
		this.pencolor = pencolor;
	}

	public HtmlLabel getLabel() {
		return label;
	}

	// ------------------------------------------------------------------
	// Fonts and text

	private FontConfiguration font(HtmlFont f) {
		FontConfiguration result = font;
		if (f.getSize() != null)
			result = result.changeSize(f.getSize().floatValue());
		if (f.getFace() != null)
			result = result.changeFamily(f.getFace());
		if (f.getColor() != null) {
			final HColor color = DotColors.parse(f.getColor(), colorSet);
			if (color != null)
				result = result.changeColor(color);
		}
		if (f.isBold())
			result = result.bold();
		if (f.isItalic())
			result = result.italic();
		if (f.isUnderline())
			result = result.underline();
		if (f.isStrike())
			result = result.add(FontStyle.STRIKE);
		return result;
	}

	/** The width, ascent and descent of a line. */
	private double[] metrics(HtmlText.Line line, HtmlFont lastFont, StringBounder stringBounder) {
		double width = 0;
		double ascent = 0;
		double descent = 0;
		final List<HtmlText.Span> spans = line.getSpans();
		if (spans.isEmpty()) {
			// An empty line has the height of the current font
			final FontConfiguration fc = font(lastFont);
			final XDimension2D dim = stringBounder.calculateDimension(fc.getFont(), " ");
			descent = stringBounder.getDescent(fc.getFont(), " ");
			return new double[] { 0, dim.getHeight() - descent, descent };
		}
		for (HtmlText.Span span : spans) {
			final FontConfiguration fc = font(span.getFont());
			final XDimension2D dim = stringBounder.calculateDimension(fc.getFont(), span.getText());
			final double d = stringBounder.getDescent(fc.getFont(), span.getText());
			width += dim.getWidth();
			ascent = Math.max(ascent, dim.getHeight() - d);
			descent = Math.max(descent, d);
		}
		return new double[] { width, ascent, descent };
	}

	private void sizeText(HtmlText text, HtmlFont font, StringBounder stringBounder) {
		double width = 0;
		double height = 0;
		HtmlFont last = font;
		for (HtmlText.Line line : text.getLines()) {
			final double[] m = metrics(line, last, stringBounder);
			width = Math.max(width, m[0]);
			height += m[1] + m[2];
			if (line.getSpans().isEmpty() == false)
				last = line.getSpans().get(line.getSpans().size() - 1).getFont();
		}
		text.width = width;
		text.height = height;
	}

	// ------------------------------------------------------------------
	// Sizes

	private static double number(HtmlAttributes attributes, String name, double defaultValue) {
		final Double value = attributes.getNumber(name);
		if (value == null || value < 0)
			return defaultValue;
		return value;
	}

	private void sizeTable(HtmlTable table, StringBounder stringBounder) {
		final HtmlAttributes attributes = table.getAttributes();
		table.border = number(attributes, "BORDER", DEFAULT_BORDER);
		table.cellSpacing = number(attributes, "CELLSPACING", DEFAULT_CELLSPACING);
		table.cellPadding = number(attributes, "CELLPADDING", DEFAULT_CELLPADDING);
		table.cellBorder = number(attributes, "CELLBORDER", table.border);

		// processTbl: the row and the column of each cell, spans included
		final Set<Long> used = new HashSet<Long>();
		int rowCount = 0;
		int columnCount = 0;
		final List<List<HtmlCell>> rows = table.getRows();
		for (int r = 0; r < rows.size(); r++) {
			int c = 0;
			for (HtmlCell cell : rows.get(r)) {
				while (used.contains(key(r, c)))
					c++;
				cell.row = r;
				cell.column = c;
				for (int i = r; i < r + cell.getRowspan(); i++)
					for (int j = c; j < c + cell.getColspan(); j++)
						used.add(key(i, j));
				c += cell.getColspan();
				columnCount = Math.max(columnCount, c);
				rowCount = Math.max(rowCount, r + cell.getRowspan());
			}
		}
		table.rowCount = rowCount;
		table.columnCount = columnCount;

		for (HtmlCell cell : table.getCells())
			sizeCell(cell, table, stringBounder);

		table.widths = new double[columnCount];
		table.heights = new double[rowCount];
		if (rowCount == 1 || columnCount == 1)
			sizeLinearArray(table);
		else
			sizeArray(table);

		double width = (columnCount + 1) * table.cellSpacing + 2 * table.border;
		double height = (rowCount + 1) * table.cellSpacing + 2 * table.border;
		for (double w : table.widths)
			width += w;
		for (double h : table.heights)
			height += h;
		table.width = fixedOrMin(attributes, "WIDTH", width);
		table.height = fixedOrMin(attributes, "HEIGHT", height);
	}

	private static long key(int row, int column) {
		return ((long) row << 32) | column;
	}

	/**
	 * With {@code FIXEDSIZE="TRUE"}, the given {@code WIDTH} or {@code HEIGHT};
	 * otherwise at least that size.
	 */
	private static double fixedOrMin(HtmlAttributes attributes, String name, double size) {
		final Double given = attributes.getNumber(name);
		if (given == null || given < 0)
			return size;
		if (attributes.isTrue("FIXEDSIZE"))
			return given;
		return Math.max(size, given);
	}

	private void sizeCell(HtmlCell cell, HtmlTable parent, StringBounder stringBounder) {
		final HtmlAttributes attributes = cell.getAttributes();
		cell.padding = number(attributes, "CELLPADDING", parent.cellPadding);
		cell.border = number(attributes, "BORDER", parent.cellBorder);
		double width = 0;
		double height = 0;
		if (cell.getTable() != null) {
			sizeTable(cell.getTable(), stringBounder);
			width = cell.getTable().width;
			height = cell.getTable().height;
		} else if (cell.getText() != null) {
			sizeText(cell.getText(), parent.getFont(), stringBounder);
			width = cell.getText().width;
			height = cell.getText().height;
		}
		final double margin = 2 * (cell.padding + cell.border);
		cell.width = fixedOrMin(attributes, "WIDTH", width + margin);
		cell.height = fixedOrMin(attributes, "HEIGHT", height + margin);
	}

	/** Graphviz SPLIT: the share of each of n rows or columns of a spanning cell. */
	private static double split(double size, int n, double space) {
		return Math.max(1, (size - (space - 1) * (n - 1)) / n);
	}

	/** sizeLinearArray: a table of one row or one column. */
	private static void sizeLinearArray(HtmlTable table) {
		for (HtmlCell cell : table.getCells()) {
			final double ht = cell.getRowspan() == 1 ? cell.height
					: split(cell.height, cell.getRowspan(), table.cellSpacing);
			final double wd = cell.getColspan() == 1 ? cell.width
					: split(cell.width, cell.getColspan(), table.cellSpacing);
			for (int i = cell.row; i < cell.row + cell.getRowspan(); i++)
				table.heights[i] = Math.max(table.heights[i], ht);
			for (int i = cell.column; i < cell.column + cell.getColspan(); i++)
				table.widths[i] = Math.max(table.widths[i], wd);
		}
	}

	/**
	 * The general case. Graphviz finds the smallest rows and columns with a
	 * network simplex; here the cells without span set the minimum sizes, then
	 * each spanning cell spreads what it lacks evenly over its rows or columns.
	 */
	private static void sizeArray(HtmlTable table) {
		final List<HtmlCell> cells = table.getCells();
		for (HtmlCell cell : cells) {
			if (cell.getRowspan() == 1)
				table.heights[cell.row] = Math.max(table.heights[cell.row], cell.height);
			if (cell.getColspan() == 1)
				table.widths[cell.column] = Math.max(table.widths[cell.column], cell.width);
		}
		for (HtmlCell cell : cells) {
			spread(table.heights, cell.row, cell.getRowspan(), cell.height, table.cellSpacing);
			spread(table.widths, cell.column, cell.getColspan(), cell.width, table.cellSpacing);
		}
	}

	private static void spread(double[] sizes, int start, int span, double needed, double space) {
		if (span == 1)
			return;
		double current = (span - 1) * space;
		for (int i = start; i < start + span; i++)
			current += sizes[i];
		if (current >= needed)
			return;
		final double more = (needed - current) / span;
		for (int i = start; i < start + span; i++)
			sizes[i] += more;
	}

	// ------------------------------------------------------------------
	// Positions

	/** pos_html_tbl: the table fills the given box, the extra space is shared by the rows and columns. */
	private static void posTable(HtmlTable table, double x, double y, double width, double height) {
		table.x = x;
		table.y = y;
		table.boxWidth = width;
		table.boxHeight = height;
		final double extraX = table.columnCount == 0 ? 0 : (width - table.width) / table.columnCount;
		final double extraY = table.rowCount == 0 ? 0 : (height - table.height) / table.rowCount;
		final double[] xs = new double[table.columnCount + 1];
		double pos = x + table.border + table.cellSpacing;
		for (int i = 0; i < table.columnCount; i++) {
			xs[i] = pos;
			pos += table.widths[i] + extraX + table.cellSpacing;
		}
		xs[table.columnCount] = pos;
		final double[] ys = new double[table.rowCount + 1];
		pos = y + table.border + table.cellSpacing;
		for (int i = 0; i < table.rowCount; i++) {
			ys[i] = pos;
			pos += table.heights[i] + extraY + table.cellSpacing;
		}
		ys[table.rowCount] = pos;
		table.rowTops = ys;
		for (HtmlCell cell : table.getCells()) {
			final double cx = xs[cell.column];
			final double cy = ys[cell.row];
			posCell(cell, cx, cy, xs[cell.column + cell.getColspan()] - table.cellSpacing - cx,
					ys[cell.row + cell.getRowspan()] - table.cellSpacing - cy);
		}
	}

	/** pos_html_cell: a nested table fills the cell, a text is aligned in it. */
	private static void posCell(HtmlCell cell, double x, double y, double width, double height) {
		cell.x = x;
		cell.y = y;
		cell.boxWidth = width;
		cell.boxHeight = height;
		final double inset = cell.border + cell.padding;
		double bx = x + inset;
		double by = y + inset;
		double bw = Math.max(0, width - 2 * inset);
		double bh = Math.max(0, height - 2 * inset);
		final HtmlAttributes attributes = cell.getAttributes();
		if (cell.getTable() != null) {
			posTable(cell.getTable(), bx, by, Math.max(bw, cell.getTable().width), Math.max(bh, cell.getTable().height));
			return;
		}
		final HtmlText text = cell.getText();
		if (text == null)
			return;
		final double delx = bw - text.width;
		final String align = attributes.getKeyword("ALIGN");
		if (delx > 0 && "TEXT".equals(align) == false) {
			if ("LEFT".equals(align))
				bw -= delx;
			else if ("RIGHT".equals(align))
				bx += delx;
			else {
				bx += delx / 2;
				bw -= delx;
			}
		}
		final double dely = bh - text.height;
		if (dely > 0) {
			final String valign = attributes.getKeyword("VALIGN");
			if ("BOTTOM".equals(valign))
				by += dely;
			else if ("TOP".equals(valign) == false)
				by += dely / 2;
			bh = text.height;
		}
		text.x = bx;
		text.y = by;
		text.boxWidth = bw;
		text.boxHeight = bh;
		final char balign = HtmlParser.justification(attributes.getKeyword("BALIGN"));
		text.defaultJustification = balign == 0 ? 'c' : balign;
	}

	private void layout(StringBounder stringBounder) {
		if (dimension != null)
			return;
		final HtmlTable table = label.getTable();
		if (table != null) {
			sizeTable(table, stringBounder);
			posTable(table, 0, 0, table.width, table.height);
			dimension = new XDimension2D(table.width, table.height);
		} else {
			final HtmlText text = label.getText();
			sizeText(text, HtmlFont.NONE, stringBounder);
			text.x = 0;
			text.y = 0;
			text.boxWidth = text.width;
			text.boxHeight = text.height;
			dimension = new XDimension2D(text.width, text.height);
		}
	}

	// ------------------------------------------------------------------
	// TextBlock

	@Override
	public XDimension2D calculateDimension(StringBounder stringBounder) {
		layout(stringBounder);
		return dimension;
	}

	@Override
	public void drawU(UGraphic ug) {
		layout(ug.getStringBounder());
		if (label.getTable() != null)
			drawTable(ug, label.getTable(), pencolor);
		else
			drawText(ug, label.getText(), HtmlFont.NONE);
	}

	private HColor color(HtmlAttributes attributes, String name) {
		final String value = attributes.get(name);
		return value == null ? null : DotColors.parse(value, colorSet);
	}

	private static Set<String> styles(HtmlAttributes attributes) {
		final Set<String> result = new HashSet<String>();
		final String style = attributes.get("STYLE");
		if (style != null)
			for (String s : style.split("[ ,]+"))
				if (s.length() > 0)
					result.add(s.toLowerCase());
		return result;
	}

	private void drawTable(UGraphic ug, HtmlTable table, HColor inheritedPen) {
		final HtmlAttributes attributes = table.getAttributes();
		final Set<String> styles = styles(attributes);
		if (styles.contains("invis") || styles.contains("invisible"))
			return;
		final HColor pen = firstNotNull(color(attributes, "COLOR"), inheritedPen);
		final boolean rounded = styles.contains("rounded");
		final HColor bgcolor = color(attributes, "BGCOLOR");
		if (bgcolor != null)
			fill(ug, bgcolor, table.x, table.y, table.boxWidth, table.boxHeight, rounded);

		for (HtmlCell cell : table.getCells())
			drawCell(ug, cell, pen, table.getFont());

		// Rules: drawn after the cells, with a pen of width 1
		final UGraphic ugRule = ug.apply(pen).apply(UStroke.withThickness(1));
		final double half = table.cellSpacing / 2;
		final double left = table.x + table.border;
		final double right = table.x + table.boxWidth - table.border;
		for (int r = 1; r < table.rowCount; r++)
			if (table.isRuledBefore(r)) {
				final double y = table.rowTops[r] - half;
				ugRule.apply(new UTranslate(left, y)).draw(new ULine(right - left, 0));
			}
		for (HtmlCell cell : table.getCells())
			if (cell.isRuledBefore()) {
				final double x = cell.x - half;
				final double top = cell.y - half;
				ugRule.apply(new UTranslate(x, top)).draw(new ULine(0, cell.boxHeight + table.cellSpacing));
			}

		if (table.border > 0)
			drawBorder(ug, pen, styles, table.border, null, table.x, table.y, table.boxWidth, table.boxHeight);
	}

	private void drawCell(UGraphic ug, HtmlCell cell, HColor tablePen, HtmlFont tableFont) {
		final HtmlAttributes attributes = cell.getAttributes();
		final Set<String> styles = styles(attributes);
		if (styles.contains("invis") || styles.contains("invisible"))
			return;
		final HColor pen = firstNotNull(color(attributes, "COLOR"), tablePen);
		final HColor bgcolor = color(attributes, "BGCOLOR");
		if (bgcolor != null)
			fill(ug, bgcolor, cell.x, cell.y, cell.boxWidth, cell.boxHeight, styles.contains("rounded"));
		if (cell.border > 0)
			drawBorder(ug, pen, styles, cell.border, attributes.getKeyword("SIDES"), cell.x, cell.y, cell.boxWidth,
					cell.boxHeight);
		if (cell.getTable() != null)
			drawTable(ug, cell.getTable(), pen);
		else if (cell.getText() != null)
			drawText(ug, cell.getText(), tableFont);
	}

	private static void fill(UGraphic ug, HColor color, double x, double y, double width, double height,
			boolean rounded) {
		final URectangle rect = URectangle.build(width, height);
		ug.apply(HColors.none()).apply(color.bg()).apply(new UTranslate(x, y))
				.draw(rounded ? rect.rounded(Math.min(ROUND, Math.min(width, height))) : rect);
	}

	/**
	 * doBorder: a border of width {@code border} drawn inside the box, on all
	 * the sides or on those of {@code SIDES} ({@code L T R B}).
	 */
	private static void drawBorder(UGraphic ug, HColor pen, Set<String> styles, double border, String sides,
			double x, double y, double width, double height) {
		UStroke stroke = UStroke.withThickness(border);
		if (styles.contains("dashed"))
			stroke = new UStroke(5 * Math.max(1, border), 2 * Math.max(1, border), border);
		else if (styles.contains("dotted"))
			stroke = new UStroke(Math.max(1, border), 5 * Math.max(1, border), border);
		final UGraphic ugLine = ug.apply(pen).apply(HColors.none().bg()).apply(stroke);
		if (border > 1) {
			final double delta = border / 2;
			x += delta;
			y += delta;
			width -= border;
			height -= border;
		}
		if (styles.contains("rounded")) {
			ugLine.apply(new UTranslate(x, y))
					.draw(URectangle.build(width, height).rounded(Math.min(ROUND, Math.min(width, height))));
			return;
		}
		if (sides == null || sides.length() == 0) {
			ugLine.apply(new UTranslate(x, y)).draw(URectangle.build(width, height));
			return;
		}
		if (sides.indexOf('T') != -1)
			ugLine.apply(new UTranslate(x, y)).draw(new ULine(width, 0));
		if (sides.indexOf('B') != -1)
			ugLine.apply(new UTranslate(x, y + height)).draw(new ULine(width, 0));
		if (sides.indexOf('L') != -1)
			ugLine.apply(new UTranslate(x, y)).draw(new ULine(0, height));
		if (sides.indexOf('R') != -1)
			ugLine.apply(new UTranslate(x + width, y)).draw(new ULine(0, height));
	}

	private void drawText(UGraphic ug, HtmlText text, HtmlFont font) {
		final StringBounder stringBounder = ug.getStringBounder();
		double y = text.y;
		HtmlFont last = font;
		for (HtmlText.Line line : text.getLines()) {
			final double[] m = metrics(line, last, stringBounder);
			final char just = line.getJustification() != 0 ? line.getJustification() : text.defaultJustification;
			double x = text.x;
			if (just == 'r')
				x += text.boxWidth - m[0];
			else if (just != 'l')
				x += (text.boxWidth - m[0]) / 2;
			final double baseline = y + m[1];
			for (HtmlText.Span span : line.getSpans()) {
				final FontConfiguration fc = font(span.getFont());
				final XDimension2D dim = stringBounder.calculateDimension(fc.getFont(), span.getText());
				double shift = 0;
				if (span.getFont().isSub())
					shift = fc.getSize2D() * 0.3;
				else if (span.getFont().isSup())
					shift = -fc.getSize2D() * 0.4;
				ug.apply(new UTranslate(x, baseline + shift)).draw(UText.build(span.getText(), fc));
				if (span.getFont().isOverline()) {
					final double top = baseline + shift - (dim.getHeight() - stringBounder.getDescent(fc.getFont(),
							span.getText())) + 1;
					ug.apply(fc.getColor()).apply(UStroke.withThickness(1)).apply(new UTranslate(x, top))
							.draw(new ULine(dim.getWidth(), 0));
				}
				x += dim.getWidth();
				last = span.getFont();
			}
			y += m[1] + m[2];
		}
	}

	private static HColor firstNotNull(HColor a, HColor b) {
		return a != null ? a : b;
	}

}