summaryrefslogtreecommitdiff
path: root/src/net/sourceforge/plantuml/Run.java
blob: 7182af853d60bd2f6aa4191edfb1e388f6dc9e57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
/* ========================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyright 2009-2017, Arnaud Roques
 *
 * Project Info:  http://plantuml.com
 * 
 * If you like this project or if you find it useful, you can support us at:
 * 
 * http://plantuml.com/patreon (only 1$ per month!)
 * http://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;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.imageio.ImageIO;
import javax.swing.UIManager;

import net.sourceforge.plantuml.activitydiagram.ActivityDiagramFactory;
import net.sourceforge.plantuml.classdiagram.ClassDiagramFactory;
import net.sourceforge.plantuml.code.Transcoder;
import net.sourceforge.plantuml.code.TranscoderUtil;
import net.sourceforge.plantuml.command.UmlDiagramFactory;
import net.sourceforge.plantuml.descdiagram.DescriptionDiagramFactory;
import net.sourceforge.plantuml.ftp.FtpServer;
import net.sourceforge.plantuml.objectdiagram.ObjectDiagramFactory;
import net.sourceforge.plantuml.png.MetadataTag;
import net.sourceforge.plantuml.preproc.Stdlib;
import net.sourceforge.plantuml.sequencediagram.SequenceDiagramFactory;
import net.sourceforge.plantuml.statediagram.StateDiagramFactory;
import net.sourceforge.plantuml.stats.StatsUtils;
import net.sourceforge.plantuml.swing.MainWindow2;
import net.sourceforge.plantuml.syntax.LanguageDescriptor;
import net.sourceforge.plantuml.ugraphic.sprite.SpriteGrayLevel;
import net.sourceforge.plantuml.ugraphic.sprite.SpriteUtils;
import net.sourceforge.plantuml.utils.Cypher;
import net.sourceforge.plantuml.version.Version;

public class Run {

	private static Cypher cypher;

	public static void main(String[] argsArray) throws IOException, InterruptedException {
		System.setProperty("log4j.debug", "false");
		final long start = System.currentTimeMillis();
		if (argsArray.length > 0 && argsArray[0].equalsIgnoreCase("-headless")) {
			System.setProperty("java.awt.headless", "true");
		}
		saveCommandLine(argsArray);
		final Option option = new Option(argsArray);
		ProgressBar.setEnable(option.isTextProgressBar());
		if (OptionFlags.getInstance().isClipboardLoop()) {
			ClipboardLoop.runLoop();
			return;
		}
		if (OptionFlags.getInstance().isClipboard()) {
			ClipboardLoop.runOnce();
			return;
		}
		if (OptionFlags.getInstance().isExtractStdLib()) {
			Stdlib.extractStdLib();
			return;
		}
		if (OptionFlags.getInstance().isStdLib()) {
			Stdlib.printStdLib();
			return;
		}
		if (OptionFlags.getInstance().isDumpStats()) {
			StatsUtils.dumpStats();
			return;
		}
		if (OptionFlags.getInstance().isLoopStats()) {
			StatsUtils.loopStats();
			return;
		}
		if (OptionFlags.getInstance().isDumpHtmlStats()) {
			StatsUtils.outHtml();
			return;
		}
		if (OptionFlags.getInstance().isEncodesprite()) {
			encodeSprite(option.getResult());
			return;
		}
		if (OptionFlags.getInstance().isVerbose()) {
			Log.info("PlantUML Version " + Version.versionString());
			Log.info("GraphicsEnvironment.isHeadless() " + GraphicsEnvironment.isHeadless());
		}
		if (GraphicsEnvironment.isHeadless()) {
			Log.info("Forcing -Djava.awt.headless=true");
			System.setProperty("java.awt.headless", "true");
			Log.info("java.awt.headless set as true");

		}
		if (OptionFlags.getInstance().isPrintFonts()) {
			printFonts();
			return;
		}

		if (option.getFtpPort() != -1) {
			goFtp(option);
			return;
		}

		forceOpenJdkResourceLoad();
		if (option.getPreprocessorOutputMode() == OptionPreprocOutputMode.CYPHER) {
			cypher = new LanguageDescriptor().getCypher();
		}
		boolean error = false;
		boolean forceQuit = false;
		if (option.isPattern()) {
			managePattern();
		} else if (OptionFlags.getInstance().isGui()) {
			try {
				UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			} catch (Exception e) {
			}
			final List<String> list = option.getResult();
			File dir = null;
			if (list.size() == 1) {
				final File f = new File(list.get(0));
				if (f.exists() && f.isDirectory()) {
					dir = f;
				}
			}
			new MainWindow2(option, dir);
		} else if (option.isPipe() || option.isPipeMap() || option.isSyntax()) {
			error = managePipe(option);
			forceQuit = true;
		} else if (option.isFailfast2()) {
			if (option.isSplash()) {
				Splash.createSplash();
			}
			final long start2 = System.currentTimeMillis();
			option.setCheckOnly(true);
			error = manageAllFiles(option);
			option.setCheckOnly(false);
			if (option.isDuration()) {
				final double duration = (System.currentTimeMillis() - start2) / 1000.0;
				Log.error("Check Duration = " + duration + " seconds");
			}
			if (error == false) {
				error = manageAllFiles(option);
			}
			forceQuit = true;
		} else {
			if (option.isSplash()) {
				Splash.createSplash();
			}
			error = manageAllFiles(option);
			forceQuit = true;
		}

		if (option.isDuration()) {
			final double duration = (System.currentTimeMillis() - start) / 1000.0;
			Log.error("Duration = " + duration + " seconds");
		}

		if (error) {
			Log.error("Some diagram description contains errors");
			System.exit(1);
		}

		if (forceQuit && OptionFlags.getInstance().isSystemExit()) {
			System.exit(0);
		}
	}

	private static String commandLine = "";

	public static final String getCommandLine() {
		return commandLine;
	}

	private static void saveCommandLine(String[] argsArray) {
		final StringBuilder sb = new StringBuilder();
		for (String s : argsArray) {
			sb.append(s);
			sb.append(" ");
		}
		commandLine = sb.toString();
	}

	public static void forceOpenJdkResourceLoad() {
		if (isOpenJdkRunning()) {
			// see https://github.com/plantuml/plantuml/issues/123
			Log.info("Forcing resource load on OpenJdk");
			final BufferedImage imDummy = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
			final Graphics2D gg = imDummy.createGraphics();
			final String text = "Alice";
			final Font font = new Font("SansSerif", Font.PLAIN, 12);
			final FontMetrics fm = gg.getFontMetrics(font);
			final Rectangle2D rect = fm.getStringBounds(text, gg);
		}
	}

	public static boolean isOpenJdkRunning() {
		final String jvmName = System.getProperty("java.vm.name");
		if (jvmName != null && jvmName.toLowerCase().contains("openjdk")) {
			return true;
		}
		return false;
	}

	static private final String httpProtocol = "http://";
	static private final String httpsProtocol = "https://";

	private static void encodeSprite(List<String> result) throws IOException {
		SpriteGrayLevel level = SpriteGrayLevel.GRAY_16;
		boolean compressed = false;
		final String path;
		if (result.size() > 1 && result.get(0).matches("(4|8|16)z?")) {
			if (result.get(0).startsWith("8")) {
				level = SpriteGrayLevel.GRAY_8;
			}
			if (result.get(0).startsWith("4")) {
				level = SpriteGrayLevel.GRAY_4;
			}
			compressed = StringUtils.goLowerCase(result.get(0)).endsWith("z");
			path = result.get(1);
		} else {
			path = result.get(0);
		}

		final String fileName;
		final URL source;
		final String lowerPath = StringUtils.goLowerCase(path);
		if (lowerPath.startsWith(httpProtocol) || lowerPath.startsWith(httpsProtocol)) {
			source = new URL(path);
			final String p = source.getPath();
			fileName = p.substring(p.lastIndexOf('/') + 1, p.length());
		} else {
			final File f = new File(path);
			source = f.toURI().toURL();
			fileName = f.getName();
		}

		InputStream stream = null;
		final BufferedImage im;
		try {
			stream = source.openStream();
			im = ImageIO.read(stream);
		} finally {
			if (stream != null) {
				stream.close();
			}
		}

		final String name = getSpriteName(fileName);
		final String s = compressed ? SpriteUtils.encodeCompressed(im, name, level) : SpriteUtils.encode(im, name,
				level);
		System.out.println(s);
	}

	private static String getSpriteName(String fileName) {
		final String s = getSpriteNameInternal(fileName);
		if (s.length() == 0) {
			return "test";
		}
		return s;
	}

	private static String getSpriteNameInternal(String fileName) {
		final StringBuilder sb = new StringBuilder();
		for (char c : fileName.toCharArray()) {
			if (("" + c).matches("[\\p{L}0-9_]")) {
				sb.append(c);
			} else {
				return sb.toString();
			}
		}
		return sb.toString();
	}

	private static void goFtp(Option option) throws IOException {
		final int ftpPort = option.getFtpPort();
		System.err.println("ftpPort=" + ftpPort);
		final FtpServer ftpServer = new FtpServer(ftpPort, option.getFileFormatOption().getFileFormat());
		ftpServer.go();
	}

	public static void printFonts() {
		final Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
		for (Font f : fonts) {
			System.out.println("f=" + f + "/" + f.getPSName() + "/" + f.getName() + "/" + f.getFontName() + "/"
					+ f.getFamily());
		}
		final String name[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
		for (String n : name) {
			System.out.println("n=" + n);
		}
	}

	private static void managePattern() {
		printPattern(new SequenceDiagramFactory());
		printPattern(new ClassDiagramFactory());
		printPattern(new ActivityDiagramFactory());
		printPattern(new DescriptionDiagramFactory());
		// printPattern(new ComponentDiagramFactory());
		printPattern(new StateDiagramFactory());
		printPattern(new ObjectDiagramFactory());
	}

	private static void printPattern(UmlDiagramFactory factory) {
		System.out.println();
		System.out.println(factory.getClass().getSimpleName().replaceAll("Factory", ""));
		final List<String> descriptions = factory.getDescription();
		for (String s : descriptions) {
			System.out.println(s);
		}
	}

	private static boolean managePipe(Option option) throws IOException {
		final String charset = option.getCharset();
		return new Pipe(option, System.out, System.in, charset).managePipe();
	}

	private static boolean manageAllFiles(Option option) throws IOException, InterruptedException {

		File lockFile = null;
		try {
			if (OptionFlags.getInstance().isWord()) {
				final File dir = new File(option.getResult().get(0));
				final File javaIsRunningFile = new File(dir, "javaisrunning.tmp");
				javaIsRunningFile.delete();
				lockFile = new File(dir, "javaumllock.tmp");
			}
			return processArgs(option);
		} finally {
			if (lockFile != null) {
				lockFile.delete();
			}
		}

	}

	private static boolean processArgs(Option option) throws IOException, InterruptedException {
		if (option.isDecodeurl() == false && option.getNbThreads() > 1 && option.isCheckOnly() == false
				&& OptionFlags.getInstance().isExtractFromMetadata() == false) {
			return multithread(option);
		}
		boolean errorGlobal = false;
		final List<File> files = new ArrayList<File>();
		for (String s : option.getResult()) {
			if (option.isDecodeurl()) {
				final Transcoder transcoder = TranscoderUtil.getDefaultTranscoder();
				System.out.println("@startuml");
				System.out.println(transcoder.decode(s));
				System.out.println("@enduml");
			} else {
				final FileGroup group = new FileGroup(s, option.getExcludes(), option);
				incTotal(group.getFiles().size());
				files.addAll(group.getFiles());
			}
		}
		Log.info("Found " + files.size() + " files");
		for (File f : files) {
			try {
				final boolean error = manageFileInternal(f, option);
				if (error) {
					errorGlobal = true;
				}
				incDone(error);
				if (error && option.isFailfastOrFailfast2()) {
					return true;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return errorGlobal;
	}

	private static boolean multithread(final Option option) throws InterruptedException {
		Log.info("Using several threads: " + option.getNbThreads());
		final ExecutorService executor = Executors.newFixedThreadPool(option.getNbThreads());
		final AtomicBoolean errors = new AtomicBoolean(false);
		for (String s : option.getResult()) {
			final FileGroup group = new FileGroup(s, option.getExcludes(), option);
			for (final File f : group.getFiles()) {
				incTotal(1);
				executor.submit(new Runnable() {
					public void run() {
						if (errors.get() && option.isFailfastOrFailfast2()) {
							return;
						}
						try {
							final boolean error = manageFileInternal(f, option);
							if (error) {
								errors.set(true);
							}
						} catch (IOException e) {
							e.printStackTrace();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						incDone(errors.get());
					}
				});
			}
		}
		executor.shutdown();
		executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
		return errors.get();
	}

	private static void incDone(boolean error) {
		Splash.incDone(error);
		ProgressBar.incDone(error);
	}

	private static void incTotal(int nb) {
		Splash.incTotal(nb);
		ProgressBar.incTotal(nb);
	}

	private static boolean manageFileInternal(File f, Option option) throws IOException, InterruptedException {
		Log.info("Working on " + f.getAbsolutePath());
		if (OptionFlags.getInstance().isExtractFromMetadata()) {
			System.out.println("------------------------");
			System.out.println(f);
			// new Metadata().readAndDisplayMetadata(f);
			System.out.println();
			System.out.println(new MetadataTag(f, "plantuml").getData());
			System.out.println("------------------------");
			return false;
		}
		final ISourceFileReader sourceFileReader;
		if (option.getOutputFile() == null) {
			sourceFileReader = new SourceFileReader(option.getDefaultDefines(f), f, option.getOutputDir(),
					option.getConfig(), option.getCharset(), option.getFileFormatOption());
		} else {
			sourceFileReader = new SourceFileReader2(option.getDefaultDefines(f), f, option.getOutputFile(),
					option.getConfig(), option.getCharset(), option.getFileFormatOption());
		}
		sourceFileReader.setCheckMetadata(option.isCheckMetadata());

		if (option.isComputeurl()) {
			for (BlockUml s : sourceFileReader.getBlocks()) {
				System.out.println(s.getEncodedUrl());
			}
			return false;
		}
		if (option.isCheckOnly()) {
			final boolean hasError = sourceFileReader.hasError();
			final List<GeneratedImage> result = sourceFileReader.getGeneratedImages();
			hasErrors(f, result);
			return hasError;
		}
		if (option.getPreprocessorOutputMode() != null) {
			extractPreproc(option, sourceFileReader);
			return false;
		}
		final List<GeneratedImage> result = sourceFileReader.getGeneratedImages();

		return hasErrors(f, result);
	}

	private static void extractPreproc(Option option, final ISourceFileReader sourceFileReader) throws IOException {
		final String charset = option.getCharset();
		for (BlockUml blockUml : sourceFileReader.getBlocks()) {
			final SuggestedFile suggested = ((SourceFileReaderAbstract) sourceFileReader).getSuggestedFile(blockUml)
					.withPreprocFormat();
			final File file = suggested.getFile(0);
			Log.info("Export preprocessing source to " + file.getAbsolutePath());
			final PrintWriter pw = charset == null ? new PrintWriter(file) : new PrintWriter(file, charset);
			for (CharSequence s : blockUml.getDefinition(true)) {
				if (cypher != null) {
					s = cypher.cypher(s.toString());
				}
				pw.println(s);
			}
			pw.close();
		}
	}

	private static boolean hasErrors(File f, final List<GeneratedImage> list) throws IOException {
		boolean result = false;
		for (GeneratedImage i : list) {
			final int lineError = i.lineErrorRaw();
			if (lineError != -1) {
				Log.error("Error line " + lineError + " in file: " + f.getCanonicalPath());
				result = true;
			}
		}
		return result;
	}

}