add status bar texts when connecting and disconnecting
[jSite2.git] / src / net / pterodactylus / jsite / gui / SwingInterface.java
index e022cf1..65e1edd 100644 (file)
@@ -25,27 +25,46 @@ import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
+import java.util.Map;
 import java.util.Properties;
-
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import javax.swing.AbstractAction;
+import javax.swing.Action;
 import javax.swing.JOptionPane;
+import javax.swing.UIManager;
+import javax.swing.UnsupportedLookAndFeelException;
 
 import net.pterodactylus.jsite.core.Core;
 import net.pterodactylus.jsite.core.CoreListener;
 import net.pterodactylus.jsite.core.Node;
 import net.pterodactylus.jsite.core.Project;
+import net.pterodactylus.jsite.core.Request;
 import net.pterodactylus.jsite.i18n.I18n;
 import net.pterodactylus.jsite.i18n.gui.I18nAction;
+import net.pterodactylus.util.image.IconLoader;
 import net.pterodactylus.util.io.Closer;
+import net.pterodactylus.util.logging.Logging;
+import net.pterodactylus.util.logging.LoggingListener;
 
 /**
  * The Swing user interface.
- *
+ * 
  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
  * @version $Id$
  */
-public class SwingInterface implements CoreListener {
+public class SwingInterface implements CoreListener, LoggingListener {
+
+       /** The logger. */
+       private static final Logger logger = Logging.getLogger(SwingInterface.class.getName());
 
        /** The application core. */
        private final Core core;
@@ -56,6 +75,12 @@ public class SwingInterface implements CoreListener {
        /** The main window. */
        private MainWindow mainWindow;
 
+       /** Thread pool. */
+       private Executor threadPool = Executors.newCachedThreadPool();
+
+       /** The logger window. */
+       private LogWindow logWindow;
+
        /** The “configure” action. */
        private I18nAction configureAction;
 
@@ -68,12 +93,30 @@ public class SwingInterface implements CoreListener {
        /** The “manage nodes” action. */
        private I18nAction manageNodesAction;
 
-       /** The “connect to node” action. */
+       /** The “connect to node” (simple mode) action. */
        private I18nAction nodeConnectAction;
 
-       /** The “disconnect from node” action. */
+       /** The “disconnect from node” (simple mode) action. */
        private I18nAction nodeDisconnectAction;
 
+       /** All node menu items. */
+       private List<Action> nodeConnectActions = Collections.synchronizedList(new ArrayList<Action>());
+
+       /** Mapping from nodes to node connect actions. */
+       private Map<Node, Action> nodeNodeConnectActions = Collections.synchronizedMap(new HashMap<Node, Action>());
+
+       /** Mapping from node connect actions to nodes. */
+       private Map<Action, Node> nodeConnectActionNodes = Collections.synchronizedMap(new HashMap<Action, Node>());
+
+       /** All node disconnect actions. */
+       private List<Action> nodeDisconnectActions = Collections.synchronizedList(new ArrayList<Action>());
+
+       /** Mapping from nodes to node disconnect actions. */
+       private Map<Node, Action> nodeNodeDisconnectActions = Collections.synchronizedMap(new HashMap<Node, Action>());
+
+       /** Mapping from node disconnect actions to nodes. */
+       private Map<Action, Node> nodeDisconnectActionNodes = Collections.synchronizedMap(new HashMap<Action, Node>());
+
        /** The node manager dialog. */
        private ManageNodesDialog manageNodesDialog;
 
@@ -99,7 +142,7 @@ public class SwingInterface implements CoreListener {
        private ConfigurationDialog configurationDialog;
 
        /** The list of all defined nodes. */
-       private List<Node> nodeList;
+       private List<Node> nodeList = Collections.synchronizedList(new ArrayList<Node>());
 
        //
        // CONFIGURATION
@@ -117,9 +160,12 @@ public class SwingInterface implements CoreListener {
        /** The user font. */
        private String userFont;
 
+       /** The class name of the look and feel. */
+       private String lookAndFeel;
+
        /**
         * Creates a new swing interface.
-        *
+        * 
         * @param core
         *            The core to operate on
         * @param configDirectory
@@ -130,6 +176,19 @@ public class SwingInterface implements CoreListener {
                this.configDirectory = configDirectory;
                I18n.setLocale(Locale.ENGLISH);
                loadConfig();
+               if (lookAndFeel != null) {
+                       try {
+                               UIManager.setLookAndFeel(lookAndFeel);
+                       } catch (ClassNotFoundException cnfe1) {
+                               logger.log(Level.WARNING, "could not load look and feel", cnfe1);
+                       } catch (InstantiationException ie1) {
+                               logger.log(Level.WARNING, "could not load look and feel", ie1);
+                       } catch (IllegalAccessException iae1) {
+                               logger.log(Level.WARNING, "could not load look and feel", iae1);
+                       } catch (UnsupportedLookAndFeelException ulafe1) {
+                               logger.log(Level.WARNING, "could not load look and feel", ulafe1);
+                       }
+               }
                if (antialias) {
                        System.setProperty("swing.aatext", "true");
                }
@@ -141,6 +200,9 @@ public class SwingInterface implements CoreListener {
                }
                initActions();
                initDialogs();
+               mainWindow = new MainWindow(this);
+               mainWindow.setAdvancedMode(advancedMode);
+               logWindow = new LogWindow();
        }
 
        //
@@ -149,7 +211,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the core that is controlled by the Swing interface.
-        *
+        * 
         * @return The core
         */
        Core getCore() {
@@ -158,7 +220,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the main window of the Swing interface.
-        *
+        * 
         * @return The main window
         */
        MainWindow getMainWindow() {
@@ -166,8 +228,18 @@ public class SwingInterface implements CoreListener {
        }
 
        /**
+        * Returns whether the advanced mode is activated.
+        * 
+        * @return <code>true</code> if the advanced mode is activated,
+        *         <code>false</code> if the simple mode is activated
+        */
+       boolean isAdvancedMode() {
+               return advancedMode;
+       }
+
+       /**
         * Returns the “configure” action.
-        *
+        * 
         * @return The “configure” action
         */
        I18nAction getConfigureAction() {
@@ -176,7 +248,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “import config” action.
-        *
+        * 
         * @return The “import config” action
         */
        I18nAction getImportConfigAction() {
@@ -185,7 +257,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “quit” action.
-        *
+        * 
         * @return The “quit” action
         */
        I18nAction getQuitAction() {
@@ -194,7 +266,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “manage nodes” action.
-        *
+        * 
         * @return The “manage nodes” action
         */
        I18nAction getManageNodesAction() {
@@ -203,7 +275,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “connect to node” action.
-        *
+        * 
         * @return The “connect to node” action
         */
        I18nAction getNodeConnectAction() {
@@ -211,8 +283,17 @@ public class SwingInterface implements CoreListener {
        }
 
        /**
+        * Returns all “connect node” actions.
+        * 
+        * @return All “connect node” actions
+        */
+       List<Action> getNodeConnectActions() {
+               return nodeConnectActions;
+       }
+
+       /**
         * Returns the “disconnect from node” action.
-        *
+        * 
         * @return The “disconnect from node” action
         */
        I18nAction getNodeDisconnectAction() {
@@ -220,8 +301,17 @@ public class SwingInterface implements CoreListener {
        }
 
        /**
+        * Returns all “disconnect node” actions.
+        * 
+        * @return All “disconnect node” action
+        */
+       List<Action> getNodeDisconnectActions() {
+               return nodeDisconnectActions;
+       }
+
+       /**
         * Returns all language actions.
-        *
+        * 
         * @return All language actions
         */
        List<I18nAction> getLanguageActions() {
@@ -230,7 +320,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “about” action.
-        *
+        * 
         * @return The “about” action
         */
        I18nAction getHelpAboutAction() {
@@ -239,7 +329,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “add project” action.
-        *
+        * 
         * @return The “add project” action
         */
        I18nAction getAddProjectAction() {
@@ -248,7 +338,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “clone project” action.
-        *
+        * 
         * @return The “clone project” action
         */
        I18nAction getCloneProjectAction() {
@@ -257,7 +347,7 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Returns the “delete project” action.
-        *
+        * 
         * @return The “delete project” action
         */
        I18nAction getDeleteProjectAction() {
@@ -272,13 +362,6 @@ public class SwingInterface implements CoreListener {
        // SERVICE METHODS
        //
 
-       /**
-        * Starts the interface.
-        */
-       public void start() {
-               mainWindow = new MainWindow(this);
-       }
-
        //
        // PRIVATE METHODS
        //
@@ -317,6 +400,9 @@ public class SwingInterface implements CoreListener {
                if (configProperties.containsKey("userFont")) {
                        userFont = configProperties.getProperty("userFont");
                }
+               if (configProperties.containsKey("lookAndFeel")) {
+                       lookAndFeel = configProperties.getProperty("lookAndFeel");
+               }
                if (configProperties.containsKey("language")) {
                        I18n.setLocale(new Locale(configProperties.getProperty("language")));
                }
@@ -347,6 +433,9 @@ public class SwingInterface implements CoreListener {
                if (userFont != null) {
                        configProperties.setProperty("userFont", userFont);
                }
+               if (lookAndFeel != null) {
+                       configProperties.setProperty("lookAndFeel", lookAndFeel);
+               }
                configProperties.setProperty("language", I18n.getLocale().getLanguage());
                FileOutputStream configOutputStream = null;
                try {
@@ -363,7 +452,7 @@ public class SwingInterface implements CoreListener {
         * Initializes all actions.
         */
        private void initActions() {
-               configureAction = new I18nAction("mainWindow.menu.jSite.configure") {
+               configureAction = new I18nAction("mainWindow.menu.jSite.configure", IconLoader.loadIcon("/preferences-system.png")) {
 
                        /**
                         * {@inheritDoc}
@@ -383,7 +472,7 @@ public class SwingInterface implements CoreListener {
                                importConfig();
                        }
                };
-               quitAction = new I18nAction("mainWindow.menu.jSite.quit") {
+               quitAction = new I18nAction("mainWindow.menu.jSite.quit", IconLoader.loadIcon("/system-log-out.png")) {
 
                        /**
                         * {@inheritDoc}
@@ -407,7 +496,11 @@ public class SwingInterface implements CoreListener {
 
                        @SuppressWarnings("synthetic-access")
                        public void actionPerformed(ActionEvent actionEvent) {
-                               nodeConnect();
+                               List<Node> nodes = core.getNodes();
+                               if (nodes.isEmpty()) {
+                                       return;
+                               }
+                               nodeConnect(nodes.get(0));
                        }
 
                };
@@ -418,9 +511,14 @@ public class SwingInterface implements CoreListener {
                         */
                        @SuppressWarnings("synthetic-access")
                        public void actionPerformed(ActionEvent e) {
-                               nodeDisconnect();
+                               List<Node> nodes = core.getNodes();
+                               if (nodes.isEmpty()) {
+                                       return;
+                               }
+                               nodeDisconnect(nodes.get(0));
                        }
                };
+               rebuildNodeActions(core.getNodes());
                List<Locale> availableLanguages = I18n.findAvailableLanguages();
                for (final Locale locale: availableLanguages) {
                        I18nAction languageAction = new I18nAction("general.language." + locale.getLanguage()) {
@@ -499,15 +597,18 @@ public class SwingInterface implements CoreListener {
                configurationDialog.setAntialias(antialias);
                configurationDialog.setControlFont(controlFont);
                configurationDialog.setUserFont(userFont);
+               configurationDialog.setLookAndFeel(lookAndFeel);
                configurationDialog.setVisible(true);
                if (!configurationDialog.wasCancelled()) {
                        advancedMode = configurationDialog.isAdvancedMode();
                        if (!advancedMode && (nodeList.size() > 1)) {
                                JOptionPane.showMessageDialog(mainWindow, I18n.get("mainWindow.warning.multipleNodesNotAdvancedMode.message"), I18n.get("mainWindow.warning.multipleNodesNotAdvancedMode.title"), JOptionPane.WARNING_MESSAGE);
                        }
+                       mainWindow.setAdvancedMode(advancedMode);
                        antialias = configurationDialog.isAntialias();
                        controlFont = configurationDialog.getControlFont();
                        userFont = configurationDialog.getUserFont();
+                       lookAndFeel = configurationDialog.getLookAndFeel();
                        saveConfig();
                }
        }
@@ -523,11 +624,60 @@ public class SwingInterface implements CoreListener {
         * Quits jSite.
         */
        private void quit() {
+               /* TODO - ask */
+               core.stop();
                saveConfig();
                System.exit(0);
        }
 
        /**
+        * Rebuilds all node connect and disconnect actions.
+        * 
+        * @param nodes
+        *            The list of nodes
+        */
+       private void rebuildNodeActions(List<Node> nodes) {
+               logger.fine("rebuilding node actions…");
+               nodeConnectActions.clear();
+               nodeNodeConnectActions.clear();
+               nodeConnectActionNodes.clear();
+               nodeDisconnectActions.clear();
+               nodeNodeDisconnectActions.clear();
+               nodeDisconnectActionNodes.clear();
+               for (Node node: nodes) {
+                       logger.finer("adding node “" + node + "” to menu");
+                       Action nodeConnectAction = new AbstractAction(node.getName()) {
+
+                               /**
+                                * {@inheritDoc}
+                                */
+                               @SuppressWarnings("synthetic-access")
+                               public void actionPerformed(ActionEvent e) {
+                                       Node node = nodeConnectActionNodes.get(this);
+                                       nodeConnect(node);
+                               }
+                       };
+                       nodeConnectActions.add(nodeConnectAction);
+                       nodeConnectActionNodes.put(nodeConnectAction, node);
+                       nodeNodeConnectActions.put(node, nodeConnectAction);
+                       Action nodeDisconnectAction = new AbstractAction(node.getName()) {
+
+                               /**
+                                * {@inheritDoc}
+                                */
+                               @SuppressWarnings("synthetic-access")
+                               public void actionPerformed(ActionEvent e) {
+                                       Node node = nodeDisconnectActionNodes.get(this);
+                                       nodeDisconnect(node);
+                               }
+                       };
+// nodeDisconnectActions.add(nodeDisconnectAction);
+                       nodeDisconnectActionNodes.put(nodeDisconnectAction, node);
+                       nodeNodeDisconnectActions.put(node, nodeDisconnectAction);
+               }
+       }
+
+       /**
         * Pops up the “manage nodes” dialog.
         */
        private void manageNodes() {
@@ -535,6 +685,8 @@ public class SwingInterface implements CoreListener {
                        manageNodesDialog.setNodeList(nodeList);
                        manageNodesDialog.setVisible(true);
                        nodeList = manageNodesDialog.getNodeList();
+                       rebuildNodeActions(nodeList);
+                       mainWindow.refreshNodeMenuItems();
                } else {
                        if (nodeList.isEmpty()) {
                                Node newNode = new Node();
@@ -560,22 +712,39 @@ public class SwingInterface implements CoreListener {
 
        /**
         * Connects to the node.
+        * 
+        * @param node
+        *            The node to connect to
         */
-       private void nodeConnect() {
-               /* TODO */
+       private void nodeConnect(final Node node) {
+               threadPool.execute(new Runnable() {
+
+                       /**
+                        * {@inheritDoc}
+                        */
+                       @SuppressWarnings("synthetic-access")
+                       public void run() {
+                               logger.log(Level.INFO, "connecting to node “" + node.getName() + "”…");
+                               core.connectToNode(node);
+                       }
+               });
        }
 
        /**
         * Disconnects from the node.
+        * 
+        * @param node
+        *            The node to disconnect from
         */
-       private void nodeDisconnect() {
-               /* TODO */
+       private void nodeDisconnect(Node node) {
+               logger.log(Level.INFO, "disconnecting from node “" + node.getName() + "”…");
+               core.disconnectFromNode(node);
        }
 
        /**
         * Changes the language of the interface. This method also disables the
         * action for the newly set language and enables all others.
-        *
+        * 
         * @param newLocale
         *            The new language
         * @param languageAction
@@ -622,7 +791,6 @@ public class SwingInterface implements CoreListener {
        // INTERFACE CoreListener
        //
 
-
        /**
         * {@inheritDoc}
         */
@@ -683,8 +851,6 @@ public class SwingInterface implements CoreListener {
         * {@inheritDoc}
         */
        public void coreLoaded() {
-               this.nodeList = core.getNodes();
-               manageNodesDialog.setNodeList(nodeList);
                mainWindow.setVisible(true);
                mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.coreLoaded"));
        }
@@ -699,22 +865,80 @@ public class SwingInterface implements CoreListener {
        /**
         * {@inheritDoc}
         */
-       public void nodeConnected(Node node) {
-               /* TODO */
+       public void nodeAdded(Node node) {
+               logger.log(Level.INFO, "node added: " + node);
+               nodeList.add(node);
+               manageNodesDialog.setNodeList(nodeList);
+               rebuildNodeActions(nodeList);
+               mainWindow.refreshNodeMenuItems();
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public void nodeRemoved(Node node) {
+               logger.log(Level.INFO, "node removed: " + node);
+               nodeList.remove(node);
+               rebuildNodeActions(nodeList);
+               mainWindow.refreshNodeMenuItems();
        }
 
        /**
         * {@inheritDoc}
         */
        public void nodeConnecting(Node node) {
-               /* TODO */
+               Action nodeConnectAction = nodeNodeConnectActions.get(node);
+               nodeConnectActions.remove(nodeConnectAction);
+               mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.connectingToNode", node.getName(), node.getHostname(), node.getPort()));
+               mainWindow.refreshNodeMenuItems();
        }
 
        /**
         * {@inheritDoc}
         */
-       public void nodeDisconnected(Node node) {
-               /* TODO */
+       public void nodeConnected(Node node) {
+               Action nodeDisconnectAction = nodeNodeDisconnectActions.get(node);
+               nodeDisconnectActions.add(nodeDisconnectAction);
+               mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.connectedToNode", node.getName(), node.getHostname(), node.getPort()));
+               mainWindow.refreshNodeMenuItems();
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public void nodeDisconnected(Node node, Throwable throwable) {
+               Action nodeConnectAction = nodeNodeConnectActions.get(node);
+               nodeConnectActions.add(nodeConnectAction);
+               Action nodeDisconnectAction = nodeNodeDisconnectActions.get(node);
+               nodeDisconnectActions.remove(nodeDisconnectAction);
+               mainWindow.setStatusBarText(I18n.get("mainWindow.statusBar.disconnectedFromNode", node.getName(), node.getHostname(), node.getPort()));
+               mainWindow.refreshNodeMenuItems();
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public void requestAdded(Node node, Request request) {
+               logger.log(Level.INFO, "request added to node: " + request + ", " + node);
+               /* TODO - implement */
+       }
+
+       /**
+        * {@inheritDoc}
+        */
+       public void requestProgressed(Request request, int totalBlocks, int requiredBlocks, int successfulBlocks, int failedBlocks, int fatallyFailedBlocks, boolean finalizedTotal) {
+               /* TODO - update table model */
+       }
+
+       //
+       // INTERFACE LoggingListener
+       //
+
+       /**
+        * {@inheritDoc}
+        */
+       public void logged(LogRecord logRecord) {
+               logWindow.logged(logRecord);
        }
 
 }