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