Forward manifest putter to project inserter.
[jSite.git] / src / de / todesbaum / jsite / gui / ProjectInsertPage.java
1 /*
2  * jSite - ProjectInsertPage.java - Copyright © 2006–2012 David Roden
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 package de.todesbaum.jsite.gui;
20
21 import java.awt.BorderLayout;
22 import java.awt.Font;
23 import java.awt.GridBagConstraints;
24 import java.awt.GridBagLayout;
25 import java.awt.Insets;
26 import java.awt.Toolkit;
27 import java.awt.datatransfer.Clipboard;
28 import java.awt.datatransfer.ClipboardOwner;
29 import java.awt.datatransfer.StringSelection;
30 import java.awt.datatransfer.Transferable;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.KeyEvent;
33 import java.text.DateFormat;
34 import java.text.MessageFormat;
35 import java.util.Date;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38
39 import javax.swing.AbstractAction;
40 import javax.swing.Action;
41 import javax.swing.JButton;
42 import javax.swing.JComponent;
43 import javax.swing.JLabel;
44 import javax.swing.JOptionPane;
45 import javax.swing.JPanel;
46 import javax.swing.JProgressBar;
47 import javax.swing.JTextField;
48 import javax.swing.SwingUtilities;
49
50 import de.todesbaum.jsite.application.AbortedException;
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.freenet.fcp2.ClientPutDir.ManifestPutter;
58 import de.todesbaum.util.freenet.fcp2.PriorityClass;
59 import de.todesbaum.util.io.StreamCopier.ProgressListener;
60 import de.todesbaum.util.swing.TWizard;
61 import de.todesbaum.util.swing.TWizardPage;
62
63 /**
64  * Wizard page that shows the progress of an insert.
65  *
66  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
67  */
68 public class ProjectInsertPage extends TWizardPage implements InsertListener, ClipboardOwner {
69
70         /** The logger. */
71         private static final Logger logger = Logger.getLogger(ProjectInsertPage.class.getName());
72
73         /** The project inserter. */
74         private ProjectInserter projectInserter;
75
76         /** The “copy URI” action. */
77         private Action copyURIAction;
78
79         /** The “request URI” textfield. */
80         private JTextField requestURITextField;
81
82         /** The “start time” label. */
83         private JLabel startTimeLabel;
84
85         /** The progress bar. */
86         private JProgressBar progressBar;
87
88         /** The start time of the insert. */
89         private long startTime = 0;
90
91         /** The number of inserted blocks. */
92         private volatile int insertedBlocks;
93
94         /** Whether the “copy URI to clipboard” button was used. */
95         private boolean uriCopied;
96
97         /** Whether the insert is currently running. */
98         private volatile boolean running = false;
99
100         /**
101          * Creates a new progress insert wizard page.
102          *
103          * @param wizard
104          *            The wizard this page belongs to
105          */
106         public ProjectInsertPage(final TWizard wizard) {
107                 super(wizard);
108                 createActions();
109                 pageInit();
110                 setHeading(I18n.getMessage("jsite.insert.heading"));
111                 setDescription(I18n.getMessage("jsite.insert.description"));
112                 I18nContainer.getInstance().registerRunnable(new Runnable() {
113
114                         public void run() {
115                                 setHeading(I18n.getMessage("jsite.insert.heading"));
116                                 setDescription(I18n.getMessage("jsite.insert.description"));
117                         }
118                 });
119                 projectInserter = new ProjectInserter();
120                 projectInserter.addInsertListener(this);
121         }
122
123         /**
124          * Creates all used actions.
125          */
126         private void createActions() {
127                 copyURIAction = new AbstractAction(I18n.getMessage("jsite.project.action.copy-uri")) {
128
129                         @SuppressWarnings("synthetic-access")
130                         public void actionPerformed(ActionEvent actionEvent) {
131                                 actionCopyURI();
132                         }
133                 };
134                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
135                 copyURIAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_U);
136                 copyURIAction.setEnabled(false);
137
138                 I18nContainer.getInstance().registerRunnable(new Runnable() {
139
140                         @SuppressWarnings("synthetic-access")
141                         public void run() {
142                                 copyURIAction.putValue(Action.NAME, I18n.getMessage("jsite.project.action.copy-uri"));
143                                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
144                         }
145                 });
146         }
147
148         /**
149          * Initializes the page.
150          */
151         private void pageInit() {
152                 setLayout(new BorderLayout(12, 12));
153                 add(createProjectInsertPanel(), BorderLayout.CENTER);
154         }
155
156         /**
157          * Creates the main panel.
158          *
159          * @return The main panel
160          */
161         private JComponent createProjectInsertPanel() {
162                 JComponent projectInsertPanel = new JPanel(new GridBagLayout());
163
164                 requestURITextField = new JTextField();
165                 requestURITextField.setEditable(false);
166
167                 startTimeLabel = new JLabel();
168
169                 progressBar = new JProgressBar(0, 1);
170                 progressBar.setStringPainted(true);
171                 progressBar.setValue(0);
172
173                 final JLabel projectInformationLabel = new JLabel("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
174                 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));
175                 final JLabel requestURILabel = new JLabel(I18n.getMessage("jsite.insert.request-uri") + ":");
176                 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));
177                 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));
178                 final JLabel startTimeLeftLabel = new JLabel(I18n.getMessage("jsite.insert.start-time") + ":");
179                 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));
180                 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));
181                 final JLabel progressLabel = new JLabel(I18n.getMessage("jsite.insert.progress") + ":");
182                 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));
183                 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));
184                 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));
185
186                 I18nContainer.getInstance().registerRunnable(new Runnable() {
187
188                         @SuppressWarnings("synthetic-access")
189                         public void run() {
190                                 projectInformationLabel.setText("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
191                                 requestURILabel.setText(I18n.getMessage("jsite.insert.request-uri") + ":");
192                                 startTimeLeftLabel.setText(I18n.getMessage("jsite.insert.start-time") + ":");
193                                 if (startTime != 0) {
194                                         startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date(startTime)));
195                                 } else {
196                                         startTimeLabel.setText("");
197                                 }
198                                 progressLabel.setText(I18n.getMessage("jsite.insert.progress") + ":");
199                         }
200                 });
201
202                 return projectInsertPanel;
203         }
204
205         /**
206          * {@inheritDoc}
207          */
208         @Override
209         public void pageAdded(TWizard wizard) {
210                 this.wizard.setPreviousName(I18n.getMessage("jsite.wizard.previous"));
211                 this.wizard.setPreviousEnabled(false);
212                 this.wizard.setNextName(I18n.getMessage("jsite.general.cancel"));
213                 this.wizard.setQuitName(I18n.getMessage("jsite.wizard.quit"));
214         }
215
216         /**
217          * Starts the insert.
218          */
219         public void startInsert() {
220                 running = true;
221                 copyURIAction.setEnabled(false);
222                 progressBar.setValue(0);
223                 progressBar.setString(I18n.getMessage("jsite.insert.starting"));
224                 progressBar.setFont(progressBar.getFont().deriveFont(Font.PLAIN));
225                 projectInserter.start(new ProgressListener() {
226
227                         public void onProgress(final long copied, final long length) {
228                                 SwingUtilities.invokeLater(new Runnable() {
229
230                                         /**
231                                          * {@inheritDoc}
232                                          */
233                                         @SuppressWarnings("synthetic-access")
234                                         public void run() {
235                                                 int divisor = 1;
236                                                 while (((copied / divisor) > Integer.MAX_VALUE) || ((length / divisor) > Integer.MAX_VALUE)) {
237                                                         divisor *= 10;
238                                                 }
239                                                 progressBar.setMaximum((int) (length / divisor));
240                                                 progressBar.setValue((int) (copied / divisor));
241                                                 progressBar.setString("Uploaded: " + copied + " / " + length);
242                                         }
243                                 });
244                         }
245                 });
246         }
247
248         /**
249          * Stops the currently running insert.
250          */
251         public void stopInsert() {
252                 if (running) {
253                         wizard.setNextEnabled(false);
254                         projectInserter.stop();
255                 }
256         }
257
258         /**
259          * Returns whether the insert is currently running.
260          *
261          * @return {@code true} if the insert is currently running, {@code false}
262          *         otherwise
263          */
264         public boolean isRunning() {
265                 return running;
266         }
267
268         /**
269          * Sets the project to insert.
270          *
271          * @param project
272          *            The project to insert
273          */
274         public void setProject(final Project project) {
275                 projectInserter.setProject(project);
276                 SwingUtilities.invokeLater(new Runnable() {
277
278                         @SuppressWarnings("synthetic-access")
279                         public void run() {
280                                 requestURITextField.setText(project.getFinalRequestURI(1));
281                         }
282                 });
283         }
284
285         /**
286          * Sets the freenet interface to use.
287          *
288          * @param freenetInterface
289          *            The freenet interface to use
290          */
291         public void setFreenetInterface(Freenet7Interface freenetInterface) {
292                 projectInserter.setFreenetInterface(freenetInterface);
293         }
294
295         /**
296          * Sets the project inserter’s temp directory.
297          *
298          * @see ProjectInserter#setTempDirectory(String)
299          * @param tempDirectory
300          *            The temp directory to use, or {@code null} to use the system
301          *            default
302          */
303         public void setTempDirectory(String tempDirectory) {
304                 projectInserter.setTempDirectory(tempDirectory);
305         }
306
307         /**
308          * Returns whether the “copy URI to clipboard” button was used.
309          *
310          * @return {@code true} if an URI was copied to clipboard, {@code false}
311          *         otherwise
312          */
313         public boolean wasUriCopied() {
314                 return uriCopied;
315         }
316
317         /**
318          * Sets whether to use the “early encode“ flag for the insert.
319          *
320          * @param useEarlyEncode
321          *            {@code true} to set the “early encode” flag for the insert,
322          *            {@code false} otherwise
323          */
324         public void setUseEarlyEncode(boolean useEarlyEncode) {
325                 projectInserter.setUseEarlyEncode(useEarlyEncode);
326         }
327
328         /**
329          * Sets the insert priority.
330          *
331          * @param priority
332          *            The insert priority
333          */
334         public void setPriority(PriorityClass priority) {
335                 projectInserter.setPriority(priority);
336         }
337
338         /**
339          * Sets the manifest putter to use for the insert.
340          *
341          * @see ProjectInserter#setManifestPutter(ManifestPutter)
342          * @param manifestPutter
343          *            The manifest putter
344          */
345         public void setManifestPutter(ManifestPutter manifestPutter) {
346                 projectInserter.setManifestPutter(manifestPutter);
347         }
348
349         //
350         // INTERFACE InsertListener
351         //
352
353         /**
354          * {@inheritDoc}
355          */
356         public void projectInsertStarted(final Project project) {
357
358                 SwingUtilities.invokeLater(new Runnable() {
359
360                         @SuppressWarnings("synthetic-access")
361                         public void run() {
362                                 startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date()));
363                         }
364                 });
365         }
366
367         /**
368          * {@inheritDoc}
369          */
370         public void projectUploadFinished(Project project) {
371                 startTime = System.currentTimeMillis();
372                 SwingUtilities.invokeLater(new Runnable() {
373
374                         @SuppressWarnings("synthetic-access")
375                         public void run() {
376                                 progressBar.setString(I18n.getMessage("jsite.insert.starting"));
377                                 progressBar.setValue(0);
378                         }
379                 });
380         }
381
382         /**
383          * {@inheritDoc}
384          */
385         public void projectURIGenerated(Project project, final String uri) {
386                 SwingUtilities.invokeLater(new Runnable() {
387
388                         @SuppressWarnings("synthetic-access")
389                         public void run() {
390                                 copyURIAction.setEnabled(true);
391                                 requestURITextField.setText(uri);
392                         }
393                 });
394                 logger.log(Level.FINEST, "Insert generated URI: " + uri);
395                 int slash = uri.indexOf('/');
396                 slash = uri.indexOf('/', slash + 1);
397                 int secondSlash = uri.indexOf('/', slash + 1);
398                 if (secondSlash == -1) {
399                         secondSlash = uri.length();
400                 }
401                 String editionNumber = uri.substring(slash + 1, secondSlash);
402                 logger.log(Level.FINEST, "Extracted edition number: " + editionNumber);
403                 int edition = -1;
404                 try {
405                         edition = Integer.valueOf(editionNumber);
406                 } catch (NumberFormatException nfe1) {
407                         /* ignore. */
408                 }
409                 logger.log(Level.FINEST, "Insert edition: " + edition + ", Project edition: " + project.getEdition());
410                 if ((edition != -1) && (edition == project.getEdition())) {
411                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.reinserted-edition"), I18n.getMessage("jsite.insert.reinserted-edition.title"), JOptionPane.INFORMATION_MESSAGE);
412                 }
413         }
414
415         /**
416          * {@inheritDoc}
417          */
418         public void projectInsertProgress(Project project, final int succeeded, final int failed, final int fatal, final int total, final boolean finalized) {
419                 insertedBlocks = succeeded;
420                 SwingUtilities.invokeLater(new Runnable() {
421
422                         @SuppressWarnings("synthetic-access")
423                         public void run() {
424                                 if (total == 0) {
425                                         return;
426                                 }
427                                 progressBar.setMaximum(total);
428                                 progressBar.setValue(succeeded + failed + fatal);
429                                 int progress = (succeeded + failed + fatal) * 100 / total;
430                                 StringBuilder progressString = new StringBuilder();
431                                 progressString.append(progress).append("% (");
432                                 progressString.append(succeeded + failed + fatal).append('/').append(total);
433                                 progressString.append(") (");
434                                 progressString.append(getTransferRate());
435                                 progressString.append(' ').append(I18n.getMessage("jsite.insert.k-per-s")).append(')');
436                                 progressBar.setString(progressString.toString());
437                                 if (finalized) {
438                                         progressBar.setFont(progressBar.getFont().deriveFont(Font.BOLD));
439                                 }
440                         }
441                 });
442         }
443
444         /**
445          * {@inheritDoc}
446          */
447         public void projectInsertFinished(Project project, boolean success, Throwable cause) {
448                 running = false;
449                 if (success) {
450                         String copyURILabel = I18n.getMessage("jsite.insert.okay-copy-uri");
451                         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);
452                         if (selectedValue == 1) {
453                                 actionCopyURI();
454                         }
455                 } else {
456                         if (cause == null) {
457                                 JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-failed"), I18n.getMessage("jsite.insert.insert-failed.title"), JOptionPane.ERROR_MESSAGE);
458                         } else {
459                                 if (cause instanceof AbortedException) {
460                                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-aborted"), I18n.getMessage("jsite.insert.insert-aborted.title"), JOptionPane.INFORMATION_MESSAGE);
461                                 } else {
462                                         JOptionPane.showMessageDialog(this, MessageFormat.format(I18n.getMessage("jsite.insert.insert-failed-with-cause"), cause.getMessage()), I18n.getMessage("jsite.insert.insert-failed.title"), JOptionPane.ERROR_MESSAGE);
463                                 }
464                         }
465                 }
466                 SwingUtilities.invokeLater(new Runnable() {
467
468                         @SuppressWarnings("synthetic-access")
469                         public void run() {
470                                 progressBar.setValue(progressBar.getMaximum());
471                                 progressBar.setString(I18n.getMessage("jsite.insert.done") + " (" + getTransferRate() + " " + I18n.getMessage("jsite.insert.k-per-s") + ")");
472                                 wizard.setNextName(I18n.getMessage("jsite.wizard.next"));
473                                 wizard.setNextEnabled(true);
474                                 wizard.setQuitEnabled(true);
475                         }
476                 });
477         }
478
479         //
480         // ACTIONS
481         //
482
483         /**
484          * Copies the request URI of the project to the clipboard.
485          */
486         private void actionCopyURI() {
487                 uriCopied = true;
488                 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
489                 clipboard.setContents(new StringSelection(requestURITextField.getText()), this);
490         }
491
492         /**
493          * Formats the given number so that it always has the the given number of
494          * fractional digits.
495          *
496          * @param number
497          *            The number to format
498          * @param digits
499          *            The number of fractional digits
500          * @return The formatted number
501          */
502         private String formatNumber(double number, int digits) {
503                 int multiplier = (int) Math.pow(10, digits);
504                 String formattedNumber = String.valueOf((int) (number * multiplier) / (double) multiplier);
505                 if (formattedNumber.indexOf('.') == -1) {
506                         formattedNumber += '.';
507                         for (int digit = 0; digit < digits; digit++) {
508                                 formattedNumber += "0";
509                         }
510                 }
511                 return formattedNumber;
512         }
513
514         /**
515          * Returns the formatted transfer rate at this point.
516          *
517          * @return The formatted transfer rate
518          */
519         private String getTransferRate() {
520                 return formatNumber(insertedBlocks * 32.0 / ((System.currentTimeMillis() - startTime) / 1000), 1);
521         }
522
523         //
524         // INTERFACE ClipboardOwner
525         //
526
527         /**
528          * {@inheritDoc}
529          */
530         public void lostOwnership(Clipboard clipboard, Transferable contents) {
531                 /* ignore. */
532         }
533
534 }