altosui/telegps: Undo the frequency/telemetry menu changes
[fw/altos] / telegps / TeleGPS.java
1 /*
2  * Copyright © 2014 Keith Packard <keithp@keithp.com>
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; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package org.altusmetrum.telegps;
19
20 import java.awt.*;
21 import java.awt.event.*;
22 import javax.swing.*;
23 import java.io.*;
24 import java.util.concurrent.*;
25 import java.util.*;
26 import org.altusmetrum.altoslib_5.*;
27 import org.altusmetrum.altosuilib_3.*;
28
29 public class TeleGPS
30         extends AltosUIFrame
31         implements AltosFlightDisplay, AltosFontListener, AltosUnitsListener, ActionListener
32 {
33
34         static String[] telegps_icon_names = {
35                 "/telegps-16.png",
36                 "/telegps-32.png",
37                 "/telegps-48.png",
38                 "/telegps-64.png",
39                 "/telegps-128.png",
40                 "/telegps-256.png"
41         };
42
43         static { set_icon_names(telegps_icon_names); }
44
45         static AltosVoice       voice;
46
47         static AltosVoice voice() {
48                 if (voice == null)
49                         voice = new AltosVoice();
50                 return voice;
51         }
52
53         AltosFlightReader       reader;
54         TeleGPSDisplayThread    thread;
55
56         JMenuBar                menu_bar;
57
58         JMenu                   file_menu;
59         JMenu                   monitor_menu;
60         JMenu                   device_menu;
61         AltosUIFreqList         frequencies;
62         ActionListener          frequency_listener;
63
64         Container               bag;
65
66         TeleGPSStatus           telegps_status;
67         TeleGPSStatusUpdate     status_update;
68         javax.swing.Timer       status_timer;
69
70         JTabbedPane             pane;
71
72         AltosUIMap              map;
73         TeleGPSInfo             gps_info;
74         TeleGPSState            gps_state;
75         AltosInfoTable          info_table;
76
77         LinkedList<AltosFlightDisplay>  displays;
78
79         /* File menu */
80         final static String     new_command = "new";
81         final static String     graph_command = "graph";
82         final static String     export_command = "export";
83         final static String     load_maps_command = "loadmaps";
84         final static String     preferences_command = "preferences";
85         final static String     close_command = "close";
86         final static String     exit_command = "exit";
87
88         static final String[][] file_menu_entries = new String[][] {
89                 { "New Window",         new_command },
90                 { "Graph Data",         graph_command },
91                 { "Export Data",        export_command },
92                 { "Load Maps",          load_maps_command },
93                 { "Preferences",        preferences_command },
94                 { "Close",              close_command },
95                 { "Exit",               exit_command },
96         };
97
98         /* Monitor menu */
99         final static String     connect_command = "connect";
100         final static String     disconnect_command = "disconnect";
101         final static String     scan_command = "scan";
102
103         static final String[][] monitor_menu_entries = new String[][] {
104                 { "Connect Device",     connect_command },
105                 { "Disconnect",         disconnect_command },
106                 { "Scan Channels",      scan_command },
107         };
108
109         /* Device menu */
110         final static String     download_command = "download";
111         final static String     configure_command = "configure";
112         final static String     flash_command = "flash";
113
114         static final String[][] device_menu_entries = new String[][] {
115                 { "Download Data",      download_command },
116                 { "Configure Device",   configure_command },
117                 { "Flash Device",       flash_command },
118         };
119
120         void stop_display() {
121                 if (thread != null && thread.isAlive()) {
122                         thread.interrupt();
123                         try {
124                                 thread.join();
125                         } catch (InterruptedException ie) {}
126                 }
127                 thread = null;
128         }
129
130         public void reset() {
131                 for (AltosFlightDisplay display : displays)
132                         display.reset();
133         }
134
135         public void font_size_changed(int font_size) {
136                 for (AltosFlightDisplay display : displays)
137                         display.font_size_changed(font_size);
138         }
139
140         public void units_changed(boolean imperial_units) {
141                 for (AltosFlightDisplay display : displays)
142                         display.units_changed(imperial_units);
143         }
144
145         public void show(AltosState state, AltosListenerState listener_state) {
146                 try {
147                         status_update.saved_state = state;
148
149                         if (state == null)
150                                 state = new AltosState();
151
152                         int i = 0;
153                         for (AltosFlightDisplay display : displays) {
154                                 display.show(state, listener_state);
155                                 i++;
156                         }
157                 } catch (Exception ex) {
158                         System.out.printf("Exception %s\n", ex.toString());
159                         for (StackTraceElement e : ex.getStackTrace())
160                                 System.out.printf("%s\n", e.toString());
161                 }
162         }
163
164         void new_window() {
165                 new TeleGPS();
166         }
167
168         void preferences() {
169                 new TeleGPSPreferences(this, voice());
170         }
171
172         void load_maps() {
173                 new AltosUIMapPreload(this);
174         }
175
176         void disconnect() {
177                 setTitle("TeleGPS");
178                 stop_display();
179                 if (status_timer != null) {
180                         status_timer.stop();
181                         status_timer = null;
182                         status_update = null;
183                 }
184
185                 telegps_status.disable_receive();
186                 disable_frequency_menu();
187         }
188
189         void connect(AltosDevice device) {
190                 if (reader != null)
191                         disconnect();
192                 try {
193                         AltosFlightReader       reader = new AltosTelemetryReader(new AltosSerial(device));
194                         set_reader(reader, device);
195                 } catch (FileNotFoundException ee) {
196                         JOptionPane.showMessageDialog(this,
197                                                       ee.getMessage(),
198                                                       String.format ("Cannot open %s", device.toShortString()),
199                                                       JOptionPane.ERROR_MESSAGE);
200                 } catch (AltosSerialInUseException si) {
201                         JOptionPane.showMessageDialog(this,
202                                                       String.format("Device \"%s\" already in use",
203                                                                     device.toShortString()),
204                                                       "Device in use",
205                                                       JOptionPane.ERROR_MESSAGE);
206                 } catch (IOException ee) {
207                         JOptionPane.showMessageDialog(this,
208                                                       String.format ("Unknown I/O error on %s", device.toShortString()),
209                                                       "Unknown I/O error",
210                                                       JOptionPane.ERROR_MESSAGE);
211                 } catch (TimeoutException te) {
212                         JOptionPane.showMessageDialog(this,
213                                                       String.format ("Timeout on %s", device.toShortString()),
214                                                       "Timeout error",
215                                                       JOptionPane.ERROR_MESSAGE);
216                 } catch (InterruptedException ie) {
217                         JOptionPane.showMessageDialog(this,
218                                                       String.format("Interrupted %s", device.toShortString()),
219                                                       "Interrupted exception",
220                                                       JOptionPane.ERROR_MESSAGE);
221                 }
222         }
223
224         void connect() {
225                 AltosDevice     device = AltosDeviceUIDialog.show(this,
226                                                                   AltosLib.product_basestation);
227                 if (device == null)
228                         return;
229                 connect(device);
230         }
231
232         public void scan_device_selected(AltosDevice device) {
233                 connect(device);
234         }
235
236         void scan() {
237                 new AltosScanUI(this, false);
238         }
239
240         void download(){
241                 new AltosEepromManage(this, AltosLib.product_telegps);
242         }
243
244         void configure() {
245                 new TeleGPSConfig(this);
246         }
247
248         void export() {
249                 AltosDataChooser chooser;
250                 chooser = new AltosDataChooser(this);
251                 AltosStateIterable states = chooser.runDialog();
252                 if (states == null)
253                         return;
254                 new AltosCSVUI(this, states, chooser.file());
255         }
256
257         void graph() {
258                 AltosDataChooser chooser;
259                 chooser = new AltosDataChooser(this);
260                 AltosStateIterable states = chooser.runDialog();
261                 if (states == null)
262                         return;
263                 try {
264                         new TeleGPSGraphUI(states, chooser.file());
265                 } catch (InterruptedException ie) {
266                 } catch (IOException ie) {
267                 }
268         }
269
270         void flash() {
271                 AltosFlashUI.show(this);
272         }
273
274         public void actionPerformed(ActionEvent ev) {
275
276                 /* File menu */
277                 if (new_command.equals(ev.getActionCommand())) {
278                         new_window();
279                         return;
280                 }
281                 if (preferences_command.equals(ev.getActionCommand())) {
282                         preferences();
283                         return;
284                 }
285                 if (load_maps_command.equals(ev.getActionCommand())) {
286                         load_maps();
287                         return;
288                 }
289                 if (close_command.equals(ev.getActionCommand())) {
290                         close();
291                         return;
292                 }
293                 if (exit_command.equals(ev.getActionCommand()))
294                         System.exit(0);
295
296                 /* Monitor menu */
297                 if (connect_command.equals(ev.getActionCommand())) {
298                         connect();
299                         return;
300                 }
301                 if (disconnect_command.equals(ev.getActionCommand())) {
302                         disconnect();
303                         return;
304                 }
305                 if (scan_command.equals(ev.getActionCommand())) {
306                         scan();
307                         return;
308                 }
309
310                 /* Device menu */
311                 if (download_command.equals(ev.getActionCommand())) {
312                         download();
313                         return;
314                 }
315                 if (configure_command.equals(ev.getActionCommand())) {
316                         configure();
317                         return;
318                 }
319                 if (export_command.equals(ev.getActionCommand())) {
320                         export();
321                         return;
322                 }
323                 if (graph_command.equals(ev.getActionCommand())) {
324                         graph();
325                         return;
326                 }
327                 if (flash_command.equals(ev.getActionCommand())) {
328                         flash();
329                         return;
330                 }
331         }
332
333         void enable_frequency_menu(int serial, final AltosFlightReader reader) {
334
335                 if (frequency_listener != null)
336                         disable_frequency_menu();
337
338                 frequency_listener = new ActionListener() {
339                                 public void actionPerformed(ActionEvent e) {
340                                         double frequency = frequencies.frequency();
341                                         try {
342                                                 reader.set_frequency(frequency);
343                                         } catch (TimeoutException te) {
344                                         } catch (InterruptedException ie) {
345                                         }
346                                         reader.save_frequency();
347                                 }
348                         };
349
350                 frequencies.addActionListener(frequency_listener);
351                 frequencies.set_product("Monitor");
352                 frequencies.set_serial(serial);
353                 frequencies.set_frequency(AltosUIPreferences.frequency(serial));
354                 frequencies.setEnabled(true);
355
356         }
357
358         void disable_frequency_menu() {
359                 if (frequency_listener != null) {
360                         frequencies.removeActionListener(frequency_listener);
361                         frequencies.setEnabled(false);
362                         frequency_listener = null;
363                 }
364
365         }
366
367         public void set_reader(AltosFlightReader reader, AltosDevice device) {
368                 status_update = new TeleGPSStatusUpdate(telegps_status);
369
370                 status_timer = new javax.swing.Timer(100, status_update);
371                 status_timer.start();
372
373                 setTitle(String.format("TeleGPS %s", reader.name));
374                 thread = new TeleGPSDisplayThread(this, voice(), this, reader);
375                 thread.start();
376
377                 if (device != null)
378                         enable_frequency_menu(device.getSerial(), reader);
379         }
380
381         static int      number_of_windows;
382
383         static public void add_window() {
384                 ++number_of_windows;
385         }
386
387         static public void subtract_window() {
388                 --number_of_windows;
389                 if (number_of_windows == 0)
390                         System.exit(0);
391         }
392
393         private void close() {
394                 disconnect();
395                 AltosUIPreferences.unregister_font_listener(this);
396                 AltosPreferences.unregister_units_listener(this);
397                 setVisible(false);
398                 dispose();
399                 subtract_window();
400         }
401
402         private void add_menu(JMenu menu, String label, String action) {
403                 JMenuItem       item = new JMenuItem(label);
404                 menu.add(item);
405                 item.addActionListener(this);
406                 item.setActionCommand(action);
407         }
408
409
410         private JMenu make_menu(String label, String[][] items) {
411                 JMenu   menu = new JMenu(label);
412                 for (int i = 0; i < items.length; i++) {
413                         if (MAC_OS_X) {
414                                 if (items[i][1].equals("exit"))
415                                         continue;
416                                 if (items[i][1].equals("preferences"))
417                                         continue;
418                         }
419                         add_menu(menu, items[i][0], items[i][1]);
420                 }
421                 menu_bar.add(menu);
422                 return menu;
423         }
424
425         /* OSXAdapter interfaces */
426         public void macosx_file_handler(String path) {
427                 process_graph(new File(path));
428         }
429
430         public void macosx_quit_handler() {
431                 System.exit(0);
432         }
433
434         public void macosx_preferences_handler() {
435                 preferences();
436         }
437
438         public TeleGPS() {
439
440                 AltosUIPreferences.set_component(this);
441
442                 register_for_macosx_events();
443
444                 reader = null;
445
446                 bag = getContentPane();
447                 bag.setLayout(new GridBagLayout());
448
449                 GridBagConstraints c = new GridBagConstraints();
450
451                 setTitle("TeleGPS");
452
453                 menu_bar = new JMenuBar();
454                 setJMenuBar(menu_bar);
455
456                 file_menu = make_menu("File", file_menu_entries);
457                 monitor_menu = make_menu("Monitor", monitor_menu_entries);
458                 device_menu = make_menu("Device", device_menu_entries);
459
460                 frequencies = new AltosUIFreqList();
461                 frequencies.setEnabled(false);
462                 c.gridx = 0;
463                 c.gridy = 0;
464                 c.fill = GridBagConstraints.NONE;
465                 c.anchor = GridBagConstraints.WEST;
466                 c.weightx = 0;
467                 c.gridwidth = 1;
468                 bag.add(frequencies, c);
469
470                 displays = new LinkedList<AltosFlightDisplay>();
471
472                 int serial = -1;
473
474                 /* TeleGPS status is always visible */
475                 telegps_status = new TeleGPSStatus();
476                 c.gridx = 0;
477                 c.gridy = 1;
478                 c.fill = GridBagConstraints.HORIZONTAL;
479                 c.weightx = 1;
480                 c.gridwidth = 2;
481                 bag.add(telegps_status, c);
482                 c.gridwidth = 1;
483                 displays.add(telegps_status);
484
485
486                 /* The rest of the window uses a tabbed pane to
487                  * show one of the alternate data views
488                  */
489                 pane = new JTabbedPane();
490
491                 /* Make the tabbed pane use the rest of the window space */
492                 c.gridx = 0;
493                 c.gridy = 2;
494                 c.fill = GridBagConstraints.BOTH;
495                 c.weightx = 1;
496                 c.weighty = 1;
497                 c.gridwidth = 2;
498                 bag.add(pane, c);
499
500                 map = new AltosUIMap();
501                 pane.add(map.getName(), map);
502                 displays.add(map);
503
504                 gps_info = new TeleGPSInfo();
505                 pane.add(gps_info.getName(), gps_info);
506                 displays.add(gps_info);
507
508                 gps_state = new TeleGPSState();
509                 pane.add(gps_state.getName(), gps_state);
510                 displays.add(gps_state);
511
512                 info_table = new AltosInfoTable();
513                 pane.add("Table", info_table);
514                 displays.add(info_table);
515
516                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
517
518                 AltosUIPreferences.register_font_listener(this);
519                 AltosPreferences.register_units_listener(this);
520
521                 addWindowListener(new WindowAdapter() {
522                                 @Override
523                                 public void windowClosing(WindowEvent e) {
524                                         close();
525                                 }
526                         });
527
528                 pack();
529                 setVisible(true);
530
531                 add_window();
532         }
533
534         public TeleGPS(AltosFlightReader reader) {
535                 this();
536                 set_reader(reader, null);
537         }
538
539         public TeleGPS(AltosDevice device) {
540                 this();
541                 connect(device);
542         }
543
544         static AltosStateIterable record_iterable(File file) {
545                 FileInputStream in;
546                 try {
547                         in = new FileInputStream(file);
548                 } catch (Exception e) {
549                         System.out.printf("Failed to open file '%s'\n", file);
550                         return null;
551                 }
552                 if (file.getName().endsWith("telem"))
553                         return new AltosTelemetryFile(in);
554                 else
555                         return new AltosEepromFile(in);
556         }
557
558         static AltosReplayReader replay_file(File file) {
559                 AltosStateIterable states = record_iterable(file);
560                 if (states == null)
561                         return null;
562                 return new AltosReplayReader(states.iterator(), file);
563         }
564
565         static boolean process_graph(File file) {
566                 AltosStateIterable states = record_iterable(file);
567                 if (states == null)
568                         return false;
569                 try {
570                         new TeleGPSGraphUI(states, file);
571                 } catch (Exception e) {
572                         return false;
573                 }
574                 return true;
575         }
576
577         static boolean process_replay(File file) {
578                 AltosReplayReader new_reader = replay_file(file);
579                 if (new_reader == null)
580                         return false;
581
582                 new TeleGPS(new_reader);
583                 return true;
584         }
585
586         static final int process_none = 0;
587         static final int process_csv = 1;
588         static final int process_kml = 2;
589         static final int process_graph = 3;
590         static final int process_replay = 4;
591         static final int process_summary = 5;
592         static final int process_cat = 6;
593
594         public static boolean load_library(Frame frame) {
595                 if (!AltosUILib.load_library()) {
596                         JOptionPane.showMessageDialog(frame,
597                                                       String.format("No AltOS library in \"%s\"",
598                                                                     System.getProperty("java.library.path","<undefined>")),
599                                                       "Cannot load device access library",
600                                                       JOptionPane.ERROR_MESSAGE);
601                         return false;
602                 }
603                 return true;
604         }
605
606         public static void help(int code) {
607                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
608                 System.out.printf("  Options:\n");
609                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
610                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
611                 System.out.printf("    --graph <filename>\t\tgraph a flight\n");
612                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
613                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
614                 System.exit(code);
615         }
616
617         public static void main(String[] args) {
618                 int     errors = 0;
619
620                 load_library(null);
621                 try {
622                         UIManager.setLookAndFeel(AltosUIPreferences.look_and_feel());
623                 } catch (Exception e) {
624                 }
625
626                 boolean any_created = false;
627
628
629                 /* Handle batch-mode */
630                 int process = process_none;
631                 for (int i = 0; i < args.length; i++) {
632                         if (args[i].equals("--help"))
633                                 help(0);
634                         else if (args[i].equals("--fetchmaps")) {
635                                 if (args.length < i + 3) {
636                                         help(1);
637                                 } else {
638                                         double lat = Double.parseDouble(args[i+1]);
639                                         double lon = Double.parseDouble(args[i+2]);
640                                         AltosUIMap.prefetch_maps(lat, lon);
641                                         i += 2;
642                                 }
643                         } else if (args[i].equals("--replay"))
644                                 process = process_replay;
645                         else if (args[i].equals("--kml"))
646                                 process = process_kml;
647                         else if (args[i].equals("--csv"))
648                                 process = process_csv;
649                         else if (args[i].equals("--graph"))
650                                 process = process_graph;
651                         else if (args[i].equals("--summary"))
652                                 process = process_summary;
653                         else if (args[i].equals("--cat"))
654                                 process = process_cat;
655                         else if (args[i].startsWith("--"))
656                                 help(1);
657                         else {
658                                 File file = new File(args[i]);
659                                 switch (process) {
660                                 case process_none:
661                                 case process_graph:
662                                         if (!process_graph(file))
663                                                 ++errors;
664                                         break;
665                                 case process_replay:
666                                         if (!process_replay(file))
667                                                 ++errors;
668                                         any_created = true;
669                                         break;
670                                 case process_kml:
671                                         ++errors;
672                                         break;
673                                 case process_csv:
674                                         ++errors;
675                                         break;
676                                 case process_summary:
677                                         ++errors;
678                                         break;
679                                 case process_cat:
680                                         ++errors;
681                                 }
682                         }
683                 }
684                 if (errors != 0)
685                         System.exit(errors);
686                 if (number_of_windows == 0) {
687                         java.util.List<AltosDevice> devices = AltosUSBDevice.list(AltosLib.product_basestation);
688                         if (devices != null)
689                                 for (AltosDevice device : devices) {
690                                         new TeleGPS(device);
691                                         any_created = true;
692                                 }
693                         if (number_of_windows == 0)
694                                 new TeleGPS();
695                 }
696         }
697 }