1 package com.nilhcem.fakesmtp.gui;
2
3 import com.nilhcem.fakesmtp.core.ArgsHandler;
4 import com.nilhcem.fakesmtp.core.Configuration;
5 import com.nilhcem.fakesmtp.core.exception.UncaughtExceptionHandler;
6 import com.nilhcem.fakesmtp.model.UIModel;
7 import com.nilhcem.fakesmtp.server.SMTPServerHandler;
8 import org.slf4j.LoggerFactory;
9
10 import javax.swing.JFrame;
11 import java.awt.Dimension;
12 import java.awt.Toolkit;
13 import java.awt.event.WindowAdapter;
14 import java.awt.event.WindowEvent;
15 import java.io.IOException;
16
17
18
19
20
21
22
23 public final class MainFrame extends WindowAdapter {
24
25 private final JFrame mainFrame = new JFrame(Configuration.INSTANCE.get("application.title"));
26 private final MenuBar menu = new MenuBar();
27 private final MainPanel panel = new MainPanel(menu);
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 public MainFrame() {
47 ((UncaughtExceptionHandler) Thread.getDefaultUncaughtExceptionHandler()).setParentComponent(panel.get());
48 Dimension frameSize = new Dimension(Integer.parseInt(Configuration.INSTANCE.get("application.min.width")),
49 Integer.parseInt(Configuration.INSTANCE.get("application.min.height")));
50
51 mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
52 mainFrame.addWindowListener(this);
53 mainFrame.setSize(frameSize);
54 mainFrame.setMinimumSize(frameSize);
55
56 mainFrame.setJMenuBar(menu.get());
57 mainFrame.getContentPane().add(panel.get());
58 mainFrame.setLocationRelativeTo(null);
59 mainFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().
60 getResource(Configuration.INSTANCE.get("application.icon.path"))));
61
62
63 Runtime.getRuntime().addShutdownHook(new Thread() {
64 public void run() {
65 SMTPServerHandler.INSTANCE.stopServer();
66 }
67 });
68
69
70 String smtpPort = ArgsHandler.INSTANCE.getPort();
71 if (smtpPort == null) {
72 smtpPort = Configuration.INSTANCE.get("smtp.default.port");
73 }
74 panel.getPortText().setText(smtpPort);
75
76
77 String emailsDir = ArgsHandler.INSTANCE.getOutputDirectory();
78 if (emailsDir == null) {
79 emailsDir = Configuration.INSTANCE.get("emails.default.dir");
80 }
81 if (emailsDir != null && !emailsDir.isEmpty()) {
82 panel.getSaveMsgTextField().get().setText(emailsDir);
83 UIModel.INSTANCE.setSavePath(emailsDir);
84 }
85
86 mainFrame.setVisible(true);
87 }
88
89 @Override
90 public void windowClosing(WindowEvent e) {
91
92 Configuration.INSTANCE.set("smtp.default.port", panel.getPortText().get().getText());
93 Configuration.INSTANCE.set("emails.default.dir", panel.getSaveMsgTextField().get().getText());
94 try {
95 Configuration.INSTANCE.saveToUserProfile();
96 } catch (IOException ex) {
97 LoggerFactory.getLogger(MainFrame.class).error("Could not save configuration", ex);
98 }
99
100 if (SMTPServerHandler.INSTANCE.getSmtpServer().isRunning()) {
101 SMTPServerHandler.INSTANCE.getSmtpServer().stop();
102 }
103 mainFrame.dispose();
104 }
105 }