HtmlPorts.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.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import net.sourceforge.plantuml.klimt.geom.XDimension2D;
import net.sourceforge.plantuml.ngdot.attr.RecordLabel;

/**
 * The ports of an HTML-like table ({@code <TD PORT="p">}), given to Smetana as
 * a record of the same geometry.
 * <p>
 * Smetana has no HTML-like labels ({@code html_port} is not ported), but it
 * knows how to end an edge on a field of a record. The node is cut in bands
 * along the gaps between the cells, recursively (rows, then columns, then rows
 * again, nested tables included), until each band holds one cell: each cell
 * with a port becomes the field of that port, and an edge going to it ends on
 * the side of the cell, as {@code html_port} and {@code compassPort} do in
 * Graphviz. A table that cannot be cut that way keeps the ports found so far.
 */
public final class HtmlPorts {

	private HtmlPorts() {
	}

	/** A cell placed in the node: its box, in the coordinates of the node. */
	private static final class Box {
		final double x0;
		final double y0;
		final double x1;
		final double y1;
		final HtmlCell cell;

		Box(double x0, double y0, double x1, double y1, HtmlCell cell) {
			this.x0 = x0;
			this.y0 = y0;
			this.x1 = x1;
			this.y1 = y1;
			this.cell = cell;
		}
	}

	/**
	 * Builds the record standing for a table, or returns {@code null} when the
	 * label has no port.
	 *
	 * @param block       the label, already sized
	 * @param nodeSize    the size of the node, the label being at its center
	 * @param leftToRight the orientation Smetana gives to the top-level fields
	 *                    of a record
	 * @param fieldSizes  receives the size of each field, in the order of
	 *                    {@link RecordLabel#getLeaves()}
	 */
	public static RecordLabel carrier(HtmlBlock block, XDimension2D nodeSize, boolean leftToRight,
			List<XDimension2D> fieldSizes) {
		final HtmlTable table = block.getLabel().getTable();
		if (table == null || hasPort(table) == false)
			return null;
		final double dx = (nodeSize.getWidth() - table.boxWidth) / 2;
		final double dy = (nodeSize.getHeight() - table.boxHeight) / 2;
		final List<Box> boxes = boxes(table, dx, dy);
		final RecordLabel root = cut(new Box(0, 0, nodeSize.getWidth(), nodeSize.getHeight(), null), boxes, dx, dy,
				fieldSizes);
		if (root.isLeaf() || root.isLeftToRight() != leftToRight)
			return RecordLabel.list(leftToRight, Collections.singletonList(root));
		return root;
	}

	private static boolean hasPort(HtmlTable table) {
		for (HtmlCell cell : table.getCells()) {
			if (port(cell) != null)
				return true;
			if (cell.getTable() != null && hasPort(cell.getTable()))
				return true;
		}
		return false;
	}

	private static String port(HtmlCell cell) {
		final String port = cell.getAttributes().get("PORT");
		return port == null || port.length() == 0 ? null : port;
	}

	private static List<Box> boxes(HtmlTable table, double dx, double dy) {
		final List<Box> result = new ArrayList<Box>();
		for (HtmlCell cell : table.getCells())
			result.add(new Box(cell.x + dx, cell.y + dy, cell.x + cell.boxWidth + dx, cell.y + cell.boxHeight + dy,
					cell));
		return result;
	}

	/**
	 * The fields of a region of the node holding some cells: a list of bands
	 * when the cells can be separated by horizontal (or else vertical) lines,
	 * a field otherwise.
	 */
	private static RecordLabel cut(Box region, List<Box> cells, double dx, double dy, List<XDimension2D> sizes) {
		if (cells.size() == 1) {
			final HtmlCell cell = cells.get(0).cell;
			if (cell.getTable() != null && hasPort(cell.getTable()))
				return cut(region, boxes(cell.getTable(), dx, dy), dx, dy, sizes);
			return leaf(region, port(cell), sizes);
		}
		if (cells.isEmpty())
			return leaf(region, null, sizes);
		for (int pass = 0; pass < 2; pass++) {
			final boolean horizontalLines = pass == 0;
			final List<List<Box>> groups = groups(cells, horizontalLines);
			if (groups.size() < 2)
				continue;
			// Bands one above the other make a top to bottom list
			final boolean leftToRight = horizontalLines == false;
			final List<RecordLabel> fields = new ArrayList<RecordLabel>();
			double start = horizontalLines ? region.y0 : region.x0;
			for (int i = 0; i < groups.size(); i++) {
				double end = horizontalLines ? region.y1 : region.x1;
				if (i + 1 < groups.size())
					end = (max(groups.get(i), horizontalLines) + min(groups.get(i + 1), horizontalLines)) / 2;
				final Box band = horizontalLines ? new Box(region.x0, start, region.x1, end, null)
						: new Box(start, region.y0, end, region.y1, null);
				RecordLabel field = cut(band, groups.get(i), dx, dy, sizes);
				// A nested list must be turned the other way
				if (field.isLeaf() == false && field.isLeftToRight() == leftToRight)
					field = RecordLabel.list(leftToRight == false, Collections.singletonList(field));
				fields.add(field);
				start = end;
			}
			return RecordLabel.list(leftToRight, fields);
		}
		return leaf(region, null, sizes);
	}

	private static RecordLabel leaf(Box region, String port, List<XDimension2D> sizes) {
		sizes.add(new XDimension2D(region.x1 - region.x0, region.y1 - region.y0));
		return RecordLabel.field("", port);
	}

	/**
	 * Sorts the cells and groups those that cannot be separated by a line
	 * (horizontal or vertical).
	 */
	private static List<List<Box>> groups(List<Box> cells, final boolean horizontalLines) {
		final List<Box> sorted = new ArrayList<Box>(cells);
		Collections.sort(sorted, new Comparator<Box>() {
			public int compare(Box a, Box b) {
				return Double.compare(horizontalLines ? a.y0 : a.x0, horizontalLines ? b.y0 : b.x0);
			}
		});
		final List<List<Box>> result = new ArrayList<List<Box>>();
		double end = Double.NEGATIVE_INFINITY;
		for (Box box : sorted) {
			final double start = horizontalLines ? box.y0 : box.x0;
			if (result.isEmpty() || start >= end)
				result.add(new ArrayList<Box>());
			result.get(result.size() - 1).add(box);
			end = Math.max(end, horizontalLines ? box.y1 : box.x1);
		}
		return result;
	}

	private static double max(List<Box> boxes, boolean horizontalLines) {
		double result = Double.NEGATIVE_INFINITY;
		for (Box box : boxes)
			result = Math.max(result, horizontalLines ? box.y1 : box.x1);
		return result;
	}

	private static double min(List<Box> boxes, boolean horizontalLines) {
		double result = Double.POSITIVE_INFINITY;
		for (Box box : boxes)
			result = Math.min(result, horizontalLines ? box.y0 : box.x0);
		return result;
	}

}