2e9286eca9f4e3f6bf5b0c9d0f8775026762f1b1
[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.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();
224         }
225
226         /**
227          * Stops the currently running insert.
228          */
229         public void stopInsert() {
230                 if (running) {
231                         wizard.setNextEnabled(false);
232                         projectInserter.stop();
233                 }
234         }
235
236         /**
237          * Returns whether the insert is currently running.
238          *
239          * @return {@code true} if the insert is currently running, {@code false}
240          *         otherwise
241          */
242         public boolean isRunning() {
243                 return running;
244         }
245
246         /**
247          * Sets the project to insert.
248          *
249          * @param project
250          *            The project to insert
251          */
252         public void setProject(final Project project) {
253                 projectInserter.setProject(project);
254                 SwingUtilities.invokeLater(new Runnable() {
255
256                         @SuppressWarnings("synthetic-access")
257                         public void run() {
258                                 requestURITextField.setText(project.getFinalRequestURI(1));
259                         }
260                 });
261         }
262
263         /**
264          * Sets the freenet interface to use.
265          *
266          * @param freenetInterface
267          *            The freenet interface to use
268          */
269         public void setFreenetInterface(Freenet7Interface freenetInterface) {
270                 projectInserter.setFreenetInterface(freenetInterface);
271         }
272
273         /**
274          * Sets the project inserter’s temp directory.
275          *
276          * @see ProjectInserter#setTempDirectory(String)
277          * @param tempDirectory
278          *            The temp directory to use, or {@code null} to use the system
279          *            default
280          */
281         public void setTempDirectory(String tempDirectory) {
282                 projectInserter.setTempDirectory(tempDirectory);
283         }
284
285         /**
286          * Returns whether the “copy URI to clipboard” button was used.
287          *
288          * @return {@code true} if an URI was copied to clipboard, {@code false}
289          *         otherwise
290          */
291         public boolean wasUriCopied() {
292                 return uriCopied;
293         }
294
295         //
296         // INTERFACE InsertListener
297         //
298
299         /**
300          * {@inheritDoc}
301          */
302         public void projectInsertStarted(final Project project) {
303
304                 SwingUtilities.invokeLater(new Runnable() {
305
306                         @SuppressWarnings("synthetic-access")
307                         public void run() {
308                                 startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date()));
309                         }
310                 });
311         }
312
313         /**
314          * {@inheritDoc}
315          */
316         public void projectUploadFinished(Project project) {
317                 startTime = System.currentTimeMillis();
318         }
319
320         /**
321          * {@inheritDoc}
322          */
323         public void projectURIGenerated(Project project, final String uri) {
324                 SwingUtilities.invokeLater(new Runnable() {
325
326                         @SuppressWarnings("synthetic-access")
327                         public void run() {
328                                 copyURIAction.setEnabled(true);
329                                 requestURITextField.setText(uri);
330                         }
331                 });
332                 logger.log(Level.FINEST, "Insert generated URI: " + uri);
333                 int slash = uri.indexOf('/');
334                 slash = uri.indexOf('/', slash + 1);
335                 int secondSlash = uri.indexOf('/', slash + 1);
336                 if (secondSlash == -1) {
337                         secondSlash = uri.length();
338                 }
339                 String editionNumber = uri.substring(slash + 1, secondSlash);
340                 logger.log(Level.FINEST, "Extracted edition number: " + editionNumber);
341                 int edition = -1;
342                 try {
343                         edition = Integer.valueOf(editionNumber);
344                 } catch (NumberFormatException nfe1) {
345                         /* ignore. */
346                 }
347                 logger.log(Level.FINEST, "Insert edition: " + edition + ", Project edition: " + project.getEdition());
348                 if ((edition != -1) && (edition == project.getEdition())) {
349                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.reinserted-edition"), I18n.getMessage("jsite.insert.reinserted-edition.title"), JOptionPane.INFORMATION_MESSAGE);
350                 }
351         }
352
353         /**
354          * {@inheritDoc}
355          */
356         public void projectInsertProgress(Project project, final int succeeded, final int failed, final int fatal, final int total, final boolean finalized) {
357                 insertedBlocks = succeeded;
358                 SwingUtilities.invokeLater(new Runnable() {
359
360                         @SuppressWarnings("synthetic-access")
361                         public void run() {
362                                 progressBar.setMaximum(total);
363                                 progressBar.setValue(succeeded + failed + fatal);
364                                 int progress = (succeeded + failed + fatal) * 100 / total;
365                                 StringBuilder progressString = new StringBuilder();
366                                 progressString.append(progress).append("% (");
367                                 progressString.append(succeeded + failed + fatal).append('/').append(total);
368                                 progressString.append(") (");
369                                 progressString.append(getTransferRate());
370                                 progressString.append(' ').append(I18n.getMessage("jsite.insert.k-per-s")).append(')');
371                                 progressBar.setString(progressString.toString());
372                                 if (finalized) {
373                                         progressBar.setFont(progressBar.getFont().deriveFont(Font.BOLD));
374                                 }
375                         }
376                 });
377         }
378
379         /**
380          * {@inheritDoc}
381          */
382         public void projectInsertFinished(Project project, boolean success, Throwable cause) {
383                 running = false;
384                 if (success) {
385                         String copyURILabel = I18n.getMessage("jsite.insert.okay-copy-uri");
386                         int selectedValue = JOptionPane.showOptionDialog(this, I18n.getMessage("jsite.insert.inserted"), I18n.getMessage("jsite.insert.done.title"), 0, JOptionPane.INFORMATION_MESSAGE, null, new Object[] { I18n.getMessage("jsite.general.ok"), copyURILabel }, copyURILabel);
387                         if (selectedValue == 1) {
388                                 actionCopyURI();
389                         }
390                 } else {
391                         if (cause == null) {
392                                 JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-failed"), I18n.getMessage("jsite.insert.insert-failed.title"), JOptionPane.ERROR_MESSAGE);
393                         } else {
394                                 if (cause instanceof AbortedException) {
395                                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-aborted"), I18n.getMessage("jsite.insert.insert-aborted.title"), JOptionPane.INFORMATION_MESSAGE);
396                                 } else {
397                                         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);
398                                 }
399                         }
400                 }
401                 SwingUtilities.invokeLater(new Runnable() {
402
403                         @SuppressWarnings("synthetic-access")
404                         public void run() {
405                                 progressBar.setValue(progressBar.getMaximum());
406                                 progressBar.setString(I18n.getMessage("jsite.insert.done") + " (" + getTransferRate() + " " + I18n.getMessage("jsite.insert.k-per-s") + ")");
407                                 wizard.setNextName(I18n.getMessage("jsite.wizard.next"));
408                                 wizard.setNextEnabled(true);
409                                 wizard.setQuitEnabled(true);
410                         }
411                 });
412         }
413
414         //
415         // ACTIONS
416         //
417
418         /**
419          * Copies the request URI of the project to the clipboard.
420          */
421         private void actionCopyURI() {
422                 uriCopied = true;
423                 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
424                 clipboard.setContents(new StringSelection(requestURITextField.getText()), this);
425         }
426
427         /**
428          * Formats the given number so that it always has the the given number of
429          * fractional digits.
430          *
431          * @param number
432          *            The number to format
433          * @param digits
434          *            The number of fractional digits
435          * @return The formatted number
436          */
437         private String formatNumber(double number, int digits) {
438                 int multiplier = (int) Math.pow(10, digits);
439                 String formattedNumber = String.valueOf((int) (number * multiplier) / (double) multiplier);
440                 if (formattedNumber.indexOf('.') == -1) {
441                         formattedNumber += '.';
442                         for (int digit = 0; digit < digits; digit++) {
443                                 formattedNumber += "0";
444                         }
445                 }
446                 return formattedNumber;
447         }
448
449         /**
450          * Returns the formatted transfer rate at this point.
451          *
452          * @return The formatted transfer rate
453          */
454         private String getTransferRate() {
455                 return formatNumber(insertedBlocks * 32.0 / ((System.currentTimeMillis() - startTime) / 1000), 1);
456         }
457
458         //
459         // INTERFACE ClipboardOwner
460         //
461
462         /**
463          * {@inheritDoc}
464          */
465         public void lostOwnership(Clipboard clipboard, Transferable contents) {
466                 /* ignore. */
467         }
468
469 }