9797708d27de7da54ce15f40cc454517d6ebbd05
[jSite.git] / src / main / java / de / todesbaum / jsite / gui / KeyDialog.java
1 /*
2  * jSite - KeyDialog.java - Copyright © 2010–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.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                 synchronized (projects) {
352                         projectsComboBox = new JComboBox(new ComboBoxModelList<Project>(projects));
353                 }
354                 projectsComboBox.addActionListener(new ActionListener() {
355
356                         @Override
357                         @SuppressWarnings("synthetic-access")
358                         public void actionPerformed(ActionEvent actionEvent) {
359                                 copyFromProjectAction.setEnabled(projectsComboBox.getSelectedIndex() > -1);
360                         }
361
362                 });
363                 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));
364
365                 JButton copyFromProjectButton = new JButton(copyFromProjectAction);
366                 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));
367
368                 final JLabel identityLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.identity"));
369                 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));
370
371                 ownIdentitiesComboBox = new JComboBox(new ComboBoxModelList<OwnIdentity>(ownIdentities));
372                 ownIdentitiesComboBox.addActionListener(new ActionListener() {
373
374                         @Override
375                         @SuppressWarnings("synthetic-access")
376                         public void actionPerformed(ActionEvent actionevent) {
377                                 copyFromIdentityAction.setEnabled(ownIdentitiesComboBox.getSelectedIndex() > -1);
378                         }
379                 });
380                 ownIdentitiesComboBox.setRenderer(new DefaultListCellRenderer() {
381
382                         @Override
383                         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
384                                 super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
385                                 if (value == null) {
386                                         setText("");
387                                 } else {
388                                         OwnIdentity ownIdentity = (OwnIdentity) value;
389                                         setText(String.format("%s (%s)", ownIdentity.getNickname(), ownIdentity.getRequestUri().substring(0, ownIdentity.getRequestUri().indexOf(','))));
390                                 }
391                                 return this;
392                         }
393                 });
394                 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));
395
396                 JButton copyFromIdentityButton = new JButton(copyFromIdentityAction);
397                 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));
398
399                 final JLabel actionsLabel = new JLabel(I18n.getMessage("jsite.key-dialog.label.actions"));
400                 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));
401
402                 JPanel actionButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 12, 12));
403                 actionButtonPanel.setBorder(BorderFactory.createEmptyBorder(-12, -12, -12, -12));
404                 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));
405
406                 actionButtonPanel.add(new JButton(generateAction));
407
408                 JPanel separatorPanel = new JPanel(new BorderLayout(12, 12));
409                 dialogPanel.add(separatorPanel, BorderLayout.PAGE_END);
410                 separatorPanel.add(new JSeparator(SwingConstants.HORIZONTAL), BorderLayout.PAGE_START);
411
412                 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 12, 12));
413                 buttonPanel.setBorder(BorderFactory.createEmptyBorder(-12, -12, -12, -12));
414                 separatorPanel.add(buttonPanel, BorderLayout.CENTER);
415                 buttonPanel.add(new JButton(okAction));
416                 buttonPanel.add(new JButton(cancelAction));
417
418                 I18nContainer.getInstance().registerRunnable(new Runnable() {
419
420                         @Override
421                         public void run() {
422                                 keysLabel.setText(I18n.getMessage("jsite.key-dialog.label.keys"));
423                                 privateKeyLabel.setText(I18n.getMessage("jsite.key-dialog.label.private-key"));
424                                 publicKeyLabel.setText(I18n.getMessage("jsite.key-dialog.label.public-key"));
425                                 copyKeysLabel.setText(I18n.getMessage("jsite.key-dialog.label.copy-keys"));
426                                 identityLabel.setText(I18n.getMessage("jsite.key-dialog.label.identity"));
427                                 projectLabel.setText(I18n.getMessage("jsite.key-dialog.label.project"));
428                                 actionsLabel.setText(I18n.getMessage("jsite.key-dialog.label.actions"));
429                         }
430                 });
431
432                 getContentPane().add(dialogPanel, BorderLayout.CENTER);
433                 pack();
434                 setResizable(false);
435         }
436
437         //
438         // PRIVATE ACTIONS
439         //
440
441         /**
442          * Quits the dialog, accepting all changes.
443          */
444         private void actionOk() {
445                 publicKey = publicKeyTextField.getText();
446                 privateKey = privateKeyTextField.getText();
447                 cancelled = false;
448                 setVisible(false);
449         }
450
451         /**
452          * Quits the dialog, discarding all changes.
453          */
454         private void actionCancel() {
455                 cancelled = true;
456                 setVisible(false);
457         }
458
459         /**
460          * Copies the public and private key from the selected project.
461          */
462         private void actionCopyFromProject() {
463                 Project project = (Project) projectsComboBox.getSelectedItem();
464                 if (project == null) {
465                         return;
466                 }
467                 setPublicKey(project.getRequestURI());
468                 setPrivateKey(project.getInsertURI());
469         }
470
471         /**
472          * Copies the public and private key from the selected identity.
473          */
474         private void actionCopyFromIdentity() {
475                 OwnIdentity ownIdentity = (OwnIdentity) ownIdentitiesComboBox.getSelectedItem();
476                 if (ownIdentity == null) {
477                         return;
478                 }
479                 setPublicKey(ownIdentity.getRequestUri());
480                 setPrivateKey(ownIdentity.getInsertUri());
481         }
482
483         /**
484          * Generates a new key pair.
485          */
486         private void actionGenerate() {
487                 if (JOptionPane.showConfirmDialog(this, I18n.getMessage("jsite.project.warning.generate-new-key"), null, JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) {
488                         return;
489                 }
490                 String[] keyPair = null;
491                 try {
492                         keyPair = freenetInterface.generateKeyPair();
493                 } catch (IOException ioe1) {
494                         JOptionPane.showMessageDialog(this, MessageFormat.format(I18n.getMessage("jsite.project.keygen.io-error"), ioe1.getMessage()), null, JOptionPane.ERROR_MESSAGE);
495                         return;
496                 }
497                 publicKeyTextField.setText(keyPair[1].substring(keyPair[1].indexOf('@') + 1, keyPair[1].lastIndexOf('/')));
498                 privateKeyTextField.setText(keyPair[0].substring(keyPair[0].indexOf('@') + 1, keyPair[0].lastIndexOf('/')));
499                 pack();
500         }
501
502 }