Factor out transfer rate calculation.
[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
38 import javax.swing.AbstractAction;
39 import javax.swing.Action;
40 import javax.swing.JButton;
41 import javax.swing.JComponent;
42 import javax.swing.JLabel;
43 import javax.swing.JOptionPane;
44 import javax.swing.JPanel;
45 import javax.swing.JProgressBar;
46 import javax.swing.JTextField;
47 import javax.swing.SwingUtilities;
48
49 import de.todesbaum.jsite.application.Freenet7Interface;
50 import de.todesbaum.jsite.application.InsertListener;
51 import de.todesbaum.jsite.application.Project;
52 import de.todesbaum.jsite.application.ProjectInserter;
53 import de.todesbaum.jsite.i18n.I18n;
54 import de.todesbaum.jsite.i18n.I18nContainer;
55 import de.todesbaum.util.swing.TWizard;
56 import de.todesbaum.util.swing.TWizardPage;
57
58 /**
59  * Wizard page that shows the progress of an insert.
60  *
61  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
62  */
63 public class ProjectInsertPage extends TWizardPage implements InsertListener, ClipboardOwner {
64
65         /** The project inserter. */
66         private ProjectInserter projectInserter;
67
68         /** The “copy URI” action. */
69         private Action copyURIAction;
70
71         /** The “request URI” textfield. */
72         private JTextField requestURITextField;
73
74         /** The “start time” label. */
75         private JLabel startTimeLabel;
76
77         /** The progress bar. */
78         private JProgressBar progressBar;
79
80         /** The start time of the insert. */
81         private long startTime = 0;
82
83         /** The number of inserted blocks. */
84         private volatile int insertedBlocks;
85
86         /**
87          * Creates a new progress insert wizard page.
88          *
89          * @param wizard
90          *            The wizard this page belongs to
91          */
92         public ProjectInsertPage(final TWizard wizard) {
93                 super(wizard);
94                 createActions();
95                 pageInit();
96                 setHeading(I18n.getMessage("jsite.insert.heading"));
97                 setDescription(I18n.getMessage("jsite.insert.description"));
98                 I18nContainer.getInstance().registerRunnable(new Runnable() {
99
100                         public void run() {
101                                 setHeading(I18n.getMessage("jsite.insert.heading"));
102                                 setDescription(I18n.getMessage("jsite.insert.description"));
103                         }
104                 });
105                 projectInserter = new ProjectInserter();
106                 projectInserter.addInsertListener(this);
107         }
108
109         /**
110          * Creates all used actions.
111          */
112         private void createActions() {
113                 copyURIAction = new AbstractAction(I18n.getMessage("jsite.project.action.copy-uri")) {
114
115                         @SuppressWarnings("synthetic-access")
116                         public void actionPerformed(ActionEvent actionEvent) {
117                                 actionCopyURI();
118                         }
119                 };
120                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
121                 copyURIAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_U);
122                 copyURIAction.setEnabled(false);
123
124                 I18nContainer.getInstance().registerRunnable(new Runnable() {
125
126                         @SuppressWarnings("synthetic-access")
127                         public void run() {
128                                 copyURIAction.putValue(Action.NAME, I18n.getMessage("jsite.project.action.copy-uri"));
129                                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
130                         }
131                 });
132         }
133
134         /**
135          * Initializes the page.
136          */
137         private void pageInit() {
138                 setLayout(new BorderLayout(12, 12));
139                 add(createProjectInsertPanel(), BorderLayout.CENTER);
140         }
141
142         /**
143          * Creates the main panel.
144          *
145          * @return The main panel
146          */
147         private JComponent createProjectInsertPanel() {
148                 JComponent projectInsertPanel = new JPanel(new GridBagLayout());
149
150                 requestURITextField = new JTextField();
151                 requestURITextField.setEditable(false);
152
153                 startTimeLabel = new JLabel();
154
155                 progressBar = new JProgressBar(0, 1);
156                 progressBar.setStringPainted(true);
157                 progressBar.setValue(0);
158
159                 final JLabel projectInformationLabel = new JLabel("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
160                 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));
161                 final JLabel requestURILabel = new JLabel(I18n.getMessage("jsite.insert.request-uri") + ":");
162                 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));
163                 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));
164                 final JLabel startTimeLeftLabel = new JLabel(I18n.getMessage("jsite.insert.start-time") + ":");
165                 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));
166                 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));
167                 final JLabel progressLabel = new JLabel(I18n.getMessage("jsite.insert.progress") + ":");
168                 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));
169                 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));
170                 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));
171
172                 I18nContainer.getInstance().registerRunnable(new Runnable() {
173
174                         @SuppressWarnings("synthetic-access")
175                         public void run() {
176                                 projectInformationLabel.setText("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
177                                 requestURILabel.setText(I18n.getMessage("jsite.insert.request-uri") + ":");
178                                 startTimeLeftLabel.setText(I18n.getMessage("jsite.insert.start-time") + ":");
179                                 if (startTime != 0) {
180                                         startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date(startTime)));
181                                 } else {
182                                         startTimeLabel.setText("");
183                                 }
184                                 progressLabel.setText(I18n.getMessage("jsite.insert.progress") + ":");
185                         }
186                 });
187
188                 return projectInsertPanel;
189         }
190
191         /**
192          * {@inheritDoc}
193          */
194         @Override
195         public void pageAdded(TWizard wizard) {
196                 this.wizard.setPreviousName(I18n.getMessage("jsite.wizard.previous"));
197                 this.wizard.setPreviousEnabled(false);
198                 this.wizard.setNextName(I18n.getMessage("jsite.wizard.next"));
199                 this.wizard.setQuitName(I18n.getMessage("jsite.wizard.quit"));
200         }
201
202         /**
203          * Starts the insert.
204          */
205         public void startInsert() {
206                 wizard.setNextEnabled(false);
207                 copyURIAction.setEnabled(false);
208                 progressBar.setValue(0);
209                 progressBar.setString(I18n.getMessage("jsite.insert.starting"));
210                 progressBar.setFont(progressBar.getFont().deriveFont(Font.PLAIN));
211                 projectInserter.start();
212         }
213
214         /**
215          * Sets the project to insert.
216          *
217          * @param project
218          *            The project to insert
219          */
220         public void setProject(final Project project) {
221                 projectInserter.setProject(project);
222                 SwingUtilities.invokeLater(new Runnable() {
223
224                         @SuppressWarnings("synthetic-access")
225                         public void run() {
226                                 requestURITextField.setText(project.getFinalRequestURI(1));
227                         }
228                 });
229         }
230
231         /**
232          * Sets the freenet interface to use.
233          *
234          * @param freenetInterface
235          *            The freenet interface to use
236          */
237         public void setFreenetInterface(Freenet7Interface freenetInterface) {
238                 projectInserter.setFreenetInterface(freenetInterface);
239         }
240
241         /**
242          * Sets the project inserter’s temp directory.
243          *
244          * @see ProjectInserter#setTempDirectory(String)
245          * @param tempDirectory
246          *            The temp directory to use, or {@code null} to use the system
247          *            default
248          */
249         public void setTempDirectory(String tempDirectory) {
250                 projectInserter.setTempDirectory(tempDirectory);
251         }
252
253         //
254         // INTERFACE InsertListener
255         //
256
257         /**
258          * {@inheritDoc}
259          */
260         public void projectInsertStarted(final Project project) {
261
262                 SwingUtilities.invokeLater(new Runnable() {
263
264                         @SuppressWarnings("synthetic-access")
265                         public void run() {
266                                 startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date()));
267                         }
268                 });
269         }
270
271         /**
272          * {@inheritDoc}
273          */
274         public void projectUploadFinished(Project project) {
275                 startTime = System.currentTimeMillis();
276         }
277
278         /**
279          * {@inheritDoc}
280          */
281         public void projectURIGenerated(Project project, final String uri) {
282                 SwingUtilities.invokeLater(new Runnable() {
283
284                         @SuppressWarnings("synthetic-access")
285                         public void run() {
286                                 copyURIAction.setEnabled(true);
287                                 requestURITextField.setText(uri);
288                         }
289                 });
290         }
291
292         /**
293          * {@inheritDoc}
294          */
295         public void projectInsertProgress(Project project, final int succeeded, final int failed, final int fatal, final int total, final boolean finalized) {
296                 insertedBlocks = succeeded;
297                 SwingUtilities.invokeLater(new Runnable() {
298
299                         @SuppressWarnings("synthetic-access")
300                         public void run() {
301                                 progressBar.setMaximum(total);
302                                 progressBar.setValue(succeeded + failed + fatal);
303                                 int progress = (succeeded + failed + fatal) * 100 / total;
304                                 StringBuilder progressString = new StringBuilder();
305                                 progressString.append(progress).append("% (");
306                                 progressString.append(succeeded + failed + fatal).append('/').append(total);
307                                 progressString.append(") (");
308                                 progressString.append(getTransferRate());
309                                 progressString.append(' ').append(I18n.getMessage("jsite.insert.k-per-s")).append(')');
310                                 progressBar.setString(progressString.toString());
311                                 if (finalized) {
312                                         progressBar.setFont(progressBar.getFont().deriveFont(Font.BOLD));
313                                 }
314                         }
315                 });
316         }
317
318         /**
319          * {@inheritDoc}
320          */
321         public void projectInsertFinished(Project project, boolean success, Throwable cause) {
322                 if (success) {
323                         String copyURILabel = I18n.getMessage("jsite.insert.okay-copy-uri");
324                         String selectedValue = (String) JOptionPane.showInputDialog(this, I18n.getMessage("jsite.insert.inserted"), I18n.getMessage("jsite.insert.done.title"), JOptionPane.INFORMATION_MESSAGE, null, new Object[] { I18n.getMessage("jsite.insert.okay"), copyURILabel }, copyURILabel);
325                         if (copyURILabel.equals(selectedValue)) {
326                                 actionCopyURI();
327                         }
328                 } else {
329                         if (cause == null) {
330                                 JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-failed"), null, JOptionPane.ERROR_MESSAGE);
331                         } else {
332                                 JOptionPane.showMessageDialog(this, MessageFormat.format(I18n.getMessage("jsite.insert.insert-failed-with-cause"), cause.getMessage()), null, JOptionPane.ERROR_MESSAGE);
333                         }
334                 }
335                 SwingUtilities.invokeLater(new Runnable() {
336
337                         @SuppressWarnings("synthetic-access")
338                         public void run() {
339                                 progressBar.setValue(progressBar.getMaximum());
340                                 progressBar.setString(I18n.getMessage("jsite.insert.done"));
341                                 wizard.setNextEnabled(true);
342                                 wizard.setQuitEnabled(true);
343                         }
344                 });
345         }
346
347         //
348         // ACTIONS
349         //
350
351         /**
352          * Copies the request URI of the project to the clipboard.
353          */
354         private void actionCopyURI() {
355                 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
356                 clipboard.setContents(new StringSelection(requestURITextField.getText()), this);
357         }
358
359         /**
360          * Formats the given number so that it always has the the given number of
361          * fractional digits.
362          *
363          * @param number
364          *            The number to format
365          * @param digits
366          *            The number of fractional digits
367          * @return The formatted number
368          */
369         private String formatNumber(double number, int digits) {
370                 int multiplier = (int) Math.pow(10, digits);
371                 String formattedNumber = String.valueOf((int) (number * multiplier) / (double) multiplier);
372                 if (formattedNumber.indexOf('.') == -1) {
373                         formattedNumber += '.';
374                         for (int digit = 0; digit < digits; digit++) {
375                                 formattedNumber += "0";
376                         }
377                 }
378                 return formattedNumber;
379         }
380
381         /**
382          * Returns the formatted transfer rate at this point.
383          *
384          * @return The formatted transfer rate
385          */
386         private String getTransferRate() {
387                 return formatNumber(insertedBlocks * 32.0 / ((System.currentTimeMillis() - startTime) / 1000), 1);
388         }
389
390         //
391         // INTERFACE ClipboardOwner
392         //
393
394         /**
395          * {@inheritDoc}
396          */
397         public void lostOwnership(Clipboard clipboard, Transferable contents) {
398                 /* ignore. */
399         }
400
401 }