update node labels when connecting or disconnecting
[jSite2.git] / src / net / pterodactylus / jsite / gui / MainWindow.java
1 /*
2  * jSite2 - MainWindow.java -
3  * Copyright © 2008 David Roden
4  *
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.
9  *
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.
14  *
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.
18  */
19
20 package net.pterodactylus.jsite.gui;
21
22 import java.awt.BorderLayout;
23 import java.awt.Component;
24 import java.awt.Container;
25 import java.awt.Dimension;
26 import java.awt.event.WindowAdapter;
27 import java.awt.event.WindowEvent;
28 import java.awt.event.WindowListener;
29 import java.beans.PropertyChangeEvent;
30 import java.beans.PropertyChangeListener;
31 import java.util.HashMap;
32 import java.util.Map;
33 import java.util.Timer;
34 import java.util.TimerTask;
35 import java.util.logging.Logger;
36
37 import javax.swing.Box;
38 import javax.swing.BoxLayout;
39 import javax.swing.Icon;
40 import javax.swing.JButton;
41 import javax.swing.JFrame;
42 import javax.swing.JMenu;
43 import javax.swing.JMenuBar;
44 import javax.swing.JPanel;
45 import javax.swing.JTabbedPane;
46 import javax.swing.JToolBar;
47 import javax.swing.SwingConstants;
48 import javax.swing.border.EmptyBorder;
49
50 import net.pterodactylus.jsite.core.Node;
51 import net.pterodactylus.jsite.i18n.I18n;
52 import net.pterodactylus.jsite.i18n.I18nable;
53 import net.pterodactylus.jsite.i18n.gui.I18nAction;
54 import net.pterodactylus.jsite.i18n.gui.I18nMenu;
55 import net.pterodactylus.jsite.main.Version;
56 import net.pterodactylus.jsite.project.Project;
57 import net.pterodactylus.util.image.IconLoader;
58 import net.pterodactylus.util.logging.Logging;
59 import net.pterodactylus.util.swing.StatusBar;
60 import net.pterodactylus.util.swing.SwingUtils;
61
62 /**
63  * Defines the main window of the application.
64  * 
65  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
66  */
67 public class MainWindow extends JFrame implements WindowListener, I18nable, PropertyChangeListener {
68
69         /** Logger. */
70         @SuppressWarnings("unused")
71         private static final Logger logger = Logging.getLogger(MainWindow.class.getName());
72
73         /** The swing interface that receives all actions. */
74         private final SwingInterface swingInterface;
75
76         /** The status bar. */
77         private StatusBar statusBar = new StatusBar();
78
79         /** Timer for clearing the status bar. */
80         private Timer statusBarClearTimer = new Timer("StatusBar Cleaner", true);
81
82         /** Object for status bar clearing ticker event. */
83         private TimerTask statusBarClearTimerTask;
84
85         /** Delay (in seconds) after which to clear status bar. */
86         private int statusBarClearDelay = 5000;
87
88         /** The icon for offline nodes. */
89         private Icon offlineIcon;
90
91         /** The icon for online nodes. */
92         private Icon onlineIcon;
93
94         /** The icon for error nodes. */
95         private Icon errorIcon;
96
97         /** The content pane. */
98         private JPanel contentPane = new JPanel(new BorderLayout(12, 12));
99
100         /** The jSite menu. */
101         private I18nMenu jSiteMenu;
102
103         /** The node menu. */
104         private I18nMenu nodeMenu;
105
106         /** The language menu. */
107         private I18nMenu languageMenu;
108
109         /** The about menu. */
110         private I18nMenu helpMenu;
111
112         /** The tabbed project pane. */
113         private JTabbedPane projectPane;
114
115         /** The project overview panel. */
116         private Box projectOverviewPanel;
117
118         /** Maps from node to menus. */
119         private final Map<Node, JMenu> nodeMenus = new HashMap<Node, JMenu>();
120
121         /** Maps from nodes to node panels. */
122         private final Map<Node, NodeLabel> nodeLabels = new HashMap<Node, NodeLabel>();
123
124         /**
125          * Creates a new main window that redirects all actions to the given swing
126          * interface.
127          * 
128          * @param swingInterface
129          *            The swing interface to receive all actions
130          */
131         public MainWindow(SwingInterface swingInterface) {
132                 super("jSite " + Version.getVersion());
133                 this.swingInterface = swingInterface;
134                 initWindow();
135                 setPreferredSize(new Dimension(480, 280));
136                 pack();
137                 SwingUtils.center(this);
138                 I18n.registerI18nable(this);
139                 addWindowListener(this);
140         }
141
142         //
143         // ACCESSORS
144         //
145
146         /**
147          * Sets the text of the status bar.
148          * 
149          * @param text
150          *            The text of the status bar
151          */
152         public void setStatusBarText(String text) {
153                 statusBar.setText(text);
154                 synchronized (statusBar) {
155                         if (statusBarClearTimerTask != null) {
156                                 statusBarClearTimerTask.cancel();
157                         }
158                         statusBarClearTimerTask = new TimerTask() {
159
160                                 @SuppressWarnings("synthetic-access")
161                                 @Override
162                                 public void run() {
163                                         statusBar.setText("\u00a0");
164                                 }
165
166                         };
167                         statusBarClearTimer.schedule(statusBarClearTimerTask, statusBarClearDelay);
168                 }
169         }
170
171         /**
172          * Returns the status bar clear delay (in milliseconds).
173          * 
174          * @return The status bar clear delay
175          */
176         public int getStatusBarClearDelay() {
177                 return statusBarClearDelay;
178         }
179
180         /**
181          * Sets the status bar clear delay (in milliseconds).
182          * 
183          * @param statusBarClearDelay
184          *            The status bar clear delay
185          */
186         public void setStatusBarClearDelay(int statusBarClearDelay) {
187                 this.statusBarClearDelay = statusBarClearDelay;
188         }
189
190         /**
191          * Sets whether the advanced mode is activated.
192          * 
193          * @param advancedMode
194          *            <code>true</code> if the advanced mode is activated,
195          *            <code>false</code> if the simple mode is activated
196          */
197         public void setAdvancedMode(boolean advancedMode) {
198                 /* doesn’t do anything right now. */
199         }
200
201         /**
202          * {@inheritDoc}
203          */
204         @Override
205         public Container getContentPane() {
206                 return contentPane;
207         }
208
209         /**
210          * Returns the currently selected project.
211          * 
212          * @return The currently selected project
213          */
214         public Project getSelectedProject() {
215                 return null;
216         }
217
218         /**
219          * Sets the given node to the “online” state.
220          * 
221          * @param node
222          *            The node to set online
223          */
224         public void setOnline(Node node) {
225                 nodeLabels.get(node).setOnline();
226         }
227
228         /**
229          * Sets the given node to the “offline” state in the status bar.
230          * 
231          * @param node
232          *            The node to set offline
233          */
234         public void setOffline(Node node) {
235                 nodeLabels.get(node).setOffline();
236         }
237
238         /**
239          * Sets the given node to the “error” state in the status bar.
240          * 
241          * @param node
242          *            The node to set the error state for
243          */
244         public void setError(Node node) {
245                 nodeLabels.get(node).setError();
246         }
247
248         //
249         // ACTIONS
250         //
251
252         /**
253          * Adds a node to the menu.
254          * 
255          * @param node
256          *            The node to add
257          */
258         void addNode(Node node) {
259                 JMenu newNodeMenu = new JMenu(node.getName());
260                 nodeMenus.put(node, newNodeMenu);
261                 newNodeMenu.add(swingInterface.getNodeConnectAction(node));
262                 newNodeMenu.add(swingInterface.getNodeDisconnectAction(node));
263                 newNodeMenu.addSeparator();
264                 newNodeMenu.add(swingInterface.getNodeEditAction(node));
265                 newNodeMenu.add(swingInterface.getNodeDeleteAction(node));
266                 nodeMenu.add(newNodeMenu);
267                 NodeLabel nodeLabel = new NodeLabel(swingInterface, node, onlineIcon, offlineIcon, errorIcon);
268                 nodeLabels.put(node, nodeLabel);
269                 statusBar.addSideComponent(nodeLabel);
270                 node.addPropertyChangeListener(this);
271         }
272
273         /**
274          * Removes a node from the menu.
275          * 
276          * @param node
277          *            The node to remove
278          */
279         void removeNode(Node node) {
280                 nodeMenu.remove(nodeMenus.remove(node));
281                 statusBar.removeSideComponent(nodeLabels.remove(node));
282                 node.removePropertyChangeListener(this);
283         }
284
285         /**
286          * Adds a project to the project pane.
287          * 
288          * @param project
289          *            The project to add
290          * @param switchToProject
291          *            <code>true</code> to switch to the new panel,
292          *            <code>false</code> to not change the current panel
293          */
294         void addProject(Project project, boolean switchToProject) {
295                 ProjectPanel projectPanel = new ProjectPanel(swingInterface, project);
296                 int newTabIndex = projectPane.getTabCount();
297                 projectPane.add(project.getName(), projectPanel);
298                 projectPane.setToolTipTextAt(newTabIndex, project.getDescription());
299                 project.addPropertyChangeListener(this);
300                 if (switchToProject) {
301                         projectPane.setSelectedIndex(newTabIndex);
302                 }
303         }
304
305         /**
306          * @param project
307          */
308         void projectInsertStarted(Project project) {
309                 int projectIndex = getProjectIndex(project);
310                 if (projectIndex == -1) {
311                         return;
312                 }
313                 projectPane.setTitleAt(projectIndex, I18n.get("projectPanel.title.starting", project.getName()));
314         }
315
316         /**
317          * @param project
318          * @param totalBlocks
319          * @param requiredBlocks
320          * @param successfulBlocks
321          * @param failedBlocks
322          * @param fatallyFailedBlocks
323          * @param finalizedTotal
324          */
325         void projectInsertProgressed(Project project, int totalBlocks, int requiredBlocks, int successfulBlocks, int failedBlocks, int fatallyFailedBlocks, boolean finalizedTotal) {
326                 int projectIndex = getProjectIndex(project);
327                 if (projectIndex == -1) {
328                         return;
329                 }
330                 projectPane.setTitleAt(projectIndex, I18n.get("projectPanel.title.progress", project.getName(), requiredBlocks / (double) successfulBlocks));
331         }
332
333         /**
334          * @param project
335          */
336         void projectInsertGeneratedURI(Project project) {
337                 /* TODO - update panel. */
338         }
339
340         /**
341          * @param project
342          * @param success
343          */
344         void projectInsertFinished(Project project, boolean success) {
345                 int projectIndex = getProjectIndex(project);
346                 if (projectIndex == -1) {
347                         return;
348                 }
349                 projectPane.setTitleAt(projectIndex, project.getName());
350         }
351
352         //
353         // PRIVATE METHODS
354         //
355
356         /**
357          * Returns the index of the project panel that contains the given project.
358          * 
359          * @param project
360          *            The wanted project
361          * @return The index of {@link #projectPane}’s tab that contains the given
362          *         project, or <code>-1</code> if the project can not be found
363          */
364         private int getProjectIndex(Project project) {
365                 int tabCount = projectPane.getTabCount();
366                 for (int tabIndex = 1; tabIndex < tabCount; tabIndex++) {
367                         Component tabComponent = projectPane.getComponentAt(tabIndex);
368                         if (tabComponent instanceof ProjectPanel) {
369                                 if (((ProjectPanel) tabComponent).getProject() == project) {
370                                         return tabIndex;
371                                 }
372                         }
373                 }
374                 return -1;
375         }
376
377         /**
378          * Initializes the window by creating all its components.
379          */
380         private void initWindow() {
381                 onlineIcon = IconLoader.loadIcon("/node-online.png");
382                 offlineIcon = IconLoader.loadIcon("/node-offline.png");
383                 errorIcon = IconLoader.loadIcon("/node-error.png");
384
385                 JMenuBar menuBar = new JMenuBar();
386
387                 jSiteMenu = new I18nMenu("mainWindow.menu.jSite");
388                 menuBar.add(jSiteMenu);
389
390                 jSiteMenu.add(new FixedJMenuItem(swingInterface.getConfigureAction()));
391                 jSiteMenu.addSeparator();
392                 jSiteMenu.add(new FixedJMenuItem(swingInterface.getImportConfigAction()));
393                 jSiteMenu.addSeparator();
394                 jSiteMenu.add(new FixedJMenuItem(swingInterface.getQuitAction()));
395
396                 nodeMenu = new I18nMenu("mainWindow.menu.node");
397                 menuBar.add(nodeMenu);
398
399                 nodeMenu.add(new FixedJMenuItem(swingInterface.getAddNodeAction()));
400                 nodeMenu.addSeparator();
401
402                 languageMenu = new I18nMenu("mainWindow.menu.language");
403                 menuBar.add(languageMenu);
404
405                 for (I18nAction languageAction: swingInterface.getLanguageActions()) {
406                         languageMenu.add(new FixedJMenuItem(languageAction));
407                 }
408
409                 menuBar.add(Box.createHorizontalGlue());
410
411                 helpMenu = new I18nMenu("mainWindow.menu.help");
412                 menuBar.add(helpMenu);
413
414                 helpMenu.add(new FixedJMenuItem(swingInterface.getHelpAboutAction()));
415
416                 setJMenuBar(menuBar);
417
418                 JToolBar toolBar = new JToolBar(I18n.get("mainWindow.toolbar.name"));
419                 toolBar.add(swingInterface.getAddNodeAction());
420                 toolBar.addSeparator();
421                 toolBar.add(swingInterface.getQuitAction());
422                 super.getContentPane().add(toolBar, BorderLayout.PAGE_START);
423
424                 super.getContentPane().add(contentPane, BorderLayout.CENTER);
425
426                 addWindowListener(new WindowAdapter() {
427
428                         /**
429                          * {@inheritDoc}
430                          */
431                         @SuppressWarnings("synthetic-access")
432                         @Override
433                         public void windowClosing(WindowEvent windowEvent) {
434                                 swingInterface.getQuitAction().actionPerformed(null);
435                         }
436                 });
437
438                 initComponents();
439         }
440
441         /**
442          * Initializes all components of this window.
443          */
444         private void initComponents() {
445                 super.getContentPane().add(statusBar, BorderLayout.PAGE_END);
446                 contentPane.setBorder(new EmptyBorder(12, 12, 12, 12));
447
448                 projectPane = new JTabbedPane(SwingConstants.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
449                 contentPane.add(projectPane, BorderLayout.CENTER);
450
451                 projectOverviewPanel = new Box(BoxLayout.PAGE_AXIS);
452                 projectOverviewPanel.setName(I18n.get("mainWindow.pane.overview.title"));
453                 projectPane.add(projectOverviewPanel);
454                 projectOverviewPanel.setBorder(new EmptyBorder(12, 12, 12, 12));
455                 projectOverviewPanel.add(Box.createVerticalGlue());
456                 JButton addProjectButton = new JButton(swingInterface.getAddProjectAction());
457                 addProjectButton.setAlignmentX(0.5f);
458                 projectOverviewPanel.add(addProjectButton);
459                 projectOverviewPanel.add(Box.createVerticalGlue());
460         }
461
462         //
463         // INTERFACE I18nable
464         //
465
466         /**
467          * {@inheritDoc}
468          */
469         public void updateI18n() {
470                 swingInterface.getConfigureAction().updateI18n();
471                 swingInterface.getImportConfigAction().updateI18n();
472                 swingInterface.getQuitAction().updateI18n();
473                 swingInterface.getAddNodeAction().updateI18n();
474                 swingInterface.getAddProjectAction().updateI18n();
475                 swingInterface.getCloneProjectAction().updateI18n();
476                 swingInterface.getDeleteProjectAction().updateI18n();
477                 swingInterface.getHelpAboutAction().updateI18n();
478                 jSiteMenu.updateI18n();
479                 nodeMenu.updateI18n();
480                 languageMenu.updateI18n();
481                 for (Node node: swingInterface.getNodes()) {
482                         swingInterface.getNodeConnectAction(node).updateI18n();
483                         swingInterface.getNodeDisconnectAction(node).updateI18n();
484                         swingInterface.getNodeEditAction(node).updateI18n();
485                         swingInterface.getNodeDeleteAction(node).updateI18n();
486                 }
487                 for (I18nAction languageAction: swingInterface.getLanguageActions()) {
488                         languageAction.updateI18n();
489                 }
490                 helpMenu.updateI18n();
491                 getJMenuBar().revalidate();
492                 projectPane.setTitleAt(0, I18n.get("mainWindow.pane.overview.title"));
493                 for (int componentIndex = 0; componentIndex < projectPane.getTabCount(); componentIndex++) {
494                         Component tabComponent = projectPane.getComponentAt(componentIndex);
495                         if (tabComponent instanceof ProjectPanel) {
496                                 ((ProjectPanel) tabComponent).updateI18n();
497                         }
498                 }
499                 SwingUtils.repackCentered(this);
500         }
501
502         //
503         // INTERFACE WindowListener
504         //
505
506         /**
507          * {@inheritDoc}
508          */
509         public void windowActivated(WindowEvent e) {
510                 /* do nothing. */
511         }
512
513         /**
514          * {@inheritDoc}
515          */
516         public void windowClosed(WindowEvent e) {
517                 /* do nothing. */
518         }
519
520         /**
521          * {@inheritDoc}
522          */
523         public void windowClosing(WindowEvent e) {
524                 swingInterface.getQuitAction().actionPerformed(null);
525         }
526
527         /**
528          * {@inheritDoc}
529          */
530         public void windowDeactivated(WindowEvent e) {
531                 /* do nothing. */
532         }
533
534         /**
535          * {@inheritDoc}
536          */
537         public void windowDeiconified(WindowEvent e) {
538                 /* do nothing. */
539         }
540
541         /**
542          * {@inheritDoc}
543          */
544         public void windowIconified(WindowEvent e) {
545                 /* do nothing. */
546         }
547
548         /**
549          * {@inheritDoc}
550          */
551         public void windowOpened(WindowEvent e) {
552                 /* do nothing. */
553         }
554
555         //
556         // INTERFACE PropertyChangeListener
557         //
558
559         /**
560          * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
561          */
562         public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
563                 Object eventSource = propertyChangeEvent.getSource();
564                 String propertyName = propertyChangeEvent.getPropertyName();
565                 if (eventSource instanceof Project) {
566                         /* if a project was changed, update the tab title and tooltip. */
567                         if (Project.PROPERTY_NAME.equals(propertyName) || Project.PROPERTY_DESCRIPTION.equals(propertyName)) {
568                                 Project project = (Project) eventSource;
569                                 int tabCount = projectPane.getTabCount();
570                                 for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
571                                         Component tabComponent = projectPane.getComponentAt(tabIndex);
572                                         if (tabComponent instanceof ProjectPanel) {
573                                                 Project tabProject = ((ProjectPanel) tabComponent).getProject();
574                                                 if (tabProject.equals(project)) {
575                                                         projectPane.setTitleAt(tabIndex, project.getName());
576                                                         projectPane.setToolTipTextAt(tabIndex, project.getDescription());
577                                                         projectPane.repaint();
578                                                 }
579                                         }
580                                 }
581                         }
582                 } else if (eventSource instanceof Node) {
583                         if (propertyName.equals(Node.PROPERTY_NAME)) {
584                                 Node changedNode = (Node) eventSource;
585                                 nodeMenus.get(changedNode).setText(changedNode.getName());
586                         }
587                 }
588         }
589
590 }