HorizontalLinkOrder.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.svek;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sourceforge.plantuml.abel.EntityPosition;
import net.sourceforge.plantuml.klimt.geom.Rankdir;

/**
 * Issue #1825: the order in which one cluster has to declare its content so that
 * horizontal links keep their tail on the left of their head.
 * <p>
 * A horizontal link (a single dash: {@code ->}, {@code -left->},
 * {@code -right->}) becomes a flat edge with {@code minlen=0}, and graphviz keeps
 * the tail of a flat edge before its head, but only when both ends belong to the
 * same cluster. When one end sits in a sub-cluster, graphviz leaves the edge out
 * while it orders the current level ({@code interclrep} in {@code class2.c}:
 * {@code if (ND_rank(t) == ND_rank(h)) return;}) and places the plain nodes and
 * the sub-clusters in an order of its own, so the arrow can end up pointing
 * backwards. Sibling clusters, on the other hand, keep their declaration order.
 * <p>
 * So the plain ends of such links are wrapped in an anonymous cluster, as
 * {@code together} does, and the items of this level are declared tail first.
 * When no horizontal link reaches a sub-cluster, nothing changes.
 * <p>
 * This is applied inside a cluster and in top-to-bottom mode only (the case of
 * the issue): see {@link #of}.
 */
final class HorizontalLinkOrder {

	private final Set<SvekNode> wrapped;
	private final List<Object> sequence;

	private HorizontalLinkOrder(Set<SvekNode> wrapped, List<Object> sequence) {
		this.wrapped = wrapped;
		this.sequence = sequence;
	}

	private static final HorizontalLinkOrder NONE = new HorizontalLinkOrder(Collections.<SvekNode>emptySet(),
			Collections.emptyList());

	static HorizontalLinkOrder of(Cluster cluster, Collection<SvekEdge> lines, Rankdir rankdir) {
		// At the root, the edges are declared before any node, so graphviz creates
		// the nodes in edge order and that order decides, whatever the declaration
		// order of the clusters: the root is left as it is. Left-to-right mode is
		// left as it is too: a one-dash link runs vertically there, and graphviz
		// alone would put its tail below its head, which is not what is drawn today.
		if (cluster.getParentCluster() == null || rankdir != Rankdir.TOP_TO_BOTTOM)
			return NONE;

		// Every uid of this level, mapped to the item that declares it: a node of
		// this cluster, or the child cluster whose subtree holds it. Items that
		// belong to a together group are left alone: the group already orders them.
		final Map<String, Object> itemOf = new HashMap<>();
		final List<Object> items = new ArrayList<>();
		for (SvekNode node : cluster.getNodes())
			if (node.getEntityPosition() == EntityPosition.NORMAL && node.getTogether() == null
					&& itemOf.containsKey(node.getUid()) == false) {
				itemOf.put(node.getUid(), node);
				items.add(node);
			}

		for (Cluster child : cluster.getChildren())
			if (child.getGroup().getTogether() == null) {
				collectUids(child, child, itemOf);
				items.add(child);
			}

		final List<Object[]> pairs = new ArrayList<>();
		for (SvekEdge line : lines) {
			if (line.getLength() != 1)
				continue;

			final Object tail = itemOf.get(line.getStartUidPrefix());
			final Object head = itemOf.get(line.getEndUidPrefix());
			if (tail != null && head != null && tail != head)
				pairs.add(new Object[] { tail, head });
		}

		// Only a link that reaches a sub-cluster needs help. A plain node joined to
		// a wrapped one by a horizontal link is wrapped as well, otherwise their own
		// flat edge would become an inter-cluster one and lose its order too.
		final Set<Object> involved = new LinkedHashSet<>();
		for (Object[] pair : pairs)
			if (pair[0] instanceof Cluster || pair[1] instanceof Cluster) {
				involved.add(pair[0]);
				involved.add(pair[1]);
			}

		boolean changed = involved.isEmpty() == false;
		while (changed) {
			changed = false;
			for (Object[] pair : pairs)
				if (involved.contains(pair[0]) != involved.contains(pair[1])) {
					involved.add(pair[0]);
					involved.add(pair[1]);
					changed = true;
				}
		}
		if (involved.isEmpty())
			return NONE;

		final Set<SvekNode> wrapped = new LinkedHashSet<>();
		final List<Object> start = new ArrayList<>();
		for (Object item : items)
			if (item instanceof SvekNode && involved.contains(item)) {
				wrapped.add((SvekNode) item);
				start.add(item);
			}

		for (Object item : items)
			if (item instanceof Cluster)
				start.add(item);

		return new HorizontalLinkOrder(wrapped, sort(start, pairs, involved));
	}

	private static void collectUids(Cluster cluster, Cluster item, Map<String, Object> itemOf) {
		for (SvekNode node : cluster.getNodes())
			itemOf.put(node.getUid(), item);

		for (Cluster child : cluster.getChildren())
			collectUids(child, item, itemOf);
	}

	// Stable topological sort: an item comes out as soon as every tail it is the
	// head of has come out, otherwise the declaration order is kept. A cycle of
	// horizontal links cannot be satisfied, so it falls back to that order.
	private static List<Object> sort(List<Object> start, List<Object[]> pairs, Set<Object> involved) {
		final List<Object> pending = new ArrayList<>(start);
		final List<Object> result = new ArrayList<>();
		while (pending.isEmpty() == false) {
			Object next = pending.get(0);
			for (Object candidate : pending)
				if (hasPendingTail(candidate, pending, pairs, involved) == false) {
					next = candidate;
					break;
				}
			pending.remove(next);
			result.add(next);
		}
		return result;
	}

	private static boolean hasPendingTail(Object item, List<Object> pending, List<Object[]> pairs,
			Set<Object> involved) {
		for (Object[] pair : pairs)
			if (pair[1] == item && pair[0] != item && involved.contains(pair[0]) && pending.contains(pair[0]))
				return true;

		return false;
	}

	boolean isEmpty() {
		return sequence.isEmpty();
	}

	boolean isWrapped(SvekNode node) {
		return wrapped.contains(node);
	}

	/**
	 * The wrapped nodes and the child clusters outside any together group, in the
	 * order they have to be declared.
	 */
	List<Object> getSequence() {
		return sequence;
	}

}