macosx: Define icons for our file types on OS X
[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         AltosFreqList           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
355                 menu_bar.add(frequencies);
356                 menu_bar.repaint();
357         }
358
359         void disable_frequency_menu() {
360                 if (frequency_listener == null)
361                         return;
362                 frequencies.removeActionListener(frequency_listener);
363                 menu_bar.remove(frequencies);
364                 menu_bar.repaint();
365                 frequency_listener = null;
366         }
367
368         public void set_reader(AltosFlightReader reader, AltosDevice device) {
369                 status_update = new TeleGPSStatusUpdate(telegps_status);
370
371                 status_timer = new javax.swing.Timer(100, status_update);
372                 status_timer.start();
373
374                 setTitle(String.format("TeleGPS %s", reader.name));
375                 thread = new TeleGPSDisplayThread(this, voice(), this, reader);
376                 thread.start();
377
378                 if (device != null)
379                         enable_frequency_menu(device.getSerial(), reader);
380         }
381
382         static int      number_of_windows;
383
384         static public void add_window() {
385                 ++number_of_windows;
386         }
387
388         static public void subtract_window() {
389                 --number_of_windows;
390                 if (number_of_windows == 0)
391                         System.exit(0);
392         }
393
394         private void close() {
395                 disconnect();
396                 AltosUIPreferences.unregister_font_listener(this);
397                 AltosPreferences.unregister_units_listener(this);
398                 setVisible(false);
399                 dispose();
400                 subtract_window();
401         }
402
403         private void add_menu(JMenu menu, String label, String action) {
404                 JMenuItem       item = new JMenuItem(label);
405                 menu.add(item);
406                 item.addActionListener(this);
407                 item.setActionCommand(action);
408         }
409
410
411         private JMenu make_menu(String label, String[][] items) {
412                 JMenu   menu = new JMenu(label);
413                 for (int i = 0; i < items.length; i++)
414                         add_menu(menu, items[i][0], items[i][1]);
415                 menu_bar.add(menu);
416                 return menu;
417         }
418
419         public TeleGPS() {
420
421                 AltosUIPreferences.set_component(this);
422
423                 reader = null;
424
425                 bag = getContentPane();
426                 bag.setLayout(new GridBagLayout());
427
428                 GridBagConstraints c = new GridBagConstraints();
429
430                 setTitle("TeleGPS");
431
432                 menu_bar = new JMenuBar();
433                 setJMenuBar(menu_bar);
434
435                 file_menu = make_menu("File", file_menu_entries);
436                 monitor_menu = make_menu("Monitor", monitor_menu_entries);
437                 device_menu = make_menu("Device", device_menu_entries);
438                 frequencies = new AltosFreqList();
439
440                 displays = new LinkedList<AltosFlightDisplay>();
441
442                 int serial = -1;
443
444                 /* TeleGPS status is always visible */
445                 telegps_status = new TeleGPSStatus();
446                 c.gridx = 0;
447                 c.gridy = 1;
448                 c.fill = GridBagConstraints.HORIZONTAL;
449                 c.weightx = 1;
450                 c.gridwidth = 2;
451                 bag.add(telegps_status, c);
452                 c.gridwidth = 1;
453                 displays.add(telegps_status);
454
455
456                 /* The rest of the window uses a tabbed pane to
457                  * show one of the alternate data views
458                  */
459                 pane = new JTabbedPane();
460
461                 /* Make the tabbed pane use the rest of the window space */
462                 c.gridx = 0;
463                 c.gridy = 2;
464                 c.fill = GridBagConstraints.BOTH;
465                 c.weightx = 1;
466                 c.weighty = 1;
467                 c.gridwidth = 2;
468                 bag.add(pane, c);
469
470                 map = new AltosUIMap();
471                 pane.add(map.getName(), map);
472                 displays.add(map);
473
474                 gps_info = new TeleGPSInfo();
475                 pane.add(gps_info.getName(), gps_info);
476                 displays.add(gps_info);
477
478                 gps_state = new TeleGPSState();
479                 pane.add(gps_state.getName(), gps_state);
480                 displays.add(gps_state);
481
482                 info_table = new AltosInfoTable();
483                 pane.add("Table", info_table);
484                 displays.add(info_table);
485
486                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
487
488                 AltosUIPreferences.register_font_listener(this);
489                 AltosPreferences.register_units_listener(this);
490
491                 addWindowListener(new WindowAdapter() {
492                                 @Override
493                                 public void windowClosing(WindowEvent e) {
494                                         close();
495                                 }
496                         });
497
498                 pack();
499                 setVisible(true);
500
501                 add_window();
502         }
503
504         public TeleGPS(AltosFlightReader reader) {
505                 this();
506                 set_reader(reader, null);
507         }
508
509         public TeleGPS(AltosDevice device) {
510                 this();
511                 connect(device);
512         }
513
514         static AltosStateIterable record_iterable(File file) {
515                 FileInputStream in;
516                 try {
517                         in = new FileInputStream(file);
518                 } catch (Exception e) {
519                         System.out.printf("Failed to open file '%s'\n", file);
520                         return null;
521                 }
522                 if (file.getName().endsWith("telem"))
523                         return new AltosTelemetryFile(in);
524                 else
525                         return new AltosEepromFile(in);
526         }
527
528         static AltosReplayReader replay_file(File file) {
529                 AltosStateIterable states = record_iterable(file);
530                 if (states == null)
531                         return null;
532                 return new AltosReplayReader(states.iterator(), file);
533         }
534
535         static boolean process_graph(File file) {
536                 AltosStateIterable states = record_iterable(file);
537                 if (states == null)
538                         return false;
539                 try {
540                         new TeleGPSGraphUI(states, file);
541                 } catch (Exception e) {
542                         return false;
543                 }
544                 return true;
545         }
546
547         static boolean process_replay(File file) {
548                 AltosReplayReader new_reader = replay_file(file);
549                 if (new_reader == null)
550                         return false;
551
552                 new TeleGPS(new_reader);
553                 return true;
554         }
555
556         static final int process_none = 0;
557         static final int process_csv = 1;
558         static final int process_kml = 2;
559         static final int process_graph = 3;
560         static final int process_replay = 4;
561         static final int process_summary = 5;
562         static final int process_cat = 6;
563
564         public static boolean load_library(Frame frame) {
565                 if (!AltosUILib.load_library()) {
566                         JOptionPane.showMessageDialog(frame,
567                                                       String.format("No AltOS library in \"%s\"",
568                                                                     System.getProperty("java.library.path","<undefined>")),
569                                                       "Cannot load device access library",
570                                                       JOptionPane.ERROR_MESSAGE);
571                         return false;
572                 }
573                 return true;
574         }
575
576         public static void help(int code) {
577                 System.out.printf("Usage: altosui [OPTION]... [FILE]...\n");
578                 System.out.printf("  Options:\n");
579                 System.out.printf("    --fetchmaps <lat> <lon>\tpre-fetch maps for site map view\n");
580                 System.out.printf("    --replay <filename>\t\trelive the glory of past flights \n");
581                 System.out.printf("    --graph <filename>\t\tgraph a flight\n");
582                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
583                 System.out.printf("    --kml\tgenerate KML output for use with Google Earth\n");
584                 System.exit(code);
585         }
586
587         public static void main(String[] args) {
588                 int     errors = 0;
589
590                 load_library(null);
591                 try {
592                         UIManager.setLookAndFeel(AltosUIPreferences.look_and_feel());
593                 } catch (Exception e) {
594                 }
595
596                 boolean any_created = false;
597
598
599                 /* Handle batch-mode */
600                 int process = process_none;
601                 for (int i = 0; i < args.length; i++) {
602                         if (args[i].equals("--help"))
603                                 help(0);
604                         else if (args[i].equals("--fetchmaps")) {
605                                 if (args.length < i + 3) {
606                                         help(1);
607                                 } else {
608                                         double lat = Double.parseDouble(args[i+1]);
609                                         double lon = Double.parseDouble(args[i+2]);
610                                         AltosUIMap.prefetch_maps(lat, lon);
611                                         i += 2;
612                                 }
613                         } else if (args[i].equals("--replay"))
614                                 process = process_replay;
615                         else if (args[i].equals("--kml"))
616                                 process = process_kml;
617                         else if (args[i].equals("--csv"))
618                                 process = process_csv;
619                         else if (args[i].equals("--graph"))
620                                 process = process_graph;
621                         else if (args[i].equals("--summary"))
622                                 process = process_summary;
623                         else if (args[i].equals("--cat"))
624                                 process = process_cat;
625                         else if (args[i].startsWith("--"))
626                                 help(1);
627                         else {
628                                 File file = new File(args[i]);
629                                 switch (process) {
630                                 case process_none:
631                                 case process_graph:
632                                         if (!process_graph(file))
633                                                 ++errors;
634                                         break;
635                                 case process_replay:
636                                         if (!process_replay(file))
637                                                 ++errors;
638                                         any_created = true;
639                                         break;
640                                 case process_kml:
641                                         ++errors;
642                                         break;
643                                 case process_csv:
644                                         ++errors;
645                                         break;
646                                 case process_summary:
647                                         ++errors;
648                                         break;
649                                 case process_cat:
650                                         ++errors;
651                                 }
652                         }
653                 }
654                 if (errors != 0)
655                         System.exit(errors);
656                 if (number_of_windows == 0) {
657                         java.util.List<AltosDevice> devices = AltosUSBDevice.list(AltosLib.product_basestation);
658                         if (devices != null)
659                                 for (AltosDevice device : devices) {
660                                         new TeleGPS(device);
661                                         any_created = true;
662                                 }
663                         if (number_of_windows == 0)
664                                 new TeleGPS();
665                 }
666         }
667 }