Implement cancelling the insert when the “cancel” button is pressed.
[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.general.cancel"));
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                 copyURIAction.setEnabled(false);
219                 progressBar.setValue(0);
220                 progressBar.setString(I18n.getMessage("jsite.insert.starting"));
221                 progressBar.setFont(progressBar.getFont().deriveFont(Font.PLAIN));
222                 projectInserter.start();
223         }
224
225         /**
226          * Stops the currently running insert.
227          */
228         public void stopInsert() {
229                 if (running) {
230                         wizard.setNextEnabled(false);
231                         projectInserter.stop();
232                 }
233         }
234
235         /**
236          * Returns whether the insert is currently running.
237          *
238          * @return {@code true} if the insert is currently running, {@code false}
239          *         otherwise
240          */
241         public boolean isRunning() {
242                 return running;
243         }
244
245         /**
246          * Sets the project to insert.
247          *
248          * @param project
249          *            The project to insert
250          */
251         public void setProject(final Project project) {
252                 projectInserter.setProject(project);
253                 SwingUtilities.invokeLater(new Runnable() {
254
255                         @SuppressWarnings("synthetic-access")
256                         public void run() {
257                                 requestURITextField.setText(project.getFinalRequestURI(1));
258                         }
259                 });
260         }
261
262         /**
263          * Sets the freenet interface to use.
264          *
265          * @param freenetInterface
266          *            The freenet interface to use
267          */
268         public void setFreenetInterface(Freenet7Interface freenetInterface) {
269                 projectInserter.setFreenetInterface(freenetInterface);
270         }
271
272         /**
273          * Sets the project inserter’s temp directory.
274          *
275          * @see ProjectInserter#setTempDirectory(String)
276          * @param tempDirectory
277          *            The temp directory to use, or {@code null} to use the system
278          *            default
279          */
280         public void setTempDirectory(String tempDirectory) {
281                 projectInserter.setTempDirectory(tempDirectory);
282         }
283
284         /**
285          * Returns whether the “copy URI to clipboard” button was used.
286          *
287          * @return {@code true} if an URI was copied to clipboard, {@code false}
288          *         otherwise
289          */
290         public boolean wasUriCopied() {
291                 return uriCopied;
292         }
293
294         //
295         // INTERFACE InsertListener
296         //
297
298         /**
299          * {@inheritDoc}
300          */
301         public void projectInsertStarted(final Project project) {
302
303                 SwingUtilities.invokeLater(new Runnable() {
304
305                         @SuppressWarnings("synthetic-access")
306                         public void run() {
307                                 startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date()));
308                         }
309                 });
310         }
311
312         /**
313          * {@inheritDoc}
314          */
315         public void projectUploadFinished(Project project) {
316                 startTime = System.currentTimeMillis();
317         }
318
319         /**
320          * {@inheritDoc}
321          */
322         public void projectURIGenerated(Project project, final String uri) {
323                 SwingUtilities.invokeLater(new Runnable() {
324
325                         @SuppressWarnings("synthetic-access")
326                         public void run() {
327                                 copyURIAction.setEnabled(true);
328                                 requestURITextField.setText(uri);
329                         }
330                 });
331                 logger.log(Level.FINEST, "Insert generated URI: " + uri);
332                 int slash = uri.indexOf('/');
333                 slash = uri.indexOf('/', slash + 1);
334                 int secondSlash = uri.indexOf('/', slash + 1);
335                 if (secondSlash == -1) {
336                         secondSlash = uri.length();
337                 }
338                 String editionNumber = uri.substring(slash + 1, secondSlash);
339                 logger.log(Level.FINEST, "Extracted edition number: " + editionNumber);
340                 int edition = -1;
341                 try {
342                         edition = Integer.valueOf(editionNumber);
343                 } catch (NumberFormatException nfe1) {
344                         /* ignore. */
345                 }
346                 logger.log(Level.FINEST, "Insert edition: " + edition + ", Project edition: " + project.getEdition());
347                 if ((edition != -1) && (edition == project.getEdition())) {
348                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.reinserted-edition"), I18n.getMessage("jsite.insert.reinserted-edition.title"), JOptionPane.INFORMATION_MESSAGE);
349                 }
350         }
351
352         /**
353          * {@inheritDoc}
354          */
355         public void projectInsertProgress(Project project, final int succeeded, final int failed, final int fatal, final int total, final boolean finalized) {
356                 insertedBlocks = succeeded;
357                 SwingUtilities.invokeLater(new Runnable() {
358
359                         @SuppressWarnings("synthetic-access")
360                         public void run() {
361                                 progressBar.setMaximum(total);
362                                 progressBar.setValue(succeeded + failed + fatal);
363                                 int progress = (succeeded + failed + fatal) * 100 / total;
364                                 StringBuilder progressString = new StringBuilder();
365                                 progressString.append(progress).append("% (");
366                                 progressString.append(succeeded + failed + fatal).append('/').append(total);
367                                 progressString.append(") (");
368                                 progressString.append(getTransferRate());
369                                 progressString.append(' ').append(I18n.getMessage("jsite.insert.k-per-s")).append(')');
370                                 progressBar.setString(progressString.toString());
371                                 if (finalized) {
372                                         progressBar.setFont(progressBar.getFont().deriveFont(Font.BOLD));
373                                 }
374                         }
375                 });
376         }
377
378         /**
379          * {@inheritDoc}
380          */
381         public void projectInsertFinished(Project project, boolean success, Throwable cause) {
382                 running = false;
383                 if (success) {
384                         String copyURILabel = I18n.getMessage("jsite.insert.okay-copy-uri");
385                         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);
386                         if (selectedValue == 1) {
387                                 actionCopyURI();
388                         }
389                 } else {
390                         if (cause == null) {
391                                 JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-failed"), null, JOptionPane.ERROR_MESSAGE);
392                         } else {
393                                 JOptionPane.showMessageDialog(this, MessageFormat.format(I18n.getMessage("jsite.insert.insert-failed-with-cause"), cause.getMessage()), null, JOptionPane.ERROR_MESSAGE);
394                         }
395                 }
396                 SwingUtilities.invokeLater(new Runnable() {
397
398                         @SuppressWarnings("synthetic-access")
399                         public void run() {
400                                 progressBar.setValue(progressBar.getMaximum());
401                                 progressBar.setString(I18n.getMessage("jsite.insert.done") + " (" + getTransferRate() + " " + I18n.getMessage("jsite.insert.k-per-s") + ")");
402                                 wizard.setNextName(I18n.getMessage("jsite.wizard.next"));
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 }