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