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