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