c34e874aaaa05b2708a17ef2f9c20ae2b65f143c
[fw/altos] / micropeak / MicroPeak.java
1 /*
2  * Copyright © 2012 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; 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, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
17  */
18
19 package org.altusmetrum.micropeak;
20
21 import java.awt.*;
22 import java.awt.event.*;
23 import javax.swing.*;
24 import java.io.*;
25 import java.util.concurrent.*;
26 import java.util.*;
27 import org.altusmetrum.altoslib_14.*;
28 import org.altusmetrum.altosuilib_14.*;
29
30 public class MicroPeak extends MicroFrame implements ActionListener, ItemListener, AltosFilterListener {
31
32         File            filename;
33         AltosGraph      graph;
34         AltosUIEnable   enable;
35         AltosFlightStatsTable   statsTable;
36         MicroRaw        raw;
37         MicroData       data;
38         Container       container;
39         JTabbedPane     pane;
40         JMenuBar        menu_bar;
41         static int      number_of_windows;
42
43         /* File menu */
44         final static String     open_command = "open";
45         final static String     save_command = "save";
46         final static String     export_command = "export";
47         final static String     preferences_command = "preferences";
48         final static String     close_command = "close";
49         final static String     exit_command = "exit";
50
51         static final String[][] file_menu_entries = new String[][] {
52                 { "Open",               open_command },
53                 { "Save a Copy",        save_command },
54                 { "Export Data",        export_command },
55                 { "Preferences",        preferences_command },
56                 { "Close",              close_command },
57                 { "Exit",               exit_command },
58         };
59
60         /* Download menu */
61         final static String     download_command = "download";
62         final static String     download_label = "Download";
63
64         static final String[][] download_menu_entries = new String[][] {
65                 { download_label,       download_command }
66         };
67
68         MicroPeak SetData(MicroData data) {
69                 MicroPeak       mp = this;
70                 if (this.data != null) {
71                         mp = new MicroPeak();
72                         return mp.SetData(data);
73                 }
74                 this.data = data;
75                 if (data.flight_series == null)
76                         System.out.printf("no data in flight\n");
77                 if (data.flight_stats == null)
78                         System.out.printf("no stats in flight\n");
79                 graph.set_data(data.flight_stats, data.flight_series);
80                 statsTable.set_stats(data.flight_stats);
81                 raw.setData(data);
82                 setTitle(data.name);
83                 return this;
84         }
85
86         void SetName(String name) {
87                 graph.setName(name);
88                 setTitle(name);
89         }
90
91         private static MicroData ReadFile(File filename) throws IOException, FileNotFoundException {
92                 MicroData       data = null;
93                 FileInputStream fis = new FileInputStream(filename);
94                 try {
95                         data = new MicroData((InputStream) fis, filename.getName());
96                         AltosUIPreferences.set_last_logdir(filename);
97                 } catch (MicroData.NonHexcharException nhe) {
98                         data = null;
99                 } catch (MicroData.FileEndedException nhe) {
100                         data = null;
101                 } catch (InterruptedException ie) {
102                         data = null;
103                 } finally {
104                         fis.close();
105                 }
106                 return data;
107         }
108
109         private void OpenFile(File filename) {
110                 try {
111                         SetData(ReadFile(filename));
112                 } catch (FileNotFoundException fne) {
113                         JOptionPane.showMessageDialog(this,
114                                                       fne.getMessage(),
115                                                       "Cannot open file",
116                                                       JOptionPane.ERROR_MESSAGE);
117                 } catch (IOException ioe) {
118                         JOptionPane.showMessageDialog(this,
119                                                       ioe.getMessage(),
120                                                       "File Read Error",
121                                                       JOptionPane.ERROR_MESSAGE);
122                 }
123         }
124
125         private void SelectFile() {
126                 MicroFileChooser        chooser = new MicroFileChooser(this);
127                 File                    file = chooser.runDialog();
128
129                 if (file != null)
130                         OpenFile(file);
131         }
132
133         private void Preferences() {
134                 new AltosUIConfigure(this);
135         }
136
137         private void DownloadData() {
138                 AltosDevice     device = MicroDeviceDialog.show(this);
139
140                 if (device != null)
141                         new MicroDownload(this, device);
142         }
143
144         private void no_data() {
145                         JOptionPane.showMessageDialog(this,
146                                                       "No data available",
147                                                       "No data",
148                                                       JOptionPane.INFORMATION_MESSAGE);
149         }
150
151         private void Save() {
152                 if (data == null) {
153                         no_data();
154                         return;
155                 }
156                 MicroSave       save = new MicroSave (this, data);
157                 if (save.runDialog())
158                         SetName(data.name);
159         }
160
161         private void Export() {
162                 if (data == null) {
163                         no_data();
164                         return;
165                 }
166                 MicroExport     export = new MicroExport (this, data);
167                 export.runDialog();
168         }
169
170         private static void CommandGraph(File file) {
171                 MicroPeak m = new MicroPeak();
172                 m.OpenFile(file);
173         }
174
175         private static void CommandExport(File file) {
176                 try {
177                         MicroData d = ReadFile(file);
178                         if (d != null) {
179                                 File    csv = new File(AltosLib.replace_extension(file.getPath(), ".csv"));
180                                 try {
181                                         System.out.printf ("Export \"%s\" to \"%s\"\n", file.getPath(), csv.getPath());
182                                         MicroExport.export(csv, d);
183                                 } catch (FileNotFoundException fe) {
184                                         System.err.printf("Cannot create file \"%s\" (%s)\n", csv.getName(), fe.getMessage());
185                                 } catch (IOException ie) {
186                                         System.err.printf("Cannot write file \"%s\" (%s)\n", csv.getName(), ie.getMessage());
187                                 }
188                         }
189                 } catch (IOException ie) {
190                         System.err.printf("Cannot read file \"%s\" (%s)\n", file.getName(), ie.getMessage());
191                 }
192         }
193
194         private void Close() {
195                 setVisible(false);
196                 dispose();
197                 --number_of_windows;
198                 if (number_of_windows == 0)
199                         System.exit(0);
200         }
201
202         public void actionPerformed(ActionEvent ev) {
203                 if (open_command.equals(ev.getActionCommand()))
204                         SelectFile();
205                 else if (save_command.equals(ev.getActionCommand()))
206                         Save();
207                 else if (export_command.equals(ev.getActionCommand()))
208                         Export();
209                 else if (preferences_command.equals(ev.getActionCommand()))
210                         Preferences();
211                 else if (close_command.equals(ev.getActionCommand()))
212                         Close();
213                 else if (exit_command.equals(ev.getActionCommand()))
214                         System.exit(0);
215                 else if (download_command.equals(ev.getActionCommand()))
216                         DownloadData();
217         }
218
219         public void itemStateChanged(ItemEvent e) {
220         }
221
222         /* OSXAdapter interfaces */
223         public void macosx_file_handler(String path) {
224                 CommandGraph(new File(path));
225         }
226
227         public void macosx_quit_handler() {
228                 System.exit(0);
229         }
230
231         public void macosx_preferences_handler() {
232                 Preferences();
233         }
234
235         public void filter_changed(double speed_filter, double accel_filter) {
236                 data.flight_series.set_filter(speed_filter, accel_filter);
237                 graph.filter_changed();
238                 data.flight_stats = new AltosFlightStats(data.flight_series);
239                 statsTable.filter_changed(data.flight_stats);
240         }
241
242         public double speed_filter() {
243                 if (data != null && data.flight_series != null)
244                         return data.flight_series.speed_filter_width;
245                 return 4.0;
246         }
247
248         public double accel_filter() {
249                 if (data != null && data.flight_series != null)
250                         return data.flight_series.accel_filter_width;
251                 return 1.0;
252         }
253
254         private void add_menu(JMenu menu, String label, String action) {
255                 JMenuItem       item = new JMenuItem(label);
256                 menu.add(item);
257                 item.addActionListener(this);
258                 item.setActionCommand(action);
259         }
260
261
262         private void make_menu(String label, String[][] items) {
263                 JMenu   menu = new JMenu(label);
264                 for (int i = 0; i < items.length; i++) {
265                         if (MAC_OS_X) {
266                                 if (items[i][1].equals("exit"))
267                                         continue;
268                                 if (items[i][1].equals("preferences"))
269                                         continue;
270                         }
271                         add_menu(menu, items[i][0], items[i][1]);
272                 }
273                 menu_bar.add(menu);
274         }
275
276         public MicroPeak() {
277
278                 ++number_of_windows;
279
280                 register_for_macosx_events();
281
282                 AltosUIPreferences.set_component(this);
283
284                 container = getContentPane();
285                 pane = new JTabbedPane();
286
287                 setTitle("MicroPeak");
288
289                 menu_bar = new JMenuBar();
290                 setJMenuBar(menu_bar);
291
292                 make_menu("File", file_menu_entries);
293
294                 if (MAC_OS_X) {
295                         make_menu(download_label, download_menu_entries);
296                 } else {
297                         JButton download_button = new JButton (download_label);
298                         download_button.setActionCommand(download_command);
299                         download_button.addActionListener(this);
300                         menu_bar.add(download_button);
301                 }
302
303                 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
304                 addWindowListener(new WindowAdapter() {
305                         @Override
306                         public void windowClosing(WindowEvent e) {
307                                 statsTable.tell_closing();
308                                 raw.tell_closing();
309                                 Close();
310                         }
311                 });
312
313                 enable = new AltosUIEnable(this);
314
315                 graph = new AltosGraph(enable);
316                 statsTable = new AltosFlightStatsTable();
317                 raw = new MicroRaw();
318                 pane.add(graph.panel, "Graph");
319                 pane.add(enable, "Configure Graph");
320                 pane.add(statsTable, "Statistics");
321                 JScrollPane scroll = new JScrollPane(raw);
322                 pane.add(scroll, "Raw Data");
323                 pane.doLayout();
324                 pane.validate();
325                 container.add(pane);
326                 container.doLayout();
327                 container.validate();
328                 doLayout();
329                 validate();
330                 Insets i = getInsets();
331                 Dimension ps = pane.getPreferredSize();
332                 ps.width += i.left + i.right;
333                 ps.height += i.top + i.bottom;
334                 setSize(ps);
335                 pack();
336                 setVisible(true);
337         }
338
339         public static void help(int code) {
340                 System.out.printf("Usage: micropeak [OPTION] ... [FILE]...\n");
341                 System.out.printf("  Options:\n");
342                 System.out.printf("    --csv\tgenerate comma separated output for spreadsheets, etc\n");
343                 System.out.printf("    --graph\tgraph a flight\n");
344                 System.exit(code);
345         }
346
347         public static void main(final String[] args) {
348                 boolean opened = false;
349                 boolean graphing = true;
350
351                 try {
352                         UIManager.setLookAndFeel(AltosUIPreferences.look_and_feel());
353                 } catch (Exception e) {
354                 }
355
356                 for (int i = 0; i < args.length; i++) {
357                         if (args[i].equals("--help"))
358                                 help(0);
359                         else if (args[i].equals("--export"))
360                                 graphing = false;
361                         else if (args[i].equals("--graph"))
362                                 graphing = true;
363                         else if (args[i].startsWith("--"))
364                                 help(1);
365                         else {
366                                 File    file = new File(args[i]);
367                                 try {
368                                         if (graphing)
369                                                 CommandGraph(file);
370                                         else
371                                                 CommandExport(file);
372                                         opened = true;
373                                 } catch (Exception e) {
374                                         System.err.printf("Error processing \"%s\": %s %s\n",
375                                                           file.getName(), e.toString(), e.getMessage());
376                                         e.printStackTrace();
377                                 }
378                         }
379                 }
380                 if (!opened)
381                         new MicroPeak();
382         }
383 }