set frame icon
[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                 setIconImage(IconLoader.loadImage("/jSite-frame-icon.png"));
141         }
142
143         //
144         // ACCESSORS
145         //
146
147         /**
148          * Sets the text of the status bar.
149          * 
150          * @param text
151          *            The text of the status bar
152          */
153         public void setStatusBarText(String text) {
154                 statusBar.setText(text);
155                 synchronized (statusBar) {
156                         if (statusBarClearTimerTask != null) {
157                                 statusBarClearTimerTask.cancel();
158                         }
159                         statusBarClearTimerTask = new TimerTask() {
160
161                                 @SuppressWarnings("synthetic-access")
162                                 @Override
163                                 public void run() {
164                                         statusBar.setText("\u00a0");
165                                 }
166
167                         };
168                         statusBarClearTimer.schedule(statusBarClearTimerTask, statusBarClearDelay);
169                 }
170         }
171
172         /**
173          * Returns the status bar clear delay (in milliseconds).
174          * 
175          * @return The status bar clear delay
176          */
177         public int getStatusBarClearDelay() {
178                 return statusBarClearDelay;
179         }
180
181         /**
182          * Sets the status bar clear delay (in milliseconds).
183          * 
184          * @param statusBarClearDelay
185          *            The status bar clear delay
186          */
187         public void setStatusBarClearDelay(int statusBarClearDelay) {
188                 this.statusBarClearDelay = statusBarClearDelay;
189         }
190
191         /**
192          * Sets whether the advanced mode is activated.
193          * 
194          * @param advancedMode
195          *            <code>true</code> if the advanced mode is activated,
196          *            <code>false</code> if the simple mode is activated
197          */
198         public void setAdvancedMode(boolean advancedMode) {
199                 /* doesn’t do anything right now. */
200         }
201
202         /**
203          * {@inheritDoc}
204          */
205         @Override
206         public Container getContentPane() {
207                 return contentPane;
208         }
209
210         /**
211          * Returns the currently selected project.
212          * 
213          * @return The currently selected project
214          */
215         public Project getSelectedProject() {
216                 return null;
217         }
218
219         /**
220          * Sets the given node to the “online” state.
221          * 
222          * @param node
223          *            The node to set online
224          */
225         public void setOnline(Node node) {
226                 nodeLabels.get(node).setOnline();
227         }
228
229         /**
230          * Sets the given node to the “offline” state in the status bar.
231          * 
232          * @param node
233          *            The node to set offline
234          */
235         public void setOffline(Node node) {
236                 nodeLabels.get(node).setOffline();
237         }
238
239         /**
240          * Sets the given node to the “error” state in the status bar.
241          * 
242          * @param node
243          *            The node to set the error state for
244          */
245         public void setError(Node node) {
246                 nodeLabels.get(node).setError();
247         }
248
249         //
250         // ACTIONS
251         //
252
253         /**
254          * Adds a node to the menu.
255          * 
256          * @param node
257          *            The node to add
258          */
259         void addNode(Node node) {
260                 JMenu newNodeMenu = new JMenu(node.getName());
261                 nodeMenus.put(node, newNodeMenu);
262                 newNodeMenu.add(swingInterface.getNodeConnectAction(node));
263                 newNodeMenu.add(swingInterface.getNodeDisconnectAction(node));
264                 newNodeMenu.addSeparator();
265                 newNodeMenu.add(swingInterface.getNodeEditAction(node));
266                 newNodeMenu.add(swingInterface.getNodeDeleteAction(node));
267                 nodeMenu.add(newNodeMenu);
268                 NodeLabel nodeLabel = new NodeLabel(swingInterface, node, onlineIcon, offlineIcon, errorIcon);
269                 nodeLabels.put(node, nodeLabel);
270                 statusBar.addSideComponent(nodeLabel);
271                 node.addPropertyChangeListener(this);
272         }
273
274         /**
275          * Removes a node from the menu.
276          * 
277          * @param node
278          *            The node to remove
279          */
280         void removeNode(Node node) {
281                 nodeMenu.remove(nodeMenus.remove(node));
282                 statusBar.removeSideComponent(nodeLabels.remove(node));
283                 node.removePropertyChangeListener(this);
284         }
285
286         /**
287          * Adds a project to the project pane.
288          * 
289          * @param project
290          *            The project to add
291          * @param switchToProject
292          *            <code>true</code> to switch to the new panel,
293          *            <code>false</code> to not change the current panel
294          */
295         void addProject(Project project, boolean switchToProject) {
296                 ProjectPanel projectPanel = new ProjectPanel(swingInterface, project);
297                 int newTabIndex = projectPane.getTabCount();
298                 projectPane.add(project.getName(), projectPanel);
299                 projectPane.setToolTipTextAt(newTabIndex, project.getDescription());
300                 project.addPropertyChangeListener(this);
301                 if (switchToProject) {
302                         projectPane.setSelectedIndex(newTabIndex);
303                 }
304         }
305
306         /**
307          * @param project
308          */
309         void projectInsertStarted(Project project) {
310                 int projectIndex = getProjectIndex(project);
311                 if (projectIndex == -1) {
312                         return;
313                 }
314                 projectPane.setTitleAt(projectIndex, I18n.get("projectPanel.title.starting", project.getName()));
315         }
316
317         /**
318          * @param project
319          * @param totalBlocks
320          * @param requiredBlocks
321          * @param successfulBlocks
322          * @param failedBlocks
323          * @param fatallyFailedBlocks
324          * @param finalizedTotal
325          */
326         void projectInsertProgressed(Project project, int totalBlocks, int requiredBlocks, int successfulBlocks, int failedBlocks, int fatallyFailedBlocks, boolean finalizedTotal) {
327                 int projectIndex = getProjectIndex(project);
328                 if (projectIndex == -1) {
329                         return;
330                 }
331                 projectPane.setTitleAt(projectIndex, I18n.get("projectPanel.title.progress", project.getName(), requiredBlocks / (double) successfulBlocks));
332         }
333
334         /**
335          * @param project
336          */
337         void projectInsertGeneratedURI(Project project) {
338                 /* TODO - update panel. */
339         }
340
341         /**
342          * @param project
343          * @param success
344          */
345         void projectInsertFinished(Project project, boolean success) {
346                 int projectIndex = getProjectIndex(project);
347                 if (projectIndex == -1) {
348                         return;
349                 }
350                 projectPane.setTitleAt(projectIndex, project.getName());
351         }
352
353         //
354         // PRIVATE METHODS
355         //
356
357         /**
358          * Returns the index of the project panel that contains the given project.
359          * 
360          * @param project
361          *            The wanted project
362          * @return The index of {@link #projectPane}’s tab that contains the given
363          *         project, or <code>-1</code> if the project can not be found
364          */
365         private int getProjectIndex(Project project) {
366                 int tabCount = projectPane.getTabCount();
367                 for (int tabIndex = 1; tabIndex < tabCount; tabIndex++) {
368                         Component tabComponent = projectPane.getComponentAt(tabIndex);
369                         if (tabComponent instanceof ProjectPanel) {
370                                 if (((ProjectPanel) tabComponent).getProject() == project) {
371                                         return tabIndex;
372                                 }
373                         }
374                 }
375                 return -1;
376         }
377
378         /**
379          * Initializes the window by creating all its components.
380          */
381         private void initWindow() {
382                 onlineIcon = IconLoader.loadIcon("/node-online.png");
383                 offlineIcon = IconLoader.loadIcon("/node-offline.png");
384                 errorIcon = IconLoader.loadIcon("/node-error.png");
385
386                 JMenuBar menuBar = new JMenuBar();
387
388                 jSiteMenu = new I18nMenu("mainWindow.menu.jSite");
389                 menuBar.add(jSiteMenu);
390
391                 jSiteMenu.add(new FixedJMenuItem(swingInterface.getConfigureAction()));
392                 jSiteMenu.addSeparator();
393                 jSiteMenu.add(new FixedJMenuItem(swingInterface.getImportConfigAction()));
394                 jSiteMenu.addSeparator();
395                 jSiteMenu.add(new FixedJMenuItem(swingInterface.getQuitAction()));
396
397                 nodeMenu = new I18nMenu("mainWindow.menu.node");
398                 menuBar.add(nodeMenu);
399
400                 nodeMenu.add(new FixedJMenuItem(swingInterface.getAddNodeAction()));
401                 nodeMenu.addSeparator();
402
403                 languageMenu = new I18nMenu("mainWindow.menu.language");
404                 menuBar.add(languageMenu);
405
406                 for (I18nAction languageAction: swingInterface.getLanguageActions()) {
407                         languageMenu.add(new FixedJMenuItem(languageAction));
408                 }
409
410                 menuBar.add(Box.createHorizontalGlue());
411
412                 helpMenu = new I18nMenu("mainWindow.menu.help");
413                 menuBar.add(helpMenu);
414
415                 helpMenu.add(new FixedJMenuItem(swingInterface.getHelpAboutAction()));
416
417                 setJMenuBar(menuBar);
418
419                 JToolBar toolBar = new JToolBar(I18n.get("mainWindow.toolbar.name"));
420                 toolBar.add(swingInterface.getAddNodeAction());
421                 toolBar.addSeparator();
422                 toolBar.add(swingInterface.getQuitAction());
423                 super.getContentPane().add(toolBar, BorderLayout.PAGE_START);
424
425                 super.getContentPane().add(contentPane, BorderLayout.CENTER);
426
427                 addWindowListener(new WindowAdapter() {
428
429                         /**
430                          * {@inheritDoc}
431                          */
432                         @SuppressWarnings("synthetic-access")
433                         @Override
434                         public void windowClosing(WindowEvent windowEvent) {
435                                 swingInterface.getQuitAction().actionPerformed(null);
436                         }
437                 });
438
439                 initComponents();
440         }
441
442         /**
443          * Initializes all components of this window.
444          */
445         private void initComponents() {
446                 super.getContentPane().add(statusBar, BorderLayout.PAGE_END);
447                 contentPane.setBorder(new EmptyBorder(12, 12, 12, 12));
448
449                 projectPane = new JTabbedPane(SwingConstants.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
450                 contentPane.add(projectPane, BorderLayout.CENTER);
451
452                 projectOverviewPanel = new Box(BoxLayout.PAGE_AXIS);
453                 projectOverviewPanel.setName(I18n.get("mainWindow.pane.overview.title"));
454                 projectPane.add(projectOverviewPanel);
455                 projectOverviewPanel.setBorder(new EmptyBorder(12, 12, 12, 12));
456                 projectOverviewPanel.add(Box.createVerticalGlue());
457                 JButton addProjectButton = new JButton(swingInterface.getAddProjectAction());
458                 addProjectButton.setAlignmentX(0.5f);
459                 projectOverviewPanel.add(addProjectButton);
460                 projectOverviewPanel.add(Box.createVerticalGlue());
461         }
462
463         //
464         // INTERFACE I18nable
465         //
466
467         /**
468          * {@inheritDoc}
469          */
470         public void updateI18n() {
471                 swingInterface.getConfigureAction().updateI18n();
472                 swingInterface.getImportConfigAction().updateI18n();
473                 swingInterface.getQuitAction().updateI18n();
474                 swingInterface.getAddNodeAction().updateI18n();
475                 swingInterface.getAddProjectAction().updateI18n();
476                 swingInterface.getCloneProjectAction().updateI18n();
477                 swingInterface.getDeleteProjectAction().updateI18n();
478                 swingInterface.getHelpAboutAction().updateI18n();
479                 jSiteMenu.updateI18n();
480                 nodeMenu.updateI18n();
481                 languageMenu.updateI18n();
482                 for (Node node: swingInterface.getNodes()) {
483                         swingInterface.getNodeConnectAction(node).updateI18n();
484                         swingInterface.getNodeDisconnectAction(node).updateI18n();
485                         swingInterface.getNodeEditAction(node).updateI18n();
486                         swingInterface.getNodeDeleteAction(node).updateI18n();
487                 }
488                 for (I18nAction languageAction: swingInterface.getLanguageActions()) {
489                         languageAction.updateI18n();
490                 }
491                 helpMenu.updateI18n();
492                 getJMenuBar().revalidate();
493                 projectPane.setTitleAt(0, I18n.get("mainWindow.pane.overview.title"));
494                 for (int componentIndex = 0; componentIndex < projectPane.getTabCount(); componentIndex++) {
495                         Component tabComponent = projectPane.getComponentAt(componentIndex);
496                         if (tabComponent instanceof ProjectPanel) {
497                                 ((ProjectPanel) tabComponent).updateI18n();
498                         }
499                 }
500                 SwingUtils.repackCentered(this);
501         }
502
503         //
504         // INTERFACE WindowListener
505         //
506
507         /**
508          * {@inheritDoc}
509          */
510         public void windowActivated(WindowEvent e) {
511                 /* do nothing. */
512         }
513
514         /**
515          * {@inheritDoc}
516          */
517         public void windowClosed(WindowEvent e) {
518                 /* do nothing. */
519         }
520
521         /**
522          * {@inheritDoc}
523          */
524         public void windowClosing(WindowEvent e) {
525                 swingInterface.getQuitAction().actionPerformed(null);
526         }
527
528         /**
529          * {@inheritDoc}
530          */
531         public void windowDeactivated(WindowEvent e) {
532                 /* do nothing. */
533         }
534
535         /**
536          * {@inheritDoc}
537          */
538         public void windowDeiconified(WindowEvent e) {
539                 /* do nothing. */
540         }
541
542         /**
543          * {@inheritDoc}
544          */
545         public void windowIconified(WindowEvent e) {
546                 /* do nothing. */
547         }
548
549         /**
550          * {@inheritDoc}
551          */
552         public void windowOpened(WindowEvent e) {
553                 /* do nothing. */
554         }
555
556         //
557         // INTERFACE PropertyChangeListener
558         //
559
560         /**
561          * @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
562          */
563         public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
564                 Object eventSource = propertyChangeEvent.getSource();
565                 String propertyName = propertyChangeEvent.getPropertyName();
566                 if (eventSource instanceof Project) {
567                         /* if a project was changed, update the tab title and tooltip. */
568                         if (Project.PROPERTY_NAME.equals(propertyName) || Project.PROPERTY_DESCRIPTION.equals(propertyName)) {
569                                 Project project = (Project) eventSource;
570                                 int tabCount = projectPane.getTabCount();
571                                 for (int tabIndex = 0; tabIndex < tabCount; tabIndex++) {
572                                         Component tabComponent = projectPane.getComponentAt(tabIndex);
573                                         if (tabComponent instanceof ProjectPanel) {
574                                                 Project tabProject = ((ProjectPanel) tabComponent).getProject();
575                                                 if (tabProject.equals(project)) {
576                                                         projectPane.setTitleAt(tabIndex, project.getName());
577                                                         projectPane.setToolTipTextAt(tabIndex, project.getDescription());
578                                                         projectPane.repaint();
579                                                 }
580                                         }
581                                 }
582                         }
583                 } else if (eventSource instanceof Node) {
584                         if (propertyName.equals(Node.PROPERTY_NAME)) {
585                                 Node changedNode = (Node) eventSource;
586                                 nodeMenus.get(changedNode).setText(changedNode.getName());
587                         }
588                 }
589         }
590
591 }