PSystemError.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.error;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import net.sourceforge.plantuml.ErrorUml;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.FileImageData;
import net.sourceforge.plantuml.UgDiagram;
import net.sourceforge.plantuml.api.ImageDataSimple;
import net.sourceforge.plantuml.core.DiagramDescription;
import net.sourceforge.plantuml.core.ImageData;
import net.sourceforge.plantuml.core.UmlSource;
import net.sourceforge.plantuml.crash.ReportLog;
import net.sourceforge.plantuml.eggs.PSystemWelcome;
import net.sourceforge.plantuml.error.messages.MessageRenderer;
import net.sourceforge.plantuml.error.messages.MessageRule;
import net.sourceforge.plantuml.error.messages.MessageSelector;
import net.sourceforge.plantuml.klimt.color.HColors;
import net.sourceforge.plantuml.klimt.font.FontConfiguration;
import net.sourceforge.plantuml.klimt.geom.GraphicPosition;
import net.sourceforge.plantuml.klimt.geom.HorizontalAlignment;
import net.sourceforge.plantuml.klimt.geom.XDimension2D;
import net.sourceforge.plantuml.klimt.shape.GraphicStrings;
import net.sourceforge.plantuml.klimt.shape.TextBlock;
import net.sourceforge.plantuml.klimt.shape.TextBlockRaw;
import net.sourceforge.plantuml.klimt.shape.TextBlockUtils;
import net.sourceforge.plantuml.log.Logme;
import net.sourceforge.plantuml.preproc.PreprocessingArtifact;
import net.sourceforge.plantuml.security.SecurityUtils;
import net.sourceforge.plantuml.teavm.TeaVM;
import net.sourceforge.plantuml.text.BackSlash;
import net.sourceforge.plantuml.text.StringLocated;
import net.sourceforge.plantuml.utils.LineLocation;
import net.sourceforge.plantuml.version.Version;

public abstract class PSystemError extends UgDiagram {

	protected List<StringLocated> trace;
	protected ErrorUml singleError;

	public PSystemError(UmlSource source, PreprocessingArtifact preprocessing) {
		super(source, preprocessing);
	}

	final protected StringLocated getLastLine() {
		return trace.get(trace.size() - 1);
	}

	final public LineLocation getLineLocation() {
		return getLastLine().getLocation();
	}

	final public Collection<ErrorUml> getErrorsUml() {
		return Collections.singleton(singleError);
	}

	final public ErrorUml getFirstError() {
		return singleError;
	}

	final public String getWarningOrError() {
		final StringBuilder sb = new StringBuilder();
		sb.append(getDescription());
		sb.append(BackSlash.CHAR_NEWLINE);
		for (CharSequence t : getTitle().getDisplay()) {
			sb.append(t);
			sb.append(BackSlash.CHAR_NEWLINE);
		}
		sb.append(BackSlash.CHAR_NEWLINE);
		return sb.toString();
	}

	private TextBlock getGraphicalFormatted() {
		final FontConfiguration fc0 = GraphicStrings.sansSerif14(HColors.BLACK).bold();
		final FontConfiguration fc1 = GraphicStrings.sansSerif14(HColors.MY_GREEN).bold();
		final FontConfiguration fc2 = GraphicStrings.sansSerif14(HColors.RED).bold();
		final FontConfiguration fc4 = GraphicStrings.sansSerif12(HColors.MY_GREEN).bold().italic();

		final List<String> fullBody = getTextFullBody();
		final TextBlock result0 = TextBlockUtils.addBackcolor(
				TextBlockUtils.withMargin(new TextBlockRaw(getTextFromStack(), fc0), 1, 1, 1, 4), HColors.MY_GREEN);
		final TextBlock result1 = new TextBlockRaw(allButLast(fullBody), fc1);
		final TextBlock result2 = new TextBlockRaw(onlyLast(fullBody), fc1.wave(HColors.RED));
		final TextBlock result3 = new TextBlockRaw(getTextError(), fc2);
		final TextBlock result4 = TextBlockUtils.withMargin(new TextBlockRaw(header(), fc4), 0, 2, 0, 8);
		TextBlock result = result0;
		result = TextBlockUtils.mergeTB(result, result1, HorizontalAlignment.LEFT);
		result = TextBlockUtils.mergeTB(result, result2, HorizontalAlignment.LEFT);
		result = TextBlockUtils.mergeTB(result, result3, HorizontalAlignment.LEFT);
		result = TextBlockUtils.mergeTB(result4, result, HorizontalAlignment.LEFT);
		result = TextBlockUtils.withMargin(result, 5, 5);
		return TextBlockUtils.addBackcolor(result, HColors.BLACK);
	}

	private List<String> header() {
		final ReportLog result = new ReportLog();
		if (!Logme.MODE_VEGA) {
			result.add(Version.fullDescription());
			result.checkOldVersionWarningRaw();
		}
		return result.asList();
	}

	// Where the error was found, the source up to the faulty line, that line
	// underlined, and
	// the message
	public List<String> getPureAsciiFormatted() {
		final List<String> result = getTextFromStack();
		final List<String> body = getTextFullBody();
		result.addAll(body);
		result.add(underline(body.get(body.size() - 1)));
		result.addAll(getTextError());
		return result;
	}

	// Carets under the text of a line, its indentation kept
	private static String underline(String line) {
		final StringBuilder sb = new StringBuilder();
		int i = 0;
		while (i < line.length() && Character.isWhitespace(line.charAt(i))) {
			sb.append(line.charAt(i) == '\t' ? '\t' : ' ');
			i++;
		}
		final int end = line.trim().isEmpty() ? i + 1 : line.length();
		while (i < end) {
			sb.append('^');
			i++;
		}
		return sb.toString();
	}

	/**
	 * ATXT and UTXT: the error as plain text (see {@link #getPureAsciiFormatted}).
	 * The graphical image drawn as text would be as wide as its pixels, and would
	 * put the message at the very end, under the welcome text added to a short
	 * source.
	 */
	@Override
	protected ImageData exportTxt(OutputStream os, int index, FileFormat fileFormat) throws IOException {
		final PrintStream ps = SecurityUtils.createPrintStream(os, true, StandardCharsets.UTF_8);
		// Without trailing spaces, as the blank line before the source
		for (String line : getPureAsciiFormatted())
			ps.println(line.replaceAll("\\s+$", ""));
		ps.flush();
		return new ImageDataSimple(new XDimension2D(0, 0), FileImageData.ERROR);
	}

	private List<String> getTextFromStack() {
		LineLocation lineLocation = getLineLocation();
		final List<String> result = new ArrayList<>();
		if (lineLocation != null) {
			append(result, lineLocation);
			while (lineLocation.getParent() != null) {
				lineLocation = lineLocation.getParent();
				append(result, lineLocation);
			}
		}
		return result;
	}

	protected List<String> getTextFullBody() {
		final List<String> result = new ArrayList<>();
		result.add(" ");
		final int traceSize = trace.size();
		if (traceSize > 40) {
			for (StringLocated s : trace.subList(0, 5))
				addToResult(result, s);

			result.add("...");
			final int skipped = traceSize - 5 - 20;
			result.add("... ( skipping " + skipped + " lines )");
			result.add("...");
			for (StringLocated s : trace.subList(traceSize - 20, traceSize))
				addToResult(result, s);

		} else {
			for (StringLocated s : trace)
				addToResult(result, s);

		}
		return result;
	}

	private void addToResult(final List<String> result, StringLocated s) {
		String tmp = s.getString();
		if (tmp.length() > 120)
			tmp = tmp.substring(0, 120) + " ...";

		result.add(tmp);
	}

	private List<String> getTextError() {
		return Arrays.asList(" " + singleError.getError());
	}

	@Override
	public TextBlock getTextBlock(int num, FileFormatOption fileFormatOption) throws IOException {
		TextBlock result = getGraphicalFormatted();

		if (!TeaVM.isTeaVM() && !Logme.MODE_VEGA)
			if (getSource().getTotalLineCountLessThan5())
				result = addWelcome(result);

		// MessageSelector decides, Vega mode included (see its Vega clock)
		result = addMessage(result);

		return result;
	}

	// The message of messages.yaml chosen right now, if any: drawing it never breaks the error diagram
	private TextBlock addMessage(TextBlock result) {
		try {
			final MessageRule rule = MessageSelector.selectNow(getSource());
			if (rule == null)
				return result;

			return MessageRenderer.decorate(result, rule);
		} catch (RuntimeException e) {
			Logme.error(e);
			return result;
		}
	}

	private void append(List<String> result, LineLocation lineLocation) {
		if (lineLocation.getDescription() != null)
			result.add("[From " + lineLocation.getDescription() + " (line " + (lineLocation.getPosition() + 1) + ") ]");

	}

	final public DiagramDescription getDescription() {
		return new DiagramDescription("(Error)");
	}

	private List<String> allButLast(List<String> full) {
		return full.subList(0, full.size() - 1);
	}

	private List<String> onlyLast(List<String> full) {
		return full.subList(full.size() - 1, full.size());
	}

	private TextBlock getWelcome() {
		return new PSystemWelcome(getSource(), GraphicPosition.BACKGROUND_CORNER_TOP_RIGHT, getPreprocessingArtifact())
				.getTextBlock(0, null);
	}

	private TextBlock addWelcome(final TextBlock result) {
		final TextBlock welcome = getWelcome();
		return TextBlockUtils.mergeTB(welcome, result, HorizontalAlignment.LEFT);
	}

	public int score() {
		final int result = trace.size() * 10 + singleError.score();
		return result;
	}

}