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