HtmlParser.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.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Reads an HTML-like label with the grammar of Graphviz {@code htmlparse.y}:
* <pre>
* label : fonttext | fonttable
* fonttable : table | font fonttable /font (font: FONT B I U O S SUB SUP)
* table : TABLE rows /TABLE
* rows : row ( [HR] row )*
* row : TR cell ( [VR] cell )* /TR
* cell : TD ( fonttable | fonttext | IMG )? /TD
* fonttext : ( string | BR | font fonttext /font )*
* </pre>
* As in {@code htmllex.c}, the text outside the cells of a table is ignored,
* the control characters of a text are dropped and its
* spaces are kept. Names are case-insensitive.
*/
final class HtmlParser {
private static final List<String> FONT_TAGS = Arrays.asList("FONT", "B", "I", "U", "O", "S", "SUB",
"SUP");
private static final Map<String, Integer> ENTITIES = new HashMap<String, Integer>();
static {
final Object[] entities = { "amp", 38, "lt", 60, "gt", 62, "quot", 34, "apos", 39, "nbsp", 160, "iexcl", 161,
"cent", 162, "pound", 163, "yen", 165, "sect", 167, "copy", 169, "laquo", 171, "reg", 174, "deg", 176,
"plusmn", 177, "sup2", 178, "sup3", 179, "micro", 181, "para", 182, "middot", 183, "raquo", 187,
"frac14", 188, "frac12", 189, "frac34", 190, "times", 215, "divide", 247, "euro", 8364, "bull", 8226,
"hellip", 8230, "ndash", 8211, "mdash", 8212, "lsquo", 8216, "rsquo", 8217, "ldquo", 8220, "rdquo",
8221, "larr", 8592, "uarr", 8593, "rarr", 8594, "darr", 8595, "harr", 8596, "lArr", 8656, "rArr", 8658,
"hArr", 8660, "forall", 8704, "exist", 8707, "empty", 8709, "isin", 8712, "notin", 8713, "sum", 8721,
"minus", 8722, "infin", 8734, "and", 8743, "or", 8744, "cap", 8745, "cup", 8746, "ne", 8800, "equiv",
8801, "le", 8804, "ge", 8805, "sub", 8834, "sup", 8835, "alpha", 945, "beta", 946, "gamma", 947,
"delta", 948, "epsilon", 949, "lambda", 955, "mu", 956, "pi", 960, "sigma", 963, "tau", 964, "phi",
966, "omega", 969, "Delta", 916, "Sigma", 931, "Omega", 937, "trade", 8482, "dagger", 8224, "check",
10003 };
for (int i = 0; i < entities.length; i += 2)
ENTITIES.put((String) entities[i], (Integer) entities[i + 1]);
}
private enum Kind {
TEXT, START, END, EOF
}
private static final class Token {
final Kind kind;
final String name;
final String text;
final HtmlAttributes attributes;
Token(Kind kind, String name, String text, HtmlAttributes attributes) {
this.kind = kind;
this.name = name;
this.text = text;
this.attributes = attributes;
}
boolean isStart(String tag) {
return kind == Kind.START && name.equals(tag);
}
boolean isEnd(String tag) {
return kind == Kind.END && name.equals(tag);
}
@Override
public String toString() {
if (kind == Kind.TEXT)
return "'" + text + "'";
if (kind == Kind.EOF)
return "end of label";
return (kind == Kind.END ? "</" : "<") + name + ">";
}
}
private final List<Token> tokens;
private int pos;
HtmlParser(String content) throws HtmlSyntaxException {
this.tokens = tokenize(content);
}
// ------------------------------------------------------------------
// Tokens
private static List<Token> tokenize(String s) throws HtmlSyntaxException {
final List<Token> result = new ArrayList<Token>();
int i = 0;
final StringBuilder text = new StringBuilder();
while (i < s.length()) {
final char c = s.charAt(i);
if (c != '<') {
text.append(c);
i++;
continue;
}
if (s.startsWith("<!--", i)) {
final int end = s.indexOf("-->", i + 4);
if (end == -1)
throw new HtmlSyntaxException("Unclosed comment");
i = end + 3;
continue;
}
if (text.length() > 0) {
result.add(new Token(Kind.TEXT, null, decode(text.toString()), null));
text.setLength(0);
}
final int end = tagEnd(s, i);
result.addAll(tag(s.substring(i + 1, end)));
i = end + 1;
}
if (text.length() > 0)
result.add(new Token(Kind.TEXT, null, decode(text.toString()), null));
result.add(new Token(Kind.EOF, null, null, null));
return result;
}
/** The position of the {@code >} closing the tag at {@code start}, quotes skipped. */
private static int tagEnd(String s, int start) throws HtmlSyntaxException {
char quote = 0;
for (int i = start + 1; i < s.length(); i++) {
final char c = s.charAt(i);
if (quote != 0) {
if (c == quote)
quote = 0;
} else if (c == '"' || c == '\'') {
quote = c;
} else if (c == '>') {
return i;
}
}
throw new HtmlSyntaxException("Unclosed tag");
}
/** One tag, or two for {@code <BR/>} written as a start and an end. */
private static List<Token> tag(String inside) throws HtmlSyntaxException {
final List<Token> result = new ArrayList<Token>();
String s = inside.trim();
if (s.startsWith("/")) {
final String name = s.substring(1).trim().toUpperCase();
if (name.length() == 0)
throw new HtmlSyntaxException("Empty end tag");
result.add(new Token(Kind.END, name, null, null));
return result;
}
boolean selfClosing = false;
if (s.endsWith("/")) {
selfClosing = true;
s = s.substring(0, s.length() - 1).trim();
}
int i = 0;
while (i < s.length() && isNameChar(s.charAt(i)))
i++;
final String name = s.substring(0, i).toUpperCase();
if (name.length() == 0)
throw new HtmlSyntaxException("Bad tag <" + inside + ">");
final HtmlAttributes attributes = new HtmlAttributes();
while (true) {
while (i < s.length() && Character.isWhitespace(s.charAt(i)))
i++;
if (i >= s.length())
break;
final int startName = i;
while (i < s.length() && isNameChar(s.charAt(i)))
i++;
if (startName == i)
throw new HtmlSyntaxException("Bad attribute in <" + inside + ">");
final String attName = s.substring(startName, i);
while (i < s.length() && Character.isWhitespace(s.charAt(i)))
i++;
String value = "";
if (i < s.length() && s.charAt(i) == '=') {
i++;
while (i < s.length() && Character.isWhitespace(s.charAt(i)))
i++;
if (i < s.length() && (s.charAt(i) == '"' || s.charAt(i) == '\'')) {
final char quote = s.charAt(i);
final int end = s.indexOf(quote, i + 1);
value = s.substring(i + 1, end);
i = end + 1;
} else {
final int startValue = i;
while (i < s.length() && Character.isWhitespace(s.charAt(i)) == false)
i++;
value = s.substring(startValue, i);
}
}
attributes.put(attName, decode(value));
}
result.add(new Token(Kind.START, name, null, attributes));
if (selfClosing)
result.add(new Token(Kind.END, name, null, null));
return result;
}
private static boolean isNameChar(char c) {
return Character.isLetterOrDigit(c) || c == '-' || c == '_' || c == ':' || c == '.';
}
/** Replaces the entities ({@code &}, {@code ©}, {@code ©}...). */
static String decode(String s) {
if (s.indexOf('&') == -1)
return s;
final StringBuilder sb = new StringBuilder();
int i = 0;
while (i < s.length()) {
final char c = s.charAt(i);
final int semicolon = c == '&' ? s.indexOf(';', i) : -1;
if (semicolon != -1 && semicolon - i <= 10) {
final String name = s.substring(i + 1, semicolon);
final int code = entity(name);
if (code != -1) {
sb.appendCodePoint(code);
i = semicolon + 1;
continue;
}
}
sb.append(c);
i++;
}
return sb.toString();
}
private static int entity(String name) {
try {
if (name.startsWith("#x") || name.startsWith("#X"))
return Integer.parseInt(name.substring(2), 16);
if (name.startsWith("#"))
return Integer.parseInt(name.substring(1));
} catch (NumberFormatException e) {
return -1;
}
final Integer result = ENTITIES.get(name);
return result == null ? -1 : result;
}
// ------------------------------------------------------------------
// Grammar
private Token peek() {
return tokens.get(pos);
}
private Token next() {
return tokens.get(pos++);
}
/**
* Skips the text around the tags of a table: as in Graphviz, it is ignored
* ({@code opt_space} of htmlparse.y, and no text outside the cells).
*/
private void skipText() {
while (peek().kind == Kind.TEXT)
pos++;
}
private void expectEnd(String tag) throws HtmlSyntaxException {
skipText();
final Token token = next();
if (token.isEnd(tag) == false)
throw new HtmlSyntaxException("Expected </" + tag + "> but found " + token);
}
private static HtmlSyntaxException unexpected(Token token) {
return new HtmlSyntaxException("Unexpected " + token);
}
HtmlLabel parseLabel() throws HtmlSyntaxException {
final HtmlLabel result;
if (startsTable()) {
result = new HtmlLabel(parseFontTable(HtmlFont.NONE), null);
skipText();
} else {
final HtmlText text = new HtmlText();
parseText(text, HtmlFont.NONE, null);
result = new HtmlLabel(null, text);
}
if (peek().kind != Kind.EOF)
throw unexpected(peek());
return result;
}
/** Tells whether a table comes next, maybe inside font elements. */
private boolean startsTable() {
for (int i = pos; i < tokens.size(); i++) {
final Token token = tokens.get(i);
if (token.kind == Kind.TEXT)
continue;
if (token.kind == Kind.START && FONT_TAGS.contains(token.name))
continue;
return token.isStart("TABLE");
}
return false;
}
private HtmlTable parseFontTable(HtmlFont font) throws HtmlSyntaxException {
skipText();
final Token token = next();
if (token.isStart("TABLE"))
return parseTable(token.attributes, font);
if (token.kind == Kind.START && FONT_TAGS.contains(token.name)) {
final HtmlTable result = parseFontTable(font.with(token.name, token.attributes));
expectEnd(token.name);
return result;
}
throw unexpected(token);
}
private HtmlTable parseTable(HtmlAttributes attributes, HtmlFont font) throws HtmlSyntaxException {
final HtmlTable table = new HtmlTable(attributes, font);
boolean rule = false;
while (true) {
skipText();
final Token token = next();
if (token.isEnd("TABLE"))
break;
if (token.isStart("HR") && table.getRows().size() > 0 && rule == false) {
expectEnd("HR");
rule = true;
continue;
}
if (token.isStart("TR") == false)
throw unexpected(token);
table.addRow(rule);
rule = false;
parseRow(table, font);
}
if (table.getRows().size() == 0 || rule)
throw new HtmlSyntaxException("A table needs rows");
return table;
}
private void parseRow(HtmlTable table, HtmlFont font) throws HtmlSyntaxException {
boolean rule = false;
int count = 0;
while (true) {
skipText();
final Token token = next();
if (token.isEnd("TR"))
break;
if (token.isStart("VR") && count > 0 && rule == false) {
expectEnd("VR");
rule = true;
continue;
}
if (token.isStart("TD") == false)
throw unexpected(token);
final HtmlCell cell = new HtmlCell(token.attributes);
if (rule)
cell.setRuledBefore();
rule = false;
parseCell(cell, font);
table.addCell(cell);
count++;
}
if (count == 0 || rule)
throw new HtmlSyntaxException("A row needs cells");
}
private void parseCell(HtmlCell cell, HtmlFont font) throws HtmlSyntaxException {
if (startsTable()) {
cell.setTable(parseFontTable(font));
expectEnd("TD");
return;
}
final int start = pos;
skipText();
if (peek().isStart("IMG")) {
// Images are not supported: the cell stays empty
next();
expectEnd("IMG");
expectEnd("TD");
return;
}
pos = start;
final HtmlText text = new HtmlText();
parseText(text, font, "TD");
if (text.isEmpty() == false)
cell.setText(text);
}
/**
* Reads a text up to the end tag {@code end} (consumed), or to the end of
* the label when {@code end} is {@code null}.
*/
private void parseText(HtmlText text, HtmlFont font, String end) throws HtmlSyntaxException {
while (true) {
final Token token = next();
if (end == null && token.kind == Kind.EOF) {
pos--;
return;
}
if (end != null && token.isEnd(end))
return;
if (token.kind == Kind.TEXT) {
text.add(dropControlCharacters(token.text), font);
} else if (token.isStart("BR")) {
expectEnd("BR");
text.endLine(justification(token.attributes.getKeyword("ALIGN")));
} else if (token.kind == Kind.START && FONT_TAGS.contains(token.name)) {
parseText(text, font.with(token.name, token.attributes), token.name);
} else {
throw unexpected(token);
}
}
}
static char justification(String align) {
if ("LEFT".equals(align))
return 'l';
if ("RIGHT".equals(align))
return 'r';
if ("CENTER".equals(align))
return 'c';
return 0;
}
private static String dropControlCharacters(String s) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) >= ' ')
sb.append(s.charAt(i));
return sb.toString();
}
}