86305aa0604339ca59b8b9f7fed9e22c5f186b5a
[jSite.git] / src / de / todesbaum / jsite / gui / ProjectInsertPage.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.gui;
21
22 import java.awt.BorderLayout;
23 import java.awt.Font;
24 import java.awt.GridBagConstraints;
25 import java.awt.GridBagLayout;
26 import java.awt.Insets;
27 import java.awt.Toolkit;
28 import java.awt.datatransfer.Clipboard;
29 import java.awt.datatransfer.ClipboardOwner;
30 import java.awt.datatransfer.StringSelection;
31 import java.awt.datatransfer.Transferable;
32 import java.awt.event.ActionEvent;
33 import java.awt.event.KeyEvent;
34 import java.text.DateFormat;
35 import java.text.MessageFormat;
36 import java.util.Date;
37 import java.util.logging.Level;
38 import java.util.logging.Logger;
39
40 import javax.swing.AbstractAction;
41 import javax.swing.Action;
42 import javax.swing.JButton;
43 import javax.swing.JComponent;
44 import javax.swing.JLabel;
45 import javax.swing.JOptionPane;
46 import javax.swing.JPanel;
47 import javax.swing.JProgressBar;
48 import javax.swing.JTextField;
49 import javax.swing.SwingUtilities;
50
51 import de.todesbaum.jsite.application.Freenet7Interface;
52 import de.todesbaum.jsite.application.InsertListener;
53 import de.todesbaum.jsite.application.Project;
54 import de.todesbaum.jsite.application.ProjectInserter;
55 import de.todesbaum.jsite.i18n.I18n;
56 import de.todesbaum.jsite.i18n.I18nContainer;
57 import de.todesbaum.util.swing.TWizard;
58 import de.todesbaum.util.swing.TWizardPage;
59
60 /**
61  * Wizard page that shows the progress of an insert.
62  *
63  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
64  */
65 public class ProjectInsertPage extends TWizardPage implements InsertListener, ClipboardOwner {
66
67         /** The logger. */
68         private static final Logger logger = Logger.getLogger(ProjectInsertPage.class.getName());
69
70         /** The project inserter. */
71         private ProjectInserter projectInserter;
72
73         /** The “copy URI” action. */
74         private Action copyURIAction;
75
76         /** The “request URI” textfield. */
77         private JTextField requestURITextField;
78
79         /** The “start time” label. */
80         private JLabel startTimeLabel;
81
82         /** The progress bar. */
83         private JProgressBar progressBar;
84
85         /** The start time of the insert. */
86         private long startTime = 0;
87
88         /** The number of inserted blocks. */
89         private volatile int insertedBlocks;
90
91         /** Whether the “copy URI to clipboard” button was used. */
92         private boolean uriCopied;
93
94         /** Whether the insert is currently running. */
95         private volatile boolean running = false;
96
97         /**
98          * Creates a new progress insert wizard page.
99          *
100          * @param wizard
101          *            The wizard this page belongs to
102          */
103         public ProjectInsertPage(final TWizard wizard) {
104                 super(wizard);
105                 createActions();
106                 pageInit();
107                 setHeading(I18n.getMessage("jsite.insert.heading"));
108                 setDescription(I18n.getMessage("jsite.insert.description"));
109                 I18nContainer.getInstance().registerRunnable(new Runnable() {
110
111                         public void run() {
112                                 setHeading(I18n.getMessage("jsite.insert.heading"));
113                                 setDescription(I18n.getMessage("jsite.insert.description"));
114                         }
115                 });
116                 projectInserter = new ProjectInserter();
117                 projectInserter.addInsertListener(this);
118         }
119
120         /**
121          * Creates all used actions.
122          */
123         private void createActions() {
124                 copyURIAction = new AbstractAction(I18n.getMessage("jsite.project.action.copy-uri")) {
125
126                         @SuppressWarnings("synthetic-access")
127                         public void actionPerformed(ActionEvent actionEvent) {
128                                 actionCopyURI();
129                         }
130                 };
131                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
132                 copyURIAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_U);
133                 copyURIAction.setEnabled(false);
134
135                 I18nContainer.getInstance().registerRunnable(new Runnable() {
136
137                         @SuppressWarnings("synthetic-access")
138                         public void run() {
139                                 copyURIAction.putValue(Action.NAME, I18n.getMessage("jsite.project.action.copy-uri"));
140                                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
141                         }
142                 });
143         }
144
145         /**
146          * Initializes the page.
147          */
148         private void pageInit() {
149                 setLayout(new BorderLayout(12, 12));
150                 add(createProjectInsertPanel(), BorderLayout.CENTER);
151         }
152
153         /**
154          * Creates the main panel.
155          *
156          * @return The main panel
157          */
158         private JComponent createProjectInsertPanel() {
159                 JComponent projectInsertPanel = new JPanel(new GridBagLayout());
160
161                 requestURITextField = new JTextField();
162                 requestURITextField.setEditable(false);
163
164                 startTimeLabel = new JLabel();
165
166                 progressBar = new JProgressBar(0, 1);
167                 progressBar.setStringPainted(true);
168                 progressBar.setValue(0);
169
170                 final JLabel projectInformationLabel = new JLabel("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
171                 projectInsertPanel.add(projectInformationLabel, new GridBagConstraints(0, 0, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
172                 final JLabel requestURILabel = new JLabel(I18n.getMessage("jsite.insert.request-uri") + ":");
173                 projectInsertPanel.add(requestURILabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(6, 18, 0, 0), 0, 0));
174                 projectInsertPanel.add(requestURITextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
175                 final JLabel startTimeLeftLabel = new JLabel(I18n.getMessage("jsite.insert.start-time") + ":");
176                 projectInsertPanel.add(startTimeLeftLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(6, 18, 0, 0), 0, 0));
177                 projectInsertPanel.add(startTimeLabel, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
178                 final JLabel progressLabel = new JLabel(I18n.getMessage("jsite.insert.progress") + ":");
179                 projectInsertPanel.add(progressLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(6, 18, 0, 0), 0, 0));
180                 projectInsertPanel.add(progressBar, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
181                 projectInsertPanel.add(new JButton(copyURIAction), new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.NONE, new Insets(12, 18, 0, 0), 0, 0));
182
183                 I18nContainer.getInstance().registerRunnable(new Runnable() {
184
185                         @SuppressWarnings("synthetic-access")
186                         public void run() {
187                                 projectInformationLabel.setText("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
188                                 requestURILabel.setText(I18n.getMessage("jsite.insert.request-uri") + ":");
189                                 startTimeLeftLabel.setText(I18n.getMessage("jsite.insert.start-time") + ":");
190                                 if (startTime != 0) {
191                                         startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date(startTime)));
192                                 } else {
193                                         startTimeLabel.setText("");
194                                 }
195                                 progressLabel.setText(I18n.getMessage("jsite.insert.progress") + ":");
196                         }
197                 });
198
199                 return projectInsertPanel;
200         }
201
202         /**
203          * {@inheritDoc}
204          */
205         @Override
206         public void pageAdded(TWizard wizard) {
207                 this.wizard.setPreviousName(I18n.getMessage("jsite.wizard.previous"));
208                 this.wizard.setPreviousEnabled(false);
209                 this.wizard.setNextName(I18n.getMessage("jsite.wizard.next"));
210                 this.wizard.setQuitName(I18n.getMessage("jsite.wizard.quit"));
211         }
212
213         /**
214          * Starts the insert.
215          */
216         public void startInsert() {
217                 running = true;
218                 wizard.setNextEnabled(false);
219                 copyURIAction.setEnabled(false);
220                 progressBar.setValue(0);
221                 progressBar.setString(I18n.getMessage("jsite.insert.starting"));
222                 progressBar.setFont(progressBar.getFont().deriveFont(Font.PLAIN));
223                 projectInserter.start();
224         }
225
226         /**
227          * Stops the currently running insert.
228          */
229         public void stopInsert() {
230                 if (running) {
231                         wizard.setNextEnabled(false);
232                         projectInserter.stop();
233                 }
234         }
235
236         /**
237          * Returns whether the insert is currently running.
238          *
239          * @return {@code true} if the insert is currently running, {@code false}
240          *         otherwise
241          */
242         public boolean isRunning() {
243                 return running;
244         }
245
246         /**
247          * Sets the project to insert.
248          *
249          * @param project
250          *            The project to insert
251          */
252         public void setProject(final Project project) {
253                 projectInserter.setProject(project);
254                 SwingUtilities.invokeLater(new Runnable() {
255
256                         @SuppressWarnings("synthetic-access")
257                         public void run() {
258                                 requestURITextField.setText(project.getFinalRequestURI(1));
259                         }
260                 });
261         }
262
263         /**
264          * Sets the freenet interface to use.
265          *
266          * @param freenetInterface
267          *            The freenet interface to use
268          */
269         public void setFreenetInterface(Freenet7Interface freenetInterface) {
270                 projectInserter.setFreenetInterface(freenetInterface);
271         }
272
273         /**
274          * Sets the project inserter’s temp directory.
275          *
276          * @see ProjectInserter#setTempDirectory(String)
277          * @param tempDirectory
278          *            The temp directory to use, or {@code null} to use the system
279          *            default
280          */
281         public void setTempDirectory(String tempDirectory) {
282                 projectInserter.setTempDirectory(tempDirectory);
283         }
284
285         /**
286          * Returns whether the “copy URI to clipboard” button was used.
287          *
288          * @return {@code true} if an URI was copied to clipboard, {@code false}
289          *         otherwise
290          */
291         public boolean wasUriCopied() {
292                 return uriCopied;
293         }
294
295         //
296         // INTERFACE InsertListener
297         //
298
299         /**
300          * {@inheritDoc}
301          */
302         public void projectInsertStarted(final Project project) {
303
304                 SwingUtilities.invokeLater(new Runnable() {
305
306                         @SuppressWarnings("synthetic-access")
307                         public void run() {
308                                 startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date()));
309                         }
310                 });
311         }
312
313         /**
314          * {@inheritDoc}
315          */
316         public void projectUploadFinished(Project project) {
317                 startTime = System.currentTimeMillis();
318         }
319
320         /**
321          * {@inheritDoc}
322          */
323         public void projectURIGenerated(Project project, final String uri) {
324                 SwingUtilities.invokeLater(new Runnable() {
325
326                         @SuppressWarnings("synthetic-access")
327                         public void run() {
328                                 copyURIAction.setEnabled(true);
329                                 requestURITextField.setText(uri);
330                         }
331                 });
332                 logger.log(Level.FINEST, "Insert generated URI: " + uri);
333                 int slash = uri.indexOf('/');
334                 slash = uri.indexOf('/', slash + 1);
335                 int secondSlash = uri.indexOf('/', slash + 1);
336                 if (secondSlash == -1) {
337                         secondSlash = uri.length();
338                 }
339                 String editionNumber = uri.substring(slash + 1, secondSlash);
340                 logger.log(Level.FINEST, "Extracted edition number: " + editionNumber);
341                 int edition = -1;
342                 try {
343                         edition = Integer.valueOf(editionNumber);
344                 } catch (NumberFormatException nfe1) {
345                         /* ignore. */
346                 }
347                 logger.log(Level.FINEST, "Insert edition: " + edition + ", Project edition: " + project.getEdition());
348                 if ((edition != -1) && (edition == project.getEdition())) {
349                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.reinserted-edition"), I18n.getMessage("jsite.insert.reinserted-edition.title"), JOptionPane.INFORMATION_MESSAGE);
350                 }
351         }
352
353         /**
354          * {@inheritDoc}
355          */
356         public void projectInsertProgress(Project project, final int succeeded, final int failed, final int fatal, final int total, final boolean finalized) {
357                 insertedBlocks = succeeded;
358                 SwingUtilities.invokeLater(new Runnable() {
359
360                         @SuppressWarnings("synthetic-access")
361                         public void run() {
362                                 progressBar.setMaximum(total);
363                                 progressBar.setValue(succeeded + failed + fatal);
364                                 int progress = (succeeded + failed + fatal) * 100 / total;
365                                 StringBuilder progressString = new StringBuilder();
366                                 progressString.append(progress).append("% (");
367                                 progressString.append(succeeded + failed + fatal).append('/').append(total);
368                                 progressString.append(") (");
369                                 progressString.append(getTransferRate());
370                                 progressString.append(' ').append(I18n.getMessage("jsite.insert.k-per-s")).append(')');
371                                 progressBar.setString(progressString.toString());
372                                 if (finalized) {
373                                         progressBar.setFont(progressBar.getFont().deriveFont(Font.BOLD));
374                                 }
375                         }
376                 });
377         }
378
379         /**
380          * {@inheritDoc}
381          */
382         public void projectInsertFinished(Project project, boolean success, Throwable cause) {
383                 running = false;
384                 if (success) {
385                         String copyURILabel = I18n.getMessage("jsite.insert.okay-copy-uri");
386                         int selectedValue = JOptionPane.showOptionDialog(this, I18n.getMessage("jsite.insert.inserted"), I18n.getMessage("jsite.insert.done.title"), 0, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { I18n.getMessage("jsite.general.ok"), copyURILabel }, copyURILabel);
387                         if (selectedValue == 1) {
388                                 actionCopyURI();
389                         }
390                 } else {
391                         if (cause == null) {
392                                 JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-failed"), null, JOptionPane.ERROR_MESSAGE);
393                         } else {
394                                 JOptionPane.showMessageDialog(this, MessageFormat.format(I18n.getMessage("jsite.insert.insert-failed-with-cause"), cause.getMessage()), null, JOptionPane.ERROR_MESSAGE);
395                         }
396                 }
397                 SwingUtilities.invokeLater(new Runnable() {
398
399                         @SuppressWarnings("synthetic-access")
400                         public void run() {
401                                 progressBar.setValue(progressBar.getMaximum());
402                                 progressBar.setString(I18n.getMessage("jsite.insert.done") + " (" + getTransferRate() + " " + I18n.getMessage("jsite.insert.k-per-s") + ")");
403                                 wizard.setNextEnabled(true);
404                                 wizard.setQuitEnabled(true);
405                         }
406                 });
407         }
408
409         //
410         // ACTIONS
411         //
412
413         /**
414          * Copies the request URI of the project to the clipboard.
415          */
416         private void actionCopyURI() {
417                 uriCopied = true;
418                 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
419                 clipboard.setContents(new StringSelection(requestURITextField.getText()), this);
420         }
421
422         /**
423          * Formats the given number so that it always has the the given number of
424          * fractional digits.
425          *
426          * @param number
427          *            The number to format
428          * @param digits
429          *            The number of fractional digits
430          * @return The formatted number
431          */
432         private String formatNumber(double number, int digits) {
433                 int multiplier = (int) Math.pow(10, digits);
434                 String formattedNumber = String.valueOf((int) (number * multiplier) / (double) multiplier);
435                 if (formattedNumber.indexOf('.') == -1) {
436                         formattedNumber += '.';
437                         for (int digit = 0; digit < digits; digit++) {
438                                 formattedNumber += "0";
439                         }
440                 }
441                 return formattedNumber;
442         }
443
444         /**
445          * Returns the formatted transfer rate at this point.
446          *
447          * @return The formatted transfer rate
448          */
449         private String getTransferRate() {
450                 return formatNumber(insertedBlocks * 32.0 / ((System.currentTimeMillis() - startTime) / 1000), 1);
451         }
452
453         //
454         // INTERFACE ClipboardOwner
455         //
456
457         /**
458          * {@inheritDoc}
459          */
460         public void lostOwnership(Clipboard clipboard, Transferable contents) {
461                 /* ignore. */
462         }
463
464 }