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