Made it connect/disconnect more correctly.
[FinalKeyGui.git] / src / fkgui / MainWin.java
1 package fkgui;
2
3
4 import  java.util.prefs.*;
5 import java.awt.*;
6 import java.awt.event.ActionEvent;
7 import java.awt.event.ActionListener;
8 import java.beans.PropertyChangeEvent;
9 import java.beans.PropertyChangeListener;
10
11 import javax.swing.UIManager;
12 import javax.swing.UnsupportedLookAndFeelException;
13
14 import org.eclipse.swt.widgets.Display;
15 import org.eclipse.swt.widgets.Shell;
16 import org.eclipse.swt.widgets.Button;
17 import org.eclipse.swt.SWT;
18 import org.eclipse.swt.events.SelectionAdapter;
19 import org.eclipse.swt.events.SelectionEvent;
20 import org.eclipse.swt.events.ShellEvent;
21 import org.eclipse.swt.events.ShellListener;
22 import org.eclipse.swt.widgets.Text;
23 import org.eclipse.swt.widgets.Label;
24 import org.eclipse.swt.widgets.Control;
25 import org.eclipse.wb.swt.SWTResourceManager;
26
27 import fkgui.SerialWorker.SerialState;
28
29 public class MainWin implements ConsoleMsg {
30
31         protected Shell shell;
32         private Text txtPsw;
33         public TrayIcon trayIcon;
34         public PopupMenu popup;
35         public MenuItem showMain;
36         public MenuItem hideMain;
37
38         public Text txtLog;
39         public Button btnStart;
40         public Label lblPort;
41         public Label lblPassword;
42
43         private Text txtDev;
44         Preferences prefs;
45         MainWin mySelf;
46         private SerialState lastState = SerialState.Disconnected;
47         
48         SerialWorker fkSerial;
49         private boolean sysTrayIconVisible;
50
51         
52         static final String PREF_PORT ="lastUsedPortPref";
53         static final String DEFAULT_DEVICE = "/dev/FinalKey";
54         static final String PREF_AUTOHIDE = "hideMainWinAfterConnect";
55  
56         
57         /**
58          * Launch the application.
59          * @param args
60          */
61         public static void main(String[] args) {
62
63                 try {
64                         MainWin window = new MainWin();
65                         window.open();
66                 } catch (Exception e) {
67                         e.printStackTrace();
68                 }
69                 
70         }
71
72         /**
73          * Open the window.
74          */
75         public void open() {
76                 Display display = Display.getDefault();
77                 createContents();
78                 shell.open();
79                 shell.layout();
80                 createSysTrayIcon();
81                 serialEvent(SerialState.Disconnected);
82
83                 while (!shell.isDisposed()) {
84                         if (!display.readAndDispatch()) {
85                                 display.sleep();                                
86                         }
87                 }
88         }
89         
90         public void log( String str )
91         {
92                 txtLog.append(str+"\n");
93                 txtLog.redraw();
94                 shell.redraw();
95                 System.out.println(str);
96         }
97
98         /**
99          * Create a systemTray icon
100          */
101         private void createSysTrayIcon()
102         {
103                 sysTrayIconVisible=true;
104         //Check the SystemTray is supported
105         if (!SystemTray.isSupported()) {
106             log("SystemTray is not supported, app is useless");
107             return;
108         }
109         
110         try {
111                         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
112                 } catch (ClassNotFoundException e1) {
113                         // TODO Auto-generated catch block
114                         e1.printStackTrace();
115                 } catch (InstantiationException e1) {
116                         // TODO Auto-generated catch block
117                         e1.printStackTrace();
118                 } catch (IllegalAccessException e1) {
119                         // TODO Auto-generated catch block
120                         e1.printStackTrace();
121                 } catch (UnsupportedLookAndFeelException e1) {
122                         // TODO Auto-generated catch block
123                         e1.printStackTrace();
124                 }
125
126         popup = new PopupMenu();
127         trayIcon =
128                 new TrayIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource("finalkey.png")));
129         trayIcon.setImageAutoSize(true);
130         final SystemTray tray = SystemTray.getSystemTray();
131        
132         // Create a pop-up menu components
133         showMain = new MenuItem("Show FinalKey");
134         hideMain = new MenuItem("Hide FinalKey");
135
136         showMain.addActionListener(new ActionListener() {
137                         @Override
138                         public void actionPerformed(ActionEvent e) {
139                                 Display.getDefault().syncExec( new Runnable(){
140                                         
141                                         public void run()
142                                         {
143                                 //Remove myself and make main window visible
144                                                 showFromTray();
145                                         }
146                                 } );
147                         }
148                                 
149                 });
150         
151         hideMain.addActionListener(new ActionListener() {
152                         @Override
153                         public void actionPerformed(ActionEvent e) {
154                                 Display.getDefault().syncExec( new Runnable(){
155                                         
156                                         public void run()
157                                         {
158                                                 hideToTray();
159                                         }
160                                 } );
161                         }
162                                 
163                 });
164
165         clearSystray();
166
167
168         trayIcon.setPopupMenu(popup);
169        
170         try {
171             tray.add(trayIcon);
172         } catch (AWTException e) {
173                 log("TrayIcon could not be added.");
174         }       
175         
176         }
177         
178         private void hideToTray()
179         {
180                 popup.remove(0);
181                 popup.insert(showMain, 0);
182                 shell.setVisible(false);
183         }
184         
185         private void showFromTray()
186         {
187                 popup.remove(0);
188                 popup.insert(hideMain, 0);
189                 shell.setVisible(true);
190                 shell.forceActive();
191         }
192         
193         private void destroySysTrayIcon()
194         {
195                 sysTrayIconVisible=false;
196                 SystemTray.getSystemTray().remove(trayIcon);
197         }
198         
199         private void clearSystray() {
200                         popup.removeAll();
201                 //Add components to pop-up menu
202                         if(shell.isVisible()==true)
203                         {
204                                 popup.add(hideMain);
205                         } else {
206                                 popup.add(showMain);
207                         }
208                 popup.addSeparator();
209         }
210
211         public void shutDownApp()
212         {
213                 if(fkSerial != null)
214                 {
215                         fkSerial.disconnect();
216                 }
217                 if(sysTrayIconVisible == true)
218                 {
219                         destroySysTrayIcon();
220                 }
221                 System.exit(0);
222         }
223         
224         /**
225          * Create contents of the window.
226          */
227         protected void createContents() {
228                 shell = new Shell();
229                 shell.setImage(SWTResourceManager.getImage(MainWin.class, "/fkgui/finalkey.png"));
230                 shell.setSize(450, 495);
231                 shell.setText("Final Key (Not connected)");
232                 
233                 shell.setLayout(null);
234
235                 
236                 prefs = Preferences.userNodeForPackage(this.getClass());
237                 
238
239                 mySelf = this;
240                 
241
242                 btnStart = new Button(shell, SWT.NONE);
243                 btnStart.setBounds(330, 10, 104, 52);
244                 btnStart.addSelectionListener(new SelectionAdapter() {
245                         public void widgetSelected(SelectionEvent e) {
246                                 
247                                 if( fkSerial!=null && fkSerial.state == SerialState.Connected )
248                                 {
249                                         fkSerial.disconnect();
250                                 } else {
251                                         fkSerial = new SerialWorker(mySelf);
252                                         prefs.put(PREF_PORT, txtDev.getText() );
253                                         fkSerial.connect(txtDev.getText(),txtPsw.getText());
254                                         txtPsw.setText("");
255                                 }
256                         }
257                 });
258 //              btnStart.setText("Connect");
259                 lblPassword = new Label(shell, SWT.NONE);
260                 lblPassword.setText("Password");
261                 lblPassword.setBounds(10, 39, 85, 23);
262                 
263                 txtPsw = new Text(shell, SWT.SINGLE | SWT.BORDER | SWT.PASSWORD);
264                 txtPsw.setBounds(101, 39, 223, 23);
265                 
266                 txtLog = new Text(shell, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
267                 txtLog.setEditable(false);
268                 txtLog.setBounds(10, 68, 424, 388);
269                 
270                 lblPort = new Label(shell, SWT.NONE);
271                 lblPort.setBounds(10, 10, 76, 23);
272                 lblPort.setText("Port");
273                 
274                 txtDev = new Text(shell, SWT.BORDER);
275                 txtDev.setFont(SWTResourceManager.getFont("Cantarell", 9, SWT.NORMAL));
276                 txtDev.setText( prefs.get(PREF_PORT, DEFAULT_DEVICE));
277                 txtDev.setBounds(101, 10, 223, 23);
278                 shell.setTabList(new Control[]{txtPsw, btnStart});
279                 
280                 log("Welcome!\nConnect your Final Key and enter password.\nThen press connect.\nPress the button when it blinks.\n----------\n");
281
282
283                 shell.addShellListener( new ShellListener() {
284                         
285                         public void shellIconified(ShellEvent e) {
286
287                         }
288
289                         public void shellDeiconified(ShellEvent e) {
290                                 // TODO Auto-generated method stub
291                                 
292                         }
293                         
294                         public void shellDeactivated(ShellEvent e) {
295                                 // TODO Auto-generated method stub
296                                 
297                         }
298                         
299                         public void shellClosed(ShellEvent e) {
300                                 shutDownApp();
301                                 
302                         }
303                         
304                         public void shellActivated(ShellEvent e) {
305                                 // TODO Auto-generated method stub
306                                 
307                         }
308                 } );
309                 
310
311
312         }
313
314
315
316         @Override
317         public PopupMenu getPopup() {
318                 return this.popup;
319         }
320
321         @Override
322         public void serialEvent(SerialState state) {
323                 switch(state)
324                 {
325                 case Connected:
326                         btnStart.setText("Disconnect");
327                         btnStart.setVisible(true);
328                         //Should we hide?
329                         if( prefs.getBoolean(PREF_AUTOHIDE, false) == true)
330                         {
331                                 hideToTray();
332                         }
333                         log("* Connected *");
334                         break;
335                 case Connecting:
336                         shell.setText("Final Key (Connecting...)");
337                         txtPsw.setVisible(false);
338                         txtDev.setVisible(false);
339                         btnStart.setVisible(false);
340                         lblPort.setVisible(false);
341                         lblPassword.setVisible(false);
342                         break;
343                 case Disconnected:
344                         fkSerial=null;
345                         shell.setText("Final Key (Not connected)");
346                         txtPsw.setVisible(true);
347                         txtDev.setVisible(true);
348                         btnStart.setText("Connect");
349                         btnStart.setVisible(true);
350                         lblPort.setVisible(true);
351                         lblPassword.setVisible(true);
352                         clearSystray();
353                         if(lastState != state)
354                         {
355                                 log("* Disconnected *");
356                         }
357                         break;
358                 default:
359                         break;
360                 }
361                 lastState=state;
362                 
363         }
364
365
366 }