SpritesJsGenerator.java

/* ========================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyright 2009-2025, 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.klimt.sprite;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Generates <code>src/main/teavm/generated/sprites.js</code>, the companion
 * script that makes the internal SVG sprites (src/main/resources/sprites, for
 * instance the ArchiMate icons) available to the TeaVM (browser) build.
 * <p>
 * The browser build has no classpath, so {@link SpriteImage#fromInternal}
 * cannot reach <code>/sprites/...</code>. This generator writes those same SVG
 * files into a JS map on <code>PLANTUML_SPRITES</code>, which the engine loads
 * on demand through {@code ScriptLoaderJs}, exactly like
 * <code>themes.js</code> and <code>openiconic.js</code>. The PNG sprites are
 * left out, as in the C build.
 * <p>
 * Run it after adding or editing a sprite:
 *
 * <pre>
 * java net.sourceforge.plantuml.klimt.sprite.SpritesJsGenerator
 * </pre>
 */
public final class SpritesJsGenerator {

	static final String SPRITES_DIR = "src/main/resources/sprites";

	private static final String OUTPUT = "src/main/teavm/generated/sprites.js";

	public static void main(String[] args) throws IOException {
		final File spritesDir = new File(SPRITES_DIR);
		if (spritesDir.isDirectory() == false)
			throw new IOException("Sprites directory does not exist: " + spritesDir.getAbsolutePath());

		final File output = new File(OUTPUT);
		if (output.getParentFile().isDirectory() == false)
			throw new IOException("Target directory does not exist: " + output.getParentFile());

		final List<String> names = listSpriteNames(spritesDir);

		// Written with explicit \n line endings so the output is byte-identical on
		// every platform.
		final StringBuilder out = new StringBuilder();
		out.append("// sprites.js - Generated by SpritesJsGenerator.main()\n");
		out.append("// Do not edit manually\n");
		out.append("(function () {\n");
		out.append("var g = (typeof globalThis !== 'undefined') ? globalThis"
				+ " : ((typeof self !== 'undefined') ? self : this);\n");
		out.append("g.PLANTUML_SPRITES = g.PLANTUML_SPRITES || {};\n");
		out.append("\n");
		for (String name : names) {
			final File file = new File(spritesDir, name + ".svg");
			final String content = readSvg(file);
			out.append("g.PLANTUML_SPRITES[").append(toJsLiteral(name)).append("]=").append(toJsLiteral(content))
					.append(";\n");
		}
		out.append("})();\n");
		Files.write(output.toPath(), out.toString().getBytes(StandardCharsets.UTF_8));

		System.out.println("Generated " + output.getAbsolutePath() + " (" + names.size() + " sprites)");
	}

	/**
	 * The content of an SVG sprite, as written in sprites.js.
	 */
	static String readSvg(File file) throws IOException {
		return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8).replace("\r\n", "\n");
	}

	/**
	 * The names of the SVG sprites, as used in <code>&lt;$folder/name&gt;</code>,
	 * sorted.
	 */
	static List<String> listSpriteNames(File spritesDir) throws IOException {
		final File[] folders = spritesDir.listFiles();
		if (folders == null)
			throw new IOException("Cannot list " + spritesDir.getAbsolutePath());

		final List<String> result = new ArrayList<>();
		for (File folder : folders) {
			if (folder.isDirectory() == false)
				continue;
			final String[] files = folder.list();
			if (files == null)
				throw new IOException("Cannot list " + folder.getAbsolutePath());
			for (String file : files)
				if (file.endsWith(".svg"))
					result.add(folder.getName() + "/" + file.substring(0, file.length() - ".svg".length()));
		}
		Collections.sort(result);
		return result;
	}

	/**
	 * Renders a string as a JS double-quoted literal. Everything outside printable
	 * ASCII is escaped as \\uXXXX so the generated file stays pure ASCII.
	 */
	static String toJsLiteral(String value) {
		final StringBuilder sb = new StringBuilder("\"");
		for (int i = 0; i < value.length(); i++) {
			final char c = value.charAt(i);
			switch (c) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				if (c < 0x20 || c > 0x7E)
					sb.append(String.format("\\u%04x", (int) c));
				else
					sb.append(c);
			}
		}
		return sb.append('"').toString();
	}

	private SpritesJsGenerator() {
	}

}