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