2 * jSite2 - SwingInterface.java -
3 * Copyright © 2008 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package net.pterodactylus.jsite.gui;
22 import java.awt.event.ActionEvent;
23 import java.beans.PropertyChangeEvent;
24 import java.beans.PropertyChangeListener;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.Date;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Locale;
36 import java.util.Properties;
37 import java.util.concurrent.Executor;
38 import java.util.concurrent.Executors;
39 import java.util.logging.Level;
40 import java.util.logging.LogRecord;
41 import java.util.logging.Logger;
43 import javax.swing.JOptionPane;
44 import javax.swing.UIManager;
45 import javax.swing.UnsupportedLookAndFeelException;
47 import net.pterodactylus.jsite.core.Core;
48 import net.pterodactylus.jsite.core.CoreListener;
49 import net.pterodactylus.jsite.core.JSiteException;
50 import net.pterodactylus.jsite.core.Node;
51 import net.pterodactylus.jsite.i18n.I18n;
52 import net.pterodactylus.jsite.i18n.gui.I18nAction;
53 import net.pterodactylus.jsite.project.Project;
54 import net.pterodactylus.util.image.IconLoader;
55 import net.pterodactylus.util.io.Closer;
56 import net.pterodactylus.util.logging.Logging;
57 import net.pterodactylus.util.logging.LoggingListener;
60 * The Swing user interface.
62 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
65 public class SwingInterface implements CoreListener, LoggingListener, PropertyChangeListener {
68 private static final Logger logger = Logging.getLogger(SwingInterface.class.getName());
70 /** The application core. */
71 private final Core core;
73 /** The configuration directory. */
74 private final String configDirectory;
76 /** The main window. */
77 private MainWindow mainWindow;
80 private Executor threadPool = Executors.newCachedThreadPool();
82 /** The logger window. */
83 private LogWindow logWindow;
85 /** The “configure” action. */
86 private I18nAction configureAction;
88 /** The “import config” action. */
89 private I18nAction importConfigAction;
91 /** The “quit” action. */
92 private I18nAction quitAction;
94 /** The “manage nodes” action. */
95 private I18nAction manageNodesAction;
97 /** All node menu items. */
98 private Map<Node, I18nAction> nodeConnectActions = Collections.synchronizedMap(new HashMap<Node, I18nAction>());
100 /** All node disconnect actions. */
101 private Map<Node, I18nAction> nodeDisconnectActions = Collections.synchronizedMap(new HashMap<Node, I18nAction>());
103 /** The node manager dialog. */
104 private ManageNodesDialog manageNodesDialog;
106 /** All lanugage menu items. */
107 private List<I18nAction> languageActions = new ArrayList<I18nAction>();
109 /** The “about” action. */
110 private I18nAction helpAboutAction;
112 /** The “add project” action. */
113 private I18nAction addProjectAction;
115 /** The “clone project” action. */
116 private I18nAction cloneProjectAction;
118 /** The “delete project” action. */
119 private I18nAction deleteProjectAction;
121 /** The “about” dialog. */
122 private AboutDialog aboutDialog;
124 /** The configuration dialog. */
125 private ConfigurationDialog configurationDialog;
127 /** The list of all defined nodes. */
128 private List<Node> nodeList = Collections.synchronizedList(new ArrayList<Node>());
134 /** The advanced mode. */
135 private boolean advancedMode;
137 /** Whether to antialias the GUI. */
138 private boolean antialias;
140 /** The control font. */
141 private String controlFont;
143 /** The user font. */
144 private String userFont;
146 /** The class name of the look and feel. */
147 private String lookAndFeel;
149 /** X coordinate of the main window. */
150 private int mainWindowX = -1;
152 /** Y coordinate of the main window. */
153 private int mainWindowY = -1;
155 /** Width of the main window. */
156 private int mainWindowWidth = -1;
158 /** Height of the main window. */
159 private int mainWindowHeight = -1;
162 * Creates a new swing interface.
165 * The core to operate on
166 * @param configDirectory
167 * The directory the configuration is stored in
169 public SwingInterface(Core core, String configDirectory) {
171 this.configDirectory = configDirectory;
172 I18n.setLocale(Locale.ENGLISH);
174 if (lookAndFeel != null) {
176 UIManager.setLookAndFeel(lookAndFeel);
177 } catch (ClassNotFoundException cnfe1) {
178 logger.log(Level.WARNING, "could not load look and feel", cnfe1);
179 } catch (InstantiationException ie1) {
180 logger.log(Level.WARNING, "could not load look and feel", ie1);
181 } catch (IllegalAccessException iae1) {
182 logger.log(Level.WARNING, "could not load look and feel", iae1);
183 } catch (UnsupportedLookAndFeelException ulafe1) {
184 logger.log(Level.WARNING, "could not load look and feel", ulafe1);
188 System.setProperty("swing.aatext", "true");
190 if (controlFont != null) {
191 System.setProperty("swing.plaf.metal.controlFont", controlFont);
193 if (userFont != null) {
194 System.setProperty("swing.plaf.metal.userFont", userFont);
198 mainWindow = new MainWindow(this);
199 mainWindow.setAdvancedMode(advancedMode);
200 if ((mainWindowX != -1) && (mainWindowY != -1) && (mainWindowWidth != -1) && (mainWindowHeight != -1)) {
201 mainWindow.setLocation(mainWindowX, mainWindowY);
202 mainWindow.setSize(mainWindowWidth, mainWindowHeight);
204 logWindow = new LogWindow();
212 * Returns the core that is controlled by the Swing interface.
221 * Returns the main window of the Swing interface.
223 * @return The main window
225 MainWindow getMainWindow() {
230 * Returns whether the advanced mode is activated.
232 * @return <code>true</code> if the advanced mode is activated,
233 * <code>false</code> if the simple mode is activated
235 boolean isAdvancedMode() {
240 * Returns the “configure” action.
242 * @return The “configure” action
244 I18nAction getConfigureAction() {
245 return configureAction;
249 * Returns the “import config” action.
251 * @return The “import config” action
253 I18nAction getImportConfigAction() {
254 return importConfigAction;
258 * Returns the “quit” action.
260 * @return The “quit” action
262 I18nAction getQuitAction() {
267 * Returns the “manage nodes” action.
269 * @return The “manage nodes” action
271 I18nAction getManageNodesAction() {
272 return manageNodesAction;
276 * Returns the “connect to node” action for the given node.
279 * The node go get the “connect” action for
280 * @return The “connect to node” action
282 I18nAction getNodeConnectAction(Node node) {
283 return nodeConnectActions.get(node);
287 * Returns the “disconnect from node” action for the given node.
290 * The node go get the “disconnect” action for
291 * @return The “disconnect from node” action
293 I18nAction getNodeDisconnectAction(Node node) {
294 return nodeDisconnectActions.get(node);
298 * Returns all language actions.
300 * @return All language actions
302 List<I18nAction> getLanguageActions() {
303 return languageActions;
307 * Returns the “about” action.
309 * @return The “about” action
311 I18nAction getHelpAboutAction() {
312 return helpAboutAction;
316 * Returns the “add project” action.
318 * @return The “add project” action
320 I18nAction getAddProjectAction() {
321 return addProjectAction;
325 * Returns the “clone project” action.
327 * @return The “clone project” action
329 I18nAction getCloneProjectAction() {
330 return cloneProjectAction;
334 * Returns the “delete project” action.
336 * @return The “delete project” action
338 I18nAction getDeleteProjectAction() {
339 return deleteProjectAction;
343 * Returns all currently configured nodes.
345 * @return All configured nodes
347 List<Node> getNodes() {
364 * Loads the configuration of the interface.
366 private void loadConfig() {
367 /* initialize default stuff. */
369 /* now read config. */
370 File configFile = new File(configDirectory, "swing-interface.properties");
371 if (!configFile.exists() || !configFile.canRead() || !configFile.isFile()) {
372 System.err.println("could not find “" + configFile.getAbsolutePath() + "”!");
375 Properties configProperties = new Properties();
376 FileInputStream configInputStream = null;
378 configInputStream = new FileInputStream(configFile);
379 configProperties.load(configInputStream);
380 } catch (IOException ioe1) {
381 System.err.println("could not load config, " + ioe1.getMessage());
383 Closer.close(configInputStream);
385 if (configProperties.containsKey("advancedMode")) {
386 advancedMode = Boolean.valueOf(configProperties.getProperty("advancedMode"));
388 if (configProperties.containsKey("antialias")) {
389 antialias = Boolean.valueOf(configProperties.getProperty("antialias"));
391 if (configProperties.containsKey("controlFont")) {
392 controlFont = configProperties.getProperty("controlFont");
394 if (configProperties.containsKey("userFont")) {
395 userFont = configProperties.getProperty("userFont");
397 if (configProperties.containsKey("lookAndFeel")) {
398 lookAndFeel = configProperties.getProperty("lookAndFeel");
400 if (configProperties.containsKey("language")) {
401 I18n.setLocale(new Locale(configProperties.getProperty("language")));
403 if (configProperties.containsKey("mainWindowX")) {
404 mainWindowX = Integer.valueOf(configProperties.getProperty("mainWindowX"));
406 if (configProperties.containsKey("mainWindowY")) {
407 mainWindowY = Integer.valueOf(configProperties.getProperty("mainWindowY"));
409 if (configProperties.containsKey("mainWindowWidth")) {
410 mainWindowWidth = Integer.valueOf(configProperties.getProperty("mainWindowWidth"));
412 if (configProperties.containsKey("mainWindowHeight")) {
413 mainWindowHeight = Integer.valueOf(configProperties.getProperty("mainWindowHeight"));
418 * Saves the configuration.
420 private void saveConfig() {
421 File configDirectory = new File(this.configDirectory);
422 if (!configDirectory.exists()) {
423 if (!configDirectory.mkdirs()) {
424 System.err.println("could not create “" + this.configDirectory + "”!");
428 if (!configDirectory.exists() || !configDirectory.isDirectory() || !configDirectory.canWrite()) {
429 System.err.println("can not access “" + this.configDirectory + "”!");
432 File configFile = new File(configDirectory, "swing-interface.properties");
433 Properties configProperties = new Properties();
434 configProperties.setProperty("advancedMode", String.valueOf(advancedMode));
435 configProperties.setProperty("antialias", String.valueOf(antialias));
436 if (controlFont != null) {
437 configProperties.setProperty("controlFont", controlFont);
439 if (userFont != null) {
440 configProperties.setProperty("userFont", userFont);
442 if (lookAndFeel != null) {
443 configProperties.setProperty("lookAndFeel", lookAndFeel);
445 configProperties.setProperty("language", I18n.getLocale().getLanguage());
446 configProperties.setProperty("mainWindowX", String.valueOf(mainWindowX));
447 configProperties.setProperty("mainWindowY", String.valueOf(mainWindowY));
448 configProperties.setProperty("mainWindowWidth", String.valueOf(mainWindowWidth));
449 configProperties.setProperty("mainWindowHeight", String.valueOf(mainWindowHeight));
450 FileOutputStream configOutputStream = null;
452 configOutputStream = new FileOutputStream(configFile);
453 configProperties.store(configOutputStream, "configuration of swing interface");
454 } catch (IOException ioe1) {
455 System.err.println("could not save config, " + ioe1.getMessage());
457 Closer.close(configOutputStream);
462 * Initializes all actions.
464 private void initActions() {
465 configureAction = new I18nAction("mainWindow.menu.jSite.configure", IconLoader.loadIcon("/preferences-system.png")) {
470 @SuppressWarnings("synthetic-access")
471 public void actionPerformed(ActionEvent actionEvent) {
475 importConfigAction = new I18nAction("mainWindow.menu.jSite.importConfig") {
480 @SuppressWarnings("synthetic-access")
481 public void actionPerformed(ActionEvent actionEvent) {
485 quitAction = new I18nAction("mainWindow.menu.jSite.quit", IconLoader.loadIcon("/system-log-out.png")) {
490 @SuppressWarnings("synthetic-access")
491 public void actionPerformed(ActionEvent actionEvent) {
495 manageNodesAction = new I18nAction("mainWindow.menu.node.item.manageNodes") {
500 @SuppressWarnings("synthetic-access")
501 public void actionPerformed(ActionEvent actionEvent) {
505 List<Locale> availableLanguages = I18n.findAvailableLanguages();
506 for (final Locale locale: availableLanguages) {
507 I18nAction languageAction = new I18nAction("general.language." + locale.getLanguage()) {
509 @SuppressWarnings("synthetic-access")
510 public void actionPerformed(ActionEvent e) {
511 changeLanguage(locale, this);
515 if (I18n.getLocale().getLanguage().equals(locale.getLanguage())) {
516 languageAction.setEnabled(false);
518 languageActions.add(languageAction);
520 helpAboutAction = new I18nAction("mainWindow.menu.help.item.about") {
525 @SuppressWarnings("synthetic-access")
526 public void actionPerformed(ActionEvent actionEvent) {
530 addProjectAction = new I18nAction("mainWindow.button.addProject") {
535 @SuppressWarnings("synthetic-access")
536 public void actionPerformed(ActionEvent actionEvent) {
540 cloneProjectAction = new I18nAction("mainWindow.button.cloneProject") {
545 @SuppressWarnings("synthetic-access")
546 public void actionPerformed(ActionEvent actionEvent) {
550 deleteProjectAction = new I18nAction("mainWindow.button.deleteProject") {
555 @SuppressWarnings("synthetic-access")
556 public void actionPerformed(ActionEvent actionEvent) {
563 * Initializes all child dialogs.
565 private void initDialogs() {
566 manageNodesDialog = new ManageNodesDialog(this);
567 aboutDialog = new AboutDialog(this);
568 configurationDialog = new ConfigurationDialog(this);
576 * Shows the configuration dialog.
578 private void configure() {
579 configurationDialog.setAdvancedMode(advancedMode);
580 configurationDialog.setAntialias(antialias);
581 configurationDialog.setControlFont(controlFont);
582 configurationDialog.setUserFont(userFont);
583 configurationDialog.setLookAndFeel(lookAndFeel);
584 configurationDialog.setVisible(true);
585 if (!configurationDialog.wasCancelled()) {
586 advancedMode = configurationDialog.isAdvancedMode();
587 if (!advancedMode && (nodeList.size() > 1)) {
588 JOptionPane.showMessageDialog(mainWindow, I18n.get("mainWindow.warning.multipleNodesNotAdvancedMode.message"), I18n.get("mainWindow.warning.multipleNodesNotAdvancedMode.title"), JOptionPane.WARNING_MESSAGE);
590 mainWindow.setAdvancedMode(advancedMode);
591 antialias = configurationDialog.isAntialias();
592 controlFont = configurationDialog.getControlFont();
593 userFont = configurationDialog.getUserFont();
594 lookAndFeel = configurationDialog.getLookAndFeel();
600 * Imports old jSite configuration.
602 private void importConfig() {
609 private void quit() {
612 mainWindowX = mainWindow.getX();
613 mainWindowY = mainWindow.getY();
614 mainWindowWidth = mainWindow.getWidth();
615 mainWindowHeight = mainWindow.getHeight();
621 * Pops up the “manage nodes” dialog.
623 private void manageNodes() {
625 manageNodesDialog.setNodeList(nodeList);
626 manageNodesDialog.setVisible(true);
627 nodeList = manageNodesDialog.getNodeList();
628 /* TODO - notify main window of changes */
630 if (nodeList.isEmpty()) {
631 Node newNode = new Node();
632 newNode.setName(I18n.get("general.defaultNode.name"));
633 newNode.setHostname("localhost");
634 newNode.setPort(9481);
635 nodeList.add(newNode);
637 Node firstNode = nodeList.get(0);
638 EditNodeDialog editNodeDialog = manageNodesDialog.getEditNodeDialog();
639 editNodeDialog.setNodeName(firstNode.getName());
640 editNodeDialog.setNodeHostname(firstNode.getHostname());
641 editNodeDialog.setNodePort(firstNode.getPort());
642 editNodeDialog.setVisible(true);
643 if (!editNodeDialog.wasCancelled()) {
644 firstNode.setName(editNodeDialog.getNodeName());
645 firstNode.setHostname(editNodeDialog.getNodeHostname());
646 firstNode.setPort(editNodeDialog.getNodePort());
647 /* TODO - give to core. */
653 * Connects to the node.
656 * The node to connect to
658 private void nodeConnect(final Node node) {
659 threadPool.execute(new Runnable() {
664 @SuppressWarnings("synthetic-access")
666 logger.log(Level.INFO, "connecting to node “" + node.getName() + "”…");
667 core.connectToNode(node);
673 * Disconnects from the node.
676 * The node to disconnect from
678 private void nodeDisconnect(Node node) {
679 logger.log(Level.INFO, "disconnecting from node “" + node.getName() + "”…");
680 core.disconnectFromNode(node);
684 * Changes the language of the interface. This method also disables the
685 * action for the newly set language and enables all others.
689 * @param languageAction
690 * The action that triggered the change
692 private void changeLanguage(Locale newLocale, I18nAction languageAction) {
693 for (I18nAction i18nAction: languageActions) {
694 i18nAction.setEnabled(i18nAction != languageAction);
696 I18n.setLocale(newLocale);
700 * Shows the “about” dialog.
702 private void helpAbout() {
703 aboutDialog.setVisible(true);
709 private void addProject() {
711 Project project = core.createProject();
712 project.setName(I18n.get("general.newProject.name"));
713 project.setDescription(I18n.get("general.newProject.description", new Date()));
714 mainWindow.addProject(project, true);
715 } catch (JSiteException nne1) {
716 /* TODO - add i18n */
717 JOptionPane.showMessageDialog(mainWindow, I18n.get(""), I18n.get(""), JOptionPane.ERROR_MESSAGE);
718 } catch (IOException e) {
719 /* TODO - add i18n */
720 JOptionPane.showMessageDialog(mainWindow, I18n.get(""), I18n.get(""), JOptionPane.ERROR_MESSAGE);
727 private void cloneProject() {
734 private void deleteProject() {
739 // INTERFACE CoreListener
745 public void loadingProjectsDone(String directory) {
746 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.projectLoadingDone"));
747 for (Project project: core.getProjects()) {
748 mainWindow.addProject(project, false);
755 public void loadingProjectsFailed(String directory, Throwable throwable) {
756 JOptionPane.showMessageDialog(mainWindow, I18n.get("mainWindow.error.projectLoadingFailed.message", directory), I18n.get("mainWindow.error.projectLoadingFailed.title"), JOptionPane.ERROR_MESSAGE);
762 public void savingProjectsDone(String directory) {
763 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.projectSavingDone"));
769 public void savingProjectsFailed(String directory, Throwable throwabled) {
776 public void loadingNodesDone(String directory) {
777 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.loadingNodesDone"));
783 public void loadingNodesFailed(String directory, Throwable throwable) {
790 public void savingNodesDone(String directory) {
791 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.savingNodesDone"));
797 public void savingNodesFailed(String directory, Throwable throwable) {
804 public void coreLoaded() {
805 mainWindow.setVisible(true);
806 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.coreLoaded"));
812 public void coreStopped() {
813 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.coreStopped"));
819 public void nodeAdded(final Node node) {
820 logger.log(Level.INFO, "node added: " + node);
822 node.addPropertyChangeListener(this);
823 logger.log(Level.FINE, "nodeList.size(): " + nodeList.size());
824 manageNodesDialog.setNodeList(nodeList);
825 nodeConnectActions.put(node, new I18nAction("mainWindow.menu.connect") {
830 @SuppressWarnings("synthetic-access")
831 public void actionPerformed(ActionEvent e) {
835 nodeDisconnectActions.put(node, new I18nAction("mainWindow.menu.disconnect") {
840 @SuppressWarnings("synthetic-access")
841 public void actionPerformed(ActionEvent e) {
842 nodeDisconnect(node);
845 nodeDisconnectActions.get(node).setEnabled(false);
846 mainWindow.addNode(node);
852 public void nodeRemoved(Node node) {
853 logger.log(Level.INFO, "node removed: " + node);
854 nodeList.remove(node);
855 node.removePropertyChangeListener(this);
856 nodeConnectActions.remove(node);
857 nodeDisconnectActions.remove(node);
858 mainWindow.removeNode(node);
864 public void nodeConnecting(Node node) {
865 nodeConnectActions.get(node).setEnabled(false);
866 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.connectingToNode", node.getName(), node.getHostname(), node.getPort()));
872 public void nodeConnected(Node node) {
873 nodeDisconnectActions.get(node).setEnabled(true);
874 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.connectedToNode", node.getName(), node.getHostname(), node.getPort()));
880 public void nodeConnectionFailed(Node node, Throwable cause) {
881 nodeConnectActions.get(node).setEnabled(true);
882 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.connectionToNodeFailed", node.getName(), node.getHostname(), node.getPort(), (cause != null) ? cause.getMessage() : "no reason given"));
883 JOptionPane.showMessageDialog(mainWindow, I18n.get("mainWindow.error.nodeConnectionFailed.message", node.getName(), node.getHostname(), node.getPort(), (cause != null) ? cause.getMessage() : "no reason given"), I18n.get("mainWindow.error.nodeConnectionFailed.title"), JOptionPane.ERROR_MESSAGE);
889 public void nodeDisconnected(Node node, Throwable throwable) {
890 nodeDisconnectActions.get(node).setEnabled(false);
891 nodeConnectActions.get(node).setEnabled(true);
892 mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.disconnectedFromNode", node.getName(), node.getHostname(), node.getPort()));
896 * @see net.pterodactylus.jsite.core.CoreListener#projectInsertStarted(net.pterodactylus.jsite.project.Project)
898 public void projectInsertStarted(Project project) {
899 mainWindow.projectInsertStarted(project);
903 * @see net.pterodactylus.jsite.core.CoreListener#projectInsertProgressed(net.pterodactylus.jsite.project.Project,
904 * int, int, int, int, int, boolean)
906 public void projectInsertProgressed(Project project, int totalBlocks, int requiredBlocks, int successfulBlocks, int failedBlocks, int fatallyFailedBlocks, boolean finalizedTotal) {
907 mainWindow.projectInsertProgressed(project, totalBlocks, requiredBlocks, successfulBlocks, failedBlocks, fatallyFailedBlocks, finalizedTotal);
911 * @see net.pterodactylus.jsite.core.CoreListener#projectInsertGeneratedURI(net.pterodactylus.jsite.project.Project,
914 public void projectInsertGeneratedURI(Project project, String uri) {
915 mainWindow.projectInsertGeneratedURI(project);
919 * @see net.pterodactylus.jsite.core.CoreListener#projectInsertFinished(net.pterodactylus.jsite.project.Project,
922 public void projectInsertFinished(Project project, boolean success) {
923 mainWindow.projectInsertFinished(project, success);
927 // INTERFACE LoggingListener
933 public void logged(LogRecord logRecord) {
934 logWindow.logged(logRecord);
938 // INTERFACE PropertyChangeListener
944 public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
945 /* do not react to anything (yet). */