CucaDiagramFileMakerSmetana.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.sdot;

import static gen.lib.cgraph.attr__c.agsafeset;
import static gen.lib.cgraph.edge__c.agedge;
import static gen.lib.cgraph.graph__c.agopen;
import static gen.lib.cgraph.node__c.agnode;
import static gen.lib.cgraph.subg__c.agsubg;
import static gen.lib.gvc.gvc__c.gvContext;
import static gen.lib.gvc.gvlayout__c.gvLayoutJobs;
import static smetana.core.debug.SmetanaDebug.SMETANA_TRACE;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import h.ST_Agedge_s;
import h.ST_Agedgeinfo_t;
import h.ST_Agnode_s;
import h.ST_Agraph_s;
import h.ST_Agraphinfo_t;
import h.ST_Agrec_s;
import h.ST_GVC_s;
import net.atmp.CucaDiagram;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.abel.CucaNote;
import net.sourceforge.plantuml.abel.Entity;
import net.sourceforge.plantuml.abel.EntityPosition;
import net.sourceforge.plantuml.abel.EntityUtils;
import net.sourceforge.plantuml.abel.GroupType;
import net.sourceforge.plantuml.abel.LeafType;
import net.sourceforge.plantuml.abel.Link;
import net.sourceforge.plantuml.abel.LinkArrow;
import net.sourceforge.plantuml.annotation.DuplicateCode;
import net.sourceforge.plantuml.annotation.Fast;
import net.sourceforge.plantuml.core.DiagramType;
import net.sourceforge.plantuml.decoration.symbol.USymbol;
import net.sourceforge.plantuml.dot.DotSplines;
import net.sourceforge.plantuml.klimt.LineBreakStrategy;
import net.sourceforge.plantuml.klimt.UTranslate;
import net.sourceforge.plantuml.klimt.color.HColor;
import net.sourceforge.plantuml.klimt.creole.CreoleMode;
import net.sourceforge.plantuml.klimt.creole.Display;
import net.sourceforge.plantuml.klimt.drawing.UGraphic;
import net.sourceforge.plantuml.klimt.font.FontConfiguration;
import net.sourceforge.plantuml.klimt.font.StringBounder;
import net.sourceforge.plantuml.klimt.geom.HorizontalAlignment;
import net.sourceforge.plantuml.klimt.geom.MinMax;
import net.sourceforge.plantuml.klimt.geom.MinMaxMutable;
import net.sourceforge.plantuml.klimt.geom.Rankdir;
import net.sourceforge.plantuml.klimt.geom.RectangleArea;
import net.sourceforge.plantuml.klimt.geom.VerticalAlignment;
import net.sourceforge.plantuml.klimt.geom.XDimension2D;
import net.sourceforge.plantuml.klimt.geom.XPoint2D;
import net.sourceforge.plantuml.klimt.shape.DotPath;
import net.sourceforge.plantuml.klimt.shape.TextBlock;
import net.sourceforge.plantuml.klimt.shape.TextBlockUtils;
import net.sourceforge.plantuml.klimt.shape.UHidden;
import net.sourceforge.plantuml.skin.AlignmentParam;
import net.sourceforge.plantuml.skin.PragmaKey;
import net.sourceforge.plantuml.skin.VisibilityModifier;
import net.sourceforge.plantuml.skin.rose.Rose;
import net.sourceforge.plantuml.stereo.Stereotype;
import net.sourceforge.plantuml.style.ISkinParam;
import net.sourceforge.plantuml.style.SName;
import net.sourceforge.plantuml.style.Style;
import net.sourceforge.plantuml.style.StyleQueries;
import net.sourceforge.plantuml.style.StyleQuery;
import net.sourceforge.plantuml.svek.Cluster;
import net.sourceforge.plantuml.svek.ClusterHeader;
import net.sourceforge.plantuml.svek.CucaDiagramFileMaker;
import net.sourceforge.plantuml.svek.GeneralImageBuilder;
import net.sourceforge.plantuml.svek.IEntityImage;
import net.sourceforge.plantuml.svek.RoleLabels;
import net.sourceforge.plantuml.svek.SvekNode;
import net.sourceforge.plantuml.svek.SvekUtils;
import net.sourceforge.plantuml.svek.image.EntityImageNote;
import net.sourceforge.plantuml.svek.image.EntityImageNoteLink;
import net.sourceforge.plantuml.teavm.TeaVM;
import net.sourceforge.plantuml.utils.Position;
import smetana.core.CString;
import smetana.core.Globals;
import smetana.core.JUtils;
import smetana.core.Macro;
import smetana.core.debug.SmetanaDebug;

@DuplicateCode(reference = "SvekEdge, CucaDiagramFileMakerElk, CucaDiagramFileMakerSmetana")
public class CucaDiagramFileMakerSmetana extends CucaDiagramFileMaker {
	private final Map<Entity, ST_Agnode_s> nodes = new LinkedHashMap<Entity, ST_Agnode_s>();
	private final Map<Entity, ST_Agnode_s> coreNodes = new LinkedHashMap<Entity, ST_Agnode_s>();
	private final Map<Link, ST_Agedge_s> edges = new LinkedHashMap<Link, ST_Agedge_s>();
	private final Map<Link, SmetanaEdge> smetanaPathes = new LinkedHashMap<Link, SmetanaEdge>();
	private final Map<Entity, ST_Agraph_s> clusters = new LinkedHashMap<Entity, ST_Agraph_s>();

	private final Rankdir rankdir;

	private final Entity root;
	// Shared with the nested layouts of composite states.
	private final OrthogonalPath.SearchBudget budget;

	public CucaDiagramFileMakerSmetana(CucaDiagram diagram) {
		this(diagram, diagram.getRootGroup(), new OrthogonalPath.SearchBudget());
	}

	CucaDiagramFileMakerSmetana(CucaDiagram diagram, Entity root, OrthogonalPath.SearchBudget budget) {
		super(diagram, root);
		this.root = root;
		this.budget = budget;
		this.rankdir = diagram.getSkinParam().getRankdir();

	}

	// Structural access relative to the local layout root.
	// At the diagram root, these behave exactly like before (whole diagram).
	// In a nested sub-layout (root is a group, e.g. a composite state rendered as a
	// leaf), they restrict the scope to that group: concurrent sub-regions are
	// filtered out of the group hierarchy, and only links fully internal to the
	// group are laid out. This mirrors GroupMakerState.InnerGroupHierarchy /
	// getPureInnerLinks on the dot side, and avoids trying to resolve links that
	// touch the group itself or the outside world (which have no node in the
	// sub-layout).
	private boolean isNestedLayout() {
		return root != diagram.getRootGroup();
	}

	private Collection<Entity> getChildrenGroups(Entity parent) {
		if (isNestedLayout() == false)
			return diagram.getChildrenGroups(parent);

		final List<Entity> result = new ArrayList<>();
		for (Entity g : diagram.getChildrenGroups(parent))
			if (g.getGroupType() != GroupType.CONCURRENT_STATE)
				result.add(g);

		return result;
	}

	private Collection<Link> getLocalLinks() {
		if (isNestedLayout() == false)
			return diagram.getLinks();

		final List<Link> result = new ArrayList<>();
		for (Link link : diagram.getLinks())
			if (EntityUtils.isPureInnerLink12(root, link))
				result.add(link);

		return result;
	}

	// Routing "linetype ortho" on top of a layout made for splines is opt-in,
	// until it has proved itself on real diagrams.
	private boolean isOrthogonal() {
		return diagram.getSkinParam().getDotSplines() == DotSplines.ORTHO
				&& diagram.getPragma().isTrue(PragmaKey.SMETANA_ORTHO);
	}

	private MinMaxMutable getSmetanaMinMax() {
		final MinMaxMutable result = MinMaxMutable.getEmpty(false);
		for (ST_Agnode_s n : nodes.values()) {
			final BoxInfo data = BoxInfo.fromNode(n);
			result.addPoint(data.getUpperRight());
			result.addPoint(data.getLowerLeft());
		}
		for (ST_Agraph_s gr : clusters.values()) {
			final ST_Agrec_s tmp1 = gr.data;
			if (tmp1 instanceof ST_Agraphinfo_t == false) {
				System.err.println("ERROR IN CucaDiagramFileMakerSmetana");
				continue;
			}
			final ST_Agraphinfo_t info = (ST_Agraphinfo_t) tmp1;
			final BoxInfo data = BoxInfo.fromGraphInfo(info);
			result.addPoint(data.getUpperRight());
			result.addPoint(data.getLowerLeft());

		}
		return result;
	}

	class Drawing implements TextBlock {

		private final YMirror ymirror;
		private final MinMaxMutable minMax;
		private final double canvasMargin;
		private MinMax measuredMinMax;

		public Drawing(double canvasMargin) {
			this.minMax = getSmetanaMinMax();
			this.ymirror = new YMirror(minMax.getMaxY() + 6);
			this.canvasMargin = canvasMargin;
		}

		// Builds the edges and routes them once, so that measuring and drawing
		// only read the result.
		void prepareEdges(StringBounder stringBounder) {
			makeEdges(stringBounder);
			if (isOrthogonal())
				routeOrthogonalEdges(stringBounder);
		}

		private UTranslate getBaselineTranslate() {
			return new UTranslate(canvasMargin, canvasMargin - minMax.getMinY());
		}

		private XDimension2D getBaselineDimension() {
			return minMax.getDimension().delta(2 * canvasMargin + 4, canvasMargin + 16);
		}

		// Smetana's layout bounds cover the nodes and clusters. Measure the
		// rendered edges and labels as well so the canvas and any enclosing
		// state region can expand where the drawing extends past those bounds.
		private MinMax getMeasuredMinMax(StringBounder stringBounder) {
			if (measuredMinMax == null) {
				final UTranslate baseline = getBaselineTranslate();
				measuredMinMax = TextBlockUtils.getMinMax(ug -> drawContent(ug.apply(baseline)), stringBounder, false);
			}
			return measuredMinMax;
		}

		public void drawU(UGraphic ug) {
			final MinMax measured = getMeasuredMinMax(ug.getStringBounder());
			final double extraLeft = Math.max(0, -measured.getMinX());
			final double extraTop = Math.max(0, -measured.getMinY());

			UGraphic shifted = ug.apply(getBaselineTranslate());
			if (extraLeft != 0 || extraTop != 0)
				shifted = shifted.apply(new UTranslate(extraLeft, extraTop));

			drawContent(shifted);
		}

		private void makeEdges(StringBounder stringBounder) {
			for (Map.Entry<Link, ST_Agedge_s> ent : edges.entrySet()) {
				final Link link = ent.getKey();
				if (link.isInvis())
					continue;

				final ST_Agedge_s edge = ent.getValue();
				final TextBlock quantifier1 = getQuantifier(stringBounder, link, 1);
				final TextBlock quantifier2 = getQuantifier(stringBounder, link, 2);
				final TextBlock role1 = getRoleLabel(stringBounder, link, 1);
				final TextBlock role2 = getRoleLabel(stringBounder, link, 2);
				final SmetanaEdge smetanaPath = new SmetanaEdge(link, edge, ymirror,
							getLabel(stringBounder, link), quantifier1, quantifier2, role1, role2,
						getBibliotekon(), diagram.getSkinParam(), isOrthogonal());
				smetanaPathes.put(link, smetanaPath);
			}
		}

		// The caller supplies the drawing origin, both for measurement and for
		// the actual rendering.
		private void drawContent(UGraphic ug) {
			for (Map.Entry<Entity, ST_Agraph_s> ent : clusters.entrySet())
				drawGroup(ug, ymirror, ent.getKey(), ent.getValue());

			for (Map.Entry<Entity, ST_Agnode_s> ent : nodes.entrySet()) {
				final XPoint2D corner = moveToLayoutPosition(ent.getKey(), ent.getValue());

				final SvekNode node = getBibliotekon().getNode(ent.getKey());
				final IEntityImage image = node.getImage();
				// Same as SvekResult on the dot pipeline: 'hide' (as opposed to 'remove')
				// keeps the node in the layout but must not paint it.
				final UGraphic ugNode = node.isHidden() ? ug.apply(UHidden.HIDDEN) : ug;
				image.drawU(ugNode.apply(UTranslate.point(corner)));
			}

			for (Entry<Link, SmetanaEdge> ent : smetanaPathes.entrySet())
				if (ent.getKey().isOpale() == false)
					ent.getValue().drawU(ug);
		}

		private XPoint2D moveToLayoutPosition(Entity leaf, ST_Agnode_s agnode) {
			final SvekNode node = getBibliotekon().getNode(leaf);
			// A port box may be wider than its marker (see getDim): keep the marker
			// centred in it, where the edges attach, instead of at its left side.
			final double padding = (node.getLayoutWidth() - node.getWidth()) / 2;
			final XPoint2D corner = getCorner(agnode).move(padding, 0);
			node.resetMove();
			node.moveDelta(corner.getX(), corner.getY());
			return corner;
		}

		// Routes and label positions use layout coordinates, so the measured and
		// the rendered diagram share them at different drawing origins.
		private void routeOrthogonalEdges(StringBounder stringBounder) {
			final Map<Entity, RectangleArea> nodeAreas = new LinkedHashMap<>();
			final List<RectangleArea> obstacles = new ArrayList<>();
			for (Map.Entry<Entity, ST_Agnode_s> ent : nodes.entrySet()) {
				final Entity entity = ent.getKey();
				// The frame of a cluster with entry or exit points follows their positions.
				moveToLayoutPosition(entity, ent.getValue());
				final SvekNode node = getBibliotekon().getNode(entity);
				final RectangleArea area = node.getRectangleArea();
				nodeAreas.put(entity, area);
				if (node.isHidden() == false)
					obstacles.add(area);
			}
			final List<RectangleArea> clusterAreas = new ArrayList<>();
			final List<RectangleArea> usedTracks = new ArrayList<>();
			// Entry and exit points move the frame of their cluster, which also
			// depends on the frames of the clusters inside it. The map lists outer
			// clusters first, so place them all and fit the inner ones first.
			// A hidden cluster keeps its layout frame, as it does when drawing.
			final Map<Entity, Cluster> placed = new LinkedHashMap<>();
			for (Map.Entry<Entity, ST_Agraph_s> ent : clusters.entrySet())
				placed.put(ent.getKey(), placeGroup(stringBounder, ymirror, ent.getKey(), ent.getValue()));
			final List<Entity> innerFirst = new ArrayList<>(placed.keySet());
			Collections.reverse(innerFirst);
			for (Entity entity : innerFirst)
				if (entity.isHidden() == false)
					placed.get(entity).fitToEntryExitPoints(stringBounder);

			for (Map.Entry<Entity, Cluster> ent : placed.entrySet()) {
				final Entity entity = ent.getKey();
				final Cluster cluster = ent.getValue();
				nodeAreas.put(entity, cluster.getRectangleArea());
				if (entity.isHidden())
					continue;
				clusterAreas.add(cluster.getRectangleArea());
				// An edge running along a border would disappear into it.
				usedTracks.addAll(OrthogonalPath.sides(cluster.getRectangleArea()));
				// The border remains traversable. Only the title is in the way.
				obstacles.addAll(cluster.getHeaderAreas(stringBounder));
			}
			final OrthogonalLabelPlacement placement = new OrthogonalLabelPlacement(obstacles);
			for (RectangleArea area : clusterAreas)
				placement.addClusterBorder(area);

			// Edges that share a node side divide it among themselves before any is routed.
			final OrthogonalPorts ports = new OrthogonalPorts(obstacles, clusterAreas);
			final Map<SmetanaEdge, OrthogonalPorts.Attachment> attachments = new LinkedHashMap<>();
			for (Entry<Link, SmetanaEdge> entry : smetanaPathes.entrySet()) {
				final Link link = entry.getKey();
				if (link.isHidden() || link.isOpale())
					continue;
				final OrthogonalPorts.Attachment attachment = entry.getValue().attach(stringBounder, nodeAreas, ports);
				if (attachment != null)
					attachments.put(entry.getValue(), attachment);
			}
			ports.assign(budget);

			final Map<SmetanaEdge, DotPath> visiblePaths = new LinkedHashMap<>();
			// Labels on both orthogonal routes and splines must clear every visible connector.
			for (Entry<Link, SmetanaEdge> entry : smetanaPathes.entrySet()) {
				final Link link = entry.getKey();
				if (link.isHidden())
					continue;
				final SmetanaEdge edge = entry.getValue();
				if (link.isOpale()) {
					edge.reserveNoteConnector(placement);
					continue;
				}
				final OrthogonalPorts.Attachment attachment = attachments.get(edge);
				if (attachment == null)
					continue;
				final DotPath path = edge.routeOrthogonally(stringBounder, attachment, obstacles, clusterAreas,
						usedTracks, budget);
				if (path != null) {
					visiblePaths.put(edge, path);
					edge.reserveConnector(placement, path, stringBounder);
				}
			}
			// End labels have less room to move than labels along the connector.
			for (Entry<SmetanaEdge, DotPath> entry : visiblePaths.entrySet())
				entry.getKey().placeEndpointLabels(placement, entry.getValue(), stringBounder);
			for (Entry<SmetanaEdge, DotPath> entry : visiblePaths.entrySet())
				entry.getKey().placeMiddleLabel(placement, entry.getValue(), stringBounder);
		}

		@Fast
		@Override
		public XDimension2D calculateDimension(StringBounder stringBounder) {
			final MinMax measured = getMeasuredMinMax(stringBounder);
			final XDimension2D baseline = getBaselineDimension();

			final double extraLeft = Math.max(0, -measured.getMinX());
			final double extraTop = Math.max(0, -measured.getMinY());
			final double extraRight = Math.max(0, measured.getMaxX() - baseline.getWidth());
			final double extraBottom = Math.max(0, measured.getMaxY() - baseline.getHeight());

			return new XDimension2D(baseline.getWidth() + extraLeft + extraRight,
					baseline.getHeight() + extraTop + extraBottom);
		}

		private XPoint2D getCorner(ST_Agnode_s n) {
			final BoxInfo data = BoxInfo.fromNode(n);
			return ymirror.getMirrored(data.getLowerLeft());
		}

		public HColor getBackcolor() {
			return null;
		}

	}

	// Duplicate GeneralImageBuilder
	private boolean isOpalisable(Entity entity) {
		if (entity.isGroup())
			return false;

		if (entity.getLeafType() != LeafType.NOTE)
			return false;

		final Link single = onlyOneLink(entity);
		if (single == null)
			return false;

		return single.getOther(entity).getLeafType() != LeafType.NOTE;
	}

	// Duplicate GeneralImageBuilder
	private Link onlyOneLink(Entity ent) {
		Link single = null;
		for (Link link : diagram.getLinks()) {
			if (link.isInvis())
				continue;
			if (link.contains(ent) == false)
				continue;

			if (single != null)
				return null;
			single = link;
		}
		return single;
	}

	private void drawGroup(UGraphic ug, YMirror ymirror, Entity group, ST_Agraph_s gr) {
		JUtils.LOG2("drawGroup");
		try {
			final Cluster cluster = placeGroup(ug.getStringBounder(), ymirror, group, gr);
			JUtils.LOG2("cluster=" + cluster);
			cluster.drawU(ug);
			// ug.apply(new UTranslate(llx, lly)).apply(HColors.BLUE).draw(new
			// URectangle(urx - llx, ury - lly));
		} catch (Exception e) {
			System.err.println("CANNOT DRAW GROUP");
		}
	}

	// Drawing a cluster with entry or exit points moves its frame onto them.
	// Start again from the layout each time, so that this happens only once.
	private Cluster placeGroup(StringBounder stringBounder, YMirror ymirror, Entity group, ST_Agraph_s gr) {
		final ST_Agrec_s tmp1 = gr.data;
		final ST_Agraphinfo_t data = (ST_Agraphinfo_t) tmp1;
		final BoxInfo boxInfo = BoxInfo.fromGraphInfo(data);
		final XPoint2D upperRight = ymirror.getMirrored(boxInfo.getUpperRight());
		final XPoint2D lowerLeft = ymirror.getMirrored(boxInfo.getLowerLeft());

		final Cluster cluster = getBibliotekon().getCluster(group);
		cluster.setPosition(upperRight, lowerLeft);

		final XDimension2D dimTitle = cluster.getTitleDimension(stringBounder);
		if (dimTitle != null) {
			final double x = (upperRight.getX() + lowerLeft.getX()) / 2 - dimTitle.getWidth() / 2;
			cluster.setTitlePosition(new XPoint2D(x, Math.min(upperRight.getY(), lowerLeft.getY())));
		}
		return cluster;
	}

	private void printAllSubgroups(StringBounder stringBounder, Entity parent) {
		for (Entity g : getChildrenGroups(parent)) {
			if (g.isRemoved())
				continue;

			if (diagram.isEmpty(g) && g.getGroupType() == GroupType.PACKAGE) {
				g.muteToType(LeafType.EMPTY_PACKAGE);
				this.printEntity(stringBounder, g);
			} else {
				this.printSingleGroup(stringBounder, g);
			}
		}
	}

	private void printSingleGroup(StringBounder stringBounder, Entity g) {
		if (g.getGroupType() == GroupType.CONCURRENT_STATE)
			return;

		if (g.isPacked() == false) {
			final ClusterHeader clusterHeader = new ClusterHeader(g, diagram, stringBounder);
			clusterManager.openCluster(g, clusterHeader);
		}

		this.printEntities(stringBounder, g.leafs());
		this.printAllSubgroups(stringBounder, g);

		if (g.isPacked() == false)
			clusterManager.closeCluster();

	}

	private void printEntities(StringBounder stringBounder, Collection<Entity> entities) {
		for (Entity ent : entities) {
			if (ent.isRemoved())
				continue;

			this.printEntity(stringBounder, ent);
		}
	}

	private void exportEntities(Globals zz, ST_Agraph_s cluster, Collection<Entity> entities) {
		for (Entity ent : entities) {
			if (ent.isRemoved())
				continue;
			exportEntity(zz, cluster, ent);
		}
	}

	private XDimension2D getDim(SvekNode node) {
		final double width = node.getLayoutWidth() / 72;
		final double height = node.getHeight() / 72;
		return new XDimension2D(width, height);
	}

	private ST_Agnode_s getCoreFromGroup(Globals zz, Entity group) {
		ST_Agnode_s result = coreNodes.get(group);
		if (result != null)
			return result;

		final ST_Agraph_s cluster = clusters.get(group);
		if (cluster == null)
			throw new IllegalStateException();

		result = agnode(zz, cluster, new CString("z" + group.getUid()), true);
		agsafeset(zz, result, new CString("shape"), new CString("box"), new CString(""));
		agsafeset(zz, result, new CString("width"), new CString("0.1"), new CString(""));
		agsafeset(zz, result, new CString("height"), new CString("0.1"), new CString(""));
		coreNodes.put(group, result);
		return result;
	}

	private void exportEntity(Globals zz, ST_Agraph_s cluster, Entity leaf) {
		final SvekNode node = getBibliotekon().getNode(leaf);
		if (node == null) {
			System.err.println("CANNOT FIND NODE");
			return;
		}
		final ST_Agnode_s agnode = agnode(zz, cluster, new CString(node.getUid()), true);
		// [DEBUG-Test_15] zdev.Test_15 investigation (SMETANA.md): map each real
		// Smetana node (whose safeName() shows as "CString:shNNNN" everywhere
		// else in the traces) back to its actual PlantUML entity name, so the
		// GD_nlist/ND_flat_out/ND_other traversal-order traces in flat__c can be
		// read directly without guessing which shNNNN is which A-node.
		if (false) SMETANA_TRACE("CucaDiagramFileMakerSmetana",
				"exportEntity: entity=" + leaf.getName() + " nodeUid=" + node.getUid());
		agsafeset(zz, agnode, new CString("shape"), new CString("box"), new CString(""));
		// These symbols attach edges at their painted bounds. Smetana's default
		// node label would enlarge their layout boxes beyond those bounds.
		if (leaf.getLeafType() == LeafType.POINT_FOR_ASSOCIATION || leaf.getLeafType() == LeafType.JUNCTION
				|| (leaf.getEntityPosition().usePortP() && isOrthogonal()))
			agsafeset(zz, agnode, new CString("label"), new CString(""), new CString(""));
		final XDimension2D dim = getDim(node);
		final String width = "" + dim.getWidth();
		final String height = "" + dim.getHeight();
		agsafeset(zz, agnode, new CString("width"), new CString(width), new CString(""));
		agsafeset(zz, agnode, new CString("height"), new CString(height), new CString(""));
		nodes.put(leaf, agnode);
	}

	private void printEntity(StringBounder stringBounder, Entity ent) {
		if (ent.isRemoved())
			throw new IllegalStateException();

		final IEntityImage image = printEntityInternal(ent);
		final SvekNode node = getBibliotekon().createNode(ent, image, stringBounder);
		clusterManager.addNode(node);
	}

	private Collection<Entity> getUnpackagedEntities() {
		final List<Entity> result = new ArrayList<>();
		for (Entity ent : diagram.leafs())
			if (root == ent.getParentContainer()) {
				// In a nested sub-layout of a concurrent state, the STATE_CONCURRENT
				// leaves are the other regions: they are stacked separately by
				// GroupMakerStateSmetana, so they must not be laid out here.
				if (isNestedLayout() && ent.getLeafType() == LeafType.STATE_CONCURRENT)
					continue;

				result.add(ent);
			}

		return result;
	}

	// A plain monitor rather than a ReentrantLock: the smetana port keeps its
	// state in Globals, so layout runs are serialized process-wide. No fairness
	// or interruptibility is used, so synchronized is equivalent on the JVM, and
	// unlike java.util.concurrent.locks it is available in the TeaVM classlib,
	// which the browser build needs now that "!pragma layout smetana" reaches
	// this class there.
	private static final Object lock = new Object();

	@Override
	public TextBlock getTextBlock(List<String> dotStrings, FileFormatOption fileFormatOption)
			throws IOException, InterruptedException {

		final StringBounder stringBounder = fileFormatOption.getDefaultStringBounder(diagram.getSkinParam(),
				diagram.getPragma());

		// Turn composite states into pre-rendered leaves, mirroring the dot pipeline.
		// Selective for now: concurrent states are left untouched (see the simplifier).
		if (diagram.getDiagramType() == DiagramType.STATE)
			new CucaDiagramSimplifierStateSmetana().simplify(diagram, stringBounder, budget);

		return layoutAndGetTextBlock(stringBounder);
	}

	// Layout the current root and return the resulting drawable.
	// Factored out of getTextBlock so that a sub-layout (e.g. a composite state
	// rendered as a leaf) can be produced from a StringBounder alone, mirroring
	// GraphvizImageBuilder.buildImage(stringBounder, ...) on the dot side.
	private TextBlock layoutAndGetTextBlock(StringBounder stringBounder) {

		this.printAllSubgroups(stringBounder, root);
		this.printEntities(stringBounder, getUnpackagedEntities());

		for (Link link : getLocalLinks()) {
			if (link.isRemoved())
				continue;

			if (isOpalisable(link.getEntity1())) {
				final SvekNode node = getBibliotekon().getNode(link.getEntity1());
				final SvekNode other = getBibliotekon().getNode(link.getEntity2());
				if (other != null) {
					((EntityImageNote) node.getImage()).setOpaleLink(link, node, other, smetanaPathes);
					link.setOpale(true);
				}
			} else if (isOpalisable(link.getEntity2())) {
				final SvekNode node = getBibliotekon().getNode(link.getEntity2());
				final SvekNode other = getBibliotekon().getNode(link.getEntity1());
				if (other != null) {
					((EntityImageNote) node.getImage()).setOpaleLink(link, node, other, smetanaPathes);
					link.setOpale(true);
				}
			}
		}

		// No monitor in the C build: it is single-threaded, and its monitors do not
		// survive a garbage collection happening while they are held
		final Drawing drawing;
		if (TeaVM.isC())
			drawing = layoutOpen(stringBounder);
		else
			synchronized (lock) {
				drawing = layoutOpen(stringBounder);
			}

		if (drawing == null)
			return TextBlockUtils.EMPTY_TEXT_BLOCK;

		// Routing only reads the finished layout, so it does not make other
		// diagrams wait for the lock.
		drawing.prepareEdges(stringBounder);
		return drawing;
	}

	// On some graphs with nested clusters the network simplex reports "trouble in
	// init_rank" (in the ranking or in the placement of the nodes): the layout
	// then drops edges and breaks the clusters apart. As with Graphviz (see
	// GraphvizImageBuilder), it is then run once more with newrank=true, which
	// handles those graphs (dot2_rank).
	private Drawing layoutOpen(StringBounder stringBounder) {
		Globals zz = Globals.open();
		try {
			final Drawing drawing = getTextBlockInternal(stringBounder, zz, false);
			if (drawing == null || isLayoutIncomplete(zz) == false)
				return drawing;
		} finally {
			Globals.close();
		}
		nodes.clear();
		coreNodes.clear();
		edges.clear();
		clusters.clear();
		zz = Globals.open();
		try {
			return getTextBlockInternal(stringBounder, zz, true);
		} finally {
			Globals.close();
		}
	}

	private boolean isLayoutIncomplete(Globals zz) {
		if (zz.initRankTroubles > 0)
			return true;

		for (Map.Entry<Link, ST_Agedge_s> ent : edges.entrySet())
			if (ent.getKey().isInvis() == false && ((ST_Agedgeinfo_t) ent.getValue().data).spl == null)
				return true;

		return false;
	}

	// Render the current root as a self-contained IEntityImage.
	// Used when a composite state is turned into a leaf and laid out by a nested
	// Smetana pass (see GroupMakerStateSmetana). The returned image is autonomous:
	// the layout is fully computed here, so drawing later does not require an open
	// Globals context.
	public IEntityImage getImage(StringBounder stringBounder) {
		final TextBlock textBlock = layoutAndGetTextBlock(stringBounder);
		return new TextBlockToEntityImage(textBlock);
	}

	// Returns null when there is nothing to lay out.
	private Drawing getTextBlockInternal(StringBounder stringBounder, Globals zz, boolean newrank) {

		final ST_Agraph_s g = agopen(zz, new CString("g"), zz.Agdirected, null);

		// Horizontal breathing room between the top-level clusters (e.g. a / a1 / c).
		// Their gap is NOT governed by each cluster's own margin but by the 'margin'
		// attribute of their container - here the root graph - since separate_subclust/
		// keepout_othernodes/contain_subclust all read late_int(g, G_margin, 8) on the
		// graph that owns the clusters (see gen.lib.dotgen.position__c). Note this only
		// affects horizontal separation: the vertical gap between stacked top-level
		// clusters is driven by ranksep, because clust_ht forces CL_OFFSET at the root.
		agsafeset(zz, g, new CString("margin"), new CString("16"), new CString(""));
		if (newrank)
			agsafeset(zz, g, new CString("newrank"), new CString("true"), new CString(""));

		// Honor an explicit "skinparam nodesep/ranksep" (issue #2903). Only explicit
		// values are forwarded: when they are not set, Smetana keeps its own
		// defaults (unlike the dot pipeline, which derives a minimum of 35/60 px),
		// so that existing diagrams are not moved.
		if (diagram.getSkinParam().getNodesep() != 0)
			agsafeset(zz, g, new CString("nodesep"),
					new CString(SvekUtils.pixelToInches(diagram.getSkinParam().getNodesep())), new CString(""));
		if (diagram.getSkinParam().getRanksep() != 0)
			agsafeset(zz, g, new CString("ranksep"),
					new CString(SvekUtils.pixelToInches(diagram.getSkinParam().getRanksep())), new CString(""));

		exportGraph(stringBounder, zz, g);

		addPortRankingEdges(zz, g);

		if (nodes.values().isEmpty() && clusters.values().isEmpty())
			return null;

		final ST_GVC_s gvc = gvContext(zz);
		SmetanaDebug.reset();
		if (rankdir == Rankdir.LEFT_TO_RIGHT)
			agsafeset(zz, g, new CString("rankdir"), new CString("LR"), new CString("LR"));
		gvLayoutJobs(zz, gvc, g);
		SmetanaDebug.printMe();

		// At the diagram root, keep the historical canvas margin (6). In a nested
		// sub-layout the surrounding InnerStateAutonom already provides the padding,
		// so we drop this margin to avoid extra space inside the composite state.
		final double canvasMargin = isNestedLayout() ? 0 : 6;
		return new Drawing(canvasMargin);
	}

	// Smetana has no {rank=source/sink} groups (unlike the dot pipeline), so a
	// portout without an incoming link floats to the top rank instead of sitting
	// on the bottom edge of its container (issue #2457). These invisible minlen
	// edges force every portout strictly below the content of its own cluster:
	// its plain leaves plus every leaf of nested clusters — a port-only child
	// cluster still occupies the container (issues #1602, #2032). They are not
	// registered in edges/smetanaPathes, so they only take part in ranking and
	// are never drawn. Clusters holding only ports get no extra edge and keep
	// their previous layout.
	private void addPortRankingEdges(Globals zz, ST_Agraph_s graph) {
		for (Map.Entry<Entity, ST_Agraph_s> ent : clusters.entrySet()) {
			final List<Entity> ports = new ArrayList<>();
			final List<Entity> content = new ArrayList<>();
			for (Entity leaf : ent.getKey().leafs()) {
				if (leaf.getEntityPosition() == EntityPosition.PORTOUT)
					ports.add(leaf);
				else if (leaf.getEntityPosition() == EntityPosition.NORMAL)
					content.add(leaf);

			}
			if (ports.isEmpty())
				continue;

			addDescendantLeafs(ent.getKey(), content);
			if (content.isEmpty())
				continue;
			for (Entity port : ports) {
				final ST_Agnode_s portNode = nodes.get(port);
				if (portNode == null)
					continue;

				for (Entity inside : content) {
					final ST_Agnode_s contentNode = nodes.get(inside);
					if (contentNode == null)
						continue;

					final ST_Agedge_s e = agedge(zz, graph, contentNode, portNode, null, true);
					agsafeset(zz, e, new CString("minlen"), new CString("1"), new CString(""));
				}
			}
		}
	}

	// Every leaf below the group counts as content, whatever its position: the
	// own-level ports are the objects being placed (selected above), but a
	// port-only child cluster still occupies layout space in the container.
	private void addDescendantLeafs(Entity group, List<Entity> content) {
		for (Entity child : getChildrenGroups(group)) {
			if (child.isRemoved())
				continue;

			content.addAll(child.leafs());

			addDescendantLeafs(child, content);
		}
	}

	// Builds the nodes, clusters and edges of the root graph in the order in which
	// the dot pipeline writes them to its .dot file (DotStringFactory with
	// Cluster.printCluster1/printCluster2 and Bibliotekon.lines0/lines1):
	//
	// 1. the start nodes of inverted links of the root level (see exportLevel),
	// 2. the links of length 1 between two leaves,
	// 3. the remaining nodes of the root level, then its clusters, recursively,
	// 4. all other links (longer links and links to or from a group).
	//
	// dot breaks ties in mincross by the order in which nodes and edges were
	// created, so the same input order gives the same left-to-right order as the
	// Graphviz rendering, and arrows such as -l-/-r- keep the order their author
	// tuned with Graphviz.
	//
	// The endpoints of the length-1 links are declared in the root graph before
	// the clusters exist; declaring them again later inside their cluster moves
	// the existing node into it (agnode -> agsubnode). This is what dot does when
	// it reads an edge statement before the subgraph statement of its nodes.
	private void exportGraph(StringBounder stringBounder, Globals zz, ST_Agraph_s g) {
		final List<Link> links = new ArrayList<>();
		for (Link link : getLocalLinks())
			if (link.isRemoved() == false)
				links.add(link);

		final Set<Entity> exportedLeaves = new HashSet<>();
		collectExportedLeaves(root, true, exportedLeaves);

		final List<Link> lines0 = new ArrayList<>();
		final List<Link> lines1 = new ArrayList<>();
		for (Link link : links)
			if (isLengthOneBetweenLeaves(link, exportedLeaves))
				addLengthOneLink(lines0, link);
			else
				lines1.add(link);

		final Map<Link, ST_Agedge_s> created = new HashMap<>();

		final List<Entity> rootLeaves = new ArrayList<>();
		final List<Entity> rootGroups = new ArrayList<>();
		collectLevel(root, true, rootLeaves, rootGroups);
		final List<Entity> rootStarts = getInvertedStarts(rootLeaves, links);
		exportEntities(zz, g, rootStarts);

		for (Link link : lines0) {
			final ST_Agnode_s node1 = declareInRootGraph(zz, g, link.getEntity1());
			final ST_Agnode_s node2 = declareInRootGraph(zz, g, link.getEntity2());
			created.put(link, createEdge(stringBounder, zz, g, link, node1, node2));
		}

		exportLevelContent(zz, g, rootLeaves, rootGroups, rootStarts, links);

		for (Link link : lines1)
			created.put(link, createEdge(stringBounder, zz, g, link, getAgnode(zz, link.getEntity1()),
					getAgnode(zz, link.getEntity2())));

		// The order given to dot only drives the layout. The SVG keeps drawing the
		// edges in the order of the links in the source, and the nodes in the order
		// of collectDrawingOrder.
		for (Link link : links) {
			final ST_Agedge_s e = created.get(link);
			if (e != null)
				edges.put(link, e);
		}

		final Map<Entity, ST_Agnode_s> exported = new LinkedHashMap<>(nodes);
		nodes.clear();
		final List<Entity> drawingOrder = new ArrayList<>();
		collectDrawingOrder(root, true, drawingOrder);
		for (Entity ent : drawingOrder) {
			final ST_Agnode_s n = exported.remove(ent);
			if (n != null)
				nodes.put(ent, n);
		}
		nodes.putAll(exported);
	}

	// The unpackaged entities, then the content of each group in source order,
	// depth first.
	private void collectDrawingOrder(Entity parent, boolean isLayoutRoot, List<Entity> result) {
		final Collection<Entity> leaves = isLayoutRoot ? getUnpackagedEntities() : parent.leafs();
		for (Entity ent : leaves)
			if (ent.isRemoved() == false)
				result.add(ent);

		for (Entity g : getChildrenGroups(parent)) {
			if (g.isRemoved())
				continue;

			if (diagram.isEmpty(g) && g.getGroupType() == GroupType.PACKAGE)
				result.add(g);
			else
				collectDrawingOrder(g, false, result);
		}
	}

	// Mirrors Bibliotekon.addLine: only links of length 1 are written before the
	// clusters. A link carrying a label, a note or a direction arrow
	// (SvekEdge.hasNoteLabelText) is put before the first plain link joining the
	// same two entities.
	private static void addLengthOneLink(List<Link> lines0, Link link) {
		if (hasLabelText(link))
			for (int i = 0; i < lines0.size(); i++) {
				final Link other = lines0.get(i);
				if (hasLabelText(other) == false && link.sameConnections(other)) {
					lines0.add(i, link);
					return;
				}
			}

		lines0.add(link);
	}

	// Same condition as SvekEdge.hasNoteLabelText, which is true as soon as the
	// edge has a label block, even an empty one: a label, a note on the link or a
	// direction arrow on the label all create one.
	private static boolean hasLabelText(Link link) {
		return Display.isNull(link.getLabel()) == false || link.getNote() != null
				|| link.getLinkArrow() != LinkArrow.NONE_OR_SEVERAL;
	}

	// Unlike Bibliotekon.addLine, a length-1 link to or from a group is not written
	// early. It ends on the core node of the group's cluster, which stands for the
	// center point of the dot pipeline (Cluster.getSpecialPointId). That point sits
	// beside extra clusters wrapping the cluster's content (ClusterDotString,
	// thereALinkFromOrToGroup1); Smetana builds no such clusters. Creating the core
	// node early without them puts it on the far side of the content, so the edge
	// would reach the cluster from behind its content.
	private boolean isLengthOneBetweenLeaves(Link link, Set<Entity> exportedLeaves) {
		if (link.getLength() != 1)
			return false;

		final Entity entity1 = link.getEntity1();
		final Entity entity2 = link.getEntity2();
		if (entity1.isGroup() || entity2.isGroup())
			return false;

		return exportedLeaves.contains(entity1) && exportedLeaves.contains(entity2);
	}

	private ST_Agnode_s declareInRootGraph(Globals zz, ST_Agraph_s g, Entity leaf) {
		final SvekNode node = getBibliotekon().getNode(leaf);
		return agnode(zz, g, new CString(node.getUid()), true);
	}

	private ST_Agnode_s getAgnode(Globals zz, Entity entity) {
		if (entity.isGroup())
			return getCoreFromGroup(zz, entity);

		return getAgnodeFromLeaf(entity);
	}

	// Lists what belongs directly to the graph of 'parent', in the order in which
	// the dot pipeline registers the nodes of its Cluster and so writes them
	// (GraphvizImageBuilder.printGroups/printGroup): the leaves, then the groups,
	// in source order.
	//
	// Empty packages are leaves too: printAllSubgroups has already turned them
	// into EMPTY_PACKAGE leaves, which leafs() lists at their source position. The
	// dot pipeline registers them while it walks the child groups, so they follow
	// the other leaves of a cluster. At the layout root they come before the
	// unpackaged entities instead, as the groups are printed first there.
	//
	// A packed group is listed among the groups like any other: the dot pipeline
	// keeps it as a child Cluster and writes its content, without a subgraph of
	// its own, at its position among the children (ClusterDotString).
	private void collectLevel(Entity parent, boolean isLayoutRoot, List<Entity> leaves, List<Entity> groups) {
		final List<Entity> emptyPackages = new ArrayList<>();
		final List<Entity> otherLeaves = new ArrayList<>();
		for (Entity ent : isLayoutRoot ? getUnpackagedEntities() : parent.leafs()) {
			if (ent.isRemoved())
				continue;

			if (ent.getLeafType() == LeafType.EMPTY_PACKAGE)
				emptyPackages.add(ent);
			else
				otherLeaves.add(ent);
		}

		if (isLayoutRoot) {
			leaves.addAll(emptyPackages);
			leaves.addAll(otherLeaves);
		} else {
			leaves.addAll(otherLeaves);
			leaves.addAll(emptyPackages);
		}

		for (Entity g : getChildrenGroups(parent))
			if (g.isRemoved() == false)
				groups.add(g);
	}

	// Every leaf that exportGraph turns into a node, so that a link is only
	// written early when both of its ends really get a node.
	private void collectExportedLeaves(Entity parent, boolean isLayoutRoot, Set<Entity> result) {
		final List<Entity> leaves = new ArrayList<>();
		final List<Entity> groups = new ArrayList<>();
		collectLevel(parent, isLayoutRoot, leaves, groups);
		for (Entity leaf : leaves)
			if (getBibliotekon().getNode(leaf) != null)
				result.add(leaf);

		for (Entity group : groups)
			if (group.isPacked() || getBibliotekon().getCluster(group) != null)
				collectExportedLeaves(group, false, result);
	}

	// Mirrors Cluster.getNodesOrderedTop: the start node of every inverted link
	// that sits at this level in a normal position comes first. An arrow pointing
	// left or up is stored inverted: "A -l- B" becomes a link from B to A, whose
	// start is B. Each start is inserted at the front, so the last such link gives
	// the first node.
	private static List<Entity> getInvertedStarts(List<Entity> leaves, List<Link> links) {
		final List<Entity> result = new ArrayList<>();
		for (Link link : links) {
			if (link.isInverted() == false)
				continue;

			final Entity start = link.getEntity1();
			if (start.getEntityPosition() == EntityPosition.NORMAL && leaves.contains(start)) {
				result.remove(start);
				result.add(0, start);
			}
		}
		return result;
	}

	// Mirrors Cluster.printCluster1 followed by Cluster.printCluster2 for one
	// cluster: the start nodes of inverted links, the other leaves, then the
	// nested clusters. For a packed group, 'graph' is the graph of its parent.
	private void exportLevel(Globals zz, ST_Agraph_s graph, Entity parent, List<Link> links) {
		final List<Entity> leaves = new ArrayList<>();
		final List<Entity> groups = new ArrayList<>();
		collectLevel(parent, false, leaves, groups);
		final List<Entity> starts = getInvertedStarts(leaves, links);
		exportEntities(zz, graph, starts);
		exportLevelContent(zz, graph, leaves, groups, starts, links);
	}

	private void exportLevelContent(Globals zz, ST_Agraph_s graph, List<Entity> leaves, List<Entity> groups,
			List<Entity> alreadyExported, List<Link> links) {
		for (Entity leaf : leaves)
			if (alreadyExported.contains(leaf) == false)
				exportEntity(zz, graph, leaf);

		for (Entity group : groups)
			exportGroup(zz, graph, group, links);
	}

	private void exportGroup(Globals zz, ST_Agraph_s graph, Entity group, List<Link> links) {
		// A packed group draws no frame of its own: its content goes into the parent
		// graph, ordered as a level of its own (ClusterDotString, packed case).
		if (group.isPacked()) {
			exportLevel(zz, graph, group, links);
			return;
		}

		final Cluster cluster = getBibliotekon().getCluster(group);
		if (cluster == null) {
			System.err.println("CucaDiagramFileMakerSmetana::exportGroup issue");
			return;
		}
		JUtils.LOG2("cluster = " + cluster.getClusterId());
		final ST_Agraph_s cluster1 = agsubg(zz, graph, new CString(cluster.getClusterId()), true);
		if (cluster.isLabel()) {
			final double width = cluster.getTitleAndAttributeWidth();
			// +8: artificial extra margin for the Smetana pipeline only (issue #1638 -
			// Smetana does not reserve enough vertical space between a cluster's title
			// and its nested components, unlike the external dot pipeline).
			final double height = cluster.getTitleAndAttributeHeight() - 5 + 8;
			agsafeset(zz, cluster1, new CString("label"), createLabelDim(width, height), new CString(""));
		}
		// Base containment margin applied to EVERY cluster. Smetana's default is
		// CL_OFFSET = 8 (see gen.lib.dotgen.position__c: clust_ht for the vertical
		// padding, separate_subclust for the horizontal gap between two sibling
		// sub-clusters, contain_subclust/keepout_othernodes for neighbours). Each of
		// them reads the 'margin' attribute of the graph it processes, so the gap
		// between two nested packages (e.g. d and d2 inside c) is driven by the
		// margin set on their PARENT cluster. The default 8 packs packages quite
		// tightly, so bump it a little to give nested clusters some breathing room.
		// --> single knob to tune the overall spacing between clusters.
		int clusterMargin = 16;

		// Shapes that need extra room for their own decoration (e.g. USymbolNode's
		// diagonal 3D corner cut) need even more, so nested content doesn't overlap.
		final USymbol uSymbol = group.getUSymbol();
		if (uSymbol != null && uSymbol.suppWidthBecauseOfShape() > 0)
			clusterMargin = Math.max(clusterMargin, 20);

		agsafeset(zz, cluster1, new CString("margin"), new CString("" + clusterMargin), new CString(""));

		this.clusters.put(group, cluster1);
		this.exportLevel(zz, cluster1, group, links);
	}

	private CString createLabelDim(final double width, final double height) {
		return Macro.createHackInitDimensionFromLabel((int) width, (int) height);
	}

	private Style getStyle() {
		return diagram.getSkinParam().getCurrentStyleBuilder()
				.getMergedStyle(StyleQueries.ARROW.add(diagram.getDiagramType().getStyleName()));
	}

	// Duplication from SvekEdge
	private StyleQuery getDefaultStyleDefinitionArrow(Stereotype stereotype, SName styleName) {
		StyleQuery result = StyleQueries.ARROW.add(styleName);
		if (stereotype != null)
			result = result.withStereotype(stereotype);

		return result;
	}

	private FontConfiguration getFontForLink(Link link, final ISkinParam skinParam) {
		final SName styleName = skinParam.getDiagramType().getStyleName();

		final Style style = link.getStyleBuilder()
				.getMergedStyle(getDefaultStyleDefinitionArrow(link.getStereotype(), styleName));
		return style.getFontConfiguration(skinParam.getIHtmlColorSet());
	}

	private HorizontalAlignment getMessageTextAlignment(DiagramType diagramType, ISkinParam skinParam) {
		if (diagramType == DiagramType.STATE)
			return skinParam.getHorizontalAlignment(AlignmentParam.stateMessageAlignment, null, false, null);

		return skinParam.getDefaultTextAlignment(HorizontalAlignment.CENTER);
	}

	private TextBlock addVisibilityModifier(TextBlock block, Link link, ISkinParam skinParam) {
		final VisibilityModifier visibilityModifier = link.getVisibilityModifier();
		if (visibilityModifier != null) {
			final Rose rose = new Rose();
			final HColor fore = rose.getHtmlColor(skinParam, visibilityModifier.getForeground());
			TextBlock visibility = visibilityModifier.getUBlock(skinParam.classAttributeIconSize(), fore, null, false);
			visibility = TextBlockUtils.withMargin(visibility, 0, 1, 2, 0);
			block = TextBlockUtils.mergeLR(visibility, block, VerticalAlignment.CENTER);
		}
		final double marginLabel = 1; // startUid.equalsId(endUid) ? 6 : 1;
		return TextBlockUtils.withMargin(block, marginLabel, marginLabel);
	}

	private LinkArrow getLinkArrow(Link link) {
		return link.getLinkArrow();
	}

	private TextBlock getLabel(StringBounder stringBounder, Link link) {
		final ISkinParam skinParam = diagram.getSkinParam();
		final double marginLabel = 1; // startUid.equals(endUid) ? 6 : 1;

		// final FontConfiguration labelFont =
		// style.getFontConfiguration(skinParam.getIHtmlColorSet());
//		TextBlock labelOnly = link.getLabel().create(labelFont,
//				skinParam.getDefaultTextAlignment(HorizontalAlignment.CENTER), skinParam);

		final DiagramType type = skinParam.getDiagramType();
		final FontConfiguration font = getFontForLink(link, skinParam);

		TextBlock labelOnly;
		// toto2
		if (Display.isNull(link.getLabel())) {
			labelOnly = TextBlockUtils.EMPTY_TEXT_BLOCK;
			if (getLinkArrow(link) != LinkArrow.NONE_OR_SEVERAL) {
				// labelOnly = StringWithArrow.addMagicArrow(labelOnly, this, font);
			}

		} else {
			final HorizontalAlignment alignment = getMessageTextAlignment(type, skinParam);
			final boolean hasSeveralGuideLines = link.getLabel().hasSeveralGuideLines();
			final TextBlock block;
			// if (hasSeveralGuideLines)
			// block = StringWithArrow.addSeveralMagicArrows(link.getLabel(), this, font,
			// alignment, skinParam);
			// else
			final Style arrowStyle = link.getStyleBuilder().getMergedStyle(getDefaultStyleDefinitionArrow(
					link.getStereotype(), skinParam.getDiagramType().getStyleName()));
			final LineBreakStrategy styleWidth = arrowStyle.wrapWidth();
			final LineBreakStrategy wrapWidth = styleWidth.getMaxWidth() > 0 ? styleWidth : skinParam.maxMessageSize();
			block = link.getLabel().create0(font, alignment, skinParam, wrapWidth, CreoleMode.SIMPLE_LINE, null, null);

			labelOnly = addVisibilityModifier(block, link, skinParam);
			if (getLinkArrow(link) != LinkArrow.NONE_OR_SEVERAL && hasSeveralGuideLines == false) {
				// labelOnly = StringWithArrow.addMagicArrow(labelOnly, this, font);
			}

		}

		final CucaNote note = link.getNote();
		if (note == null) {
			if (TextBlockUtils.isEmpty(labelOnly, stringBounder) == false)
				labelOnly = TextBlockUtils.withMargin(labelOnly, marginLabel, marginLabel);
			return labelOnly;
		}
		final TextBlock noteOnly = new EntityImageNoteLink(note.getDisplay(), note.getColors(), skinParam,
				link.getStyleBuilder());

		if (note.getPosition() == Position.LEFT)
			return TextBlockUtils.mergeLR(noteOnly, labelOnly, VerticalAlignment.CENTER);
		else if (note.getPosition() == Position.RIGHT)
			return TextBlockUtils.mergeLR(labelOnly, noteOnly, VerticalAlignment.CENTER);
		else if (note.getPosition() == Position.TOP)
			return TextBlockUtils.mergeTB(noteOnly, labelOnly, HorizontalAlignment.CENTER);
		else
			return TextBlockUtils.mergeTB(labelOnly, noteOnly, HorizontalAlignment.CENTER);

	}

	private TextBlock getQuantifier(StringBounder stringBounder, Link link, int n) {
		final String tmp = n == 1 ? link.getQuantifier1() : link.getQuantifier2();
		if (tmp == null)
			return null;

		final double marginLabel = 1; // startUid.equals(endUid) ? 6 : 1;
		ISkinParam skinParam = diagram.getSkinParam();
		final Style style = getStyle();
		final FontConfiguration labelFont = style.getFontConfiguration(skinParam.getIHtmlColorSet());
		final TextBlock label = Display.getWithNewlines(diagram.getPragma(), tmp).create(labelFont,
				skinParam.getDefaultTextAlignment(HorizontalAlignment.CENTER), skinParam);
		if (TextBlockUtils.isEmpty(label, stringBounder))
			return label;

		return TextBlockUtils.withMargin(label, marginLabel, marginLabel);
	}

	private TextBlock getRoleLabel(StringBounder stringBounder, Link link, int n) {
		final String role = n == 1 ? link.getRole1() : link.getRole2();
		if (role == null)
			return null;

		final double marginLabel = 1;
		ISkinParam skinParam = diagram.getSkinParam();
		final Style style = getStyle();
		final FontConfiguration labelFont = style.getFontConfiguration(skinParam.getIHtmlColorSet());
		final TextBlock label = RoleLabels.create(role, diagram.getPragma(), labelFont, skinParam);
		if (TextBlockUtils.isEmpty(label, stringBounder))
			return label;

		return TextBlockUtils.withMargin(label, marginLabel, marginLabel);
	}

	private ST_Agnode_s getAgnodeFromLeaf(Entity entity) {
		final ST_Agnode_s n = nodes.get(entity);
		if (n != null)
			return n;

		try {
			final String id = getBibliotekon().getNodeUid((Entity) entity);
			for (Map.Entry<Entity, ST_Agnode_s> ent : nodes.entrySet())
				if (id.equals(getBibliotekon().getNodeUid(ent.getKey())))
					return ent.getValue();

		} catch (IllegalStateException e) {
			System.err.println("UNKNOWN ENTITY");
		}
		return null;

	}

	private ST_Agedge_s createEdge(StringBounder stringBounder, Globals zz, final ST_Agraph_s g, Link link,
			ST_Agnode_s node1, ST_Agnode_s node2) {

		if (node1 == null || node2 == null)
			return null;
		// throw new IllegalStateException();

		final ST_Agedge_s e = agedge(zz, g, node1, node2, null, true);
		// [DEBUG-flat-label] Cross-reference key for flat__c.flat_node's
		// "origEdgeIdentityHash" trace: this is the edge object SmetanaEdge
		// ultimately holds, so any identityHash seen further down the
		// pipeline (dotsplines__c, flat__c, position__c) can be traced back
		// here to the real PlantUML entity names/label. See SMETANA.md,
		// zdev.Test_15 investigation.
		if (false) SMETANA_TRACE("CucaDiagramFileMakerSmetana",
				"createEdge: edgeIdentityHash=" + System.identityHashCode(e)
				+ " entity1=" + link.getEntity1().getName() + " entity2=" + link.getEntity2().getName()
				+ " isSelfLoop=" + link.getEntity1().equals(link.getEntity2())
				+ " label=" + link.getLabel());
		agsafeset(zz, e, new CString("arrowtail"), new CString("none"), new CString(""));
		agsafeset(zz, e, new CString("arrowhead"), new CString("none"), new CString(""));

		int length = link.getLength();
		agsafeset(zz, e, new CString("minlen"), new CString("" + (length - 1)), new CString(""));
		if (link.isPortoutToOwnContent())
			agsafeset(zz, e, new CString("constraint"), new CString("false"), new CString(""));

		final TextBlock label = getLabel(stringBounder, link);
		if (TextBlockUtils.isEmpty(label, stringBounder) == false) {
			final XDimension2D dimLabel = label.calculateDimension(stringBounder);
			final CString hackDim = createLabelDim(dimLabel.getWidth(), dimLabel.getHeight());
			agsafeset(zz, e, new CString("label"), hackDim, new CString(""));
		}
		final TextBlock q1 = getQuantifier(stringBounder, link, 1);
		final TextBlock r1 = getRoleLabel(stringBounder, link, 1);
		final TextBlock tailForLayout = q1 != null ? q1 : r1;
		if (tailForLayout != null) {
			final XDimension2D dimLabel = tailForLayout.calculateDimension(stringBounder);
			final CString hackDim = createLabelDim(dimLabel.getWidth(), dimLabel.getHeight());
			agsafeset(zz, e, new CString("taillabel"), hackDim, new CString(""));
		}
		final TextBlock q2 = getQuantifier(stringBounder, link, 2);
		final TextBlock r2 = getRoleLabel(stringBounder, link, 2);
		final TextBlock headForLayout = q2 != null ? q2 : r2;
		if (headForLayout != null) {
			final XDimension2D dimLabel = headForLayout.calculateDimension(stringBounder);
			final CString hackDim = createLabelDim(dimLabel.getWidth(), dimLabel.getHeight());
			agsafeset(zz, e, new CString("headlabel"), hackDim, new CString(""));
		}
		return e;
	}

	private IEntityImage printEntityInternal(Entity ent) {
		if (ent.isRemoved())
			throw new IllegalStateException();

		if (ent.getSvekImage() == null) {
			ISkinParam skinParam = diagram.getSkinParam();
			if (skinParam.sameClassWidth()) {
				System.err.println("NOT YET IMPLEMENTED");
//				throw new UnsupportedOperationException();
				// final double width = getMaxWidth();
				// skinParam = new SkinParamSameClassWidth(dotData.getSkinParam(), width);
			}

			final IEntityImage result = GeneralImageBuilder.createEntityImageBlock(ent,
					diagram.isHideEmptyDescriptionForState(), diagram, getBibliotekon(), null, diagram.getLinks());
			ent.setSvekImage(result);
			return result;
		}
		return ent.getSvekImage();
	}

}