RecordLabel.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.attr;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The label of a {@code record} node: a list of fields, each one being a text
 * (with an optional port name) or a nested list turned the other way.
 * <p>
 * The parsing follows {@code parse_reclbl} of Graphviz 2.38
 * ({@code lib/common/shapes.c}): {@code |} separates the fields, braces open a
 * nested list, {@code <name>} gives a port to a text field, {@code \{ \} \| \< \>}
 * are literal characters and {@code \ } is a space that is never collapsed.
 * The other escapes ({@code \n}, {@code \l}, {@code \r}...) are kept for the
 * drawing of the text. The spaces are collapsed and trimmed as in Graphviz.
 */
public final class RecordLabel {

	// The mode bits of parse_reclbl
	private static final int HASTEXT = 1;
	private static final int HASPORT = 2;
	private static final int HASTABLE = 4;
	private static final int INTEXT = 8;
	private static final int INPORT = 16;

	private final boolean leftToRight;
	private final List<RecordLabel> fields;
	private final String text;
	private final String port;

	private RecordLabel(boolean leftToRight, List<RecordLabel> fields) {
		this.leftToRight = leftToRight;
		this.fields = Collections.unmodifiableList(fields);
		this.text = null;
		this.port = null;
	}

	private RecordLabel(String text, String port) {
		this.leftToRight = true;
		this.fields = Collections.emptyList();
		this.text = text;
		this.port = port;
	}

	/**
	 * Parses a record label, or returns {@code null} when Graphviz would report
	 * a bad label format.
	 *
	 * @param leftToRight how the top-level fields are laid out: left to right
	 *                    with {@code rankdir=TB} or {@code BT}, top to bottom
	 *                    with {@code LR} or {@code RL}
	 */
	public static RecordLabel parse(String label, boolean leftToRight) {
		final Parser parser = new Parser(label == null ? "" : label);
		return parser.parse(leftToRight, true);
	}

	/** A text field, for a record built by program. */
	public static RecordLabel field(String text, String port) {
		return new RecordLabel(text, port);
	}

	/** A list of fields, for a record built by program. */
	public static RecordLabel list(boolean leftToRight, List<RecordLabel> fields) {
		return new RecordLabel(leftToRight, new ArrayList<RecordLabel>(fields));
	}

	/**
	 * A record made of one text field, what Graphviz uses for a bad label.
	 */
	public static RecordLabel single(String text, boolean leftToRight) {
		final List<RecordLabel> fields = new ArrayList<RecordLabel>();
		fields.add(new RecordLabel(text, null));
		return new RecordLabel(leftToRight, fields);
	}

	public boolean isLeaf() {
		return text != null;
	}

	/** For a list: {@code true} when its fields are side by side. */
	public boolean isLeftToRight() {
		return leftToRight;
	}

	public List<RecordLabel> getFields() {
		return fields;
	}

	/** For a text field: its text, with the escapes of a label. */
	public String getText() {
		return text;
	}

	/** For a text field: its port name, or {@code null}. */
	public String getPort() {
		return port;
	}

	/** The text fields, depth first. */
	public List<RecordLabel> getLeaves() {
		final List<RecordLabel> result = new ArrayList<RecordLabel>();
		addLeaves(result);
		return result;
	}

	private void addLeaves(List<RecordLabel> result) {
		if (isLeaf())
			result.add(this);
		else
			for (RecordLabel field : fields)
				field.addLeaves(result);
	}

	@Override
	public String toString() {
		if (isLeaf())
			return (port == null ? "" : "<" + port + ">") + "'" + text + "'";
		final StringBuilder sb = new StringBuilder(leftToRight ? "LR[" : "TB[");
		for (int i = 0; i < fields.size(); i++) {
			if (i > 0)
				sb.append(", ");
			sb.append(fields.get(i));
		}
		return sb.append("]").toString();
	}

	private static final class Parser {

		private final String s;
		private int pos;

		Parser(String s) {
			this.s = s;
		}

		private char current() {
			return pos < s.length() ? s.charAt(pos) : '\0';
		}

		private static boolean endsWithSpace(StringBuilder sb) {
			return sb.length() > 0 && sb.charAt(sb.length() - 1) == ' ';
		}

		/**
		 * Removes one trailing space, unless it is a hard space or the only
		 * character, as parse_reclbl does when a field or a port ends.
		 */
		private static String trim(StringBuilder sb, int hardSpace) {
			if (sb.length() > 1 && sb.length() - 1 != hardSpace && endsWithSpace(sb))
				sb.setLength(sb.length() - 1);
			return sb.toString();
		}

		RecordLabel parse(boolean leftToRight, boolean top) {
			final List<RecordLabel> fields = new ArrayList<RecordLabel>();
			final StringBuilder text = new StringBuilder();
			final StringBuilder port = new StringBuilder();
			int hardText = -1;
			int hardPort = -1;
			String pendingPort = null;
			int mode = 0;
			while (true) {
				char c = current();
				if (c != '\0' && c < ' ') {
					// Ignore non-0 control characters
					pos++;
					continue;
				}
				boolean hardSpace = false;
				switch (c) {
				case '<':
					if ((mode & (HASTABLE | HASPORT)) != 0)
						return null;
					mode |= HASPORT | INPORT;
					pos++;
					port.setLength(0);
					hardPort = -1;
					continue;
				case '>':
					if ((mode & INPORT) == 0)
						return null;
					pendingPort = trim(port, hardPort);
					mode &= ~INPORT;
					pos++;
					continue;
				case '{':
					pos++;
					if (mode != 0 || current() == '\0')
						return null;
					mode = HASTABLE;
					final RecordLabel sub = parse(leftToRight == false, false);
					if (sub == null)
						return null;
					fields.add(sub);
					continue;
				case '}':
				case '|':
				case '\0':
					if ((c == '\0' && top == false) || (mode & INPORT) != 0)
						return null;
					if ((mode & HASTABLE) == 0) {
						if ((mode & (HASTEXT | HASTABLE)) == 0) {
							// An empty field is a space
							text.setLength(0);
							text.append(' ');
						}
						fields.add(new RecordLabel(trim(text, hardText), pendingPort));
						pendingPort = null;
					}
					text.setLength(0);
					hardText = -1;
					if (c == '\0' || c == '}') {
						pos++;
						return new RecordLabel(leftToRight, fields);
					}
					mode = 0;
					pos++;
					continue;
				case '\\':
					if (pos + 1 < s.length()) {
						final char next = s.charAt(pos + 1);
						if (next == '{' || next == '}' || next == '|' || next == '<' || next == '>') {
							pos++;
						} else if (next == ' ') {
							hardSpace = true;
							pos++;
						} else {
							// Kept for the drawing of the text (\n, \l, \r, \\...)
							text.append('\\');
							mode |= INTEXT | HASTEXT;
							pos++;
						}
					}
					c = current();
					break;
				default:
					break;
				}

				// dotext
				if ((mode & HASTABLE) != 0 && c != ' ')
					return null;
				if ((mode & (INTEXT | INPORT)) == 0 && c != ' ')
					mode |= INTEXT | HASTEXT;
				if ((mode & INTEXT) != 0) {
					if ((c == ' ' && hardSpace == false && endsWithSpace(text)) == false)
						text.append(c);
					if (hardSpace)
						hardText = text.length() - 1;
				} else if ((mode & INPORT) != 0) {
					if ((c == ' ' && hardSpace == false && (port.length() == 0 || endsWithSpace(port))) == false)
						port.append(c);
					if (hardSpace)
						hardPort = port.length() - 1;
				}
				pos++;
			}
		}
	}

}