summaryrefslogtreecommitdiff
path: root/src/net/sourceforge/plantuml/swing/MainWindow2.java
blob: 72daca1bb5be00a5a6701d2ee0dd48d03af4b7fb (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
/* ========================================================================
 * PlantUML : a free UML diagram generator
 * ========================================================================
 *
 * (C) Copyright 2009-2020, 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.swing;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.CompoundBorder;

import net.sourceforge.plantuml.DirWatcher2;
import net.sourceforge.plantuml.GeneratedImage;
import net.sourceforge.plantuml.Log;
import net.sourceforge.plantuml.Option;
import net.sourceforge.plantuml.version.PSystemVersion;

public class MainWindow2 extends JFrame {

	final private static Preferences prefs = Preferences.userNodeForPackage(MainWindow2.class);
	final private static String KEY_DIR = "cur";
	final private static String KEY_PATTERN = "pat";

	private final JList jList1 = new JList();
	private final JScrollPane scrollPane;
	private final JButton changeDirButton = new JButton("Change Directory");
	private final JTextField extensions = new JTextField();
	private final int period = 300;

	final private List<SimpleLine2> currentDirectoryListing2 = new ArrayList<SimpleLine2>();
	final private Set<ImageWindow2> openWindows2 = new HashSet<ImageWindow2>();
	final private Option option;

	private DirWatcher2 dirWatcher;

	private String getExtensions() {
		return prefs.get(KEY_PATTERN, getDefaultFileExtensions());
	}

	private String getDefaultFileExtensions() {
		return "txt, tex, java, htm, html, c, h, cpp, apt, pu, puml, hpp, hh";
	}

	private void changeExtensions(String ext) {
		if (ext.equals(getExtensions())) {
			return;
		}
		final Pattern p = Pattern.compile("\\w+");
		final Matcher m = p.matcher(ext);
		final StringBuilder sb = new StringBuilder();

		while (m.find()) {
			final String value = m.group();
			if (sb.length() > 0) {
				sb.append(", ");
			}
			sb.append(value);

		}
		ext = sb.toString();
		if (ext.length() == 0) {
			ext = getDefaultFileExtensions();
		}
		extensions.setText(ext);
		prefs.put(KEY_PATTERN, ext);
		changeDir(dirWatcher.getDir());
	}

	private String getRegexpPattern(String ext) {
		final Pattern p = Pattern.compile("\\w+");
		final Matcher m = p.matcher(ext);
		final StringBuilder filePattern = new StringBuilder("(?i)^.*\\.(");

		while (m.find()) {
			final String value = m.group();
			if (filePattern.toString().endsWith("(") == false) {
				filePattern.append("|");
			}
			filePattern.append(value);
		}
		if (filePattern.toString().endsWith("(") == false) {
			filePattern.append(")$");
			return filePattern.toString();
		}
		return Option.getPattern();
	}

	public MainWindow2(Option option, File arg) {
		super(getDirectory(arg).getAbsolutePath());
		final File dir = getDirectory(arg);
		setIconImage(PSystemVersion.getPlantumlSmallIcon2());
		this.option = option;
		dirWatcher = new DirWatcher2(dir, option, getRegexpPattern(getExtensions()));

		Log.info("Showing MainWindow");
		scrollPane = new JScrollPane(jList1);
		scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

		final JPanel south = new JPanel(new BorderLayout());
		final JLabel labelFileExtensions = new JLabel("File extensions: ");
		extensions.setText(getExtensions());

		labelFileExtensions.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
		CompoundBorder border = BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10),
				BorderFactory.createEtchedBorder());
		border = BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(5, 5, 5, 5));
		south.setBorder(border);
		south.add(labelFileExtensions, BorderLayout.WEST);
		south.add(extensions, BorderLayout.CENTER);

		south.add(changeDirButton, BorderLayout.SOUTH);

		getContentPane().add(south, BorderLayout.SOUTH);
		getContentPane().add(scrollPane, BorderLayout.CENTER);

		final MouseListener mouseListener = new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					if (e.getClickCount() == 2) {
						final int index = jList1.locationToIndex(e.getPoint());
						doubleClick((SimpleLine2) jList1.getModel().getElementAt(index), jList1.getModel(), index);
					}
				} catch (Exception ex) {

				}
			}
		};
		jList1.addMouseListener(mouseListener);
		changeDirButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.err.println("Opening Directory Window");
				displayDialogChangeDir();
			}
		});
		jList1.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					final int index = jList1.getSelectedIndex();
					doubleClick((SimpleLine2) jList1.getModel().getElementAt(index), jList1.getModel(), index);
				}
			}

		});

		extensions.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				changeExtensions(extensions.getText());
			}
		});
		extensions.addFocusListener(new FocusListener() {

			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				changeExtensions(extensions.getText());
			}
		});

		final JMenuBar menuBar = new JMenuBar();
		final JMenu mFile = new JMenu("File");
		menuBar.add(mFile);
		setJMenuBar(menuBar);

		final JMenuItem sprite = new JMenuItem("Open Sprite Window");
		mFile.add(sprite);
		sprite.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new SpriteWindow();
			}
		});

		final JMenuItem about = new JMenuItem("About");
		mFile.add(about);
		about.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new AboutWindow();
			}
		});

		final JMenuItem exit = new JMenuItem("Exit");
		mFile.add(exit);
		exit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		setSize(640, 400);
		this.setLocationRelativeTo(this.getParent());
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		startTimer();
	}

	private static File getDirectory(File arg) {
		if (arg != null && arg.exists() && arg.isDirectory()) {
			return arg;
		}
		return new File(prefs.get(KEY_DIR, "."));
	}

	private void startTimer() {
		Log.info("Init done");
		final Timer timer = new Timer(period, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tick();
			}
		});
		timer.setInitialDelay(0);
		timer.start();
		Log.info("Timer started");
	}

	private void displayDialogChangeDir() {
		final JFileChooser chooser = new JFileChooser();
		chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
		chooser.setDialogTitle("Directory to watch:");
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		chooser.setAcceptAllFileFilterUsed(false);
		final String currentPath = prefs.get(KEY_DIR, ".");
		chooser.setCurrentDirectory(new File(currentPath));
		Log.info("Showing OpenDialog");
		final int returnVal = chooser.showOpenDialog(this);
		Log.info("Closing OpenDialog");
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			final File dir = chooser.getSelectedFile();
			changeDir(dir);
		}

	}

	private void changeDir(File dir) {
		prefs.put(KEY_DIR, dir.getAbsolutePath());
		dirWatcher.cancel();
		dirWatcher = new DirWatcher2(dir, option, getRegexpPattern(getExtensions()));
		setTitle(dir.getAbsolutePath());
		Log.info("Creating DirWatcher");
		currentDirectoryListing2.clear();
		jList1.setListData(new Vector<SimpleLine2>(currentDirectoryListing2));
		jList1.setVisible(true);
	}

	private void doubleClick(SimpleLine2 simpleLine, ListModel listModel, int index) {
		for (ImageWindow2 win : openWindows2) {
			if (win.getSimpleLine().equals(simpleLine)) {
				win.setVisible(true);
				win.setExtendedState(Frame.NORMAL);
				return;
			}
		}
		if (simpleLine.getGeneratedImage() != null) {
			openWindows2.add(new ImageWindow2(simpleLine, this, listModel, index));
		}
	}

	private void tick() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					final boolean changed = refreshDir();
					if (changed) {
						jList1.setListData(new Vector<SimpleLine2>(currentDirectoryListing2));
						jList1.setVisible(true);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private boolean refreshDir() throws IOException, InterruptedException, ExecutionException {
		final Map<File, Future<List<GeneratedImage>>> createdFiles2 = dirWatcher.buildCreatedFiles();
		boolean changed = false;

		for (Map.Entry<File, Future<List<GeneratedImage>>> ent : createdFiles2.entrySet()) {
			final File file = ent.getKey();
			removeAllThatUseThisFile(file);
			final Future<List<GeneratedImage>> future = ent.getValue();
			final SimpleLine2 simpleLine = SimpleLine2.fromFuture(file, future);
			currentDirectoryListing2.add(simpleLine);
			changed = true;
		}

		for (SimpleLine2 line : new ArrayList<SimpleLine2>(currentDirectoryListing2)) {
			if (line.pendingAndFinished()) {
				currentDirectoryListing2.remove(line);
				changed = true;
				final Future<List<GeneratedImage>> future = line.getFuture();
				for (GeneratedImage im : future.get()) {
					mayRefreshImageWindow(im.getPngFile());
					final SimpleLine2 simpleLine = SimpleLine2.fromGeneratedImage(line.getFile(), im);
					currentDirectoryListing2.add(simpleLine);
				}
			}
		}
		Collections.sort(currentDirectoryListing2);
		return changed;
	}

	private void removeAllThatUseThisFile(File file) {
		for (final Iterator<SimpleLine2> it = currentDirectoryListing2.iterator(); it.hasNext();) {
			final SimpleLine2 line = it.next();
			if (line.getFile().equals(file)) {
				it.remove();
			}
		}
	}

	private void mayRefreshImageWindow(File pngFile) {
		for (ImageWindow2 win : openWindows2) {
			if (win.getSimpleLine().getGeneratedImage() == null) {
				continue;
			}
			if (pngFile.equals(win.getSimpleLine().getGeneratedImage().getPngFile())) {
				win.refreshImage(true);
			}
		}

	}

	public void closing(ImageWindow2 imageWindow) {
		final boolean ok = openWindows2.remove(imageWindow);
		if (ok == false) {
			throw new IllegalStateException();
		}
	}

	public List<SimpleLine2> getCurrentDirectoryListing2() {
		return Collections.unmodifiableList(currentDirectoryListing2);
	}

}