b73a49a9810e4f71f03cfd5d7872c9a38ec73725
[jSite.git] / src / main / java / de / todesbaum / jsite / gui / ProjectInsertPage.java
1 /*
2  * jSite - ProjectInsertPage.java - Copyright © 2006–2012 David Roden
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 package de.todesbaum.jsite.gui;
20
21 import java.awt.BorderLayout;
22 import java.awt.Font;
23 import java.awt.GridBagConstraints;
24 import java.awt.GridBagLayout;
25 import java.awt.Insets;
26 import java.awt.Toolkit;
27 import java.awt.datatransfer.Clipboard;
28 import java.awt.datatransfer.ClipboardOwner;
29 import java.awt.datatransfer.StringSelection;
30 import java.awt.datatransfer.Transferable;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.KeyEvent;
33 import java.text.DateFormat;
34 import java.text.MessageFormat;
35 import java.util.Date;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38
39 import javax.swing.AbstractAction;
40 import javax.swing.Action;
41 import javax.swing.JButton;
42 import javax.swing.JComponent;
43 import javax.swing.JLabel;
44 import javax.swing.JOptionPane;
45 import javax.swing.JPanel;
46 import javax.swing.JProgressBar;
47 import javax.swing.JTextField;
48 import javax.swing.SwingUtilities;
49
50 import net.pterodactylus.util.io.StreamCopier.ProgressListener;
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.freenet.fcp2.ClientPutDir.ManifestPutter;
59 import de.todesbaum.util.freenet.fcp2.PriorityClass;
60 import de.todesbaum.util.swing.TWizard;
61 import de.todesbaum.util.swing.TWizardPage;
62
63 /**
64  * Wizard page that shows the progress of an insert.
65  *
66  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
67  */
68 public class ProjectInsertPage extends TWizardPage implements InsertListener, ClipboardOwner {
69
70         /** The logger. */
71         private static final Logger logger = Logger.getLogger(ProjectInsertPage.class.getName());
72
73         /** The project inserter. */
74         private ProjectInserter projectInserter;
75
76         /** The “copy URI” action. */
77         private Action copyURIAction;
78
79         /** The “request URI” textfield. */
80         private JTextField requestURITextField;
81
82         /** The “start time” label. */
83         private JLabel startTimeLabel;
84
85         /** The progress bar. */
86         private JProgressBar progressBar;
87
88         /** The start time of the insert. */
89         private long startTime = 0;
90
91         /** The number of inserted blocks. */
92         private volatile int insertedBlocks;
93
94         /** Whether the “copy URI to clipboard” button was used. */
95         private boolean uriCopied;
96
97         /** Whether the insert is currently running. */
98         private volatile boolean running = false;
99
100         /**
101          * Creates a new progress insert wizard page.
102          *
103          * @param wizard
104          *            The wizard this page belongs to
105          */
106         public ProjectInsertPage(final TWizard wizard) {
107                 super(wizard);
108                 createActions();
109                 pageInit();
110                 setHeading(I18n.getMessage("jsite.insert.heading"));
111                 setDescription(I18n.getMessage("jsite.insert.description"));
112                 I18nContainer.getInstance().registerRunnable(new Runnable() {
113
114                         @Override
115                         public void run() {
116                                 setHeading(I18n.getMessage("jsite.insert.heading"));
117                                 setDescription(I18n.getMessage("jsite.insert.description"));
118                         }
119                 });
120                 projectInserter = new ProjectInserter();
121                 projectInserter.addInsertListener(this);
122         }
123
124         /**
125          * Creates all used actions.
126          */
127         private void createActions() {
128                 copyURIAction = new AbstractAction(I18n.getMessage("jsite.project.action.copy-uri")) {
129
130                         @Override
131                         @SuppressWarnings("synthetic-access")
132                         public void actionPerformed(ActionEvent actionEvent) {
133                                 actionCopyURI();
134                         }
135                 };
136                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
137                 copyURIAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_U);
138                 copyURIAction.setEnabled(false);
139
140                 I18nContainer.getInstance().registerRunnable(new Runnable() {
141
142                         @Override
143                         @SuppressWarnings("synthetic-access")
144                         public void run() {
145                                 copyURIAction.putValue(Action.NAME, I18n.getMessage("jsite.project.action.copy-uri"));
146                                 copyURIAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.project.action.copy-uri.tooltip"));
147                         }
148                 });
149         }
150
151         /**
152          * Initializes the page.
153          */
154         private void pageInit() {
155                 setLayout(new BorderLayout(12, 12));
156                 add(createProjectInsertPanel(), BorderLayout.CENTER);
157         }
158
159         /**
160          * Creates the main panel.
161          *
162          * @return The main panel
163          */
164         private JComponent createProjectInsertPanel() {
165                 JComponent projectInsertPanel = new JPanel(new GridBagLayout());
166
167                 requestURITextField = new JTextField();
168                 requestURITextField.setEditable(false);
169
170                 startTimeLabel = new JLabel();
171
172                 progressBar = new JProgressBar(0, 1);
173                 progressBar.setStringPainted(true);
174                 progressBar.setValue(0);
175
176                 final JLabel projectInformationLabel = new JLabel("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
177                 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));
178                 final JLabel requestURILabel = new JLabel(I18n.getMessage("jsite.insert.request-uri") + ":");
179                 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));
180                 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));
181                 final JLabel startTimeLeftLabel = new JLabel(I18n.getMessage("jsite.insert.start-time") + ":");
182                 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));
183                 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));
184                 final JLabel progressLabel = new JLabel(I18n.getMessage("jsite.insert.progress") + ":");
185                 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));
186                 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));
187                 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));
188
189                 I18nContainer.getInstance().registerRunnable(new Runnable() {
190
191                         @Override
192                         @SuppressWarnings("synthetic-access")
193                         public void run() {
194                                 projectInformationLabel.setText("<html><b>" + I18n.getMessage("jsite.insert.project-information") + "</b></html>");
195                                 requestURILabel.setText(I18n.getMessage("jsite.insert.request-uri") + ":");
196                                 startTimeLeftLabel.setText(I18n.getMessage("jsite.insert.start-time") + ":");
197                                 if (startTime != 0) {
198                                         startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date(startTime)));
199                                 } else {
200                                         startTimeLabel.setText("");
201                                 }
202                                 progressLabel.setText(I18n.getMessage("jsite.insert.progress") + ":");
203                         }
204                 });
205
206                 return projectInsertPanel;
207         }
208
209         /**
210          * {@inheritDoc}
211          */
212         @Override
213         public void pageAdded(TWizard wizard) {
214                 this.wizard.setPreviousName(I18n.getMessage("jsite.wizard.previous"));
215                 this.wizard.setPreviousEnabled(false);
216                 this.wizard.setNextName(I18n.getMessage("jsite.general.cancel"));
217                 this.wizard.setQuitName(I18n.getMessage("jsite.wizard.quit"));
218         }
219
220         /**
221          * Starts the insert.
222          */
223         public void startInsert() {
224                 running = true;
225                 copyURIAction.setEnabled(false);
226                 progressBar.setValue(0);
227                 progressBar.setString(I18n.getMessage("jsite.insert.starting"));
228                 progressBar.setFont(progressBar.getFont().deriveFont(Font.PLAIN));
229                 projectInserter.start(new ProgressListener() {
230
231                         @Override
232                         public void onProgress(final long copied, final long length) {
233                                 SwingUtilities.invokeLater(new Runnable() {
234
235                                         /**
236                                          * {@inheritDoc}
237                                          */
238                                         @Override
239                                         @SuppressWarnings("synthetic-access")
240                                         public void run() {
241                                                 int divisor = 1;
242                                                 while (((copied / divisor) > Integer.MAX_VALUE) || ((length / divisor) > Integer.MAX_VALUE)) {
243                                                         divisor *= 10;
244                                                 }
245                                                 progressBar.setMaximum((int) (length / divisor));
246                                                 progressBar.setValue((int) (copied / divisor));
247                                                 progressBar.setString("Uploaded: " + copied + " / " + length);
248                                         }
249                                 });
250                         }
251                 });
252         }
253
254         /**
255          * Stops the currently running insert.
256          */
257         public void stopInsert() {
258                 if (running) {
259                         wizard.setNextEnabled(false);
260                         projectInserter.stop();
261                 }
262         }
263
264         /**
265          * Returns whether the insert is currently running.
266          *
267          * @return {@code true} if the insert is currently running, {@code false}
268          *         otherwise
269          */
270         public boolean isRunning() {
271                 return running;
272         }
273
274         /**
275          * Sets the project to insert.
276          *
277          * @param project
278          *            The project to insert
279          */
280         public void setProject(final Project project) {
281                 projectInserter.setProject(project);
282                 SwingUtilities.invokeLater(new Runnable() {
283
284                         @Override
285                         @SuppressWarnings("synthetic-access")
286                         public void run() {
287                                 requestURITextField.setText(project.getFinalRequestURI(1));
288                         }
289                 });
290         }
291
292         /**
293          * Sets the freenet interface to use.
294          *
295          * @param freenetInterface
296          *            The freenet interface to use
297          */
298         public void setFreenetInterface(Freenet7Interface freenetInterface) {
299                 projectInserter.setFreenetInterface(freenetInterface);
300         }
301
302         /**
303          * Sets the project inserter’s temp directory.
304          *
305          * @see ProjectInserter#setTempDirectory(String)
306          * @param tempDirectory
307          *            The temp directory to use, or {@code null} to use the system
308          *            default
309          */
310         public void setTempDirectory(String tempDirectory) {
311                 projectInserter.setTempDirectory(tempDirectory);
312         }
313
314         /**
315          * Returns whether the “copy URI to clipboard” button was used.
316          *
317          * @return {@code true} if an URI was copied to clipboard, {@code false}
318          *         otherwise
319          */
320         public boolean wasUriCopied() {
321                 return uriCopied;
322         }
323
324         /**
325          * Sets whether to use the “early encode“ flag for the insert.
326          *
327          * @param useEarlyEncode
328          *            {@code true} to set the “early encode” flag for the insert,
329          *            {@code false} otherwise
330          */
331         public void setUseEarlyEncode(boolean useEarlyEncode) {
332                 projectInserter.setUseEarlyEncode(useEarlyEncode);
333         }
334
335         /**
336          * Sets the insert priority.
337          *
338          * @param priority
339          *            The insert priority
340          */
341         public void setPriority(PriorityClass priority) {
342                 projectInserter.setPriority(priority);
343         }
344
345         /**
346          * Sets the manifest putter to use for the insert.
347          *
348          * @see ProjectInserter#setManifestPutter(ManifestPutter)
349          * @param manifestPutter
350          *            The manifest putter
351          */
352         public void setManifestPutter(ManifestPutter manifestPutter) {
353                 projectInserter.setManifestPutter(manifestPutter);
354         }
355
356         //
357         // INTERFACE InsertListener
358         //
359
360         /**
361          * {@inheritDoc}
362          */
363         @Override
364         public void projectInsertStarted(final Project project) {
365
366                 SwingUtilities.invokeLater(new Runnable() {
367
368                         @Override
369                         @SuppressWarnings("synthetic-access")
370                         public void run() {
371                                 startTimeLabel.setText(DateFormat.getDateTimeInstance().format(new Date()));
372                         }
373                 });
374         }
375
376         /**
377          * {@inheritDoc}
378          */
379         @Override
380         public void projectUploadFinished(Project project) {
381                 startTime = System.currentTimeMillis();
382                 SwingUtilities.invokeLater(new Runnable() {
383
384                         @Override
385                         @SuppressWarnings("synthetic-access")
386                         public void run() {
387                                 progressBar.setString(I18n.getMessage("jsite.insert.starting"));
388                                 progressBar.setValue(0);
389                         }
390                 });
391         }
392
393         /**
394          * {@inheritDoc}
395          */
396         @Override
397         public void projectURIGenerated(Project project, final String uri) {
398                 SwingUtilities.invokeLater(new Runnable() {
399
400                         @Override
401                         @SuppressWarnings("synthetic-access")
402                         public void run() {
403                                 copyURIAction.setEnabled(true);
404                                 requestURITextField.setText(uri);
405                         }
406                 });
407                 logger.log(Level.FINEST, "Insert generated URI: " + uri);
408                 int slash = uri.indexOf('/');
409                 slash = uri.indexOf('/', slash + 1);
410                 int secondSlash = uri.indexOf('/', slash + 1);
411                 if (secondSlash == -1) {
412                         secondSlash = uri.length();
413                 }
414                 String editionNumber = uri.substring(slash + 1, secondSlash);
415                 logger.log(Level.FINEST, "Extracted edition number: " + editionNumber);
416                 int edition = -1;
417                 try {
418                         edition = Integer.valueOf(editionNumber);
419                 } catch (NumberFormatException nfe1) {
420                         /* ignore. */
421                 }
422                 logger.log(Level.FINEST, "Insert edition: " + edition + ", Project edition: " + project.getEdition());
423                 if ((edition != -1) && (edition == project.getEdition())) {
424                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.reinserted-edition"), I18n.getMessage("jsite.insert.reinserted-edition.title"), JOptionPane.INFORMATION_MESSAGE);
425                 }
426         }
427
428         /**
429          * {@inheritDoc}
430          */
431         @Override
432         public void projectInsertProgress(Project project, final int succeeded, final int failed, final int fatal, final int total, final boolean finalized) {
433                 insertedBlocks = succeeded;
434                 SwingUtilities.invokeLater(new Runnable() {
435
436                         @Override
437                         @SuppressWarnings("synthetic-access")
438                         public void run() {
439                                 if (total == 0) {
440                                         return;
441                                 }
442                                 progressBar.setMaximum(total);
443                                 progressBar.setValue(succeeded + failed + fatal);
444                                 int progress = (succeeded + failed + fatal) * 100 / total;
445                                 StringBuilder progressString = new StringBuilder();
446                                 progressString.append(progress).append("% (");
447                                 progressString.append(succeeded + failed + fatal).append('/').append(total);
448                                 progressString.append(") (");
449                                 progressString.append(getTransferRate());
450                                 progressString.append(' ').append(I18n.getMessage("jsite.insert.k-per-s")).append(')');
451                                 progressBar.setString(progressString.toString());
452                                 if (finalized) {
453                                         progressBar.setFont(progressBar.getFont().deriveFont(Font.BOLD));
454                                 }
455                         }
456                 });
457         }
458
459         /**
460          * {@inheritDoc}
461          */
462         @Override
463         public void projectInsertFinished(Project project, boolean success, Throwable cause) {
464                 running = false;
465                 if (success) {
466                         String copyURILabel = I18n.getMessage("jsite.insert.okay-copy-uri");
467                         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);
468                         if (selectedValue == 1) {
469                                 actionCopyURI();
470                         }
471                 } else {
472                         if (cause == null) {
473                                 JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-failed"), I18n.getMessage("jsite.insert.insert-failed.title"), JOptionPane.ERROR_MESSAGE);
474                         } else {
475                                 if (cause instanceof AbortedException) {
476                                         JOptionPane.showMessageDialog(this, I18n.getMessage("jsite.insert.insert-aborted"), I18n.getMessage("jsite.insert.insert-aborted.title"), JOptionPane.INFORMATION_MESSAGE);
477                                 } else {
478                                         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);
479                                 }
480                         }
481                 }
482                 SwingUtilities.invokeLater(new Runnable() {
483
484                         @Override
485                         @SuppressWarnings("synthetic-access")
486                         public void run() {
487                                 progressBar.setValue(progressBar.getMaximum());
488                                 progressBar.setString(I18n.getMessage("jsite.insert.done") + " (" + getTransferRate() + " " + I18n.getMessage("jsite.insert.k-per-s") + ")");
489                                 wizard.setNextName(I18n.getMessage("jsite.wizard.next"));
490                                 wizard.setNextEnabled(true);
491                                 wizard.setQuitEnabled(true);
492                         }
493                 });
494         }
495
496         //
497         // ACTIONS
498         //
499
500         /**
501          * Copies the request URI of the project to the clipboard.
502          */
503         private void actionCopyURI() {
504                 uriCopied = true;
505                 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
506                 clipboard.setContents(new StringSelection(requestURITextField.getText()), this);
507         }
508
509         /**
510          * Formats the given number so that it always has the the given number of
511          * fractional digits.
512          *
513          * @param number
514          *            The number to format
515          * @param digits
516          *            The number of fractional digits
517          * @return The formatted number
518          */
519         private static String formatNumber(double number, int digits) {
520                 int multiplier = (int) Math.pow(10, digits);
521                 String formattedNumber = String.valueOf((int) (number * multiplier) / (double) multiplier);
522                 if (formattedNumber.indexOf('.') == -1) {
523                         formattedNumber += '.';
524                         for (int digit = 0; digit < digits; digit++) {
525                                 formattedNumber += "0";
526                         }
527                 }
528                 return formattedNumber;
529         }
530
531         /**
532          * Returns the formatted transfer rate at this point.
533          *
534          * @return The formatted transfer rate
535          */
536         private String getTransferRate() {
537                 return formatNumber(insertedBlocks * 32.0 / ((System.currentTimeMillis() - startTime) / 1000), 1);
538         }
539
540         //
541         // INTERFACE ClipboardOwner
542         //
543
544         /**
545          * {@inheritDoc}
546          */
547         @Override
548         public void lostOwnership(Clipboard clipboard, Transferable contents) {
549                 /* ignore. */
550         }
551
552 }