ae8cea46d37a9388a971de2d22302d7b80d8d1a2
[jSite.git] / src / main / java / de / todesbaum / jsite / gui / KeyDialog.java
1 /*
2  * jSite - KeyDialog.java - Copyright © 2010–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.Component;
23 import java.awt.Dimension;
24 import java.awt.FlowLayout;
25 import java.awt.GridBagConstraints;
26 import java.awt.GridBagLayout;
27 import java.awt.Insets;
28 import java.awt.Toolkit;
29 import java.awt.event.ActionEvent;
30 import java.awt.event.ActionListener;
31 import java.awt.event.InputEvent;
32 import java.awt.event.KeyEvent;
33 import java.awt.event.WindowAdapter;
34 import java.awt.event.WindowEvent;
35 import java.io.IOException;
36 import java.text.MessageFormat;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.Comparator;
41 import java.util.List;
42
43 import javax.swing.AbstractAction;
44 import javax.swing.Action;
45 import javax.swing.BorderFactory;
46 import javax.swing.DefaultListCellRenderer;
47 import javax.swing.JButton;
48 import javax.swing.JComboBox;
49 import javax.swing.JDialog;
50 import javax.swing.JFrame;
51 import javax.swing.JLabel;
52 import javax.swing.JList;
53 import javax.swing.JOptionPane;
54 import javax.swing.JPanel;
55 import javax.swing.JSeparator;
56 import javax.swing.JTextField;
57 import javax.swing.KeyStroke;
58 import javax.swing.SwingConstants;
59
60 import net.pterodactylus.util.swing.ComboBoxModelList;
61 import de.todesbaum.jsite.application.Freenet7Interface;
62 import de.todesbaum.jsite.application.Project;
63 import de.todesbaum.jsite.i18n.I18n;
64 import de.todesbaum.jsite.i18n.I18nContainer;
65 import de.todesbaum.util.freenet.fcp2.wot.OwnIdentity;
66
67 /**
68  * A dialog that lets the user edit the private and public key for a project.
69  *
70  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
71  */
72 public class KeyDialog extends JDialog {
73
74         /** Interface to the freenet node. */
75         private final Freenet7Interface freenetInterface;
76
77         /** The public key. */
78         private String publicKey;
79
80         /** The private key. */
81         private String privateKey;
82
83         /** The “OK” button’s action. */
84         private Action okAction;
85
86         /** The “Cancel” button’s action. */
87         private Action cancelAction;
88
89         /** The “Regenerate” button’s action. */
90         private Action generateAction;
91
92         /** The “Copy from Project” action. */
93         private Action copyFromProjectAction;
94
95         /** The “Copy from Identity” action. */
96         private Action copyFromIdentityAction;
97
98         /** The text field for the private key. */
99         private JTextField privateKeyTextField;
100
101         /** The text field for the public key. */
102         private JTextField publicKeyTextField;
103
104         /** The select box for the projects. */
105         private JComboBox projectsComboBox;
106
107         /** The select box for the own identities. */
108         private JComboBox ownIdentitiesComboBox;
109
110         /** Whether the dialog was cancelled. */
111         private boolean cancelled;
112
113         /** The list of projects. */
114         private final List<Project> projects = new ArrayList<Project>();
115
116         /** The list of own identities. */
117         private final List<OwnIdentity> ownIdentities = new ArrayList<OwnIdentity>();
118
119         /**
120          * Creates a new key dialog.
121          *
122          * @param freenetInterface
123          *            Interface to the freenet node
124          * @param parent
125          *            The parent frame
126          */
127         public KeyDialog(Freenet7Interface freenetInterface, JFrame parent) {
128                 super(parent, I18n.getMessage("jsite.key-dialog.title"), true);
129                 this.freenetInterface = freenetInterface;
130                 addWindowListener(new WindowAdapter() {
131
132                         @Override
133                         @SuppressWarnings("synthetic-access")
134                         public void windowClosing(WindowEvent windowEvent) {
135                                 actionCancel();
136                         }
137                 });
138                 initDialog();
139         }
140
141         //
142         // ACCESSORS
143         //
144
145         /**
146          * Returns whether the dialog was cancelled.
147          *
148          * @return {@code true} if the dialog was cancelled, {@code false} otherwise
149          */
150         public boolean wasCancelled() {
151                 return cancelled;
152         }
153
154         /**
155          * Returns the public key.
156          *
157          * @return The public key
158          */
159         public String getPublicKey() {
160                 return publicKey;
161         }
162
163         /**
164          * Sets the public key.
165          *
166          * @param publicKey
167          *            The public key
168          */
169         public void setPublicKey(String publicKey) {
170                 this.publicKey = publicKey;
171                 publicKeyTextField.setText(publicKey);
172                 pack();
173         }
174
175         /**
176          * Returns the private key.
177          *
178          * @return The private key
179          */
180         public String getPrivateKey() {
181                 return privateKey;
182         }
183
184         /**
185          * Sets the private key.
186          *
187          * @param privateKey
188          *            The private key
189          */
190         public void setPrivateKey(String privateKey) {
191                 this.privateKey = privateKey;
192                 privateKeyTextField.setText(privateKey);
193                 pack();
194         }
195
196         /**
197          * Sets the projects to display and copy URIs from.
198          *
199          * @param projects
200          *            The list of projects
201          */
202         public void setProjects(Collection<? extends Project> projects) {
203                 synchronized (this.projects) {
204                         this.projects.clear();
205                         this.projects.addAll(projects);
206                 }
207                 projectsComboBox.setSelectedIndex(-1);
208         }
209
210         /**
211          * Sets the own identities to display and copy URIs from.
212          *
213          * @param ownIdentities
214          *            The list of own identities
215          */
216         public void setOwnIdentities(Collection<? extends OwnIdentity> ownIdentities) {
217                 synchronized (this.ownIdentities) {
218                         this.ownIdentities.clear();
219                         this.ownIdentities.addAll(ownIdentities);
220                         Collections.sort(this.ownIdentities, new Comparator<OwnIdentity>() {
221
222                                 @Override
223                                 public int compare(OwnIdentity leftOwnIdentity, OwnIdentity rightOwnIdentity) {
224                                         return leftOwnIdentity.getNickname().compareToIgnoreCase(rightOwnIdentity.getNickname());
225                                 }
226                         });
227                 }
228                 int selectedIndex = -1;
229                 int index = 0;
230                 for (OwnIdentity ownIdentity : this.ownIdentities) {
231                         if (ownIdentity.getInsertUri().equals(privateKey) && ownIdentity.getRequestUri().equals(publicKey)) {
232                                 selectedIndex = index;
233                         }
234                         index++;
235                 }
236                 ownIdentitiesComboBox.setSelectedIndex(selectedIndex);
237         }
238
239         //
240         // ACTIONS
241         //
242
243         /**
244          * {@inheritDoc}
245          */
246         @Override
247         public void pack() {
248                 super.pack();
249                 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
250                 setLocation((screenSize.width - getWidth()) / 2, (screenSize.height - getHeight()) / 2);
251         }
252
253         //
254         // PRIVATE METHODS
255         //
256
257         /**
258          * Creates all necessary actions.
259          */
260         private void createActions() {
261                 okAction = new AbstractAction(I18n.getMessage("jsite.general.ok")) {
262
263                         @Override
264                         @SuppressWarnings("synthetic-access")
265                         public void actionPerformed(ActionEvent actionEvent) {
266                                 actionOk();
267                         }
268                 };
269                 okAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.key-dialog.button.ok.tooltip"));
270                 okAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_ENTER);
271
272                 cancelAction = new AbstractAction(I18n.getMessage("jsite.general.cancel")) {
273
274                         @Override
275                         @SuppressWarnings("synthetic-access")
276                         public void actionPerformed(ActionEvent actionEvent) {
277                                 actionCancel();
278                         }
279                 };
280                 cancelAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.key-dialog.button.cancel.tooltip"));
281                 cancelAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_ESCAPE);
282
283                 copyFromProjectAction = new AbstractAction(I18n.getMessage("jsite.key-dialog.button.copy-from-project")) {
284
285                         @Override
286                         @SuppressWarnings("synthetic-access")
287                         public void actionPerformed(ActionEvent actionevent) {
288                                 actionCopyFromProject();
289                         }
290                 };
291                 copyFromProjectAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.key-dialog.button.copy-from-project.tooltip"));
292                 copyFromProjectAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_P);
293                 copyFromProjectAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_DOWN_MASK));
294
295                 copyFromIdentityAction = new AbstractAction(I18n.getMessage("jsite.key-dialog.button.copy-from-identity")) {
296
297                         @Override
298                         @SuppressWarnings("synthetic-access")
299                         public void actionPerformed(ActionEvent actionevent) {
300                                 actionCopyFromIdentity();
301                         }
302                 };
303                 copyFromIdentityAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.key-dialog.button.copy-from-identity.tooltip"));
304                 copyFromIdentityAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_I);
305                 copyFromIdentityAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_DOWN_MASK));
306
307                 generateAction = new AbstractAction(I18n.getMessage("jsite.key-dialog.button.generate")) {
308
309                         @Override
310                         @SuppressWarnings("synthetic-access")
311                         public void actionPerformed(ActionEvent actionEvent) {
312                                 actionGenerate();
313                         }
314                 };
315                 generateAction.putValue(Action.SHORT_DESCRIPTION, I18n.getMessage("jsite.key-dialog.button.generate.tooltip"));
316                 generateAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK));
317         }
318
319         /**
320          * Initializes the dialog and all its components.
321          */
322         private void initDialog() {
323                 createActions();
324                 JPanel dialogPanel = new JPanel(new BorderLayout(12, 12));
325                 dialogPanel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
326
327                 JPanel contentPanel = new JPanel(new GridBagLayout());
328                 dialogPanel.add(contentPanel, BorderLayout.CENTER);
329
330                 final JLabel keysLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.keys"));
331                 contentPanel.add(keysLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
332
333                 final JLabel privateKeyLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.private-key"));
334                 contentPanel.add(privateKeyLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(12, 18, 0, 0), 0, 0));
335
336                 privateKeyTextField = new JTextField();
337                 contentPanel.add(privateKeyTextField, new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 12, 0, 0), 0, 0));
338
339                 final JLabel publicKeyLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.public-key"));
340                 contentPanel.add(publicKeyLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(6, 18, 0, 0), 0, 0));
341
342                 publicKeyTextField = new JTextField();
343                 contentPanel.add(publicKeyTextField, new GridBagConstraints(1, 2, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 12, 0, 0), 0, 0));
344
345                 final JLabel copyKeysLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.copy-keys"));
346                 contentPanel.add(copyKeysLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
347
348                 final JLabel projectLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.project"));
349                 contentPanel.add(projectLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(12, 18, 0, 0), 0, 0));
350
351                 projectsComboBox = new JComboBox(new ComboBoxModelList<Project>(projects));
352                 projectsComboBox.addActionListener(new ActionListener() {
353
354                         @Override
355                         @SuppressWarnings("synthetic-access")
356                         public void actionPerformed(ActionEvent actionEvent) {
357                                 copyFromProjectAction.setEnabled(projectsComboBox.getSelectedIndex() > -1);
358                         }
359
360                 });
361                 contentPanel.add(projectsComboBox, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 12, 0, 0), 0, 0));
362
363                 JButton copyFromProjectButton = new JButton(copyFromProjectAction);
364                 contentPanel.add(copyFromProjectButton, new GridBagConstraints(2, 4, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.HORIZONTAL, new Insets(6, 12, 0, 0), 0, 0));
365
366                 final JLabel identityLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.identity"));
367                 contentPanel.add(identityLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(12, 18, 0, 0), 0, 0));
368
369                 ownIdentitiesComboBox = new JComboBox(new ComboBoxModelList<OwnIdentity>(ownIdentities));
370                 ownIdentitiesComboBox.addActionListener(new ActionListener() {
371
372                         @Override
373                         @SuppressWarnings("synthetic-access")
374                         public void actionPerformed(ActionEvent actionevent) {
375                                 copyFromIdentityAction.setEnabled(ownIdentitiesComboBox.getSelectedIndex() > -1);
376                         }
377                 });
378                 ownIdentitiesComboBox.setRenderer(new DefaultListCellRenderer() {
379
380                         @Override
381                         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
382                                 super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
383                                 if (value == null) {
384                                         setText("");
385                                 } else {
386                                         OwnIdentity ownIdentity = (OwnIdentity) value;
387                                         setText(String.format("%s (%s)", ownIdentity.getNickname(), ownIdentity.getRequestUri().substring(0, ownIdentity.getRequestUri().indexOf(','))));
388                                 }
389                                 return this;
390                         }
391                 });
392                 contentPanel.add(ownIdentitiesComboBox, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 12, 0, 0), 0, 0));
393
394                 JButton copyFromIdentityButton = new JButton(copyFromIdentityAction);
395                 contentPanel.add(copyFromIdentityButton, new GridBagConstraints(2, 5, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_END, GridBagConstraints.HORIZONTAL, new Insets(6, 12, 0, 0), 0, 0));
396
397                 final JLabel actionsLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.actions"));
398                 contentPanel.add(actionsLabel, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
399
400                 JPanel actionButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 12, 12));
401                 actionButtonPanel.setBorder(BorderFactory.createEmptyBorder(-12, -12, -12, -12));
402                 contentPanel.add(actionButtonPanel, new GridBagConstraints(0, 7, 3, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(12, 18, 0, 0), 0, 0));
403
404                 actionButtonPanel.add(new JButton(generateAction));
405
406                 JPanel separatorPanel = new JPanel(new BorderLayout(12, 12));
407                 dialogPanel.add(separatorPanel, BorderLayout.PAGE_END);
408                 separatorPanel.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.PAGE_START);
409
410                 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 12, 12));
411                 buttonPanel.setBorder(BorderFactory.createEmptyBorder(-12, -12, -12, -12));
412                 separatorPanel.add(buttonPanel, BorderLayout.CENTER);
413                 buttonPanel.add(new JButton(okAction));
414                 buttonPanel.add(new JButton(cancelAction));
415
416                 I18nContainer.getInstance().registerRunnable(new Runnable() {
417
418                         @Override
419                         public void run() {
420                                 keysLabel.setText(I18n.getMessage("jsite.key-dialog.label.keys"));
421                                 privateKeyLabel.setText(I18n.getMessage("jsite.key-dialog.label.private-key"));
422                                 publicKeyLabel.setText(I18n.getMessage("jsite.key-dialog.label.public-key"));
423                                 copyKeysLabel.setText(I18n.getMessage("jsite.key-dialog.label.copy-keys"));
424                                 identityLabel.setText(I18n.getMessage("jsite.key-dialog.label.identity"));
425                                 projectLabel.setText(I18n.getMessage("jsite.key-dialog.label.project"));
426                                 actionsLabel.setText(I18n.getMessage("jsite.key-dialog.label.actions"));
427                         }
428                 });
429
430                 getContentPane().add(dialogPanel, BorderLayout.CENTER);
431                 pack();
432                 setResizable(false);
433         }
434
435         //
436         // PRIVATE ACTIONS
437         //
438
439         /**
440          * Quits the dialog, accepting all changes.
441          */
442         private void actionOk() {
443                 publicKey = publicKeyTextField.getText();
444                 privateKey = privateKeyTextField.getText();
445                 cancelled = false;
446                 setVisible(false);
447         }
448
449         /**
450          * Quits the dialog, discarding all changes.
451          */
452         private void actionCancel() {
453                 cancelled = true;
454                 setVisible(false);
455         }
456
457         /**
458          * Copies the public and private key from the selected project.
459          */
460         private void actionCopyFromProject() {
461                 Project project = (Project) projectsComboBox.getSelectedItem();
462                 if (project == null) {
463                         return;
464                 }
465                 setPublicKey(project.getRequestURI());
466                 setPrivateKey(project.getInsertURI());
467         }
468
469         /**
470          * Copies the public and private key from the selected identity.
471          */
472         private void actionCopyFromIdentity() {
473                 OwnIdentity ownIdentity = (OwnIdentity) ownIdentitiesComboBox.getSelectedItem();
474                 if (ownIdentity == null) {
475                         return;
476                 }
477                 setPublicKey(ownIdentity.getRequestUri());
478                 setPrivateKey(ownIdentity.getInsertUri());
479         }
480
481         /**
482          * Generates a new key pair.
483          */
484         private void actionGenerate() {
485                 if (JOptionPane.showConfirmDialog(this, I18n.getMessage("jsite.project.warning.generate-new-key"), null, JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) {
486                         return;
487                 }
488                 String[] keyPair = null;
489                 try {
490                         keyPair = freenetInterface.generateKeyPair();
491                 } catch (IOException ioe1) {
492                         JOptionPane.showMessageDialog(this, MessageFormat.format(I18n.getMessage("jsite.project.keygen.io-error"), ioe1.getMessage()), null, JOptionPane.ERROR_MESSAGE);
493                         return;
494                 }
495                 publicKeyTextField.setText(keyPair[1].substring(keyPair[1].indexOf('@') + 1, keyPair[1].lastIndexOf('/')));
496                 privateKeyTextField.setText(keyPair[0].substring(keyPair[0].indexOf('@') + 1, keyPair[0].lastIndexOf('/')));
497                 pack();
498         }
499
500 }