Get AltOS version numbers into Mac 'about' dialog
[fw/altos] / altosui / AltosScanUI.java
1 /*
2  * Copyright © 2011 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 altosui;
19
20 import java.awt.*;
21 import java.awt.event.*;
22 import javax.swing.*;
23 import javax.swing.filechooser.FileNameExtensionFilter;
24 import javax.swing.table.*;
25 import javax.swing.event.*;
26 import java.io.*;
27 import java.util.*;
28 import java.text.*;
29 import java.util.prefs.*;
30 import java.util.concurrent.*;
31 import org.altusmetrum.AltosLib.*;
32
33 class AltosScanResult {
34         String          callsign;
35         int             serial;
36         int             flight;
37         AltosFrequency  frequency;
38         int             telemetry;
39         
40         boolean interrupted = false;
41         
42         public String toString() {
43                 return String.format("%-9.9s serial %-4d flight %-4d (%s %s)",
44                                      callsign, serial, flight, frequency.toShortString(), Altos.telemetry_name(telemetry));
45         }
46
47         public String toShortString() {
48                 return String.format("%s %d %d %7.3f %d",
49                                      callsign, serial, flight, frequency, telemetry);
50         }
51
52         public AltosScanResult(String in_callsign, int in_serial,
53                                int in_flight, AltosFrequency in_frequency, int in_telemetry) {
54                 callsign = in_callsign;
55                 serial = in_serial;
56                 flight = in_flight;
57                 frequency = in_frequency;
58                 telemetry = in_telemetry;
59         }
60
61         public boolean equals(AltosScanResult other) {
62                 return (callsign.equals(other.callsign) &&
63                         serial == other.serial &&
64                         flight == other.flight &&
65                         frequency.frequency == other.frequency.frequency &&
66                         telemetry == other.telemetry);
67         }
68 }
69
70 class AltosScanResults extends LinkedList<AltosScanResult> implements ListModel {
71         
72         LinkedList<ListDataListener>    listeners = new LinkedList<ListDataListener>();
73
74         public boolean add(AltosScanResult r) {
75                 for (AltosScanResult old : this)
76                         if (old.equals(r))
77                                 return true;
78
79                 super.add(r);
80                 ListDataEvent   de = new ListDataEvent(this,
81                                                        ListDataEvent.INTERVAL_ADDED,
82                                                        this.size() - 2, this.size() - 1);
83                 for (ListDataListener l : listeners)
84                         l.contentsChanged(de);
85                 return true;
86         }
87
88         public void addListDataListener(ListDataListener l) {
89                 listeners.add(l);
90         }
91         
92         public void removeListDataListener(ListDataListener l) {
93                 listeners.remove(l);
94         }
95
96         public AltosScanResult getElementAt(int i) {
97                 return this.get(i);
98         }
99
100         public int getSize() {
101                 return this.size();
102         }
103 }
104
105 public class AltosScanUI
106         extends AltosDialog
107         implements ActionListener
108 {
109         AltosUI                         owner;
110         AltosDevice                     device;
111         AltosConfigData                 config_data;
112         AltosTelemetryReader            reader;
113         private JList                   list;
114         private JLabel                  scanning_label;
115         private JLabel                  frequency_label;
116         private JLabel                  telemetry_label;
117         private JButton                 cancel_button;
118         private JButton                 monitor_button;
119         private JCheckBox[]             telemetry_boxes;
120         javax.swing.Timer               timer;
121         AltosScanResults                results = new AltosScanResults();
122
123         int                             telemetry;
124
125         final static int                timeout = 1200;
126         TelemetryHandler                handler;
127         Thread                          thread;
128         AltosFrequency[]                frequencies;
129         int                             frequency_index;
130
131         void scan_exception(Exception e) {
132                 if (e instanceof FileNotFoundException) {
133                         JOptionPane.showMessageDialog(owner,
134                                                       ((FileNotFoundException) e).getMessage(),
135                                                       "Cannot open target device",
136                                                       JOptionPane.ERROR_MESSAGE);
137                 } else if (e instanceof AltosSerialInUseException) {
138                         JOptionPane.showMessageDialog(owner,
139                                                       String.format("Device \"%s\" already in use",
140                                                                     device.toShortString()),
141                                                       "Device in use",
142                                                       JOptionPane.ERROR_MESSAGE);
143                 } else if (e instanceof IOException) {
144                         IOException ee = (IOException) e;
145                         JOptionPane.showMessageDialog(owner,
146                                                       device.toShortString(),
147                                                       ee.getLocalizedMessage(),
148                                                       JOptionPane.ERROR_MESSAGE);
149                 } else {
150                         JOptionPane.showMessageDialog(owner,
151                                                       String.format("Connection to \"%s\" failed",
152                                                                     device.toShortString()),
153                                                       "Connection Failed",
154                                                       JOptionPane.ERROR_MESSAGE);
155                 }
156                 close();
157         }
158
159         class TelemetryHandler implements Runnable {
160
161                 public void run() {
162
163                         boolean interrupted = false;
164
165                         try {
166                                 for (;;) {
167                                         try {
168                                                 AltosRecord     record = reader.read();
169                                                 if (record == null)
170                                                         continue;
171                                                 if ((record.seen & AltosRecord.seen_flight) != 0) {
172                                                         final AltosScanResult   result = new AltosScanResult(record.callsign,
173                                                                                                      record.serial,
174                                                                                                      record.flight,
175                                                                                                      frequencies[frequency_index],
176                                                                                                      telemetry);
177                                                         Runnable r = new Runnable() {
178                                                                         public void run() {
179                                                                                 results.add(result);
180                                                                         }
181                                                                 };
182                                                         SwingUtilities.invokeLater(r);
183                                                 }
184                                         } catch (ParseException pp) {
185                                         } catch (AltosCRCException ce) {
186                                         }
187                                 }
188                         } catch (InterruptedException ee) {
189                                 interrupted = true;
190                         } catch (IOException ie) {
191                         } finally {
192                                 reader.close(interrupted);
193                         }
194                 }
195         }
196
197         void set_label() {
198                 frequency_label.setText(String.format("Frequency: %s", frequencies[frequency_index].toString()));
199                 telemetry_label.setText(String.format("Telemetry: %s", Altos.telemetry_name(telemetry)));
200         }
201
202         void set_telemetry() {
203                 reader.set_telemetry(telemetry);
204         }
205         
206         void set_frequency() throws InterruptedException, TimeoutException {
207                 reader.set_frequency(frequencies[frequency_index].frequency);
208         }
209         
210         void next() throws InterruptedException, TimeoutException {
211                 reader.set_monitor(false);
212                 Thread.sleep(100);
213                 ++frequency_index;
214                 if (frequency_index >= frequencies.length ||
215                     !telemetry_boxes[telemetry - Altos.ao_telemetry_min].isSelected())
216                 {
217                         frequency_index = 0;
218                         do {
219                                 ++telemetry;
220                                 if (telemetry > Altos.ao_telemetry_max)
221                                         telemetry = Altos.ao_telemetry_min;
222                         } while (!telemetry_boxes[telemetry - Altos.ao_telemetry_min].isSelected());
223                         set_telemetry();
224                 }
225                 set_frequency();
226                 set_label();
227                 reader.set_monitor(true);
228         }
229
230
231         void close() {
232                 if (thread != null && thread.isAlive()) {
233                         thread.interrupt();
234                         try {
235                                 thread.join();
236                         } catch (InterruptedException ie) {}
237                 }
238                 thread = null;
239                 if (timer != null)
240                         timer.stop();
241                 setVisible(false);
242                 dispose();
243         }
244
245         void tick_timer() throws InterruptedException, TimeoutException {
246                 next();
247         }
248
249         public void actionPerformed(ActionEvent e) {
250                 String cmd = e.getActionCommand();
251
252                 try {
253                         if (cmd.equals("cancel"))
254                                 close();
255
256                         if (cmd.equals("tick"))
257                                 tick_timer();
258
259                         if (cmd.equals("telemetry")) {
260                                 int k;
261                                 int scanning_telemetry = 0;
262                                 for (k = Altos.ao_telemetry_min; k <= Altos.ao_telemetry_max; k++) {
263                                         int j = k - Altos.ao_telemetry_min;
264                                         if (telemetry_boxes[j].isSelected())
265                                                 scanning_telemetry |= (1 << k);
266                                 }
267                                 if (scanning_telemetry == 0) {
268                                         scanning_telemetry |= (1 << Altos.ao_telemetry_standard);
269                                         telemetry_boxes[Altos.ao_telemetry_standard - Altos.ao_telemetry_min].setSelected(true);
270                                 }
271                                 AltosUIPreferences.set_scanning_telemetry(scanning_telemetry);
272                         }
273
274                         if (cmd.equals("monitor")) {
275                                 close();
276                                 AltosScanResult r = (AltosScanResult) (list.getSelectedValue());
277                                 if (r != null) {
278                                         if (device != null) {
279                                                 if (reader != null) {
280                                                         reader.set_telemetry(r.telemetry);
281                                                         reader.set_frequency(r.frequency.frequency);
282                                                         reader.save_frequency();
283                                                         owner.telemetry_window(device);
284                                                 }
285                                         }
286                                 }
287                         }
288                 } catch (TimeoutException te) {
289                         close();
290                 } catch (InterruptedException ie) {
291                         close();
292                 }
293         }
294
295         /* A window listener to catch closing events and tell the config code */
296         class ConfigListener extends WindowAdapter {
297                 AltosScanUI     ui;
298
299                 public ConfigListener(AltosScanUI this_ui) {
300                         ui = this_ui;
301                 }
302
303                 public void windowClosing(WindowEvent e) {
304                         ui.actionPerformed(new ActionEvent(e.getSource(),
305                                                            ActionEvent.ACTION_PERFORMED,
306                                                            "close"));
307                 }
308         }
309
310         private boolean open() {
311                 device = AltosDeviceDialog.show(owner, Altos.product_basestation);
312                 if (device == null)
313                         return false;
314                 try {
315                         reader = new AltosTelemetryReader(new AltosSerial(device));
316                         set_frequency();
317                         set_telemetry();
318                         try {
319                                 Thread.sleep(100);
320                         } catch (InterruptedException ie) {
321                         }
322                         reader.flush();
323                         handler = new TelemetryHandler();
324                         thread = new Thread(handler);
325                         thread.start();
326                         return true;
327                 } catch (FileNotFoundException ee) {
328                         JOptionPane.showMessageDialog(owner,
329                                                       ee.getMessage(),
330                                                       "Cannot open target device",
331                                                       JOptionPane.ERROR_MESSAGE);
332                 } catch (AltosSerialInUseException si) {
333                         JOptionPane.showMessageDialog(owner,
334                                                       String.format("Device \"%s\" already in use",
335                                                                     device.toShortString()),
336                                                       "Device in use",
337                                                       JOptionPane.ERROR_MESSAGE);
338                 } catch (IOException ee) {
339                         JOptionPane.showMessageDialog(owner,
340                                                       device.toShortString(),
341                                                       "Unkonwn I/O error",
342                                                       JOptionPane.ERROR_MESSAGE);
343                 } catch (TimeoutException te) {
344                         JOptionPane.showMessageDialog(owner,
345                                                       device.toShortString(),
346                                                       "Timeout error",
347                                                       JOptionPane.ERROR_MESSAGE);
348                 } catch (InterruptedException ie) {
349                         JOptionPane.showMessageDialog(owner,
350                                                       device.toShortString(),
351                                                       "Interrupted exception",
352                                                       JOptionPane.ERROR_MESSAGE);
353                 }
354                 if (reader != null)
355                         reader.close(false);
356                 return false;
357         }
358
359         public AltosScanUI(AltosUI in_owner) {
360
361                 owner = in_owner;
362
363                 frequencies = AltosUIPreferences.common_frequencies();
364                 frequency_index = 0;
365                 telemetry = Altos.ao_telemetry_min;
366
367                 if (!open())
368                         return;
369
370                 Container               pane = getContentPane();
371                 GridBagConstraints      c = new GridBagConstraints();
372                 Insets                  i = new Insets(4,4,4,4);
373
374                 timer = new javax.swing.Timer(timeout, this);
375                 timer.setActionCommand("tick");
376                 timer.restart();
377
378                 owner = in_owner;
379
380                 pane.setLayout(new GridBagLayout());
381
382                 scanning_label = new JLabel("Scanning:");
383                 frequency_label = new JLabel("");
384                 telemetry_label = new JLabel("");
385                 
386                 set_label();
387
388                 c.fill = GridBagConstraints.HORIZONTAL;
389                 c.anchor = GridBagConstraints.WEST;
390                 c.insets = i;
391                 c.weightx = 1;
392                 c.weighty = 1;
393
394                 c.gridx = 0;
395                 c.gridy = 0;
396                 c.gridwidth = 2;
397
398                 pane.add(scanning_label, c);
399                 c.gridy = 1;
400                 pane.add(frequency_label, c);
401                 c.gridy = 2;
402                 pane.add(telemetry_label, c);
403
404                 int     scanning_telemetry = AltosUIPreferences.scanning_telemetry();
405                 telemetry_boxes = new JCheckBox[Altos.ao_telemetry_max - Altos.ao_telemetry_min + 1];
406                 for (int k = Altos.ao_telemetry_min; k <= Altos.ao_telemetry_max; k++) {
407                         int j = k - Altos.ao_telemetry_min;
408                         telemetry_boxes[j] = new JCheckBox(Altos.ao_telemetry_name[k]);
409                         c.gridy = 3 + j;
410                         pane.add(telemetry_boxes[j], c);
411                         telemetry_boxes[j].setActionCommand("telemetry");
412                         telemetry_boxes[j].addActionListener(this);
413                         telemetry_boxes[j].setSelected((scanning_telemetry & (1 << k)) != 0);
414                 }
415
416                 int     y_offset = 3 + (Altos.ao_telemetry_max - Altos.ao_telemetry_min + 1);
417                                 
418                 list = new JList(results) {
419                                 //Subclass JList to workaround bug 4832765, which can cause the
420                                 //scroll pane to not let the user easily scroll up to the beginning
421                                 //of the list.  An alternative would be to set the unitIncrement
422                                 //of the JScrollBar to a fixed value. You wouldn't get the nice
423                                 //aligned scrolling, but it should work.
424                                 public int getScrollableUnitIncrement(Rectangle visibleRect,
425                                                                       int orientation,
426                                                                       int direction) {
427                                         int row;
428                                         if (orientation == SwingConstants.VERTICAL &&
429                                             direction < 0 && (row = getFirstVisibleIndex()) != -1) {
430                                                 Rectangle r = getCellBounds(row, row);
431                                                 if ((r.y == visibleRect.y) && (row != 0))  {
432                                                         Point loc = r.getLocation();
433                                                         loc.y--;
434                                                         int prevIndex = locationToIndex(loc);
435                                                         Rectangle prevR = getCellBounds(prevIndex, prevIndex);
436
437                                                         if (prevR == null || prevR.y >= r.y) {
438                                                                 return 0;
439                                                         }
440                                                         return prevR.height;
441                                                 }
442                                         }
443                                         return super.getScrollableUnitIncrement(
444                                                 visibleRect, orientation, direction);
445                                 }
446                         };
447
448                 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
449                 list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
450                 list.setVisibleRowCount(-1);
451
452                 list.addMouseListener(new MouseAdapter() {
453                                  public void mouseClicked(MouseEvent e) {
454                                          if (e.getClickCount() == 2) {
455                                                  monitor_button.doClick(); //emulate button click
456                                          }
457                                  }
458                         });
459                 JScrollPane listScroller = new JScrollPane(list);
460                 listScroller.setPreferredSize(new Dimension(400, 80));
461                 listScroller.setAlignmentX(LEFT_ALIGNMENT);
462
463                 //Create a container so that we can add a title around
464                 //the scroll pane.  Can't add a title directly to the
465                 //scroll pane because its background would be white.
466                 //Lay out the label and scroll pane from top to bottom.
467                 JPanel listPane = new JPanel();
468                 listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
469
470                 JLabel label = new JLabel("Select Device");
471                 label.setLabelFor(list);
472                 listPane.add(label);
473                 listPane.add(Box.createRigidArea(new Dimension(0,5)));
474                 listPane.add(listScroller);
475                 listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
476
477                 c.fill = GridBagConstraints.BOTH;
478                 c.anchor = GridBagConstraints.CENTER;
479                 c.insets = i;
480                 c.weightx = 1;
481                 c.weighty = 1;
482
483                 c.gridx = 0;
484                 c.gridy = y_offset;
485                 c.gridwidth = 2;
486                 c.anchor = GridBagConstraints.CENTER;
487
488                 pane.add(listPane, c);
489
490                 cancel_button = new JButton("Cancel");
491                 cancel_button.addActionListener(this);
492                 cancel_button.setActionCommand("cancel");
493
494                 c.fill = GridBagConstraints.NONE;
495                 c.anchor = GridBagConstraints.CENTER;
496                 c.insets = i;
497                 c.weightx = 1;
498                 c.weighty = 1;
499
500                 c.gridx = 0;
501                 c.gridy = y_offset + 1;
502                 c.gridwidth = 1;
503                 c.anchor = GridBagConstraints.CENTER;
504
505                 pane.add(cancel_button, c);
506
507                 monitor_button = new JButton("Monitor");
508                 monitor_button.addActionListener(this);
509                 monitor_button.setActionCommand("monitor");
510
511                 c.fill = GridBagConstraints.NONE;
512                 c.anchor = GridBagConstraints.CENTER;
513                 c.insets = i;
514                 c.weightx = 1;
515                 c.weighty = 1;
516
517                 c.gridx = 1;
518                 c.gridy = y_offset + 1;
519                 c.gridwidth = 1;
520                 c.anchor = GridBagConstraints.CENTER;
521
522                 pane.add(monitor_button, c);
523
524                 pack();
525                 setLocationRelativeTo(owner);
526
527                 addWindowListener(new ConfigListener(this));
528
529                 setVisible(true);
530         }
531 }