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