8c9a15df6260cf9a35005dde178944cfe751109b
[jSite.git] / src / de / todesbaum / jsite / main / Main.java
1 /*
2  * jSite - a tool for uploading websites into Freenet
3  * Copyright (C) 2006 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 de.todesbaum.jsite.main;
21
22 import java.awt.event.ActionEvent;
23 import java.awt.event.ActionListener;
24 import java.io.File;
25 import java.io.IOException;
26 import java.text.MessageFormat;
27 import java.util.HashMap;
28 import java.util.Locale;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.Map.Entry;
32
33 import javax.swing.AbstractAction;
34 import javax.swing.Action;
35 import javax.swing.ButtonGroup;
36 import javax.swing.Icon;
37 import javax.swing.JList;
38 import javax.swing.JMenu;
39 import javax.swing.JMenuBar;
40 import javax.swing.JOptionPane;
41 import javax.swing.JPanel;
42 import javax.swing.JRadioButtonMenuItem;
43 import javax.swing.event.ListSelectionEvent;
44 import javax.swing.event.ListSelectionListener;
45
46 import de.todesbaum.jsite.application.FileOption;
47 import de.todesbaum.jsite.application.Freenet7Interface;
48 import de.todesbaum.jsite.application.Node;
49 import de.todesbaum.jsite.application.Project;
50 import de.todesbaum.jsite.gui.NodeManagerListener;
51 import de.todesbaum.jsite.gui.NodeManagerPage;
52 import de.todesbaum.jsite.gui.ProjectFilesPage;
53 import de.todesbaum.jsite.gui.ProjectInsertPage;
54 import de.todesbaum.jsite.gui.ProjectPage;
55 import de.todesbaum.jsite.i18n.I18n;
56 import de.todesbaum.jsite.i18n.I18nContainer;
57 import de.todesbaum.util.image.IconLoader;
58 import de.todesbaum.util.swing.TWizard;
59 import de.todesbaum.util.swing.TWizardPage;
60 import de.todesbaum.util.swing.WizardListener;
61
62 /**
63  * The main class that ties together everything.
64  *
65  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
66  */
67 public class Main implements ActionListener, ListSelectionListener, WizardListener, NodeManagerListener {
68
69         /** Whether the debug mode is activated. */
70         private static boolean debug = false;
71
72         /** The configuration. */
73         private Configuration configuration;
74
75         /** The freenet interface. */
76         private Freenet7Interface freenetInterface = new Freenet7Interface();
77
78         /** The jSite icon. */
79         private Icon jSiteIcon;
80
81         /**
82          * Enumeration for all possible pages.
83          *
84          * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
85          */
86         private static enum PageType {
87
88                 /** The node manager page. */
89                 PAGE_NODE_MANAGER,
90
91                 /** The project page. */
92                 PAGE_PROJECTS,
93
94                 /** The project files page. */
95                 PAGE_PROJECT_FILES,
96
97                 /** The project insert page. */
98                 PAGE_INSERT_PROJECT
99
100         }
101
102         /** The supported locales. */
103         private static final Locale[] SUPPORTED_LOCALES = new Locale[] { Locale.ENGLISH, Locale.GERMAN, Locale.FRENCH, Locale.ITALIAN, new Locale("pl") };
104
105         /** The actions that switch the language. */
106         private Map<Locale, Action> languageActions = new HashMap<Locale, Action>();
107
108         /** The “manage nodes” action. */
109         private Action manageNodeAction;
110
111         /** The “about jSite” action. */
112         private Action aboutAction;
113
114         /** The wizard. */
115         private TWizard wizard;
116
117         /** The node menu. */
118         private JMenu nodeMenu;
119
120         /** The currently selected node. */
121         private Node selectedNode;
122
123         /** Mapping from page type to page. */
124         private final Map<PageType, TWizardPage> pages = new HashMap<PageType, TWizardPage>();
125
126         /**
127          * Creates a new core with the default configuration file.
128          */
129         private Main() {
130                 this(null);
131         }
132
133         /**
134          * Creates a new core with the given configuration from the given file.
135          *
136          * @param configFilename
137          *            The name of the configuration file
138          */
139         private Main(String configFilename) {
140                 if (configFilename != null) {
141                         configuration = new Configuration(configFilename);
142                 } else {
143                         configuration = new Configuration();
144                 }
145                 Locale.setDefault(configuration.getLocale());
146                 I18n.setLocale(configuration.getLocale());
147                 if (!configuration.createLockFile()) {
148                         int option = JOptionPane.showOptionDialog(null, I18n.getMessage("jsite.main.already-running"), "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { I18n.getMessage("jsite.main.already-running.override"), I18n.getMessage("jsite.wizard.quit") }, I18n.getMessage("jsite.wizard.quit"));
149                         if (option != 0) {
150                                 return;
151                         }
152                         configuration.removeLockfileOnExit();
153                 }
154                 wizard = new TWizard();
155                 createActions();
156                 wizard.setJMenuBar(createMenuBar());
157                 wizard.setQuitName(I18n.getMessage("jsite.wizard.quit"));
158                 wizard.setPreviousEnabled(false);
159                 wizard.setNextEnabled(true);
160                 wizard.addWizardListener(this);
161                 jSiteIcon = IconLoader.loadIcon("/jsite-icon.png");
162                 wizard.setIcon(jSiteIcon);
163
164                 initPages();
165                 showPage(PageType.PAGE_PROJECTS);
166         }
167
168         /**
169          * Creates all actions.
170          */
171         private void createActions() {
172                 for (final Locale locale : SUPPORTED_LOCALES) {
173                         languageActions.put(locale, new AbstractAction(I18n.getMessage("jsite.menu.language." + locale.getLanguage()), IconLoader.loadIcon("/flag-" + locale.getLanguage() + ".png")) {
174
175                                 @SuppressWarnings("synthetic-access")
176                                 public void actionPerformed(ActionEvent actionEvent) {
177                                         switchLanguage(locale);
178                                 }
179                         });
180                 }
181                 manageNodeAction = new AbstractAction(I18n.getMessage("jsite.menu.nodes.manage-nodes")) {
182
183                         @SuppressWarnings("synthetic-access")
184                         public void actionPerformed(ActionEvent actionEvent) {
185                                 showPage(PageType.PAGE_NODE_MANAGER);
186                                 wizard.setPreviousName(I18n.getMessage("jsite.wizard.previous"));
187                                 wizard.setNextName(I18n.getMessage("jsite.wizard.next"));
188                         }
189                 };
190                 aboutAction = new AbstractAction(I18n.getMessage("jsite.menu.help.about")) {
191
192                         @SuppressWarnings("synthetic-access")
193                         public void actionPerformed(ActionEvent e) {
194                                 JOptionPane.showMessageDialog(wizard, MessageFormat.format(I18n.getMessage("jsite.about.message"), Version.getVersion()), null, JOptionPane.INFORMATION_MESSAGE, jSiteIcon);
195                         }
196                 };
197
198                 I18nContainer.getInstance().registerRunnable(new Runnable() {
199
200                         @SuppressWarnings("synthetic-access")
201                         public void run() {
202                                 manageNodeAction.putValue(Action.NAME, I18n.getMessage("jsite.menu.nodes.manage-nodes"));
203                                 aboutAction.putValue(Action.NAME, I18n.getMessage("jsite.menu.help.about"));
204                         }
205                 });
206         }
207
208         /**
209          * Creates the menu bar.
210          *
211          * @return The menu bar
212          */
213         private JMenuBar createMenuBar() {
214                 JMenuBar menuBar = new JMenuBar();
215                 final JMenu languageMenu = new JMenu(I18n.getMessage("jsite.menu.languages"));
216                 menuBar.add(languageMenu);
217                 ButtonGroup languageButtonGroup = new ButtonGroup();
218                 for (Locale locale : SUPPORTED_LOCALES) {
219                         Action languageAction = languageActions.get(locale);
220                         JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem(languageActions.get(locale));
221                         if (locale.equals(Locale.getDefault())) {
222                                 menuItem.setSelected(true);
223                         }
224                         languageAction.putValue("menuItem", menuItem);
225                         languageButtonGroup.add(menuItem);
226                         languageMenu.add(menuItem);
227                 }
228                 nodeMenu = new JMenu(I18n.getMessage("jsite.menu.nodes"));
229                 menuBar.add(nodeMenu);
230                 selectedNode = configuration.getSelectedNode();
231                 nodesUpdated(configuration.getNodes());
232
233                 /* evil hack to right-align the help menu */
234                 JPanel panel = new JPanel();
235                 panel.setOpaque(false);
236                 menuBar.add(panel);
237
238                 final JMenu helpMenu = new JMenu(I18n.getMessage("jsite.menu.help"));
239                 menuBar.add(helpMenu);
240                 helpMenu.add(aboutAction);
241
242                 I18nContainer.getInstance().registerRunnable(new Runnable() {
243
244                         @SuppressWarnings("synthetic-access")
245                         public void run() {
246                                 languageMenu.setText(I18n.getMessage("jsite.menu.languages"));
247                                 nodeMenu.setText(I18n.getMessage("jsite.menu.nodes"));
248                                 helpMenu.setText(I18n.getMessage("jsite.menu.help"));
249                                 for (Map.Entry<Locale, Action> languageActionEntry : languageActions.entrySet()) {
250                                         languageActionEntry.getValue().putValue(Action.NAME, I18n.getMessage("jsite.menu.language." + languageActionEntry.getKey().getLanguage()));
251                                 }
252                         }
253                 });
254
255                 return menuBar;
256         }
257
258         /**
259          * Initializes all pages.
260          */
261         private void initPages() {
262                 NodeManagerPage nodeManagerPage = new NodeManagerPage(wizard);
263                 nodeManagerPage.setName("page.node-manager");
264                 nodeManagerPage.addNodeManagerListener(this);
265                 nodeManagerPage.setNodes(configuration.getNodes());
266                 pages.put(PageType.PAGE_NODE_MANAGER, nodeManagerPage);
267
268                 ProjectPage projectPage = new ProjectPage(wizard);
269                 projectPage.setName("page.project");
270                 projectPage.setProjects(configuration.getProjects());
271                 projectPage.setFreenetInterface(freenetInterface);
272                 projectPage.addListSelectionListener(this);
273                 pages.put(PageType.PAGE_PROJECTS, projectPage);
274
275                 ProjectFilesPage projectFilesPage = new ProjectFilesPage(wizard);
276                 projectFilesPage.setName("page.project.files");
277                 pages.put(PageType.PAGE_PROJECT_FILES, projectFilesPage);
278
279                 ProjectInsertPage projectInsertPage = new ProjectInsertPage(wizard);
280                 projectInsertPage.setDebug(debug);
281                 projectInsertPage.setName("page.project.insert");
282                 projectInsertPage.setFreenetInterface(freenetInterface);
283                 pages.put(PageType.PAGE_INSERT_PROJECT, projectInsertPage);
284         }
285
286         /**
287          * Shows the page with the given type.
288          *
289          * @param pageType
290          *            The page type to show
291          */
292         private void showPage(PageType pageType) {
293                 wizard.setPreviousEnabled(pageType.ordinal() > 0);
294                 wizard.setNextEnabled(pageType.ordinal() < (pages.size() - 1));
295                 wizard.setPage(pages.get(pageType));
296                 wizard.setTitle(pages.get(pageType).getHeading() + " - jSite");
297         }
298
299         /**
300          * Saves the configuration.
301          *
302          * @return <code>true</code> if the configuration could be saved,
303          *         <code>false</code> otherwise
304          */
305         private boolean saveConfiguration() {
306                 NodeManagerPage nodeManagerPage = (NodeManagerPage) pages.get(PageType.PAGE_NODE_MANAGER);
307                 configuration.setNodes(nodeManagerPage.getNodes());
308                 if (selectedNode != null) {
309                         configuration.setSelectedNode(selectedNode);
310                 }
311
312                 ProjectPage projectPage = (ProjectPage) pages.get(PageType.PAGE_PROJECTS);
313                 configuration.setProjects(projectPage.getProjects());
314
315                 return configuration.save();
316         }
317
318         /**
319          * Finds a supported locale for the given locale.
320          *
321          * @param forLocale
322          *            The locale to find a supported locale for
323          * @return The supported locale that was found, or the default locale if no
324          *         supported locale could be found
325          */
326         private Locale findSupportedLocale(Locale forLocale) {
327                 for (Locale locale : SUPPORTED_LOCALES) {
328                         if (locale.equals(forLocale)) {
329                                 return locale;
330                         }
331                 }
332                 for (Locale locale : SUPPORTED_LOCALES) {
333                         if (locale.getCountry().equals(forLocale.getCountry()) && locale.getLanguage().equals(forLocale.getLanguage())) {
334                                 return locale;
335                         }
336                 }
337                 for (Locale locale : SUPPORTED_LOCALES) {
338                         if (locale.getLanguage().equals(forLocale.getLanguage())) {
339                                 return locale;
340                         }
341                 }
342                 return SUPPORTED_LOCALES[0];
343         }
344
345         //
346         // ACTIONS
347         //
348
349         /**
350          * Switches the language of the interface to the given locale.
351          *
352          * @param locale
353          *            The locale to switch to
354          */
355         private void switchLanguage(Locale locale) {
356                 Locale supportedLocale = findSupportedLocale(locale);
357                 Action languageAction = languageActions.get(supportedLocale);
358                 JRadioButtonMenuItem menuItem = (JRadioButtonMenuItem) languageAction.getValue("menuItem");
359                 menuItem.setSelected(true);
360                 I18n.setLocale(supportedLocale);
361                 for (Runnable i18nRunnable : I18nContainer.getInstance()) {
362                         try {
363                                 i18nRunnable.run();
364                         } catch (Throwable t) {
365                                 /* we probably shouldn't swallow this. */
366                         }
367                 }
368                 wizard.setPage(wizard.getPage());
369                 configuration.setLocale(supportedLocale);
370         }
371
372         //
373         // INTERFACE ListSelectionListener
374         //
375
376         /**
377          * {@inheritDoc}
378          */
379         public void valueChanged(ListSelectionEvent e) {
380                 JList list = (JList) e.getSource();
381                 int selectedRow = list.getSelectedIndex();
382                 wizard.setNextEnabled(selectedRow > -1);
383         }
384
385         //
386         // INTERFACE WizardListener
387         //
388
389         /**
390          * {@inheritDoc}
391          */
392         public void wizardNextPressed(TWizard wizard) {
393                 String pageName = wizard.getPage().getName();
394                 if ("page.node-manager".equals(pageName)) {
395                         showPage(PageType.PAGE_PROJECTS);
396                 } else if ("page.project".equals(pageName)) {
397                         ProjectPage projectPage = (ProjectPage) wizard.getPage();
398                         Project project = projectPage.getSelectedProject();
399                         if ((project.getLocalPath() == null) || (project.getLocalPath().trim().length() == 0)) {
400                                 JOptionPane.showMessageDialog(wizard, I18n.getMessage("jsite.project.warning.no-local-path"), null, JOptionPane.ERROR_MESSAGE);
401                                 return;
402                         }
403                         if ((project.getPath() == null) || (project.getPath().trim().length() == 0)) {
404                                 JOptionPane.showMessageDialog(wizard, I18n.getMessage("jsite.project.warning.no-path"), null, JOptionPane.ERROR_MESSAGE);
405                                 return;
406                         }
407                         ((ProjectFilesPage) pages.get(PageType.PAGE_PROJECT_FILES)).setProject(project);
408                         ((ProjectInsertPage) pages.get(PageType.PAGE_INSERT_PROJECT)).setProject(project);
409                         showPage(PageType.PAGE_PROJECT_FILES);
410                 } else if ("page.project.files".equals(pageName)) {
411                         ProjectPage projectPage = (ProjectPage) pages.get(PageType.PAGE_PROJECTS);
412                         Project project = projectPage.getSelectedProject();
413                         if (selectedNode == null) {
414                                 JOptionPane.showMessageDialog(wizard, I18n.getMessage("jsite.project-files.no-node-selected"), null, JOptionPane.ERROR_MESSAGE);
415                                 return;
416                         }
417                         if (project.getIndexFile() == null) {
418                                 if (JOptionPane.showConfirmDialog(wizard, I18n.getMessage("jsite.project-files.empty-index"), null, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
419                                         return;
420                                 }
421                         } else {
422                                 File indexFile = new File(project.getLocalPath(), project.getIndexFile());
423                                 if (!indexFile.exists()) {
424                                         JOptionPane.showMessageDialog(wizard, I18n.getMessage("jsite.project-files.index-missing"), null, JOptionPane.ERROR_MESSAGE);
425                                         return;
426                                 }
427                         }
428                         String indexFile = project.getIndexFile();
429                         boolean hasIndexFile = (indexFile != null);
430                         if (hasIndexFile && !project.getFileOption(indexFile).getContainer().equals("")) {
431                                 if (JOptionPane.showConfirmDialog(wizard, I18n.getMessage("jsite.project-files.container-index"), null, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
432                                         return;
433                                 }
434                         }
435                         if (hasIndexFile && !project.getFileOption(indexFile).getMimeType().equals("text/html")) {
436                                 if (JOptionPane.showConfirmDialog(wizard, I18n.getMessage("jsite.project-files.index-not-html"), null, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION) {
437                                         return;
438                                 }
439                         }
440                         Map<String, FileOption> fileOptions = project.getFileOptions();
441                         Set<Entry<String, FileOption>> fileOptionEntries = fileOptions.entrySet();
442                         for (Entry<String, FileOption> fileOptionEntry : fileOptionEntries) {
443                                 FileOption fileOption = fileOptionEntry.getValue();
444                                 if (!fileOption.isInsert() && ((fileOption.getCustomKey().length() == 0) || "CHK@".equals(fileOption.getCustomKey()))) {
445                                         JOptionPane.showMessageDialog(wizard, MessageFormat.format(I18n.getMessage("jsite.project-files.no-custom-key"), fileOptionEntry.getKey()), null, JOptionPane.ERROR_MESSAGE);
446                                         return;
447                                 }
448                         }
449                         boolean nodeRunning = false;
450                         try {
451                                 nodeRunning = freenetInterface.isNodePresent();
452                         } catch (IOException e) {
453                                 /* ignore. */
454                         }
455                         if (!nodeRunning) {
456                                 JOptionPane.showMessageDialog(wizard, I18n.getMessage("jsite.project-files.no-node-running"), null, JOptionPane.ERROR_MESSAGE);
457                                 return;
458                         }
459                         configuration.save();
460                         showPage(PageType.PAGE_INSERT_PROJECT);
461                         ((ProjectInsertPage) pages.get(PageType.PAGE_INSERT_PROJECT)).startInsert();
462                         nodeMenu.setEnabled(false);
463                 } else if ("page.project.insert".equals(pageName)) {
464                         showPage(PageType.PAGE_PROJECTS);
465                         nodeMenu.setEnabled(true);
466                 }
467         }
468
469         /**
470          * {@inheritDoc}
471          */
472         public void wizardPreviousPressed(TWizard wizard) {
473                 String pageName = wizard.getPage().getName();
474                 if ("page.project".equals(pageName)) {
475                         showPage(PageType.PAGE_NODE_MANAGER);
476                 } else if ("page.project.files".equals(pageName)) {
477                         showPage(PageType.PAGE_PROJECTS);
478                 } else if ("page.project.insert".equals(pageName)) {
479                         showPage(PageType.PAGE_PROJECT_FILES);
480                 }
481         }
482
483         /**
484          * {@inheritDoc}
485          */
486         public void wizardQuitPressed(TWizard wizard) {
487                 if (JOptionPane.showConfirmDialog(wizard, I18n.getMessage("jsite.quit.question"), null, JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
488                         if (saveConfiguration()) {
489                                 System.exit(0);
490                         }
491                         if (JOptionPane.showConfirmDialog(wizard, I18n.getMessage("jsite.quit.config-not-saved"), null, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) {
492                                 System.exit(0);
493                         }
494                 }
495         }
496
497         //
498         // INTERFACE NodeManagerListener
499         //
500
501         /**
502          * {@inheritDoc}
503          */
504         public void nodesUpdated(Node[] nodes) {
505                 nodeMenu.removeAll();
506                 ButtonGroup nodeButtonGroup = new ButtonGroup();
507                 Node newSelectedNode = null;
508                 for (Node node : nodes) {
509                         JRadioButtonMenuItem nodeMenuItem = new JRadioButtonMenuItem(node.getName());
510                         nodeMenuItem.putClientProperty("Node", node);
511                         nodeMenuItem.addActionListener(this);
512                         nodeButtonGroup.add(nodeMenuItem);
513                         if (node.equals(selectedNode)) {
514                                 newSelectedNode = node;
515                                 nodeMenuItem.setSelected(true);
516                         }
517                         nodeMenu.add(nodeMenuItem);
518                 }
519                 nodeMenu.addSeparator();
520                 nodeMenu.add(manageNodeAction);
521                 selectedNode = newSelectedNode;
522                 freenetInterface.setNode(selectedNode);
523         }
524
525         /**
526          * {@inheritDoc}
527          */
528         public void actionPerformed(ActionEvent e) {
529                 Object source = e.getSource();
530                 if (source instanceof JRadioButtonMenuItem) {
531                         JRadioButtonMenuItem menuItem = (JRadioButtonMenuItem) source;
532                         Node node = (Node) menuItem.getClientProperty("Node");
533                         selectedNode = node;
534                         freenetInterface.setNode(selectedNode);
535                 }
536         }
537
538         //
539         // MAIN METHOD
540         //
541
542         /**
543          * Main method that is called by the VM.
544          *
545          * @param args
546          *            The command-line arguments
547          */
548         public static void main(String[] args) {
549                 String configFilename = null;
550                 boolean nextIsConfigFilename = false;
551                 for (String argument : args) {
552                         if (nextIsConfigFilename) {
553                                 configFilename = argument;
554                                 nextIsConfigFilename = false;
555                         }
556                         if ("--help".equals(argument)) {
557                                 printHelp();
558                                 return;
559                         } else if ("--debug".equals(argument)) {
560                                 debug = true;
561                         } else if ("--config-file".equals(argument)) {
562                                 nextIsConfigFilename = true;
563                         }
564                 }
565                 if (nextIsConfigFilename) {
566                         System.out.println("--config-file needs parameter!");
567                         return;
568                 }
569                 new Main(configFilename);
570         }
571
572         /**
573          * Prints a small syntax help.
574          */
575         private static void printHelp() {
576                 System.out.println("--help\tshows this cruft");
577                 System.out.println("--debug\tenables some debug output");
578                 System.out.println("--config-file <file>\tuse specified configuration file");
579         }
580
581 }